<commit_before>#include "sgct.h"
#include "ParticleSystem.h"
#include "Snow.h"
#include "World.h"
#include "HelperFunctions.h"
#include "Field.h"
#include "Gravity.h"
#include "Wind.h"
#include "ObjSystem.h"
#include "SoapBubble.h"
#include "Vortex.h"
#include <iostream>

//our beautiful global variables
sgct::Engine* gEngine;
Snow* gParticles;
World* gWorld;
Object* gObject;
SoapBubble* gBubble;
Wind* wind;
Gravity* grav;

sgct::SharedBool showStats(false);
sgct::SharedBool showGraph(false);
sgct::SharedDouble sizeFactorX(0.0);
sgct::SharedDouble sizeFactorY(0.0);
sgct::SharedDouble sizeFactorZ(0.0);
sgct::SharedDouble gravFactor(0.0);
sgct::SharedDouble curr_time(0.0);

void initialize();
void draw();
void myPreSyncFun();
void myPostSyncPreDrawFun();
void myEncodeFun();
void myDecodeFun();
void externalControlCallback(const char * receivedChars, int size, int clientId);

int main(int argc, char *argv[])
{
	initRandom();

	gEngine = new sgct::Engine(argc, argv);

	gEngine->setInitOGLFunction(initialize);
	gEngine->setDrawFunction(draw);
	gEngine->setPreSyncFunction(myPreSyncFun);
	gEngine->setPostSyncPreDrawFunction(myPostSyncPreDrawFun);
	gEngine->setExternalControlCallback(externalControlCallback);

	sgct::SharedData::instance()->setEncodeFunction(myEncodeFun);
	sgct::SharedData::instance()->setDecodeFunction(myDecodeFun);

	gParticles = new Snow(gEngine);
	gWorld = new World(gEngine);
	gBubble = new SoapBubble(gEngine);

	gObject = new Object(gEngine);

	grav = new Gravity();
	grav->init(-9.81f);
	gParticles->addField(grav);

	wind = new Wind();
	//wind->init(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2));
	wind->setAcceleration(0.0f, 0.0f, 0.0f);
	gParticles->addField(wind);

	Vortex* turbine = new Vortex();
	//turbine->init(0.0f, -4.0f, 5.0f);
	//turbine->setForce(-10.0f, 0.0f, -1.0f);
	//gParticles->addField(turbine);

	cout << "---- Fields active on gParticles ----" << endl;
	gParticles->printFields();
	cout << "---------------" << endl << endl;

	if(!gEngine->init(sgct::Engine::OpenGL_3_3_Core_Profile))
	{
		delete gEngine;
		return EXIT_FAILURE;
	}

	gEngine->render();

	gParticles->destroy();
	gObject->deleteObject();
	delete gObject;
	delete gEngine;
	delete gParticles;
	delete gWorld;
	delete gBubble;

	exit(EXIT_SUCCESS);
}

void initialize()
{
	if(!gParticles->initialize())
	{
		std::cout << "Error Initialzing Particle System:" << std::endl;
		exit(EXIT_FAILURE);
	}
	gWorld->initializeWorld();

	//gObject->initialize();
	gObject->loadObj("road/road.obj");
	gObject->scale(0.2f,0.2f,0.2f);
	gObject->translate(0.0f, -2.0f, 5.0f);

	gBubble->createSphere(1.5f, 100);
}

void draw()
{
	double delta = gEngine->getDt();

	gWorld->drawWorld();
	gBubble->drawBubble();
	//gObject->draw();
	gParticles->move(delta);
	gParticles->draw(delta);

}

//Checking the time since the program started, not sure if we need this either.
void myPreSyncFun()
{
	//Checks so the gEnginenode is actually the master.
	if( gEngine->isMaster() )
	{
		//Sets the current time since the program started
		curr_time.setVal(sgct::Engine::getTime());
	}
}

//Shows stats and graph depending on if the variables are true or not. Dont know if we need this?
void myPostSyncPreDrawFun()
{
	//gEngine->setDisplayInfoVisibility(&showStats);
	//gEngine->setStatsGraphVisibility(&showGraph);
}

//Encodes the data sent from GUI
void myEncodeFun()
{
	sgct::SharedData::instance()->writeDouble(&curr_time);
	sgct::SharedData::instance()->writeDouble(&sizeFactorX);
	sgct::SharedData::instance()->writeDouble(&sizeFactorY);
	sgct::SharedData::instance()->writeDouble(&sizeFactorZ);
	sgct::SharedData::instance()->writeDouble(&gravFactor);
	sgct::SharedData::instance()->writeBool(&showStats);
	sgct::SharedData::instance()->writeBool(&showGraph);
}

//Decodes the data sent from GUI
void myDecodeFun()
{
	sgct::SharedData::instance()->readDouble(&curr_time);
	sgct::SharedData::instance()->readDouble(&sizeFactorX);
	sgct::SharedData::instance()->readDouble(&sizeFactorY);
	sgct::SharedData::instance()->readDouble(&sizeFactorZ);
	sgct::SharedData::instance()->readDouble(&gravFactor);
	sgct::SharedData::instance()->readBool(&showStats);
	sgct::SharedData::instance()->readBool(&showGraph);
}

//Used to alter certain values when sent from GUI. This way we can alter the fields or change gravity in realtime!
void externalControlCallback(const char * receivedChars, int size, int clientId)
{
	//Checks so the gEnginenode is actually the master.
	if(gEngine->isMaster())
	{
		//Compares the length of the strings so no weird runtime errors occur
		if(size == 7 &&  strncmp(receivedChars, "stats", 5) == 0)
		{
			showStats.setVal(true);
		}

		else if(size == 7 &&  strncmp(receivedChars, "graph", 5) == 0)
		{
			showGraph.setVal(true);
		}

		else if(size >= 6 && strncmp(receivedChars, "winX", 4) == 0)
		{
			//We need an int.
			int tmpValX = atoi(receivedChars + 5);

			sizeFactorX.setVal(tmpValX);
			wind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
			cout << sizeFactorX.getVal();
		}

		else if(size >= 6 && strncmp(receivedChars, "winY", 4) == 0)
		{
			//We need an int.
			int tmpValY = atoi(receivedChars + 5);

			sizeFactorY.setVal(tmpValY);
			wind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
			cout << sizeFactorY.getVal();
		}

		else if(size >= 6 && strncmp(receivedChars, "winZ", 4) == 0)
		{
			//We need an int.
			int tmpValZ = atoi(receivedChars + 5);

			sizeFactorZ.setVal(tmpValZ);
			wind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
			cout << sizeFactorZ.getVal();
		}

		else if(size >= 6 && strncmp(receivedChars, "grav", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			grav->init(tmpVal);
		}
	}
}
<commit_msg>Started implementing turbine in remotegui<commit_after>#include "sgct.h"
#include "ParticleSystem.h"
#include "Snow.h"
#include "World.h"
#include "HelperFunctions.h"
#include "Field.h"
#include "Gravity.h"
#include "Wind.h"
#include "ObjSystem.h"
#include "SoapBubble.h"
#include "Vortex.h"
#include <iostream>

//our beautiful global variables
sgct::Engine* gEngine;
Snow* gParticles;
World* gWorld;
Object* gObject;
SoapBubble* gBubble;
Wind* gWind;
Gravity* gGrav;
Vortex* gTurbine;

sgct::SharedBool windBox(false);
sgct::SharedBool vortexBox(false);
sgct::SharedDouble sizeFactorX(0.0);
sgct::SharedDouble sizeFactorY(0.0);
sgct::SharedDouble sizeFactorZ(0.0);
sgct::SharedDouble gravFactor(0.0);
sgct::SharedDouble vortexPosX(0.0);
sgct::SharedDouble vortexPosY(0.0);
sgct::SharedDouble vortexPosZ(0.0);
sgct::SharedDouble curr_time(0.0);

void initialize();
void draw();
void myPreSyncFun();
void statsDrawfun();
void myEncodeFun();
void myDecodeFun();
void externalControlCallback(const char * receivedChars, int size, int clientId);

int main(int argc, char *argv[])
{
	initRandom();

	gEngine = new sgct::Engine(argc, argv);

	gEngine->setInitOGLFunction(initialize);
	gEngine->setDrawFunction(draw);
	gEngine->setPreSyncFunction(myPreSyncFun);
	gEngine->setPostSyncPreDrawFunction(statsDrawfun);
	gEngine->setExternalControlCallback(externalControlCallback);

	sgct::SharedData::instance()->setEncodeFunction(myEncodeFun);
	sgct::SharedData::instance()->setDecodeFunction(myDecodeFun);

	gParticles = new Snow(gEngine);
	gWorld = new World(gEngine);
	gBubble = new SoapBubble(gEngine);

	gObject = new Object(gEngine);

	gGrav = new Gravity();
	gGrav->init(-9.81f);
	gParticles->addField(gGrav);

	gWind = new Wind();
	//wind->init(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2));
	gWind->setAcceleration(0.0f, 0.0f, 0.0f);
	gParticles->addField(gWind);

	gTurbine = new Vortex();
	gTurbine->init(0.0f, 0.0f, 0.0f);
	//turbine->setForce(-10.0f, 0.0f, -1.0f);
	gParticles->addField(gTurbine);

	cout << "---- Fields active on gParticles ----" << endl;
	gParticles->printFields();
	cout << "---------------" << endl << endl;

	if(!gEngine->init(sgct::Engine::OpenGL_3_3_Core_Profile))
	{
		delete gEngine;
		return EXIT_FAILURE;
	}

	gEngine->render();

	gParticles->destroy();
	gObject->deleteObject();
	delete gObject;
	delete gEngine;
	delete gParticles;
	delete gWorld;
	delete gBubble;

	exit(EXIT_SUCCESS);
}

void initialize()
{
	if(!gParticles->initialize())
	{
		std::cout << "Error Initialzing Particle System:" << std::endl;
		exit(EXIT_FAILURE);
	}
	gWorld->initializeWorld();

	//gObject->initialize();
	gObject->loadObj("road/road.obj");
	gObject->scale(0.2f,0.2f,0.2f);
	gObject->translate(0.0f, -2.0f, 5.0f);

	gBubble->createSphere(1.5f, 100);
}

void draw()
{
	double delta = gEngine->getDt();

	gWorld->drawWorld();
	gBubble->drawBubble();
	//gObject->draw();
	gParticles->move(delta);
	gParticles->draw(delta);

}

//Checking the time since the program started, not sure if we need this either.
void myPreSyncFun()
{
	//Checks so the gEnginenode is actually the master.
	if( gEngine->isMaster() )
	{
		//Sets the current time since the program started
		curr_time.setVal(sgct::Engine::getTime());
	}
}

//Shows stats and graph depending on if the variables are true or not. Dont know if we need this?
void statsDrawfun()
{
	//gEngine->setDisplayInfoVisibility(&windBox);
	//gEngine->setStatsGraphVisibility(&vortexBox);
}

//Encodes the data sent from GUI
void myEncodeFun()
{
	sgct::SharedData::instance()->writeBool(&windBox);
	sgct::SharedData::instance()->writeBool(&vortexBox);
	sgct::SharedData::instance()->writeDouble(&curr_time);
	sgct::SharedData::instance()->writeDouble(&sizeFactorX);
	sgct::SharedData::instance()->writeDouble(&sizeFactorY);
	sgct::SharedData::instance()->writeDouble(&sizeFactorZ);
	sgct::SharedData::instance()->writeDouble(&gravFactor);
	sgct::SharedData::instance()->writeBool(&windBox);
	sgct::SharedData::instance()->writeBool(&vortexBox);
}

//Decodes the data sent from GUI
void myDecodeFun()
{
	sgct::SharedData::instance()->readBool(&windBox);
	sgct::SharedData::instance()->readBool(&vortexBox);
	sgct::SharedData::instance()->readDouble(&curr_time);
	sgct::SharedData::instance()->readDouble(&sizeFactorX);
	sgct::SharedData::instance()->readDouble(&sizeFactorY);
	sgct::SharedData::instance()->readDouble(&sizeFactorZ);
	sgct::SharedData::instance()->readDouble(&gravFactor);
	sgct::SharedData::instance()->readBool(&windBox);
	sgct::SharedData::instance()->readBool(&vortexBox);
}

//Used to alter certain values when sent from GUI. This way we can alter the fields or change gravity in realtime!
void externalControlCallback(const char * receivedChars, int size, int clientId)
{
	//Checks so the gEnginenode is actually the master.
	if(gEngine->isMaster())
	{
		//Compares the length of the strings so no weird runtime errors occur
		if(size == 7 &&  strncmp(receivedChars, "stats", 5) == 0)
		{
			windBox.setVal(true);
			vortexBox.setVal(false);
		}

		else if(size == 7 &&  strncmp(receivedChars, "graph", 5) == 0)
		{
			vortexBox.setVal(true);
			windBox.setVal(false);
		}

		else if(size >= 6 && strncmp(receivedChars, "winX", 4) == 0)
		{
			//We need an int.
			int tmpValX = atoi(receivedChars + 5);

			sizeFactorX.setVal(tmpValX);
			if(windBox.getVal())
				gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
			else
				gTurbine->setForce((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));

		}

		else if(size >= 6 && strncmp(receivedChars, "winY", 4) == 0)
		{
			//We need an int.
			int tmpValY = atoi(receivedChars + 5);

			sizeFactorY.setVal(tmpValY);
			if(windBox.getVal())
				gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
			else
				gTurbine->setForce((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));

		}

		else if(size >= 6 && strncmp(receivedChars, "winZ", 4) == 0)
		{
			//We need an int.
			int tmpValZ = atoi(receivedChars + 5);

			sizeFactorZ.setVal(tmpValZ);
			if(windBox.getVal())
				gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
			else
				gTurbine->setForce((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "grav", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			gGrav->init(tmpVal);
		}
	}
}
<|endoftext|>


<commit_before>79fb0038-ad5c-11e7-820d-ac87a332f658<commit_msg>( ͡° ͜ʖ ͡°)<commit_after>7a6ffd2b-ad5c-11e7-aea4-ac87a332f658<|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>
#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;
          }
        }
      }
    }
  }
}
<commit_msg>spanning forests created<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 = (bool *)calloc(g_max_id, sizeof(bool));
bool * inQueue = (bool *)calloc(g_max_id, sizeof(bool));
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();
  for(int i=0; i<g_max_id; i++){
    visited[i]=false;
    inQueue[i]=false;
  }

  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 == 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->second.size() == 1) {
      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;
      }
    }
    else {
      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;
          }
        }
      }
    }
    prev = s;
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2017
 *
 * Made by vincent leroy
 * Mail <vincent.54.leroy@gmail.com>
 */

// Project includes ------------------------------------------------------------
#include "MainWindow.hpp"

// Qt includes -----------------------------------------------------------------
#include <QApplication>
#include <QWidget>
#include <QStyleFactory>
#include <QFileInfo>

// C++ standard library includes -----------------------------------------------
#include <csignal>

namespace
{
    constexpr const auto styleName = "Adwaita-Dark";
}

int main(int ac, char * av[])
{
    std::signal(SIGINT,  [](int){ qApp->quit(); });
    std::signal(SIGTERM, [](int){ qApp->quit(); });

    QApplication app(ac, av);

    QApplication::setOrganizationDomain("vivoka.com");
    QApplication::setOrganizationName("vivoka");
    QApplication::setApplicationName(QFileInfo(av[0]).baseName());
    QApplication::setApplicationVersion("1.4");

    if (QStyleFactory::keys().contains(styleName))
        QApplication::setStyle(QStyleFactory::create(styleName));

    MainWindow w;
    w.restoreState();

    return app.exec();
}
<commit_msg>Bump to version 1.5<commit_after>/*
 * Copyright 2017
 *
 * Made by vincent leroy
 * Mail <vincent.54.leroy@gmail.com>
 */

// Project includes ------------------------------------------------------------
#include "MainWindow.hpp"

// Qt includes -----------------------------------------------------------------
#include <QApplication>
#include <QWidget>
#include <QStyleFactory>
#include <QFileInfo>

// C++ standard library includes -----------------------------------------------
#include <csignal>

namespace
{
    constexpr const auto styleName = "Adwaita-Dark";
}

int main(int ac, char * av[])
{
    std::signal(SIGINT,  [](int){ qApp->quit(); });
    std::signal(SIGTERM, [](int){ qApp->quit(); });

    QApplication app(ac, av);

    QApplication::setOrganizationDomain("vivoka.com");
    QApplication::setOrganizationName("vivoka");
    QApplication::setApplicationName(QFileInfo(av[0]).baseName());
    QApplication::setApplicationVersion("1.5");

    if (QStyleFactory::keys().contains(styleName))
        QApplication::setStyle(QStyleFactory::create(styleName));

    MainWindow w;
    w.restoreState();

    return app.exec();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <opencv2/core/core.hpp>
#include "opencv2/imgcodecs.hpp"

#include "cuBoF.h"

extern "C" {
  #include <vl/generic.h>
  #include <vl/kmeans.h>
  #include <vl/sift.h>
}

#include "lib/cuSIFT/cudaSift.h"

using namespace std;

// TODO
// - Examine other kmeans algorithms

int main(int argc, char **argv) {

	VL_PRINT("Hello world!\n");

  char *limgPath = argv[1];
  char *rimgPath = argv[2];

  cv::Mat limg, rimg;
  cv::imread(limgPath, 0).convertTo(limg, CV_32FC1);
  cv::imread(rimgPath, 0).convertTo(rimg, CV_32FC1);

  unsigned int w = limg.cols;
  unsigned int h = limg.rows;
  cout << "Image size = (" << w << "," << h << ")" << endl;

  std::cout << "Initializing data..." << std::endl;

  InitCuda(0);
  CudaImage img1, img2;
  img1.Allocate(w, h, iAlignUp(w, 128), false, NULL, (float*)limg.data);
  img2.Allocate(w, h, iAlignUp(w, 128), false, NULL, (float*)rimg.data);
  img1.Download();
  img2.Download();

  // Extract Sift features from images
  std::cout << "Extracting SIFT..." << std::endl;

  SiftData siftData1, siftData2;
  float initBlur = 0.0f;
  float thresh = 5.0f;
  InitSiftData(siftData1, 4096, true, true);
  InitSiftData(siftData2, 4096, true, true);
  ExtractSift(siftData1, img1, 5, initBlur, thresh, 0.0f);
  ExtractSift(siftData2, img2, 5, initBlur, thresh, 0.0f);

  double energy;
  float *centers;
  vl_size numData = siftData1.numPts;
  vl_size numCenters = 20;
  vl_size dimension = 128;
  float *data = new float[128 * numData];

  for (int i = 0; i < numData; i++) {
    memcpy(data + 128 * i, siftData1.h_data[i].data, 128 * sizeof(float));

    // fprintf(stderr, "Data %d: ", i);
    // for (int j = 0; j < 128; j++) {
    //   fprintf(stderr, "%0.4f ", data[i * 128 + j]);
    // }
    // fprintf(stderr, "\n");
  }

  std::cout << "Clustering SIFT..." << std::endl;

	VlKMeans *kMeans = vl_kmeans_new(VL_TYPE_FLOAT, VlDistanceL2);
  vl_kmeans_set_algorithm(kMeans, VlKMeansElkan);
  vl_kmeans_init_centers_with_rand_data (kMeans, data, dimension, numData, numCenters);
  vl_kmeans_set_max_num_iterations (kMeans, 100);
  energy = vl_kmeans_get_energy(kMeans);
  centers = (float *)vl_kmeans_get_centers(kMeans);

  // for (int i = 0; i < numCenters; i++) {
  //   fprintf(stderr, "Center %d: ", i);
  //   for (int j = 0; j < 128; j++) {
  //     fprintf(stderr, "%0.4f ", centers[i * 128 + j]);
  //   }
  //   fprintf(stderr, "\n");
  // }

  std::cout << "Building vocabulary tree..." << std::endl;

  vl_size numTrees = 3;
  VlKDForest *kdForest = vl_kdforest_new(VL_TYPE_FLOAT, dimension, numTrees, VlDistanceL2);
  vl_kdforest_build(kdForest, numData, centers);

  VlKDForestSearcher *kdForestSearcher = vl_kdforest_new_searcher(kdForest);

  vl_size numNeighbors = 1;
  VlKDForestNeighbor kdForestNeighbor;

  float *query = centers + 10 * 128;
  vl_kdforest_query(kdForest, &kdForestNeighbor, numNeighbors, query);

  cout << "Neighbor: " << kdForestNeighbor.distance << " " << kdForestNeighbor.index << endl;

  free(data);
  vl_kmeans_delete(kMeans);
  vl_kdforest_delete(kdForest);
  // Don't need to free because kd_forest should delete searcher
  // vl_kdforestsearcher_delete(kdForestSearcher);
  FreeSiftData(siftData1);
  FreeSiftData(siftData2);
  limg.release();
  rimg.release();

	return 0;
}<commit_msg>Compute IDF weights<commit_after>#include <iostream>
#include <ctime>
#include <math.h>
#include <algorithm>
#include <opencv2/core/core.hpp>
#include "opencv2/imgcodecs.hpp"

#include "cuBoF.h"

extern "C" {
  #include <vl/generic.h>
  #include <vl/kmeans.h>
  #include <vl/sift.h>
}

#include "lib/cuSIFT/cudaSift.h"

using namespace std;

// TODO
// - Examine other kmeans algorithms
// - Remove duplicate SIFT keypoints?

int main(int argc, char **argv) {

	VL_PRINT("Hello world!\n");

  int numFrames = argc - 1;

  char *limgPath = argv[1];
  char *rimgPath = argv[2];

  cv::Mat limg, rimg;
  cv::imread(limgPath, 0).convertTo(limg, CV_32FC1);
  cv::imread(rimgPath, 0).convertTo(rimg, CV_32FC1);

  unsigned int w = limg.cols;
  unsigned int h = limg.rows;
  cout << "Image size = (" << w << "," << h << ")" << endl;

  cout << "Initializing data..." << endl;

  InitCuda(0);
  CudaImage lCudaImg, rCudaImg;
  lCudaImg.Allocate(w, h, iAlignUp(w, 128), false, NULL, (float*)limg.data);
  rCudaImg.Allocate(w, h, iAlignUp(w, 128), false, NULL, (float*)rimg.data);
  lCudaImg.Download();
  rCudaImg.Download();

  // Extract Sift features from images
  cout << "Extracting SIFT..." << endl;

  SiftData lSiftData, rSiftData;
  float initBlur = 0.0f;
  float thresh = 5.0f;
  InitSiftData(lSiftData, 4096, true, true);
  InitSiftData(rSiftData, 4096, true, true);
  ExtractSift(lSiftData, lCudaImg, 5, initBlur, thresh, 0.0f);
  ExtractSift(rSiftData, rCudaImg, 5, initBlur, thresh, 0.0f);

  double energy;
  float *centers;
  vl_size numData = lSiftData.numPts;
  vl_size numCenters = 20;
  vl_size dimension = 128;
  float *data = new float[128 * numData];

  for (int i = 0; i < numData; i++) {
    memcpy(data + 128 * i, lSiftData.h_data[i].data, 128 * sizeof(float));

    // fprintf(stderr, "Data %d: ", i);
    // for (int j = 0; j < 128; j++) {
    //   fprintf(stderr, "%0.4f ", data[i * 128 + j]);
    // }
    // fprintf(stderr, "\n");
  }

  cout << "Clustering SIFT..." << endl;

	VlKMeans *kMeans = vl_kmeans_new(VL_TYPE_FLOAT, VlDistanceL2);
  vl_kmeans_set_algorithm(kMeans, VlKMeansANN);
  vl_kmeans_init_centers_with_rand_data (kMeans, data, dimension, numData, numCenters);
  vl_kmeans_set_max_num_iterations (kMeans, 100);
  energy = vl_kmeans_get_energy(kMeans);
  centers = (float *)vl_kmeans_get_centers(kMeans);

  // for (int i = 0; i < numCenters; i++) {
  //   fprintf(stderr, "Center %d: ", i);
  //   for (int j = 0; j < 128; j++) {
  //     fprintf(stderr, "%0.4f ", centers[i * 128 + j]);
  //   }
  //   fprintf(stderr, "\n");
  // }

  cout << "Building vocabulary tree..." << endl;

  vl_size numTrees = 3;
  VlKDForest *kdForest = vl_kdforest_new(VL_TYPE_FLOAT, dimension, numTrees, VlDistanceL2);
  vl_size maxNumComparisons = 500;
  vl_kdforest_set_max_num_comparisons(kdForest, maxNumComparisons);
  vl_kdforest_build(kdForest, numData, centers);

  // VlKDForestSearcher *kdForestSearcher = vl_kdforest_new_searcher(kdForest);

  cout << "Building histogram..." << endl;

  clock_t start = clock();

  int *lHistogram = new int[numCenters]();
  cout << "Num points (l): " << lSiftData.numPts << endl;
  for (int i = 0; i < lSiftData.numPts; i++) {
    vl_size numNeighbors = 1;
    VlKDForestNeighbor kdForestNeighbor;
    float *query = lSiftData.h_data[i].data;
    vl_kdforest_query(kdForest, &kdForestNeighbor, numNeighbors, query);
    lHistogram[kdForestNeighbor.index]++;
  }

  cout << "Histogram: ";
  int lsum = 0;
  for (int i = 0; i < numCenters; i++) {
    cout << lHistogram[i] << " ";
    lsum += lHistogram[i];
  }
  cout << endl;
  cout << "Total points: " << lsum << endl;

  int *rHistogram = new int[numCenters]();
  cout << "Num points(r): " << rSiftData.numPts << endl;
  for (int i = 0; i < rSiftData.numPts; i++) {
    vl_size numNeighbors = 1;
    VlKDForestNeighbor kdForestNeighbor;
    float *query = rSiftData.h_data[i].data;
    vl_kdforest_query(kdForest, &kdForestNeighbor, numNeighbors, query);
    rHistogram[kdForestNeighbor.index]++;
  }

  cout << "Histogram: ";
  int rsum = 0;
  for (int i = 0; i < numCenters; i++) {
    cout << rHistogram[i] << " ";
    rsum += rHistogram[i];
  }
  cout << endl;
  cout << "Total points: " << rsum << endl;

  double duration = (clock() - start) / (double) CLOCKS_PER_SEC;
  cout << "Building histogram took " << duration * 1000 << "ms." << endl;

  cout << "Computing IDF weights..." << endl;
  float *IDFWeights = new float[numCenters];
  float numerator = log(numFrames + 1);
  for (int i = 0; i < numCenters; i++) {
    int numFramesWithTerm = 0;
    if (lHistogram[i] > 0) numFramesWithTerm++;
    if (rHistogram[i] > 0) numFramesWithTerm++;

    IDFWeights[i] = numerator / max(numFramesWithTerm, 1);
  }

  cout << "Weighting and normalizing histograms..." << endl;
  for (int i = 0; i < numCenters; i++) {
    // lHistogram[i]
  }

  cout << "IDF weights: ";
  for (int i = 0; i < numCenters; i++) {
    cout << IDFWeights[i] << " ";
  }
  cout << endl;

  free(lHistogram);
  free(rHistogram);
  free(IDFWeights);
  free(data);
  vl_kmeans_delete(kMeans);
  vl_kdforest_delete(kdForest);
  FreeSiftData(lSiftData);
  FreeSiftData(rSiftData);
  limg.release();
  rimg.release();

	return 0;
}<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include "toyfs.hpp"

using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::getline;
using std::istringstream;
using std::make_shared;
using std::shared_ptr;
using std::string;
using std::vector;

const string PRMPT = "sh> ";
const uint DISKSIZE = 102400;
const uint BLOCKSIZE = 1024;

int test_fs(const string filename) {
  ToyFS myfs(filename, DISKSIZE, BLOCKSIZE);

  vector<string> args1 = {"mkdir", "/dir-1"};
  vector<string> args2 = {"mkdir", "/dir-1/dir-b"};
  vector<string> args3 = {"mkdir", "dir-2"};
  vector<string> args4 = {"mkdir", "dir-2/dir-b"};
  vector<string> args5 = {"mkdir", "dir-2/dir-b/dir-deep"};
  vector<string> args6 = {"open", "somefile", "3"};
  vector<string> args7 = {"open", "somefile", "1"};
  vector<string> args8 = {"ls"};
  myfs.mkdir(args1);
  myfs.mkdir(args2);
  myfs.mkdir(args3);
  myfs.mkdir(args4);
  myfs.mkdir(args5);
  cout << "Opening a new file" << endl;
  myfs.open(args6);
  cout << "Opening an existing file" << endl;
  myfs.open(args7);
  myfs.ls(args8);

  return 0;
}

void repl(const string filename) {

    ToyFS *fs = new ToyFS(filename, DISKSIZE, BLOCKSIZE);

    string cmd;
    vector<string> args;
    string token;

    cout << PRMPT;
    while (getline(cin, cmd)) {
        args.clear();
        istringstream iss(cmd);
        while (iss >> token) { args.push_back(token); }
        if (args.size() == 0) {
            cout << PRMPT;
            continue;
        }

        if (args[0] == "mkfs") {
            if (args.size() == 1) {
                delete(fs);
                fs = new ToyFS(filename, DISKSIZE, BLOCKSIZE);
            } else {
                cerr << "mkfs: too many operands" << endl;
            }
        } else if (args[0] == "open") {
            fs->open(args);
        } else if (args[0] == "read") {
            fs->close(args);
        } else if (args[0] == "write") {
            fs->write(args);
        } else if (args[0] == "seek") {
            fs->seek(args);
        } else if (args[0] == "close") {
            fs->close(args);
        } else if (args[0] == "mkdir") {
            fs->mkdir(args);
        } else if (args[0] == "rmdir") {
            fs->rmdir(args);
        } else if (args[0] == "cd") {
            fs->cd(args);
        } else if (args[0] == "link") {
            fs->link(args);
        } else if (args[0] == "unlink") {
            fs->unlink(args);
        } else if (args[0] == "stat") {
            fs->stat(args);
        } else if (args[0] == "ls") {
            fs->ls(args);
        } else if (args[0] == "cat") {
            fs->cat(args);
        } else if (args[0] == "cp") {
            fs->cp(args);
        } else if (args[0] == "tree") {
            fs->tree(args);
        } else if (args[0] == "import") {
            fs->import(args);
        } else if (args[0] == "export") {
            fs->FS_export(args);
        } else if (args[0] == "exit") {
            break;
        } else if (args[0] == "pwd") {
            fs->printwd(args);
        } else {
            cout << "unknown command: " << args[0] << endl;
        }
        cout << PRMPT;
    }

    delete(fs);
    return;
}

int main(int argc, char **argv) {
    if (argc != 2) {
        cerr << "usage: " << argv[0] << " filename" << endl;
        return 1;
    }

#ifdef DEBUG
    test_fs(string(argv[1]));
#else
    repl(string(argv[1]));
#endif
    return 0;
}

<commit_msg>corrected bug where main called close instead of read<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include "toyfs.hpp"

using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::getline;
using std::istringstream;
using std::make_shared;
using std::shared_ptr;
using std::string;
using std::vector;

const string PRMPT = "sh> ";
const uint DISKSIZE = 102400;
const uint BLOCKSIZE = 1024;

int test_fs(const string filename) {
  ToyFS myfs(filename, DISKSIZE, BLOCKSIZE);

  vector<string> args1 = {"mkdir", "/dir-1"};
  vector<string> args2 = {"mkdir", "/dir-1/dir-b"};
  vector<string> args3 = {"mkdir", "dir-2"};
  vector<string> args4 = {"mkdir", "dir-2/dir-b"};
  vector<string> args5 = {"mkdir", "dir-2/dir-b/dir-deep"};
  vector<string> args6 = {"open", "somefile", "3"};
  vector<string> args7 = {"open", "somefile", "1"};
  vector<string> args8 = {"ls"};
  myfs.mkdir(args1);
  myfs.mkdir(args2);
  myfs.mkdir(args3);
  myfs.mkdir(args4);
  myfs.mkdir(args5);
  cout << "Opening a new file" << endl;
  myfs.open(args6);
  cout << "Opening an existing file" << endl;
  myfs.open(args7);
  myfs.ls(args8);

  return 0;
}

void repl(const string filename) {

    ToyFS *fs = new ToyFS(filename, DISKSIZE, BLOCKSIZE);

    string cmd;
    vector<string> args;
    string token;

    cout << PRMPT;
    while (getline(cin, cmd)) {
        args.clear();
        istringstream iss(cmd);
        while (iss >> token) { args.push_back(token); }
        if (args.size() == 0) {
            cout << PRMPT;
            continue;
        }

        if (args[0] == "mkfs") {
            if (args.size() == 1) {
                delete(fs);
                fs = new ToyFS(filename, DISKSIZE, BLOCKSIZE);
            } else {
                cerr << "mkfs: too many operands" << endl;
            }
        } else if (args[0] == "open") {
            fs->open(args);
        } else if (args[0] == "read") {
            fs->read(args);
        } else if (args[0] == "write") {
            fs->write(args);
        } else if (args[0] == "seek") {
            fs->seek(args);
        } else if (args[0] == "close") {
            fs->close(args);
        } else if (args[0] == "mkdir") {
            fs->mkdir(args);
        } else if (args[0] == "rmdir") {
            fs->rmdir(args);
        } else if (args[0] == "cd") {
            fs->cd(args);
        } else if (args[0] == "link") {
            fs->link(args);
        } else if (args[0] == "unlink") {
            fs->unlink(args);
        } else if (args[0] == "stat") {
            fs->stat(args);
        } else if (args[0] == "ls") {
            fs->ls(args);
        } else if (args[0] == "cat") {
            fs->cat(args);
        } else if (args[0] == "cp") {
            fs->cp(args);
        } else if (args[0] == "tree") {
            fs->tree(args);
        } else if (args[0] == "import") {
            fs->import(args);
        } else if (args[0] == "export") {
            fs->FS_export(args);
        } else if (args[0] == "exit") {
            break;
        } else if (args[0] == "pwd") {
            fs->printwd(args);
        } else {
            cout << "unknown command: " << args[0] << endl;
        }
        cout << PRMPT;
    }

    delete(fs);
    return;
}

int main(int argc, char **argv) {
    if (argc != 2) {
        cerr << "usage: " << argv[0] << " filename" << endl;
        return 1;
    }

#ifdef DEBUG
    test_fs(string(argv[1]));
#else
    repl(string(argv[1]));
#endif
    return 0;
}

<|endoftext|>


<commit_before>/*
 * This is an example showing how to use the Safaia-framework.
 * Created By Delton Ding (dsh0416@gmail.com)
 * Create Time: 30 Aug 2015
 * Last Edited Time: 30 Aug 2015
 * */

#include "framework/Safaia.h"
#include "framework/Request.h"
#include <functional>

// Server Configuration Start
const int port = 21411;
const int max_connections = 1024;
// Server Configuration End

int main() {
    Safaia server = Safaia::Safaia(port, max_connections);
    server.add_route(Route("/index", "GET", [](Request req){return "Hello World";}));
    server.run();
    return 0;
}<commit_msg>clean up code<commit_after>/*
 * This is an example showing how to use the Safaia-framework.
 * Created By Delton Ding (dsh0416@gmail.com)
 * Create Time: 30 Aug 2015
 * Last Edited Time: 30 Aug 2015
 * */

#include "framework/Safaia.h"

// Server Configuration Start
const int port = 21411;
const int max_connections = 1024;
// Server Configuration End

int main() {
    Safaia server = Safaia::Safaia(port, max_connections);
    server.add_route(Route("/index", "GET", [](Request req){return "Hello World";}));
    server.run();
    return 0;
}<|endoftext|>


<commit_before>7d9780a3-4b02-11e5-8575-28cfe9171a43<commit_msg>That didn't fix it<commit_after>7da6d342-4b02-11e5-b229-28cfe9171a43<|endoftext|>


<commit_before>/*
 * File:   main.cpp
 * Author: tjoppen
 *
 * Created on February 12, 2010, 3:53 PM
 */

#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <sstream>
#include <fstream>
#include <boost/shared_ptr.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/dom/DOMNode.hpp>
#include <xercesc/dom/DOMNodeList.hpp>
#include <xercesc/dom/DOMAttr.hpp>
#include <xercesc/dom/DOMNamedNodeMap.hpp>

#include "main.h"
#include "XercesString.h"
#include "Class.h"
#include "BuiltInClasses.h"

using namespace std;
using namespace boost;
using namespace xercesc;

static void printUsage() {
    cout << "USAGE: james output-dir list-of-XSL-documents" << endl;
    cout << " Generates C++ classes for marshalling and unmarshalling XML to C++ objects according to the given schemas." << endl;
    cout << " Files are output in the specified output directory and are named type.h and type.cpp" << endl;
}

//maps namespace abbreviation to their full URIs
map<string, string> nsLUT;

//collection of all generated classes
map<FullName, shared_ptr<Class> > classes;

static shared_ptr<Class> addClass(shared_ptr<Class> cl) {
    if(classes.find(cl->name) != classes.end())
        throw runtime_error(cl->name.first + ":" + cl->name.second + " defined more than once");

    return classes[cl->name] = cl;
}

static string lookupNamespace(string typeName) {
    //figures out namespace URI of given type
    size_t pos = typeName.find_last_of(':');

    return nsLUT[typeName.substr(0, pos)];
}

static string stripNamespace(string typeName) {
    //strip namespace part of string
    //makes "xs:int" into "int", "tns:Foo" into "Foo" etc.
    size_t pos = typeName.find_last_of(':');

    if(pos == string::npos)
        return typeName;
    else
        return typeName.substr(pos + 1, typeName.length() - pos - 1);
}

static FullName toFullName(string typeName) {
    //looks up and strips namespace from typeName and builds a FullName of the result
    return FullName(lookupNamespace(typeName), stripNamespace(typeName));
}

static DOMElement *getExpectedChildElement(DOMNode *parent, string childName) {
    for(DOMNode *child = parent->getFirstChild(); child; child = child->getNextSibling()) {
        if(child->getNodeType() == DOMNode::ELEMENT_NODE && child->getLocalName() && X(child->getLocalName()) == childName) {
            DOMElement *childElement = dynamic_cast<DOMElement*>(child);
            CHECK(childElement);

            return childElement;
        }
    }

    throw runtime_error((string)X(parent->getLocalName()) + " missing expected child element " + childName);
}

static vector<DOMElement*> getChildElements(DOMElement *parent) {
    vector<DOMElement*> ret;

    for(DOMNode *child = parent->getFirstChild(); child; child = child->getNextSibling()) {
        if(child->getNodeType() == DOMNode::ELEMENT_NODE) {
            DOMElement *childElement = dynamic_cast<DOMElement*>(child);
            CHECK(childElement);

            ret.push_back(childElement);
        }
    }

    return ret;
}

static vector<DOMElement*> getChildElementsByTagName(DOMElement *parent, string childName) {
    vector<DOMElement*> childElements = getChildElements(parent);
    vector<DOMElement*> ret;

    for(int x = 0; x < childElements.size(); x++) {
        if(childElements[x]->getLocalName() && X(childElements[x]->getLocalName()) == childName) {
            ret.push_back(childElements[x]);
        }
    }

    return ret;
}

static void parseComplexType(DOMElement *element, FullName fullName, shared_ptr<Class> cl = shared_ptr<Class>());

static void parseSequence(DOMElement *parent, DOMElement *sequence, shared_ptr<Class> cl, bool choice = false) {
    //we expect to see a whole bunch of <element>s here
    //if choice is true then this is a choice sequence - every element is optional
    CHECK(parent);
    CHECK(sequence);

    vector<DOMElement*> children = getChildElementsByTagName(sequence, "element");

    for(int x = 0; x < children.size(); x++) {
        DOMElement *child = children[x];

        int minOccurs = 1;
        int maxOccurs = 1;

        XercesString typeStr("type");
        XercesString minOccursStr("minOccurs");
        XercesString maxOccursStr("maxOccurs");
        XercesString name = child->getAttribute(X("name"));

        if(child->hasAttribute(minOccursStr)) {
            stringstream ss;
            ss << X(child->getAttribute(minOccursStr));
            ss >> minOccurs;
        }

        if(child->hasAttribute(maxOccursStr)) {
            XercesString str(child->getAttribute(maxOccursStr));

            if(str == "unbounded")
                maxOccurs = UNBOUNDED;
            else {
                stringstream ss;
                ss << str;
                ss >> maxOccurs;
            }
        }

        //all choice elements are optional
        if(choice) {
            if(maxOccurs > 1)
                throw runtime_error("maxOccurs > 1 specified for choice element");

            minOccurs = 0;
            maxOccurs = 1;
        }

        if(child->hasAttribute(typeStr)) {
            //has type == end point - add as member of cl
            Class::Member info;

            //assume in same namespace for now
            info.type = toFullName(X(child->getAttribute(typeStr)));
            info.minOccurs = minOccurs;
            info.maxOccurs = maxOccurs;
            info.isAttribute = false;

            cl->addMember(name, info);
        } else {
            //no type - anonymous subtype
            //generate name
            FullName subName(cl->name.first, cl->name.second + "_" + (string)name);

            //expect <complexType> sub-tag
            parseComplexType(getExpectedChildElement(child, "complexType"), subName);

            Class::Member info;
            info.type = subName;
            info.minOccurs = minOccurs;
            info.maxOccurs = maxOccurs;
            info.isAttribute = false;

            cl->addMember(name, info);
        }
    }
}

static void parseComplexType(DOMElement *element, FullName fullName, shared_ptr<Class> cl) {
    //we handle two cases with <complexType>:
    //child is <sequence>
    //child is <complexContent> - expect grandchild <extension>
    CHECK(element);

    //bootstrap Class pointer in case we didn't come from the recursive <extension> call below
    if(!cl)
        cl = addClass(shared_ptr<Class>(new Class(fullName, Class::COMPLEX_TYPE)));

    vector<DOMElement*> childElements = getChildElements(element);

    for(int x = 0; x < childElements.size(); x++) {
        DOMElement *child = childElements[x];
        XercesString name(child->getLocalName());

        if(name == "sequence") {
            parseSequence(element, child, cl);
        } else if(name == "choice") {
            if(child->hasAttribute(X("minOccurs")) || child->hasAttribute(X("maxOccurs")))
                throw runtime_error("minOccurs/maxOccurs not currently supported in choices types");

            parseSequence(element, child, cl, true);
        } else if(name == "complexContent" || name == "simpleContent") {
            DOMElement *extension = getExpectedChildElement(child, "extension");

            if(!extension->hasAttribute(X("base")))
                throw runtime_error("Extension missing expected attribute base");

            //set base type and treat the extension as complexType itself
            FullName base = toFullName(X(extension->getAttribute(X("base"))));

            cl->baseType = base;
            cl->hasBase = true;

            parseComplexType(extension, fullName, cl);
        } else if(name == "attribute") {
            bool optional = false;

            if(!child->hasAttribute(X("type")))
                throw runtime_error("<attribute> missing expected attribute 'type'");

            if(!child->hasAttribute(X("name")))
                throw runtime_error("<attribute> missing expected attribute 'name'");

            XercesString attributeName = child->getAttribute(X("name"));

            FullName type = toFullName(X(child->getAttribute(X("type"))));

            //check for optional use
            if(child->hasAttribute(X("use")) && X(child->getAttribute(X("use"))) == "optional")
                optional = true;

            Class::Member info;
            info.type = type;
            info.isAttribute = true;
            info.minOccurs = optional ? 0 : 1;
            info.maxOccurs = 1;

            cl->addMember(attributeName, info);
        } else {
            throw runtime_error("Unknown complexType child of type " + (string)name);
        }
    }
}

static void parseSimpleType(DOMElement *element, FullName fullName) {
    //expect a <restriction> child element
    CHECK(element);

    DOMElement *restriction = getExpectedChildElement(element, "restriction");

    if(!restriction->hasAttribute(X("base")))
        throw runtime_error("simpleType restriction lacks expected attribute 'base'");

    //convert xs:string and the like to their respective FullName
    FullName baseName = toFullName(X(restriction->getAttribute(X("base"))));

    //add class and return
    addClass(shared_ptr<Class>(new Class(fullName, Class::SIMPLE_TYPE, baseName)));
}

static void parseElement(DOMElement *element, string tns) {
    CHECK(element);

    XercesString nodeNs(element->getNamespaceURI());
    XercesString nodeName(element->getLocalName());

    if(nodeNs != XSL || (
            nodeName != "complexType" &&
            nodeName != "element" &&
            nodeName != "simpleType"))
        return;

    //<complexType>, <element> or <simpleType>
    //figure out its class name
    XercesString name(element->getAttribute(X("name")));
    FullName fullName(tns, name);

    cout << "\t" << "new " << nodeName << ": " << fullName.second << endl;

    if(nodeName == "complexType")
        parseComplexType(element, fullName);
    else if(nodeName == "element") {
        //if <element> is missing type, then its type is anonymous
        FullName type;

        if(!element->hasAttribute(X("type"))) {
            //anonymous element type. derive it using expected <complexType>
            type = FullName(tns, fullName.second + "Type");

            parseComplexType(getExpectedChildElement(element, "complexType"), type);
        } else
            type = FullName(tns, X(element->getAttribute(X("type"))));

        addClass(shared_ptr<Class>(new Class(fullName, Class::COMPLEX_TYPE, type)))->isDocument = true;
    } else if(nodeName == "simpleType") {
        parseSimpleType(element, fullName);
    }
}

static void work(string outputDir, const vector<string>& schemaNames) {
    XercesDOMParser parser;
    parser.setDoNamespaces(true);

    for(size_t x = 0; x < schemaNames.size(); x++) {
        string name = schemaNames[x];
        parser.parse(name.c_str());

        DOMDocument *document = parser.getDocument();
        DOMElement *root = document->getDocumentElement();

        DOMAttr *targetNamespace = root->getAttributeNode(X("targetNamespace"));
        CHECK(targetNamespace);
        string tns = X(targetNamespace->getValue());

        //HACKHACK: we should handle NS lookup properly
        nsLUT["tns"] = tns;

        cout << "Target namespace: " << tns << endl;

        vector<DOMElement*> elements = getChildElements(root);

        for(int x = 0; x < elements.size(); x++)
            parseElement(elements[x], tns);
    }

    cout << "About to make second pass. Pointing class members to referenced classes, or failing if any undefined classes are encountered." << endl;

    //make second pass through classes and set all member and base class pointers correctly
    //this has the side effect of catching any undefined classes
    for(map<FullName, shared_ptr<Class> >::iterator it = classes.begin(); it != classes.end(); it++) {
        if(it->second->hasBase) {
            if(classes.find(it->second->baseType) == classes.end())
                throw runtime_error("Undefined base type " + it->second->baseType.first + ":" + it->second->baseType.second + " of " + it->second->name.first + ":" + it->second->name.second);

            it->second->base = classes[it->second->baseType].get();
        }

        for(map<string, Class::Member>::iterator it2 = it->second->members.begin(); it2 != it->second->members.end(); it2++) {
            if(classes.find(it2->second.type) == classes.end())
                throw runtime_error("Undefined type " + it2->second.type.first + ":" + it2->second.type.second + " in member " + it2->first + " of " + it->first.first + ":" + it->first.second);

            it2->second.cl = classes[it2->second.type].get();
        }
    }
}

int main(int argc, char** argv) {
    if(argc <= 2) {
        printUsage();
        return 1;
    }

    XMLPlatformUtils::Initialize();

    //HACKHACK: we should handle NS lookup properly
    nsLUT["xs"] = XSL;
    nsLUT["xsl"] = XSL;
    nsLUT["xsd"] = XSL;

    addClass(shared_ptr<Class>(new IntClass));
    addClass(shared_ptr<Class>(new IntegerClass));
    addClass(shared_ptr<Class>(new LongClass));
    addClass(shared_ptr<Class>(new StringClass));
    addClass(shared_ptr<Class>(new AnyURIClass));

    string outputDir = argv[1];
    vector<string> schemaNames;

    for(int x = 2; x < argc; x++)
        schemaNames.push_back(argv[x]);

    work(outputDir, schemaNames);

    //dump the appenders and parsers of all non-build-in classes
    for(map<FullName, shared_ptr<Class> >::iterator it = classes.begin(); it != classes.end(); it++) {
        if(!it->second->isBuiltIn()) {
            if(!it->second->isSimple())
            {
                ostringstream oss;
                oss << outputDir << "/" << it->first.second << ".cpp";

                cout << oss.str() << endl;

                ofstream ofs(oss.str().c_str());

                it->second->writeImplementation(ofs);
            }

            {
                ostringstream oss;
                oss << outputDir << "/" << it->first.second << ".h";

                cout << oss.str() << endl;

                ofstream ofs(oss.str().c_str());

                it->second->writeHeader(ofs);
            }
        }
    }

    XMLPlatformUtils::Terminate();

    return 0;
}

<commit_msg>Rudimentary support for <all><commit_after>/*
 * File:   main.cpp
 * Author: tjoppen
 *
 * Created on February 12, 2010, 3:53 PM
 */

#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <sstream>
#include <fstream>
#include <boost/shared_ptr.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/dom/DOMNode.hpp>
#include <xercesc/dom/DOMNodeList.hpp>
#include <xercesc/dom/DOMAttr.hpp>
#include <xercesc/dom/DOMNamedNodeMap.hpp>

#include "main.h"
#include "XercesString.h"
#include "Class.h"
#include "BuiltInClasses.h"

using namespace std;
using namespace boost;
using namespace xercesc;

static void printUsage() {
    cout << "USAGE: james output-dir list-of-XSL-documents" << endl;
    cout << " Generates C++ classes for marshalling and unmarshalling XML to C++ objects according to the given schemas." << endl;
    cout << " Files are output in the specified output directory and are named type.h and type.cpp" << endl;
}

//maps namespace abbreviation to their full URIs
map<string, string> nsLUT;

//collection of all generated classes
map<FullName, shared_ptr<Class> > classes;

static shared_ptr<Class> addClass(shared_ptr<Class> cl) {
    if(classes.find(cl->name) != classes.end())
        throw runtime_error(cl->name.first + ":" + cl->name.second + " defined more than once");

    return classes[cl->name] = cl;
}

static string lookupNamespace(string typeName) {
    //figures out namespace URI of given type
    size_t pos = typeName.find_last_of(':');

    return nsLUT[typeName.substr(0, pos)];
}

static string stripNamespace(string typeName) {
    //strip namespace part of string
    //makes "xs:int" into "int", "tns:Foo" into "Foo" etc.
    size_t pos = typeName.find_last_of(':');

    if(pos == string::npos)
        return typeName;
    else
        return typeName.substr(pos + 1, typeName.length() - pos - 1);
}

static FullName toFullName(string typeName) {
    //looks up and strips namespace from typeName and builds a FullName of the result
    return FullName(lookupNamespace(typeName), stripNamespace(typeName));
}

static DOMElement *getExpectedChildElement(DOMNode *parent, string childName) {
    for(DOMNode *child = parent->getFirstChild(); child; child = child->getNextSibling()) {
        if(child->getNodeType() == DOMNode::ELEMENT_NODE && child->getLocalName() && X(child->getLocalName()) == childName) {
            DOMElement *childElement = dynamic_cast<DOMElement*>(child);
            CHECK(childElement);

            return childElement;
        }
    }

    throw runtime_error((string)X(parent->getLocalName()) + " missing expected child element " + childName);
}

static vector<DOMElement*> getChildElements(DOMElement *parent) {
    vector<DOMElement*> ret;

    for(DOMNode *child = parent->getFirstChild(); child; child = child->getNextSibling()) {
        if(child->getNodeType() == DOMNode::ELEMENT_NODE) {
            DOMElement *childElement = dynamic_cast<DOMElement*>(child);
            CHECK(childElement);

            ret.push_back(childElement);
        }
    }

    return ret;
}

static vector<DOMElement*> getChildElementsByTagName(DOMElement *parent, string childName) {
    vector<DOMElement*> childElements = getChildElements(parent);
    vector<DOMElement*> ret;

    for(int x = 0; x < childElements.size(); x++) {
        if(childElements[x]->getLocalName() && X(childElements[x]->getLocalName()) == childName) {
            ret.push_back(childElements[x]);
        }
    }

    return ret;
}

static void parseComplexType(DOMElement *element, FullName fullName, shared_ptr<Class> cl = shared_ptr<Class>());

static void parseSequence(DOMElement *parent, DOMElement *sequence, shared_ptr<Class> cl, bool choice = false) {
    //we expect to see a whole bunch of <element>s here
    //if choice is true then this is a choice sequence - every element is optional
    CHECK(parent);
    CHECK(sequence);

    vector<DOMElement*> children = getChildElementsByTagName(sequence, "element");

    for(int x = 0; x < children.size(); x++) {
        DOMElement *child = children[x];

        int minOccurs = 1;
        int maxOccurs = 1;

        XercesString typeStr("type");
        XercesString minOccursStr("minOccurs");
        XercesString maxOccursStr("maxOccurs");
        XercesString name = child->getAttribute(X("name"));

        if(child->hasAttribute(minOccursStr)) {
            stringstream ss;
            ss << X(child->getAttribute(minOccursStr));
            ss >> minOccurs;
        }

        if(child->hasAttribute(maxOccursStr)) {
            XercesString str(child->getAttribute(maxOccursStr));

            if(str == "unbounded")
                maxOccurs = UNBOUNDED;
            else {
                stringstream ss;
                ss << str;
                ss >> maxOccurs;
            }
        }

        //all choice elements are optional
        if(choice) {
            if(maxOccurs > 1)
                throw runtime_error("maxOccurs > 1 specified for choice element");

            minOccurs = 0;
            maxOccurs = 1;
        }

        if(child->hasAttribute(typeStr)) {
            //has type == end point - add as member of cl
            Class::Member info;

            //assume in same namespace for now
            info.type = toFullName(X(child->getAttribute(typeStr)));
            info.minOccurs = minOccurs;
            info.maxOccurs = maxOccurs;
            info.isAttribute = false;

            cl->addMember(name, info);
        } else {
            //no type - anonymous subtype
            //generate name
            FullName subName(cl->name.first, cl->name.second + "_" + (string)name);

            //expect <complexType> sub-tag
            parseComplexType(getExpectedChildElement(child, "complexType"), subName);

            Class::Member info;
            info.type = subName;
            info.minOccurs = minOccurs;
            info.maxOccurs = maxOccurs;
            info.isAttribute = false;

            cl->addMember(name, info);
        }
    }
}

static void parseComplexType(DOMElement *element, FullName fullName, shared_ptr<Class> cl) {
    //we handle two cases with <complexType>:
    //child is <sequence>
    //child is <complexContent> - expect grandchild <extension>
    CHECK(element);

    //bootstrap Class pointer in case we didn't come from the recursive <extension> call below
    if(!cl)
        cl = addClass(shared_ptr<Class>(new Class(fullName, Class::COMPLEX_TYPE)));

    vector<DOMElement*> childElements = getChildElements(element);

    for(int x = 0; x < childElements.size(); x++) {
        DOMElement *child = childElements[x];
        XercesString name(child->getLocalName());

        if(name == "sequence") {
            parseSequence(element, child, cl);
        } else if(name == "choice" || name == "all") {
            if(child->hasAttribute(X("minOccurs")) || child->hasAttribute(X("maxOccurs")))
                throw runtime_error("minOccurs/maxOccurs not currently supported in <choice>/<all> types");

            parseSequence(element, child, cl, true);
        } else if(name == "complexContent" || name == "simpleContent") {
            DOMElement *extension = getExpectedChildElement(child, "extension");

            if(!extension->hasAttribute(X("base")))
                throw runtime_error("Extension missing expected attribute base");

            //set base type and treat the extension as complexType itself
            FullName base = toFullName(X(extension->getAttribute(X("base"))));

            cl->baseType = base;
            cl->hasBase = true;

            parseComplexType(extension, fullName, cl);
        } else if(name == "attribute") {
            bool optional = false;

            if(!child->hasAttribute(X("type")))
                throw runtime_error("<attribute> missing expected attribute 'type'");

            if(!child->hasAttribute(X("name")))
                throw runtime_error("<attribute> missing expected attribute 'name'");

            XercesString attributeName = child->getAttribute(X("name"));

            FullName type = toFullName(X(child->getAttribute(X("type"))));

            //check for optional use
            if(child->hasAttribute(X("use")) && X(child->getAttribute(X("use"))) == "optional")
                optional = true;

            Class::Member info;
            info.type = type;
            info.isAttribute = true;
            info.minOccurs = optional ? 0 : 1;
            info.maxOccurs = 1;

            cl->addMember(attributeName, info);
        } else {
            throw runtime_error("Unknown complexType child of type " + (string)name);
        }
    }
}

static void parseSimpleType(DOMElement *element, FullName fullName) {
    //expect a <restriction> child element
    CHECK(element);

    DOMElement *restriction = getExpectedChildElement(element, "restriction");

    if(!restriction->hasAttribute(X("base")))
        throw runtime_error("simpleType restriction lacks expected attribute 'base'");

    //convert xs:string and the like to their respective FullName
    FullName baseName = toFullName(X(restriction->getAttribute(X("base"))));

    //add class and return
    addClass(shared_ptr<Class>(new Class(fullName, Class::SIMPLE_TYPE, baseName)));
}

static void parseElement(DOMElement *element, string tns) {
    CHECK(element);

    XercesString nodeNs(element->getNamespaceURI());
    XercesString nodeName(element->getLocalName());

    if(nodeNs != XSL || (
            nodeName != "complexType" &&
            nodeName != "element" &&
            nodeName != "simpleType"))
        return;

    //<complexType>, <element> or <simpleType>
    //figure out its class name
    XercesString name(element->getAttribute(X("name")));
    FullName fullName(tns, name);

    cout << "\t" << "new " << nodeName << ": " << fullName.second << endl;

    if(nodeName == "complexType")
        parseComplexType(element, fullName);
    else if(nodeName == "element") {
        //if <element> is missing type, then its type is anonymous
        FullName type;

        if(!element->hasAttribute(X("type"))) {
            //anonymous element type. derive it using expected <complexType>
            type = FullName(tns, fullName.second + "Type");

            parseComplexType(getExpectedChildElement(element, "complexType"), type);
        } else
            type = FullName(tns, X(element->getAttribute(X("type"))));

        addClass(shared_ptr<Class>(new Class(fullName, Class::COMPLEX_TYPE, type)))->isDocument = true;
    } else if(nodeName == "simpleType") {
        parseSimpleType(element, fullName);
    }
}

static void work(string outputDir, const vector<string>& schemaNames) {
    XercesDOMParser parser;
    parser.setDoNamespaces(true);

    for(size_t x = 0; x < schemaNames.size(); x++) {
        string name = schemaNames[x];
        parser.parse(name.c_str());

        DOMDocument *document = parser.getDocument();
        DOMElement *root = document->getDocumentElement();

        DOMAttr *targetNamespace = root->getAttributeNode(X("targetNamespace"));
        CHECK(targetNamespace);
        string tns = X(targetNamespace->getValue());

        //HACKHACK: we should handle NS lookup properly
        nsLUT["tns"] = tns;

        cout << "Target namespace: " << tns << endl;

        vector<DOMElement*> elements = getChildElements(root);

        for(int x = 0; x < elements.size(); x++)
            parseElement(elements[x], tns);
    }

    cout << "About to make second pass. Pointing class members to referenced classes, or failing if any undefined classes are encountered." << endl;

    //make second pass through classes and set all member and base class pointers correctly
    //this has the side effect of catching any undefined classes
    for(map<FullName, shared_ptr<Class> >::iterator it = classes.begin(); it != classes.end(); it++) {
        if(it->second->hasBase) {
            if(classes.find(it->second->baseType) == classes.end())
                throw runtime_error("Undefined base type " + it->second->baseType.first + ":" + it->second->baseType.second + " of " + it->second->name.first + ":" + it->second->name.second);

            it->second->base = classes[it->second->baseType].get();
        }

        for(map<string, Class::Member>::iterator it2 = it->second->members.begin(); it2 != it->second->members.end(); it2++) {
            if(classes.find(it2->second.type) == classes.end())
                throw runtime_error("Undefined type " + it2->second.type.first + ":" + it2->second.type.second + " in member " + it2->first + " of " + it->first.first + ":" + it->first.second);

            it2->second.cl = classes[it2->second.type].get();
        }
    }
}

int main(int argc, char** argv) {
    if(argc <= 2) {
        printUsage();
        return 1;
    }

    XMLPlatformUtils::Initialize();

    //HACKHACK: we should handle NS lookup properly
    nsLUT["xs"] = XSL;
    nsLUT["xsl"] = XSL;
    nsLUT["xsd"] = XSL;

    addClass(shared_ptr<Class>(new IntClass));
    addClass(shared_ptr<Class>(new IntegerClass));
    addClass(shared_ptr<Class>(new LongClass));
    addClass(shared_ptr<Class>(new StringClass));
    addClass(shared_ptr<Class>(new AnyURIClass));

    string outputDir = argv[1];
    vector<string> schemaNames;

    for(int x = 2; x < argc; x++)
        schemaNames.push_back(argv[x]);

    work(outputDir, schemaNames);

    //dump the appenders and parsers of all non-build-in classes
    for(map<FullName, shared_ptr<Class> >::iterator it = classes.begin(); it != classes.end(); it++) {
        if(!it->second->isBuiltIn()) {
            if(!it->second->isSimple())
            {
                ostringstream oss;
                oss << outputDir << "/" << it->first.second << ".cpp";

                cout << oss.str() << endl;

                ofstream ofs(oss.str().c_str());

                it->second->writeImplementation(ofs);
            }

            {
                ostringstream oss;
                oss << outputDir << "/" << it->first.second << ".h";

                cout << oss.str() << endl;

                ofstream ofs(oss.str().c_str());

                it->second->writeHeader(ofs);
            }
        }
    }

    XMLPlatformUtils::Terminate();

    return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>

#include "BinaryTree.hpp"

using namespace std;

const int pop_size = 5;
const int pop_deepth = 10;

const double mutation_rate = 0.01;

int main() {

	population *pop = new population(pop_size);

	pop->imprime_pop();

  	delete pop;

	return 0;
}
<commit_msg>Update main.cpp<commit_after>#include <iostream>
#include <cstdio>

#include "BinaryTree.hpp"

using namespace std;

const int pop_size = 5;
const int pop_deepth = 10;

const double mutation_rate = 0.01;

int main() {

	population *pop = new population(pop_size);

	pop->print_pop();

  	delete pop;

	return 0;
}
<|endoftext|>


<commit_before>//c and posix
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>

//c++
#include <string>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <future>

namespace cnc
{
    class ThreadPool
    {
    public:
        ThreadPool(size_t);

        template<class F, class... Args>
        auto enqueue(F &&f, Args &&... args) -> std::future<typename std::result_of<F(Args...)>::type>;

        ~ThreadPool();

    private:
        // need to keep track of threads so we can join them
        std::vector<std::thread> workers;
        // the task queue
        std::queue<std::function<void()>> tasks;

        // synchronization
        std::mutex queue_mutex;
        std::condition_variable condition;
        bool stop;
    };

    // the constructor just launches some amount of workers
    inline ThreadPool::ThreadPool(size_t threads)
            : stop(false)
    {
        for (size_t i = 0; i < threads; ++i)
            workers.emplace_back(
                    [this]
                    {
                        for (; ;)
                        {
                            std::function<void()> task;

                            {
                                std::unique_lock<std::mutex> lock(this->queue_mutex);
                                this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
                                if (this->stop && this->tasks.empty())
                                    return;
                                task = std::move(this->tasks.front());
                                this->tasks.pop();
                            }

                            task();
                        }
                    }
            );
    }

    // add new work item to the pool
    template<class F, class... Args>
    auto ThreadPool::enqueue(F &&f, Args &&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
        using return_type = typename std::result_of<F(Args...)>::type;

        auto task = std::make_shared<std::packaged_task<return_type()>>
        (
                std::bind(std::forward<F>(f), std::forward<Args>(args)...)
        );

        std::future<return_type> res = task->get_future();
        {
            std::unique_lock<std::mutex> lock(queue_mutex);

            // don't allow enqueueing after stopping the pool
            if (stop)
                throw std::runtime_error("enqueue on stopped ThreadPool");

            tasks.emplace([task]() { (*task)(); });
        }
        condition.notify_one();
        return res;
    }

    // the destructor joins all threads
    inline ThreadPool::~ThreadPool()
    {
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            stop = true;
        }
        condition.notify_all();
        for (auto& worker: workers) worker.join();
    }

    template<typename Socket>
    void send_file(std::string const &filename, Socket const &socket)
    {
        std::ifstream ifs{filename};
        for (std::string str; ifs >> str;)
        {
            auto msg = str + "\r\n";
            send(socket, msg.c_str(), msg.size(), 0);
        }
    }

    template <typename StatusCode>
    auto make_reply_header(StatusCode code) -> std::string
    {
        const static std::unordered_map<StatusCode, std::string> status
                {
                        {200, "200 OK"},
                        {404, "404 Not Found"},
                        {501, "501 Not Implemented"}
                };

        return "HTTP/1.1 "  + status.at(code) + "\r\nContent-Type: text/html\r\n\r\n";
    }

}// end of namespace ccur

int main()
{
    auto const PORT = 3490;

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = INADDR_ANY;
    memset( addr.sin_zero, '\0', sizeof(addr.sin_zero) );

    // Create a socket and bind it the port PORT
    auto const soc = socket(PF_INET,SOCK_STREAM, 0);

    auto optval = 1;
    setsockopt(soc, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
    auto bind_result = bind(soc, (struct sockaddr *)&addr, sizeof(addr));
    if (bind_result != 0)
        printf("%d\n", errno);

//    bind(soc, (struct sockaddr *)&addr, sizeof(addr));
//    printf("%d\n", addr.sin_port);

    // Allow up to 10 incoming connections
    auto const limit = 10;
    listen(soc,limit);
    std::cout << "listenning\n";

    auto const header = cnc::make_reply_header(200);
    for(cnc::ThreadPool pool{ limit }; true;)
    {
        auto request_handler = [&](int socket){
            char data[512];
            char filename[256];
            auto size = recv(socket, data, 512, 0);                 // recieve the request using fd
            data[size] = 0;                                         // NUL terminate it
            sscanf(data, "GET /%s ", filename);                     // get the name of the file
            send(socket, header.c_str(), header.size(), 0);
            std::this_thread::sleep_for(std::chrono::seconds(2));
            cnc::send_file(filename, socket);
            close(socket);                                          // close the socket
        };

        pool.enqueue(request_handler, accept(soc, NULL, NULL));
    }
}
<commit_msg>extract out port reusable<commit_after>//c and posix
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>

//c++
#include <string>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <future>

namespace cnc
{
    class ThreadPool
    {
    public:
        ThreadPool(size_t);

        template<class F, class... Args>
        auto enqueue(F &&f, Args &&... args) -> std::future<typename std::result_of<F(Args...)>::type>;

        ~ThreadPool();

    private:
        // need to keep track of threads so we can join them
        std::vector<std::thread> workers;
        // the task queue
        std::queue<std::function<void()>> tasks;

        // synchronization
        std::mutex queue_mutex;
        std::condition_variable condition;
        bool stop;
    };

    // the constructor just launches some amount of workers
    inline ThreadPool::ThreadPool(size_t threads)
            : stop(false)
    {
        for (size_t i = 0; i < threads; ++i)
            workers.emplace_back(
                    [this]
                    {
                        for (; ;)
                        {
                            std::function<void()> task;

                            {
                                std::unique_lock<std::mutex> lock(this->queue_mutex);
                                this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
                                if (this->stop && this->tasks.empty())
                                    return;
                                task = std::move(this->tasks.front());
                                this->tasks.pop();
                            }

                            task();
                        }
                    }
            );
    }

    // add new work item to the pool
    template<class F, class... Args>
    auto ThreadPool::enqueue(F &&f, Args &&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
        using return_type = typename std::result_of<F(Args...)>::type;

        auto task = std::make_shared<std::packaged_task<return_type()>>
        (
                std::bind(std::forward<F>(f), std::forward<Args>(args)...)
        );

        std::future<return_type> res = task->get_future();
        {
            std::unique_lock<std::mutex> lock(queue_mutex);

            // don't allow enqueueing after stopping the pool
            if (stop)
                throw std::runtime_error("enqueue on stopped ThreadPool");

            tasks.emplace([task]() { (*task)(); });
        }
        condition.notify_one();
        return res;
    }

    // the destructor joins all threads
    inline ThreadPool::~ThreadPool()
    {
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            stop = true;
        }
        condition.notify_all();
        for (auto& worker: workers) worker.join();
    }

    template<typename Socket>
    void send_file(std::string const &filename, Socket const &socket)
    {
        std::ifstream ifs{filename};
        for (std::string str; ifs >> str;)
        {
            auto msg = str + "\r\n";
            send(socket, msg.c_str(), msg.size(), 0);
        }
    }

    template <typename StatusCode>
    auto make_reply_header(StatusCode code) -> std::string
    {
        const static std::unordered_map<StatusCode, std::string> status
                {
                        {200, "200 OK"},
                        {404, "404 Not Found"},
                        {501, "501 Not Implemented"}
                };

        return "HTTP/1.1 "  + status.at(code) + "\r\nContent-Type: text/html\r\n\r\n";
    }

    template <typename Socket>
    void enable_port_reusable(Socket soc)
    {
        auto optval = 1;
        setsockopt(soc, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
    }

}// end of namespace ccur

int main()
{
    auto const PORT = 3490;

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = INADDR_ANY;
    memset( addr.sin_zero, '\0', sizeof(addr.sin_zero) );

    // Create a socket and bind it the port PORT
    auto const soc = socket(PF_INET,SOCK_STREAM, 0);

    cnc::enable_port_reusable(soc);
    auto bind_result = bind(soc, (struct sockaddr *)&addr, sizeof(addr));
    if (bind_result != 0)
        printf("%d\n", errno);

//    bind(soc, (struct sockaddr *)&addr, sizeof(addr));
//    printf("%d\n", addr.sin_port);

    // Allow up to 10 incoming connections
    auto const limit = 10;
    listen(soc,limit);
    std::cout << "listenning\n";

    auto const header = cnc::make_reply_header(200);
    for(cnc::ThreadPool pool{ limit }; true;)
    {
        auto request_handler = [&](int socket){
            char data[512];
            char filename[256];
            auto size = recv(socket, data, 512, 0);                 // recieve the request using fd
            data[size] = 0;                                         // NUL terminate it
            sscanf(data, "GET /%s ", filename);                     // get the name of the file
            send(socket, header.c_str(), header.size(), 0);
            std::this_thread::sleep_for(std::chrono::seconds(2));
            cnc::send_file(filename, socket);
            close(socket);                                          // close the socket
        };

        pool.enqueue(request_handler, accept(soc, NULL, NULL));
    }
}
<|endoftext|>


<commit_before>65a7cc0a-2749-11e6-8129-e0f84713e7b8<commit_msg>That didn't fix it<commit_after>65b603ae-2749-11e6-96bd-e0f84713e7b8<|endoftext|>


<commit_before>87069354-ad58-11e7-824d-ac87a332f658<commit_msg>more fixes<commit_after>877679e3-ad58-11e7-8e4d-ac87a332f658<|endoftext|>


<commit_before>#include <unistd.h>

#include "game.hpp"
#include "bitboard.hpp"

#if defined(_WIN32) || defined(_WIN64)
	#include <windows.h>
#elif defined(__unix__) || defined(unix) || defined(__unix)
	#include <unistd.h>

	#include <sys/time.h>
	#include <sys/types.h>
	#include <sys/select.h>
#endif

bool is_input_available() {

#if defined(_WIN32) || defined(_WIN64)

	static bool init = false, is_pipe;
	static HANDLE stdin_h;
	DWORD val, error;
	bool UseDebug = false;

	// val = 0; // needed to make the compiler happy?

	// have a look at the "local" buffer first, *this time before init (no idea if it helps)*

	if (UseDebug && !init) printf("info string init=%d stdin->_cnt=%d\n",int(init),stdin->_cnt);

	if (stdin->_cnt > 0) return true; // HACK: assumes FILE internals

	// input init (only done once)

	if (!init) {

		init = true;

		stdin_h = GetStdHandle(STD_INPUT_HANDLE);

		if (UseDebug && (stdin_h == NULL || stdin_h == INVALID_HANDLE_VALUE)) {
			error = GetLastError();
			printf("info string GetStdHandle() failed, error=%d\n",error);
		}

		is_pipe = !GetConsoleMode(stdin_h,&val); // HACK: assumes pipe on failure

		if (UseDebug) printf("info string init=%d is_pipe=%d\n",int(init),int(is_pipe));

		if (UseDebug && is_pipe) { // GetConsoleMode() failed, everybody assumes pipe then
			error = GetLastError();
			printf("info string GetConsoleMode() failed, error=%d\n",error);
		}

		if (!is_pipe) {
			SetConsoleMode(stdin_h,val&~(ENABLE_MOUSE_INPUT|ENABLE_WINDOW_INPUT));
			FlushConsoleInputBuffer(stdin_h); // no idea if we can lose data doing this
		}
	}

	// different polling depending on input type
	// does this code work at all for pipes?

	if (is_pipe) {

		if (!PeekNamedPipe(stdin_h,NULL,0,NULL,&val ,NULL)) {

			if (UseDebug) { // PeekNamedPipe() failed, everybody assumes EOF then
				error = GetLastError();
				printf("info string PeekNamedPipe() failed, error=%d\n",error);
			}

			return true; // HACK: assumes EOF on failure
		}

		if (UseDebug && val < 0) printf("info string PeekNamedPipe(): val=%d\n",val);

		return val > 0; // != 0???

	} else {

		GetNumberOfConsoleInputEvents(stdin_h,&val);
		return val > 1; // no idea why 1
	}

	return false;

#else // assume POSIX

	int val;
	fd_set set[1];
	struct timeval time_val[1];

	FD_ZERO(set);
	FD_SET(STDIN_FILENO,set);

	time_val->tv_sec = 0;
	time_val->tv_usec = 0;

	val = select(STDIN_FILENO+1,set,NULL,NULL,time_val);
	//if (val == -1 && errno != EINTR) {
	//my_fatal("input_available(): select(): %s\n",strerror(errno));
	//}

	return val > 0;

#endif
}

int main() {
	Game* game = new Game();
	game->startGame();
	delete game;
}
<commit_msg>исправлены ошибки<commit_after>#include "game.hpp"
#include "bitboard.hpp"

#if defined(_WIN32) || defined(_WIN64)
	#include <windows.h>
#elif defined(__unix__) || defined(unix) || defined(__unix) || defined(__APPLE__)
	#include <unistd.h>

	#include <sys/time.h>
	#include <sys/types.h>
	#include <sys/select.h>
#endif

bool is_input_available() {

#if defined(_WIN32) || defined(_WIN64)

	static bool init = false, is_pipe;
	static HANDLE stdin_h;
	DWORD val, error;
	bool UseDebug = false;

	// val = 0; // needed to make the compiler happy?

	// have a look at the "local" buffer first, *this time before init (no idea if it helps)*

	if (UseDebug && !init) printf("info string init=%d stdin->_cnt=%d\n",int(init),stdin->_cnt);

	if (stdin->_cnt > 0) return true; // HACK: assumes FILE internals

	// input init (only done once)

	if (!init) {

		init = true;

		stdin_h = GetStdHandle(STD_INPUT_HANDLE);

		if (UseDebug && (stdin_h == NULL || stdin_h == INVALID_HANDLE_VALUE)) {
			error = GetLastError();
			printf("info string GetStdHandle() failed, error=%d\n",error);
		}

		is_pipe = !GetConsoleMode(stdin_h,&val); // HACK: assumes pipe on failure

		if (UseDebug) printf("info string init=%d is_pipe=%d\n",int(init),int(is_pipe));

		if (UseDebug && is_pipe) { // GetConsoleMode() failed, everybody assumes pipe then
			error = GetLastError();
			printf("info string GetConsoleMode() failed, error=%d\n",error);
		}

		if (!is_pipe) {
			SetConsoleMode(stdin_h,val&~(ENABLE_MOUSE_INPUT|ENABLE_WINDOW_INPUT));
			FlushConsoleInputBuffer(stdin_h); // no idea if we can lose data doing this
		}
	}

	// different polling depending on input type
	// does this code work at all for pipes?

	if (is_pipe) {

		if (!PeekNamedPipe(stdin_h,NULL,0,NULL,&val ,NULL)) {

			if (UseDebug) { // PeekNamedPipe() failed, everybody assumes EOF then
				error = GetLastError();
				printf("info string PeekNamedPipe() failed, error=%d\n",error);
			}

			return true; // HACK: assumes EOF on failure
		}

		if (UseDebug && val < 0) printf("info string PeekNamedPipe(): val=%d\n",val);

		return val > 0; // != 0???

	} else {

		GetNumberOfConsoleInputEvents(stdin_h,&val);
		return val > 1; // no idea why 1
	}

	return false;

#else // assume POSIX

	int val;
	fd_set set[1];
	struct timeval time_val[1];

	FD_ZERO(set);
	FD_SET(STDIN_FILENO,set);

	time_val->tv_sec = 0;
	time_val->tv_usec = 0;

	val = select(STDIN_FILENO+1,set,NULL,NULL,time_val);
	//if (val == -1 && errno != EINTR) {
	//my_fatal("input_available(): select(): %s\n",strerror(errno));
	//}

	return val > 0;

#endif
}

int main() {
	Game* game = new Game();
	game->startGame();
	delete game;
}
<|endoftext|>