<commit_before>#include <iostream>
#include <stdlib.h>
#include <opencv2/opencv.hpp>
#include "rectangle.h"
#include "circle.h"
#include "ellipse.h"
#include "picture.h"

using namespace std;
using namespace cv;

const int POPULATION = 3;		//size of test population
const int POINT_GUESS = 5;		//# used in guess heuristic

Scalar guessColor(Mat mainImage, Point p)
{
	Vec3b bgrMainPic = mainImage.at<Vec3b>(p.x, p.y);
	return Scalar(bgrMainPic.val[0], bgrMainPic.val[1], bgrMainPic.val[2]);
}

Point guessPoint(picture curr, Mat mainImage)
{
	bool found = false;
	int trials = 50;
	while (!found)
	{
		int x = rand() % mainImage.rows;
		int y = rand() % mainImage.cols;

		Vec3b bgrMainPic = mainImage.at<Vec3b>(x, y);
		Vec3b bgrCurrPic = curr.img.at<Vec3b>(x, y);

		if (abs(bgrCurrPic.val[0] - bgrMainPic.val[0]) > POINT_GUESS ||
			abs(bgrCurrPic.val[1] - bgrMainPic.val[1]) > POINT_GUESS ||
			abs(bgrCurrPic.val[2] - bgrMainPic.val[2]) > POINT_GUESS)
		{
			return Point(x, y);
		}
		trials--;
		if (trials == 0)
			return Point(0, 0);
	}
}

float getFitness(picture curr, Mat mainImage)
{
	float f = 0.0;
	for (int x = 0; x < curr.img.rows; x++)
	{
		for (int y = 0; y < curr.img.cols; y++)
		{
			Vec3b bgrMainPic = mainImage.at<Vec3b>(x, y);
			Vec3b bgrCurrPic = curr.img.at<Vec3b>(x, y);

			f += abs(bgrCurrPic.val[0] - bgrMainPic.val[0]);	//b
			f += abs(bgrCurrPic.val[1] - bgrMainPic.val[1]);	//g
			f += abs(bgrCurrPic.val[2] - bgrMainPic.val[2]);	//r
		}
	}
	return f;
}

int main (int argc, char** argv)
{
	//get main image
	Mat mainImage = imread(argv[1], IMREAD_UNCHANGED);
	if (!mainImage.data)
	{
		cout << "Could not open image" << endl;
		return 0;
	}

	int ROWS = mainImage.rows;
	int COLS = mainImage.cols;

	//set up display windows
	namedWindow("Evolving Image", WINDOW_AUTOSIZE);
	//set rand seed
	srand(time(NULL));

	vector<picture> current(POPULATION);

	//generate random images
	for (int i = 0; i < POPULATION; i++)
	{
		Mat curModel(ROWS, COLS, CV_8UC3, Scalar(0,0,0));
		current.at(i).img = curModel;
		current.at(i).fitness = 0;

		Mat buf(ROWS, COLS, CV_8UC3, Scalar(0,0,0));
		my_ellipse el(Point(rand()%COLS, rand()%ROWS),
					  Size(rand()%100+20, rand()%100+20),
					  Scalar(rand()%255, rand()%255, rand()%255),
					  rand()%360);
		ellipse(current.at(i).img, el.pos, el.size, el.angle, 0, 360, el.color, -1);
		current.at(i).ellipses.push_back(el);
	}

	picture bestPicture;
	Mat curModel(ROWS, COLS, CV_8UC3, Scalar(0,0,0));
	bestPicture.img = curModel;
	bestPicture.fitness = 9999;

	for (int k = 0; k < 10000; k++)
	{
		cout << "Number of shapes = " << k << endl;
		for (int n = 0; n < 100; n++)
		{
			//calculate image fitness level for all in population
			for (int i = 0; i < POPULATION; i++)
			{
				current.at(i).fitness = 0;
				current.at(i).fitness = getFitness(current.at(i), mainImage);
				current.at(i).fitness /= (current.at(i).img.rows * current.at(i).img.cols) * 3;
				imshow("Evolving Image", current.at(i).img);
				waitKey(1);
			}

			float bestFitness = 9999;
			int bestPic = -1;

			//select best image generated in population
			for (int i = 0; i < POPULATION; i++)
			{
				if (current.at(i).fitness < bestFitness)
				{
					bestFitness = current.at(i).fitness;
					bestPic = i;
				}
			}

			//generate new population by mutating the best image
			my_ellipse el = current.at(bestPic).ellipses.at(current.at(bestPic).ellipses.size() - 1);
			for (int i = 0; i < POPULATION; i++) //mutate the population
			{
				current.at(i) = current.at(bestPic);
				if (i != bestPic)
				{
					el.pos += Point(rand()%15-15/2,rand()%15-15/2) ;
					el.color += Scalar(rand()%50-50/2,rand()%50-50/2,rand()%50-50/2) ;
					el.size += Size(rand()%15-15/2,rand()%15-15/2) ;
					el.size.width = abs(el.size.width) ;
					el.size.height = abs(el.size.height) ;
					el.angle += rand()%15-15/2;
					Mat buf(ROWS, COLS, CV_8UC3, Scalar(0,0,0)) ;
					bestPicture.img.copyTo(buf) ;
					ellipse(buf, el.pos, el.size, el.angle, 0, 360, el.color, -1);
					current.at(i).img = buf;
					current.at(i).ellipses.at(current.at(i).ellipses.size() - 1) = el;
				}
			}

			if (n == 99)
			{
				//change bestPicture if new picture is an improvement
				cout << "Previous best = " << bestPicture.fitness << endl;
				cout << "Current best = " << current.at(bestPic).fitness << endl;
				if (bestPicture.fitness >= current.at(bestPic).fitness)
				{
					bestPicture = current.at(bestPic);
					stringstream path;
					path << k << ".jpg";
					string savePath = path.str();
					if (k % 5 == 0)
					{
						imwrite(savePath, bestPicture.img);
					}
				}
				cout << "Best fitness = " << bestFitness << endl;
			}
		}
		for (int q = 0; q < POPULATION; q++) //create new shapes
		{
			Mat buf(ROWS, COLS, CV_8UC3, Scalar(0,0,0));
			bestPicture.img.copyTo(buf);
			current.at(q).fitness = bestPicture.fitness;
			current.at(q).ellipses = bestPicture.ellipses;

			my_ellipse el(Point(rand() % COLS, rand() % ROWS),
						  Size(rand()%100+20, rand()%100+20),
						  Scalar(rand() % 255, rand() % 255, rand() % 255),
						  rand()%360);
			ellipse(buf, el.pos, el.size, el.angle, 0, 360, el.color, -1);
			current.at(q).img = buf;
			current.at(q).ellipses.push_back(el);
		}
	}

	waitKey(0);
	return 0;

}
<commit_msg>success with ellipses<commit_after>#include <iostream>
#include <stdlib.h>
#include <opencv2/opencv.hpp>
#include "rectangle.h"
#include "circle.h"
#include "ellipse.h"
#include "picture.h"

using namespace std;
using namespace cv;

const int POPULATION = 3;		//size of test population

float getFitness(picture curr, Mat mainImage)
{
	float f = 0.0;
	for (int x = 0; x < curr.img.rows; x++)
	{
		for (int y = 0; y < curr.img.cols; y++)
		{
			Vec3b bgrMainPic = mainImage.at<Vec3b>(x, y);
			Vec3b bgrCurrPic = curr.img.at<Vec3b>(x, y);

			f += abs(bgrCurrPic.val[0] - bgrMainPic.val[0]);	//b
			f += abs(bgrCurrPic.val[1] - bgrMainPic.val[1]);	//g
			f += abs(bgrCurrPic.val[2] - bgrMainPic.val[2]);	//r
		}
	}
	return f;
}

int main (int argc, char** argv)
{
	//get main image
	Mat mainImage = imread(argv[1], IMREAD_UNCHANGED);
	if (!mainImage.data)
	{
		cout << "Could not open image" << endl;
		return 0;
	}

	int ROWS = mainImage.rows;
	int COLS = mainImage.cols;

	//set up display windows
	namedWindow("Evolving Image", WINDOW_AUTOSIZE);
	//set rand seed
	srand(time(NULL));

	vector<picture> current(POPULATION);

	//generate random images
	for (int i = 0; i < POPULATION; i++)
	{
		Mat curModel(ROWS, COLS, CV_8UC3, Scalar(0,0,0));
		current.at(i).img = curModel;
		current.at(i).fitness = 0;

		Mat buf(ROWS, COLS, CV_8UC3, Scalar(0,0,0));
		my_ellipse el(Point(rand()%COLS, rand()%ROWS),
					  Size(rand()%100+20, rand()%100+20),
					  Scalar(rand()%255, rand()%255, rand()%255),
					  rand()%360);
		ellipse(current.at(i).img, el.pos, el.size, el.angle, 0, 360, el.color, -1);
		current.at(i).ellipses.push_back(el);
	}

	picture bestPicture;
	Mat curModel(ROWS, COLS, CV_8UC3, Scalar(0,0,0));
	bestPicture.img = curModel;
	bestPicture.fitness = 9999;

	for (int k = 0; k < 10000; k++)
	{
		cout << "Number of shapes = " << k << endl;
		for (int n = 0; n < 100; n++)
		{
			//calculate image fitness level for all in population
			for (int i = 0; i < POPULATION; i++)
			{
				current.at(i).fitness = 0;
				current.at(i).fitness = getFitness(current.at(i), mainImage);
				current.at(i).fitness /= (current.at(i).img.rows * current.at(i).img.cols) * 3;
				imshow("Evolving Image", current.at(i).img);
				waitKey(1);
			}

			float bestFitness = 9999;
			int bestPic = -1;

			//select best image generated in population
			for (int i = 0; i < POPULATION; i++)
			{
				if (current.at(i).fitness < bestFitness)
				{
					bestFitness = current.at(i).fitness;
					bestPic = i;
				}
			}

			//generate new population by mutating the best image
			my_ellipse el = current.at(bestPic).ellipses.at(current.at(bestPic).ellipses.size() - 1);
			for (int i = 0; i < POPULATION; i++) //mutate the population
			{
				current.at(i) = current.at(bestPic);
				if (i != bestPic)
				{
					el.pos += Point(rand()%15-15/2,rand()%15-15/2) ;
					el.color += Scalar(rand()%50-50/2,rand()%50-50/2,rand()%50-50/2) ;
					el.size += Size(rand()%15-15/2,rand()%15-15/2) ;
					el.size.width = abs(el.size.width) ;
					el.size.height = abs(el.size.height) ;
					el.angle += rand()%15-15/2;
					Mat buf(ROWS, COLS, CV_8UC3, Scalar(0,0,0)) ;
					bestPicture.img.copyTo(buf) ;
					ellipse(buf, el.pos, el.size, el.angle, 0, 360, el.color, -1);
					current.at(i).img = buf;
					current.at(i).ellipses.at(current.at(i).ellipses.size() - 1) = el;
				}
			}

			if (n == 99)
			{
				//change bestPicture if new picture is an improvement
				cout << "Previous best = " << bestPicture.fitness << endl;
				cout << "Current best = " << current.at(bestPic).fitness << endl;
				if (bestPicture.fitness >= current.at(bestPic).fitness)
				{
					bestPicture = current.at(bestPic);
					stringstream path;
					path << "KyloRen" << k << ".jpg";
					string savePath = path.str();
					if (k % 5 == 0)
					{
						imwrite(savePath, bestPicture.img);
					}
				}
				cout << "Best fitness = " << bestFitness << endl;
			}
		}
		for (int q = 0; q < POPULATION; q++) //create new shapes
		{
			Mat buf(ROWS, COLS, CV_8UC3, Scalar(0,0,0));
			bestPicture.img.copyTo(buf);
			current.at(q).fitness = bestPicture.fitness;
			current.at(q).ellipses = bestPicture.ellipses;

			my_ellipse el(Point(rand()%COLS, rand()%ROWS),
						  Size(rand()%100+20, rand()%100+20),
						  Scalar(rand()%255, rand()%255, rand()%255),
						  rand()%360);
			ellipse(buf, el.pos, el.size, el.angle, 0, 360, el.color, -1);
			current.at(q).img = buf;
			current.at(q).ellipses.push_back(el);
		}
	}

	waitKey(0);
	return 0;

}
<|endoftext|>


<commit_before>811b17b0-ad58-11e7-93dd-ac87a332f658<commit_msg>( ͡° ͜ʖ ͡°)<commit_after>819500de-ad58-11e7-8cfc-ac87a332f658<|endoftext|>


<commit_before>c680e6e8-4b02-11e5-94c2-28cfe9171a43<commit_msg>This'll fix that<commit_after>c691bacc-4b02-11e5-a53e-28cfe9171a43<|endoftext|>


<commit_before>#include "autotab.hpp"
#include "cmdline.hpp"

#include <iostream>
#include <fstream>
#include <string>
#include <sys/stat.h>

bool is_file(const char* path) {
    struct stat buf;
    stat(path, &buf);
    return S_ISREG(buf.st_mode);
}

bool is_dir(const char* path) {
    struct stat buf;
    stat(path, &buf);
    return S_ISDIR(buf.st_mode);
}

int main(int argc, const char **argv)
{
    // get list of files from commandline
    std::vector<std::string> files = autotab::parse_cmdline(argc, argv);

    // if no file is provided, read from std::cin
    if(files.empty())
    {
        // process
        autotab::autotab(std::cin, std::cout);

        // success!
        return 0;
    }

    // if files are provided, read from files
    bool success = true;
    for(std::vector<std::string>::iterator file = files.begin();
            file != files.end(); file++)
    {

        // print errormessage if file is a directory
        if(is_dir(file->c_str()))
        {
            std::cerr << "autotab: " << (*file) << ": Is a directory"
                      << std::endl;
            success = false;
            continue;
        }

        // open file
        std::ifstream fin(file->c_str());

        // check if file was successfully opened
        if(!fin.good() || !fin.is_open())
        {
            std::cerr << "autotab: " << (*file) << ": No such file or directory"
                      << std::endl;

            fin.close();

            success = false;
            continue;
        }

        // process
        autotab::autotab(fin, std::cout);

        // close file
        fin.close();

    }

    // success?
    return success;
}
<commit_msg>removed unnecessary check<commit_after>#include "autotab.hpp"
#include "cmdline.hpp"

#include <iostream>
#include <fstream>
#include <string>
#include <sys/stat.h>

bool is_file(const char* path) {
    struct stat buf;
    stat(path, &buf);
    return S_ISREG(buf.st_mode);
}

bool is_dir(const char* path) {
    struct stat buf;
    stat(path, &buf);
    return S_ISDIR(buf.st_mode);
}

int main(int argc, const char **argv)
{
    // get list of files from commandline
    std::vector<std::string> files = autotab::parse_cmdline(argc, argv);

    // if no file is provided, read from std::cin
    if(files.empty())
    {
        // process
        autotab::autotab(std::cin, std::cout);

        // success!
        return 0;
    }

    // if files are provided, read from files
    bool success = true;
    for(std::vector<std::string>::iterator file = files.begin();
            file != files.end(); file++)
    {

        // print errormessage if file is a directory
        if(is_dir(file->c_str()))
        {
            std::cerr << "autotab: " << (*file) << ": Is a directory"
                      << std::endl;
            success = false;
            continue;
        }

        // open file
        std::ifstream fin(file->c_str());

        // check if file was successfully opened
        if(!fin.good())
        {
            std::cerr << "autotab: " << (*file) << ": No such file or directory"
                      << std::endl;

            fin.close();

            success = false;
            continue;
        }

        // process
        autotab::autotab(fin, std::cout);

        // close file
        fin.close();

    }

    // success?
    return success;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>

using namespace std;

int main()
{
    cout << " -----------------------------" << endl
         //<< "|                             |" << endl
         << "|     Plants v.s Zombies      |" << endl
         //<< "|                             |" << endl
         << " -----------------------------" << endl;
    constexpr int LAND_DEFAULT=8;
    constexpr int LAND_MAX=10;
    constexpr int LAND_MIN=1;
    constexpr int ZOMBIE_DEFAULT=3;
    constexpr int ZOMBIE_MAX=10;
    constexpr int ZOMBIE_MIN=1;

    string input;

    cout << "Number of lands on the map (" << LAND_MIN << "-" << LAND_MAX << ", default: " << LAND_DEFAULT <<")...>";
    int value = LAND_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > LAND_MAX) value = LAND_MAX;
        if(value < LAND_MIN) value = LAND_MIN;
    }
    const int LANDS=value;

    cout << "Number of zombies on the map (" << ZOMBIE_MIN << "-" << ZOMBIE_MAX << ", default: "<< ZOMBIE_DEFAULT <<")...>";
    value=ZOMBIE_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > ZOMBIE_MAX) value = ZOMBIE_MAX;
        if(value < ZOMBIE_MIN) value = ZOMBIE_MIN;
    }
    const int ZOMBIES=value;

    //game rules
    cout << "=============================================================================" << endl
         << "Plants vs. Zombies Rule:" << endl
         << endl
         << "How to win:" << endl
         << "  (1) All zombies are dead." << endl
         << "  (2) At least one plant is live." << endl
         << "  (3) The number of dead bomb plants cannot exceed the number of zombies." << endl
         << endl
         << "How to lose:" << endl
         << "  All plants are dead." << endl
         << "=============================================================================" << endl;
    system("pause");
    system("cls");

    return 0;
}
<commit_msg>preset main code<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
//#include <vector>
//#include <fstream>

using namespace std;

int main()
{
    //game start
    cout << " -----------------------------" << endl
         << "|     Plants v.s Zombies      |" << endl
         << " -----------------------------" << endl;
    constexpr int LAND_DEFAULT=8;
    constexpr int LAND_MAX=10;
    constexpr int LAND_MIN=1;
    constexpr int ZOMBIE_DEFAULT=3;
    constexpr int ZOMBIE_MAX=10;
    constexpr int ZOMBIE_MIN=1;

    string input;
    //initialize game setting
    cout << "Number of lands on the map (" << LAND_MIN << "-" << LAND_MAX << ", default: " << LAND_DEFAULT <<")...>";
    int value = LAND_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > LAND_MAX) value = LAND_MAX;
        if(value < LAND_MIN) value = LAND_MIN;
    }
    const int LANDS=value;

    cout << "Number of zombies on the map (" << ZOMBIE_MIN << "-" << ZOMBIE_MAX << ", default: "<< ZOMBIE_DEFAULT <<")...>";
    value=ZOMBIE_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > ZOMBIE_MAX) value = ZOMBIE_MAX;
        if(value < ZOMBIE_MIN) value = ZOMBIE_MIN;
    }
    const int ZOMBIES=value;

    //game rules
    cout << "=============================================================================" << endl
         << "Plants vs. Zombies Rule:" << endl
         << endl
         << "How to win:" << endl
         << "  (1) All zombies are dead." << endl
         << "  (2) At least one plant is live." << endl
         << "  (3) The number of dead bomb plants cannot exceed the number of zombies." << endl
         << endl
         << "How to lose:" << endl
         << "  All plants are dead." << endl
         << "=============================================================================" << endl;
    system("pause");
    system("cls");

    //game start
    /*
    //construct
    Player *player = new Player();
    Zombie *zombie = new Zombie()[ZOMBIES];
    Land *land = new Land()[LANDS];
    Map *map = new Map(land);
    vector<Plant*> plant;
    ifstream fin=open("plants.txt");
    while(!fin.eof())
    {
        char type;
        fin << type;
        if(fin.eof()) break;
        Plant *tmp = nullptr;
        switch(type)
        {
        case 'C':
            {
                tmp = new CoinPlant(fin);
            }
        case 'S':
            {
                tmp = new HornPlant(fin);
            }
        case 'B':
            {
                tmp = new BombPlant(fin);
            }
        case 'H':
            {
                tmp = new HealPlant(fin);
            }
        default:
            continue;
        }
        if(tmp)
        {
            plant.push_back(tmp);
        }
    }

    cout << *map << endl;
    cout << "------------------------------------------------" << endl;
    cout << "Zombie information:" << endl;
    for(int i=0;i<ZOMBIES;i++)
    {
        cout << '[' << i << "] " << zombie[i];
    }
    cout << endl << "================================================" << endl;
    for(int i=0;i<plant.size();++i)
    {
        cout << '[' << i << "] " ;
        switch(plant[i]->type())
        {
            case 'C':
                cout << dynamic_cast<CoinPlant *>(plant[i]);
            case 'S':
                cout << dynamic_cast<HornPlant *>(plant[i]);
            case 'B':
                cout << dynamic_cast<BombPlant *>(plant[i]);
            case 'H':
                cout << dynamic_cast<HealPlant *>(plant[i]);
        }
        cout << endl;
    }
    cout << endl << *player;
    int choice = plant.size();
    cout << ":    Enter your choice (" << choice << " to give up, default: " << choice << ")...>";

    // destruct
    while(!plant.empty())
        delete plant.pop_back();
    delete player;
    delete map;
    delete [] zombie;
    delete [] land;
    */

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

#include "log.h"
#include "crawler.h"
#include "threadpool.h"
#include "workset.h"

ThreadPool<Workset> *global_pool = nullptr;
void signal_handler_exit()
{
    if(global_pool != nullptr)
            global_pool->stopall();
}

#include "util.h"

void usage() {
    std::cerr << "Usage: robot_farmer seed_domain" << std::endl;
    exit(1);
}

int main(int argc, char **argv) {
    Log::create(std::cout);
    LOG << "Starting..." << std::endl;

    signal(SIGINT, signal_handler_exit);
    signal(SIGTERM, signal_handler_exit);

    if(argc < 2)
        usage();

    Crawler c;
    ThreadPool<Workset> pool(100);
    global_pool = &pool;

    c.crawl(argv[1]);

    return 0;
}

<commit_msg>corrected errors with signal handler :')<commit_after>#include <iostream>
#include <csignal>

#include "log.h"
#include "crawler.h"
#include "threadpool.h"
#include "workset.h"

ThreadPool<Workset> *global_pool = nullptr;
void signal_handler_exit(int sig)
{
    if(global_pool != nullptr)
            global_pool->stopall();
}

#include "util.h"

void usage() {
    std::cerr << "Usage: robot_farmer seed_domain" << std::endl;
    exit(1);
}

int main(int argc, char **argv) {
    Log::create(std::cout);
    LOG << "Starting..." << std::endl;

    signal(SIGINT, signal_handler_exit);
    signal(SIGTERM, signal_handler_exit);

    if(argc < 2)
        usage();

    Crawler c;
    ThreadPool<Workset> pool(100);
    global_pool = &pool;

    c.crawl(argv[1]);

    return 0;
}

<|endoftext|>


<commit_before>//
//  main.cpp
//  tile
//
//  Created by Nhat Nguyen on 9/5/16.
//  Copyright © 2016 Nhat Nguyen. All rights reserved.
//

#include <iostream>
#include <vector>
#include <iterator>
#include <random>

#include "tile.hpp"

using namespace std;

/* Testing */

int main(void) {
    // At start of game read in all text files.
    vector<string> titleAridVector;
    vector<string> titleForestVector;
    vector<string> titleWaterVector;

    vector<string> descriptionVector;

    vector<string> climateAridVector;
    vector<string> climateForestVector;
    vector<string> climateWaterVector;

    // Testing random element selecting from vector
    vector<int> myVector;
    myVector.push_back(1);
    myVector.push_back(2);
    myVector.push_back(3);
    myVector.push_back(4);
    myVector.push_back(5);
    // Chooses random element from vector.
    cout << "Random element: " << *select_randomly(myVector.begin(), myVector.end()) << endl << endl;

    // Testing tile class
    Tile startingTile;
    startingTile.setTileType(true);
    startingTile.setTitle("In a galaxy far far away... a galactic war rages on.");
    cout << startingTile.getTitle() << endl;
    startingTile.setDescription("You begin your journey on the planet Krypton in the small and humble town of Kal-el.");
    cout << startingTile.getDescription() << endl;

    for (int i = 0; i < 5; i++) {
        Tile myTile;
    }

    return 0;
}<commit_msg>Renamed tile.hpp to tile.h and fixed spacing.<commit_after>//
//  main.cpp
//  tile
//
//  Created by Nhat Nguyen on 9/5/16.
//  Copyright © 2016 Nhat Nguyen. All rights reserved.
//

#include <iostream>
#include <vector>
#include <iterator>
#include <random>

#include "tile.h"

using namespace std;

/* Testing */

int main(void) {
    // At start of game read in all text files.
    vector<string> titleAridVector;
    vector<string> titleForestVector;
    vector<string> titleWaterVector;

    vector<string> descriptionVector;

    vector<string> climateAridVector;
    vector<string> climateForestVector;
    vector<string> climateWaterVector;

    // Testing random element selecting from vector
    vector<int> myVector;
    myVector.push_back(1);
    myVector.push_back(2);
    myVector.push_back(3);
    myVector.push_back(4);
    myVector.push_back(5);
    // Chooses random element from vector.
    cout << "Random element: " << *select_randomly(myVector.begin(), myVector.end()) << endl << endl;

    // Testing tile class
    Tile startingTile;
    startingTile.setTileType(true);
    startingTile.setTitle("In a galaxy far far away... a galactic war rages on.");
    cout << startingTile.getTitle() << endl;
    startingTile.setDescription("You begin your journey on the planet Krypton in the small and humble town of Kal-el.");
    cout << startingTile.getDescription() << endl;

    for (int i = 0; i < 5; i++) {
        Tile myTile;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "main.h"

blaze::CompressedMatrix<double> D_T_blaze, M_invD_blaze;
blaze::DynamicVector<double> gamma_blaze, rhs_blaze;

int num_rows;
int num_cols;
int num_nonzeros;
int RUNS = 100;

vex::profiler<> prof;

double blaze_time;
double eigen_time;
double vexcl_time;

template <typename Matrix, typename Vector>
void TEST(Matrix& D_T, Matrix& M_invD, Vector& gamma, Vector& temporary, Vector& result) {
  for (size_t i = 0; i < RUNS; i++) {
    temporary = M_invD * gamma;
    result = D_T * temporary;
  }
}

void Blaze_TEST() {
  blaze::DynamicVector<double> temporary(num_rows);
  blaze::DynamicVector<double> result(num_rows);

  prof.tic_cpu("Blaze");
  TEST(D_T_blaze, M_invD_blaze, gamma_blaze, temporary, result);
  blaze_time = prof.toc("Blaze");
}

void VexCL_TEST() {

  vex::Context ctx(vex::Filter::Env && vex::Filter::DoublePrecision);
  std::cout << ctx;

  std::vector<size_t> row, col;
  std::vector<double> val;

  ConvertSparse(D_T_blaze, row, col, val);
  vex::SpMat<double> D_T_vex(ctx, num_rows, num_cols, row.data(), col.data(), val.data());

  ConvertSparse(M_invD_blaze, row, col, val);
  vex::SpMat<double> M_invD_vex(ctx, num_rows, num_cols, row.data(), col.data(), val.data());

  std::vector<double> gamma_temp(num_rows);

  for (int i = 0; i < num_rows; i++) {
    gamma_temp[i] = gamma_blaze[i];
  }

  vex::vector<double> gamma_vex(ctx, num_rows);
  vex::vector<double> temporary(ctx, num_rows);
  vex::vector<double> result(ctx, num_rows);
  vex::copy(gamma_temp, gamma_vex);

  temporary = M_invD_vex * gamma_vex;
  temporary = 0;
  result = D_T_vex * temporary;
  result = 0;

  prof.tic_cpu("VexCL");
  TEST(D_T_vex, M_invD_vex, gamma_vex, temporary, result);
  ctx.finish();
  vexcl_time = prof.toc("VexCL");
  // std::cout << vexcl_time << std::endl;
}
//
// void Eigen_TEST() {
//
//  Eigen::SparseMatrix<double> M_invD_eigen(num_cols, num_rows);
//  Eigen::SparseMatrix<double> D_T_eigen(num_rows, num_cols);
//
//  std::vector<Eigen::Triplet<double> > triplet;
//  ConvertSparse(D_T_blaze, triplet);
//  D_T_eigen.setFromTriplets(triplet.begin(), triplet.end());
//
//  ConvertSparse(M_invD_blaze, triplet);
//  M_invD_eigen.setFromTriplets(triplet.begin(), triplet.end());
//
//  Eigen::AMDOrdering<int> ordering;
//  Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic, int> perm;
//
//  ordering(D_T_eigen, perm);
//  ordering(M_invD_eigen, perm);
//
//  Eigen::VectorXd gamma_eigen(num_rows);
//  Eigen::VectorXd temporary(num_rows);
//  Eigen::VectorXd result(num_rows);
//
//  for (int i = 0; i < num_rows; i++) {
//    gamma_eigen[i] = gamma_blaze[i];
//  }
//  prof.tic_cpu("EIGEN");
//  TEST(D_T_eigen, M_invD_eigen, gamma_eigen, temporary, result);
//  eigen_time = prof.toc("EIGEN");
//}

int main(int argc, char* argv[]) {
  if (argc > 2) {
    RUNS = atoi(argv[2]);
  }

  FillSparseMatrix("D_T_" + std::string(argv[1]) + ".dat", D_T_blaze);
  FillSparseMatrix("M_invD_" + std::string(argv[1]) + ".dat", M_invD_blaze);
  FillVector("gamma_" + std::string(argv[1]) + ".dat", gamma_blaze);
  FillVector("b_" + std::string(argv[1]) + ".dat", rhs_blaze);

  num_rows = D_T_blaze.rows();
  num_cols = D_T_blaze.columns();
  num_nonzeros = D_T_blaze.nonZeros();
  printf("D_T: rows:, columns:, non zeros:,M_invD: rows:, columns:, non zeros:, gamma: size:, b: size: \n");
  printf("%d, %d, %d, %d, %d, %d, %d, %d \n",
         D_T_blaze.rows(),
         D_T_blaze.columns(),
         D_T_blaze.nonZeros(),
         M_invD_blaze.rows(),
         M_invD_blaze.columns(),
         M_invD_blaze.nonZeros(),
         gamma_blaze.size(),
         rhs_blaze.size());
  //  printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T_blaze.rows(), D_T_blaze.columns(), D_T_blaze.nonZeros());
  //  printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros());
  //  printf("gamma: size: %d\n", gamma_blaze.size());
  //  printf("b: size: %d\n", rhs_blaze.size());

  Blaze_TEST();
  // Eigen_TEST();
  VexCL_TEST();

  // Two Spmv each with 2*nnz operations
  uint operations = 2 * 2 * num_nonzeros;
  uint moved = 2 * (num_nonzeros + 2 * num_rows) * sizeof(double);

  double blaze_single = blaze_time / RUNS;
  double vex_single = vexcl_time / RUNS;
  double eig_single = eigen_time / RUNS;
  double GFLOP = 1000000000;

  printf("Blaze sec, VexCL sec, Speedup, Blaze Flops, VexCL Flops, Bandwidth Blaze, Bandwidth VexCL \n");
  printf("%f, %f, %f, %f, %f, %f, %f\n",
         blaze_single,
         vex_single,
         blaze_single / vex_single,
         operations / blaze_single / GFLOP,
         operations / vex_single / GFLOP,
         moved / blaze_single / GFLOP,
         moved / vex_single / GFLOP);

  //  printf("Blaze %f sec. Eigen %f sec. VexCL %f sec.\n", blaze_single, eig_single, vex_single);
  //  printf("Speedup: Blaze vs Eigen %f\n", blaze_single / eig_single);
  //  printf("Speedup: Blaze vs VexCL %f\n", blaze_single / vex_single);
  //  printf("Speedup: Eigen vs VexCL %f\n", eig_single / vex_single);
  //
  //  printf("Flops: Blaze %f Eigen %f VexCL %f\n", operations / blaze_single / GFLOP, operations / eig_single / GFLOP, operations / vex_single / GFLOP);
  //  printf("Bandwidth: Blaze %f Eigen %f VexCL %f\n", moved / blaze_single / GFLOP, moved / eig_single / GFLOP, moved / vex_single / GFLOP);

  return 0;
}
<commit_msg>Print out the memory used on the device and individual timings<commit_after>#include "main.h"

blaze::CompressedMatrix<double> D_T_blaze, M_invD_blaze;
blaze::DynamicVector<double> gamma_blaze, rhs_blaze;

int num_rows;
int num_cols;
int num_nonzeros;
int RUNS = 100;

vex::profiler<> prof;

double blaze_time;
double eigen_time;
double vexcl_time;
double GFLOP = 1000000000;
template <typename Matrix, typename Vector>
void TEST(Matrix& D_T, Matrix& M_invD, Vector& gamma, Vector& temporary, Vector& result) {
  for (size_t i = 0; i < RUNS; i++) {
    temporary = M_invD * gamma;
    result = D_T * temporary;
  }
}

void Blaze_TEST() {
  blaze::DynamicVector<double> temporary(num_rows);
  blaze::DynamicVector<double> result(num_rows);

  prof.tic_cpu("Blaze");
  TEST(D_T_blaze, M_invD_blaze, gamma_blaze, temporary, result);
  blaze_time = prof.toc("Blaze");
  std::cout << blaze_time << std::endl;
}

void VexCL_TEST() {

  vex::Context ctx(vex::Filter::Env && vex::Filter::DoublePrecision);
  std::cout << ctx;

  std::vector<size_t> row, col;
  std::vector<double> val;

  ConvertSparse(D_T_blaze, row, col, val);
  vex::SpMat<double> D_T_vex(ctx, num_rows, num_cols, row.data(), col.data(), val.data());

  ConvertSparse(M_invD_blaze, row, col, val);
  vex::SpMat<double> M_invD_vex(ctx, num_rows, num_cols, row.data(), col.data(), val.data());

  std::vector<double> gamma_temp(num_rows);

  for (int i = 0; i < num_rows; i++) {
    gamma_temp[i] = gamma_blaze[i];
  }

  vex::vector<double> gamma_vex(ctx, num_rows);
  vex::vector<double> temporary(ctx, num_rows);
  vex::vector<double> result(ctx, num_rows);
  vex::copy(gamma_temp, gamma_vex);

  temporary = M_invD_vex * gamma_vex;
  result = D_T_vex * temporary;

  prof.tic_cpu("VexCL");
  TEST(D_T_vex, M_invD_vex, gamma_vex, temporary, result);
  ctx.finish();
  vexcl_time = prof.toc("VexCL");
   std::cout << vexcl_time << std::endl;
}
//
// void Eigen_TEST() {
//
//  Eigen::SparseMatrix<double> M_invD_eigen(num_cols, num_rows);
//  Eigen::SparseMatrix<double> D_T_eigen(num_rows, num_cols);
//
//  std::vector<Eigen::Triplet<double> > triplet;
//  ConvertSparse(D_T_blaze, triplet);
//  D_T_eigen.setFromTriplets(triplet.begin(), triplet.end());
//
//  ConvertSparse(M_invD_blaze, triplet);
//  M_invD_eigen.setFromTriplets(triplet.begin(), triplet.end());
//
//  Eigen::AMDOrdering<int> ordering;
//  Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic, int> perm;
//
//  ordering(D_T_eigen, perm);
//  ordering(M_invD_eigen, perm);
//
//  Eigen::VectorXd gamma_eigen(num_rows);
//  Eigen::VectorXd temporary(num_rows);
//  Eigen::VectorXd result(num_rows);
//
//  for (int i = 0; i < num_rows; i++) {
//    gamma_eigen[i] = gamma_blaze[i];
//  }
//  prof.tic_cpu("EIGEN");
//  TEST(D_T_eigen, M_invD_eigen, gamma_eigen, temporary, result);
//  eigen_time = prof.toc("EIGEN");
//}

int main(int argc, char* argv[]) {
  if (argc > 2) {
    RUNS = atoi(argv[2]);
  }

  FillSparseMatrix("D_T_" + std::string(argv[1]) + ".dat", D_T_blaze);
  FillSparseMatrix("M_invD_" + std::string(argv[1]) + ".dat", M_invD_blaze);
  FillVector("gamma_" + std::string(argv[1]) + ".dat", gamma_blaze);
  FillVector("b_" + std::string(argv[1]) + ".dat", rhs_blaze);

  num_rows = D_T_blaze.rows();
  num_cols = D_T_blaze.columns();
  num_nonzeros = D_T_blaze.nonZeros();
  printf("D_T: rows:, columns:, non zeros:,M_invD: rows:, columns:, non zeros:, gamma: size:, b: size: Memory\n");
  printf("%d, %d, %d, %d, %d, %d, %d, %d %f\n",
		  num_rows,
		  num_cols,
		  num_nonzeros,
         M_invD_blaze.rows(),
         M_invD_blaze.columns(),
         M_invD_blaze.nonZeros(),
         gamma_blaze.size(),
         rhs_blaze.size(),
		 ((num_nonzeros + M_invD_blaze.nonZeros() + gamma_blaze.size() + rhs_blaze.size()) * sizeof(double))/GFLOP );
  //  printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T_blaze.rows(), D_T_blaze.columns(), D_T_blaze.nonZeros());
  //  printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros());
  //  printf("gamma: size: %d\n", gamma_blaze.size());
  //  printf("b: size: %d\n", rhs_blaze.size());

  Blaze_TEST();
  // Eigen_TEST();
  VexCL_TEST();

  // Two Spmv each with 2*nnz operations
  uint operations = 2 * 2 * num_nonzeros;
  uint moved = 2 * (num_nonzeros + 2 * num_rows) * sizeof(double);

  double blaze_single = blaze_time / RUNS;
  double vex_single = vexcl_time / RUNS;
  double eig_single = eigen_time / RUNS;

  printf("Blaze sec, VexCL sec, Speedup, Blaze Flops, VexCL Flops, Bandwidth Blaze, Bandwidth VexCL \n");
  printf("%f, %f, %f, %f, %f, %f, %f\n",
         blaze_single,
         vex_single,
         blaze_single / vex_single,
         operations / blaze_single / GFLOP,
         operations / vex_single / GFLOP,
         moved / blaze_single / GFLOP,
         moved / vex_single / GFLOP);

  //  printf("Blaze %f sec. Eigen %f sec. VexCL %f sec.\n", blaze_single, eig_single, vex_single);
  //  printf("Speedup: Blaze vs Eigen %f\n", blaze_single / eig_single);
  //  printf("Speedup: Blaze vs VexCL %f\n", blaze_single / vex_single);
  //  printf("Speedup: Eigen vs VexCL %f\n", eig_single / vex_single);
  //
  //  printf("Flops: Blaze %f Eigen %f VexCL %f\n", operations / blaze_single / GFLOP, operations / eig_single / GFLOP, operations / vex_single / GFLOP);
  //  printf("Bandwidth: Blaze %f Eigen %f VexCL %f\n", moved / blaze_single / GFLOP, moved / eig_single / GFLOP, moved / vex_single / GFLOP);

  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <iterator>
using namespace std;

const vector<string>& split(string filename)
{
	/*
	takes filename to open
	returns a vector of commands, ignoring white space and grouping based on {}
	*/
	ifstream myfile(filename);
	vector<string>* commands = new vector<string>();
	string current_command = "";
	int brace_balance;
	typedef std::istream_iterator<char> CharIter;

	for (CharIter it(myfile); it != CharIter(); ++it)
	{
		switch (*it)
		{
		case ' ': case '\t': case '\n': break;
		case '{':
			brace_balance = 1;
			++it;
			while (brace_balance > 0 && it != CharIter())
			{
				if (*it == '{') ++brace_balance;
				if (*it == '}') --brace_balance;
				if (brace_balance > 0)
				{
					current_command = current_command + *it;
					++it;
				}
			}
		case ';':
			commands->push_back(current_command);
			current_command = "";
			break;
		default:
			current_command = current_command + *it;
			break;
		}
	}
	myfile.close();
	return *commands;
}

int main()
{
	vector<string> commands = split("file");
	cout << "Commands read as follows: (in order of execution)\n";
	for (vector<string>::const_iterator i = commands.begin(); i != commands.end(); ++i) cout << "  - " << *i << endl;
}
<commit_msg>Changed how split() groups braces<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <iterator>
using namespace std;

const vector<string>& split(string filename)
{
	ifstream myfile(filename);
	vector<string>* commands = new vector<string>();
	string current_command = "";
	int brace_balance = 0;
	typedef std::istreambuf_iterator<char> CharIter;

	for (CharIter it(myfile); it != CharIter(); ++it)
	{
		cout << current_command << endl;
		switch (*it)
		{
		case '\t': case '\n': case ' ':
			// silly whitespace
			break;
		case '{':
			++brace_balance;
			if (brace_balance != 1) // if it's not the opening {
			{
				current_command += *it;
			}
			break;
		case '}':
			--brace_balance;
			if (brace_balance != 0) // if it's not the closing }
			{
				current_command += *it;
			}
			break;
		case ';':
			if (brace_balance == 0)
			{
				commands->push_back(current_command);
				current_command = "";
			}
			else
			{
				current_command += ';';
			}
			break;
		default:
			current_command += *it;
			break;
		}
	}
	myfile.close();
	return *commands;
}
int main()
{
	vector<string> commands = split("file");
	cout << "Commands read as follows: (in order of execution)\n";
	for (vector<string>::const_iterator i = commands.begin(); i != commands.end(); ++i) cout << "  - " << *i << endl;
}
<|endoftext|>


<commit_before>cc88cb38-2747-11e6-b78c-e0f84713e7b8<commit_msg>That didn't fix it<commit_after>cca1ff02-2747-11e6-bb0f-e0f84713e7b8<|endoftext|>


<commit_before>a376b154-ad58-11e7-8f26-ac87a332f658<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>a3ed3573-ad58-11e7-8dc7-ac87a332f658<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2010-2011 Razor team
 * Authors:
 *   Petr Vanek <petr@scribus.info>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <LxQtApplication>
#include <LxQtAboutDialog>
#include <LxQtGridLayout>

int main(int argc, char *argv[])
{
    //QApplication app(argc, argv);
    //LxQt::GridLayout *g = new LxQt::GridLayout();
    LxQt::Application app(argc, argv);
    LxQt::AboutDialog dlg;
    return app.exec();
}
<commit_msg>Use preferred header style<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2010-2011 Razor team
 * Authors:
 *   Petr Vanek <petr@scribus.info>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <LXQt/Application>
#include <LXQt/AboutDialog>
#include <LXQt/GridLayout>

int main(int argc, char *argv[])
{
    //QApplication app(argc, argv);
    //LxQt::GridLayout *g = new LxQt::GridLayout();
    LxQt::Application app(argc, argv);
    LxQt::AboutDialog dlg;
    return app.exec();
}
<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 *  Created on: Apr 9, 2014
 *      Author: Pimenta
 */

#include <cmath>
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <list>
#include <map>
#include <set>
#include <string>

using namespace std;

typedef int64_t  word_t;
typedef uint64_t uword_t;
typedef uint32_t address_t;

enum field_t {
  A, B, J
};

#ifndef MEM_WORDS
#define MEM_WORDS 0x2000
#endif

const uword_t ADDRESS_WIDTH = uword_t(log2(double(MEM_WORDS)));

fstream f;
string buf;
set<string> exported;
map<string, address_t> symbols;
map<string, list<pair<address_t, field_t>>> references;
list<pair<address_t, field_t>> absolute;
address_t code_size = 0;
uword_t* mem = new uword_t[MEM_WORDS];

inline void readField(uword_t& instr, field_t field) {
  int mult = field == A ? 2 : (field == B ? 1 : 0);
  if (buf[0] == '0' && buf[1] == 'x') {
    address_t tmp;
    sscanf(buf.c_str(), "%i", &tmp);
    instr |= (tmp << mult*ADDRESS_WIDTH);
    absolute.emplace_back(code_size, field);
  }
  else {
    auto sym = symbols.find(buf);
    if (sym == symbols.end())
      references[buf].emplace_back(code_size, field);
    else
      instr |= (uword_t(sym->second) << mult*ADDRESS_WIDTH);
  }
}

int main(int argc, char* argv[]) {
  if (argc != 3) {
    fprintf(stderr, "Usage mode: subleq-asm <assembly_file> <object_file>\n");
    return 0;
  }

  f.open(argv[1]);

  f >> buf; // reading ".export"

  for (f >> buf; buf != ".data"; f >> buf) { // reading export section
    exported.insert(buf);
  }

  for (f >> buf; buf != ".text"; f >> buf) { // reading data section
    symbols[buf.substr(0, buf.size() - 1)] = code_size;
    f >> mem[code_size++];
  }

  for (f >> buf; !f.eof(); f >> buf) { // reading text section
    if (buf[buf.size() - 1] == ':') { // label found
      symbols[buf.substr(0, buf.size() - 1)] = code_size;

      if (buf == "start:") // exporting start label
        exported.insert(string("start"));

      continue;
    }

    uword_t instr = 0;
    readField(instr, A);
    f >> buf;
    readField(instr, B);
    f >> buf;
    readField(instr, J);
    mem[code_size++] = instr;
  }

  f.close();

  // solve references
  for (auto map_it = references.begin(); map_it != references.end();) {
    // external symbols
    auto sym = symbols.find(map_it->first);
    if (sym == symbols.end()) {
      ++map_it;
      continue;
    }

    // solve
    for (auto it = map_it->second.begin(); it != map_it->second.end(); ++it) {
      uword_t& instr = mem[it->first];
      switch (it->second) {
        case A:
          instr |= (uword_t(sym->second) << 2*ADDRESS_WIDTH);
          break;
        case B:
          instr |= (uword_t(sym->second) << 1*ADDRESS_WIDTH);
          break;
        case J:
          instr |= (uword_t(sym->second) << 0*ADDRESS_WIDTH);
          break;
      }
    }

    references.erase(map_it++);
  }

  f.open(argv[2], fstream::out | fstream::binary);

  {
    uint32_t tmp;

    // write number of exported symbols
    tmp = exported.size();
    f.write((const char*)&tmp, sizeof(uint32_t));

    // write exported symbols
    for (auto& exp : exported) {
      // string
      f.write(exp.c_str(), exp.size() + 1);

      // address
      tmp = symbols[exp];
      f.write((const char*)&tmp, sizeof(uint32_t));
    }

    // write number of symbols of pending references
    tmp = references.size();
    f.write((const char*)&tmp, sizeof(uint32_t));

    // write symbols of pending references
    for (auto& sym : references) {
      // string
      f.write(sym.first.c_str(), sym.first.size() + 1);

      // write number of references to current symbol
      tmp = sym.second.size();
      f.write((const char*)&tmp, sizeof(uint32_t));

      // write references to current symbol
      for (auto& ref : sym.second) {
        // address
        tmp = ref.first;
        f.write((const char*)&tmp, sizeof(uint32_t));

        // field
        tmp = ref.second;
        f.write((const char*)&tmp, sizeof(uint32_t));
      }
    }

    // write number of absolute addresses
    tmp = absolute.size();
    f.write((const char*)&tmp, sizeof(uint32_t));

    // write absolute addresses
    for (auto& addr : absolute) {
      // address
      tmp = addr.first;
      f.write((const char*)&tmp, sizeof(uint32_t));

      // field
      tmp = addr.second;
      f.write((const char*)&tmp, sizeof(uint32_t));
    }

    // write assembled code size
    f.write((const char*)&code_size, sizeof(address_t));

    // write assembled code
    f.write((const char*)mem, sizeof(uword_t)*code_size);
  }

  f.close();

  delete[] mem;

  return 0;
}
<commit_msg>Changing variable name<commit_after>/*
 * main.cpp
 *
 *  Created on: Apr 9, 2014
 *      Author: Pimenta
 */

#include <cmath>
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <list>
#include <map>
#include <set>
#include <string>

using namespace std;

typedef int64_t  word_t;
typedef uint64_t uword_t;
typedef uint32_t address_t;

enum field_t {
  A, B, J
};

#ifndef MEM_WORDS
#define MEM_WORDS 0x2000
#endif

const uword_t ADDRESS_WIDTH = uword_t(log2(double(MEM_WORDS)));

fstream f;
string buf;
set<string> exported;
map<string, address_t> symbols;
map<string, list<pair<address_t, field_t>>> references;
list<pair<address_t, field_t>> absolute;
address_t mem_size = 0;
uword_t* mem = new uword_t[MEM_WORDS];

inline void readField(uword_t& instr, field_t field) {
  int mult = field == A ? 2 : (field == B ? 1 : 0);
  if (buf[0] == '0' && buf[1] == 'x') {
    address_t tmp;
    sscanf(buf.c_str(), "%i", &tmp);
    instr |= (tmp << mult*ADDRESS_WIDTH);
    absolute.emplace_back(mem_size, field);
  }
  else {
    auto sym = symbols.find(buf);
    if (sym == symbols.end())
      references[buf].emplace_back(mem_size, field);
    else
      instr |= (uword_t(sym->second) << mult*ADDRESS_WIDTH);
  }
}

int main(int argc, char* argv[]) {
  if (argc != 3) {
    fprintf(stderr, "Usage mode: subleq-asm <assembly_file> <object_file>\n");
    return 0;
  }

  f.open(argv[1]);

  f >> buf; // reading ".export"

  for (f >> buf; buf != ".data"; f >> buf) { // reading export section
    exported.insert(buf);
  }

  for (f >> buf; buf != ".text"; f >> buf) { // reading data section
    symbols[buf.substr(0, buf.size() - 1)] = mem_size;
    f >> mem[mem_size++];
  }

  for (f >> buf; !f.eof(); f >> buf) { // reading text section
    if (buf[buf.size() - 1] == ':') { // label found
      symbols[buf.substr(0, buf.size() - 1)] = mem_size;

      if (buf == "start:") // exporting start label
        exported.insert(string("start"));

      continue;
    }

    uword_t instr = 0;
    readField(instr, A);
    f >> buf;
    readField(instr, B);
    f >> buf;
    readField(instr, J);
    mem[mem_size++] = instr;
  }

  f.close();

  // solve references
  for (auto map_it = references.begin(); map_it != references.end();) {
    // external symbols
    auto sym = symbols.find(map_it->first);
    if (sym == symbols.end()) {
      ++map_it;
      continue;
    }

    // solve
    for (auto it = map_it->second.begin(); it != map_it->second.end(); ++it) {
      uword_t& instr = mem[it->first];
      switch (it->second) {
        case A:
          instr |= (uword_t(sym->second) << 2*ADDRESS_WIDTH);
          break;
        case B:
          instr |= (uword_t(sym->second) << 1*ADDRESS_WIDTH);
          break;
        case J:
          instr |= (uword_t(sym->second) << 0*ADDRESS_WIDTH);
          break;
      }
    }

    references.erase(map_it++);
  }

  f.open(argv[2], fstream::out | fstream::binary);

  {
    uint32_t tmp;

    // write number of exported symbols
    tmp = exported.size();
    f.write((const char*)&tmp, sizeof(uint32_t));

    // write exported symbols
    for (auto& exp : exported) {
      // string
      f.write(exp.c_str(), exp.size() + 1);

      // address
      tmp = symbols[exp];
      f.write((const char*)&tmp, sizeof(uint32_t));
    }

    // write number of symbols of pending references
    tmp = references.size();
    f.write((const char*)&tmp, sizeof(uint32_t));

    // write symbols of pending references
    for (auto& sym : references) {
      // string
      f.write(sym.first.c_str(), sym.first.size() + 1);

      // write number of references to current symbol
      tmp = sym.second.size();
      f.write((const char*)&tmp, sizeof(uint32_t));

      // write references to current symbol
      for (auto& ref : sym.second) {
        // address
        tmp = ref.first;
        f.write((const char*)&tmp, sizeof(uint32_t));

        // field
        tmp = ref.second;
        f.write((const char*)&tmp, sizeof(uint32_t));
      }
    }

    // write number of absolute addresses
    tmp = absolute.size();
    f.write((const char*)&tmp, sizeof(uint32_t));

    // write absolute addresses
    for (auto& addr : absolute) {
      // address
      tmp = addr.first;
      f.write((const char*)&tmp, sizeof(uint32_t));

      // field
      tmp = addr.second;
      f.write((const char*)&tmp, sizeof(uint32_t));
    }

    // write assembled code size
    f.write((const char*)&mem_size, sizeof(address_t));

    // write assembled code
    f.write((const char*)mem, sizeof(uword_t)*mem_size);
  }

  f.close();

  delete[] mem;

  return 0;
}
<|endoftext|>


<commit_before>/*
    //problems to fix: need to find a way to download the file via the internet that works on windows too

*/

#include <iostream>
#include <stdlib.h> //for system() function
#include <unistd.h> //for changing directories
#include <sys/stat.h> //for stat() function
#include <fstream>
#include <ctime>
#include <sstream> //for stringstream: convert int to string
#include <vector>
#include <iomanip> //output manipulators
#include "termcolor.hpp" //header only library for colored output

using namespace std;

void weekConvert(int &tempWeek_, string &pcWeek_); //converts tempWeek
void monthConvert(int &tempMonth_, string &pcMonth_); //converts tempMonth
void dataInput(ifstream &schedule_, vector<string> &weekDay_, vector<string> &time_, vector<string> &box_, vector<string> &team1_, vector<string> &team1Score_, vector<string> &team2_,
vector<string> &team2Score_, vector<string> &OT_, vector<string> &notes_, string userString); //gets data from file
void outFunction(vector<string> &team_, vector<int> &placeHolder_, int &numb);
int main()
{
    int changeDir, newDir;
    ifstream schedule;
    string a, b, c, userString; //to ignore first three lines
    vector<string> weekDay, times, box, team1, team1Score, team2, team2Score, OT, notes;
    vector<int> placeHolder;
    string pcWeek, pcMonth, pcDay, pcYear; //system dates
    string pcDate; //final string for system date
    int tempMonth, tempYear, tempDay, tempWeek, i = 0;
    stringstream convertYear, convertDay;

    time_t t = time(0);   // get time now
    struct tm *now = localtime( &t );

    tempWeek = (now->tm_wday);
    tempMonth = (now->tm_mon + 1);
    tempDay = (now->tm_mday);
    tempYear = (now->tm_year + 1900);

    weekConvert(tempWeek, pcWeek); //converts tempWeek
    monthConvert(tempMonth, pcMonth); //converts tempMonth

    convertYear << tempYear; //converts years to string
    pcYear = convertYear.str();

    convertDay << tempDay; //converts days to string
    pcDay = convertDay.str();

    pcDate = pcWeek + " " + pcMonth + " " + pcDay + " " + pcYear;

    //newDir = system("mkdir NBAschedule"); //linux only command
    //changeDir = chdir("/home/dan/NBAschedule/"); //linux only command

    schedule.open("schedule.csv");

    if (schedule.is_open())
    {

        getline(schedule, a);
        getline(schedule, b);
        getline(schedule, c);

        dataInput(schedule, weekDay, times, box, team1, team1Score, team2, team2Score, OT, notes, userString); //first read of the file

        do
        {
            if (weekDay[i] != pcDate)
            {
                dataInput(schedule, weekDay, times, box, team1, team1Score, team2, team2Score, OT, notes, userString); //calling the function if system date doesnt match
            }
            else
            {
                placeHolder.push_back(i); //holds the location of today's games

                dataInput(schedule, weekDay, times, box, team1, team1Score, team2, team2Score, OT, notes, userString); //calling the input function
            }

            i++; //put this int the else statement and delete the output then print out formatted date after the loop

        }while(!schedule.eof());

        schedule.close();

        int one = 0;
        int two = 0;
        int three = 0;
        int four = 0;
        int five = 0;
        int six = 0;
        int seven = 0;
        int y = 0;
        int i = 0;
        int z = 2;

        for(i; i < placeHolder.size(); i++)
        {
            cout << termcolor::cyan << setw(30) << left << weekDay[placeHolder[i]] << setw(5) << " ";//22
	    cout << termcolor::reset;

            if (i == placeHolder.size() - 1)
                {
                    y = 1;

                        if(placeHolder.size()%2)
                        {
                            z = 1;
                        }
                }

            if(y == 1)
            {

                cout << endl;
                for(int x = 0; x < z; x++) //need to find a way to continue
                {
                    cout << termcolor::cyan << setw(30) << left << times[placeHolder[one]] << setw(5) << " ";//29
		    cout << termcolor::reset;
                    one++;
                }
                cout << endl;
		for(int x = 0; x < z; x++)
                {
			outFunction(team1,placeHolder,two);
			two++;
                }
                for(int x = 0; x < z; x++)
                {
                    cout << team1Score[placeHolder[three]];
                    three++;
                }
                cout << endl;
                for(int x = 0; x < z; x++)
                {
                    //cout << setw(30) << left << team2[placeHolder[four]] << setw(5) << " ";//23
		    outFunction(team2,placeHolder,four);
                    four++;
                }

                for(int x = 0; x < z; x++)
                {
                    cout << team2Score[placeHolder[five]];
                    five++;
                }
                cout << endl;
                for(int x = 0; x < z; x++)
                {
                    cout << OT[placeHolder[six]];
                    six++;
                }
                cout << endl;
                for(int x = 0; x < z; x++)
                {
                    cout << notes[placeHolder[seven]];
                    seven++;
                }

                y = 0;

                cout << "\n\n" << endl;
            }
            else
            {
                y++;
            }
        }

       /* i = 0;

        do
        {
                //going to write for loops to format output into columns and rows. ex: for(){ cout << vectorString << setw() }
                cout << weekDay[placeHolder[i]] << endl;
                cout << times[placeHolder[i]] << endl;
                cout << team1[placeHolder[i]] << " " << team1Score[placeHolder[i]] << endl;
                cout << team2[placeHolder[i]] << " " << team2Score[placeHolder[i]] << endl;
                cout << OT[placeHolder[i]] << endl;
                cout << notes[placeHolder[i]] << endl;

                i++;

        }while(i < placeHolder.size()); */

    }
    else
    {
        cout << "Couldn't find the file, downloading now...please re-run the program" << endl;
        system("wget https://raw.githubusercontent.com/dm117/NBA-terminal/master/schedule.csv");
        cout << termcolor::on_red << "\n\nDownloaded file, re-run the program..." << endl;
	cout << termcolor::reset << endl;
    }

    cout << "\nAll times are in EST" << endl;

    return 0;
}

void weekConvert(int &tempWeek_, string &pcWeek_)
{
    switch ( tempWeek_ )
    {
    case 0:
        pcWeek_ = "Sun";
        break;
    case 1:
        pcWeek_ = "Mon";
        break;
    case 2:
        pcWeek_ = "Tue";
        break;
    case 3:
        pcWeek_ = "Wed";
        break;
    case 4:
        pcWeek_ = "Thu";
        break;
    case 5:
        pcWeek_ = "Fri";
        break;
    case 6:
        pcWeek_ = "Sat";
        break;
    default:
        cout<<"ERROR GETTING DAY OF THE WEEK\n";
        break;
    }
}

void monthConvert(int &tempMonth_, string &pcMonth_)
{
    switch ( tempMonth_ )
    {
    case 1:
        pcMonth_ = "Jan";
        break;
    case 2:
        pcMonth_ = "Feb";
        break;
    case 3:
        pcMonth_ = "March";
        break;
    case 4:
        pcMonth_ = "Apr";
        break;
    case 5:
        pcMonth_ = "May";
        break;
    case 6:
        pcMonth_ = "Jun";
        break;
    case 7:
        pcMonth_ = "Jul";
        break;
    case 8:
        pcMonth_ = "Aug";
        break;
    case 9:
        pcMonth_ = "Sep";
        break;
    case 10:
        pcMonth_ = "Oct";
        break;
    case 11:
        pcMonth_ = "Nov";
        break;
    case 12:
        pcMonth_ = "Dec";
        break;
    default:
        cout<<"ERROR\n";
        break;
    }
}

void dataInput(ifstream &schedule_, vector<string> &weekDay_, vector<string> &time_, vector<string> &box_, vector<string> &team1_, vector<string> &team1Score_, vector<string> &team2_,
vector<string> &team2Score_, vector<string> &OT_, vector<string> &notes_, string userString_) //gets data from file
{

    getline(schedule_, userString_, ',');
    weekDay_.push_back(userString_);

    getline(schedule_, userString_, ',');
    time_.push_back(userString_);

    getline(schedule_, userString_, ',');
    box_.push_back(userString_);

    getline(schedule_, userString_, ',');
    team1_.push_back(userString_);

    getline(schedule_, userString_, ',');
    team1Score_.push_back(userString_);

    getline(schedule_, userString_, ',');
    team2_.push_back(userString_);

    getline(schedule_, userString_, ',');
    team2Score_.push_back(userString_);

    getline(schedule_, userString_, ',');
    OT_.push_back(userString_);

    getline(schedule_, userString_);
    notes_.push_back(userString_);

}
void outFunction(vector<string> &team1_, vector<int> &placeHolder_, int &two_)
{
	if (team1_[placeHolder_[two_]] == "Miami Heat" || team1_[placeHolder_[two_]] == "Toronto Raptors" || team1_[placeHolder_[two_]] == "Chicago Bulls" || team1_[placeHolder_[two_]] == "Atlanta Hawks" || team1_[placeHolder_[two_]] == "Portland Trail Blazers" || team1_[placeHolder_[two_]] == "Los Angeles Clippers" || team1_[placeHolder_[two_]] == "Houston Rockets")
	{
		cout <<  termcolor::red << setw(30) << left << team1_[placeHolder_[two_]] << setw(5) << " ";//22
	}
	else if (team1_[placeHolder_[two_]] == "New York Knicks" || team1_[placeHolder_[two_]] == "Detroit Pistons" || team1_[placeHolder_[two_]] == "Orlando Magic" || team1_[placeHolder_[two_]] == "Washington Wizards" || team1_[placeHolder_[two_]] == "Oklahoma City Thunder" || team1_[placeHolder_[two_]] == "Utah Jazz" || team1_[placeHolder_[two_]] == "Dallas Mavericks" || team1_[placeHolder_[two_]] == "Memphis Grizzlies")
	{
		cout << termcolor::blue << setw(30) << left << team1_[placeHolder_[two_]] << setw(5) << " ";//22
	}
	else if (team1_[placeHolder_[two_]] == "Boston Celtics" || team1_[placeHolder_[two_]] == "Milwaukee Bucks" || team1_[placeHolder_[two_]] == "Minnesota Timberwolves")
	{
		cout << termcolor::green << setw(30) << left << team1_[placeHolder_[two_]] << setw(5) << " ";//22
	}
	else if (team1_[placeHolder_[two_]] == "Cleveland Cavaliers" || team1_[placeHolder_[two_]] == "Indiana Pacers" || team1_[placeHolder_[two_]] == "Denver Nuggets" || team1_[placeHolder_[two_]] == "Golden State Warriors" || team1_[placeHolder_[two_]] == "Los Angeles Lakers")
	{
		cout << termcolor::yellow << setw(30) << left << team1_[placeHolder_[two_]] << setw(5) << " ";//22
	}
	else if (team1_[placeHolder_[two_]] == "Charlotte Hornets" || team1_[placeHolder_[two_]] == "Sacramento Kings")
	{
		cout << termcolor::magenta << setw(30) << left << team1_[placeHolder_[two_]] << setw(5) << " ";//22
	}
	else if (team1_[placeHolder_[two_]] == "Brooklyn Nets" || team1_[placeHolder_[two_]] == "Philadelphia 76ers" || team1_[placeHolder_[two_]] == "New Orleans Pelicans" || team1_[placeHolder_[two_]] == "San Antonio Spurs")
	{
		cout << termcolor::white << setw(30) << left << team1_[placeHolder_[two_]] << setw(5) << " ";//22
	}

		cout << termcolor::reset;
}

/*--------------------------------------------THIS WILL BE USE LATER TO CHECK IF THE DIRECTORY ALREADY EXISTS------------
struct stat statbuf;
int isDir = 0;
if (stat("/NBAschedule", &statbuf) != -1) {
   if (S_ISDIR(statbuf.st_mode)) {
      isDir = 1;
   }
} else {

       here you might check errno for the reason, ENOENT will mean the path
       was bad, ENOTDIR means part of the path is not a directory, EACCESS
       would mean you can't access the path. Regardless, from the point of
       view of your app, the path is not a directory if stat fails.

}

//Source: https://www.quora.com/How-do-I-check-if-a-directory-exists-in-Linux-using-C++
--------------------------------------------THIS WILL BE USE LATER TO CHECK IF THE DIRECTORY ALREADY EXISTS------------*/

<commit_msg>BSD license, termcolor attribution, code clean up<commit_after>/*

-----------------termcolor library used for color output-----------------
Copyright (c) 2013 by Igor Kalnitsky
license BSD, see LICENSE for details
-------------------------------------------------------------------------

NBA-terminal is a simple open-source, simplistic terminal application that displays the NBA schedule for the day.
Copyright (c) 2013, Daniel Maria All rights reserved.
License BSD, see LICENSE for details

problems to fix: need to find a way to download the file via the internet that works on windows too

*/

#include <iostream>
#include <stdlib.h> //for system() function
#include <unistd.h> //for changing directories
#include <sys/stat.h> //for stat() function
#include <fstream>
#include <ctime>
#include <sstream> //for stringstream: convert int to string
#include <vector>
#include <iomanip> //output manipulators
#include "termcolor.hpp" //header only library for colored output

using namespace std;

void weekConvert(int &tempWeek_, string &pcWeek_); //converts tempWeek
void monthConvert(int &tempMonth_, string &pcMonth_); //converts tempMonth
void dataInput(ifstream &schedule_, vector<string> &weekDay_, vector<string> &time_, vector<string> &box_, vector<string> &team1_, vector<string> &team1Score_, vector<string> &team2_,
vector<string> &team2Score_, vector<string> &OT_, vector<string> &notes_, string userString); //gets data from file
void outFunction(vector<string> &team_, vector<int> &placeHolder_, int &numb);
int main()
{
    int changeDir, newDir;
    ifstream schedule;
    string a, b, c, userString; //to ignore first three lines
    vector<string> weekDay, times, box, team1, team1Score, team2, team2Score, OT, notes;
    vector<int> placeHolder;
    string pcWeek, pcMonth, pcDay, pcYear; //system dates
    string pcDate; //final string for system date
    int tempMonth, tempYear, tempDay, tempWeek, i = 0;
    stringstream convertYear, convertDay;

    time_t t = time(0);   // get time now
    struct tm *now = localtime( &t );

    tempWeek = (now->tm_wday);
    tempMonth = (now->tm_mon + 1);
    tempDay = (now->tm_mday);
    tempYear = (now->tm_year + 1900);

    weekConvert(tempWeek, pcWeek); //converts tempWeek
    monthConvert(tempMonth, pcMonth); //converts tempMonth

    convertYear << tempYear; //converts years to string
    pcYear = convertYear.str();

    convertDay << tempDay; //converts days to string
    pcDay = convertDay.str();

    pcDate = pcWeek + " " + pcMonth + " " + pcDay + " " + pcYear;

    //newDir = system("mkdir NBAschedule"); //linux only command
    //changeDir = chdir("/home/dan/NBAschedule/"); //linux only command

    schedule.open("schedule.csv");

    if (schedule.is_open())
    {

        getline(schedule, a);
        getline(schedule, b);
        getline(schedule, c);

        dataInput(schedule, weekDay, times, box, team1, team1Score, team2, team2Score, OT, notes, userString); //first read of the file

        do
        {
            if (weekDay[i] != pcDate)
            {
                dataInput(schedule, weekDay, times, box, team1, team1Score, team2, team2Score, OT, notes, userString); //calling the function if system date doesnt match
            }
            else
            {
                placeHolder.push_back(i); //holds the location of today's games

                dataInput(schedule, weekDay, times, box, team1, team1Score, team2, team2Score, OT, notes, userString); //calling the input function
            }

            i++; //put this int the else statement and delete the output then print out formatted date after the loop

        }while(!schedule.eof());

        schedule.close();

        int one = 0;
        int two = 0;
        int three = 0;
        int four = 0;
        int five = 0;
        int six = 0;
        int seven = 0;
        int y = 0;
        int i = 0;
        int z = 2;

        for(i; i < placeHolder.size(); i++)
        {
            cout << termcolor::cyan << setw(30) << left << weekDay[placeHolder[i]] << setw(5) << " ";//22
	    cout << termcolor::reset;

            if (i == placeHolder.size() - 1)
                {
                    y = 1;

                        if(placeHolder.size()%2)
                        {
                            z = 1;
                        }
                }

            if(y == 1)
            {

                cout << endl;
                for(int x = 0; x < z; x++) //need to find a way to continue
                {
                    cout << termcolor::cyan << setw(30) << left << times[placeHolder[one]] << setw(5) << " ";//29
		    cout << termcolor::reset;
                    one++;
                }
                cout << endl;
		for(int x = 0; x < z; x++)
                {
			outFunction(team1,placeHolder,two);
			two++;
                }
                for(int x = 0; x < z; x++)
                {
                    cout << team1Score[placeHolder[three]];
                    three++;
                }
                cout << endl;
                for(int x = 0; x < z; x++)
                {
                    //cout << setw(30) << left << team2[placeHolder[four]] << setw(5) << " ";//23
		    outFunction(team2,placeHolder,four);
                    four++;
                }

                for(int x = 0; x < z; x++)
                {
                    cout << team2Score[placeHolder[five]];
                    five++;
                }
                cout << endl;
                for(int x = 0; x < z; x++)
                {
                    cout << OT[placeHolder[six]];
                    six++;
                }
                cout << endl;
                for(int x = 0; x < z; x++)
                {
                    cout << notes[placeHolder[seven]];
                    seven++;
                }

                y = 0;

                cout << "\n\n" << endl;
            }
            else
            {
                y++;
            }
        }

        cout << "\nAll times are in EST" << endl;

    }
    else
    {
        cout << "Couldn't find the file, downloading now...please re-run the program" << endl;
        system("wget https://raw.githubusercontent.com/dm117/NBA-terminal/master/schedule.csv");
        cout << termcolor::on_red << "\n\nDownloaded file, re-run the program..." << endl;
	cout << termcolor::reset << endl;
    }

    return 0;
}

void weekConvert(int &tempWeek_, string &pcWeek_)
{
    switch ( tempWeek_ )
    {
    case 0:
        pcWeek_ = "Sun";
        break;
    case 1:
        pcWeek_ = "Mon";
        break;
    case 2:
        pcWeek_ = "Tue";
        break;
    case 3:
        pcWeek_ = "Wed";
        break;
    case 4:
        pcWeek_ = "Thu";
        break;
    case 5:
        pcWeek_ = "Fri";
        break;
    case 6:
        pcWeek_ = "Sat";
        break;
    default:
        cout<<"ERROR GETTING DAY OF THE WEEK\n";
        break;
    }
}

void monthConvert(int &tempMonth_, string &pcMonth_)
{
    switch ( tempMonth_ )
    {
    case 1:
        pcMonth_ = "Jan";
        break;
    case 2:
        pcMonth_ = "Feb";
        break;
    case 3:
        pcMonth_ = "March";
        break;
    case 4:
        pcMonth_ = "Apr";
        break;
    case 5:
        pcMonth_ = "May";
        break;
    case 6:
        pcMonth_ = "Jun";
        break;
    case 7:
        pcMonth_ = "Jul";
        break;
    case 8:
        pcMonth_ = "Aug";
        break;
    case 9:
        pcMonth_ = "Sep";
        break;
    case 10:
        pcMonth_ = "Oct";
        break;
    case 11:
        pcMonth_ = "Nov";
        break;
    case 12:
        pcMonth_ = "Dec";
        break;
    default:
        cout<<"ERROR\n";
        break;
    }
}

void dataInput(ifstream &schedule_, vector<string> &weekDay_, vector<string> &time_, vector<string> &box_, vector<string> &team1_, vector<string> &team1Score_, vector<string> &team2_,
vector<string> &team2Score_, vector<string> &OT_, vector<string> &notes_, string userString_) //gets data from file
{

    getline(schedule_, userString_, ',');
    weekDay_.push_back(userString_);

    getline(schedule_, userString_, ',');
    time_.push_back(userString_);

    getline(schedule_, userString_, ',');
    box_.push_back(userString_);

    getline(schedule_, userString_, ',');
    team1_.push_back(userString_);

    getline(schedule_, userString_, ',');
    team1Score_.push_back(userString_);

    getline(schedule_, userString_, ',');
    team2_.push_back(userString_);

    getline(schedule_, userString_, ',');
    team2Score_.push_back(userString_);

    getline(schedule_, userString_, ',');
    OT_.push_back(userString_);

    getline(schedule_, userString_);
    notes_.push_back(userString_);

}
void outFunction(vector<string> &team1_, vector<int> &placeHolder_, int &two_)
{
	if (team1_[placeHolder_[two_]] == "Miami Heat" || team1_[placeHolder_[two_]] == "Toronto Raptors" || team1_[placeHolder_[two_]] == "Chicago Bulls" || team1_[placeHolder_[two_]] == "Atlanta Hawks" || team1_[placeHolder_[two_]] == "Portland Trail Blazers" || team1_[placeHolder_[two_]] == "Los Angeles Clippers" || team1_[placeHolder_[two_]] == "Houston Rockets")
	{
		cout <<  termcolor::red << setw(30) << left << team1_[placeHolder_[two_]] << setw(5) << " ";//22
	}
	else if (team1_[placeHolder_[two_]] == "New York Knicks" || team1_[placeHolder_[two_]] == "Detroit Pistons" || team1_[placeHolder_[two_]] == "Orlando Magic" || team1_[placeHolder_[two_]] == "Washington Wizards" || team1_[placeHolder_[two_]] == "Oklahoma City Thunder" || team1_[placeHolder_[two_]] == "Utah Jazz" || team1_[placeHolder_[two_]] == "Dallas Mavericks" || team1_[placeHolder_[two_]] == "Memphis Grizzlies")
	{
		cout << termcolor::blue << setw(30) << left << team1_[placeHolder_[two_]] << setw(5) << " ";//22
	}
	else if (team1_[placeHolder_[two_]] == "Boston Celtics" || team1_[placeHolder_[two_]] == "Milwaukee Bucks" || team1_[placeHolder_[two_]] == "Minnesota Timberwolves")
	{
		cout << termcolor::green << setw(30) << left << team1_[placeHolder_[two_]] << setw(5) << " ";//22
	}
	else if (team1_[placeHolder_[two_]] == "Cleveland Cavaliers" || team1_[placeHolder_[two_]] == "Indiana Pacers" || team1_[placeHolder_[two_]] == "Denver Nuggets" || team1_[placeHolder_[two_]] == "Golden State Warriors" || team1_[placeHolder_[two_]] == "Los Angeles Lakers")
	{
		cout << termcolor::yellow << setw(30) << left << team1_[placeHolder_[two_]] << setw(5) << " ";//22
	}
	else if (team1_[placeHolder_[two_]] == "Charlotte Hornets" || team1_[placeHolder_[two_]] == "Sacramento Kings")
	{
		cout << termcolor::magenta << setw(30) << left << team1_[placeHolder_[two_]] << setw(5) << " ";//22
	}
	else if (team1_[placeHolder_[two_]] == "Brooklyn Nets" || team1_[placeHolder_[two_]] == "Philadelphia 76ers" || team1_[placeHolder_[two_]] == "New Orleans Pelicans" || team1_[placeHolder_[two_]] == "San Antonio Spurs")
	{
		cout << termcolor::white << setw(30) << left << team1_[placeHolder_[two_]] << setw(5) << " ";//22
	}

		cout << termcolor::reset;
}

/*--------------------------------------------THIS WILL BE USE LATER TO CHECK IF THE DIRECTORY ALREADY EXISTS------------
struct stat statbuf;
int isDir = 0;
if (stat("/NBAschedule", &statbuf) != -1) {
   if (S_ISDIR(statbuf.st_mode)) {
      isDir = 1;
   }
} else {

       here you might check errno for the reason, ENOENT will mean the path
       was bad, ENOTDIR means part of the path is not a directory, EACCESS
       would mean you can't access the path. Regardless, from the point of
       view of your app, the path is not a directory if stat fails.

}

//Source: https://www.quora.com/How-do-I-check-if-a-directory-exists-in-Linux-using-C++
--------------------------------------------THIS WILL BE USE LATER TO CHECK IF THE DIRECTORY ALREADY EXISTS------------*/

<|endoftext|>


<commit_before>8c95d4dc-ad59-11e7-ba94-ac87a332f658<commit_msg>Fixed that one bug<commit_after>8d3d298a-ad59-11e7-b964-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
#include "getTime.h"

int main()
{
	//Initializes writing and puts in opening message.
	getTime time;
	std::ofstream logger;
	logger.open("logger.txt", std::fstream::app);
	std::string LogStartMessage = "Program Started At: ";
	LogStartMessage.append(time.getCurrentTime());
	logger << LogStartMessage << std::endl;
	logger.close();

	//Variables
	std::string ID;
	std::string writeMessage;
	std::vector <std::string> loggedIn(0);

	std::string message; //Used for std::cin commands

	std::cout << "Loading ClockIN by Anubis Studios..." << std::endl;

	while (true)
	{
		std::cout << "Welcome! Please type in a command:\n" << std::endl;
		std::cout << " 1) Check In" << std::endl;
		std::cout << " 2) Check Out" << std::endl;
		std::cout << " 3) Help" << std::endl;
		std::cout << " 4) Exit" << std::endl;
		std::cout << " ";
		std::cin >> message;

		if (message == "1")
		{
			std::cout << "Please Insert Your ID:" << std::endl;
			std::cin >> message;

			if (message == "CJHERFU")
			{
				if (std::find(loggedIn.begin(), loggedIn.end(), "CJHERFU") != loggedIn.end())
				{
					std::cout << "CJHERFU has already clocked in." << std::endl;
				}
				else
				{
					logger.open("logger.txt", std::fstream::app);
					logger << "CJHERFU clocked in at: " << time.getCurrentTime() << std::endl;
					logger.close();

					loggedIn.push_back("CJHERFU");

					std::cout << "Welcome, Connor Herfurth.  You have been logged in." << std::endl;
				}
			}
			else
			{
				std::cout << "Unrecognized ID. Please start over." << std::endl;
			}
		}
		else if (message == "2")
		{
			std::cout << "Please enter your ID:" << std::endl;
			std::cin >> message;
			if (std::find(loggedIn.begin(), loggedIn.end(), message) != loggedIn.end())
			{
				logger.open("logger.txt", std::fstream::app);
				logger << message << " clocked out at: " << time.getCurrentTime() << std::endl;
				logger.close();

				loggedIn.erase(std::remove(loggedIn.begin(), loggedIn.end(), message), loggedIn.end());

				std::cout << "You have been clocked out and removed." << std::endl;
			}
			else
			{
				std::cout << "You are not clocked in." << std::endl;
			}
		}
		else if (message == "3")
		{
			std::cout << "This program clocks you in and out to calculate how much time" << std::endl;
			std::cout << "you have spent on the job." << std::endl;
			std::cout << "Unregistered Copyright Anubis Studios 2017." << std::endl;
		}
		else if (message == "4")
		{
			return 0;
		}
		else
		{
			std::cout << "Command not recognized.  Please try again." << std::endl;
		}
	}
}<commit_msg>Delete main.cpp<commit_after><|endoftext|>


<commit_before>313264dc-ad5b-11e7-b101-ac87a332f658<commit_msg>I'm done<commit_after>31b7b068-ad5b-11e7-9b1b-ac87a332f658<|endoftext|>


<commit_before>#include "part_data.hpp"
#include "cosmology.hpp"
#include "power.hpp"
#include "displacement.hpp"
#include "read_param.hpp"
#include "thermalvel.hpp"
#include "save.hpp"
#include <cassert>

int main(int argc, char **argv)
{
  if(argc < 2)
    {
	  fprintf(stdout, "\nParameters are missing.\n");
	  fprintf(stdout, "Call with <ParameterFile>\n\n");
      exit(0);
    }
  /*Make sure stdout is line buffered even when not
   * printing to a terminal but, eg, perl*/
  setlinebuf(stdout);
  //May throw std::runtime_error
  try {
  //Read the config file
  SpbConfigParser config(argv[1]);
  //Cosmological parameters
  const auto Omega = config.PopValue<double>("Omega");
  const auto OmegaLambda = config.PopValue<double>("OmegaLambda");
  const auto OmegaBaryon = config.PopValue<double>("OmegaBaryon");
  const auto OmegaDM_2ndSpecies = config.PopValue<double>("OmegaDM_2ndSpecies");
  const auto HubbleParam = config.PopValue<double>("HubbleParam");
  //Which output format should we use. 3 is HDF5, 2 is Gadget 2. Default to 3.
  const auto ICFormat = config.PopValue<int>("ICFormat", 3);
  //How many output files to use in the set
  const auto NumFiles = config.PopValue<int>("NumFiles");
  //Parameters of the simulation box
  const auto Box = config.PopValue<double>("Box");
  const auto Redshift = config.PopValue<double>("Redshift");
  const double InitTime = 1 / (1 + Redshift);
  //Size of FFT
  const size_t Nmesh = config.PopValue<int>("Nmesh");
  //Unused unless CAMB spectrum
  const auto FileWithInputSpectrum = config.PopValue<std::string>("FileWithInputSpectrum");
  const auto FileWithTransfer = config.PopValue<std::string>("FileWithTransfer");
  const auto InputSpectrum_UnitLength_in_cm = config.PopValue<double>("InputSpectrum_UnitLength_in_cm", 3.085678e24);
  //Output filenames
  const auto OutputDir = config.PopValue<std::string>("OutputDir");
  const auto FileBase = config.PopValue<std::string>("FileBase");
  //Random number seed
  const auto Seed = config.PopValue<int>("Seed");
  //Various boolean flags
  const auto ReNormalizeInputSpectrum = config.PopValue<bool>("ReNormalizeInputSpectrum", false);
  const auto RayleighScatter = config.PopValue<bool>("RayleighScatter", true);
  //Power spectrum to use. Default to CAMB
  const auto WhichSpectrum = config.PopValue<int>("WhichSpectrum", 2);
  //Is twolpt on?
  const auto twolpt = config.PopValue<bool>("TWOLPT",true);
  //Unit system
  const auto UnitLength_in_cm = config.PopValue<double>("UnitLength_in_cm", 3.085678e21);
  const auto UnitVelocity_in_cm_per_s = config.PopValue<double>("UnitVelocity_in_cm_per_s", 1e5);
  const auto UnitMass_in_g = config.PopValue<double>("UnitMass_in_g", 1.989e43);
  const double UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s;
  //WDM options
  bool WDM_Vtherm_On = config.PopValue<bool>("WDM_On",false);
  WDM_Vtherm_On = config.PopValue<bool>("WDM_Vtherm_On",false) && WDM_Vtherm_On;
  const auto WDM_PartMass_in_kev = config.PopValue<double>("WDM_PartMass_in_kev", 0);
  //Neutrino options
  //Enable particle neutrinos for type 2 particles. Does nothing unless NU_Vtherm is also true
  bool NU_Vtherm_On = config.PopValue<bool>("NU_On",false);
  //Add thermal velocities to type 2 particles if NU_On is also true.
  NU_Vtherm_On = config.PopValue<bool>("NU_Vtherm_On",false) && NU_Vtherm_On;
  //This triggers the use of neutrinos via an altered transfer function
  //Should be on only if you are faking neutrinos by combining them with the dark matter,
  //and changing the transfer function, which is a terrible way of simulating neutrinos. So leave it off.
  const auto combined_neutrinos = config.PopValue<bool>("NU_KSPACE",false);
  //Changes whether we have two heavy and one light neutrino or one heavy two light.
  const auto InvertedHierarchy = config.PopValue<bool>("InvertedHierarchy",false);
  //Total neutrino mass
  const auto NU_PartMass_in_ev = config.PopValue<double>("NU_PartMass_in_ev",0);
  //Parameter for the Efstathiou power spectrum. Generally does nothing.
  const auto ShapeGamma = config.PopValue<double>("ShapeGamma",0.201);
  //Needed if ReNormaliseInputSpectrum is on. Otherwise unused
  const auto PrimordialIndex = config.PopValue<double>("PrimordialIndex",1.);
  const auto Sigma8 = config.PopValue<double>("Sigma8",0.8);
  //Number of particles desired
  std::valarray<int64_t> npart((int64_t)0,(size_t)N_TYPE);
  int CbRtNpart[6] = {0};
  CbRtNpart[BARYON_TYPE] = config.PopValue<int>("NBaryon", 0);
  CbRtNpart[DM_TYPE] = config.PopValue<int>("NCDM", 0);
  CbRtNpart[NEUTRINO_TYPE] = config.PopValue<int>("NNeutrino", 0);
  for(int type=0; type<N_TYPES; ++type)
      npart[type] = static_cast<int64_t>(CbRtNpart[type])*CbRtNpart[type]*CbRtNpart[type];

  printf("Particle numbers: %ld %ld %ld\n",npart[BARYON_TYPE], npart[DM_TYPE], npart[NEUTRINO_TYPE]);
  assert(npart[BARYON_TYPE] > 0 || npart[DM_TYPE] > 0 || npart[NEUTRINO_TYPE] > 0);

  if (Nmesh % 2 != 0){
    printf("Nmesh must be even or correct output is not guaranteed.\n");
    exit(1);
  }

  std::vector<std::string> unexpected = config.GetRemainingKeys();
  if(unexpected.size() > 0){
    std::cerr<<"Config file contained the following unexpected keys:"<<std::endl;
    for(auto unex: unexpected)
        std::cerr<<unex<<std::endl;
    exit(1);
  }
  DisplacementFields displace(Nmesh, Seed, Box, twolpt);
  /*Set particle numbers*/
  if(npart.sum() == 0)
          exit(1);
  //Initialise a power spectrum
  PowerSpec * PSpec;
  switch(WhichSpectrum)
  {
      case 1:
            PSpec = new PowerSpec_EH(HubbleParam, Omega, OmegaBaryon, UnitLength_in_cm);
            break;
      case 2:
            PSpec = new PowerSpec_Tabulated(FileWithTransfer, FileWithInputSpectrum, Omega, OmegaLambda, OmegaBaryon, OmegaDM_2ndSpecies,InputSpectrum_UnitLength_in_cm, UnitLength_in_cm, !npart[BARYON_TYPE], combined_neutrinos);
            break;
      default:
            PSpec = new PowerSpec_Efstathiou(ShapeGamma, UnitLength_in_cm);
  }

  //Make a cosmology
  Cosmology cosmo(HubbleParam, Omega, OmegaLambda, NU_PartMass_in_ev, InvertedHierarchy);
  //If normalisation or WDM are on, decorate the base power spectrum
  //to do that
  if (ReNormalizeInputSpectrum) {
      PSpec = new NormalizedPowerSpec(PSpec, Sigma8, PrimordialIndex, cosmo.GrowthFactor(InitTime, 1.0), UnitLength_in_cm);
  }
  if(WDM_Vtherm_On)
      PSpec = new WDMPowerSpec(PSpec, WDM_PartMass_in_kev, Omega, OmegaBaryon, HubbleParam, UnitLength_in_cm);

  std::string extension("");
  if (ICFormat > 4 || ICFormat < 2) {
          fprintf(stderr, "Supported ICFormats:\n 2: Gadget 2 format files\n 3: HDF5\n 4: BigFile\n");
          exit(1);
  }
  if (ICFormat == 3){
      printf("Outputting HDF5 ICs\n");
      extension=".hdf5";
  }
#ifdef NEUTRINO_PAIRS
  npart[NEUTRINO_TYPE] *= 2;
#endif //NEUTRINO_PAIRS
  GadgetWriter::GWriteBaseSnap *osnap;
#ifdef HAVE_BGFL
  if(ICFormat == 4) {
     osnap = new GadgetWriter::GWriteBigSnap(OutputDir+std::string("/")+FileBase+extension, npart, NumFiles);
  }
  else
#endif
  osnap = new GadgetWriter::GWriteSnap(OutputDir+std::string("/")+FileBase+extension, npart,NumFiles, sizeof(id_type));
  assert(osnap);
  /*Write headers*/
  gadget_header header = generate_header(npart, Omega, OmegaBaryon, OmegaDM_2ndSpecies, OmegaLambda, HubbleParam, Box, InitTime, UnitMass_in_g, UnitLength_in_cm, UnitVelocity_in_cm_per_s, combined_neutrinos);

  //Generate regular particle grid
  part_grid Pgrid(CbRtNpart, header.mass, Box);

  if(osnap->WriteHeaders(header)) {
      fprintf(stderr, "Could not write headers to snapshot\n");
      exit(1);
  }

  int64_t FirstId=1;
  //Compute the factors to go from velocity to displacement
  const double hubble_a = cosmo.Hubble(InitTime)*UnitTime_in_s;
  const double vel_prefac = InitTime * hubble_a * cosmo.F_Omega(InitTime) /sqrt(InitTime);
  //Only used if twolpt is on
  //This is slightly approximate: we are assuming that D2 ~ -3/7 Da^2 Omega_m^{-1/143} (Bouchet, F 1995, A&A 296)
  const double vel_prefac2 = -3./7.*pow(Omega, -1./143)*InitTime * hubble_a * cosmo.F2_Omega(InitTime) /sqrt(InitTime);
  printf("vel_prefac= %g  hubble_a=%g fom=%g Omega=%g \n", vel_prefac, hubble_a, cosmo.F_Omega(InitTime), Omega);

  for(int type=0; type<N_TYPE;type++){
      if(npart[type] == 0)
              continue;
      FermiDiracVel * therm_vels = NULL;
      //For WDM thermal velocities
      if(WDM_Vtherm_On && type == 1){
        const double wdm_vth = WDM_V0(Redshift, WDM_PartMass_in_kev, Omega-OmegaBaryon, HubbleParam, UnitVelocity_in_cm_per_s);
        therm_vels = new FermiDiracVel (wdm_vth);
        printf("\nWarm dark matter rms velocity dispersion at starting redshift = %g km/sec\n\n",3.59714 * wdm_vth);
      }
#ifdef NEUTRINOS
      //Neutrino thermal velocities
      if(NU_Vtherm_On && type == 2) {
          //Init structure for neutrino velocities
          const double v_th = NU_V0(Redshift, NU_PartMass_in_ev, UnitVelocity_in_cm_per_s);
          therm_vels = new FermiDiracVel (v_th);
          printf("\nNeutrino rms vel. dispersion %g (km/s)\n\n",v_th/sqrt(1+Redshift));
      }
#endif //NEUTRINOS
      lpt_data outdata = displace.displacement_fields(type, Pgrid, PSpec, RayleighScatter);
      outdata.SetVelPrefac(vel_prefac, vel_prefac2);
      try {
      FirstId = write_particle_data(*osnap, type,&outdata, Pgrid, therm_vels, FirstId);
      } catch(std::ios_base::failure& e) {
          std::cerr<<e.what();
          return 4;
      }
      delete therm_vels;
  }

    delete PSpec;
  printf("Initial scale factor = %g\n", InitTime);

  }
  catch(std::runtime_error& e) {
      std::cerr<<e.what();
      return 1;
  }
  catch(std::invalid_argument& e) {
      std::cerr<<e.what();
      return 2;
  }
  catch(std::domain_error& e) {
      std::cerr<<e.what();
      return 3;
  }
  return 0;
}
<commit_msg>Catch all exceptions in the same place<commit_after>#include "part_data.hpp"
#include "cosmology.hpp"
#include "power.hpp"
#include "displacement.hpp"
#include "read_param.hpp"
#include "thermalvel.hpp"
#include "save.hpp"
#include <cassert>

int main(int argc, char **argv)
{
  if(argc < 2)
    {
	  fprintf(stdout, "\nParameters are missing.\n");
	  fprintf(stdout, "Call with <ParameterFile>\n\n");
      exit(0);
    }
  /*Make sure stdout is line buffered even when not
   * printing to a terminal but, eg, perl*/
  setlinebuf(stdout);
  //May throw std::runtime_error
  try {
  //Read the config file
  SpbConfigParser config(argv[1]);
  //Cosmological parameters
  const auto Omega = config.PopValue<double>("Omega");
  const auto OmegaLambda = config.PopValue<double>("OmegaLambda");
  const auto OmegaBaryon = config.PopValue<double>("OmegaBaryon");
  const auto OmegaDM_2ndSpecies = config.PopValue<double>("OmegaDM_2ndSpecies");
  const auto HubbleParam = config.PopValue<double>("HubbleParam");
  //Which output format should we use. 3 is HDF5, 2 is Gadget 2. Default to 3.
  const auto ICFormat = config.PopValue<int>("ICFormat", 3);
  //How many output files to use in the set
  const auto NumFiles = config.PopValue<int>("NumFiles");
  //Parameters of the simulation box
  const auto Box = config.PopValue<double>("Box");
  const auto Redshift = config.PopValue<double>("Redshift");
  const double InitTime = 1 / (1 + Redshift);
  //Size of FFT
  const size_t Nmesh = config.PopValue<int>("Nmesh");
  //Unused unless CAMB spectrum
  const auto FileWithInputSpectrum = config.PopValue<std::string>("FileWithInputSpectrum");
  const auto FileWithTransfer = config.PopValue<std::string>("FileWithTransfer");
  const auto InputSpectrum_UnitLength_in_cm = config.PopValue<double>("InputSpectrum_UnitLength_in_cm", 3.085678e24);
  //Output filenames
  const auto OutputDir = config.PopValue<std::string>("OutputDir");
  const auto FileBase = config.PopValue<std::string>("FileBase");
  //Random number seed
  const auto Seed = config.PopValue<int>("Seed");
  //Various boolean flags
  const auto ReNormalizeInputSpectrum = config.PopValue<bool>("ReNormalizeInputSpectrum", false);
  const auto RayleighScatter = config.PopValue<bool>("RayleighScatter", true);
  //Power spectrum to use. Default to CAMB
  const auto WhichSpectrum = config.PopValue<int>("WhichSpectrum", 2);
  //Is twolpt on?
  const auto twolpt = config.PopValue<bool>("TWOLPT",true);
  //Unit system
  const auto UnitLength_in_cm = config.PopValue<double>("UnitLength_in_cm", 3.085678e21);
  const auto UnitVelocity_in_cm_per_s = config.PopValue<double>("UnitVelocity_in_cm_per_s", 1e5);
  const auto UnitMass_in_g = config.PopValue<double>("UnitMass_in_g", 1.989e43);
  const double UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s;
  //WDM options
  bool WDM_Vtherm_On = config.PopValue<bool>("WDM_On",false);
  WDM_Vtherm_On = config.PopValue<bool>("WDM_Vtherm_On",false) && WDM_Vtherm_On;
  const auto WDM_PartMass_in_kev = config.PopValue<double>("WDM_PartMass_in_kev", 0);
  //Neutrino options
  //Enable particle neutrinos for type 2 particles. Does nothing unless NU_Vtherm is also true
  bool NU_Vtherm_On = config.PopValue<bool>("NU_On",false);
  //Add thermal velocities to type 2 particles if NU_On is also true.
  NU_Vtherm_On = config.PopValue<bool>("NU_Vtherm_On",false) && NU_Vtherm_On;
  //This triggers the use of neutrinos via an altered transfer function
  //Should be on only if you are faking neutrinos by combining them with the dark matter,
  //and changing the transfer function, which is a terrible way of simulating neutrinos. So leave it off.
  const auto combined_neutrinos = config.PopValue<bool>("NU_KSPACE",false);
  //Changes whether we have two heavy and one light neutrino or one heavy two light.
  const auto InvertedHierarchy = config.PopValue<bool>("InvertedHierarchy",false);
  //Total neutrino mass
  const auto NU_PartMass_in_ev = config.PopValue<double>("NU_PartMass_in_ev",0);
  //Parameter for the Efstathiou power spectrum. Generally does nothing.
  const auto ShapeGamma = config.PopValue<double>("ShapeGamma",0.201);
  //Needed if ReNormaliseInputSpectrum is on. Otherwise unused
  const auto PrimordialIndex = config.PopValue<double>("PrimordialIndex",1.);
  const auto Sigma8 = config.PopValue<double>("Sigma8",0.8);
  //Number of particles desired
  std::valarray<int64_t> npart((int64_t)0,(size_t)N_TYPE);
  int CbRtNpart[6] = {0};
  CbRtNpart[BARYON_TYPE] = config.PopValue<int>("NBaryon", 0);
  CbRtNpart[DM_TYPE] = config.PopValue<int>("NCDM", 0);
  CbRtNpart[NEUTRINO_TYPE] = config.PopValue<int>("NNeutrino", 0);
  for(int type=0; type<N_TYPES; ++type)
      npart[type] = static_cast<int64_t>(CbRtNpart[type])*CbRtNpart[type]*CbRtNpart[type];

  printf("Particle numbers: %ld %ld %ld\n",npart[BARYON_TYPE], npart[DM_TYPE], npart[NEUTRINO_TYPE]);
  assert(npart[BARYON_TYPE] > 0 || npart[DM_TYPE] > 0 || npart[NEUTRINO_TYPE] > 0);

  if (Nmesh % 2 != 0){
    printf("Nmesh must be even or correct output is not guaranteed.\n");
    exit(1);
  }

  std::vector<std::string> unexpected = config.GetRemainingKeys();
  if(unexpected.size() > 0){
    std::cerr<<"Config file contained the following unexpected keys:"<<std::endl;
    for(auto unex: unexpected)
        std::cerr<<unex<<std::endl;
    exit(1);
  }
  DisplacementFields displace(Nmesh, Seed, Box, twolpt);
  /*Set particle numbers*/
  if(npart.sum() == 0)
          exit(1);
  //Initialise a power spectrum
  PowerSpec * PSpec;
  switch(WhichSpectrum)
  {
      case 1:
            PSpec = new PowerSpec_EH(HubbleParam, Omega, OmegaBaryon, UnitLength_in_cm);
            break;
      case 2:
            PSpec = new PowerSpec_Tabulated(FileWithTransfer, FileWithInputSpectrum, Omega, OmegaLambda, OmegaBaryon, OmegaDM_2ndSpecies,InputSpectrum_UnitLength_in_cm, UnitLength_in_cm, !npart[BARYON_TYPE], combined_neutrinos);
            break;
      default:
            PSpec = new PowerSpec_Efstathiou(ShapeGamma, UnitLength_in_cm);
  }

  //Make a cosmology
  Cosmology cosmo(HubbleParam, Omega, OmegaLambda, NU_PartMass_in_ev, InvertedHierarchy);
  //If normalisation or WDM are on, decorate the base power spectrum
  //to do that
  if (ReNormalizeInputSpectrum) {
      PSpec = new NormalizedPowerSpec(PSpec, Sigma8, PrimordialIndex, cosmo.GrowthFactor(InitTime, 1.0), UnitLength_in_cm);
  }
  if(WDM_Vtherm_On)
      PSpec = new WDMPowerSpec(PSpec, WDM_PartMass_in_kev, Omega, OmegaBaryon, HubbleParam, UnitLength_in_cm);

  std::string extension("");
  if (ICFormat > 4 || ICFormat < 2) {
          fprintf(stderr, "Supported ICFormats:\n 2: Gadget 2 format files\n 3: HDF5\n 4: BigFile\n");
          exit(1);
  }
  if (ICFormat == 3){
      printf("Outputting HDF5 ICs\n");
      extension=".hdf5";
  }
#ifdef NEUTRINO_PAIRS
  npart[NEUTRINO_TYPE] *= 2;
#endif //NEUTRINO_PAIRS
  GadgetWriter::GWriteBaseSnap *osnap;
#ifdef HAVE_BGFL
  if(ICFormat == 4) {
     osnap = new GadgetWriter::GWriteBigSnap(OutputDir+std::string("/")+FileBase+extension, npart, NumFiles);
  }
  else
#endif
  osnap = new GadgetWriter::GWriteSnap(OutputDir+std::string("/")+FileBase+extension, npart,NumFiles, sizeof(id_type));
  assert(osnap);
  /*Write headers*/
  gadget_header header = generate_header(npart, Omega, OmegaBaryon, OmegaDM_2ndSpecies, OmegaLambda, HubbleParam, Box, InitTime, UnitMass_in_g, UnitLength_in_cm, UnitVelocity_in_cm_per_s, combined_neutrinos);

  //Generate regular particle grid
  part_grid Pgrid(CbRtNpart, header.mass, Box);

  if(osnap->WriteHeaders(header)) {
      fprintf(stderr, "Could not write headers to snapshot\n");
      exit(1);
  }

  int64_t FirstId=1;
  //Compute the factors to go from velocity to displacement
  const double hubble_a = cosmo.Hubble(InitTime)*UnitTime_in_s;
  const double vel_prefac = InitTime * hubble_a * cosmo.F_Omega(InitTime) /sqrt(InitTime);
  //Only used if twolpt is on
  //This is slightly approximate: we are assuming that D2 ~ -3/7 Da^2 Omega_m^{-1/143} (Bouchet, F 1995, A&A 296)
  const double vel_prefac2 = -3./7.*pow(Omega, -1./143)*InitTime * hubble_a * cosmo.F2_Omega(InitTime) /sqrt(InitTime);
  printf("vel_prefac= %g  hubble_a=%g fom=%g Omega=%g \n", vel_prefac, hubble_a, cosmo.F_Omega(InitTime), Omega);

  for(int type=0; type<N_TYPE;type++){
      if(npart[type] == 0)
              continue;
      FermiDiracVel * therm_vels = NULL;
      //For WDM thermal velocities
      if(WDM_Vtherm_On && type == 1){
        const double wdm_vth = WDM_V0(Redshift, WDM_PartMass_in_kev, Omega-OmegaBaryon, HubbleParam, UnitVelocity_in_cm_per_s);
        therm_vels = new FermiDiracVel (wdm_vth);
        printf("\nWarm dark matter rms velocity dispersion at starting redshift = %g km/sec\n\n",3.59714 * wdm_vth);
      }
#ifdef NEUTRINOS
      //Neutrino thermal velocities
      if(NU_Vtherm_On && type == 2) {
          //Init structure for neutrino velocities
          const double v_th = NU_V0(Redshift, NU_PartMass_in_ev, UnitVelocity_in_cm_per_s);
          therm_vels = new FermiDiracVel (v_th);
          printf("\nNeutrino rms vel. dispersion %g (km/s)\n\n",v_th/sqrt(1+Redshift));
      }
#endif //NEUTRINOS
      lpt_data outdata = displace.displacement_fields(type, Pgrid, PSpec, RayleighScatter);
      outdata.SetVelPrefac(vel_prefac, vel_prefac2);
      FirstId = write_particle_data(*osnap, type,&outdata, Pgrid, therm_vels, FirstId);
      delete therm_vels;
  }

    delete PSpec;
  printf("Initial scale factor = %g\n", InitTime);

  }
  catch(std::ios_base::failure& e) {
      std::cerr<<e.what();
      return 4;
  }
  catch(std::runtime_error& e) {
      std::cerr<<e.what();
      return 1;
  }
  catch(std::invalid_argument& e) {
      std::cerr<<e.what();
      return 2;
  }
  catch(std::domain_error& e) {
      std::cerr<<e.what();
      return 3;
  }
  return 0;
}
<|endoftext|>


<commit_before>90965257-ad5b-11e7-b26d-ac87a332f658<commit_msg>#BUG723 uncommitted code found on my computer Monday morning<commit_after>9107e8b3-ad5b-11e7-8c5f-ac87a332f658<|endoftext|>


<commit_before>//
// Created by alex on 4/12/16.
//
#include <iostream>

#include "Game.h"
#include "GameState.h"

constexpr unsigned int winWidth{800}, winHeight{600};

int main()
{
    std::cout << "Hello World" << std::endl;

    Game game;

    sf::Clock clock;

    sf::RenderWindow window{{winWidth, winHeight}, "Legend"};
    window.setFramerateLimit(60);

    while(window.isOpen())
    {
        sf::Time elapsed{clock.restart()};
        float dt{elapsed.asSeconds()};

        if(game.peekState())
        {
            continue;
        }

        game.peekState()->handleInput();
        game.peekState()->update(dt);

        window.clear(sf::Color::Black);

        game.peekState()->draw(dt);

        window.display();
    }

    return 0;
}<commit_msg>added reference to guide<commit_after>//
// Created by alex on 4/12/16.
//
#include <iostream>

#include "Game.h"
#include "GameState.h"

constexpr unsigned int winWidth{800}, winHeight{600};

// Mainly following this guide
// https://www.binpress.com/tutorial/creating-a-city-building-game-with-sfml/137
int main()
{
    std::cout << "Hello World" << std::endl;

    Game game;

    sf::Clock clock;

    sf::RenderWindow window{{winWidth, winHeight}, "Legend"};
    window.setFramerateLimit(60);

    while(window.isOpen())
    {
        sf::Time elapsed{clock.restart()};
        float dt{elapsed.asSeconds()};

        if(game.peekState())
        {
            continue;
        }

        game.peekState()->handleInput();
        game.peekState()->update(dt);

        window.clear(sf::Color::Black);

        game.peekState()->draw(dt);

        window.display();
    }

    return 0;
}<|endoftext|>


<commit_before>0b04e700-2748-11e6-88e4-e0f84713e7b8<commit_msg>No longer crashes if X<commit_after>0b1380dc-2748-11e6-ad17-e0f84713e7b8<|endoftext|>


<commit_before>638179a6-2749-11e6-bd01-e0f84713e7b8<commit_msg>No longer crashes if X<commit_after>638f439e-2749-11e6-bbaa-e0f84713e7b8<|endoftext|>