<commit_before>/**
* Assimp2XML3D
*
* Copyright (c)2015, Christian Schlinkmann
*
*
**/

#include <assimp/version.h>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <assimp/Importer.hpp>
#include <assimp/Exporter.hpp>

#include <iostream>

extern Assimp::Exporter::ExportFormatEntry Assimp2XML3D_desc;

int invalidUsageExit() {
	std::cout << "usage: assimp2xml3d [FLAGS] inputFile [outputFile]" << std::endl;
	return -1;
}

int main(int argc, char *argv[]) {
	if (argc < 3) {
		return invalidUsageExit();
	}

	const char* input = argv[1], *output = argv[2];

	Assimp::Importer importer;
	importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true);

	const aiScene* const scene = importer.ReadFile(input, aiProcessPreset_TargetRealtime_MaxQuality);

	if (!scene) {
		std::cerr << "Assimp: Could not read file " << input << std::endl;
		return -1;
	}

	std::cout << "Assimp read file successfully";

	Assimp::Exporter exporter;
	exporter.RegisterExporter(Assimp2XML3D_desc);
	exporter.Export(scene, "xml", output);
}
<commit_msg>Assimp should filter out points and lines until support for them is added<commit_after>/**
* Assimp2XML3D
*
* Copyright (c)2015, Christian Schlinkmann
*
*
**/

#include <assimp/version.h>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <assimp/Importer.hpp>
#include <assimp/Exporter.hpp>

#include <iostream>

extern Assimp::Exporter::ExportFormatEntry Assimp2XML3D_desc;

int invalidUsageExit() {
	std::cout << "usage: assimp2xml3d [FLAGS] inputFile [outputFile]" << std::endl;
	return -1;
}

int main(int argc, char *argv[]) {
	if (argc < 3) {
		return invalidUsageExit();
	}

	const char* input = argv[1], *output = argv[2];

	Assimp::Importer importer;
	importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true);
	importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_POINT | aiPrimitiveType_LINE);

	const aiScene* const scene = importer.ReadFile(input, aiProcessPreset_TargetRealtime_MaxQuality);

	if (!scene) {
		std::cerr << "Assimp: Could not read file " << input << std::endl;
		return -1;
	}

	std::cout << "Assimp read file successfully";

	Assimp::Exporter exporter;
	exporter.RegisterExporter(Assimp2XML3D_desc);
	exporter.Export(scene, "xml", output);
}
<|endoftext|>


<commit_before>#include "parse_git_st.h"
#include "git_committer.h"
#include "exceptions.h"
#include <ncurses.h>
#include <menu.h>
#include <iostream>
#include <sstream>

using namespace std;

MENU* init_all_files_menu(GitStatusParser* git_status_parser, WINDOW* window) {
    vector<string*>* new_files = git_status_parser->getNewFiles();
    vector<string*>* modified_files = git_status_parser->getModifiedFiles();
    vector<string*>* untracked_files = git_status_parser->getUntrackedFiles();
    int total_files = new_files->size() + modified_files->size() + untracked_files->size();

    ITEM** items = new ITEM*[total_files  + 1]; //need 1 more space for null entry (end of menu)
    int index = 0;
    for (int i = 0; i < new_files->size(); i++, index++) {
            items[index] = new_item((new_files->at(i))->c_str(), "(new)");
    }
    for (int i = 0; i < modified_files->size(); i++, index++) {
            items[index] = new_item((modified_files->at(i))->c_str(), "(modified)");
    }
    for (int i = 0; i < untracked_files->size(); i++, index++) {
            items[index] = new_item((untracked_files->at(i))->c_str(), "(untracked)");
    }
    items[index] = 0;
    MENU* menu = new_menu(items);
    set_menu_win(menu, window);
    menu_opts_off(menu, O_ONEVALUE);
    return menu;
}

string* menu_item_to_string(ITEM* item) {
    const char* name = item->name.str;
    return new string(name);
}

bool is_selected_any_file(MENU* menu) {
    ITEM** items = menu_items(menu);
    int count = item_count(menu);
    for (int i = 0; i < count; i++) {
        if (item_value(items[i]) == TRUE) {
            return true;
        }
    }
}

void add_selected_files(MENU* menu, GitCommitter* git_committer) {
    ITEM** items = menu_items(menu);
    int count = item_count(menu);
    for (int i = 0; i < count; i++) {
        if (item_value(items[i]) == TRUE) {
            string* filename = menu_item_to_string(items[i]);
            git_committer->addFile(filename);
        }
    }
}

void draw_title_line() {
    const char* title = "GIT EASY COMMIT";
    int x, y;
    attron(COLOR_PAIR(3) | A_REVERSE | A_BOLD);
    getmaxyx(stdscr, y, x);
    for (int i = 0; i < x; i++) {
        mvaddch(0, i, ' ');
    }
    mvprintw(0, (x / 2) - (strlen(title) / 2), title);
    attroff(A_REVERSE | A_BOLD);
}

void draw_help() {
    attron(COLOR_PAIR(1));
    mvprintw(1, 1, "<up>, k - navigate up, <down>, j - navigate down");;
    mvprintw(2, 1, "<space> - select/deselect file, c - commit selected file(s)");
    mvprintw(3, 1, "<esc>, q - quit");
    attron(A_BOLD);
    mvprintw(5, 1, "All files");
    attroff(A_BOLD);
}

// Global variables
WINDOW* menu_window;
MENU* files_menu;
GitStatusParser git_st_parser;
GitCommitter git_committer;
bool terminated = false;

void init_git_parser() {
    try {
        git_st_parser.parse();
    } catch (NotAGitRepositoryException e) {
        cerr << "Missing git repository! Use git-ec in the git repository or any of it's subdirectories." << endl;
        cerr.flush();
        exit(1);
    }
}

void init_curses() {
    initscr();
    keypad(stdscr, TRUE);
    start_color();
    noecho();
    curs_set(0);
    init_pair(1, COLOR_WHITE, COLOR_BLACK);
    init_pair(2, COLOR_CYAN, COLOR_BLACK);
    init_pair(3, COLOR_GREEN, COLOR_BLACK);
}

void init_menu_window() {
    int rows, cols;
    int menu_y = 6;
    getmaxyx(stdscr, rows, cols);
    int menu_height = (rows - menu_y) - 2;
    if (menu_height < 2) {
        menu_height = 2;
    }
    menu_window = newwin(menu_height, cols, 6, 0);
    files_menu = init_all_files_menu(&git_st_parser, menu_window);
    set_menu_format(files_menu, menu_height, 1);
    set_menu_fore(files_menu, COLOR_PAIR(2) | A_REVERSE | A_BOLD);
    set_menu_grey(files_menu, COLOR_PAIR(1) | A_REVERSE | A_BOLD);
    post_menu(files_menu);
    refresh();
    wrefresh(menu_window);
}

void cleanup() {
    if (files_menu) {
        free_menu(files_menu);
    }
    endwin();
}

//TODO add ctrl-c handling (cleanup)
int main(int argc, char** argv) {
    init_git_parser();
    init_curses();
    init_menu_window();

    draw_title_line();
    draw_help();

    bool done = false;
    int key = 0;

    do {
        key = getch();
        switch (key) {
            case KEY_DOWN:
            case 'j':
                menu_driver(files_menu, REQ_DOWN_ITEM);
                break;

            case KEY_UP:
            case 'k':
                menu_driver(files_menu, REQ_UP_ITEM);
                break;

            case KEY_PPAGE:
                menu_driver(files_menu, REQ_SCR_UPAGE);
                break;

            case KEY_NPAGE:
                menu_driver(files_menu, REQ_SCR_DPAGE);
                break;

            case ' ':
                menu_driver(files_menu, REQ_TOGGLE_ITEM);
                break;

            case 'c':
                if (is_selected_any_file(files_menu)) {
                    add_selected_files(files_menu, &git_committer);
                    free_menu(files_menu);
                    endwin();
                    git_committer.commit();
                    return 0;
                }
                break;

            case 'q':
            case 27: //ESC
                done = true;
                break;
        }
        wrefresh(menu_window);
        refresh();
    } while (!done);
    free_menu(files_menu);
    endwin();
    return 0;
}

<commit_msg>Add basic SIGINT handler with cleanup method.<commit_after>#include "parse_git_st.h"
#include "git_committer.h"
#include "exceptions.h"
#include <ncurses.h>
#include <menu.h>
#include <iostream>
#include <sstream>

using namespace std;

MENU* init_all_files_menu(GitStatusParser* git_status_parser, WINDOW* window) {
    vector<string*>* new_files = git_status_parser->getNewFiles();
    vector<string*>* modified_files = git_status_parser->getModifiedFiles();
    vector<string*>* untracked_files = git_status_parser->getUntrackedFiles();
    int total_files = new_files->size() + modified_files->size() + untracked_files->size();

    ITEM** items = new ITEM*[total_files  + 1]; //need 1 more space for null entry (end of menu)
    int index = 0;
    for (int i = 0; i < new_files->size(); i++, index++) {
            items[index] = new_item((new_files->at(i))->c_str(), "(new)");
    }
    for (int i = 0; i < modified_files->size(); i++, index++) {
            items[index] = new_item((modified_files->at(i))->c_str(), "(modified)");
    }
    for (int i = 0; i < untracked_files->size(); i++, index++) {
            items[index] = new_item((untracked_files->at(i))->c_str(), "(untracked)");
    }
    items[index] = 0;
    MENU* menu = new_menu(items);
    set_menu_win(menu, window);
    menu_opts_off(menu, O_ONEVALUE);
    return menu;
}

string* menu_item_to_string(ITEM* item) {
    const char* name = item->name.str;
    return new string(name);
}

bool is_selected_any_file(MENU* menu) {
    ITEM** items = menu_items(menu);
    int count = item_count(menu);
    for (int i = 0; i < count; i++) {
        if (item_value(items[i]) == TRUE) {
            return true;
        }
    }
}

void add_selected_files(MENU* menu, GitCommitter* git_committer) {
    ITEM** items = menu_items(menu);
    int count = item_count(menu);
    for (int i = 0; i < count; i++) {
        if (item_value(items[i]) == TRUE) {
            string* filename = menu_item_to_string(items[i]);
            git_committer->addFile(filename);
        }
    }
}

void draw_title_line() {
    const char* title = "GIT EASY COMMIT";
    int x, y;
    attron(COLOR_PAIR(3) | A_REVERSE | A_BOLD);
    getmaxyx(stdscr, y, x);
    for (int i = 0; i < x; i++) {
        mvaddch(0, i, ' ');
    }
    mvprintw(0, (x / 2) - (strlen(title) / 2), title);
    attroff(A_REVERSE | A_BOLD);
}

void draw_help() {
    attron(COLOR_PAIR(1));
    mvprintw(1, 1, "<up>, k - navigate up, <down>, j - navigate down");;
    mvprintw(2, 1, "<space> - select/deselect file, c - commit selected file(s)");
    mvprintw(3, 1, "<esc>, q - quit");
    attron(A_BOLD);
    mvprintw(5, 1, "All files");
    attroff(A_BOLD);
}

// Global variables
WINDOW* menu_window;
MENU* files_menu;
GitStatusParser git_st_parser;
GitCommitter git_committer;

void init_git_parser() {
    try {
        git_st_parser.parse();
    } catch (NotAGitRepositoryException e) {
        cerr << "Missing git repository! Use git-ec in the git repository or any of it's subdirectories." << endl;
        cerr.flush();
        exit(1);
    }
}

void init_curses() {
    initscr();
    keypad(stdscr, TRUE);
    start_color();
    noecho();
    curs_set(0);
    init_pair(1, COLOR_WHITE, COLOR_BLACK);
    init_pair(2, COLOR_CYAN, COLOR_BLACK);
    init_pair(3, COLOR_GREEN, COLOR_BLACK);
}

void init_menu_window() {
    int rows, cols;
    int menu_y = 6;
    getmaxyx(stdscr, rows, cols);
    int menu_height = (rows - menu_y) - 2;
    if (menu_height < 2) {
        menu_height = 2;
    }
    menu_window = newwin(menu_height, cols, 6, 0);
    files_menu = init_all_files_menu(&git_st_parser, menu_window);
    set_menu_format(files_menu, menu_height, 1);
    set_menu_fore(files_menu, COLOR_PAIR(2) | A_REVERSE | A_BOLD);
    set_menu_grey(files_menu, COLOR_PAIR(1) | A_REVERSE | A_BOLD);
    post_menu(files_menu);
    refresh();
    wrefresh(menu_window);
}

void cleanup() {
    if (files_menu) {
        free_menu(files_menu);
    }
    endwin();
}

void handle_sigint(int params) {
    cleanup();
    exit(1);
}

//TODO add ctrl-c handling (cleanup)
int main(int argc, char** argv) {
    init_git_parser();
    init_curses();
    init_menu_window();

    draw_title_line();
    draw_help();

    signal(SIGINT, handle_sigint);

    bool done = false;
    int key = 0;

    do {
        key = getch();
        switch (key) {
            case KEY_DOWN:
            case 'j':
                menu_driver(files_menu, REQ_DOWN_ITEM);
                break;

            case KEY_UP:
            case 'k':
                menu_driver(files_menu, REQ_UP_ITEM);
                break;

            case KEY_PPAGE:
                menu_driver(files_menu, REQ_SCR_UPAGE);
                break;

            case KEY_NPAGE:
                menu_driver(files_menu, REQ_SCR_DPAGE);
                break;

            case ' ':
                menu_driver(files_menu, REQ_TOGGLE_ITEM);
                break;

            case 'c':
                if (is_selected_any_file(files_menu)) {
                    add_selected_files(files_menu, &git_committer);
                    cleanup();
                    git_committer.commit();
                    return 0;
                }
                break;

            case 'q':
            case 27: //ESC
                done = true;
                break;
        }
        wrefresh(menu_window);
        refresh();
    } while (!done);
    cleanup();
    return 0;
}

<|endoftext|>


<commit_before>#include	<iostream>
#include	<SDL.h>
#include	"../vbam/gba/GBA.h"
#include	"../vbam/gba/Globals.h"
#include	"../vbam/gba/armdis.h"
#include	"../vbam/sdl/SDLGlobals.h"
#include        "../vbam/sdl/debugger.h"
#include	"Data.hh"
#include	"Script.hh"
#include	"ThumbDisas.hh"
#include	"PrintUtils.hh"
#include	"Bot.hh"
#include        "VM.hh"
#include        "Lua.hh"
#include        "Config.hh"

extern Lua      L;

void		doLoop()
{
  Data		&data = *Data::data;
  int		step = 0;

  while (emulating)
    {
      if (paused)
        {
          L.doREPL();
          paused = false;
        }
      L.doFunc("onEnterFrame");
      if (++step < 900)
	{
	  sdlSetButton(KEY_BUTTON_AUTO_A, step < 899);
	  sdlSetButton(KEY_BUTTON_SPEED, step < 899);
	}
      else
	{
	  data.update();
          Bot::bot.update();
	  if (step == 900)
            {
              VM::vm->update();
              L.doFunc("onInit");
            }
	  if (step % Config::getNumber("refreshRate") == 0)
	    {
              if (Config::getNumber("clearOnRefresh"))
                printf("\033[2J\033[0;0H");
	      printTeam(data);
	      printMap(data);
              L.doFunc("onRefresh");
	    }
	}

      emulator.emuMain(emulator.emuCount);
      sdlPollEvents(data, Bot::bot);
    }
}

int		main(int ac, char **av)
{
  if (ac < 2)
    {
      std::cerr << "Usage: ./pokebot <Pokemon_FireRed.gba>" << std::endl;
      return (1);
    }
  initVBAM(ac, av);
  // Break when script engine PC is modified
  debuggerDoString("bpw 03000EB8 4");
  Data::data = new Data();
  VM::vm = new VM();
  L.init();
  doLoop();
  destroyVBAM();
  return (0);
}
<commit_msg>add rom validity check for Firered US V1.0<commit_after>#include	<iostream>
#include	<SDL.h>
#include	"../vbam/gba/GBA.h"
#include	"../vbam/gba/Globals.h"
#include	"../vbam/gba/armdis.h"
#include	"../vbam/sdl/SDLGlobals.h"
#include        "../vbam/sdl/debugger.h"
#include	"Data.hh"
#include	"Script.hh"
#include	"ThumbDisas.hh"
#include	"PrintUtils.hh"
#include	"Bot.hh"
#include        "VM.hh"
#include        "Lua.hh"
#include        "Config.hh"

extern Lua      L;

void		doLoop()
{
  Data		&data = *Data::data;
  int		step = 0;

  while (emulating)
    {
      if (paused)
        {
          L.doREPL();
          paused = false;
        }
      L.doFunc("onEnterFrame");
      if (++step < 900)
        {
          sdlSetButton(KEY_BUTTON_AUTO_A, step < 899);
          sdlSetButton(KEY_BUTTON_SPEED, step < 899);
        }
      else
        {
          data.update();
          Bot::bot.update();
          if (step == 900)
            {
              VM::vm->update();
              L.doFunc("onInit");
            }
          if (step % Config::getNumber("refreshRate") == 0)
            {
              if (Config::getNumber("clearOnRefresh"))
                printf("\033[2J\033[0;0H");
              printTeam(data);
              printMap(data);
              L.doFunc("onRefresh");
            }
        }

      emulator.emuMain(emulator.emuCount);
      sdlPollEvents(data, Bot::bot);
    }
}

static bool     isROMValid()
{
  const char *err = NULL;

  if (strncmp(gbaPtr<char *>(0x080000A0), "POKEMON FIRE", 12))
    err = "the loaded game is not Pokemon FireRed";
  else if (strncmp(gbaPtr<char *>(0x080000AC), "BPRE", 4))
    err = "the loaded game is not the english version";
  else if (gbaMem<uint8_t>(0x080000BC) != 0x00)
    err = "the game version is not V1.0";

  if (err)
    fprintf(stderr, "Error: %s. Check Readme.md to see what the right rom is\n", err);
  return !err;
}

int		main(int ac, char **av)
{
  if (ac < 2)
    {
      std::cerr << "Usage: ./pokebot <Pokemon_FireRed.gba>" << std::endl;
      return (1);
    }
  initVBAM(ac, av);

  if (isROMValid())
    {
      // Break when script engine PC is modified
      debuggerDoString("bpw 03000EB8 4");
      Data::data = new Data();
      VM::vm = new VM();
      L.init();
      doLoop();
    }
  destroyVBAM();
  return (0);
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <signal.h>
#include <poll.h>
#include <unistd.h>
#include <sys/eventfd.h>
#include <sys/timerfd.h>

#include <string>

#include "SystemRecorder.hpp"
#include "SystemMonitor.hpp"

#define SIZEOF_ARRAY(array) (sizeof(array)/sizeof(array[0]))

static struct Context {
	bool stop;
	int stopfd;
	int timer;
	int durationTimer;

	Context()
	{
		stop = false;
		stopfd = -1;
		timer = -1;
		durationTimer = -1;
	}
} ctx;

struct Params {
	bool help;
	std::string output;
	int period;
	int duration;
	int recordThreads;

	Params()
	{
		help = false;
		period = 1;
		duration = -1;
		recordThreads = true;
	}
};

static int readDecimalParam(int *out_v, const char *name)
{
	char *end;
	long int v;

	errno = 0;
	v = strtol(optarg, &end, 10);
	if (errno != 0) {
		int ret = -errno;
		printf("Unable to parse '%s' %s : %d(%m)\n",
		       name, optarg, errno);
		return ret;
	} else if (*end != '\0') {
		printf("'%s' arg '%s' is not decimal\n",
		        name, optarg);
		return -EINVAL;
	} else if (v <= 0) {
		printf("'%s' arg '%s' is negative or null\n",
		       name, optarg);
		return -EINVAL;
	}

	*out_v = v;

	return 0;
}

int parseArgs(int argc, char *argv[], Params *params)
{
	int optionIndex = 0;
	int value;
	int ret;

	const struct option argsOptions[] = {
		{ "help"  ,          optional_argument, 0, 'h' },
		{ "period",          optional_argument, 0, 'p' },
		{ "duration",        optional_argument, 0, 'd' },
		{ "output",          required_argument, 0, 'o' },
		{ "disable-threads", optional_argument, &params->recordThreads, 0 },
		{ 0, 0, 0}
	};

	while (true) {
		value = getopt_long(argc, argv, "ho:p:d:", argsOptions, &optionIndex);
		if (value == -1 || value == '?')
			break;

		switch (value) {
		case 'h':
			params->help = true;
			break;

		case 'o':
			params->output = optarg;
			break;

		case 'd':
			ret = readDecimalParam(&params->duration, "duration");
			if (ret < 0)
				return ret;
			break;

		case 'p':
			ret = readDecimalParam(&params->period, "period");
			if (ret < 0)
				return ret;
			break;

		default:
			break;
		}
	}

	return 0;
}

void printUsage(int argc, char *argv[])
{
	printf("Usage  %s [-h] [-p PERIOD] -o OUTPUT process [process ...]\n",
	       argv[0]);

	printf("\n");

	printf("positional arguments:\n");
	printf("  %-20s %s\n", "process", "Process name to monitor");

	printf("\n");

	printf("optional arguments:\n");
	printf("  %-20s %s\n", "-h, --help", "show this help message and exit");
	printf("  %-20s %s\n", "-p, --period", "sample acquisition period (seconds). Default : 1");
	printf("  %-20s %s\n", "-d, --duration", "acquisition duration (seconds). Default : infinite");
	printf("  %-20s %s\n", "-o, --output", "output record file");
	printf("  %-20s %s\n", "--disable-threads", "disable threads recording");
}

static void sighandler(int s)
{
	int64_t stop = 1;
	int ret;

	printf("stop\n");
	ctx.stop = true;
	ret = write(ctx.stopfd, &stop, sizeof(stop));
	if (ret < 0)
		printf("write() failed : %d(%m)\n", errno);
}

static void systemStatsCb(
		const SystemMonitor::SystemStats &stats,
		void *userdata)
{
	SystemRecorder *recorder = (SystemRecorder *) userdata;
	int ret;

	ret = recorder->record(stats);
	if (ret < 0)
		printf("record() failed : %d(%s)\n", -ret, strerror(-ret));
}

static void processStatsCb(
		const SystemMonitor::ProcessStats &stats,
		void *userdata)
{
	SystemRecorder *recorder = (SystemRecorder *) userdata;
	int ret;

	ret = recorder->record(stats);
	if (ret < 0)
		printf("record() failed : %d(%s)\n", -ret, strerror(-ret));
}

static void threadStatsCb(
		const SystemMonitor::ThreadStats &stats,
		void *userdata)
{
	SystemRecorder *recorder = (SystemRecorder *) userdata;
	int ret;

	ret = recorder->record(stats);
	if (ret < 0)
		printf("record() failed : %d(%s)\n", -ret, strerror(-ret));
}

static void acquisitionDurationCb(
		const SystemMonitor::AcquisitionDuration &stats,
		void *userdata)
{
	SystemRecorder *recorder = (SystemRecorder *) userdata;
	int ret;

	ret = recorder->record(stats);
	if (ret < 0)
		printf("record() failed : %d(%s)\n", -ret, strerror(-ret));
}

static void buildProgParameters(int argc, char *argv[], ProgramParameters *out)
{
	std::string s;

	s = argv[0];

	for (int i = 1; i < argc; i++)
		s += std::string(" ") + std::string(argv[i]);

	snprintf(out->mParams, sizeof(out->mParams), "%s", s.c_str());
}

int main(int argc, char *argv[])
{
	struct itimerspec timer;
	struct pollfd fds[3];
	int fdsCount;
	Params params;
	ProgramParameters progParameters;
	SystemMonitor::SystemConfig systemConfig;
	SystemMonitor::Callbacks cb;
	SystemMonitor *mon = nullptr;
	SystemMonitor::Config monConfig;
	SystemRecorder *recorder = nullptr;
	int ret;

	signal(SIGINT, sighandler);

	// Parse parameters
	if (argc == 1) {
		printUsage(argc, argv);
		return 0;
	}

	ret = parseArgs(argc, argv, &params);
	if (ret < 0) {
		printUsage(argc, argv);
		return 1;
	} else if (params.output.empty()) {
		printf("No output file specified\n\n");
		printUsage(argc, argv);
		return 1;
	} else if (optind == argc) {
		printf("No process name specified\n\n");
		printUsage(argc, argv);
		return 1;
	}

	// Create recorder
	recorder = SystemRecorder::create();
	if (!recorder)
		goto error;

	ret = recorder->open(params.output.c_str());
	if (ret < 0)
		goto error;

	// Create monitor
	cb.mSystemStats = systemStatsCb;
	cb.mProcessStats = processStatsCb;
	cb.mThreadStats = threadStatsCb;
	cb.mAcquisitionDuration = acquisitionDurationCb;
	cb.mUserdata = recorder;

	monConfig.mRecordThreads = params.recordThreads;

	mon = SystemMonitor::create(monConfig, cb);
	if (!mon)
		goto error;

	for (int i = optind; i < argc; i++) {
		ret = mon->addProcess(argv[i]);
		if (ret < 0) {
			printf("addProcessFailed() : %d(%s)\n", -ret, strerror(-ret));
			goto error;
		}

	}

	mon->loadProcesses();

	// Write program parameters
	buildProgParameters(argc, argv, &progParameters);
	recorder->record(progParameters);

	// Write system config
	ret = mon->readSystemConfig(&systemConfig);
	if (ret < 0) {
		printf("readSystemConfig() failed : %d(%m)\n", errno);
		goto error;
	}

	recorder->record(systemConfig);

	// Create stopfd
	ret = eventfd(0, EFD_CLOEXEC);
	if (ret < 0) {
		printf("eventfd() failed : %d(%m)\n", errno);
		goto error;
	}

	ctx.stopfd = ret;

	fds[0].fd = ctx.stopfd;
	fds[0].events = POLLIN;
	fds[0].revents = 0;

	// Create timer
	ret = timerfd_create(CLOCK_MONOTONIC, EFD_CLOEXEC);
	if (ret < 0) {
		printf("timerfd_create() failed : %d(%m)\n", errno);
		goto error;
	}

	ctx.timer = ret;

	// Start timer
	timer.it_interval.tv_sec = params.period;
	timer.it_interval.tv_nsec = 0;

	timer.it_value.tv_sec = params.period;
	timer.it_value.tv_nsec = 0;

	ret = timerfd_settime(ctx.timer, 0, &timer, NULL);
	if (ret < 0) {
		printf("timerfd_settime() failed : %d(%m)\n", errno);
		goto error;
	}

	fds[1].fd = ctx.timer;
	fds[1].events = POLLIN;
	fds[1].revents = 0;

	fdsCount = 2;

	// Create duration timer
	if (params.duration > 0) {
		ret = timerfd_create(CLOCK_MONOTONIC, EFD_CLOEXEC);
		if (ret < 0) {
			printf("timerfd_create() failed : %d(%m)\n", errno);
			goto error;
		}

		ctx.durationTimer = ret;

		// Start timer
		timer.it_value.tv_sec = params.duration;
		timer.it_value.tv_nsec = 0;

		timer.it_interval.tv_sec = 0;
		timer.it_interval.tv_nsec = 0;

		ret = timerfd_settime(ctx.durationTimer, 0, &timer, NULL);
		if (ret < 0) {
			printf("timerfd_settime() failed : %d(%m)\n", errno);
			goto error;
		}

		fds[2].fd = ctx.durationTimer;
		fds[2].events = POLLIN;
		fds[2].revents = 0;

		fdsCount++;
	} else {
		fds[2].fd = -1;
		fds[2].events = 0;
		fds[2].revents = 0;
	}

	// Start poll
	while (true) {
		do {
			ret = poll(fds, fdsCount, -1);
		} while (ret == -1 && errno == EINTR);

		if (ret == -1) {
			printf("poll() failed : %d(%m)\n", errno);
			goto error;
		} else if (ret == 0) {
			printf("poll() : timeout\n");
			continue;
		}

		if (ctx.stop)
			break;

		if (fds[1].revents & POLLIN) {
			uint64_t expirations;

			mon->process();

			ret = read(fds[1].fd, &expirations, sizeof(expirations));
			if (ret < 0)
				printf("read() failed : %d(%m)\n", errno);
		}

		if (fds[2].revents & POLLIN)
			break;
	}

	recorder->close();

	delete mon;
	delete recorder;

	if (ctx.stopfd != -1)
		close(ctx.stopfd);

	if (ctx.timer != -1)
		close(ctx.timer);

	return 0;

error:
	delete mon;
	delete recorder;

	if (ctx.stopfd != -1)
		close(ctx.stopfd);

	if (ctx.timer != -1)
		close(ctx.timer);

	return 1;
}
<commit_msg>Introduce output filename rotation<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <signal.h>
#include <poll.h>
#include <unistd.h>
#include <sys/eventfd.h>
#include <sys/timerfd.h>
#include <sys/stat.h>

#include <string>

#include "SystemRecorder.hpp"
#include "SystemMonitor.hpp"

#define SIZEOF_ARRAY(array) (sizeof(array)/sizeof(array[0]))

static struct Context {
	bool stop;
	int stopfd;
	int timer;
	int durationTimer;

	Context()
	{
		stop = false;
		stopfd = -1;
		timer = -1;
		durationTimer = -1;
	}
} ctx;

struct Params {
	bool help;
	std::string output;
	int period;
	int duration;
	int recordThreads;

	Params()
	{
		help = false;
		period = 1;
		duration = -1;
		recordThreads = true;
	}
};

static int readDecimalParam(int *out_v, const char *name)
{
	char *end;
	long int v;

	errno = 0;
	v = strtol(optarg, &end, 10);
	if (errno != 0) {
		int ret = -errno;
		printf("Unable to parse '%s' %s : %d(%m)\n",
		       name, optarg, errno);
		return ret;
	} else if (*end != '\0') {
		printf("'%s' arg '%s' is not decimal\n",
		        name, optarg);
		return -EINVAL;
	} else if (v <= 0) {
		printf("'%s' arg '%s' is negative or null\n",
		       name, optarg);
		return -EINVAL;
	}

	*out_v = v;

	return 0;
}

int parseArgs(int argc, char *argv[], Params *params)
{
	int optionIndex = 0;
	int value;
	int ret;

	const struct option argsOptions[] = {
		{ "help"  ,          optional_argument, 0, 'h' },
		{ "period",          optional_argument, 0, 'p' },
		{ "duration",        optional_argument, 0, 'd' },
		{ "output",          required_argument, 0, 'o' },
		{ "disable-threads", optional_argument, &params->recordThreads, 0 },
		{ 0, 0, 0}
	};

	while (true) {
		value = getopt_long(argc, argv, "ho:p:d:", argsOptions, &optionIndex);
		if (value == -1 || value == '?')
			break;

		switch (value) {
		case 'h':
			params->help = true;
			break;

		case 'o':
			params->output = optarg;
			break;

		case 'd':
			ret = readDecimalParam(&params->duration, "duration");
			if (ret < 0)
				return ret;
			break;

		case 'p':
			ret = readDecimalParam(&params->period, "period");
			if (ret < 0)
				return ret;
			break;

		default:
			break;
		}
	}

	return 0;
}

void printUsage(int argc, char *argv[])
{
	printf("Usage  %s [-h] [-p PERIOD] -o OUTPUT process [process ...]\n",
	       argv[0]);

	printf("\n");

	printf("positional arguments:\n");
	printf("  %-20s %s\n", "process", "Process name to monitor");

	printf("\n");

	printf("optional arguments:\n");
	printf("  %-20s %s\n", "-h, --help", "show this help message and exit");
	printf("  %-20s %s\n", "-p, --period", "sample acquisition period (seconds). Default : 1");
	printf("  %-20s %s\n", "-d, --duration", "acquisition duration (seconds). Default : infinite");
	printf("  %-20s %s\n", "-o, --output", "output record file");
	printf("  %-20s %s\n", "--disable-threads", "disable threads recording");
}

static void sighandler(int s)
{
	int64_t stop = 1;
	int ret;

	printf("stop\n");
	ctx.stop = true;
	ret = write(ctx.stopfd, &stop, sizeof(stop));
	if (ret < 0)
		printf("write() failed : %d(%m)\n", errno);
}

static void systemStatsCb(
		const SystemMonitor::SystemStats &stats,
		void *userdata)
{
	SystemRecorder *recorder = (SystemRecorder *) userdata;
	int ret;

	ret = recorder->record(stats);
	if (ret < 0)
		printf("record() failed : %d(%s)\n", -ret, strerror(-ret));
}

static void processStatsCb(
		const SystemMonitor::ProcessStats &stats,
		void *userdata)
{
	SystemRecorder *recorder = (SystemRecorder *) userdata;
	int ret;

	ret = recorder->record(stats);
	if (ret < 0)
		printf("record() failed : %d(%s)\n", -ret, strerror(-ret));
}

static void threadStatsCb(
		const SystemMonitor::ThreadStats &stats,
		void *userdata)
{
	SystemRecorder *recorder = (SystemRecorder *) userdata;
	int ret;

	ret = recorder->record(stats);
	if (ret < 0)
		printf("record() failed : %d(%s)\n", -ret, strerror(-ret));
}

static void acquisitionDurationCb(
		const SystemMonitor::AcquisitionDuration &stats,
		void *userdata)
{
	SystemRecorder *recorder = (SystemRecorder *) userdata;
	int ret;

	ret = recorder->record(stats);
	if (ret < 0)
		printf("record() failed : %d(%s)\n", -ret, strerror(-ret));
}

static void buildProgParameters(int argc, char *argv[], ProgramParameters *out)
{
	std::string s;

	s = argv[0];

	for (int i = 1; i < argc; i++)
		s += std::string(" ") + std::string(argv[i]);

	snprintf(out->mParams, sizeof(out->mParams), "%s", s.c_str());
}

static bool getOutputPath(const std::string &basePath, std::string *outPath)
{
	struct stat st;
	char path[128];
	int ret;
	bool found = false;

	for (int i = 0; i < 100; i++) {
		snprintf(path, sizeof(path), "%s-%02d.log",
			 basePath.c_str(), i);

		ret = stat(path, &st);
		if (ret == -1 && errno == ENOENT) {
			found = true;
			*outPath = path;
			break;
		}
	}

	return found;
}

int main(int argc, char *argv[])
{
	struct itimerspec timer;
	struct pollfd fds[3];
	int fdsCount;
	Params params;
	std::string outputPath;
	ProgramParameters progParameters;
	SystemMonitor::SystemConfig systemConfig;
	SystemMonitor::Callbacks cb;
	SystemMonitor *mon = nullptr;
	SystemMonitor::Config monConfig;
	SystemRecorder *recorder = nullptr;
	int ret;

	signal(SIGINT, sighandler);

	// Parse parameters
	if (argc == 1) {
		printUsage(argc, argv);
		return 0;
	}

	ret = parseArgs(argc, argv, &params);
	if (ret < 0) {
		printUsage(argc, argv);
		return 1;
	} else if (params.output.empty()) {
		printf("No output file specified\n\n");
		printUsage(argc, argv);
		return 1;
	} else if (optind == argc) {
		printf("No process name specified\n\n");
		printUsage(argc, argv);
		return 1;
	}

	// Create recorder
	recorder = SystemRecorder::create();
	if (!recorder)
		goto error;

	if (!getOutputPath(params.output, &outputPath)) {
		printf("Can find a new output file path\n");
		return 1;
	}

	printf("Recording in file %s\n", outputPath.c_str());
	ret = recorder->open(outputPath.c_str());
	if (ret < 0)
		goto error;

	// Create monitor
	cb.mSystemStats = systemStatsCb;
	cb.mProcessStats = processStatsCb;
	cb.mThreadStats = threadStatsCb;
	cb.mAcquisitionDuration = acquisitionDurationCb;
	cb.mUserdata = recorder;

	monConfig.mRecordThreads = params.recordThreads;

	mon = SystemMonitor::create(monConfig, cb);
	if (!mon)
		goto error;

	for (int i = optind; i < argc; i++) {
		ret = mon->addProcess(argv[i]);
		if (ret < 0) {
			printf("addProcessFailed() : %d(%s)\n", -ret, strerror(-ret));
			goto error;
		}

	}

	mon->loadProcesses();

	// Write program parameters
	buildProgParameters(argc, argv, &progParameters);
	recorder->record(progParameters);

	// Write system config
	ret = mon->readSystemConfig(&systemConfig);
	if (ret < 0) {
		printf("readSystemConfig() failed : %d(%m)\n", errno);
		goto error;
	}

	recorder->record(systemConfig);

	// Create stopfd
	ret = eventfd(0, EFD_CLOEXEC);
	if (ret < 0) {
		printf("eventfd() failed : %d(%m)\n", errno);
		goto error;
	}

	ctx.stopfd = ret;

	fds[0].fd = ctx.stopfd;
	fds[0].events = POLLIN;
	fds[0].revents = 0;

	// Create timer
	ret = timerfd_create(CLOCK_MONOTONIC, EFD_CLOEXEC);
	if (ret < 0) {
		printf("timerfd_create() failed : %d(%m)\n", errno);
		goto error;
	}

	ctx.timer = ret;

	// Start timer
	timer.it_interval.tv_sec = params.period;
	timer.it_interval.tv_nsec = 0;

	timer.it_value.tv_sec = params.period;
	timer.it_value.tv_nsec = 0;

	ret = timerfd_settime(ctx.timer, 0, &timer, NULL);
	if (ret < 0) {
		printf("timerfd_settime() failed : %d(%m)\n", errno);
		goto error;
	}

	fds[1].fd = ctx.timer;
	fds[1].events = POLLIN;
	fds[1].revents = 0;

	fdsCount = 2;

	// Create duration timer
	if (params.duration > 0) {
		ret = timerfd_create(CLOCK_MONOTONIC, EFD_CLOEXEC);
		if (ret < 0) {
			printf("timerfd_create() failed : %d(%m)\n", errno);
			goto error;
		}

		ctx.durationTimer = ret;

		// Start timer
		timer.it_value.tv_sec = params.duration;
		timer.it_value.tv_nsec = 0;

		timer.it_interval.tv_sec = 0;
		timer.it_interval.tv_nsec = 0;

		ret = timerfd_settime(ctx.durationTimer, 0, &timer, NULL);
		if (ret < 0) {
			printf("timerfd_settime() failed : %d(%m)\n", errno);
			goto error;
		}

		fds[2].fd = ctx.durationTimer;
		fds[2].events = POLLIN;
		fds[2].revents = 0;

		fdsCount++;
	} else {
		fds[2].fd = -1;
		fds[2].events = 0;
		fds[2].revents = 0;
	}

	// Start poll
	while (true) {
		do {
			ret = poll(fds, fdsCount, -1);
		} while (ret == -1 && errno == EINTR);

		if (ret == -1) {
			printf("poll() failed : %d(%m)\n", errno);
			goto error;
		} else if (ret == 0) {
			printf("poll() : timeout\n");
			continue;
		}

		if (ctx.stop)
			break;

		if (fds[1].revents & POLLIN) {
			uint64_t expirations;

			mon->process();

			ret = read(fds[1].fd, &expirations, sizeof(expirations));
			if (ret < 0)
				printf("read() failed : %d(%m)\n", errno);
		}

		if (fds[2].revents & POLLIN)
			break;
	}

	recorder->close();

	delete mon;
	delete recorder;

	if (ctx.stopfd != -1)
		close(ctx.stopfd);

	if (ctx.timer != -1)
		close(ctx.timer);

	return 0;

error:
	delete mon;
	delete recorder;

	if (ctx.stopfd != -1)
		close(ctx.stopfd);

	if (ctx.timer != -1)
		close(ctx.timer);

	return 1;
}
<|endoftext|>


<commit_before>/**
 * Copyright 2016 Michal Korbela, Filip Pokrývka, Ondřej Slámečka
 * See the LICENSE file for more information.
 */

#include <bits/stdc++.h>

//#include "../mnist/include/mnist/mnist_reader.hpp"

#include "brca_image.hpp"

#include "MLP.hpp"

struct Stats {
    int corr;
    int unsure;
    int fail;
};

std::vector<double> transform(bool i) {
    std::vector<double> v;
    if(i) {
        v.push_back(0); v.push_back(1);
    }
    else {
        v.push_back(1); v.push_back(0);
    }
    return v;
}

double validate(MLP &nn, std::vector<BrcaImage> &validation) {
    Stats stats = {0,0,0};
    std::vector<double> r1, r2;
    for(unsigned i = 0; i<validation.size(); i++) {
        r1 = nn.feed(validation[i].data);
        if(r1[0]<0.5) r1[0] = 0;
        else r1[0] = 1;
        if(r1[1]<0.5) r1[1] = 0;
        else r1[1] = 1;
        if(r1 == transform(validation[i].malignant)) {
            stats.corr++;
        }
        else if (r2 == transform(!validation[i].malignant) ){
            stats.fail++;
        }
        else {
            stats.unsure++;
        }
    }
    std::cout << (stats.corr*100.0)/validation.size() << " %: " << stats.corr << "/" << validation.size() << " (" << stats.unsure << " unsure), ";
    return (stats.corr*100.0)/validation.size();
}

void normalize(std::vector<BrcaImage> &input, double a, double b) {
    double min_input = input[0].data[0];
    double max_input = input[0].data[0];
    for(auto & img: input)
        for(auto & data: img.data) {
            if (data<min_input)
                min_input = data;
            if (data>max_input)
                max_input = data;
        }
    a = (max_input + min_input) / 2;
    b = (max_input - min_input) / 2;
    std::cout << "using normalisation constants: (X-" << a << ")/" << b << "\n";
    for(auto & img: input)
        for(auto & data: img.data)
            data = (data-a)/b;

    // test of normalisation
    int bad = 0;
    for(auto & img: input)
        for(auto & data: img.data) {
            if(data < -1 || data > 1)
                bad++;
        }
    if(bad) {
        std::cout << "normalization went wrong, " << bad << " numbers are not in range <-1,1>\n";
    }
    else {
        std::cout << "data normalized successfully\n";
    }
}

int main(int argc, char** argv) {
    if (argc < 2)
        throw std::invalid_argument("No data file specified "
                                "please provide it as first parameter");
    if (argc < 3)
        throw std::invalid_argument("No training set size specified "
                                "please provide it as second parameter");
    if (argc < 4)
        throw std::invalid_argument("No validation set size specified "
                                "please provide it as third parameter (can be 0)");

    unsigned training_size;
    unsigned validation_size;

    std::stringstream ss;
    ss << argv[2] << " " << argv[3];
    ss >> training_size >> validation_size;

    std::vector<BrcaImage> all_data = parse_brca_dataset(argv[1]);
    double a=0, b=0;
    normalize(all_data, a, b);

    unsigned tot_size = training_size + validation_size;
    if (tot_size > all_data.size())
        throw std::invalid_argument("please decrease training or validation set size");

    std::vector<BrcaImage> training, validation;
    for(unsigned i = 0; i<training_size; ++i) {
        training.push_back(all_data[i]);
    }
    if (validation_size == 0)
        validation = all_data;
    else {
        for(unsigned i = training_size; i<tot_size; ++i)
            validation.push_back(all_data[i]);
    }

    unsigned queue_size = 10000000;
    unsigned interval = 100;
    double treshold = 93.0;

    MLP nn({30,2});
    nn.randomize_weights(-1, 1);
    int i = -1;

    while(validate(nn, validation) < treshold) {
        ++i;
        std::cout << i*interval << std::endl;
        // if efficiency does not grow for queue_size intervals, randomize weights
        for(unsigned i = 0; i<interval; i++) {
            for(unsigned j = 0; j<training_size; j++) {
                nn.learn(training[j].data, transform(training[j].malignant), 0.5, 0.1);
            }
        }
    }

    validate(nn, all_data);
    std::cout << queue_size*interval << "\n";

    return 0;
}
<commit_msg>final version od main.cpp<commit_after>/**
 * Copyright 2016 Michal Korbela, Filip Pokrývka, Ondřej Slámečka
 * See the LICENSE file for more information.
 */

#include <bits/stdc++.h>

#include "brca_image.hpp"

#include "MLP.hpp"

struct Stats {
    int corr;
    int unsure;
    int fail;
};

std::vector<double> transform(bool i) {
    std::vector<double> v;
    if(i) {
        v.push_back(0); v.push_back(1);
    }
    else {
        v.push_back(1); v.push_back(0);
    }
    return v;
}

double validate(MLP &nn, std::vector<BrcaImage> &validation) {
    Stats stats = {0,0,0};
    std::vector<double> r1, r2;
    for (unsigned i = 0; i<validation.size(); i++) {
        r1 = nn.feed(validation[i].data);
        if(r1[0]<0.5) r1[0] = 0;
        else r1[0] = 1;
        if(r1[1]<0.5) r1[1] = 0;
        else r1[1] = 1;
        if(r1 == transform(validation[i].malignant)) {
            stats.corr++;
        }
        else if (r2 == transform(!validation[i].malignant) ){
            stats.fail++;
        }
        else {
            stats.unsure++;
        }
    }
    std::cout << (stats.corr*100.0)/validation.size() << "%: " << stats.corr << "/" << validation.size() << " (" << stats.fail << " incorrect, " << stats.unsure << " unsure)\n";
    return (stats.corr*100.0)/validation.size();
}

void normalize(std::vector<BrcaImage> &input, double a, double b) {
    double min_input = input[0].data[0];
    double max_input = input[0].data[0];
    for (auto & img: input)
        for (auto & data: img.data) {
            if (data<min_input)
                min_input = data;
            if (data>max_input)
                max_input = data;
        }
    a = (max_input + min_input) / 2;
    b = (max_input - min_input) / 2;
    std::cout << "using normalization constants: (X-" << a << ")/" << b << "\n";
    for (auto & img: input)
        for (auto & data: img.data)
            data = (data-a)/b;

    // test of normalisation
    int bad = 0;
    for (auto & img: input)
        for (auto & data: img.data) {
            if (data < -1 || data > 1)
                bad++;
        }
    if (bad)
        std::cout << "normalization went wrong, " << bad << " numbers are not in range <-1,1>\n";
    else
        std::cout << "data normalized successfully\n";
}

int main(int argc, char** argv) {
    if (argc < 2)
        throw std::invalid_argument("No data file specified\n"
                                "USAGE: bin/nn traiing_file_name training_set_size"
                                );
    if (argc < 3)
        throw std::invalid_argument("No training set size specified "
                                "USAGE: bin/nn traiing_file_name training_set_size"
                                );

    unsigned training_size;

    std::stringstream ss;
    ss << argv[2];
    ss >> training_size;

    std::vector<BrcaImage> all_data = parse_brca_dataset(argv[1]);
    double a=0, b=0;
    normalize(all_data, a, b);

    if (training_size > all_data.size())
        throw std::invalid_argument("please decrease training set size");

    std::vector<BrcaImage> training, validation;
    for(unsigned i = 0; i<training_size; ++i)
        training.push_back(all_data[i]);

    // how often is validation run
    unsigned interval = 1000;
    // when to stop
    double treshold = 92.5;

    MLP nn({30,2});
    nn.randomize_weights(-1, 1);
    int i = -1;

    while (validate(nn, all_data) < treshold) {
        ++i;
        for (unsigned i = 0; i<interval; i++)
            for (unsigned j = 0; j<training_size; j++)
                nn.learn(training[j].data, transform(training[j].malignant), 0.5, 0.0);
    }

    std::cout << "Learning finished, reached treshold " << treshold << "%" << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 */

#include <QtGui/QApplication>
#include "config.h"
#include "dbmanager.h"
#include "iconmanager.h"
#include "mainwindow.h"
#include "sqlhighlighter.h"
#include "tabwidget/abstracttabwidget.h"
#include "widgets/querytextedit.h"

int main(int argc, char *argv[])
{
  QApplication::setApplicationName("dbmaster");
  QApplication::setApplicationVersion("0.7.4");
  QApplication::setOrganizationDomain("dbmaster.sourceforge.net");
  QApplication a(argc, argv);

  QSplashScreen splash(QPixmap(":/img/splash.png"));
  splash.show();

  // Loading translations
  splash.showMessage(QObject::tr("Loading translations..."), Qt::AlignBottom);

  QTranslator translator;
  // getting the current locale
  QString lang = QLocale::system().name();
  QString transdir;
#if defined(Q_WS_X11)
  // for *nix
  transdir = QString(PREFIX).append("/share/dbmaster/tr");
#endif

#if defined(Q_WS_WIN)
  transdir = "share/tr";
#endif

  QString path;
  /* on teste d'abord si le .qm est dans le dossier courant -> alors on est en
   * dev, on le charge, sinon il est dans le répertoire d'installation. */
  path = QDir::currentPath() + QString("/tr/%1.qm").arg(lang);
  if (!QFile::exists(path))
    path = transdir.append("/%1.qm").arg(lang);
  translator.load(path);
  a.installTranslator(&translator);

  QTranslator qtTranslator;
  qtTranslator.load("qt_" + lang,
#if defined (Q_WS_X11)
                    QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#endif
#if defined (Q_WS_WIN)
                    QDir::currentPath());
#endif
  a.installTranslator(&qtTranslator);

  splash.showMessage(QObject::tr("Initialization..."), Qt::AlignBottom);

  IconManager::init();
  DbManager::init();
  Config::init();
  QueryTextEdit::reloadCompleter();

  MainWindow *w = new MainWindow();
  w->show();
  splash.finish(w);
  return a.exec();
}
<commit_msg>No version<commit_after>/*
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 */

#include <QtGui/QApplication>
#include "config.h"
#include "dbmanager.h"
#include "iconmanager.h"
#include "mainwindow.h"
#include "sqlhighlighter.h"
#include "tabwidget/abstracttabwidget.h"
#include "widgets/querytextedit.h"

int main(int argc, char *argv[])
{
  QApplication::setApplicationName("dbmaster");
  QApplication::setApplicationVersion("0.7.5");
  QApplication::setOrganizationDomain("dbmaster.sourceforge.net");
  QApplication a(argc, argv);

  QSplashScreen splash(QPixmap(":/img/splash.png"));
  splash.show();

  // Loading translations
  splash.showMessage(QObject::tr("Loading translations..."), Qt::AlignBottom);

  QTranslator translator;
  // getting the current locale
  QString lang = QLocale::system().name();
  QString transdir;
#if defined(Q_WS_X11)
  // for *nix
  transdir = QString(PREFIX).append("/share/dbmaster/tr");
#endif

#if defined(Q_WS_WIN)
  transdir = "share/tr";
#endif

  QString path;
  /* on teste d'abord si le .qm est dans le dossier courant -> alors on est en
   * dev, on le charge, sinon il est dans le répertoire d'installation. */
  path = QDir::currentPath() + QString("/tr/%1.qm").arg(lang);
  if (!QFile::exists(path))
    path = transdir.append("/%1.qm").arg(lang);
  translator.load(path);
  a.installTranslator(&translator);

  QTranslator qtTranslator;
  qtTranslator.load("qt_" + lang,
#if defined (Q_WS_X11)
                    QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#endif
#if defined (Q_WS_WIN)
                    QDir::currentPath());
#endif
  a.installTranslator(&qtTranslator);

  splash.showMessage(QObject::tr("Initialization..."), Qt::AlignBottom);

  IconManager::init();
  DbManager::init();
  Config::init();
  QueryTextEdit::reloadCompleter();

  MainWindow *w = new MainWindow();
  w->show();
  splash.finish(w);
  return a.exec();
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Luke San Antonio
 * All rights reserved.
 */
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <vector>

#include "common/log.h"

#include "gfx/mesh.h"
#include "gfx/program.h"
#include "gfx/pipeline.h"

#include "glad/glad.h"
#include "glfw3.h"

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

#include "uv.h"

#define CATCH_CONFIG_RUNNER
#include "catch/catch.hpp"

struct Command_Options
{
  bool test = false;
};

Command_Options parse_command_line(int argc, char** argv)
{
  Command_Options opt;
  for(int i = 0; i < argc; ++i)
  {
    auto option = argv[i];
    if(strcmp(option, "--test") == 0)
    {
      opt.test = true;
    }
  }
  return opt;
}

int main(int argc, char** argv)
{
  using namespace survive;

  uv_chdir("assets/");

  // Initialize logger.
  Scoped_Log_Init log_init_raii_lock{};

  // Parse command line arguments.
  auto options = parse_command_line(argc - 1, argv+1);

  // Should be run the testing whatchamacallit?
  if(options.test)
  {
    int result = Catch::Session().run(1, argv);
    if(result)
    {
      return EXIT_FAILURE;
    }
  }

  // Init glfw.
  if(!glfwInit())
    return EXIT_FAILURE;

  auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL);
  if(!window)
  {
    glfwTerminate();
    return EXIT_FAILURE;
  }

  // Init context + load gl functions.
  glfwMakeContextCurrent(window);
  gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);

  // Log glfw version.
  log_i("Initialized GLFW %", glfwGetVersionString());

  int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);

  // Log GL profile.
  log_i("OpenGL core profile %.%.%", maj, min, rev);

  // Initialize the graphics pipeline.
  auto pipeline = gfx::Pipeline{};

  // Load a shader program.
  auto shader_program = gfx::Program::from_files("shader/diffuse/vertex",
                                                 "shader/diffuse/fragment");
  // Prepare a mesh for rendering.
  auto mesh = pipeline.prepare_mesh(Mesh::from_file("obj/plane.obj"));

  int fps = 0;
  int time = glfwGetTime();

  // Set up some pre-rendering state.
  glClearColor(.75, .34, .50, 1.0);
  glClearDepth(1);

  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);

  // Use our shader.
  shader_program.use();

  float deg = -5;
  while(!glfwWindowShouldClose(window))
  {
    ++fps;

    // Create our matrix.

    //glm::mat4 view = glm::lookAt(glm::vec3(0, 10, 0), glm::vec3(0, 0, 0),
                                 //glm::vec3(0, 0, 1));
    //glm::mat4 perspective = glm::frustum(-1, 1, -1, 1, -1, 1);
    //glm::mat4 perspective = glm::ortho(-1, 1, -1, 1, -1, 1);
    glm::mat4 view(1.0);
    view = glm::lookAt(glm::vec3(0, 0, 15), glm::vec3(0, 0, 0),
                       glm::vec3(0, 1, 0));
    glm::mat4 perspective(1.0);
    perspective = glm::perspective(45., 1., .01, 30.);

    auto model = glm::mat4(1.0);

    // rotate 90 degrees ccw
    //model = glm::translate(model, glm::vec3(0, cam_height, 0));
    model = glm::rotate(model, -3.14159f / 2.0f, glm::vec3(0, 1, 0));
    model = glm::rotate(model, deg, glm::vec3(0, 1, 0));
    //model = glm::translate(model, glm::vec3(0, 0, 0));
    //model = glm::translate(model, glm::vec3(0, 0, 7));
    model = glm::scale(model, glm::vec3(5));

    deg += .001;

    glm::mat4 mvp = perspective * view * model;

    // Set the matrix in the program.
    // TODO this seems bad, change this.
    shader_program.set_uniform_mat4("mvp", mvp);

    // Clear the screen and render.
    pipeline.clear();
    pipeline.render_pipeline_mesh(mesh);

    // Show it on screen.
    glfwSwapBuffers(window);
    glfwPollEvents();

    if(int(glfwGetTime()) != time)
    {
      time = glfwGetTime();
      log_d("fps: %", fps);
      fps = 0;
    }
  }

  glfwTerminate();
  return 0;
}
<commit_msg>New clear color.<commit_after>/*
 * Copyright (C) 2014 Luke San Antonio
 * All rights reserved.
 */
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <vector>

#include "common/log.h"

#include "gfx/mesh.h"
#include "gfx/program.h"
#include "gfx/pipeline.h"

#include "glad/glad.h"
#include "glfw3.h"

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

#include "uv.h"

#define CATCH_CONFIG_RUNNER
#include "catch/catch.hpp"

struct Command_Options
{
  bool test = false;
};

Command_Options parse_command_line(int argc, char** argv)
{
  Command_Options opt;
  for(int i = 0; i < argc; ++i)
  {
    auto option = argv[i];
    if(strcmp(option, "--test") == 0)
    {
      opt.test = true;
    }
  }
  return opt;
}

int main(int argc, char** argv)
{
  using namespace survive;

  uv_chdir("assets/");

  // Initialize logger.
  Scoped_Log_Init log_init_raii_lock{};

  // Parse command line arguments.
  auto options = parse_command_line(argc - 1, argv+1);

  // Should be run the testing whatchamacallit?
  if(options.test)
  {
    int result = Catch::Session().run(1, argv);
    if(result)
    {
      return EXIT_FAILURE;
    }
  }

  // Init glfw.
  if(!glfwInit())
    return EXIT_FAILURE;

  auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL);
  if(!window)
  {
    glfwTerminate();
    return EXIT_FAILURE;
  }

  // Init context + load gl functions.
  glfwMakeContextCurrent(window);
  gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);

  // Log glfw version.
  log_i("Initialized GLFW %", glfwGetVersionString());

  int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);

  // Log GL profile.
  log_i("OpenGL core profile %.%.%", maj, min, rev);

  // Initialize the graphics pipeline.
  auto pipeline = gfx::Pipeline{};

  // Load a shader program.
  auto shader_program = gfx::Program::from_files("shader/diffuse/vertex",
                                                 "shader/diffuse/fragment");
  // Prepare a mesh for rendering.
  auto mesh = pipeline.prepare_mesh(Mesh::from_file("obj/plane.obj"));

  int fps = 0;
  int time = glfwGetTime();

  // Set up some pre-rendering state.
  glClearColor(0.509, .694, .737, 1.0);
  glClearDepth(1);

  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);

  // Use our shader.
  shader_program.use();

  float deg = -5;
  while(!glfwWindowShouldClose(window))
  {
    ++fps;

    // Create our matrix.

    //glm::mat4 view = glm::lookAt(glm::vec3(0, 10, 0), glm::vec3(0, 0, 0),
                                 //glm::vec3(0, 0, 1));
    //glm::mat4 perspective = glm::frustum(-1, 1, -1, 1, -1, 1);
    //glm::mat4 perspective = glm::ortho(-1, 1, -1, 1, -1, 1);
    glm::mat4 view(1.0);
    view = glm::lookAt(glm::vec3(0, 0, 15), glm::vec3(0, 0, 0),
                       glm::vec3(0, 1, 0));
    glm::mat4 perspective(1.0);
    perspective = glm::perspective(45., 1., .01, 30.);

    auto model = glm::mat4(1.0);

    // rotate 90 degrees ccw
    //model = glm::translate(model, glm::vec3(0, cam_height, 0));
    model = glm::rotate(model, -3.14159f / 2.0f, glm::vec3(0, 1, 0));
    model = glm::rotate(model, deg, glm::vec3(0, 1, 0));
    //model = glm::translate(model, glm::vec3(0, 0, 0));
    //model = glm::translate(model, glm::vec3(0, 0, 7));
    model = glm::scale(model, glm::vec3(5));

    deg += .001;

    glm::mat4 mvp = perspective * view * model;

    // Set the matrix in the program.
    // TODO this seems bad, change this.
    shader_program.set_uniform_mat4("mvp", mvp);

    // Clear the screen and render.
    pipeline.clear();
    pipeline.render_pipeline_mesh(mesh);

    // Show it on screen.
    glfwSwapBuffers(window);
    glfwPollEvents();

    if(int(glfwGetTime()) != time)
    {
      time = glfwGetTime();
      log_d("fps: %", fps);
      fps = 0;
    }
  }

  glfwTerminate();
  return 0;
}
<|endoftext|>


<commit_before>

#include <iostream>

#include "rapidxml.hpp"
#include "rapidxml_utils.hpp"
#include "rapidxml_print.hpp"

namespace {

bool ignore_package(const std::string& name, const std::vector<std::string>& ignore_packages){
    for(auto& ignore : ignore_packages){
        if(std::mismatch(ignore.begin(), ignore.end(), name.begin()).first == ignore.end()){
            return true;
        }
    }

    return false;
}

} //end of anonymous namespace

int main(int argc, char* argv[]){
    //Argument counter
    std::size_t i = 1;

    //Collect the packages to ignore
    std::vector<std::string> ignore_packages;
    for(; i < std::size_t(argc); ++i){
        std::string arg(argv[i]);

        std::string ignore("--ignore=");

        if(std::mismatch(ignore.begin(), ignore.end(), arg.begin()).first == ignore.end()){
            ignore_packages.emplace_back(arg.begin() + ignore.size(), arg.end());
        } else {
            break;
        }
    }

    if(argc - i + 1 < 4){
        std::cout << "coverage_merger: not enough arguments" << std::endl;
        return 1;
    }

    //Collect the paths
    std::string source_path(argv[i]);
    std::string inc_path(argv[i+1]);
    std::string target_path(argv[i+2]);

    std::cout << "Source file: " << source_path << std::endl;
    std::cout << "Increment file: " << inc_path << std::endl;
    std::cout << "Target file: " << target_path << std::endl;

    rapidxml::file<> source_file(source_path.c_str());
    rapidxml::xml_document<> source_doc;
    source_doc.parse<0>(source_file.data());

    rapidxml::file<> inc_file(inc_path.c_str());
    rapidxml::xml_document<> inc_doc;
    inc_doc.parse<0>(inc_file.data());

    rapidxml::xml_document<> target_doc;

    std::cout << "Documents parsed" << std::endl;

    //Find the root nodes
    auto source_root_node = source_doc.first_node("coverage");
    auto inc_root_node = inc_doc.first_node("coverage");

    //Find the "packages" nodes
    auto packages_source = source_root_node->first_node("packages");
    auto packages_inc = inc_root_node->first_node("packages");

    //Create root node in target
    auto* target_root_node = target_doc.allocate_node(rapidxml::node_element, "coverage");
    //TODO Copy attributes from source
    target_doc.append_node(target_root_node);

    //Copy directly the "sources" node
    auto* target_sources_node = source_doc.clone_node(source_root_node->first_node("sources"));
    target_root_node->append_node(target_sources_node);

    //Create the "packages" node
    auto packages_target = target_doc.allocate_node(rapidxml::node_element, "packages");
    target_root_node->append_node(packages_target);

    //1. Copy all relevant packages from source -> target

    for(auto* package_node = packages_source->first_node("package"); package_node; package_node = package_node->next_sibling()){
        std::string package_name(package_node->first_attribute("name")->value());
        std::string package_branch_rate(package_node->first_attribute("branch-rate")->value());
        std::string package_line_rate(package_node->first_attribute("line-rate")->value());

        //Skip any ignored package
        bool process = !ignore_package(package_name, ignore_packages);

        //Skip the entire package is no coverage
        if(package_branch_rate == "0.0" && package_line_rate == "0.0"){
            process = false;
        }

        if(process){
            //Create the "package" node
            auto package_target = target_doc.allocate_node(rapidxml::node_element, "package");
            package_target->append_attribute(target_doc.allocate_attribute("name", package_node->first_attribute("name")->value()));
            package_target->append_attribute(target_doc.allocate_attribute("branch-rate", package_node->first_attribute("branch-rate")->value()));
            package_target->append_attribute(target_doc.allocate_attribute("line-rate", package_node->first_attribute("line-rate")->value()));
            package_target->append_attribute(target_doc.allocate_attribute("complexity", package_node->first_attribute("complexity")->value()));
            packages_target->append_node(package_target);

            //Create the "classes" node
            auto classes_target = target_doc.allocate_node(rapidxml::node_element, "classes");
            package_target->append_node(classes_target);

            auto classes_sources = package_node->first_node("classes");

            for(auto* class_source = classes_sources->first_node("class"); class_source; class_source = class_source->next_sibling()){
                std::string class_name(class_source->first_attribute("name")->value());
                std::string class_branch_rate(class_source->first_attribute("branch-rate")->value());
                std::string class_line_rate(class_source->first_attribute("line-rate")->value());

                if(!(class_branch_rate == "0.0" && class_line_rate == "0.0")){
                    //Copy "class" node into target
                    auto* class_target = source_doc.clone_node(class_source);
                    classes_target->append_node(class_target);
                }
            }
        }
    }

    //2. Copy all relevant packages not present in target from inc -> target

    for(auto* package_node = packages_inc->first_node("package"); package_node; package_node = package_node->next_sibling()){
        std::string package_name(package_node->first_attribute("name")->value());
        std::string package_branch_rate(package_node->first_attribute("branch-rate")->value());
        std::string package_line_rate(package_node->first_attribute("line-rate")->value());

        //Skip any ignored package
        bool process = !ignore_package(package_name, ignore_packages);

        //Skip the entire package is no coverage
        if(package_branch_rate == "0.0" && package_line_rate == "0.0"){
            process = false;
        }

        //Skip package that are already existing in target
        if(process){
            for(auto* target_package = packages_target->first_node("package"); target_package; target_package = target_package->next_sibling()){
                std::string source_package_name(target_package->first_attribute("name")->value());

                if(source_package_name == package_name){
                    process = false;
                    break;
                }
            }
        }

        if(process){
            //Create the "package" node
            auto package_target = target_doc.allocate_node(rapidxml::node_element, "package");
            package_target->append_attribute(target_doc.allocate_attribute("name", package_node->first_attribute("name")->value()));
            package_target->append_attribute(target_doc.allocate_attribute("branch-rate", package_node->first_attribute("branch-rate")->value()));
            package_target->append_attribute(target_doc.allocate_attribute("line-rate", package_node->first_attribute("line-rate")->value()));
            package_target->append_attribute(target_doc.allocate_attribute("complexity", package_node->first_attribute("complexity")->value()));
            packages_target->append_node(package_target);

            //Create the "classes" node
            auto classes_target = target_doc.allocate_node(rapidxml::node_element, "classes");
            package_target->append_node(classes_target);

            auto classes_sources = package_node->first_node("classes");

            for(auto* class_source = classes_sources->first_node("class"); class_source; class_source = class_source->next_sibling()){
                std::string class_name(class_source->first_attribute("name")->value());
                std::string class_branch_rate(class_source->first_attribute("branch-rate")->value());
                std::string class_line_rate(class_source->first_attribute("line-rate")->value());

                if(!(class_branch_rate == "0.0" && class_line_rate == "0.0")){
                    //Copy "class" node into target
                    auto* class_target = source_doc.clone_node(class_source);
                    classes_target->append_node(class_target);
                }
            }
        }
    }

    //Write the target doc
    std::ofstream target_stream(target_path);
    target_stream << target_doc;
    target_stream.close();

    std::cout << "Documents have been processed and target has been written" << std::endl;

    return 0;
}
<commit_msg>Refactorings<commit_after>

#include <iostream>

#include "rapidxml.hpp"
#include "rapidxml_utils.hpp"
#include "rapidxml_print.hpp"

namespace {

//The documents

rapidxml::xml_document<> source_doc;
rapidxml::xml_document<> inc_doc;
rapidxml::xml_document<> target_doc;

bool ignore_package(const std::string& name, const std::vector<std::string>& ignore_packages){
    for(auto& ignore : ignore_packages){
        if(std::mismatch(ignore.begin(), ignore.end(), name.begin()).first == ignore.end()){
            return true;
        }
    }

    return false;
}

} //end of anonymous namespace

int main(int argc, char* argv[]){
    //Argument counter
    std::size_t i = 1;

    //Collect the packages to ignore
    std::vector<std::string> ignore_packages;
    for(; i < std::size_t(argc); ++i){
        std::string arg(argv[i]);

        std::string ignore("--ignore=");

        if(std::mismatch(ignore.begin(), ignore.end(), arg.begin()).first == ignore.end()){
            ignore_packages.emplace_back(arg.begin() + ignore.size(), arg.end());
        } else {
            break;
        }
    }

    if(argc - i + 1 < 4){
        std::cout << "coverage_merger: not enough arguments" << std::endl;
        return 1;
    }

    //Collect the paths
    std::string source_path(argv[i]);
    std::string inc_path(argv[i+1]);
    std::string target_path(argv[i+2]);

    std::cout << "Source file: " << source_path << std::endl;
    std::cout << "Increment file: " << inc_path << std::endl;
    std::cout << "Target file: " << target_path << std::endl;

    //Parse all documents

    rapidxml::file<> source_file(source_path.c_str());
    source_doc.parse<0>(source_file.data());

    rapidxml::file<> inc_file(inc_path.c_str());
    inc_doc.parse<0>(inc_file.data());

    std::cout << "Documents parsed" << std::endl;

    //Find the root nodes
    auto source_root_node = source_doc.first_node("coverage");
    auto inc_root_node = inc_doc.first_node("coverage");

    //Find the "packages" nodes
    auto packages_source = source_root_node->first_node("packages");
    auto packages_inc = inc_root_node->first_node("packages");

    //Create root node in target (rates attributes are not copied on purpose)
    auto* target_root_node = target_doc.allocate_node(rapidxml::node_element, "coverage");
    target_root_node->append_attribute(target_doc.allocate_attribute("version", source_root_node->first_attribute("version")->value()));
    target_root_node->append_attribute(target_doc.allocate_attribute("timestamp", source_root_node->first_attribute("timestamp")->value()));
    target_doc.append_node(target_root_node);

    //Copy directly the "sources" node
    auto* target_sources_node = source_doc.clone_node(source_root_node->first_node("sources"));
    target_root_node->append_node(target_sources_node);

    //Create the "packages" node
    auto packages_target = target_doc.allocate_node(rapidxml::node_element, "packages");
    target_root_node->append_node(packages_target);

    //1. Copy all relevant packages from source -> target

    for(auto* package_node = packages_source->first_node("package"); package_node; package_node = package_node->next_sibling()){
        std::string package_name(package_node->first_attribute("name")->value());
        std::string package_branch_rate(package_node->first_attribute("branch-rate")->value());
        std::string package_line_rate(package_node->first_attribute("line-rate")->value());

        //Skip any ignored package
        bool process = !ignore_package(package_name, ignore_packages);

        //Skip the entire package is no coverage
        if(package_branch_rate == "0.0" && package_line_rate == "0.0"){
            process = false;
        }

        if(process){
            //Create the "package" node
            auto package_target = target_doc.allocate_node(rapidxml::node_element, "package");
            package_target->append_attribute(target_doc.allocate_attribute("name", package_node->first_attribute("name")->value()));
            package_target->append_attribute(target_doc.allocate_attribute("branch-rate", package_node->first_attribute("branch-rate")->value()));
            package_target->append_attribute(target_doc.allocate_attribute("line-rate", package_node->first_attribute("line-rate")->value()));
            package_target->append_attribute(target_doc.allocate_attribute("complexity", package_node->first_attribute("complexity")->value()));
            packages_target->append_node(package_target);

            //Create the "classes" node
            auto classes_target = target_doc.allocate_node(rapidxml::node_element, "classes");
            package_target->append_node(classes_target);

            auto classes_sources = package_node->first_node("classes");

            for(auto* class_source = classes_sources->first_node("class"); class_source; class_source = class_source->next_sibling()){
                std::string class_name(class_source->first_attribute("name")->value());
                std::string class_branch_rate(class_source->first_attribute("branch-rate")->value());
                std::string class_line_rate(class_source->first_attribute("line-rate")->value());

                if(!(class_branch_rate == "0.0" && class_line_rate == "0.0")){
                    //Copy "class" node into target
                    auto* class_target = source_doc.clone_node(class_source);
                    classes_target->append_node(class_target);
                }
            }
        }
    }

    //2. Copy all relevant packages not present in target from inc -> target

    for(auto* package_node = packages_inc->first_node("package"); package_node; package_node = package_node->next_sibling()){
        std::string package_name(package_node->first_attribute("name")->value());
        std::string package_branch_rate(package_node->first_attribute("branch-rate")->value());
        std::string package_line_rate(package_node->first_attribute("line-rate")->value());

        //Skip any ignored package
        bool process = !ignore_package(package_name, ignore_packages);

        //Skip the entire package is no coverage
        if(package_branch_rate == "0.0" && package_line_rate == "0.0"){
            process = false;
        }

        //Skip package that are already existing in target
        if(process){
            for(auto* target_package = packages_target->first_node("package"); target_package; target_package = target_package->next_sibling()){
                std::string source_package_name(target_package->first_attribute("name")->value());

                if(source_package_name == package_name){
                    process = false;
                    break;
                }
            }
        }

        if(process){
            //Create the "package" node
            auto package_target = target_doc.allocate_node(rapidxml::node_element, "package");
            package_target->append_attribute(target_doc.allocate_attribute("name", package_node->first_attribute("name")->value()));
            package_target->append_attribute(target_doc.allocate_attribute("branch-rate", package_node->first_attribute("branch-rate")->value()));
            package_target->append_attribute(target_doc.allocate_attribute("line-rate", package_node->first_attribute("line-rate")->value()));
            package_target->append_attribute(target_doc.allocate_attribute("complexity", package_node->first_attribute("complexity")->value()));
            packages_target->append_node(package_target);

            //Create the "classes" node
            auto classes_target = target_doc.allocate_node(rapidxml::node_element, "classes");
            package_target->append_node(classes_target);

            auto classes_sources = package_node->first_node("classes");

            for(auto* class_source = classes_sources->first_node("class"); class_source; class_source = class_source->next_sibling()){
                std::string class_name(class_source->first_attribute("name")->value());
                std::string class_branch_rate(class_source->first_attribute("branch-rate")->value());
                std::string class_line_rate(class_source->first_attribute("line-rate")->value());

                if(!(class_branch_rate == "0.0" && class_line_rate == "0.0")){
                    //Copy "class" node into target
                    auto* class_target = source_doc.clone_node(class_source);
                    classes_target->append_node(class_target);
                }
            }
        }
    }

    //Write the target doc
    std::ofstream target_stream(target_path);
    target_stream << target_doc;
    target_stream.close();

    std::cout << "Documents have been processed and target has been written" << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>/**
 * This is the main file that will be used to run the rshell.
**/
#include "Rshell.h"

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string input = "";
    while (input != "exit")
    {
        cout << "$";
        cin >> input;
    }
    return 0;
}
<commit_msg>Updated main.cpp file to include whitespace<commit_after>/**
 * This is the main file that will be used to run the rshell.
**/
#include "Rshell.h"

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string input = "";
    while(input != "exit")
    {
        cout << "$";
        getline(cin, input);
    }
    return 0;
}
<|endoftext|>


<commit_before>#include "Hydra.h"
#include "Sprite.h"
#include <vector>
#include <unistd.h>
#include <stdio.h>
using namespace std;
using namespace Hydra;

enum dirs {left, right, up, down};

class ComicPanel
{
public:
    int posX;
    int posY;
    int height;
    int width;
    float vel; //Speed when traveling TO this panel!    bool root;
    bool blank; //If true, don't render this panel - it's just an empty frame.
    bool root; //Is this comic a root?
    string nextComic[4]; //The name of the next panel to be moved to given
    string name;
    Sprite* image;
};

ComicPanel* loadFromXML(pugi::xml_node configNode);
ComicPanel* switchToComic(vector<ComicPanel*> panels, string nextName);
inline double getScaling(ComicPanel* panel, HydraEngine* engine);

Log* sysLog = Logger::getInstance()->getLog("sysLog");

int main(int argc, char* argv[])
{
	HydraEngine* engine = HydraEngine::getInstance();
	engine->init();

    vector<ComicPanel*> panels;
    bool quit = false;

    double currentX = 0, currentY = 0;
    double dX = 0, dY = 0;
    double scale = 1.0f;
    double scalingDiff = 0.0f; //How much to change the scaling by
    bool transitioning = false;
    bool fullscreen = false;
    int fcCooldown = 0;
    ComicPanel* currentPanel;

    char cCurrentPath[FILENAME_MAX];
    cout << "CWD: " <<  getcwd(cCurrentPath, sizeof(cCurrentPath)) << endl;

    //Load all comics
    pugi::xml_document doc;
    pugi::xml_parse_result result = doc.load_file("Comic.xml");
    cout << "Loaded file Comic.xml with result: " << result.description() << endl;
    sysLog->log("Loaded file Comic.xml with result: " + string(result.description()));
    sysLog->log("Loading panels...", Hydra::resource);
    cout << "\nLoading panels...\n" << endl;

    for (pugi::xml_node comic = doc.child("Comics").child("panel"); comic; comic = comic.next_sibling())
    {
        ComicPanel* newPanel = loadFromXML(comic);
        if (newPanel->root)
        {
            currentPanel = newPanel;
            cout << "Setting root panel to panel " << currentPanel->name << " at position " << currentPanel->posX << ", " << currentPanel->posY << endl;
            scale = getScaling(currentPanel, engine); //The comic is to start out scaled to the root panel
            currentX = currentPanel->posX;
            currentY = currentPanel->posY;
        }
        panels.push_back(newPanel);
    }

    if (currentPanel == nullptr)
        cout << "Error - couldn't find the root panel! Have you specified one yet?" << endl;

    while (!quit && currentPanel != nullptr)
    {
        if (fcCooldown > 0)
            fcCooldown--;
        Timer fpsTimer;
        fpsTimer.start();
        fpsTimer.setInterval(1000.0f / 60.0f);

        SDL_Event e;
        while (SDL_PollEvent(&e) != 0)
        {
            if (e.type == SDL_QUIT || e.key.keysym.scancode == SDL_SCANCODE_ESCAPE)
                quit = true;
            if (e.key.keysym.scancode == SDL_SCANCODE_F && !transitioning && fcCooldown == 0)
            {
                if (!fullscreen)
                {
                    fullscreen = true;
                    engine->setWSize(1366, 768);
                    SDL_SetWindowFullscreen(engine->getWindow(), SDL_WINDOW_FULLSCREEN);
                }
                else
                {
                    fullscreen = false;
                    SDL_SetWindowFullscreen(engine->getWindow(), 0);
                    engine->setWSize(800, 600);
                }

                scale = getScaling(currentPanel, engine);

                cout << "Fullscreen: " << fullscreen << ". Window dimensions: " << engine->getWXSize() << "x" <<
                    engine->getWYSize() << ". Scaling: " << scale << endl;
                fcCooldown = 30;

            }
        }

        //Transitioning stuff
        if (!transitioning)
        {
            ComicPanel* nextPanel = nullptr;

            const Uint8* keystate = SDL_GetKeyboardState(nullptr);
            if (keystate[SDL_SCANCODE_DOWN])
                nextPanel = switchToComic(panels, currentPanel->nextComic[dirs::down]);
            if (keystate[SDL_SCANCODE_UP])
                nextPanel = switchToComic(panels, currentPanel->nextComic[dirs::up]);
            if (keystate[SDL_SCANCODE_LEFT])
                nextPanel = switchToComic(panels, currentPanel->nextComic[dirs::left]);
            if (keystate[SDL_SCANCODE_RIGHT])
                nextPanel = switchToComic(panels, currentPanel->nextComic[dirs::right]);

            if (nextPanel != nullptr)
            {
                currentPanel = nextPanel;
                transitioning = true;
                cout << "Switching panels to panel " << currentPanel->name;
                sysLog->log("Switching panels to panel " + currentPanel->name);

                //Compute dX and dY values
                Vector2D dir;
                dir.rotate(atan2f((double)(currentPanel->posY - currentY), (double)(currentPanel->posX - currentX)));
                dir.setMag(currentPanel->vel);
                dX = dir.getX();
                dY = dir.getY();
            }
        }

        //Velocities in directions - uses a Vector2D for calculations (because TRIGONOMETRY!)
        if (transitioning)
        {
            Vector2D dir;
            dir.setX(abs((int)(scale * ((double)currentPanel->posX - currentX))));
            dir.setY(abs((int)(scale * ((double)currentPanel->posY - currentY))));
            scalingDiff = (getScaling(currentPanel, engine) - scale) / (dir.getMag() / (double)currentPanel->vel);

            scale += scalingDiff;
            currentX += dX;// * scale;
            currentY += dY;// * scale;

            if (dir.getMag() <= currentPanel->vel)
            {
                transitioning = false;
                currentX = (double)currentPanel->posX; //Absolute magic. Complete effing magic!
                currentY = (double)currentPanel->posY;
                scale= getScaling(currentPanel, engine); //Fix scaling
                cout << ". Viewer at " << currentX << ", " << currentY << ". Scale: " << getScaling(currentPanel, engine) << endl;
                sysLog->log("Viewer at " + to_string(currentX) + ", " + to_string(currentY) + ". Scale: " + to_string(getScaling(currentPanel, engine)));
            }
        }

        //Rendering stuff
        SDL_RenderClear(engine->getRenderer());
        for (auto iter = panels.begin(); iter != panels.end(); iter++)
        {
            if ((*iter)->blank)
              continue;
            Sprite* image = (*iter)->image;
            image->render(((*iter)->posX - currentX) * scale,
                          ((*iter)->posY - currentY) * scale,
                          image->getH() * scale,
                          image->getW() * scale);
        }

        SDL_RenderPresent(engine->getRenderer());

        //Ensures 60 fps
        while (!fpsTimer.hasIntervalPassed());
    }

    //Shutdown sequence
    cout << "\nFreeing images..." << endl;
    sysLog->log("Freeing images...", Hydra::resource);
    for (auto iter = panels.begin(); iter != panels.end(); iter++)
    {
        cout << "Freeing " << (*iter)->name << "..." << endl;
        sysLog->log("Freeing " + (*iter)->name + "...", Hydra::resource);
        (*iter)->image->free();
        delete *iter;
    }
    engine->shutdown();
}

ComicPanel* loadFromXML(pugi::xml_node configNode)
{
    //Assumes that this node is a "panel" node.
    ComicPanel* newPanel = new ComicPanel;
    newPanel->image = new Sprite;

    newPanel->name = configNode.attribute("name").as_string();
    newPanel->posX = configNode.child("position").attribute("x").as_int();
    newPanel->posY = configNode.child("position").attribute("y").as_int();
    newPanel->vel = configNode.child("vel").attribute("value").as_float();
    newPanel->root = false; //Default value
    newPanel->root = configNode.child("root").attribute("enabled").as_bool();
    newPanel->blank = false; //Default value
    newPanel->blank = configNode.child("blank").attribute("enabled").as_bool();
    for (int i = 0; i < 4; i++)
        newPanel->nextComic[i] = "null"; //Signifies that there is no transition to a new comic. These are default values.

    newPanel->nextComic[dirs::up] =       configNode.child("dirs").child("up").attribute("nextComic").as_string();
    newPanel->nextComic[dirs::down] =     configNode.child("dirs").child("down").attribute("nextComic").as_string();
    newPanel->nextComic[dirs::left] =     configNode.child("dirs").child("left").attribute("nextComic").as_string();
    newPanel->nextComic[dirs::right] =    configNode.child("dirs").child("right").attribute("nextComic").as_string();

    cout << "Loaded panel " << newPanel->name << endl;
    sysLog->log("Loaded panel " + newPanel->name, Hydra::resource);
    if (newPanel->blank)
    {
        newPanel->width = configNode.child("dims").attribute("width").as_int();
        newPanel->height = configNode.child("dims").attribute("height").as_int();
        return newPanel; //There is no image to load; skip loading an image.
    }

    newPanel->image->loadFromFile(configNode.child("filename").attribute("str").as_string());
    cout << "Loaded file " << configNode.child("filename").attribute("str").as_string() << endl << endl;
    sysLog->log("Loaded file " + string(configNode.child("filename").attribute("str").as_string()), Hydra::resource);
    newPanel->height = newPanel->image->getH();
    newPanel->width = newPanel->image->getW();
    return newPanel;
}
ComicPanel* switchToComic(vector<ComicPanel*> panels, string nextName)
{
    //Given a name of a panel and a vector of pointers to panels, find a panel with the given name.
    //Returns nullptr if there is no such pointer

    //Dummy check - XML file should specify null if you don't want to switch to comic from a dir
    if (nextName == "null")
        return nullptr;

    for (auto iter = panels.begin(); iter != panels.end(); iter++)
    {
        if ((*iter)->name == nextName)
        {
            return *iter;
        }
    }

    cout << "Error switching panels: panel " << nextName << " does not exist." << endl;
    sysLog->log("Error switching panels: panel " + nextName + " does not exist.", Hydra::error);
    return nullptr; //Yeah, sorry, this panel doesn't exist.
}
double getScaling(ComicPanel* panel, HydraEngine* engine)
{
    //Figure out the scaling needed to fit this panel's largest dimension on the screen
    if (panel->width > panel->height)
        return (double)engine->getWXSize() / (double)panel->width;
    else
        return (double)engine->getWYSize() / (double)panel->height;

    return 1.0f;
}
<commit_msg>Fixed bottom cutoff issues<commit_after>#include "Hydra.h"
#include "Sprite.h"
#include <vector>
#include <unistd.h>
#include <stdio.h>
using namespace std;
using namespace Hydra;

enum dirs {left, right, up, down};

class ComicPanel
{
public:
    int posX;
    int posY;
    int height;
    int width;
    float vel; //Speed when traveling TO this panel!    bool root;
    bool blank; //If true, don't render this panel - it's just an empty frame.
    bool root; //Is this comic a root?
    string nextComic[4]; //The name of the next panel to be moved to given
    string name;
    Sprite* image;
};

ComicPanel* loadFromXML(pugi::xml_node configNode);
ComicPanel* switchToComic(vector<ComicPanel*> panels, string nextName);
inline double getScaling(ComicPanel* panel, HydraEngine* engine);

Log* sysLog = Logger::getInstance()->getLog("sysLog");

int main(int argc, char* argv[])
{
	HydraEngine* engine = HydraEngine::getInstance();
	engine->init();

    vector<ComicPanel*> panels;
    bool quit = false;

    double currentX = 0, currentY = 0;
    double dX = 0, dY = 0;
    double scale = 1.0f;
    double scalingDiff = 0.0f; //How much to change the scaling by
    bool transitioning = false;
    bool fullscreen = false;
    int fcCooldown = 0;
    ComicPanel* currentPanel;

    char cCurrentPath[FILENAME_MAX];
    cout << "CWD: " <<  getcwd(cCurrentPath, sizeof(cCurrentPath)) << endl;

    //Load all comics
    pugi::xml_document doc;
    pugi::xml_parse_result result = doc.load_file("Comic.xml");
    cout << "Loaded file Comic.xml with result: " << result.description() << endl;
    sysLog->log("Loaded file Comic.xml with result: " + string(result.description()));
    sysLog->log("Loading panels...", Hydra::resource);
    cout << "\nLoading panels...\n" << endl;

    for (pugi::xml_node comic = doc.child("Comics").child("panel"); comic; comic = comic.next_sibling())
    {
        ComicPanel* newPanel = loadFromXML(comic);
        if (newPanel->root)
        {
            currentPanel = newPanel;
            cout << "Setting root panel to panel " << currentPanel->name << " at position " << currentPanel->posX << ", " << currentPanel->posY << endl;
            scale = getScaling(currentPanel, engine); //The comic is to start out scaled to the root panel
            currentX = currentPanel->posX;
            currentY = currentPanel->posY;
        }
        panels.push_back(newPanel);
    }

    if (currentPanel == nullptr)
        cout << "Error - couldn't find the root panel! Have you specified one yet?" << endl;

    while (!quit && currentPanel != nullptr)
    {
        if (fcCooldown > 0)
            fcCooldown--;
        Timer fpsTimer;
        fpsTimer.start();
        fpsTimer.setInterval(1000.0f / 60.0f);

        SDL_Event e;
        while (SDL_PollEvent(&e) != 0)
        {
            if (e.type == SDL_QUIT || e.key.keysym.scancode == SDL_SCANCODE_ESCAPE)
                quit = true;
            if (e.key.keysym.scancode == SDL_SCANCODE_F && !transitioning && fcCooldown == 0)
            {
                if (!fullscreen)
                {
                    fullscreen = true;
                    engine->setWSize(1366, 768);
                    SDL_SetWindowFullscreen(engine->getWindow(), SDL_WINDOW_FULLSCREEN);
                }
                else
                {
                    fullscreen = false;
                    SDL_SetWindowFullscreen(engine->getWindow(), 0);
                    engine->setWSize(800, 600);
                }

                scale = getScaling(currentPanel, engine);

                cout << "Fullscreen: " << fullscreen << ". Window dimensions: " << engine->getWXSize() << "x" <<
                    engine->getWYSize() << ". Scaling: " << scale << endl;
                fcCooldown = 30;

            }
        }

        //Transitioning stuff
        if (!transitioning)
        {
            ComicPanel* nextPanel = nullptr;

            const Uint8* keystate = SDL_GetKeyboardState(nullptr);
            if (keystate[SDL_SCANCODE_DOWN])
                nextPanel = switchToComic(panels, currentPanel->nextComic[dirs::down]);
            if (keystate[SDL_SCANCODE_UP])
                nextPanel = switchToComic(panels, currentPanel->nextComic[dirs::up]);
            if (keystate[SDL_SCANCODE_LEFT])
                nextPanel = switchToComic(panels, currentPanel->nextComic[dirs::left]);
            if (keystate[SDL_SCANCODE_RIGHT])
                nextPanel = switchToComic(panels, currentPanel->nextComic[dirs::right]);

            if (nextPanel != nullptr)
            {
                currentPanel = nextPanel;
                transitioning = true;
                cout << "Switching panels to panel " << currentPanel->name;
                sysLog->log("Switching panels to panel " + currentPanel->name);

                //Compute dX and dY values
                Vector2D dir;
                dir.rotate(atan2f((double)(currentPanel->posY - currentY), (double)(currentPanel->posX - currentX)));
                dir.setMag(currentPanel->vel);
                dX = dir.getX();
                dY = dir.getY();
            }
        }

        //Velocities in directions - uses a Vector2D for calculations (because TRIGONOMETRY!)
        if (transitioning)
        {
            Vector2D dir;
            dir.setX(abs((int)(scale * ((double)currentPanel->posX - currentX))));
            dir.setY(abs((int)(scale * ((double)currentPanel->posY - currentY))));
            scalingDiff = (getScaling(currentPanel, engine) - scale) / (dir.getMag() / (double)currentPanel->vel);

            scale += scalingDiff;
            currentX += dX;// * scale;
            currentY += dY;// * scale;

            if (dir.getMag() <= currentPanel->vel)
            {
                transitioning = false;
                currentX = (double)currentPanel->posX; //Absolute magic. Complete effing magic!
                currentY = (double)currentPanel->posY;
                scale= getScaling(currentPanel, engine); //Fix scaling
                cout << ". Viewer at " << currentX << ", " << currentY << ". Scale: " << getScaling(currentPanel, engine) << endl;
                sysLog->log("Viewer at " + to_string(currentX) + ", " + to_string(currentY) + ". Scale: " + to_string(getScaling(currentPanel, engine)));
            }
        }

        //Rendering stuff
        SDL_RenderClear(engine->getRenderer());
        for (auto iter = panels.begin(); iter != panels.end(); iter++)
        {
            if ((*iter)->blank)
              continue;
            Sprite* image = (*iter)->image;
            image->render(((*iter)->posX - currentX) * scale,
                          ((*iter)->posY - currentY) * scale,
                          image->getH() * scale,
                          image->getW() * scale);
        }

        SDL_RenderPresent(engine->getRenderer());

        //Ensures 60 fps
        while (!fpsTimer.hasIntervalPassed());
    }

    //Shutdown sequence
    cout << "\nFreeing images..." << endl;
    sysLog->log("Freeing images...", Hydra::resource);
    for (auto iter = panels.begin(); iter != panels.end(); iter++)
    {
        cout << "Freeing " << (*iter)->name << "..." << endl;
        sysLog->log("Freeing " + (*iter)->name + "...", Hydra::resource);
        (*iter)->image->free();
        delete *iter;
    }
    engine->shutdown();
}

ComicPanel* loadFromXML(pugi::xml_node configNode)
{
    //Assumes that this node is a "panel" node.
    ComicPanel* newPanel = new ComicPanel;
    newPanel->image = new Sprite;

    newPanel->name = configNode.attribute("name").as_string();
    newPanel->posX = configNode.child("position").attribute("x").as_int();
    newPanel->posY = configNode.child("position").attribute("y").as_int();
    newPanel->vel = configNode.child("vel").attribute("value").as_float();
    newPanel->root = false; //Default value
    newPanel->root = configNode.child("root").attribute("enabled").as_bool();
    newPanel->blank = false; //Default value
    newPanel->blank = configNode.child("blank").attribute("enabled").as_bool();
    for (int i = 0; i < 4; i++)
        newPanel->nextComic[i] = "null"; //Signifies that there is no transition to a new comic. These are default values.

    newPanel->nextComic[dirs::up] =       configNode.child("dirs").child("up").attribute("nextComic").as_string();
    newPanel->nextComic[dirs::down] =     configNode.child("dirs").child("down").attribute("nextComic").as_string();
    newPanel->nextComic[dirs::left] =     configNode.child("dirs").child("left").attribute("nextComic").as_string();
    newPanel->nextComic[dirs::right] =    configNode.child("dirs").child("right").attribute("nextComic").as_string();

    cout << "Loaded panel " << newPanel->name << endl;
    sysLog->log("Loaded panel " + newPanel->name, Hydra::resource);
    if (newPanel->blank)
    {
        newPanel->width = configNode.child("dims").attribute("width").as_int();
        newPanel->height = configNode.child("dims").attribute("height").as_int();
        return newPanel; //There is no image to load; skip loading an image.
    }

    newPanel->image->loadFromFile(configNode.child("filename").attribute("str").as_string());
    cout << "Loaded file " << configNode.child("filename").attribute("str").as_string() << endl << endl;
    sysLog->log("Loaded file " + string(configNode.child("filename").attribute("str").as_string()), Hydra::resource);
    newPanel->height = newPanel->image->getH();
    newPanel->width = newPanel->image->getW();
    return newPanel;
}
ComicPanel* switchToComic(vector<ComicPanel*> panels, string nextName)
{
    //Given a name of a panel and a vector of pointers to panels, find a panel with the given name.
    //Returns nullptr if there is no such pointer

    //Dummy check - XML file should specify null if you don't want to switch to comic from a dir
    if (nextName == "null")
        return nullptr;

    for (auto iter = panels.begin(); iter != panels.end(); iter++)
    {
        if ((*iter)->name == nextName)
        {
            return *iter;
        }
    }

    cout << "Error switching panels: panel " << nextName << " does not exist." << endl;
    sysLog->log("Error switching panels: panel " + nextName + " does not exist.", Hydra::error);
    return nullptr; //Yeah, sorry, this panel doesn't exist.
}
double getScaling(ComicPanel* panel, HydraEngine* engine)
{
    //Figure out the scaling needed to fit this panel's largest dimension on the screen
    double zWidth = (double)engine->getWXSize() / (double)panel->width;
    double zHeight = (double)engine->getWYSize() / (double)panel->height;

    if (zWidth < zHeight)
        return zWidth;
    else
        return zHeight;
}
<|endoftext|>