<commit_before>#include "chip8.h"

// Display size
#define SCREEN_WIDTH 64
#define SCREEN_HEIGHT 32

chip8 Chip8;
int modifier = 10;
int oglIdx = -1;
bool quit = false;

// Window size
int display_width = SCREEN_WIDTH * modifier;
int display_height = SCREEN_HEIGHT * modifier;

void display();
void reshape_window(GLsizei w, GLsizei h);

typedef unsigned __int8 u8;
u8 screenData[SCREEN_HEIGHT][SCREEN_WIDTH][3];
void setupTexture();
const unsigned char NCOLORS = 2;
Uint32 palette[NCOLORS];

SDL_Window *window = nullptr;
SDL_Surface *screen = nullptr;

// Chip8 Keypad
const Uint32 KEY_0 = SDL_SCANCODE_KP_0;
const Uint32 KEY_1 = SDL_SCANCODE_KP_1;
const Uint32 KEY_2 = SDL_SCANCODE_KP_2;
const Uint32 KEY_3 = SDL_SCANCODE_KP_3;
const Uint32 KEY_4 = SDL_SCANCODE_KP_4;
const Uint32 KEY_5 = SDL_SCANCODE_KP_5;
const Uint32 KEY_6 = SDL_SCANCODE_KP_6;
const Uint32 KEY_7 = SDL_SCANCODE_KP_7;
const Uint32 KEY_8 = SDL_SCANCODE_KP_8;
const Uint32 KEY_9 = SDL_SCANCODE_KP_9;
const Uint32 KEY_A = SDL_SCANCODE_Q;
const Uint32 KEY_B = SDL_SCANCODE_A;
const Uint32 KEY_C = SDL_SCANCODE_Z;
const Uint32 KEY_D = SDL_SCANCODE_W;
const Uint32 KEY_E = SDL_SCANCODE_S;
const Uint32 KEY_F = SDL_SCANCODE_X;

const Uint32 KEY_EXIT = SDLK_ESCAPE;

int init_SDL()
{
	//Initialize all SDL subsystems
	SDL_Init(SDL_INIT_EVERYTHING);

	window = SDL_CreateWindow("Chip8 Emulator", 100, 100, display_width, display_height, SDL_WINDOW_SHOWN);

	screen = SDL_GetWindowSurface(window);

	return 0;
}

void setup_palette()
{
	palette[0] = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
	palette[1] = SDL_MapRGB(screen->format, 0xFF, 0xFF, 0xFF);
}

int setup_graphics()
{
	if (init_SDL())
		return 1;
	setup_palette();

	return 0;
}

void render_SDL(unsigned char gfx[])
{
	SDL_Rect pixel = {0, 0, modifier, modifier};

	for (int i = 0; i < SCREEN_WIDTH; i++)
	{
		pixel.x = i * modifier;
		for (int j = 0; j < SCREEN_HEIGHT; j++)
		{
			pixel.y = j * modifier;
			SDL_FillRect(screen, &pixel, palette[gfx[i*j]]);
		}
	}
	SDL_UpdateWindowSurface(window);
}

void stop_SDL()
{
	SDL_DestroyWindow(window);
	SDL_Quit();
}

void update_key_reg(unsigned char key[])
{
	const Uint8 *keystates = SDL_GetKeyboardState(NULL);
	key[0x0] = keystates[KEY_0];
	key[0x1] = keystates[KEY_1];
	key[0x2] = keystates[KEY_2];
	key[0x3] = keystates[KEY_3];
	key[0x4] = keystates[KEY_4];
	key[0x5] = keystates[KEY_5];
	key[0x6] = keystates[KEY_6];
	key[0x7] = keystates[KEY_7];
	key[0x8] = keystates[KEY_8];
	key[0x9] = keystates[KEY_9];
	key[0xA] = keystates[KEY_A];
	key[0xB] = keystates[KEY_B];
	key[0xC] = keystates[KEY_C];
	key[0xD] = keystates[KEY_D];
	key[0xE] = keystates[KEY_E];
	key[0xF] = keystates[KEY_F];
}

int process_event(SDL_Event *e, chip8* Chip8)
{
	if (e->type == SDL_QUIT)
		return 1;
	if (!e->key.repeat)
	{
		if (e->type == SDL_KEYDOWN)
		{
			switch (e->key.keysym.sym)
			{
				/*
				case KEY_A:
					std::cout << "key Z pressed" << std::endl;
				break;
				*/
			case KEY_EXIT:
				return 1;
				break;
			default:
				break;
			}
		}
		/*
		if (e->type == SDL_KEYUP)
		{
			switch (e->key.keysym.sym)
			{
				case KEY_A:
					std::cout << "key Z unpressed" << std::endl;
				break;
				default:
				break;
			}
		}
		*/
		if (e->type == SDL_KEYUP || e->type == SDL_KEYDOWN)
			update_key_reg(Chip8->key);
	}
	return 0;
}

int main(int argc, char **argv)
{
	if (argc < 2)
	{
		printf("Usage: Chip8.exe chip8application\n\n");
		return 1;
	}

	// Load game
	if (!Chip8.loadApplication(argv[1]))
		return 1;

	// Setup OpenGL
	SDL_Event e;
	setup_graphics();
	while (1) {
		while (SDL_PollEvent(&e))
		{
			if (process_event(&e, &Chip8))
				quit = true;
		}

		render_SDL(Chip8.gfx);

	}

	stop_SDL();
	return 0;
}
<commit_msg>Cleanup main<commit_after>#include "chip8.h"

// Display size
#define SCREEN_WIDTH 64
#define SCREEN_HEIGHT 32

chip8 Chip8;
int modifier = 10;
bool quit = false;

// Window size
int display_width = SCREEN_WIDTH * modifier;
int display_height = SCREEN_HEIGHT * modifier;

typedef unsigned __int8 u8;
u8 screenData[SCREEN_HEIGHT][SCREEN_WIDTH][3];

const unsigned char NCOLORS = 2;
Uint32 palette[NCOLORS];

SDL_Window *window = nullptr;
SDL_Surface *screen = nullptr;

// Chip8 Keypad
const Uint32 KEY_0 = SDL_SCANCODE_KP_0;
const Uint32 KEY_1 = SDL_SCANCODE_KP_1;
const Uint32 KEY_2 = SDL_SCANCODE_KP_2;
const Uint32 KEY_3 = SDL_SCANCODE_KP_3;
const Uint32 KEY_4 = SDL_SCANCODE_KP_4;
const Uint32 KEY_5 = SDL_SCANCODE_KP_5;
const Uint32 KEY_6 = SDL_SCANCODE_KP_6;
const Uint32 KEY_7 = SDL_SCANCODE_KP_7;
const Uint32 KEY_8 = SDL_SCANCODE_KP_8;
const Uint32 KEY_9 = SDL_SCANCODE_KP_9;
const Uint32 KEY_A = SDL_SCANCODE_Q;
const Uint32 KEY_B = SDL_SCANCODE_A;
const Uint32 KEY_C = SDL_SCANCODE_Z;
const Uint32 KEY_D = SDL_SCANCODE_W;
const Uint32 KEY_E = SDL_SCANCODE_S;
const Uint32 KEY_F = SDL_SCANCODE_X;

const Uint32 KEY_EXIT = SDLK_ESCAPE;

int init_SDL()
{
	//Initialize all SDL subsystems
	SDL_Init(SDL_INIT_EVERYTHING);

	window = SDL_CreateWindow("Chip8 Emulator", 100, 100, display_width, display_height, SDL_WINDOW_SHOWN);

	screen = SDL_GetWindowSurface(window);

	return 0;
}

void setup_palette()
{
	palette[0] = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
	palette[1] = SDL_MapRGB(screen->format, 0xFF, 0xFF, 0xFF);
}

int setup_graphics()
{
	if (init_SDL())
		return 1;
	setup_palette();

	return 0;
}

void render_SDL(unsigned char gfx[])
{
	SDL_Rect pixel = {0, 0, modifier, modifier};

	for (int i = 0; i < SCREEN_WIDTH; i++)
	{
		pixel.x = i * modifier;
		for (int j = 0; j < SCREEN_HEIGHT; j++)
		{
			pixel.y = j * modifier;
			SDL_FillRect(screen, &pixel, palette[gfx[i*j]]);
		}
	}
	SDL_UpdateWindowSurface(window);
}

void stop_SDL()
{
	SDL_DestroyWindow(window);
	SDL_Quit();
}

void update_key_reg(unsigned char key[])
{
	const Uint8 *keystates = SDL_GetKeyboardState(NULL);
	key[0x0] = keystates[KEY_0];
	key[0x1] = keystates[KEY_1];
	key[0x2] = keystates[KEY_2];
	key[0x3] = keystates[KEY_3];
	key[0x4] = keystates[KEY_4];
	key[0x5] = keystates[KEY_5];
	key[0x6] = keystates[KEY_6];
	key[0x7] = keystates[KEY_7];
	key[0x8] = keystates[KEY_8];
	key[0x9] = keystates[KEY_9];
	key[0xA] = keystates[KEY_A];
	key[0xB] = keystates[KEY_B];
	key[0xC] = keystates[KEY_C];
	key[0xD] = keystates[KEY_D];
	key[0xE] = keystates[KEY_E];
	key[0xF] = keystates[KEY_F];
}

int process_event(SDL_Event *e, chip8* Chip8)
{
	if (e->type == SDL_QUIT)
		return 1;
	if (!e->key.repeat)
	{
		if (e->type == SDL_KEYDOWN)
		{
			switch (e->key.keysym.sym)
			{
				/*
				case KEY_A:
					std::cout << "key Z pressed" << std::endl;
				break;
				*/
			case KEY_EXIT:
				return 1;
				break;
			default:
				break;
			}
		}
		/*
		if (e->type == SDL_KEYUP)
		{
			switch (e->key.keysym.sym)
			{
				case KEY_A:
					std::cout << "key Z unpressed" << std::endl;
				break;
				default:
				break;
			}
		}
		*/
		if (e->type == SDL_KEYUP || e->type == SDL_KEYDOWN)
			update_key_reg(Chip8->key);
	}
	return 0;
}

int main(int argc, char **argv)
{
	if (argc < 2)
	{
		printf("Usage: Chip8.exe chip8application\n\n");
		return 1;
	}

	// Load game
	if (!Chip8.loadApplication(argv[1]))
		return 1;

	// Setup OpenGL
	SDL_Event e;
	setup_graphics();
	while (1) {
		while (SDL_PollEvent(&e))
		{
			if (process_event(&e, &Chip8))
				quit = true;
		}

		render_SDL(Chip8.gfx);

	}

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


<commit_before>7c6ede38-2749-11e6-b117-e0f84713e7b8<commit_msg>I hope I am done<commit_after>7c815b3a-2749-11e6-aab4-e0f84713e7b8<|endoftext|>


<commit_before>#include <cstring>
#include <iostream>
#include "permuter.cpp"
#include "param.cpp"
#include "options.cpp"

#define ENDL "\n"

using namespace std;

void showIntro() {
    cout << "Dictionary Generator v1.0 - by Miguel Espinoza - http://purefan.me" << ENDL;
    cout << ENDL;
    cout << "| This program takes words from a file and permutes them into a  |" << ENDL;
    cout << "| dictionary that can be used in brute force attacks.            |" << ENDL;
    cout << "| Intended only for educational purposes, do not use it for evil |" << ENDL;
    cout << "| By using this software you agree to release the author(s) from |" << ENDL;
    cout << "| any liability and responsibility.                              |" << ENDL;
    cout << ENDL;
}

/**
 * KISS Require 2 params
 */
int main(int argc, char *argv[]) {
    showIntro();

    Param num_range_from = Param();
    num_range_from.setDescription("Tells from which number to start");
    num_range_from.setShortForm('s');
    num_range_from.setLongForm("num-range-from");
    num_range_from.setType("numeric");

    Param num_range_to = Param();
    num_range_to.setDescription("Tells the maximum number to be used in the range");
    num_range_to.setShortForm('w');
    num_range_to.setLongForm("mix-words");

    Param lower_case = Param();
    lower_case.setDescription("Converts every character to lower case: BALL -> [bALL, BaLL, BAlL, BALl, baLL, BalL, BAll, balL, Ball, ball]");
    lower_case.setShortForm('l');
    lower_case.setLongForm("lower-case");

    Param upper_case = Param();
    upper_case.setDescription("Converts every character to upper case: ball -> [Ball, bAll, baLl, balL, BAll, bALl, baLL, BALl, bALL, BALL]");
    upper_case.setShortForm('u');
    upper_case.setLongForm("upper-case");

    Param mix_case = Param();
    mix_case.setDescription("Combines upper and lower cases in every possible way");
    mix_case.setShortForm('m');
    mix_case.setLongForm("mixed-case");

    Param add_numbers_beginning = Param();
    add_numbers_beginning.setDescription("Adds leading numbers to the beginning of the word. Requires the params \"num-range-from\" and \"num-range-to\": BALL -> [0BALL, 1BALL, 2BALL, 3BALL, 4BALL, ...]");
    add_numbers_beginning.setShortForm('n');
    add_numbers_beginning.setLongForm("leading-numbers");
    add_numbers_beginning.requires(num_range_from);
    add_numbers_beginning.requires(num_range_to);

    Param add_numbers_end = Param();
    add_numbers_end.setDescription("Adds trailing numbers of the word. Requires the params \"num-range-from\" and \"num-range-to\": BALL -> [BALL0, BALL1, BALL2, BALL3, BALL4, ...]");
    add_numbers_end.setShortForm('N');
    add_numbers_end.setLongForm("trailing-numbers");
    add_numbers_end.requires(num_range_from);
    add_numbers_end.requires(num_range_to);

    Param add_numbers_in_between = Param();
    add_numbers_in_between.setDescription("Adds numbers between each letter. Requires the params \"num-range-from\" and \"num-range-to\": BALL -> [B0ALL, BA0LL, BAL0L, B1ALL, BA1LL, ...]");
    add_numbers_in_between.setShortForm('n');
    add_numbers_in_between.setLongForm("numbers-beginning");
    add_numbers_in_between.requires(num_range_from);
    add_numbers_in_between.requires(num_range_to);

    Param mix_words = Param();
    mix_words.setDescription("Mixes words from the source file: [hello, bye, red] -> [hellobye, byehello, hellored, redhello, byered, redbye]");
    mix_words.setShortForm('w');
    mix_words.setLongForm("mix-words");

    Param source_file = Param();
    source_file.setDescription("Tells which file has the words that will be permuted.");
    source_file.setShortForm('f');
    source_file.setLongForm("source");

    Param target_file = Param();
    target_file.setDescription("Tells which file will store the permuted words.");
    target_file.setShortForm('t');
    target_file.setLongForm("target");

    std::vector<std::string> arguments(argv + 1, argv + argc);
    Options main_options = Options();
    main_options.registerParams(arguments);
    main_options.addParam(lower_case);
    main_options.addParam(upper_case);
    main_options.addParam(mix_case);
    main_options.addParam(add_numbers_beginning);
    main_options.addParam(add_numbers_end);
    main_options.addParam(add_numbers_in_between);
    main_options.addParam(mix_words);

    // SUPER important
    std::locale::global(std::locale("sv_SE"));

    if (main_options.ok) {
        Permuter myPermuter = Permuter();
        myPermuter.set_options(main_options);

        if (myPermuter.allGood() == true) {
            myPermuter.run();
        }

    }
    std::string sourcePath;
    std::string targetPath;

    if (argc > 1) {
        sourcePath = argv[1];
    } else {
        cout << "1. Path to a file with common words to permute: ";
        getline(cin, sourcePath);
    }

    if (argc > 2) {
        targetPath = argv[2];
    } else {
        cout << "2. Path to the target file: ";
        getline(cin, targetPath);
    }

    return 0;
}<commit_msg>Refactor: Rename registerArgs<commit_after>#include <cstring>
#include <iostream>
#include "permuter.cpp"
#include "param.cpp"
#include "options.cpp"

#define ENDL "\n"

using namespace std;

void showIntro() {
    cout << "Dictionary Generator v1.0 - by Miguel Espinoza - http://purefan.me" << ENDL;
    cout << ENDL;
    cout << "| This program takes words from a file and permutes them into a  |" << ENDL;
    cout << "| dictionary that can be used in brute force attacks.            |" << ENDL;
    cout << "| Intended only for educational purposes, do not use it for evil |" << ENDL;
    cout << "| By using this software you agree to release the author(s) from |" << ENDL;
    cout << "| any liability and responsibility.                              |" << ENDL;
    cout << ENDL;
}

/**
 * KISS Require 2 params
 */
int main(int argc, char *argv[]) {
    showIntro();

    Param num_range_from = Param();
    num_range_from.setDescription("Tells from which number to start");
    num_range_from.setShortForm('s');
    num_range_from.setLongForm("num-range-from");
    num_range_from.setType("numeric");

    Param num_range_to = Param();
    num_range_to.setDescription("Tells the maximum number to be used in the range");
    num_range_to.setShortForm('w');
    num_range_to.setLongForm("mix-words");

    Param lower_case = Param();
    lower_case.setDescription("Converts every character to lower case: BALL -> [bALL, BaLL, BAlL, BALl, baLL, BalL, BAll, balL, Ball, ball]");
    lower_case.setShortForm('l');
    lower_case.setLongForm("lower-case");

    Param upper_case = Param();
    upper_case.setDescription("Converts every character to upper case: ball -> [Ball, bAll, baLl, balL, BAll, bALl, baLL, BALl, bALL, BALL]");
    upper_case.setShortForm('u');
    upper_case.setLongForm("upper-case");

    Param mix_case = Param();
    mix_case.setDescription("Combines upper and lower cases in every possible way");
    mix_case.setShortForm('m');
    mix_case.setLongForm("mixed-case");

    Param add_numbers_beginning = Param();
    add_numbers_beginning.setDescription("Adds leading numbers to the beginning of the word. Requires the params \"num-range-from\" and \"num-range-to\": BALL -> [0BALL, 1BALL, 2BALL, 3BALL, 4BALL, ...]");
    add_numbers_beginning.setShortForm('n');
    add_numbers_beginning.setLongForm("leading-numbers");
    add_numbers_beginning.requires(num_range_from);
    add_numbers_beginning.requires(num_range_to);

    Param add_numbers_end = Param();
    add_numbers_end.setDescription("Adds trailing numbers of the word. Requires the params \"num-range-from\" and \"num-range-to\": BALL -> [BALL0, BALL1, BALL2, BALL3, BALL4, ...]");
    add_numbers_end.setShortForm('N');
    add_numbers_end.setLongForm("trailing-numbers");
    add_numbers_end.requires(num_range_from);
    add_numbers_end.requires(num_range_to);

    Param add_numbers_in_between = Param();
    add_numbers_in_between.setDescription("Adds numbers between each letter. Requires the params \"num-range-from\" and \"num-range-to\": BALL -> [B0ALL, BA0LL, BAL0L, B1ALL, BA1LL, ...]");
    add_numbers_in_between.setShortForm('n');
    add_numbers_in_between.setLongForm("numbers-beginning");
    add_numbers_in_between.requires(num_range_from);
    add_numbers_in_between.requires(num_range_to);

    Param mix_words = Param();
    mix_words.setDescription("Mixes words from the source file: [hello, bye, red] -> [hellobye, byehello, hellored, redhello, byered, redbye]");
    mix_words.setShortForm('w');
    mix_words.setLongForm("mix-words");

    Param source_file = Param();
    source_file.setDescription("Tells which file has the words that will be permuted.");
    source_file.setShortForm('f');
    source_file.setLongForm("source");

    Param target_file = Param();
    target_file.setDescription("Tells which file will store the permuted words.");
    target_file.setShortForm('t');
    target_file.setLongForm("target");

    std::vector<std::string> arguments(argv + 1, argv + argc);
    Options main_options = Options();
    main_options.addParam(lower_case);
    main_options.addParam(upper_case);
    main_options.addParam(mix_case);
    main_options.addParam(add_numbers_beginning);
    main_options.addParam(add_numbers_end);
    main_options.addParam(add_numbers_in_between);
    main_options.addParam(mix_words);
    main_options.registerArgs(arguments);

    // SUPER important
    std::locale::global(std::locale("sv_SE"));

    if (main_options.ok) {
        Permuter myPermuter = Permuter();
        myPermuter.set_options(main_options);

        if (myPermuter.allGood() == true) {
            myPermuter.run();
        }

    }
    std::string sourcePath;
    std::string targetPath;

    if (argc > 1) {
        sourcePath = argv[1];
    } else {
        cout << "1. Path to a file with common words to permute: ";
        getline(cin, sourcePath);
    }

    if (argc > 2) {
        targetPath = argv[2];
    } else {
        cout << "2. Path to the target file: ";
        getline(cin, targetPath);
    }

    return 0;
}<|endoftext|>


<commit_before>#include <stdio.h>
#include <mpi.h>
#include <math.h>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <sstream>

int g_world_size;
int g_mpi_rank;
int start_id;
int end_id;
int g_max_id = 3072441;
int count = 0;
MPI_Offset file_start;
MPI_Offset file_end;
std::map<int, std::vector<int>> g_adj_list;

void parse_file_one_rank();
void parse_file();
int add_to_adjlist(std::string line);
int id_to_rank(int id);
MPI_Offset compute_offset(char * filename);

int main(int argc, char** argv) {
  // Initialize the MPI environment
  int test;
  MPI_Init(&argc, &argv);

  // Get the number of processes
  MPI_Comm_size(MPI_COMM_WORLD, &g_world_size);

  // Get the rank of the process
  MPI_Comm_rank(MPI_COMM_WORLD, &g_mpi_rank);

  start_id = g_mpi_rank*(g_max_id / g_world_size);
  end_id = (g_mpi_rank+1)*(g_max_id / g_world_size);
  if (g_mpi_rank == g_world_size-1){
    end_id = g_max_id;
  }

  printf("Rank %d: start_id: %d end_id: %d\n", g_mpi_rank, start_id, end_id);

  // Print off a hello world message
  parse_file();
  // if(g_mpi_rank==0){
  //   parse_file_one_rank();
  // }

  MPI_Barrier(MPI_COMM_WORLD);
  printf("Rank: %d    g_adj_list.size(): %lu    elements in list: %d\n", g_mpi_rank, g_adj_list.size(), count);
  //if (g_mpi_rank == 0){
   // parse_file();
    //printf("Rank: %d    g_adj_list.size(): %lu\n", g_mpi_rank, g_adj_list.size());
  // }

  // Finalize the MPI environment.
  MPI_Finalize();

  return 0;
}

//only use this once to optimize file parsing
void parse_file_one_rank(){
  std::string line;
  int count = 0;
  std::ifstream infile("com-friendster.ungraph.txt");
  for(int i =0; i<4; i++){
    std::getline(infile, line);
  }
  std::vector<std::ofstream*> streams;
  for(int i=0;i<125;i++) {
    std::stringstream sstm;
    sstm<<"./Friendster/users_"<<i<<".txt";
    std::string fileName = sstm.str();
    streams.push_back(new std::ofstream(fileName.c_str(), std::ofstream::out));
  }
  while(std::getline(infile,line)){
    count++;
    int tab_pos = line.find("\t");
    int one = atoi(line.substr(0, tab_pos).c_str());
    int two = atoi(line.substr(tab_pos+1).c_str());
    int oneFile = floor((double)one/1000000);
    int twoFile = floor((double)two/1000000);
    std::stringstream sstm;
    sstm<<one<<"\t"<<two<<"\n";
    std::string lineOne = sstm.str();
    sstm.str(std::string());
    sstm.clear();
    sstm<<two<<"\t"<<one<<"\n";
    std::string lineTwo = sstm.str();

    *streams[oneFile]<<lineOne;
    *streams[twoFile]<<lineTwo;
    if(count%500000==0){
      double percent = one/(double)g_max_id*100;
      std::cout<<percent<<"%"<<std::endl;
    }
  }
}

MPI_Offset compute_offset(char * filename){
  MPI_File infile;
  MPI_File_open(MPI_COMM_WORLD, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &infile);
  MPI_Offset filesize = 0;
  MPI_File_get_size(infile, &filesize);

  MPI_Offset offset = 0;
  int num_sections = 100;
  for (int i=1; i<num_sections; i++){
    // set the temp offset
    int tmp_offset = (filesize / num_sections) * i;

    // allocate some space to read in at the offset
    char * buffer = (char *)malloc( (1001)*sizeof(char));
    // read in there
    MPI_File_read_at(infile, tmp_offset, buffer, 1000, MPI_CHAR, MPI_STATUS_IGNORE);
    buffer[1000] = '\0';
    // cast as a string
    std::string chunk(buffer);
    free(buffer);
    //std::cout << chunk << std::endl;

    // read up to the first newline and throw that away
    chunk = chunk.substr(chunk.find('\n')+1);
    // get everything from there to the next newline
    std::string line = chunk.substr(0, chunk.find('\n'));

    // split it up over the tab and pull out the first id
    int tab_pos = line.find("\t");
    int first_id = atoi(line.substr(0, tab_pos).c_str());
    // if this id is greater than the starting id, the offset is too big, go to the last one
    if (first_id > start_id){
      offset = (filesize / num_sections) * (i-1);
      break;
    }
  }
  return offset;
}

void parse_file(){
  int lowFile = floor((double)start_id/24600);
  int highFile = floor((double)end_id/24600);
  // loop through all of the files that will hold information about our set of ids
  for (int i=0; i<highFile-lowFile+1; i++){
    // create the filename as a c_str
    char filename[100];
    sprintf(filename, "/gpfs/u/home/PCP5/PCP5stns/scratch/user_%d.txt", lowFile);

    // open the file and get the filesize
    MPI_File infile;
    MPI_File_open(MPI_COMM_WORLD, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &infile);
    MPI_Offset filesize = 0;
    MPI_File_get_size(infile, &filesize);

    //printf("%s: %lu", filename, filesize);

    // start the offset at 0, for now
    MPI_Offset offset = compute_offset(filename);

    bool skip = true;
    if(offset==0){
      skip = false;
    }
    char * buffer;
    std::string chunk = "";
    // set the buffer size, ie. how much to read in at a time
    unsigned int buffer_size = 10000;

    // keep track of the latest id that we read in so that we can stop reading if we've found the last id that we need
    int latest_id_found = 0;

    // loop while we haven't read the whole file and we haven't found the latest id yet
    while (offset < filesize && latest_id_found < end_id){
      // printf("Rank: %d offset: %lld, file_end: %lld, remaining: %lld  size of adj_list: %lu\n", g_mpi_rank, offset, file_end, file_end-offset, g_adj_list.size());
      // read in a chukn to the buffer
      buffer = (char *)malloc( (buffer_size + 1)*sizeof(char));
      MPI_File_read_at(infile, offset, buffer, buffer_size, MPI_CHAR, MPI_STATUS_IGNORE);
      offset += buffer_size-100;
      // end the string
      buffer[buffer_size] = '\0';
      // make the c_string a std::string for convenience
      std::string new_string(buffer);
      free(buffer);
      // add the new string to the existing one
      chunk += new_string;

      if (skip){
        // skip up to the first newline to remove any broken lines from starting in the middle of the file
        chunk = chunk.substr(chunk.find('\n')+1);
      }else{
        skip = true;
      }

      // find the first newline in the file
      int found_nl = chunk.find('\n');
      // loop while there are still newlines and we havne't found the last id yet
      while (found_nl < chunk.size() && latest_id_found < end_id){
        // get the part of the string before the newline
        std::string line = chunk.substr(0, found_nl);
        // parse that part of it
        latest_id_found = add_to_adjlist(line);

        // reset the string so it is past that first part
        chunk = chunk.substr(found_nl+1);
        // search for another newline
        found_nl = chunk.find('\n');
      }
   }
   // go to the next file
   lowFile++;
  }
  printf("Rank %d: finished read in of own portion of file    %lu\n", g_mpi_rank, g_adj_list.size());
    //sprintf(filename, "com-friendster.ungraph.txt");
}

int id_to_rank(int id){
  int max_id=0;
  for (int i=0; i<g_world_size; i++){
    max_id += g_max_id / g_world_size;
    if (id < max_id){
      return i;
    }
  }
  return g_world_size-1;
}

int add_to_adjlist(std::string line){
  int tab_pos = line.find("\t");
  int one = atoi(line.substr(0, tab_pos).c_str());
  int two = atoi(line.substr(tab_pos+1).c_str());
  //std::cout<<start_id<<" "<<end_id<<std::endl;
  if (one >= start_id && one < end_id){
    g_adj_list[one].push_back(two);
    count++;
    if(count%100000==0){
      std::cout<<g_mpi_rank<<" "<<count<<std::endl;
    }
  }
  return one;
}
<commit_msg>working?<commit_after>#include <stdio.h>
#include <mpi.h>
#include <math.h>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <sstream>
#include <list>

int g_world_size;
int g_mpi_rank;
int start_id;
int end_id;
const int g_max_id = 3072441;
int count = 0;
MPI_Offset file_start;
MPI_Offset file_end;
std::map<int, std::vector<int> > g_adj_list;
bool visited[g_max_id] = {0};
bool inQueue[g_max_id] = {0};
std::vector<std::list<int> > connectedComponents;
std::map<int, std::vector<int> > boundaryEdges;

void parse_file_one_rank();
void parse_file();
int add_to_adjlist(std::string line);
int id_to_rank(int id);
MPI_Offset compute_offset(char * filename);
void bfs(int u, int ccCounter);

int main(int argc, char** argv) {
  // Initialize the MPI environment
  MPI_Init(&argc, &argv);

  // Get the number of processes
  MPI_Comm_size(MPI_COMM_WORLD, &g_world_size);

  // Get the rank of the process
  MPI_Comm_rank(MPI_COMM_WORLD, &g_mpi_rank);

  start_id = g_mpi_rank*(g_max_id / g_world_size);
  end_id = (g_mpi_rank+1)*(g_max_id / g_world_size);
  if (g_mpi_rank == g_world_size-1){
    end_id = g_max_id;
  }

  //printf("Rank %d: start_id: %d end_id: %d\n", g_mpi_rank, start_id, end_id);

  // Print off a hello world message
  parse_file();
  // if(g_mpi_rank==0){
  //   parse_file_one_rank();
  // }
  MPI_Barrier(MPI_COMM_WORLD);
  if(g_mpi_rank == 0){
    printf("Done parsing files");
  }
  for(std::map<int, std::vector<int> >::iterator itr =g_adj_list.begin(); itr!=g_adj_list.end(); itr++){
    visited[itr->first]=true;
  }

  for(std::map<int, std::vector<int> >::iterator itr =g_adj_list.begin(); itr!=g_adj_list.end(); itr++) {
    std::vector<int> temp = itr->second;
    for(int i =0; i<temp.size(); i++){
      if(!visited[temp[i]]){
        if(g_adj_list.find(temp[i])==g_adj_list.end()){
          std::vector<int> temp1;
          temp1.push_back(itr->first);
          g_adj_list[temp[i]] = temp1;
        }
        else{
          g_adj_list[temp[i]].push_back(itr->first);
        }
      }
    }
  }

  for(std::map<int, std::vector<int> >::iterator itr =g_adj_list.begin(); itr!=g_adj_list.end(); itr++){
    visited[itr->first]=false;
  }

  int ccCounter = -1;
  for(std::map<int, std::vector<int> >::iterator itr =g_adj_list.begin(); itr!=g_adj_list.end(); itr++) {
    if(!visited[itr->first]) {
      ccCounter += 1;
      std::list<int> temp;
      connectedComponents.push_back(temp);
      bfs(itr->first, ccCounter);
    }
  }
  // for(int i=0; i<connectedComponents.size(); i++){
  //   std::cout<<"CC "<<i<<" - ";
  //   for(int j=0; j<connectedComponents[i].size(); j++) {
  //     std::cout<<connectedComponents[i][j]<<", ";
  //   }
  //   std::cout<<std::endl;
  // }
  MPI_Barrier(MPI_COMM_WORLD);
  if(g_mpi_rank == 0){
    printf("Done computing spanning forests");
  }
  printf("Rank: %d    g_adj_list.size(): %lu    elements in list: %d    CCs: %d\n ", g_mpi_rank, g_adj_list.size(), count, ccCounter+1);

  MPI_Barrier(MPI_COMM_WORLD);
  if(g_mpi_rank == 152) {
    for(int i =0; i<connectedComponents.size(); i++) {
      std::cout<<(connectedComponents[i]).size()<<std::endl;
      for(std::list<int>::iterator itr = connectedComponents[i].begin(); itr != connectedComponents[i].end(); itr++){
        std::cout<<*itr<<" ";
      }
      printf("\n\n\n\n\n\n");
    }
  }
  //if (g_mpi_rank == 0){
   // parse_file();
    //printf("Rank: %d    g_adj_list.size(): %lu\n", g_mpi_rank, g_adj_list.size());
  // }

  // Finalize the MPI environment.
  MPI_Finalize();

  return 0;
}

//only use this once to optimize file parsing
void parse_file_one_rank(){
  std::string line;
  int count = 0;
  std::ifstream infile("com-friendster.ungraph.txt");
  for(int i =0; i<4; i++){
    std::getline(infile, line);
  }
  std::vector<std::ofstream*> streams;
  for(int i=0;i<125;i++) {
    std::stringstream sstm;
    sstm<<"./Friendster/users_"<<i<<".txt";
    std::string fileName = sstm.str();
    streams.push_back(new std::ofstream(fileName.c_str(), std::ofstream::out));
  }
  while(std::getline(infile,line)){
    count++;
    int tab_pos = line.find("\t");
    int one = atoi(line.substr(0, tab_pos).c_str());
    int two = atoi(line.substr(tab_pos+1).c_str());
    int oneFile = floor((double)one/1000000);
    int twoFile = floor((double)two/1000000);
    std::stringstream sstm;
    sstm<<one<<"\t"<<two<<"\n";
    std::string lineOne = sstm.str();
    sstm.str(std::string());
    sstm.clear();
    sstm<<two<<"\t"<<one<<"\n";
    std::string lineTwo = sstm.str();

    *streams[oneFile]<<lineOne;
    *streams[twoFile]<<lineTwo;
  }
}

MPI_Offset compute_offset(char * filename){
  MPI_File infile;
  MPI_File_open(MPI_COMM_WORLD, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &infile);
  MPI_Offset filesize = 0;
  MPI_File_get_size(infile, &filesize);

  MPI_Offset offset = 0;
  int num_sections = 100;
  for (int i=1; i<num_sections; i++){
    // set the temp offset
    int tmp_offset = (filesize / num_sections) * i;

    // allocate some space to read in at the offset
    char * buffer = (char *)malloc( (1001)*sizeof(char));
    // read in there
    MPI_File_read_at(infile, tmp_offset, buffer, 1000, MPI_CHAR, MPI_STATUS_IGNORE);
    buffer[1000] = '\0';
    // cast as a string
    std::string chunk(buffer);
    free(buffer);
    //std::cout << chunk << std::endl;

    // read up to the first newline and throw that away
    chunk = chunk.substr(chunk.find('\n')+1);
    // get everything from there to the next newline
    std::string line = chunk.substr(0, chunk.find('\n'));

    // split it up over the tab and pull out the first id
    int tab_pos = line.find("\t");
    int first_id = atoi(line.substr(0, tab_pos).c_str());
    // if this id is greater than the starting id, the offset is too big, go to the last one
    if (first_id > start_id){
      offset = (filesize / num_sections) * (i-1);
      break;
    }
  }
  return offset;
}

void parse_file(){
  int lowFile = floor((double)start_id/24600);
  int highFile = floor((double)end_id/24600);
  // loop through all of the files that will hold information about our set of ids
  for (int i=0; i<highFile-lowFile+1; i++){
    // create the filename as a c_str
    char filename[100];
    sprintf(filename, "/gpfs/u/home/PCP5/PCP5stns/scratch/user_%d.txt", lowFile);

    // open the file and get the filesize
    MPI_File infile;
    MPI_File_open(MPI_COMM_WORLD, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &infile);
    MPI_Offset filesize = 0;
    MPI_File_get_size(infile, &filesize);

    //printf("%s: %lu", filename, filesize);

    // start the offset at 0, for now
    MPI_Offset offset = compute_offset(filename);

    bool skip = true;
    if(offset==0){
      skip = false;
    }
    char * buffer;
    std::string chunk = "";
    // set the buffer size, ie. how much to read in at a time
    unsigned int buffer_size = 10000;

    // keep track of the latest id that we read in so that we can stop reading if we've found the last id that we need
    int latest_id_found = 0;

    // loop while we haven't read the whole file and we haven't found the latest id yet
    while (offset < filesize && latest_id_found < end_id){
      // printf("Rank: %d offset: %lld, file_end: %lld, remaining: %lld  size of adj_list: %lu\n", g_mpi_rank, offset, file_end, file_end-offset, g_adj_list.size());
      // read in a chukn to the buffer
      buffer = (char *)malloc( (buffer_size + 1)*sizeof(char));
      MPI_File_read_at(infile, offset, buffer, buffer_size, MPI_CHAR, MPI_STATUS_IGNORE);
      offset += buffer_size-100;
      // end the string
      buffer[buffer_size] = '\0';
      // make the c_string a std::string for convenience
      std::string new_string(buffer);
      free(buffer);
      // add the new string to the existing one
      chunk += new_string;

      if (skip){
        // skip up to the first newline to remove any broken lines from starting in the middle of the file
        chunk = chunk.substr(chunk.find('\n')+1);
      }else{
        skip = true;
      }

      // find the first newline in the file
      int found_nl = chunk.find('\n');
      // loop while there are still newlines and we havne't found the last id yet
      while (found_nl < chunk.size() && latest_id_found < end_id){
        // get the part of the string before the newline
        std::string line = chunk.substr(0, found_nl);
        // parse that part of it
        latest_id_found = add_to_adjlist(line);

        // reset the string so it is past that first part
        chunk = chunk.substr(found_nl+1);
        // search for another newline
        found_nl = chunk.find('\n');
      }
   }
   // go to the next file
   lowFile++;
  }
  //printf("Rank %d: finished read in of own portion of file    %lu\n", g_mpi_rank, g_adj_list.size());
    //sprintf(filename, "com-friendster.ungraph.txt");
}

int id_to_rank(int id){
  int max_id=0;
  for (int i=0; i<g_world_size; i++){
    max_id += g_max_id / g_world_size;
    if (id < max_id){
      return i;
    }
  }
  return g_world_size-1;
}

int add_to_adjlist(std::string line){
  int tab_pos = line.find("\t");
  int one = atoi(line.substr(0, tab_pos).c_str());
  int two = atoi(line.substr(tab_pos+1).c_str());
  //std::cout<<start_id<<" "<<end_id<<std::endl;
  if (one >= start_id && one < end_id){
    g_adj_list[one].push_back(two);
    count++;
  }
  return one;
}

void bfs(int u, int ccCounter) {
  std::list<int> queue;
  visited[u] = true;
  queue.push_back(u);
  int prev = u;
  while(!queue.empty()) {
    int s=queue.front();
    visited[s]=true;
    connectedComponents[ccCounter].push_back(s);
    queue.pop_front();
    std::map<int, std::vector<int> >::iterator adj_list_itr;
    adj_list_itr = g_adj_list.find(s);
    if(adj_list_itr == g_adj_list.end()) {
      std::map<int, std::vector<int> >::iterator it = boundaryEdges.find(prev);
      if(it != boundaryEdges.end()){
        it->second.push_back(s);
      }
      else{
        std::vector<int> temp;
        temp.push_back(s);
        boundaryEdges[prev] = temp;
      }
    }
    prev = s;
    if(adj_list_itr != g_adj_list.end()) {
      for(std::vector<int>::iterator itr = adj_list_itr->second.begin(); itr != adj_list_itr->second.end(); itr++) {
        if(!visited[*itr]){
          if(inQueue[*itr]) {
            continue;
          }
          else{
            queue.push_back(*itr);
            inQueue[*itr] = true;
          }
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "RawImage.h"
#include "RawDecoder.h"  // For exceptions
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

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

    http://www.klauspost.com
*/
#if defined(__SSE2__)
#include <emmintrin.h>
#endif

namespace RawSpeed {

RawImageData::RawImageData(void):
    dim(0, 0), bpp(0), isCFA(true),
    blackLevel(-1), whitePoint(65536),
    dataRefCount(0), data(0), cpp(1) {
  pthread_mutex_init(&mymutex, NULL);
  subsampling.x = subsampling.y = 1;
}

RawImageData::RawImageData(iPoint2D _dim, guint _bpc, guint _cpp) :
    dim(_dim), bpp(_bpc),
    blackLevel(-1), whitePoint(65536),
    dataRefCount(0), data(0), cpp(cpp) {
  subsampling.x = subsampling.y = 1;
  createData();
  pthread_mutex_init(&mymutex, NULL);
}

RawImageData::~RawImageData(void) {
  _ASSERTE(dataRefCount == 0);
  if (data)
    _aligned_free(data);
  data = 0;
  mOffset = iPoint2D(0, 0);
  pthread_mutex_destroy(&mymutex);
}

void RawImageData::createData() {
  if (dim.x > 65535 || dim.y > 65535)
    ThrowRDE("RawImageData: Dimensions too large for allocation.");
  if (data)
    ThrowRDE("RawImageData: Duplicate data allocation in createData.");
  pitch = (((dim.x * bpp) + 15) / 16) * 16;
  data = (guchar*)_aligned_malloc(pitch * dim.y, 16);
  if (!data)
    ThrowRDE("RawImageData::createData: Memory Allocation failed.");
}

void RawImageData::destroyData() {
  if (data)
    _aligned_free(data);
  data = 0;
}

void RawImageData::setCpp(guint val) {
  if (data)
    ThrowRDE("RawImageData: Attempted to set Components per pixel after data allocation");
  bpp /= cpp;
  cpp = val;
  bpp *= val;
}

guchar* RawImageData::getData() {
  if (!data)
    ThrowRDE("RawImageData::getData - Data not yet allocated.");
  return &data[mOffset.y*pitch+mOffset.x*bpp];
}

guchar* RawImageData::getData(guint x, guint y) {
  if ((int)x >= dim.x)
    ThrowRDE("RawImageData::getData - X Position outside image requested.");
  if ((int)y >= dim.y) {
    ThrowRDE("RawImageData::getData - Y Position outside image requested.");
  }

  x += mOffset.x;
  y += mOffset.y;

  if (!data)
    ThrowRDE("RawImageData::getData - Data not yet allocated.");

  return &data[y*pitch+x*bpp];
}

void RawImageData::subFrame(iPoint2D offset, iPoint2D new_size) {
  if (!new_size.isThisInside(dim - offset)) {
    printf("WARNING: RawImageData::subFrame - Attempted to create new subframe larger than original size. Crop skipped.\n");
    return;
  }

  mOffset += offset;
  dim = new_size;
}

void RawImageData::scaleBlackWhite() {
  gint gw = (dim.x - 20) * cpp;
  if (blackLevel < 0 || whitePoint == 65536) {  // Estimate
    int b = 65536;
    int m = 0;
    for (int row = 10;row < (dim.y - 10);row++) {
      gushort *pixel = (gushort*)getData(10, row);
      for (int col = 10 ; col < gw ; col++) {
        b = MIN(*pixel, b);
        m = MAX(*pixel, m);
        pixel++;
      }
    }
    if (blackLevel < 0)
      blackLevel = b;
    if (whitePoint == 65536)
      whitePoint = m;
    printf("Estimated black:%d, Estimated white: %d\n", blackLevel, whitePoint);
  }
  float f = 65535.0f / (float)(whitePoint - blackLevel);
  scaleValues(f);
}

#if _MSC_VER > 1399 || defined(__SSE2__)

void RawImageData::scaleValues(float f) {
  gboolean use_sse2;
#ifdef _MSC_VER
  int info[4];
  __cpuid(info, 1);
  use_sse2 = !!(info[3]&(1 << 26));
#else
  use_sse2 = TRUE;
#endif

  // Check SSE2
  if (f >= 0.0f && use_sse2) {

    __m128i ssescale;
    __m128i ssesub;
    __m128i sseround;
    __m128i ssesub2;
    __m128i ssesign;
    guint gw = pitch / 16;
    guint i = (int)(1024.0f * f);  // 10 bit fraction
    i |= i << 16;
    guint b = blackLevel | (blackLevel << 16);

    ssescale = _mm_set_epi32(i, i, i, i);
    ssesub = _mm_set_epi32(b, b, b, b);
    sseround = _mm_set_epi32(512, 512, 512, 512);
    ssesub2 = _mm_set_epi32(32768, 32768, 32768, 32768);
    ssesign = _mm_set_epi32(0x80008000, 0x80008000, 0x80008000, 0x80008000);

    for (int y = 0; y < dim.y; y++) {
      __m128i* pixel = (__m128i*) & data[(mOffset.y+y)*pitch];
      for (guint x = 0 ; x < gw; x++) {
        __m128i pix_high;
        __m128i temp;
        __m128i pix_low = _mm_load_si128(pixel);
        // Subtract black
        pix_low = _mm_subs_epu16(pix_low, ssesub);
        // Multiply the two unsigned shorts and combine it to 32 bit result
        pix_high = _mm_mulhi_epu16(pix_low, ssescale);
        temp = _mm_mullo_epi16(pix_low, ssescale);
        pix_low = _mm_unpacklo_epi16(temp, pix_high);
        pix_high = _mm_unpackhi_epi16(temp, pix_high);
        // Add rounder
        pix_low = _mm_add_epi32(pix_low, sseround);
        pix_high = _mm_add_epi32(pix_high, sseround);
        // Shift down
        pix_low = _mm_srai_epi32(pix_low, 10);
        pix_high = _mm_srai_epi32(pix_high, 10);
        // Subtract to avoid clipping
        pix_low = _mm_sub_epi32(pix_low, ssesub2);
        pix_high = _mm_sub_epi32(pix_high, ssesub2);
        // Pack
        pix_low = _mm_packs_epi32(pix_low, pix_high);
        // Shift sign off
        pix_low = _mm_xor_si128(pix_low, ssesign);
        _mm_store_si128(pixel, pix_low);
        pixel++;
      }
    }
  } else {
    // Not SSE2
    gint gw = dim.x * cpp;
    int scale = (int)(16384.0f * f);  // 14 bit fraction
    for (int y = 0; y < dim.y; y++) {
      gushort *pixel = (gushort*)getData(0, y);
      for (int x = 0 ; x < gw; x++) {
        pixel[x] = clampbits(((pixel[x] - blackLevel) * scale + 8192) >> 14, 16);
      }
    }
  }
}

#else

void RawImageData::scaleValues(float f) {
  gint gw = dim.x * cpp;
  int scale = (int)(16384.0f * f);  // 14 bit fraction
  for (int y = 0; y < dim.y; y++) {
    gushort *pixel = (gushort*)getData(0, y);
    for (int x = 0 ; x < gw; x++) {
      pixel[x] = clampbits(((pixel[x] - blackLevel) * scale + 8192) >> 14, 16);
    }
  }
}

#endif

RawImage::RawImage(RawImageData* p) : p_(p) {
  pthread_mutex_lock(&p_->mymutex);
  ++p_->dataRefCount;
  pthread_mutex_unlock(&p_->mymutex);
}

RawImage::RawImage(const RawImage& p) : p_(p.p_) {
  pthread_mutex_lock(&p_->mymutex);
  ++p_->dataRefCount;
  pthread_mutex_unlock(&p_->mymutex);
}

RawImage::~RawImage() {
  pthread_mutex_lock(&p_->mymutex);
  if (--p_->dataRefCount == 0) {
    pthread_mutex_unlock(&p_->mymutex);
    delete p_;
    return;
  }
  pthread_mutex_unlock(&p_->mymutex);
}

RawImageData* RawImage::operator->() {
  return p_;
}

RawImageData& RawImage::operator*() {
  return *p_;
}

RawImage& RawImage::operator=(const RawImage & p) {
  RawImageData* const old = p_;
  p_ = p.p_;
  ++p_->dataRefCount;
  if (--old->dataRefCount == 0) delete old;
  return *this;
}

} // namespace RawSpeed
<commit_msg>Check if image size is less than 0.<commit_after>#include "StdAfx.h"
#include "RawImage.h"
#include "RawDecoder.h"  // For exceptions
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

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

    http://www.klauspost.com
*/
#if defined(__SSE2__)
#include <emmintrin.h>
#endif

namespace RawSpeed {

RawImageData::RawImageData(void):
    dim(0, 0), bpp(0), isCFA(true),
    blackLevel(-1), whitePoint(65536),
    dataRefCount(0), data(0), cpp(1) {
  pthread_mutex_init(&mymutex, NULL);
  subsampling.x = subsampling.y = 1;
}

RawImageData::RawImageData(iPoint2D _dim, guint _bpc, guint _cpp) :
    dim(_dim), bpp(_bpc),
    blackLevel(-1), whitePoint(65536),
    dataRefCount(0), data(0), cpp(cpp) {
  subsampling.x = subsampling.y = 1;
  createData();
  pthread_mutex_init(&mymutex, NULL);
}

RawImageData::~RawImageData(void) {
  _ASSERTE(dataRefCount == 0);
  if (data)
    _aligned_free(data);
  data = 0;
  mOffset = iPoint2D(0, 0);
  pthread_mutex_destroy(&mymutex);
}

void RawImageData::createData() {
  if (dim.x > 65535 || dim.y > 65535)
    ThrowRDE("RawImageData: Dimensions too large for allocation.");
  if (dim.x <= 0 || dim.y <= 0)
    ThrowRDE("RawImageData: Dimension of one sides is less than 1 - cannot allocate image.");
  if (data)
    ThrowRDE("RawImageData: Duplicate data allocation in createData.");
  pitch = (((dim.x * bpp) + 15) / 16) * 16;
  data = (guchar*)_aligned_malloc(pitch * dim.y, 16);
  if (!data)
    ThrowRDE("RawImageData::createData: Memory Allocation failed.");
}

void RawImageData::destroyData() {
  if (data)
    _aligned_free(data);
  data = 0;
}

void RawImageData::setCpp(guint val) {
  if (data)
    ThrowRDE("RawImageData: Attempted to set Components per pixel after data allocation");
  bpp /= cpp;
  cpp = val;
  bpp *= val;
}

guchar* RawImageData::getData() {
  if (!data)
    ThrowRDE("RawImageData::getData - Data not yet allocated.");
  return &data[mOffset.y*pitch+mOffset.x*bpp];
}

guchar* RawImageData::getData(guint x, guint y) {
  if ((int)x >= dim.x)
    ThrowRDE("RawImageData::getData - X Position outside image requested.");
  if ((int)y >= dim.y) {
    ThrowRDE("RawImageData::getData - Y Position outside image requested.");
  }

  x += mOffset.x;
  y += mOffset.y;

  if (!data)
    ThrowRDE("RawImageData::getData - Data not yet allocated.");

  return &data[y*pitch+x*bpp];
}

void RawImageData::subFrame(iPoint2D offset, iPoint2D new_size) {
  if (!new_size.isThisInside(dim - offset)) {
    printf("WARNING: RawImageData::subFrame - Attempted to create new subframe larger than original size. Crop skipped.\n");
    return;
  }

  mOffset += offset;
  dim = new_size;
}

void RawImageData::scaleBlackWhite() {
  gint gw = (dim.x - 20) * cpp;
  if (blackLevel < 0 || whitePoint == 65536) {  // Estimate
    int b = 65536;
    int m = 0;
    for (int row = 10;row < (dim.y - 10);row++) {
      gushort *pixel = (gushort*)getData(10, row);
      for (int col = 10 ; col < gw ; col++) {
        b = MIN(*pixel, b);
        m = MAX(*pixel, m);
        pixel++;
      }
    }
    if (blackLevel < 0)
      blackLevel = b;
    if (whitePoint == 65536)
      whitePoint = m;
    printf("Estimated black:%d, Estimated white: %d\n", blackLevel, whitePoint);
  }
  float f = 65535.0f / (float)(whitePoint - blackLevel);
  scaleValues(f);
}

#if _MSC_VER > 1399 || defined(__SSE2__)

void RawImageData::scaleValues(float f) {
  gboolean use_sse2;
#ifdef _MSC_VER
  int info[4];
  __cpuid(info, 1);
  use_sse2 = !!(info[3]&(1 << 26));
#else
  use_sse2 = TRUE;
#endif

  // Check SSE2
  if (f >= 0.0f && use_sse2) {

    __m128i ssescale;
    __m128i ssesub;
    __m128i sseround;
    __m128i ssesub2;
    __m128i ssesign;
    guint gw = pitch / 16;
    guint i = (int)(1024.0f * f);  // 10 bit fraction
    i |= i << 16;
    guint b = blackLevel | (blackLevel << 16);

    ssescale = _mm_set_epi32(i, i, i, i);
    ssesub = _mm_set_epi32(b, b, b, b);
    sseround = _mm_set_epi32(512, 512, 512, 512);
    ssesub2 = _mm_set_epi32(32768, 32768, 32768, 32768);
    ssesign = _mm_set_epi32(0x80008000, 0x80008000, 0x80008000, 0x80008000);

    for (int y = 0; y < dim.y; y++) {
      __m128i* pixel = (__m128i*) & data[(mOffset.y+y)*pitch];
      for (guint x = 0 ; x < gw; x++) {
        __m128i pix_high;
        __m128i temp;
        __m128i pix_low = _mm_load_si128(pixel);
        // Subtract black
        pix_low = _mm_subs_epu16(pix_low, ssesub);
        // Multiply the two unsigned shorts and combine it to 32 bit result
        pix_high = _mm_mulhi_epu16(pix_low, ssescale);
        temp = _mm_mullo_epi16(pix_low, ssescale);
        pix_low = _mm_unpacklo_epi16(temp, pix_high);
        pix_high = _mm_unpackhi_epi16(temp, pix_high);
        // Add rounder
        pix_low = _mm_add_epi32(pix_low, sseround);
        pix_high = _mm_add_epi32(pix_high, sseround);
        // Shift down
        pix_low = _mm_srai_epi32(pix_low, 10);
        pix_high = _mm_srai_epi32(pix_high, 10);
        // Subtract to avoid clipping
        pix_low = _mm_sub_epi32(pix_low, ssesub2);
        pix_high = _mm_sub_epi32(pix_high, ssesub2);
        // Pack
        pix_low = _mm_packs_epi32(pix_low, pix_high);
        // Shift sign off
        pix_low = _mm_xor_si128(pix_low, ssesign);
        _mm_store_si128(pixel, pix_low);
        pixel++;
      }
    }
  } else {
    // Not SSE2
    gint gw = dim.x * cpp;
    int scale = (int)(16384.0f * f);  // 14 bit fraction
    for (int y = 0; y < dim.y; y++) {
      gushort *pixel = (gushort*)getData(0, y);
      for (int x = 0 ; x < gw; x++) {
        pixel[x] = clampbits(((pixel[x] - blackLevel) * scale + 8192) >> 14, 16);
      }
    }
  }
}

#else

void RawImageData::scaleValues(float f) {
  gint gw = dim.x * cpp;
  int scale = (int)(16384.0f * f);  // 14 bit fraction
  for (int y = 0; y < dim.y; y++) {
    gushort *pixel = (gushort*)getData(0, y);
    for (int x = 0 ; x < gw; x++) {
      pixel[x] = clampbits(((pixel[x] - blackLevel) * scale + 8192) >> 14, 16);
    }
  }
}

#endif

RawImage::RawImage(RawImageData* p) : p_(p) {
  pthread_mutex_lock(&p_->mymutex);
  ++p_->dataRefCount;
  pthread_mutex_unlock(&p_->mymutex);
}

RawImage::RawImage(const RawImage& p) : p_(p.p_) {
  pthread_mutex_lock(&p_->mymutex);
  ++p_->dataRefCount;
  pthread_mutex_unlock(&p_->mymutex);
}

RawImage::~RawImage() {
  pthread_mutex_lock(&p_->mymutex);
  if (--p_->dataRefCount == 0) {
    pthread_mutex_unlock(&p_->mymutex);
    delete p_;
    return;
  }
  pthread_mutex_unlock(&p_->mymutex);
}

RawImageData* RawImage::operator->() {
  return p_;
}

RawImageData& RawImage::operator*() {
  return *p_;
}

RawImage& RawImage::operator=(const RawImage & p) {
  RawImageData* const old = p_;
  p_ = p.p_;
  ++p_->dataRefCount;
  if (--old->dataRefCount == 0) delete old;
  return *this;
}

} // namespace RawSpeed
<|endoftext|>


<commit_before>9ec670f5-2747-11e6-ac77-e0f84713e7b8<commit_msg>fix for the previous fix<commit_after>9ed42297-2747-11e6-9b42-e0f84713e7b8<|endoftext|>


<commit_before><commit_msg>fix wrong var name<commit_after><|endoftext|>


<commit_before>affbc0d7-2747-11e6-8f5f-e0f84713e7b8<commit_msg>Initial commit.2<commit_after>b015661c-2747-11e6-a693-e0f84713e7b8<|endoftext|>


<commit_before>bfa86628-4b02-11e5-92fc-28cfe9171a43<commit_msg>The previous fix has been fixed<commit_after>bfb51c61-4b02-11e5-8ab7-28cfe9171a43<|endoftext|>


<commit_before>863b9f61-4b02-11e5-8214-28cfe9171a43<commit_msg>For bobby to integrate at some point<commit_after>86489dfa-4b02-11e5-b5b1-28cfe9171a43<|endoftext|>


<commit_before>#include <zmq.hpp>
#include <string>
#include <iostream>
#include "main.hpp"
#include "server_interface.hpp"
#include "control.hpp"

int main(int argc, char* argv[]) {
	if (argc != 3) {
		std::cout << "ERROR: Usage <server> <match token>" << std::endl;
		return 0;
	}

    // Parses command line arguments
	std::string protocol (PROTOCOL);
	std::string commandPort (COMMAND_PORT);
	std::string statePort (STATE_PORT);
	std::string ip (argv[1]);
	std::string matchToken (argv[2]);
	std::string commandServer = protocol + ip + commandPort;
	std::string stateServer = protocol + ip + statePort;

    // Create zmq context
	zmq::context_t context(1);

    // Create and initializes server interface
    ServerInterface si (context, commandServer, stateServer, matchToken);
    si.Initialize();

	return 0;
}

<commit_msg>Added call to Control::Execute in main<commit_after>#include <zmq.hpp>
#include <string>
#include <iostream>
#include "main.hpp"
#include "server_interface.hpp"
#include "control.hpp"

int main(int argc, char* argv[]) {
	if (argc != 3) {
		std::cout << "ERROR: Usage <server> <match token>" << std::endl;
		return 0;
	}

    // Parses command line arguments
	std::string protocol (PROTOCOL);
	std::string commandPort (COMMAND_PORT);
	std::string statePort (STATE_PORT);
	std::string ip (argv[1]);
	std::string matchToken (argv[2]);
	std::string commandServer = protocol + ip + commandPort;
	std::string stateServer = protocol + ip + statePort;

    // Create zmq context
	zmq::context_t context(1);

    // Create and initializes server interface
    ServerInterface si (context, commandServer, stateServer, matchToken);
    si.Initialize();

    Control top (context, si);
    top.Execute();

	return 0;
}

<|endoftext|>


<commit_before>9cee2bb5-2747-11e6-91b3-e0f84713e7b8<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>9cfe33cf-2747-11e6-b2a3-e0f84713e7b8<|endoftext|>


<commit_before>5cd8fcf8-ad5c-11e7-94e6-ac87a332f658<commit_msg>updated some files<commit_after>5d6ad447-ad5c-11e7-bd8a-ac87a332f658<|endoftext|>


<commit_before>
#include <math.h>
#include <mysql++.h>
#include <ssqls.h>
#include <iostream>
#include "unit.h"
#include "plant.h"
#include <vector>
#include <iterator>
#include <SFML\Graphics.hpp>
#include <SFML\System.hpp>
#include <thread>
#include <iomanip>

using namespace std;

float f_lenght(sf::Vector2f, sf::Vector2f);
string to_string(int );

sql_create_4( U1, 4,1, mysqlpp::sql_float, x, mysqlpp::sql_float, y, mysqlpp::sql_int, t, mysqlpp::sql_bool, life)
mysqlpp::Connection con( "cpp", "localhost", "tdb_user", "tdb_password" );
mysqlpp::Query query = con.query();
sf::Clock Clock2;   int time2; int real_time = 0;   string ShowCurrentTime;
int passed_time;

bool stored = false;

int main()
{

    int u_id = 1; // ñ÷¸ò÷èê îñîáåé (èèè èõ èäåíòèôèêàòîð)
    int u_number = 8; // êîëè÷åñòâî ïîÿâëÿþùèõñÿ îñîáåé
    int p_id = 1;   // ñ÷¸ò÷èê ðàñòåíèé (èèè èõ èäåíòèôèêàòîð)
    int p_number = 100;   // êîëè÷åñòâî ïîÿâëÿþùèõñÿ ðàñòåíèé
    bool rlbck = false;
    sf::Clock clock1;   float time1;    // âðåìÿ âðåìå÷êî
    float rand_time = 4 + rand()%2;

    std::vector<Unit>::iterator uit;    // ñ÷¸ò÷èê ýëåìåíòîâ äèíàìè÷åñêîãî ìàññèâà uit
    std::vector<Unit>::iterator ujt;    // ñ÷åò÷èê ýëåìåíòîâ äèíàìè÷åñêîãî ìàññèâà äëÿ ñðàâíåíèÿ Unitîâ ìåæäó ñîáîé
    std::vector<int>::iterator udt;     // ñ÷åò÷èê ýëåìåíòîâ äèíàìè÷åñêîãî ìàññèâà ID îñîáåé íà óäàëåíèå èç ìàññèâà
    std::vector<int>::iterator pdt;     // ñ÷åò÷èê ýëåìåíòîâ äèíàìè÷åñêîãî ìàññèâà ID ðàñòåíèé íà óäàëåíèå èõ æå. ÍÅÃÎÄÍÈÊÎÂ!
    std::vector<Unit> units;        // äèíàìè÷åñêèé ìàññèâ Unitîâ
    std::vector<Unit> units_1;
    std::vector<int> unitsDelete;
    std::vector<int> plantsDelete;

    std::vector<Plant>::iterator pit;
    std::vector<Plant> plants;

    srand( time( 0 ) );
    Unit u1;
    Plant p1;

    sf::RenderWindow window(sf::VideoMode(800, 600), "Bio shit stuff", sf::Style::Close|sf::Style::Titlebar);
    window.setFramerateLimit(60);
    window.setVerticalSyncEnabled(1);
    window.setKeyRepeatEnabled(false);

    sf::Text pause; // îïèñàíèå òåêñòà ïàóçû
    sf::Font font;
    font.loadFromFile("1.ttf");
    pause.setFont(font);
    pause.setCharacterSize(30);
    pause.setString("Loading...");
    pause.setPosition(650.f, 0);
    pause.setColor(sf::Color::Black);

    // îïèñàíèå ÷àñîâ, ïîêàçûâàþùèõ âðåìÿ æèçíè
    sf::Text CurrentTime;
    CurrentTime.setFont(font);
    CurrentTime.setCharacterSize(30);
    CurrentTime.setOrigin(0, 0);
    CurrentTime.setColor(sf::Color::Black);
    CurrentTime.setPosition(12.f, 0);

    while (window.isOpen()) {
        sf::Event event;
        window.clear(sf::Color::White);
        while (window.pollEvent(event)) { // îïðîñ ñîáûòèé
            if (event.type == sf::Event::Closed)    {
                query << "DROP DATABASE cpp;";
                query.execute();
                query << "CREATE DATABASE cpp;";
                query.execute();
                window.close();
                return 0;
            }
            if (event.type == sf::Event::KeyPressed && (sf::Keyboard::isKeyPressed(sf::Keyboard::Insert)))   {   // Âîçâðàò íà 22 ñåêóíäó
                //rlbck = !rlbck;                                                                      // ïî íàæàòèþ ïðîáåëà
                if (real_time > 22) {
                    real_time = 22;
                    window.clear(sf::Color::White);
                    for (pit=plants.begin();pit<plants.end();++pit) pit->draw(window);
                    for (uit=units.begin();uit<units.end();++uit) uit->draw(window);
                    window.draw(pause);
                    window.display();
                    for (uit=units.begin();uit<units.end();++uit)   {
                            query << "SELECT * FROM spawnTime WHERE id = " << uit->retUnitId() << "&& time <= 22;";
                            mysqlpp::StoreQueryResult res1 = query.store();
                            if  (!res1.empty()) {
                                query << "SELECT * FROM U" << uit->retUnitId() << " WHERE t = 22;";
                                if ( mysqlpp::UseQueryResult res = query.use())  {
                                    while ( mysqlpp::Row row = res.fetch_row() )    {   cout << uit->retUnitId() << " has it's history on server" << endl;
                                        cout << "Do rollback for " << uit->retUnitId() <<  endl;
                                        uit->RollBack(row["x"], row["y"], row["life"]);
                                    }
                                    query << "DELETE FROM U" << uit->retUnitId() << " WHERE t >= 22;";
                                    query.exec();
                                }
                                else  {
                                    cout << uit->retUnitId() << " doesn't have an answer " << query.error() << endl;
                                }
                            }
                            else    {   cout << "for " << uit->retUnitId() << " we DON'T have data" << endl;
                                query << "DELETE FROM spawnTime WHERE id = " << uit->retUnitId() << ";";
                                query.execute();
                                query << "DROP TABLE U" << uit->retUnitId() << ";";
                                query.execute();
                                unitsDelete.push_back(uit->retUnitId());
                                u_id--;

                            }
                    }
                    for (pit=plants.begin();pit<plants.end();++pit) {
                        query << "SELECT * FROM P WHERE id = " << pit->retPlantId() << ";";
                        if ( mysqlpp::UseQueryResult res = query.use())  {  //cout << "We have something" << endl;
                                int tSpawn, tEaten;
                                while ( mysqlpp::Row row = res.fetch_row() )    {
                                    tSpawn = row["tSpawn"];
                                    tEaten = row["tEaten"];
                                }
                                //cout << "Spawn time = " << tSpawn << " Eaten time = " << tEaten << " where id = " << pit->retPlantId() << endl;
                                if (tSpawn > 22) {
                                    query << "DELETE FROM P WHERE id = " << pit->retPlantId() << ";";
                                    query.execute();
                                    plantsDelete.push_back(pit->retPlantId());  //óäàëåíèå èç ìàññèâà
                                    p_id--;
                                }
                                if ((tSpawn <= 22) && (tEaten > 22))  {
                                    query << "UPDATE P SET tEaten = " << tSpawn << ", life = 1 WHERE id = " << pit->retPlantId() << ";";
                                    query.execute();
                                    pit->RollBack(1);
                                }
                                if ((tSpawn <= 22) && (tEaten < 22))  {
                                    //cout << pit->retPlantId() << " was eaten after this moment" << endl;
                                }
                        }
                        if ( con.errnum()) {
                            cerr << "No result for " << uit->retUnitId() << endl;
                        }
                    }
                    if (!unitsDelete.empty())   {
                        /*cout << "units:";
                        for (uit=units.begin();uit<units.end();++uit)
                            cout << setw(3) << uit->retUnitId();
                        cout << endl << "todel:";
                        for (udt=unitsDelete.begin();udt<unitsDelete.end();++udt)
                            cout << setw(3) << *udt;
                        cout << endl;*/
                        for (uit=units.begin();uit<units.end();uit++)   {
                            for (udt=unitsDelete.begin();udt<unitsDelete.end();++udt)   {
                                if (uit->retUnitId()==*udt)  {
                                    units.erase(uit);
                                }
                            }
                        }
                        unitsDelete.clear();
                        /*cout << "newun:";
                        for (uit=units.begin();uit<units.end();++uit)
                            cout << setw(3) << uit->retUnitId();
                        cout << endl;
                        cout << "delun:";
                        for (udt=unitsDelete.begin();udt<unitsDelete.end();++udt)
                            cout << setw(3) << *udt;
                        cout << endl;*/
                    }
                    if (!plantsDelete.empty())  {
                        /*cout << "plants:";
                        for (pit=plants.begin();pit<plants.end();++pit)
                            cout << setw(3) << pit->retPlantId();
                        cout << endl << "todel:";
                        for (pdt=plantsDelete.begin();pdt<plantsDelete.end();++pdt)
                            cout << setw(3) << *pdt;
                        cout << endl;*/
                        for (pit=plants.begin();pit<plants.end();pit++)   {
                            for (pdt=plantsDelete.begin();pdt<plantsDelete.end();++pdt)   {
                                if (pit->retPlantId()==*pdt)  {
                                    plants.erase(pit);
                                }
                            }
                        }
                        plantsDelete.clear();
                        /*for (pit=plants.begin();pit<plants.end();++pit)
                            cout << setw(3) << pit->retPlantId();
                        cout << "Current number of plants available to spawn is " << p_id << endl;*/
                    }

                    window.display();
                }

            }

        }
        if (!rlbck) {
            time1 = clock1.getElapsedTime().asSeconds();
            if (!units_1.empty())   {
                units.reserve(units_1.size());
                for (uit=units_1.begin();uit<units_1.end();++uit)
                    units.insert(units.end(), *uit);
                units_1.clear();
            }
            if (time1 > rand_time && u_id < u_number) {     // çàïîëíåíèå äèíàìè÷åñêîãî ìàññèâà (âåêòîðà)  ÏÅÐÂÈ×ÍÛÉ ÑÏÀÂÍ N ÎÑÎÁÅÉ
                if (u_id == 1)  {   // ñîçäàåì òàáëèöó ñïàâíà íà ñåðâåðå
                        query <<"CREATE TABLE spawnTime(id int, time int) ENGINE=MEMORY ";
                        query.execute();
                }
                std::cout << u_id << " is ready on " << real_time << " sec" << std::endl;
                u1.gen(u_id, rand()%800, rand()%600, 1);    // ýëåìåíòàìè êëàññà Unit ñ ñëó÷àéíûìè êîîðäèíàòàìè è ïîñëåäîâàòåëüíûì id
                units.push_back(u1);
                clock1.restart();
                //cout << "creating table" << endl;
                query << "CREATE TABLE U" << u_id << "(x float, y float, t int, life bool) ENGINE=MEMORY;";
                query.execute();
                query << "INSERT INTO spawnTime VALUES(" << u_id << ", " << real_time << ");";
                query.execute();
                u_id++;
                rand_time = 4 + rand()%2;

            }

            if (p_id < p_number )    {       //  çàïîëíåíèÿ âåêòîðà ðàñòåíèé îáúåêòà êëàññà plant    ÏÅÐÂÈ×ÍÛÉ ÑÏÀÂÍ N ÐÀÑÒÅÍÈÉ
                float p_x = rand()%1000; float p_y = rand()%800; float k = 1 + rand()%2;
                p1.gen(p_id, p_x, p_y, k);
                plants.push_back(p1);
                if (p_id == 1) {
                    query << "CREATE TABLE IF NOT EXISTS P(id int, x float, y float, tSpawn int, tEaten int, life bool, k float) ENGINE=MEMORY;";
                    query.exec();
                }
                query << "INSERT INTO P VALUES(" << p_id << ", " << p_x << ", " << p_y << ", " << real_time << ", " << real_time << ", "  << 1 << ", " << k << ");";
                query.exec();
                p_id++;
            }

            for (uit=units.begin();uit<units.end();++uit)   {   // ïðîâåðÿåì, ñúåë ëè îáúåêò åäó
                if (uit->search_over()) {   // çàêîí÷èë ïîèñê?
                    for (pit=plants.begin();pit<plants.end();++pit)
                        if (uit->retFoodId()==pit->p_id())  {   // åñëè ID ñúåäåííîãî ñîâïàäàåò ñ ID â ìàññèâå
                            pit->delete_p();    // óáèâàøêè
                            query << "UPDATE P SET tEaten = " << real_time << ", life = 0 WHERE id = " << pit->p_id() << ";";
                            query.execute();
                            //std::cout << "plant's health point = " << pit->retPlantHp() << std::endl;
                            uit->setUnitHp(pit->retPlantHp());  // äîáàâëÿåì HP åäû ê HP îáúåêòà
                            uit->set_over();    // ñáðàñûâàåì ôëàã îêîí÷àíèÿ ïîèñêà
                        }
                }

            }
            for (uit=units.begin();uit<units.end();++uit)   {       //  ãåíåðàöèÿ äåòèøåê
                if (uit->retMakeChildOver())    {
                    for (ujt=units.begin();ujt<units.end();++ujt)   {
                        if (uit->getPartnerId()==ujt->retUnitId())  {
                            uit->setMakeChildOver();
                            ujt->setMakeChildOver();
                            uit->setParentTrue();
                            ujt->setParentTrue();
                            //std::cout << "SUCCEED" << std::endl;
                            u1.gen(u_id, uit->pos().x, uit->pos().y, 2);
                            //std::cout << "PUSHING" << std::endl;
                            //cout << "creating table" << endl;
                            query << "CREATE TABLE U" << u_id << "(x float, y float, t int, life bool) ENGINE=MEMORY;";
                            query.execute();
                            query << "INSERT INTO spawnTime VALUES(" << u_id << ", " << real_time << ");";
                            query.execute();
                            units_1.push_back(u1);
                            u_id++;
                        }
                    }
                }
            }
            for (uit=units.begin();uit<units.end();++uit)   {   // ñðàâíåíèå êîîðäèíàò áëóæäàþùèõ îáúåêòîâ è ñòîÿùèõ ðàñòåíèé
                if (!uit->search_food() && !uit->search_over() && uit->retUnitHp())    {    // åñëè îáúåêò: 1) íå èäåò ê åäå 2) íå åñò 3) çäîðîâüå íå ìàêñèìàëüíîå
                    bool tar = false;   // ôëàã ïðèñóòñòâèÿ â îêðóãå îáúåêòà Unit æåëàííîãî Plant
                    sf::Vector2f t_pos;
                    float lenght = 100;
                    int t_id = 0;
                    for (pit=plants.begin();pit<plants.end();++pit) {   // ñðàâíèâàåì êàæäûé îáúåêò ñî âñåì ñïèñêîì ðàñòåíèé
                        if ((pit->is_alive()) && (f_lenght(pit->pos(), uit->pos()) <= 50) && (f_lenght(pit->pos(), uit->pos()) < lenght))    { //åñëè ðàñòåíèå æèâî
                            t_pos = pit->pos();                             //è îáúåêò íàõîäèòñÿ â 50 ïèêñåëÿõ îò ðàñòåíèÿ è ðàññòîÿíèå äî ðàñòåíèÿ
                            lenght = f_lenght(pit->pos(), uit->pos());      //ÿâëÿåòñÿ ñàìûì ìåíüøèì èç âîçìîæíûõ (âûáèðàåì ñàìûé êîðîòêèé ìàðøðóò)
                            t_id = pit->p_id();                             // òî çàïîìèíàåì êîîðäèíàòó, äëèíó è id ðàñòåíèÿ
                            tar = true;                                     // óñòàíàâëèâàåì ôëàã íàëè÷èÿ õîòÿ áû îäíîãî îáúåêòà â 1
                        }
                    }
                    if (tar) uit->food(t_id, t_pos);  // åñëè â îêðóãå ñóùåñòâóåò ðàñòåíèå, òî ïåðåäàåì îáúåêòó id è êîîðäèíàòû ëó÷øåãî âàðèàíòà
                }
            }

            for (uit=units.begin();uit<units.end();++uit)   {   // Ñðàâíåíèå îáúåêòîâ ìåæäó ñîáîé: åñëè æèâû, âçðîñëû, çäîðîâû è íå ÿâëÿòñÿ ðîäèòåëåì
                if (uit->isUnitOld() && (!uit->retMakeChild()) && (uit->is_alive()) && (!uit->retUnitHp()) && (!uit->retUnitParent())) {
                    bool tar = false;
                    sf::Vector2f t_pos;
                    float lenght = 100;
                    int t_id = 0;
                    for (ujt=units.begin();ujt<units.end();++ujt) {
                        if (uit->isUnitOld() && (!ujt->retMakeChild()) && (uit->retUnitId() != ujt->retUnitId()) && (ujt->is_alive()) && (!ujt->retUnitHp()) && (!ujt->retUnitParent())
                               && (f_lenght(ujt->pos(), uit->pos()) <= 30) && (f_lenght(ujt->pos(), uit->pos()) < lenght))  {
                            t_pos = ujt->pos();
                            lenght = f_lenght(ujt->pos(), uit->pos());
                            t_id = ujt->retUnitId();
                            tar = true;
                        }

                    }
                    if (tar)    {    std::cout << uit->retUnitId() << " and " << t_id << std::endl;
                        uit->child(t_id, t_pos);
                        for (ujt=units.begin();ujt<units.end();++ujt)   {
                            if (ujt->retUnitId() == t_id)
                                ujt->child(uit->retUnitId(), uit->pos());
                        }

                    }
                }
            }

            time2 = Clock2.getElapsedTime().asSeconds();
            for (pit=plants.begin();pit<plants.end();++pit)    {    // âûáèðàåì ýëåìåíò ìàññèâà ðàñòåíèé
                pit->draw(window);                          // îòðèñîâûâàåì
            }
            for (uit=units.begin();uit<units.end();++uit)  {   // âûáèðàåì ýëåìåíò ìàññèâà îñîáåé (îáúåêòîâ)
                uit->draw(window);       // îòðèñîâûâàåì åãî
                if (time2>=1)   {
                    //query << "CREATE TABLE IF NOT EXISTS U" << uit->retUnitId() << "(x float, y float, t int, life bool) ENGINE=MEMORY; ";
                    //query.exec();
                    query << "INSERT INTO U" << uit->retUnitId() << " VALUES(" << uit->pos().x << ", " << uit->pos().y << ", " << real_time << ", " << uit->is_alive() << ");";
                    query.exec();
                }
            }

            if (time2>=1) {
                //cout << "Current number of Units is " << u_id - 1 << " and spawnmax is " << u_number << endl;
                real_time++;
                Clock2.restart();
            }

            ShowCurrentTime = to_string(real_time);
            CurrentTime.setString(ShowCurrentTime);
            window.draw(CurrentTime);
            window.display();
        }   // ãëîáàëüíàÿ îòðèñîâêà âñåõ ýëåìåíòîâ
    }
    return EXIT_SUCCESS;
}

float f_lenght(sf::Vector2f t_pos, sf::Vector2f u_pos)    {
    sf::Vector2f direction = t_pos - u_pos;
    return sqrt(direction.x*direction.x + direction.y*direction.y);
}

string to_string(int param)
{
    string str = "";
    stringstream ss;
    ss<<param;
    getline(ss, str);
    return str;
}
<commit_msg>Delete main.cpp<commit_after><|endoftext|>


<commit_before>#include <QApplication>
#include <QCompleter>
#include <QKeySequence>
#include <QLineEdit>
#include <QMainWindow>
#include <QMessageLogger>
#include <QShortcut>
#include <QStandardPaths>
#include <QStringListModel>
#include <QVBoxLayout>
#include <QWebEngineView>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>
#include <qtwebengineglobal.h>

#define HOMEPAGE       "http://google.com"
#define SEARCH_ENGINE  "http://google.com/search?q=%1"

#define SHORTCUT_META     (Qt::CTRL)

#define SHORTCUT_FORWARD  (SHORTCUT_META + Qt::Key_I)
#define SHORTCUT_BACK     (SHORTCUT_META + Qt::Key_O)
#define SHORTCUT_BAR      (SHORTCUT_META + Qt::Key_Colon)
#define SHORTCUT_DOWN     (SHORTCUT_META + Qt::Key_J)
#define SHORTCUT_UP       (SHORTCUT_META + Qt::Key_K)
#define SHORTCUT_LEFT     (SHORTCUT_META + Qt::Key_H)
#define SHORTCUT_RIGHT    (SHORTCUT_META + Qt::Key_L)
#define SHORTCUT_ZOOMIN   (SHORTCUT_META + Qt::Key_Plus)
#define SHORTCUT_ZOOMOUT  (SHORTCUT_META + Qt::Key_Minus)

#define SCROLL_STEP_X  "20"
#define SCROLL_STEP_Y  "20"
#define ZOOM_STEP      0.1

QMessageLogger logger;

enum QueryType {
    URLWithScheme,
    URLWithoutScheme,
    SearchWithScheme,
    SearchWithoutScheme
};

QueryType GuessQueryType(const QString &str) {
    static const QRegExp hasScheme("^[a-zA-Z0-9]+://");
    static const QRegExp address("^[^/]+(\\.[^/]+|:[0-9]+)");

    if (str.startsWith("search:")) {
        return SearchWithScheme;
    } else if (hasScheme.indexIn(str) != -1) {
        return URLWithScheme;
    } else if (address.indexIn(str) != -1) {
        return URLWithoutScheme;
    } else {
        return SearchWithoutScheme;
    }
}

class TortaDatabase {
private:
    QSqlDatabase db;
    QSqlQuery append;
    QSqlQuery search;

public:
    TortaDatabase() : db(QSqlDatabase::addDatabase("QSQLITE")), append(db), search(db) {
        db.setDatabaseName(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/db");
        db.open();

        QSqlQuery(db).exec("CREATE TABLE IF NOT EXISTS history (timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, scheme TEXT NOT NULL, url TEXT NOT NULL)");

        append.prepare("INSERT INTO history (scheme, url) values (?, ?)");
        append.setForwardOnly(true);

        search.prepare("SELECT scheme || ':' || url FROM history WHERE url LIKE ? GROUP BY url ORDER BY COUNT(timestamp)");
        search.setForwardOnly(true);
    }

    ~TortaDatabase() {
        db.close();
    }

    void appendHistory(const QUrl &url) {
        append.bindValue(0, url.scheme());
        append.bindValue(1, url.url().right(url.url().length() - url.scheme().length() - 1));
        append.exec();
    }

    QStringList searchHistory(QString query) {
        QStringList r;

        search.bindValue(0, "%%" + query.replace("%%", "\\%%") + "%%");
        search.exec();
        while (search.next()) {
            r << search.value(0).toString();
        }

        return r;
    }
};

class TortaCompleter : public QCompleter {
Q_OBJECT

private:
    QStringListModel model;
    TortaDatabase &db;

public:
    TortaCompleter(QLineEdit *line, TortaDatabase &db, QObject *parent=0) : QCompleter(parent), db(db) {
        setModel(&model);
        setCompletionMode(QCompleter::UnfilteredPopupCompletion);
        setModelSorting(QCompleter::CaseInsensitivelySortedModel);
        setCaseSensitivity(Qt::CaseInsensitive);

        connect(line, &QLineEdit::textChanged, this, &TortaCompleter::update);
    }

signals:
private slots:
    void update(const QString &word) {
        QStringList list;
        auto type = GuessQueryType(word);
        if (type == SearchWithoutScheme) {
            list << "http://" + word;
        } else if (type == URLWithoutScheme) {
            list << "search:" + word;
        }
        list << db.searchHistory(word);
        model.setStringList(list);
    }
};

class DobosTorta : public QMainWindow {
Q_OBJECT

private:
    QLineEdit bar;
    QWebEngineView view;
    TortaDatabase db;

    void setShortcuts() {
        connect(new QShortcut(QKeySequence(SHORTCUT_FORWARD), this), &QShortcut::activated, &view, &QWebEngineView::forward);
        connect(new QShortcut(QKeySequence(Qt::ALT + Qt::Key_Right), this), &QShortcut::activated, &view, &QWebEngineView::forward);
        connect(new QShortcut(QKeySequence(SHORTCUT_BACK), this), &QShortcut::activated, &view, &QWebEngineView::back);
        connect(new QShortcut(QKeySequence(Qt::ALT + Qt::Key_Left), this), &QShortcut::activated, &view, &QWebEngineView::back);

        connect(new QShortcut(QKeySequence(SHORTCUT_BAR), this), &QShortcut::activated, this, &DobosTorta::toggleBar);

        connect(new QShortcut(QKeySequence(SHORTCUT_DOWN), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(0, " SCROLL_STEP_Y ")"); });
        connect(new QShortcut(QKeySequence(Qt::Key_Down), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(0, " SCROLL_STEP_Y ")"); });
        connect(new QShortcut(QKeySequence(SHORTCUT_UP), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(0, -" SCROLL_STEP_Y ")"); });
        connect(new QShortcut(QKeySequence(Qt::Key_Up), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(0, -" SCROLL_STEP_Y ")"); });
        connect(new QShortcut(QKeySequence(SHORTCUT_RIGHT), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(" SCROLL_STEP_X ", 0)"); });
        connect(new QShortcut(QKeySequence(Qt::Key_Right), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(" SCROLL_STEP_X ", 0)"); });
        connect(new QShortcut(QKeySequence(SHORTCUT_LEFT), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(-" SCROLL_STEP_X ", 0)"); });
        connect(new QShortcut(QKeySequence(Qt::Key_Left), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(-" SCROLL_STEP_X ", 0)"); });

        connect(new QShortcut(QKeySequence(Qt::Key_PageDown), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(0, window.innerHeight / 2)"); });
        connect(new QShortcut(QKeySequence(Qt::Key_PageUp), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(0, -window.innerHeight / 2)"); });

        connect(new QShortcut(QKeySequence(SHORTCUT_ZOOMIN), this), &QShortcut::activated, [&](){ view.setZoomFactor(view.zoomFactor() + ZOOM_STEP); });
        connect(new QShortcut(QKeySequence(SHORTCUT_ZOOMOUT), this), &QShortcut::activated, [&](){ view.setZoomFactor(view.zoomFactor() - ZOOM_STEP); });
    }

    void setupBar() {
        connect(&bar, &QLineEdit::returnPressed, this, &DobosTorta::executeBar);

        bar.setCompleter(new TortaCompleter(&bar, db, this));

        setMenuWidget(&bar);
    }

    void setupView() {
        connect(&view, &QWebEngineView::titleChanged, this, &QWidget::setWindowTitle);
        connect(&view, &QWebEngineView::urlChanged, this, &DobosTorta::urlChanged);
        connect(view.page(), &QWebEnginePage::linkHovered, this, &DobosTorta::linkHovered);
        connect(view.page(), &QWebEnginePage::iconChanged, this, &DobosTorta::setWindowIcon);

        view.load(QUrl(HOMEPAGE));

        setCentralWidget(&view);
    }

public:
    DobosTorta() : bar(HOMEPAGE, this), view(this) {
        setupBar();
        setupView();
        setShortcuts();
    }

signals:
private slots:
    void executeBar() {
        QString query(bar.text());

        switch (GuessQueryType(query)) {
        case URLWithScheme:
            view.load(query);
            break;
        case URLWithoutScheme:
            view.load("http://" + query);
            break;
        case SearchWithScheme:
            view.load(QString(SEARCH_ENGINE).arg(query.right(query.length() - 7)));
            break;
        case SearchWithoutScheme:
            view.load(QString(SEARCH_ENGINE).arg(query));
            break;
        }
    }

    void linkHovered(const QUrl &url) {
        auto str(url.toDisplayString());

        if (str.length() == 0) {
            setWindowTitle(view.title());
        } else {
            setWindowTitle(str);
        }
    }

    void urlChanged(const QUrl &url) {
        bar.setText(url.toString());
        db.appendHistory(url);
    }

    void toggleBar() {
        if (!bar.hasFocus()) {
            bar.setFocus();
            bar.selectAll();
        } else {
            view.setFocus();
        }
    }
};

int main(int argc, char **argv) {
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);

    QtWebEngine::initialize();

    DobosTorta window;
    window.show();

    return app.exec();
}

#include "main.moc"
<commit_msg>Set User-Agent<commit_after>#include <QApplication>
#include <QCompleter>
#include <QKeySequence>
#include <QLineEdit>
#include <QMainWindow>
#include <QMessageLogger>
#include <QShortcut>
#include <QStandardPaths>
#include <QStringListModel>
#include <QVBoxLayout>
#include <QWebEngineProfile>
#include <QWebEngineView>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <qtwebengineglobal.h>

#define HOMEPAGE       "http://google.com"
#define SEARCH_ENGINE  "http://google.com/search?q=%1"

#define SHORTCUT_META     (Qt::CTRL)

#define SHORTCUT_FORWARD  (SHORTCUT_META + Qt::Key_I)
#define SHORTCUT_BACK     (SHORTCUT_META + Qt::Key_O)
#define SHORTCUT_BAR      (SHORTCUT_META + Qt::Key_Colon)
#define SHORTCUT_DOWN     (SHORTCUT_META + Qt::Key_J)
#define SHORTCUT_UP       (SHORTCUT_META + Qt::Key_K)
#define SHORTCUT_LEFT     (SHORTCUT_META + Qt::Key_H)
#define SHORTCUT_RIGHT    (SHORTCUT_META + Qt::Key_L)
#define SHORTCUT_ZOOMIN   (SHORTCUT_META + Qt::Key_Plus)
#define SHORTCUT_ZOOMOUT  (SHORTCUT_META + Qt::Key_Minus)

#define SCROLL_STEP_X  "20"
#define SCROLL_STEP_Y  "20"
#define ZOOM_STEP      0.1

QMessageLogger logger;

enum QueryType {
    URLWithScheme,
    URLWithoutScheme,
    SearchWithScheme,
    SearchWithoutScheme
};

QueryType GuessQueryType(const QString &str) {
    static const QRegExp hasScheme("^[a-zA-Z0-9]+://");
    static const QRegExp address("^[^/]+(\\.[^/]+|:[0-9]+)");

    if (str.startsWith("search:")) {
        return SearchWithScheme;
    } else if (hasScheme.indexIn(str) != -1) {
        return URLWithScheme;
    } else if (address.indexIn(str) != -1) {
        return URLWithoutScheme;
    } else {
        return SearchWithoutScheme;
    }
}

class TortaDatabase {
private:
    QSqlDatabase db;
    QSqlQuery append;
    QSqlQuery search;

public:
    TortaDatabase() : db(QSqlDatabase::addDatabase("QSQLITE")), append(db), search(db) {
        db.setDatabaseName(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/db");
        db.open();

        QSqlQuery(db).exec("CREATE TABLE IF NOT EXISTS history (timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, scheme TEXT NOT NULL, url TEXT NOT NULL)");

        append.prepare("INSERT INTO history (scheme, url) values (?, ?)");
        append.setForwardOnly(true);

        search.prepare("SELECT scheme || ':' || url FROM history WHERE url LIKE ? GROUP BY url ORDER BY COUNT(timestamp)");
        search.setForwardOnly(true);
    }

    ~TortaDatabase() {
        db.close();
    }

    void appendHistory(const QUrl &url) {
        append.bindValue(0, url.scheme());
        append.bindValue(1, url.url().right(url.url().length() - url.scheme().length() - 1));
        append.exec();
    }

    QStringList searchHistory(QString query) {
        QStringList r;

        search.bindValue(0, "%%" + query.replace("%%", "\\%%") + "%%");
        search.exec();
        while (search.next()) {
            r << search.value(0).toString();
        }

        return r;
    }
};

class TortaCompleter : public QCompleter {
Q_OBJECT

private:
    QStringListModel model;
    TortaDatabase &db;

public:
    TortaCompleter(QLineEdit *line, TortaDatabase &db, QObject *parent=0) : QCompleter(parent), db(db) {
        setModel(&model);
        setCompletionMode(QCompleter::UnfilteredPopupCompletion);
        setModelSorting(QCompleter::CaseInsensitivelySortedModel);
        setCaseSensitivity(Qt::CaseInsensitive);

        connect(line, &QLineEdit::textChanged, this, &TortaCompleter::update);
    }

signals:
private slots:
    void update(const QString &word) {
        QStringList list;
        auto type = GuessQueryType(word);
        if (type == SearchWithoutScheme) {
            list << "http://" + word;
        } else if (type == URLWithoutScheme) {
            list << "search:" + word;
        }
        list << db.searchHistory(word);
        model.setStringList(list);
    }
};

class DobosTorta : public QMainWindow {
Q_OBJECT

private:
    QLineEdit bar;
    QWebEngineView view;
    TortaDatabase db;

    void setShortcuts() {
        connect(new QShortcut(QKeySequence(SHORTCUT_FORWARD), this), &QShortcut::activated, &view, &QWebEngineView::forward);
        connect(new QShortcut(QKeySequence(Qt::ALT + Qt::Key_Right), this), &QShortcut::activated, &view, &QWebEngineView::forward);
        connect(new QShortcut(QKeySequence(SHORTCUT_BACK), this), &QShortcut::activated, &view, &QWebEngineView::back);
        connect(new QShortcut(QKeySequence(Qt::ALT + Qt::Key_Left), this), &QShortcut::activated, &view, &QWebEngineView::back);

        connect(new QShortcut(QKeySequence(SHORTCUT_BAR), this), &QShortcut::activated, this, &DobosTorta::toggleBar);

        connect(new QShortcut(QKeySequence(SHORTCUT_DOWN), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(0, " SCROLL_STEP_Y ")"); });
        connect(new QShortcut(QKeySequence(Qt::Key_Down), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(0, " SCROLL_STEP_Y ")"); });
        connect(new QShortcut(QKeySequence(SHORTCUT_UP), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(0, -" SCROLL_STEP_Y ")"); });
        connect(new QShortcut(QKeySequence(Qt::Key_Up), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(0, -" SCROLL_STEP_Y ")"); });
        connect(new QShortcut(QKeySequence(SHORTCUT_RIGHT), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(" SCROLL_STEP_X ", 0)"); });
        connect(new QShortcut(QKeySequence(Qt::Key_Right), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(" SCROLL_STEP_X ", 0)"); });
        connect(new QShortcut(QKeySequence(SHORTCUT_LEFT), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(-" SCROLL_STEP_X ", 0)"); });
        connect(new QShortcut(QKeySequence(Qt::Key_Left), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(-" SCROLL_STEP_X ", 0)"); });

        connect(new QShortcut(QKeySequence(Qt::Key_PageDown), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(0, window.innerHeight / 2)"); });
        connect(new QShortcut(QKeySequence(Qt::Key_PageUp), this), &QShortcut::activated, [&](){ view.page()->runJavaScript("window.scrollBy(0, -window.innerHeight / 2)"); });

        connect(new QShortcut(QKeySequence(SHORTCUT_ZOOMIN), this), &QShortcut::activated, [&](){ view.setZoomFactor(view.zoomFactor() + ZOOM_STEP); });
        connect(new QShortcut(QKeySequence(SHORTCUT_ZOOMOUT), this), &QShortcut::activated, [&](){ view.setZoomFactor(view.zoomFactor() - ZOOM_STEP); });
    }

    void setupBar() {
        connect(&bar, &QLineEdit::returnPressed, this, &DobosTorta::executeBar);

        bar.setCompleter(new TortaCompleter(&bar, db, this));

        setMenuWidget(&bar);
    }

    void setupView() {
        connect(&view, &QWebEngineView::titleChanged, this, &QWidget::setWindowTitle);
        connect(&view, &QWebEngineView::urlChanged, this, &DobosTorta::urlChanged);
        connect(view.page(), &QWebEnginePage::linkHovered, this, &DobosTorta::linkHovered);
        connect(view.page(), &QWebEnginePage::iconChanged, this, &DobosTorta::setWindowIcon);

        view.page()->profile()->setHttpUserAgent("DobosTorta");

        view.load(QUrl(HOMEPAGE));

        setCentralWidget(&view);
    }

public:
    DobosTorta() : bar(HOMEPAGE, this), view(this) {
        setupBar();
        setupView();
        setShortcuts();
    }

signals:
private slots:
    void executeBar() {
        QString query(bar.text());

        switch (GuessQueryType(query)) {
        case URLWithScheme:
            view.load(query);
            break;
        case URLWithoutScheme:
            view.load("http://" + query);
            break;
        case SearchWithScheme:
            view.load(QString(SEARCH_ENGINE).arg(query.right(query.length() - 7)));
            break;
        case SearchWithoutScheme:
            view.load(QString(SEARCH_ENGINE).arg(query));
            break;
        }
    }

    void linkHovered(const QUrl &url) {
        auto str(url.toDisplayString());

        if (str.length() == 0) {
            setWindowTitle(view.title());
        } else {
            setWindowTitle(str);
        }
    }

    void urlChanged(const QUrl &url) {
        bar.setText(url.toString());
        db.appendHistory(url);
    }

    void toggleBar() {
        if (!bar.hasFocus()) {
            bar.setFocus();
            bar.selectAll();
        } else {
            view.setFocus();
        }
    }
};

int main(int argc, char **argv) {
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);

    QtWebEngine::initialize();

    DobosTorta window;
    window.show();

    return app.exec();
}

#include "main.moc"
<|endoftext|>