text:
/*
* relcoas.cpp
*
* Author: Christoph Theunert
*
*/

#include <dlib/optimization.h>			// optimization library

using namespace std;

typedef dlib::matrix<double,0,1> column_vector;					// column vector for lbfgs matrix of 0 rows and 1 column

struct parameters {
	int lrij,N,L,lcontam,si,ei;
	vector <double> pk,qk,fk;
	vector < vector <int>> haps;
	vector <int> individuals;
	vector <double> sll_vector,p_temp;
	int ws;
}sp;

vector <string> splitstr2vec(string s,string delim) {
	size_t pos = 0;
	string token;
	vector <string> ret;
	while ((pos = s.find(delim)) != string::npos) {
		token = s.substr(0, pos);
		ret.push_back(token);
		s.erase(0, pos + delim.length());
	}
	ret.push_back(s);
	return ret;
}

vector <int> splitstr2vec2 (string s) {
	vector <int> ret;
	for(string::iterator it = s.begin(); it != s.end(); ++it) {
		ret.push_back(stoi(string(1 , *it )));
	}
	return ret;
}

void fill_cv_with_randomnumbers(int l, column_vector & pv){
	random_device rnd_device;
	mt19937 mersenne_engine(rnd_device());
	uniform_real_distribution<double> dist(0,1);
   auto gen = bind(dist, mersenne_engine);
   vector<double> rands(l);
   generate(begin(pv), end(pv), gen);
}

double mn(double a, double b) {
	return (a+b)/2.0;
}

void finalize_results(column_vector & pv){

			cout<<"###	Estimated relatedness coefficients r_ij"<<endl;
			cout<<"\t";
			for(int i=0;i<sp.N;i++){
				if(sp.individuals.size()==1 && sp.N==sp.individuals[0]){
					cout<<(i+1)<<"\t";
				}else{
					cout<<sp.individuals[i]<<"\t";
				}
			}cout<<endl;
			int pc=0;
			double c1=0.0,c2=0.0;
			for(int rc=0;rc<sp.N;rc++){
				if(sp.individuals.size()==1 && sp.N==sp.individuals[0]){
					c1=pv(sp.lrij+rc);
				}else{
					c1=pv(sp.lrij+sp.individuals[rc]-1);
				}
				for(int cc=0;cc<sp.N;cc++){
					if(sp.individuals.size()==1 && sp.N==sp.individuals[0]){
						c2=pv(sp.lrij+cc);
					}else{
						c2=pv(sp.lrij+sp.individuals[cc]-1);
					}
					if(cc==0){
						if(sp.individuals.size()==1 && sp.N==sp.individuals[0]){
							cout<<(rc+1)<<"\t";
						}else{
							cout<<sp.individuals[rc]<<"\t";
						}
					}
					if(cc<rc){
						cout<<"-\t";
					}else if(cc==rc){
						cout<<"-\t";
					}else{
						printf ("%1.2f\t", (double)pv(pc)/(1-mn(c1,c2)));	//
						pc++;
					}
					if(cc==(sp.N-1))
						cout<<endl;
				}
			}

			cout<<"\n###	Contamination rate estimates C_i"<<endl;
			for(int rc=pc;rc<pc+sp.lcontam;rc++){
				printf ("%1.2f ", pv(rc));
			}cout<<endl;
			pc+=sp.lcontam;

			cout<<"\n###	Sequencing error estimates e "<<endl;
			cout<<pv(pc)<<endl;
			pc+=1;

}

double llhood_ij (int lrij,const vector <double> & pk,const vector <double> & qk,const vector <double> & fk,int i1,int j1,int i2,int j2,const vector < vector <int>> & haps,const column_vector& param_vector,int N, int L,int contamsize) {

	double ci,cj,r,e,C,i3,j3,llhoods;

	i3=i1+1;
	j3=j1+1;
	r = param_vector((i3-1)*N+j3-((i3*i3+i3)/2)-1);

	ci = param_vector(lrij+i2);
	cj = param_vector(lrij+j2);
	e = param_vector(lrij+contamsize+1-1);
	double sum = accumulate(param_vector.begin()+lrij, param_vector.begin()+lrij+contamsize, 0.0);
	C = sum / (double)contamsize;

	double P11=0.0,P10=0.0,P01=0.0,P00=0.0,Q11=0.0,Q10=0.0,Q01=0.0,Q00=0.0,R11=0.0,R10=0.0,R01=0.0,R00=0.0;
	double r1=(1-(r/2));
	double r2=r/2;
	double c1=(1-ci)*(1-cj);
	double c2=(ci*(1-cj)+cj*(1-ci));
	double c3=ci*cj;
	double c4=ci*(1-cj);
	double c5=cj*(1-ci);
	double ee=e*e;
	double ee2=(1-e)*(1-e);
	double ee3=(1-e)*e;

	double p=0.0,f=0.0,q=0.0,tmp=0.0,p2=0.0,f2=0.0;
	for(int site=0; site<L;site++) {
		f=fk[site],f2=1-fk[site],q=qk[site],tmp=0.0;
		p=(q-C*f)/(1-C);
		if(p>1.0)
			p=0.9999;
		if(p<0)
			p=0.001;

		p2=1-p;
		P11=r1*p*p + r2*p;
		P10=P01=r1*p*p2;
		P00=r1*p2*p2 + r2*p2;

		Q11=c1*P11 + c2*p*f + c3*f*f;
		Q10=c1*P10 + c4*p2*f + c5*p*f2 + c3*f*f2;
		Q01=c1*P01 + c4*p*f2 + c5*f*p2 + c3*f*f2;
		Q00=c1*P00 + c2*p2*f2 + c3*f2*f2;

		if(haps[i2][site]==1 && haps[j2][site]==1){
			tmp=ee2*Q11 + ee3*(Q10+Q01) + ee*Q00;
			if(tmp>0)
				R11+=log(tmp);
		}else if(haps[i2][site]==1 && haps[j2][site]==0){
			tmp=ee2*Q10 + ee3*(Q11+Q00) + ee*Q01;
			if(tmp>0)
				R10 +=log(tmp);
		}else if(haps[i2][site]==0 && haps[j2][site]==1){
			tmp=ee2*Q01 + ee3*(Q11+Q00) + ee*Q10;
			if(tmp>0)
				R01 +=log(tmp);
		} else if(haps[i2][site]==0 && haps[j2][site]==0){
			tmp=ee2*Q00 + ee3*(Q10+Q01) + ee*Q11;
			if(tmp>0)
				R00 += log(tmp);
		}

	}

	llhoods=R11+R10+R01+R00;
	return llhoods;
}

double llhood (const column_vector& param_vector) {
	double sll =0.0;
	if(sp.individuals.size()==1 && sp.N==sp.individuals[0]){
		for ( int j=sp.si;j<sp.N;j++) {
			for (unsigned int i=0;i<=(j+sp.ei);i++) {
				sll = sll + llhood_ij(sp.lrij,sp.pk,sp.qk,sp.fk,i,j,i,j,sp.haps,param_vector,sp.N,sp.L,sp.lcontam);
			}
		}
	}else{
		for (unsigned int j=sp.si;j<sp.individuals.size();j++) {
			for (unsigned int i=0;i<=(j+sp.ei);i++) {
				sll=sll + llhood_ij(sp.lrij,sp.pk,sp.qk,sp.fk,i,j,sp.individuals[i]-1,sp.individuals[j]-1,sp.haps,param_vector,sp.N,sp.L,sp.lcontam);
			}
		}
	}
  return -sll;
}

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

string in_file,meta_file,indis,line;
vector <string> linevec;
vector <int> linevecint;
int ic=0;
double max_c,max_e;

column_vector param_vector;
column_vector low;
column_vector up;

//READ CMD LINE ARGUMENTS
if(argc !=11) {
	cout <<to_string(argc) +" There should be 5 parameters";
	exit(0);
}
for(int i = 1; i < argc; i+=2) {
	string a=argv[i];
    if(a == "-in_file") {
       in_file = argv[i+1];
    }else if(a == "-meta_file") {
       meta_file = argv[i+1];
    } else if (a == "-indiv") {
        linevec = splitstr2vec(argv[i + 1],",");
    }else if (a == "-max_e") {
         max_e = stod(argv[i+1]);
    }else if (a == "-max_c") {
         max_c = stod(argv[i+1]);
    }else{
		 cout <<argv[i]<< " Unknown parameter!";
		exit(0);
	 }
}

// FIGURE OUT NUMBER OF INDIVIDUALS
if(linevec.size()==1){
	try{
		sp.N=stoi(linevec[0]);
	}catch (exception const & e) {
       cout <<" ERROR:	-indiv contains invalid format"<< endl;
		 exit(0);
    }
    sp.individuals.push_back(sp.N);
}else{
	sp.N=linevec.size();
	for(unsigned int i=0;i<linevec.size();i++){
		try{
			sp.individuals.push_back(stoi(linevec[i]));
		}catch (exception const & e) {
       cout <<" ERROR:	-indiv contains invalid format"<< endl;
		 exit(0);
    }
	}
	sort(sp.individuals.begin(), sp.individuals.end());	// sort if user did not sort them (e.g. 1,5,2,10,3)
}

//READ IN HAPLOTYPES
ifstream in( in_file );
if (in) {
	while (getline( in, line )) {
		if(line[0]=='0' || line[0]=='1' || line[0]=='2') {
			linevecint=splitstr2vec2(line);
			sp.haps.push_back(linevecint);
			ic+=1;
			linevecint.clear();
		}
   }
   in.close();
}else{
	cout<<"In_File not found"<<endl;
	exit(0);
}

for(unsigned int i=0;i<sp.individuals.size();i++){
	if(sp.individuals.size()>1){
		if(sp.individuals[i]>ic) {
			cout<<"ERROR: Individual "<<sp.individuals[i]<<" not found in dataset"<<endl;
			exit(0);
		}
	}else{
		if(sp.individuals[i]!=ic){
			cout<<"ERROR: Dataset does not have "<<sp.individuals[i]<<" individuals"<<endl;
			exit(0);
		}
	}
}

//READ IN METADATA
ifstream meta( meta_file );
if (meta) {
	while (getline( meta, line )) {
		if(isdigit(line[0])) {
			linevec=splitstr2vec(line,"\t");						//site	qk	fk
			try{
				sp.qk.push_back(stod(linevec[1]));
				sp.fk.push_back(stod(linevec[2]));
			}catch (exception const & e) {
				cout <<" ERROR:	Invalid format in "<< meta_file<<": "<<line<< endl;
				exit(0);
			}
		}
   }
   meta.close();
}else{
	cout<<"Meta_File not found"<<endl;
	exit(0);
}

//NUMBER OF SITES
sp.L=sp.qk.size();

//FILL THE PARAMETER VECTORS
int ltotal=0,lfreq=0,lerr=1;

sp.lcontam=ic;
sp.lrij=(sp.N*(sp.N-1)/2);
sp.si=1;
sp.ei=-1;
sp.sll_vector.resize(sp.lrij);

ltotal=sp.lcontam+sp.lrij+lerr;
param_vector.set_size(ltotal);
low.set_size(ltotal);
up.set_size(ltotal);

fill_cv_with_randomnumbers(ltotal,param_vector);

fill(low.begin(),low.begin()+sp.lrij,0.0);
fill(low.begin()+sp.lrij,low.begin()+sp.lrij+sp.lcontam,0.0001);
fill(low.begin()+sp.lrij+sp.lcontam,low.begin()+sp.lrij+sp.lcontam+lerr,0.0001);

fill(up.begin(),up.begin()+sp.lrij,1);
fill(up.begin()+sp.lrij,up.begin()+sp.lrij+sp.lcontam,max_c);
fill(up.begin()+sp.lrij+sp.lcontam,up.begin()+sp.lrij+sp.lcontam+lerr,max_e);

for(int i=0;i<param_vector.size();i++) {
	param_vector(i)=param_vector(i)*up(i);
}

cout<<"N="<<sp.N<<" lrij="<<sp.lrij<<" lcontam="<<sp.lcontam<<" lfreq="<<lfreq<<" L="<<sp.L<<endl;

// DLIB optimization
try {
	dlib::find_min_box_constrained(dlib::lbfgs_search_strategy(100),dlib::objective_delta_stop_strategy(1e-10),llhood,derivative(llhood), param_vector,low,up);
	finalize_results(param_vector);
}catch (exception const & e)
    {
        cout << e.what() << endl;
    }
return 0;

}

max_stars_repo_name: christoph-theunert/relcoas

max_issues_repo_name: christoph-theunert/relcoas

max_forks_repo_name: christoph-theunert/relcoas


text:
#include <SFML/Graphics.hpp>
#include <iostream>
#include <chrono>
#include <thread>
#include <math.h>
#include <boost/random.hpp>
#include <fstream>

class genCircle 	// Generates circle with specified name, radius, centre and colour.
{
public:
	sf::CircleShape circleObject;
	std::string _name;
	sf::RenderWindow& _window;

	genCircle(sf::RenderWindow& window, std::string name, float radius, float xCentre, float yCentre, sf::Color colour)
	:_window(window)
	{
		circleObject = sf::CircleShape(radius);
		_name = name;
		circleObject.setPosition(xCentre - radius, yCentre - radius);
		circleObject.setFillColor(colour);
		circleObject.setPointCount(100);
	}

	std::string getName()
	{
		return _name;
	}

	void draw()
	{
		_window.draw(circleObject);
	}
};

class buttonRect	 // Generates rectangular button
{
public:
	sf::Color _color;
	sf::Font& _font;
	float _xPos;
	float _yPos;
	float _width;
	float _height;
	sf::RenderWindow& _window;
	sf::Image image;
	std::string _buttonString;
	sf::RectangleShape _buttonShape;
	sf::RectangleShape _buttonShapeInner;
	sf::Text _buttonText;

	buttonRect(sf::RenderWindow& window, float xPos, float yPos, float width, float height, sf::Color color, std::string buttonString, sf::Font& font)

	:_window(window), _font(font)
	{
		_color = color;
		_xPos = xPos;
		_yPos = yPos;
		_width = width;
		_height = height;
		_buttonString = buttonString;

		sf::RectangleShape shape;
		shape.setPosition(sf::Vector2f(xPos, yPos));
		shape.setSize(sf::Vector2f(width, height));
		shape.setFillColor(_color);
		_buttonShape = shape;

		sf::RectangleShape shapeInner;
		int thickness = 10;
		shapeInner.setPosition(sf::Vector2f(xPos + thickness, yPos + thickness));
		shapeInner.setSize(sf::Vector2f(width - 2*thickness, height - 2*thickness));
		sf::Color innerColor = sf::Color::White;
		innerColor.a = 100;
		shapeInner.setFillColor(innerColor);
		_buttonShapeInner = shapeInner;

		sf::Text text;
		text.setFont(_font);
		text.setString(_buttonString);
		text.setCharacterSize(40);
		text.setScale(0.66,0.66);

		text.setFillColor(_color);
		sf::FloatRect textRect = text.getLocalBounds();

		text.setOrigin(textRect.left + textRect.width / 2.0f,
			textRect.top + textRect.height / 2.0f);
		text.setPosition(_xPos + _width/2, _yPos + _height/2);

		_buttonText = text;

	}

	bool pressedCheck(float xMouse, float yMouse)
	{
		if ((xMouse >= _xPos) & (xMouse <= _xPos + _width))
		{
			if ((yMouse >= _yPos) & (yMouse <= _yPos + _height))
			{
				sf::Color pressedColor = sf::Color::Black;
				pressedColor.a = 50;
				_buttonShapeInner.setFillColor(pressedColor);
				return true;
			}
		}
		return false;
	}

	bool hoverCheck(float xMouse, float yMouse)
	{
		if ((xMouse >= _xPos) & (xMouse <= _xPos + _width))
		{
			if ((yMouse >= _yPos) & (yMouse <= _yPos + _height))
			{
				return true;
			}
		}
		return false;
	}

	void draw()
	{
		sf::Vector2i position = sf::Mouse::getPosition(_window);
		sf::Vector2f worldPos = _window.mapPixelToCoords(position);
		if ((worldPos.x >= _xPos) & (worldPos.x <= _xPos + _width) & (worldPos.y >= _yPos) & (worldPos.y <= _yPos + _height))
		{
			_buttonText.setFillColor(sf::Color::Yellow); // Hover colour.
		}
		else
		{
			_buttonText.setFillColor(_color);
		}

		_window.draw(_buttonShape);
		_window.draw(_buttonShapeInner);
		_window.draw(_buttonText);
	}
};

class buttonRectSet	// Generates rectangular button set
{
public:
	std::vector<buttonRect> _buttonSet; // Set of buttons created in object.
	std::vector<std::string> _buttonStrings;
	bool _orientation; // False for vertical, true for horizontal
	sf::RenderWindow& _window;
	sf::Font& _font;
	int _quantity;
	float _xPos;
	float _yTop;
	float _buttonWidth;
	float _buttonHeight;
	float _gap;
	sf::Color _buttonColor;

	buttonRectSet(sf::RenderWindow& window, bool orientation, float gap, float xPos, float yTop, float buttonWidth, float buttonHeight, sf::Color buttonColor, std::vector<std::string> buttonStrings, sf::Font& font)
		:_window(window), _font(font)
	{
		_quantity = buttonStrings.size();
		_orientation = orientation;
		_xPos = xPos;
		_yTop = yTop;
		_buttonWidth = buttonWidth;
		_buttonHeight = buttonHeight;
		_buttonColor = buttonColor;
		_gap = gap;
		_buttonStrings = buttonStrings;

		if (_orientation == false)
		{
			for (int i = 0; i < _quantity; i++)
			{
				buttonRect newButton(_window, _xPos, _yTop + i*(_buttonHeight+_gap), _buttonWidth, _buttonHeight, _buttonColor, buttonStrings[i], _font);
				_buttonSet.push_back(newButton);
			}
		}
		else if (_orientation == true)
		{
			if (_quantity % 2 == 1)
			{
				for (int i = 0; i < _quantity; i++)
				{
					buttonRect newButton(_window, _xPos + i * (_buttonWidth + _gap) - (_quantity / 2) * (buttonWidth + _gap), _yTop, _buttonWidth, _buttonHeight, _buttonColor, buttonStrings[i], _font);
					_buttonSet.push_back(newButton);
				}
			}
			else
			{
				for (int i = 0; i < _quantity; i++)
				{
					buttonRect newButton(_window, _xPos + i * (_buttonWidth + _gap) - ((_quantity / 2) - 0.5) * (buttonWidth + _gap), _yTop, _buttonWidth, _buttonHeight, _buttonColor, buttonStrings[i], _font);
					_buttonSet.push_back(newButton);
				}
			}
		}
	}

	void draw()
	{
		for (int i = 0; i < _quantity; i++)
		{
			_buttonSet[i].draw();
		}
	}
};

int init_menu(sf::RenderWindow& window, int screenWidth, int screenHeight, std::vector<int> highScoreList)
{
	sf::Color backgroundColour(0, 17, 33);
	sf::RectangleShape background(sf::Vector2f( screenWidth, screenHeight ));
	background.setFillColor(backgroundColour);

	genCircle titleBackground1(window, "backgroundWhite", 200, screenWidth / 2, screenHeight / 2, sf::Color::White);
	sf::Color grey(72, 70, 70);
	genCircle titleBackground2(window, "backgroundGrey", 400, screenWidth / 2, screenHeight / 2, grey);

	/// Font load
	sf::Font font;
	if (!font.loadFromFile("fonts/FFFFORWA.ttf"))
	{
		// error...
	}

	/// Play button creation
	buttonRectSet playButtons(window, true, 100, screenWidth / 2 - 100, screenHeight / 2 + 350, 200, 100, sf::Color(77, 0, 0), { "Timed", "Accuracy", "Quit" }, font);

	sf::Text titleText1;
	sf::Text titleText2;
	sf::Text highScoreText;

	titleText1.setFont(font);
	titleText1.setString("TIPPY");
	titleText1.setCharacterSize(100);
	titleText1.setFillColor(sf::Color::Red);
	titleText1.setPosition(screenWidth/2 - 200, screenHeight/2 - 100);
	titleText2.setFont(font);
	titleText2.setString("TAP");
	titleText2.setCharacterSize(100);
	titleText2.setFillColor(sf::Color::Red);
	titleText2.setPosition(screenWidth/2 - 65, screenHeight/2 + 40);

	highScoreText.setFont(font);
	highScoreText.setString("Highscore: " + std::to_string(highScoreList[0]));
	highScoreText.setCharacterSize(40);
	highScoreText.setFillColor(sf::Color(43, 249, 1));

	/// Centres text origin.
	sf::FloatRect textRect = highScoreText.getLocalBounds();
	highScoreText.setOrigin(textRect.left + textRect.width / 2.0f,
		textRect.top + textRect.height / 2.0f);
	highScoreText.setPosition(screenWidth / 2, screenHeight/2 + 250);

	bool startCheck(false); // Click to start check.

	int effectCounter(0);

	while (window.isOpen())
	{
		// Effect counter check
		if (effectCounter == 40)
		{
			highScoreText.setFillColor(sf::Color(229, 255, 223));
		}
		if (effectCounter == 70)
		{
			highScoreText.setFillColor(sf::Color(43, 249, 1));
			effectCounter = 0;
		}

		sf::Event event;

		sf::Vector2i position = sf::Mouse::getPosition(window);
		sf::Vector2f worldPos = window.mapPixelToCoords(position);

		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)	 // Checks for window close
			{
				window.close();
			}
			else if (event.type == sf::Event::KeyPressed) 	// Checks for escape
			{
				if (event.key.code == sf::Keyboard::Key::Escape)
					return -1;
			}

			// Checks for menu button pressed, returning a corresponding int to the main() class.
			else if (event.type == sf::Event::MouseButtonPressed & event.mouseButton.button == sf::Mouse::Left)
			{
				for (int i=0; i < playButtons._quantity; i++)
				{
					if (playButtons._buttonSet[i].hoverCheck(worldPos.x, worldPos.y))
					{
						if (i < highScoreList.size())
						{
							highScoreText.setString("Highscore: " + std::to_string(highScoreList[i]));
						}
					}

					if (playButtons._buttonSet[i].pressedCheck(worldPos.x, worldPos.y))
					{
						playButtons.draw();

						window.display();
						std::this_thread::sleep_for(std::chrono::milliseconds(500));
						return i;
					}
				}
			}
			// Updates Highscore text on menu with mode.
			for (int i = 0; i < playButtons._quantity - 1; i++)
			{
				if (playButtons._buttonSet[i].hoverCheck(worldPos.x, worldPos.y))
				{
					highScoreText.setString("Highscore: " + std::to_string(highScoreList[i]));
				}
			}
		}

		window.clear();

		window.draw(background);
		window.draw(titleBackground2.circleObject);
		window.draw(titleBackground1.circleObject);
		window.draw(titleText1);
		window.draw(titleText2);
		window.draw(highScoreText);

		playButtons.draw();

		window.display();

		std::this_thread::sleep_for(std::chrono::milliseconds(17)); 	// ~ 60 fps

		effectCounter++;
	}
	return 0;
}

int drawScore(sf::RenderWindow& window, int screenWidth, int screenHeight, int score)
{
	sf::Font scoreFont;
	if (!scoreFont.loadFromFile("fonts/unispace bd.ttf"))
	{
		// error...
	}

	sf::Text scoreText;

	scoreText.setFont(scoreFont);
	scoreText.setString("SCORE: " + std::to_string(score));
	scoreText.setCharacterSize(20);
	scoreText.setFillColor(sf::Color::Yellow);
	scoreText.setPosition(screenWidth/2 - 60, 20);

	window.draw(scoreText);
	return 0;
}

int drawCountdown(sf::RenderWindow& window, int screenWidth, int screenHeight, std::string timeLeft)
{
	sf::Font scoreFont;
	if (!scoreFont.loadFromFile("fonts/unispace bd.ttf"))
	{
		// error...
	}

	sf::Text countdownText;
	sf::Color countdownTextColour(255, 100, 0, 30);

	countdownText.setFont(scoreFont);
	countdownText.setString(timeLeft);
	countdownText.setCharacterSize(200);
	countdownText.setFillColor(countdownTextColour);

	/// Centres text origin.
	sf::FloatRect textRect = countdownText.getLocalBounds();
	countdownText.setOrigin(textRect.left + textRect.width / 2.0f,
							textRect.top + textRect.height / 2.0f);
	countdownText.setPosition(screenWidth/2, screenHeight/2);

	window.draw(countdownText);
	return 0;
}

// Reads highscores from specified mode file.
int readScore(std::string modeFile)
{
	std::ifstream highScoreRecord(modeFile);
	int highScore;
	highScoreRecord >> highScore;
	highScoreRecord.close();

	return highScore;
}

int recordScore(std::string modeFile, int score, int highScore)
{

	if (score > highScore)
	{
		std::ofstream highScores;
		highScores.open(modeFile);
		highScores << std::to_string(score);
		highScores.close();
	}
	return 0;
}

int init_timedPlayLoop(sf::RenderWindow& window, int screenWidth, int screenHeight, int highScore)
{
	int playerDefaultRadius(5);
	int targetRadius(50);
	sf::Color targetColour(sf::Color::Red);
	sf::Color playerColour(sf::Color::Blue);

	int timeCounterRaw = 31000;	 // Time in milliseconds.

	int boundaryThickness(10); 	// Minimum distance from screen edge targets spawn.
	float targetThickness(5.0f);
	int growthRate(2);

	boost::random::mt19937 rng(time(0));
	boost::random::uniform_int_distribution<> xDist(targetRadius + targetThickness + boundaryThickness, screenWidth - boundaryThickness - targetRadius - targetThickness);
	boost::random::uniform_int_distribution<> yDist(targetRadius + targetThickness + boundaryThickness, screenHeight - boundaryThickness - targetRadius - targetThickness);

	// Generate player and target circles.
	genCircle target(window, "target", targetRadius, screenWidth / 2, screenHeight / 2, targetColour);
	genCircle player(window, "player", playerDefaultRadius, screenWidth / 2, screenHeight / 2, playerColour);
	target.circleObject.setOutlineThickness(targetThickness);
	target.circleObject.setOutlineColor(sf::Color::White);

	// Player position variables. (starts with offscreen values)
	int xPlayer(-100);
	int yPlayer(-100);

	bool growing(false);
	int growingRadius(playerDefaultRadius);

	int points(0);

	typedef std::chrono::high_resolution_clock Clock;

	while (window.isOpen())
	{
		auto t1 = Clock::now(); // Start time of frame.

		/// Countdown time generation per frame.
		std::string timeCounterString = std::to_string(timeCounterRaw);
		std::string timeCounterDisplay;
		if (timeCounterString.size() < 4) { timeCounterDisplay = "0"; }
		else { timeCounterDisplay = timeCounterString.substr(0, timeCounterString.size() - 3); }

		sf::Vector2i position = sf::Mouse::getPosition(window);
		sf::Vector2f worldPos = window.mapPixelToCoords(position);

		auto startTime = std::chrono::system_clock::now();
		sf::Event event;

		if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) 	// Grows circle upon holding mouse.
		{
			growingRadius += growthRate;

			if (growing == false)
			{
				xPlayer = worldPos.x - playerDefaultRadius;
				yPlayer = worldPos.y - playerDefaultRadius;
				growing = true;
			}
			else
			{
				xPlayer = worldPos.x - player.circleObject.getRadius();
				yPlayer = worldPos.y - player.circleObject.getRadius();
				growing = true;
			}
		}

		else if (growing) 	// Upon mouse release.
		{
			// Generate random coords for target.
			int xRandom = xDist(rng);
			int yRandom = yDist(rng);

			growing = false;
			growingRadius = playerDefaultRadius;

			int pointsEarned(0);

			sf::Vector2f circleCentre1(target.circleObject.getPosition().x + target.circleObject.getRadius(), target.circleObject.getPosition().y + target.circleObject.getRadius());
			sf::Vector2f circleCentre2(player.circleObject.getPosition().x + player.circleObject.getRadius(), player.circleObject.getPosition().y + player.circleObject.getRadius());

			if (pow((circleCentre1.x - circleCentre2.x), 2) + pow((circleCentre1.y - circleCentre2.y), 2) <= pow(target.circleObject.getRadius() + targetThickness, 2) && pow(pow((circleCentre1.x - circleCentre2.x), 2) + pow((circleCentre1.y - circleCentre2.y), 2), 0.5) + player.circleObject.getRadius() <= target.circleObject.getRadius() + targetThickness)
			{
				pointsEarned = player.circleObject.getRadius() / target.circleObject.getRadius() * 100;
				if (pointsEarned > 100) { pointsEarned = 100; };
				points += pointsEarned/10;
			}

			// Regenerate target and vanish player.
			target.circleObject.setPosition(xRandom - targetRadius, yRandom - targetRadius);
			target.circleObject.setRadius(targetRadius);
			target.circleObject.setOutlineThickness(targetThickness);
			target.circleObject.setOutlineColor(sf::Color::White);
			player.circleObject.setRadius(0);
		}

		if (growingRadius > playerDefaultRadius)
		{
			player.circleObject.setRadius(growingRadius);
		}

		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
			{
				window.close();
			}
			else if (event.type == sf::Event::KeyPressed)
			{
				if (event.key.code == sf::Keyboard::Key::Escape)
					return 0;
			}
		}

		window.clear();

		player.circleObject.setPosition(xPlayer, yPlayer);

		/// Draws frame.
		sf::Color borderColour(0, 17, 33);
		sf::RectangleShape border(sf::Vector2f(screenWidth, screenHeight));
		border.setFillColor(borderColour);
		sf::RectangleShape background(sf::Vector2f(screenWidth - 2 * boundaryThickness, screenHeight - 2 * boundaryThickness));
		background.setFillColor(sf::Color::Black);
		background.setPosition(boundaryThickness, boundaryThickness);
		window.draw(border);
		window.draw(background);

		drawCountdown(window, screenWidth, screenHeight, timeCounterDisplay);
		window.draw(target.circleObject);
		window.draw(player.circleObject);
		drawScore(window, screenWidth, screenHeight, points);

		window.display();

		timeCounterRaw -= 17;
		if (timeCounterRaw <= 0) { break; }

		/// Removes frametime from sleep between frames.
		auto t2 = Clock::now(); // End time of frame.
		auto timeTaken = t2 - t1;
		auto timeTakenMilliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(timeTaken).count();
		std::this_thread::sleep_for(std::chrono::milliseconds(17-timeTakenMilliseconds));

	}
	recordScore("highScoresTimed.txt", points, highScore);
	std::this_thread::sleep_for(std::chrono::seconds(2)); // Delay return to menu.

	return 0;
}

int init_accuracyPlayLoop(sf::RenderWindow& window, int screenWidth, int screenHeight, int highScore)
{
	int targetRadius(25);
	sf::Color targetColour(sf::Color::Green);
	sf::Color playerColour(sf::Color::Blue);

	int boundaryThickness(10); // Minimum distance from screen edge targets spawn.
	int targetThickness(15);

	boost::random::mt19937 rng(time(0));
	boost::random::uniform_int_distribution<> xDist(targetRadius + targetThickness + boundaryThickness, screenWidth - boundaryThickness - targetRadius - targetThickness);
	boost::random::uniform_int_distribution<> yDist(targetRadius + targetThickness + boundaryThickness, screenHeight - boundaryThickness - targetRadius - targetThickness);

	// Generate player and target circles.
	genCircle target(window, "target", targetRadius, screenWidth / 2, screenHeight / 2, targetColour);
	target.circleObject.setOutlineThickness(targetThickness);
	target.circleObject.setOutlineColor(sf::Color::White);

	// Player position variables. (starts with offscreen values)
	int xPlayer(-100);
	int yPlayer(-100);

	typedef std::chrono::high_resolution_clock Clock;

	int points(0); 		// Total points
	int pointsEarned = 5;

	int timerBase = 3000; // Initial countdown time.
	int timerResetTime = timerBase;
	int targetsHit = 0;
	int waveCounter = 1;

	int timeCounterRaw = timerBase;		// Countdown time in milliseconds, starts with base time.

	bool endGame = false;

	while (window.isOpen())
	{
		auto t1 = Clock::now(); 	// Start time of frame.

		if (endGame == true) { break; }; 	// Ends game after target is missed.

		/// Countdown time generation per frame.
		std::string timeCounterString = std::to_string(timeCounterRaw);
		std::string timeCounterDisplay;
		if (timeCounterString.size() < 3)
		{
			timeCounterDisplay = "0.0";
		}
		else if (timeCounterString.size() < 4)
		{
			timeCounterDisplay = "0.";
			timeCounterDisplay += timeCounterString.substr(0, 1);
		}
		else
		{
			timeCounterDisplay = timeCounterString.substr(0, 1) +  "." + timeCounterString.substr(1, timeCounterString.size() - 3);
		}

		sf::Vector2i position = sf::Mouse::getPosition(window);
		sf::Vector2f worldPos = window.mapPixelToCoords(position);

		auto startTime = std::chrono::system_clock::now();
		sf::Event event;

		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
			{
				window.close();
			}
			else if (event.type == sf::Event::KeyPressed)
			{
				if (event.key.code == sf::Keyboard::Key::Escape)
					return 0;
			}
			else if (event.type == sf::Event::MouseButtonPressed & event.mouseButton.button == sf::Mouse::Left)
			{
				int xRandom = xDist(rng);
				int yRandom = yDist(rng);

				if (pow((worldPos.x - (target.circleObject.getPosition().x + targetRadius)), 2) + pow((worldPos.y - (target.circleObject.getPosition().y + targetRadius)), 2) <= pow(targetRadius + targetThickness, 2))
				{
					// Adjusts timer for wave.
					if (targetsHit % 10 == 0)
					{
						waveCounter++;
						timerResetTime = timerBase - waveCounter * (100);
					}

					timeCounterRaw = timerResetTime; 	// Reset timer upon target hit.
					targetsHit++;
					/// Points logic
					points += pointsEarned;

					// Regenerate target.
					target.circleObject.setPosition(xRandom - targetRadius, yRandom - targetRadius);
					target.circleObject.setRadius(targetRadius);
					target.circleObject.setOutlineThickness(targetThickness);
					target.circleObject.setOutlineColor(sf::Color::White);
				}
				else
				{
					endGame = true;
				}
			}

		}

		window.clear();

		/// Draws frame.
		sf::Color borderColour(0, 17, 33);
		sf::RectangleShape border(sf::Vector2f(screenWidth, screenHeight));
		border.setFillColor(borderColour);
		sf::RectangleShape background(sf::Vector2f(screenWidth - 2*boundaryThickness, screenHeight - 2 * boundaryThickness));
		background.setFillColor(sf::Color::Black);
		background.setPosition(boundaryThickness, boundaryThickness);
		window.draw(border);
		window.draw(background);

		drawCountdown(window, screenWidth, screenHeight, timeCounterDisplay);
		window.draw(target.circleObject);
		drawScore(window, screenWidth, screenHeight, points);

		window.display();

		timeCounterRaw -= 17;
		if (timeCounterRaw <= 0) { break; } 	// Ends game upon timer expiry.

		/// Removes frametime from sleep between frames.
		auto t2 = Clock::now(); 	// End time of frame.
		auto timeTaken = t2 - t1;
		auto timeTakenMilliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(timeTaken).count();
		std::this_thread::sleep_for(std::chrono::milliseconds(17 - timeTakenMilliseconds));

	}
	recordScore("highScoresAccuracy.txt", points, highScore);
	std::this_thread::sleep_for(std::chrono::seconds(2));	 // Delay return to menu.

	return 0;
}

int main()
{
	sf::ContextSettings settings;
	settings.antialiasingLevel = 8;

	int screenWidth(1920);
	int screenHeight(1080);

	sf::RenderWindow window(sf::VideoMode(screenWidth, screenHeight), "TIPPY TAP", sf::Style::Fullscreen, settings);

	/// Changes cursor.
	sf::Image cursorImage;
	cursorImage.loadFromFile("cursors/cursor3.png");
	sf::Cursor cursor;
	cursor.loadFromPixels(cursorImage.getPixelsPtr(), cursorImage.getSize(), { 14, 14 });
	window.setMouseCursor(cursor);

	// Main gameplay loop.
	while (true)
	{
		std::vector<int> highScoreList;
		int timedHighScore = readScore("highScoresTimed.txt");
		highScoreList.push_back(timedHighScore);
		int accuracyHighScore = readScore("highScoresAccuracy.txt");
		highScoreList.push_back(accuracyHighScore);

		int menu = init_menu(window, screenWidth, screenHeight, highScoreList);

		// Reads menu return int to start chosen mode.
		if (menu == -1) { break; }
		else if (menu == 0)
		{
			window.clear();
			init_timedPlayLoop(window, screenWidth, screenHeight, timedHighScore);
		}
		else if (menu == 1)
		{
			window.clear();
			init_accuracyPlayLoop(window, screenWidth, screenHeight, accuracyHighScore);
		}
		else if (menu == 2)
		{
			window.clear();
			break;
		}
		window.clear();
	}
	return 0;
}

ext: cpp

max_stars_repo_name: AnonymousVegetable/Tippy-Tap

max_issues_repo_name: AnonymousVegetable/Tippy-Tap

max_forks_repo_name: AnonymousVegetable/Tippy-Tap


text:
#include "mqtt.h"
#include "windowWrapper.h"
#include <boost/algorithm/string.hpp>

extern mqtt mosquittoWrapper;
extern openCvWrapper window;
extern bool merged;

//Converts an std::string into an array of chars, syntax is very similar to how strcpy works
//Used for getting std::/toml::string into a char*
void stringToChar(char*& dest, std::string source) {
	if (strlen(source.c_str())) {
		size_t len = strlen(source.c_str()) + 1;
		dest = new char[len];
		strcpy_s(dest, len, source.c_str());
		dest[len - 1] = '\0';
	}
}

/*
The constructor sets all pointers to null and sets the non pointer variables to the default by mosquitto's standards
port = 1883
keepalive = 60
clean_session = true
*/
mqtt::mqtt() {
	this->host = nullptr;
	this->topic = nullptr;
	this->port = 1883;
	this->keepalive = 60;
	this->clean_session = true;
	this->mosq = nullptr;
	this->id = nullptr;
	this->userdata = nullptr;
}

/*
The constructor frees up all of the pointer's memory and then set them to point at 0
All other non-pointer data variables are set to 0.
*/
mqtt::~mqtt() {
	delete[] this->host;
	this->host = 0;
	delete[] this->topic;
	this->topic = 0;
	this->port = 0;
	this->keepalive = 0;
	this->clean_session = false;
	delete this->userdata;
	this->userdata = nullptr;
	mosquitto_destroy(this->mosq);
	this->mosq = 0;
}

/*
Frees up all memory for the pointer fields before allocating the data onto host, topic, and id
Sets all the other non pointer variables to their respective fields.
It will then go through and call init_mosquitto() which will initialize the mosq variable,
allowing it to connect() right after create()
*/
bool mqtt::create(char* host, char* topic, int port, char* id, void* userdata, int keep_alive, bool clean_session, int num_cameras) {
	delete[]this->host;
	delete[]this->topic;
	delete[]this->id;
	this->host = new char[strlen(host) + 1];
	strcpy_s(this->host, (strlen(host) + 1), host);
	this->topic = new char[strlen(topic) + 1];
	strcpy_s(this->topic, (strlen(topic) + 1), topic);
	this->port = port;
	this->keepalive = keepalive;
	this->clean_session = clean_session;
	this->id = new char[strlen(id) + 1];
	strcpy_s(this->id, (strlen(id) + 1), id);

	return initMosquitto();
}

/*
connect() is a wrapper that will check to make sure that the connection succeeded, if it didn't it will return 1
succeeding will return 0
*/
bool mqtt::connect(void) {
	if (mosquitto_connect(this->mosq, this->host, this->port, this->keepalive)) {
		fprintf(stderr, "Unable to connect.\n");
		return false;
	}
	return true;
}

/*
The my_function_callback are functions that will help in the debug process. They are the functions that are called as if there
were on_event() type syntax. These are added to the callback function when calling the mosquitto_log_function_set(). The
mosquitto_log_function_set() takes the mosquitto structure and these my_function_callback() as the arguments.
*/
void mqtt::callbacks(void) {
	//mosquitto_log_callback_set(this->mosq, my_log_callback);
	//mosquitto_connect_callback_set(this->mosq, my_connect_callback);
	mosquitto_message_callback_set(this->mosq, my_message_callback);
	//mosquitto_subscribe_callback_set(this->mosq, my_subscribe_callback);
}

/*
Send message is just a simple wrapper to publish/send a message over the mqtt stream with the
topic that the varible was initialized with.
The required arguments are:
payload_len: size of payload to be sent over
payload: the actual payload to be sent over
qos: 0, 1 or 2 indicating the quality of service to be used for the message
Optional arguments are:
retain: if message is desired to be kept
mid: number for the message id specifically sent over, can be NULL and the library will increment its own.
*/
void mqtt::sendMessage(int payload_len, const void* payload, char* topic, int qos, bool retain, int* mid) {
	if(topic != nullptr){
		mosquitto_publish(this->mosq, mid, topic, payload_len, payload, qos, retain);
	}
	else {
		mosquitto_publish(this->mosq, mid, this->topic, payload_len, payload, qos, retain);
	}
}

/*
Finish mosquitto is a wrapper that calls the mosquitto_lib_cleanup() function
Only do this at the end of the program.
*/
void mqtt::finishMosquitto(void) {
	mosquitto_lib_cleanup();
}

/*
Wrapper that is used to initialize the mosquitto library. Only needs to be called once.
*/
void mqtt::initMqttLib(void) {
	mosquitto_lib_init();
}

/*
Wrapper to help create a new mosquitto instance.
There are no required parameters for this function as it already assumes that the values for the class
has been populated in some fashion prior to calling this.
*/
int mqtt::initMosquitto(void) {
	this->mosq = mosquitto_new(this->id, this->clean_session, this->userdata);
	if (!mosq) {
		fprintf(stderr, "Unable to connect.\n");
		return 0;
	}
	return 1;
}

/*
ParseArgs takes in the section of toml that is relevant for mqtt info.
It will create the variables right from the file and then initialize the values to those provided from the
config.toml file.
Returns the success or failure of init_mosquitto()
*/
bool mqtt::ParseArgs(toml::Table table) {
	stringToChar(this->host, toml::get<toml::String>(table.at("host")));
	stringToChar(this->id, toml::get<toml::String>(table.at("id")));
	std::string topicString(toml::get<toml::String>(table.at("topic")));
	topicString.append("/");
	topicString.append(id);
	stringToChar(this->topic, topicString);
	this->port = (int)toml::get<toml::Integer>(table.at("port"));
	try {
		this->keepalive = (int)toml::get<toml::Integer>(table.at("keepalive"));
	}
	catch (std::exception & e) {
		e; //Removes unreferenced local veriable warning
		this->keepalive = 60;
	}
	try {
		this->clean_session = toml::get<toml::Boolean>(table.at("clean_session"));
	}
	catch (std::exception & e) {
		e; //Removes unreferenced local veriable warning
		this->clean_session = true;
	}

	return initMosquitto();
}

/*
Give the current mosquitto instance back, useful for:
mosquitto_loop_start();
*/
mosquitto* mqtt::giveMosquitto() {
	return this->mosq;
}

/*
Subscribe to the topic that is stored in the class
*/
void mqtt::subscribe() {
	mosquitto_subscribe(this->mosq, NULL, this->topic, 0);
}

/*
Subscribe to a topic that is not stored in the class
Can do either to be '(this->topic)/newtopic' in terms of appending
or its own topic to something that is not tied to this->topic
*/
void mqtt::subscribe(char* topic, bool append) {
	std::string subTopic;
	if (append) {
		subTopic = std::string(this->topic);
		subTopic.append("/");
		subTopic.append(topic);
	}
	else {
		subTopic = std::string(topic);
	}
	mosquitto_subscribe(this->mosq, NULL, subTopic.c_str(), 0);
}

/*
Disconnect the mosquitto client from the broker
*/
void mqtt::disconnect() {
	mosquitto_disconnect(this->mosq);
}

	/*
	Return the stored topic in the class
	*/
std::string mqtt::giveTopic() {
	return this->topic;
}

bool mqtt::unsubscribe(char* topic) {
	if (topic == nullptr) {
		return false;
	}

	mosquitto_unsubscribe(this->mosq, NULL, topic);

	return true;
}

/*
Function is provided by the mosquitto.org documentation
*/
void my_message_callback(struct mosquitto* mosq, void* userdata, const struct mosquitto_message* message)
{
	if (message->payloadlen) {

		if (strcmp((char*)message->topic, TOPIC_CONTROL) == 0 ) {

			if (strcmp((char*)message->payload, COMMAND_SHUTDOWN) == 0) {
				printf("Closing down the application..\n");
				window.setDone(true);
			}
			else if (strcmp((char*)message->payload, COMMAND_RESTART) == 0) {
				printf("Restarting the application..                          \n");
				window.setRestart(true);
			}
		}
		else if (strcmp((char*)message->topic, TOPIC_MERGER) == 0) {

			// Merger is responding with a list of 1 or more topics from which
			// point frames will be broadcast (either the list of individual
			// cameras, or the merged frames)

			std::string messagePayload((char*)message->payload);
			std::vector<std::string> messageVector;
			//String split using boost 'Solution 2': https://www.fluentcpp.com/2017/04/21/how-to-split-a-string-in-c/
			boost::split(messageVector, messagePayload, [](char c) {return c == ' '; });
			if (messageVector.size() != 0) {
				window.setTopicNames(messageVector);
			}
		}
		else if ( window.isActiveTopic(message->topic) ) {
			//For Debugging purposes
			//printf("%s %d bytes\n", (char*)message->topic, message->payloadlen);
			std::string topicString((char*)message->topic);
			msg newPoints;
			char* buffer = (char*)message->payload;
			int totalBuffer = message->payloadlen - 13;
			int totalPoints = 0;
			memcpy(&totalPoints, &buffer[8], 4);
			totalPoints *= 3;
			int depthSize = totalPoints * 2;
			newPoints.message = new int16_t[totalPoints];
			newPoints.size = totalPoints;
			memcpy(&newPoints.message[0], &buffer[13], depthSize);
			window.importPoints(topicString, newPoints);
			delete[]newPoints.message;
			newPoints.message = nullptr;
		}
	}
}

/*
Function is provided by the mosquitto.org documentation
*/
void my_connect_callback(struct mosquitto* mosq, void* userdata, int result)
{
	if (!result) {
		/* Subscribe to broker information topics on successful connect. */
		mosquitto_subscribe(mosq, NULL, "$SYS/#", 2);
	}
	else {
		fprintf(stderr, "Connect failed\n");
	}
}

/*
Function is provided by the mosquitto.org documentation
*/
void my_subscribe_callback(struct mosquitto* mosq, void* userdata, int mid, int qos_count, const int* granted_qos)
{
	int i;

	printf("Subscribed (mid: %d): %d", mid, granted_qos[0]);
	for (i = 1; i < qos_count; i++) {
		printf(", %d", granted_qos[i]);
	}
	printf("\n");
}

/*
Function is provided by the mosquitto.org documentation
*/
void my_log_callback(struct mosquitto* mosq, void* userdata, int level, const char* str)
{
	/* Pring all log messages regardless of level. */
	printf("%s\n", str);
}

max_stars_repo_name: PieMyth/Azure-Kinect-Samples

max_issues_repo_name: PieMyth/Azure-Kinect-Samples

max_forks_repo_name: PieMyth/Azure-Kinect-Samples


text:
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 by EMC Corporation, All Rights Reserved
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is EMC Corporation
///
/// @author Andrey Abramov
/// @author Vasiliy Nabatchikov
////////////////////////////////////////////////////////////////////////////////

#include "term_filter.hpp"
#include "term_query.hpp"
#include "cost.hpp"
#include "analysis/token_attributes.hpp"
#include "index/index_reader.hpp"

#include <boost/functional/hash.hpp>

NS_ROOT

// -----------------------------------------------------------------------------
// --SECTION--                                            by_term implementation
// -----------------------------------------------------------------------------

DEFINE_FILTER_TYPE(by_term);
DEFINE_FACTORY_DEFAULT(by_term);

by_term::by_term()
  : filter(by_term::type()) {
}

by_term::by_term(const type_id& type)
  : filter( type ) {
}

bool by_term::equals(const filter& rhs) const {
  const by_term& trhs = static_cast<const by_term&>(rhs);
  return filter::equals(rhs) && fld_ == trhs.fld_ && term_ == trhs.term_;
}

size_t by_term::hash() const {
  size_t seed = 0;
  ::boost::hash_combine(seed, filter::hash());
  ::boost::hash_combine(seed, fld_);
  ::boost::hash_combine(seed, term_);
  return seed;
}

filter::prepared::ptr by_term::prepare(
    const index_reader& rdr,
    const order::prepared& ord,
    boost_t boost,
    const attribute_view& /*ctx*/) const {
  return term_query::make(rdr, ord, boost*this->boost(), fld_, term_);
}

NS_END // ROOT


text:
#ifndef BOOST_SYSTEM_DETAIL_ERROR_CATEGORY_HPP_INCLUDED
#define BOOST_SYSTEM_DETAIL_ERROR_CATEGORY_HPP_INCLUDED

//  Copyright Beman Dawes 2006, 2007
//  Copyright Christoper Kohlhoff 2007
//  Copyright Peter Dimov 2017, 2018
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
//  See library home page at http://www.boost.org/libs/system

#include <boost/system/detail/config.hpp>
#include <boost/cstdint.hpp>
#include <boost/config.hpp>
#include <string>
#include <functional>
#include <cstddef>

#if defined(BOOST_SYSTEM_HAS_SYSTEM_ERROR)
# include <system_error>
# include <atomic>
#endif

namespace boost
{

namespace system
{

class error_category;
class error_code;
class error_condition;

std::size_t hash_value( error_code const & ec );

namespace detail
{

BOOST_SYSTEM_CONSTEXPR bool failed_impl( int ev, error_category const & cat );

class std_category;

} // namespace detail

#if ( defined( BOOST_GCC ) && BOOST_GCC >= 40600 ) || defined( BOOST_CLANG )
#pragma GCC diagnostic push
  //#pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
#endif

class BOOST_SYMBOL_VISIBLE error_category
{
private:

    friend std::size_t hash_value( error_code const & ec );
    friend BOOST_SYSTEM_CONSTEXPR bool detail::failed_impl( int ev, error_category const & cat );

    friend class error_code;
    friend class error_condition;

#if !defined(BOOST_NO_CXX11_DELETED_FUNCTIONS)
public:

    error_category( error_category const & ) = delete;
    error_category& operator=( error_category const & ) = delete;

#else
private:

    error_category( error_category const & );
    error_category& operator=( error_category const & );

#endif

private:

    boost::ulong_long_type id_;

#if defined(BOOST_SYSTEM_HAS_SYSTEM_ERROR)

    mutable std::atomic< boost::system::detail::std_category* > ps_;

#else

    boost::system::detail::std_category* ps_;

#endif

protected:

#if !defined(BOOST_NO_CXX11_DEFAULTED_FUNCTIONS) && !defined(BOOST_NO_CXX11_NON_PUBLIC_DEFAULTED_FUNCTIONS)

    ~error_category() = default;

#else

    // We'd like to make the destructor protected, to make code that deletes
    // an error_category* not compile; unfortunately, doing the below makes
    // the destructor user-provided and hence breaks use after main, as the
    // categories may get destroyed before code that uses them

    // ~error_category() {}

#endif

    BOOST_SYSTEM_CONSTEXPR error_category() BOOST_NOEXCEPT: id_( 0 ), ps_()
    {
    }

    explicit BOOST_SYSTEM_CONSTEXPR error_category( boost::ulong_long_type id ) BOOST_NOEXCEPT: id_( id ), ps_()
    {
    }

public:

    virtual const char * name() const BOOST_NOEXCEPT = 0;

    virtual error_condition default_error_condition( int ev ) const BOOST_NOEXCEPT;
    virtual bool equivalent( int code, const error_condition & condition ) const BOOST_NOEXCEPT;
    virtual bool equivalent( const error_code & code, int condition ) const BOOST_NOEXCEPT;

    virtual std::string message( int ev ) const = 0;
    virtual char const * message( int ev, char * buffer, std::size_t len ) const BOOST_NOEXCEPT;

    virtual bool failed( int ev ) const BOOST_NOEXCEPT
    {
        return ev != 0;
    }

    friend BOOST_SYSTEM_CONSTEXPR bool operator==( error_category const & lhs, error_category const & rhs ) BOOST_NOEXCEPT
    {
        return rhs.id_ == 0? &lhs == &rhs: lhs.id_ == rhs.id_;
    }

    friend BOOST_SYSTEM_CONSTEXPR bool operator!=( error_category const & lhs, error_category const & rhs ) BOOST_NOEXCEPT
    {
        return !( lhs == rhs );
    }

    friend BOOST_SYSTEM_CONSTEXPR bool operator<( error_category const & lhs, error_category const & rhs ) BOOST_NOEXCEPT
    {
        if( lhs.id_ < rhs.id_ )
        {
            return true;
        }

        if( lhs.id_ > rhs.id_ )
        {
            return false;
        }

        if( rhs.id_ != 0 )
        {
            return false; // equal
        }

        return std::less<error_category const *>()( &lhs, &rhs );
    }

#if defined(BOOST_SYSTEM_HAS_SYSTEM_ERROR)
# if defined(__SUNPRO_CC) // trailing __global is not supported
    operator std::error_category const & () const;
# else
    operator std::error_category const & () const BOOST_SYMBOL_VISIBLE;
# endif
#endif
};

#if ( defined( BOOST_GCC ) && BOOST_GCC >= 40600 ) || defined( BOOST_CLANG )
#pragma GCC diagnostic pop
#endif

namespace detail
{

static const boost::ulong_long_type generic_category_id = ( boost::ulong_long_type( 0xB2AB117A ) << 32 ) + 0x257EDFD0;
static const boost::ulong_long_type system_category_id = generic_category_id + 1;
static const boost::ulong_long_type interop_category_id = generic_category_id + 2;

BOOST_SYSTEM_CONSTEXPR inline bool failed_impl( int ev, error_category const & cat )
{
    if( cat.id_ == system_category_id || cat.id_ == generic_category_id )
    {
        return ev != 0;
    }
    else
    {
        return cat.failed( ev );
    }
}

} // namespace detail

} // namespace system

} // namespace boost

#endif // #ifndef BOOST_SYSTEM_DETAIL_ERROR_CATEGORY_HPP_INCLUDED

ext: hpp

max_stars_repo_name: robalexclark/SilveR-Dev

max_issues_repo_name: robalexclark/SilveR-Dev

max_forks_repo_name: robalexclark/SilveR-Dev


text:
#include "MeteorScorer.h"

#include <algorithm>
#include <cmath>
#include <fstream>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <cstdio>
#include <string>
#include <vector>

#include <boost/thread/mutex.hpp>

#if defined(__GLIBCXX__) || defined(__GLIBCPP__)
#include "Fdstream.h"
#endif

#include "ScoreStats.h"
#include "Util.h"

using namespace std;

namespace MosesTuning
{

// Meteor supported
#if (defined(__GLIBCXX__) || defined(__GLIBCPP__)) && !defined(_WIN32)

// for clarity
#define CHILD_STDIN_READ pipefds_input[0]
#define CHILD_STDIN_WRITE pipefds_input[1]
#define CHILD_STDOUT_READ pipefds_output[0]
#define CHILD_STDOUT_WRITE pipefds_output[1]

MeteorScorer::MeteorScorer(const string& config)
  : StatisticsBasedScorer("METEOR",config)
{
  meteor_jar = getConfig("jar", "");
  meteor_lang = getConfig("lang", "en");
  meteor_task = getConfig("task", "tune");
  meteor_m = getConfig("m", "");
  meteor_p = getConfig("p", "");
  meteor_w = getConfig("w", "");
  if (meteor_jar == "") {
    throw runtime_error("Meteor jar required, see MeteorScorer.h for full list of options: --scconfig jar:/path/to/meteor-1.4.jar");
  }
  int pipe_status;
  int pipefds_input[2];
  int pipefds_output[2];
  // Create pipes for process communication
  pipe_status = pipe(pipefds_input);
  if (pipe_status == -1) {
    throw runtime_error("Error creating pipe");
  }
  pipe_status = pipe(pipefds_output);
  if (pipe_status == -1) {
    throw runtime_error("Error creating pipe");
  }
  // Fork
  pid_t pid;
  pid = fork();
  if (pid == pid_t(0)) {
    // Child's IO
    dup2(CHILD_STDIN_READ, 0);
    dup2(CHILD_STDOUT_WRITE, 1);
    close(CHILD_STDIN_WRITE);
    close(CHILD_STDOUT_READ);
    // Call Meteor
    stringstream meteor_cmd;
    meteor_cmd << "java -Xmx1G -jar " << meteor_jar << " - - -stdio -lower -t " << meteor_task << " -l " << meteor_lang;
    if (meteor_m != "") {
      meteor_cmd << " -m '" << meteor_m << "'";
    }
    if (meteor_p != "") {
      meteor_cmd << " -p '" << meteor_p << "'";
    }
    if (meteor_w != "") {
      meteor_cmd << " -w '" << meteor_w << "'";
    }
    TRACE_ERR("Executing: " + meteor_cmd.str() + "\n");
    execl("/bin/bash", "bash", "-c", meteor_cmd.str().c_str(), (char*)NULL);
    throw runtime_error("Continued after execl");
  }
  // Parent's IO
  close(CHILD_STDIN_READ);
  close(CHILD_STDOUT_WRITE);
  m_to_meteor = new ofdstream(CHILD_STDIN_WRITE);
  m_from_meteor = new ifdstream(CHILD_STDOUT_READ);
}

MeteorScorer::~MeteorScorer()
{
  // Cleanup IO
  delete m_to_meteor;
  delete m_from_meteor;
}

void MeteorScorer::setReferenceFiles(const vector<string>& referenceFiles)
{
  // Just store strings since we're sending lines to an external process
  for (int incRefs = 0; incRefs < (int)referenceFiles.size(); incRefs++) {
    m_references.clear();
    ifstream in(referenceFiles.at(incRefs).c_str());
    if (!in) {
      throw runtime_error("Unable to open " + referenceFiles.at(incRefs));
    }
    string line;
    while (getline(in, line)) {
      line = this->preprocessSentence(line);
      m_references.push_back(line);
    }
    m_multi_references.push_back(m_references);
  }
  m_references=m_multi_references.at(0);
}

void MeteorScorer::prepareStats(size_t sid, const string& text, ScoreStats& entry)
{
  string sentence = this->preprocessSentence(text);
  string stats_str;
  stringstream input;
  // SCORE ||| ref1 ||| ref2 ||| ... ||| text
  input << "SCORE";
  for (int incRefs = 0; incRefs < (int)m_multi_references.size(); incRefs++) {
    if (sid >= m_multi_references.at(incRefs).size()) {
      stringstream msg;
      msg << "Sentence id (" << sid << ") not found in reference set";
      throw runtime_error(msg.str());
    }
    string ref = m_multi_references.at(incRefs).at(sid);
    input << " ||| " << ref;
  }
  input << " ||| " << text << "\n";
  // Threadsafe IO
#ifdef WITH_THREADS
  mtx.lock();
#endif
  //TRACE_ERR ( "in: " + input.str() );
  *m_to_meteor << input.str();
  m_from_meteor->getline(stats_str);
  //TRACE_ERR ( "out: " + stats_str + "\n" );
#ifdef WITH_THREADS
  mtx.unlock();
#endif
  entry.set(stats_str);
}

float MeteorScorer::calculateScore(const vector<ScoreStatsType>& comps) const
{
  string score;
  stringstream input;
  // EVAL ||| stats
  input << "EVAL |||";
  copy(comps.begin(), comps.end(), ostream_iterator<int>(input, " "));
  input << "\n";
  // Threadsafe IO
#ifdef WITH_THREADS
  mtx.lock();
#endif
  //TRACE_ERR ( "in: " + input.str() );
  *m_to_meteor << input.str();
  m_from_meteor->getline(score);
  //TRACE_ERR ( "out: " + score + "\n" );
#ifdef WITH_THREADS
  mtx.unlock();
#endif
  return atof(score.c_str());
}

#else

// Meteor unsupported, throw error if used

MeteorScorer::MeteorScorer(const string& config)
  : StatisticsBasedScorer("METEOR",config)
{
  throw runtime_error("Meteor unsupported, requires GLIBCXX");
}

MeteorScorer::~MeteorScorer() {}

void MeteorScorer::setReferenceFiles(const vector<string>& referenceFiles) {}

void MeteorScorer::prepareStats(size_t sid, const string& text, ScoreStats& entry) {}

float MeteorScorer::calculateScore(const vector<ScoreStatsType>& comps) const
{
  // Should never be reached
  return 0.0;
}

#endif

}

max_stars_repo_name: ugermann/MMT

max_issues_repo_name: Pangeamt/nectm

max_forks_repo_name: Pangeamt/nectm