<commit_before>/*********************************************************************/
/* File: Undistort.cpp                                               */
/* Last Edition: 23/10/2015, 17:45 PM.                               */
/*********************************************************************/
/* Programmed by:                                                    */
/* Bernardo Aceituno C                                               */
/* Jose Cappelletto                                                  */
/*********************************************************************/
/*Image undistort program, takes the Output .XML and the source as   */
/*inputs and outputs the undistorted source (image, list or video    */
/*Requires OpenCV 2.0.0 or higher                                    */
/*********************************************************************/

#include <iostream>
#include <sstream>
#include <stdio.h>

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/highgui/highgui.hpp>

#ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
#endif

using namespace cv;
using namespace std;

bool readStringList( const string& filename, vector<string>& l){

    l.clear();

    FileStorage fs(filename, FileStorage::READ);

    if( !fs.isOpened() ) return false;

    FileNode n = fs.getFirstTopLevelNode();

    if( n.type() != FileNode::SEQ ) return false;

    FileNodeIterator it = n.begin(), it_end = n.end();

    for( ; it != it_end; ++it) l.push_back((string)*it);

    return true;
}

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

    //declares the camera coefficient arrays
    Mat cameraMatrix, distCoeffs;

    //declares the image dimensions
    int width, height;

    if(argc < 2){
        cout << "ERROR!: No arguments passed!" << endl;
        return -1;
    }

    if(string(argv[1])=="-h"){
        cout << "Help:" << endl;
        cout << "argv[1]: calibration .XML in OpenCV format." << endl;
        cout << "argv[2]: Input source" << endl;
        cout << "     .xml: assumed for imagelist" << endl;
        cout << "     .avi: for video (testing)" << endl;
        cout << "         : other formats will be assumed for image" << endl;
        cout << "argv[3]: Output file [optional]" << endl;

        return 0;
    }

    //determines if the two inputs arguments are given
    if(argc < 3){
        cout << "Error! wrong or no input provided!" << endl;
        cout << "Usage: > Undistort calibration_file file_input file_output" << endl;
        cout << "HELP: argv[1] is the .XML calibration file" << endl;
        cout << "      argv[2] is the source imagefile" << endl;
        cout << "      argv[3] is the output imagefile" << endl;
        cout << "See -h option for further details" << endl;
        return -1;
    }

    //reads the path of the list
    //string basepath_input = string(argv[2]).substr(string(argv[2]),string(arg[2]).length - string(arg[2]).substr(find_last_of("/")+1).length);

    //checks if an output path has been provided
    string BasePath;
    if(argc == 4) BasePath = string(argv[3]);
    else BasePath = string("")/*basepath_input*/;

    //reads the .xml file
    const string CoeffFilename = argv[1];
    FileStorage f(CoeffFilename,FileStorage::READ);

    //declares the name of the output
    const string InputFilename = argv[2];

    //reads the data form the input
    f["Camera_Matrix"] >> cameraMatrix;
    f["Distortion_Coefficients"] >> distCoeffs;
    f["image_Width"] >> width;
    f["image_Height"] >> height;

    //determines the filetype
    const string filetype = (InputFilename.substr(InputFilename.find_last_of(".")));

    //Computes the compression parameters for the camera
    vector<int> compression_params; //vector that stores the compression parameters of the image
    compression_params.push_back(CV_IMWRITE_JPEG_QUALITY); //specify the compression technique
    compression_params.push_back(100); //specify techniquehe compression quality

    //
    if(filetype == ".xml" || filetype == ".XML") {
        //declares some variables
        vector<string> imageList;

        //reads the imagelist
        bool readed = readStringList(InputFilename, imageList);

        if(!readed){
            cout << "Failed to open image list" << endl;
            return -1;
        }

        //declares the matrix for the current image
        Mat image;

        //size of tue image
        Size imageSize;

        //declares a counter for the loop
        int atImageList = 0;

        //reads the first image from the list
        image = imread(imageList[atImageList++], CV_LOAD_IMAGE_COLOR);

        //enters the calibration loop
        while(atImageList < (int)imageList.size()){
            //gets the image size
            imageSize = image.size();
            //declares the outputs
            Mat Output(width, height, CV_16UC3, Scalar(0,50000, 50000));

            //remaps the input
            Mat map1, map2;
            initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(), getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0), imageSize, CV_16SC2, map1, map2);
            remap(image, Output, map1, map2, INTER_LINEAR);

            //gets the name of the original file
            string fullpath = imageList[atImageList];
            string filename = fullpath.substr(fullpath.find_last_of("/") + 1,fullpath.length() - 4);

            ostringstream Namefr;
            if(filename.empty()) Namefr << "REMAP_" << fullpath;
            else Namefr << BasePath << "REMAP_" << filename;

            //saves the undistorted file
            bool save = imwrite(Namefr.str(), Output, compression_params);

            //checks if the image was saved correctly;
            if(!(save)){
                cout << "Frame could not be saved" << endl;
                return -1;
            }

            cout << "image " << atImageList << " from imagelist done!" << endl;
            //loads the next image
            image = imread(imageList[atImageList++], CV_LOAD_IMAGE_COLOR);
        }
    }
    else if(filetype == ".avi"){
        VideoCapture Video(InputFilename);
        if(!Video.isOpened()){
            cout << "Video could not be opened!" << endl;
            return -1;
        }

        char number[10];

        //declares the variable for each frame
        Mat image;

        //size of tue image
        Size imageSize;

        //reads the first fream
        bool bSuccess = Video.read(image);

        //gets the name of the input
        string videoname = InputFilename.substr(InputFilename.find_last_of("/") + 1,InputFilename.length() - 4);

        //declares a counter
        int cnt = 0;

        while(!image.empty()){
            if(!bSuccess){
                cout << "error with the video frame" << endl;
                return -1;
            }

            //gets the image size
            imageSize = image.size();

            //declares the outputs
            Mat Output(width, height, CV_16UC3, Scalar(0,50000, 50000));

            //remaps the input
            Mat map1, map2;
            initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(), getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0), imageSize, CV_16SC2, map1, map2);
            remap(image, Output, map1, map2, INTER_LINEAR);

            //saves the remaped frame
            ostringstream namevidefr;
            namevidefr << BasePath << "REMAP_" << videoname << "_" <</*setw(4) <<*/ cnt << ".jpg";

            bool save = imwrite(namevidefr.str(), Output, compression_params);

            //checks if the image was saved correctly;
            if(!(save)){
                cout << "video frame could not be saved" << endl;
                return -1;
            }

            //reads the next image
            bSuccess = Video.read(image);

            //increases the counter
            cnt++;
        }
    }
    else{
        //reads the image
        Mat image = imread(argv[2],CV_LOAD_IMAGE_UNCHANGED);

        //checks if the image is empty
        if(image.empty()){
            cout << "Error! invalid imagefile" << endl;
            return -1;
        }

        //gets the size of the image
        Size imageSize = image.size();

        //declares the outputs
        Mat Output(width, height, CV_16UC3, Scalar(0,50000, 50000));

        //remaps the input
        Mat map1, map2;
        initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(), getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0), imageSize, CV_16SC2, map1, map2);
        remap(image, Output, map1, map2, INTER_LINEAR);

        string imagefilename = InputFilename.substr(InputFilename.find_last_of("/") + 1,InputFilename.length() - 4);

        ostringstream outname;

        outname << BasePath << "REMAP_" << imagefilename << ".jpg";

        //saves the calibrated frame
        bool save = imwrite(outname.str(), Output, compression_params);

        //checks if it was saved correctly
        if(!(save)){
            cout << "Image could not be saved" << endl;
            return -1;
        }

        cout << "image stored!" << endl;
    }

    return 0;
}
<commit_msg>Undistort Source V 2.0<commit_after>/*********************************************************************/
/* File: Undistort.cpp                                               */
/* Last Edition: 26/10/2015, 19:50 PM.                               */
/*********************************************************************/
/* Programmed by:                                                    */
/* Bernardo Aceituno C                                               */
/* Jose Cappelletto                                                  */
/*********************************************************************/
/*Image undistort program, takes the Output .XML and the source as   */
/*inputs and outputs the undistorted source (image, list or video    */
/*Requires OpenCV 2.0.0 or higher                                    */
/*********************************************************************/

#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string>

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/highgui/highgui.hpp>

#ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
#endif

using namespace cv;
using namespace std;

bool readStringList( const string& filename, vector<string>& l){

    l.clear();

    FileStorage fs(filename, FileStorage::READ);

    if( !fs.isOpened() ) return false;

    FileNode n = fs.getFirstTopLevelNode();

    if( n.type() != FileNode::SEQ ) return false;

    FileNodeIterator it = n.begin(), it_end = n.end();

    for( ; it != it_end; ++it) l.push_back((string)*it);

    return true;
}

void error(){
    cout << "Error! wrong or no input provided!" << endl;
    cout << "See -h option for further details" << endl;
}

void help(){
    cout << "Help: the input arguments shall be entered the following way" << endl;
    cout << "-c : calibration .XML in OpenCV format." << endl;
    cout << "-i : Input source" << endl;
    cout << "     .xml: assumed for imagelist" << endl;
    cout << "     .avi: for video (testing)" << endl;
    cout << "         : other formats will be assumed for image" << endl;
    cout << "-o : Output path [optional], if not given set as the input source directory" << endl;
    cout << "-p : Output prefix [optional] if not given set as UND" << endl;
    cout << "-r : video sampling rate [optional] if not given set as 1" << endl;
    cout << endl;
    cout << "example: " << endl;
    cout << "$ ./Undistort -c CALIBRATION.xml -i VIDEO.avi -o /home/user/Documents/ -r 5 -p REMAP_" << endl;
}

int str2int(const std::string& str) {

    // Still need to add error checking
    int i = 0;
    string::const_iterator it = str.begin();
    while (it != str.end()) {
        i *= 10;
        i += *it++ - '0';
    }

    return i;
}

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

    //verifies that at least one argument is given
    if(argc < 2){
        error();
        return -1;
    }

    //displays the help if required
    if(string(argv[1])=="-h"){
        help();
        return 0;
    }

    //determines if the two minimum inputs arguments are given
    if(argc < 3){
        error();
        return -1;
    }

    //declares the camera coefficient arrays
    Mat cameraMatrix, distCoeffs;

    //declares the image dimensions
    int width, height;

    //declares the input files
    string CoeffFilename;
    string InputFilename;
    string BasePath;

    //reads the inputs
    int i;
    int fr = 1;
    string argument, prefix, argval;

    //reads over each argument to get the inputs
    for(i=1;i<argc - 1;i++){
        //reads the argument
        argument = string(argv[i]);
        //parses the argument
        argval = string(argv[i+1]);
        //verifies the prefix of the argument to assign it
        if(argument == "-i") InputFilename = argval;
        if(argument == "-c") CoeffFilename = argval;
        if(argument == "-o") BasePath = argval;
        if(argument == "-p") prefix = argval;
        if(argument == "-r") fr = str2int(argval);
    }

    //checks that the coefficients and the input source are given
    if(InputFilename.empty() || CoeffFilename.empty() || InputFilename.length() == 2 || CoeffFilename.length() == 2){
        cout << "Error! wrong or no input provided!" << endl;
        cout << "Set -h as first parameter for further details" << endl;
        return -1;
    }

    //gets the path of the input source
    string filelen = InputFilename.substr(InputFilename.find_last_of("/")+1);
    string basepath_input = InputFilename.substr(InputFilename.length(),InputFilename.length() - filelen.length());
    //if there is no output path given the path of the source is taken as output file
    if(BasePath.empty()) BasePath = basepath_input;
    if(prefix.empty()) prefix = "UND_";

    //opens the coefficients file
    FileStorage f(CoeffFilename,FileStorage::READ);

    //reads the data form the input
    f["Camera_Matrix"] >> cameraMatrix;
    f["Distortion_Coefficients"] >> distCoeffs;
    f["image_Width"] >> width;
    f["image_Height"] >> height;

    //determines the filetype
    const string filetype = (InputFilename.substr(InputFilename.find_last_of(".")));

    //Computes the compression parameters for the camera
    vector<int> compression_params; //vector that stores the compression parameters of the image
    compression_params.push_back(CV_IMWRITE_JPEG_QUALITY); //specify the compression technique
    compression_params.push_back(100); //specify techniquehe compression quality

    //
    if(filetype == ".xml" || filetype == ".XML") {
        //declares some variables
        vector<string> imageList;

        //reads the imagelist
        bool readed = readStringList(InputFilename, imageList);

        //checks that the list was oppened succesfully
        if(!readed){
            cout << "Failed to open image list" << endl;
            return -1;
        }

        //declares the matrix for the current image
        Mat image;

        //size of tue image
        Size imageSize;

        //declares a counter for the loop
        int atImageList = 0;

        //reads the first image from the list
        image = imread(imageList[atImageList++], CV_LOAD_IMAGE_COLOR);

        //enters the calibration loop
        while(atImageList < (int)imageList.size()){
            //gets the image size
            imageSize = image.size();
            //declares the outputs
            Mat Output(width, height, CV_16UC3, Scalar(0,50000, 50000));

            //remaps the input
            Mat map1, map2;
            initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(), getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0), imageSize, CV_16SC2, map1, map2);
            remap(image, Output, map1, map2, INTER_LINEAR);

            //gets the name of the original file
            string fullpath = imageList[atImageList];

            //reads the extension
            string extension = fullpath.substr(fullpath.find_last_of("."));

            //gets the filename
            string filename = fullpath.substr(fullpath.find_last_of("/") + 1,fullpath.length() - extension.length());

            ostringstream Namefr;
            if(filename.empty()) Namefr << prefix << fullpath;
            else Namefr << BasePath << prefix << filename;

            //saves the undistorted file
            bool save = imwrite(Namefr.str(), Output, compression_params);

            //checks if the image was saved correctly;
            if(!(save)){
                cout << "Frame could not be saved" << endl;
                return -1;
            }

            cout << "image " << atImageList << " from imagelist done!" << endl;
            //loads the next image
            image = imread(imageList[atImageList++], CV_LOAD_IMAGE_COLOR);
        }
    }
    else if(filetype == ".avi"){
        VideoCapture Video(InputFilename);
        if(!Video.isOpened()){
            cout << "Video could not be opened!" << endl;
            return -1;
        }

        char number[10];

        //declares the variable for each frame
        Mat image;

        //size of tue image
        Size imageSize;

        //reads the first fream
        bool bSuccess = Video.read(image);

        //gets the name of the input
        string videoname = InputFilename.substr(InputFilename.find_last_of("/") + 1,InputFilename.length() - 4);

        //declares a counter
        int cnt = 0;

        while(!image.empty()){
            if(!bSuccess){
                cout << "error with the video frame" << endl;
                return -1;
            }

            //gets the image size
            imageSize = image.size();

            //declares the outputs
            Mat Output(width, height, CV_16UC3, Scalar(0,50000, 50000));

            //check that the rate is the specified
            if(cnt%fr==0){
                //remaps the input
                Mat map1, map2;
                initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(), getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0), imageSize, CV_16SC2, map1, map2);
                remap(image, Output, map1, map2, INTER_LINEAR);

                //saves the remaped frame
                ostringstream namevidefr;
                namevidefr << BasePath << prefix << videoname << "_" << cnt;

                bool save = imwrite(namevidefr.str(), Output, compression_params);

                //checks if the image was saved correctly;
                if(!(save)){
                    cout << "video frame could not be saved" << endl;
                    return -1;
                }

                cout << "Frame " << cnt << " saved!" << endl;
            }

            //reads the next image
            bSuccess = Video.read(image);

            //increases the counter
            cnt++;
        }
    }
    else{
        //reads the image
        Mat image = imread(InputFilename,CV_LOAD_IMAGE_UNCHANGED);

        //checks if the image is empty
        if(image.empty()){
            cout << "Error! invalid imagefile" << endl;
            return -1;
        }

        //gets the size of the image
        Size imageSize = image.size();

        //declares the outputs
        Mat Output(width, height, CV_16UC3, Scalar(0,50000, 50000));

        //remaps the input
        Mat map1, map2;
        initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(), getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0), imageSize, CV_16SC2, map1, map2);
        remap(image, Output, map1, map2, INTER_LINEAR);

        string extension = InputFilename.substr(InputFilename.find_last_of("."));
        string imagefilename = InputFilename.substr(InputFilename.find_last_of("/") + 1,InputFilename.length() - extension.length());

        ostringstream outname;

        outname << BasePath << prefix << imagefilename;
	    //saves the calibrated frame
        bool save = imwrite(outname.str(), Output, compression_params);

        //checks if it was saved correctly
        if(!(save)){
            cout << "Image could not be saved" << endl;
            return -1;
        }

        cout << "image stored!" << endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <chrono>
#include <random>
#include <algorithm>
#include <atomic>
#include "samplers/sampler.h"
#include "block_queue.h"

BlockQueue::BlockQueue(const Sampler &sampler, int blocks)
	: samplers(sampler.get_subsamplers(blocks)), sampler_idx(0)
{
	int seed = std::chrono::system_clock::now().time_since_epoch().count();
	std::mt19937 mt{seed};
	std::shuffle(samplers.begin(), samplers.end(), mt);
}
Sampler BlockQueue::get_block(){
	int n = samplers.size();
	if (sampler_idx.compare_exchange_strong(n, n, std::memory_order_acq_rel)){
		return Sampler{0, 0, 0, 0};
	}
	int s = sampler_idx.fetch_add(1, std::memory_order_acq_rel);
	return samplers[s];
}

<commit_msg>Fix race condition<commit_after>#include <chrono>
#include <random>
#include <algorithm>
#include <atomic>
#include "samplers/sampler.h"
#include "block_queue.h"

BlockQueue::BlockQueue(const Sampler &sampler, int blocks)
	: samplers(sampler.get_subsamplers(blocks)), sampler_idx(0)
{
	int seed = std::chrono::system_clock::now().time_since_epoch().count();
	std::mt19937 mt{seed};
	std::shuffle(samplers.begin(), samplers.end(), mt);
}
Sampler BlockQueue::get_block(){
	int n = samplers.size();
	if (sampler_idx.compare_exchange_strong(n, n, std::memory_order_acq_rel)){
		return Sampler{0, 0, 0, 0};
	}
	int s = sampler_idx.fetch_add(1, std::memory_order_acq_rel);
	//Potential race condition if we would have gotten the last block but some other
	//thread beat us from the cmp_exg to the fetch_add, so we need to double check
	if (s < samplers.size()){
		return samplers[s];
	}
	return Sampler{0, 0, 0, 0};
}

<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE test

#include <boost/test/unit_test.hpp>

#include <mlog/mlog.hpp>
#include <mlog/memory_logger.hpp>
#include <mlog/file_logger.hpp>
#include <thread>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <cmath>

#ifdef _MSC_VER
namespace std {
double log2(double n) {
	// log(n)/log(2) is log2.
	return log(n) / log(2);
}
}
#endif

const int num_threads = 2;
int num_loops = 100000;

void write_some_log_entrys() {
	for (int i = 0; i < num_loops; i++)
		MLOG_INFO("this is a test.");
}

double single_thread_test() {
	boost::posix_time::ptime start =
	    boost::posix_time::microsec_clock::universal_time();
	write_some_log_entrys();
	boost::posix_time::time_duration time =
	    boost::posix_time::microsec_clock::universal_time() - start;
	double ms = time.total_milliseconds() /
		    static_cast<double>(num_loops * num_threads);
	return ms;
}

double multi_thread_test() {
	std::thread threads[num_threads];

	boost::posix_time::ptime start =
	    boost::posix_time::microsec_clock::universal_time();
	for (int i = 0; i < num_threads; ++i)
		threads[i] = std::thread([]() { write_some_log_entrys(); });

	for (auto &t : threads)
		t.join();
	boost::posix_time::time_duration time =
	    boost::posix_time::microsec_clock::universal_time() - start;
	double ms = time.total_milliseconds() /
		    static_cast<double>(num_loops * num_threads);
	return ms;
}

BOOST_AUTO_TEST_CASE(mlog_empty_test) {}

BOOST_AUTO_TEST_CASE(mlog_log2_test) {
	for (unsigned long i = 1; i < 1024 * 1024; i++)
		BOOST_CHECK_EQUAL(static_cast<unsigned long>(std::log2(i)),
				  mlog::log2(i));
}

BOOST_AUTO_TEST_CASE(mlog_memory_logger_1_test) {
	auto *log = new mlog::memory_logger<2>();
	mlog::mlogger.reset(log);
	MLOG_INFO("1");
	MLOG_INFO("2");
	BOOST_CHECK_EQUAL((*log)[0].text, "1");
	BOOST_CHECK_EQUAL((*log)[1].text, "2");
	BOOST_CHECK_EQUAL((*log)[2].text, "1"); // overflow
}

BOOST_AUTO_TEST_CASE(standard_logger_speed_test) {
	num_loops = 1000;
	mlog::mlogger.reset(new mlog::standard_logger());
	double st_result = single_thread_test();
	mlog::mlogger->use_thread_id(true);
	double st_result_thread_id = single_thread_test();
	mlog::mlogger->use_time(true);
	double st_result_thread_id_time = single_thread_test();
	mlog::mlogger->use_position(true);
	double st_result_thread_id_time_pos = single_thread_test();

	mlog::mlogger.reset(new mlog::standard_logger_thread_safe());
	double mt_result = multi_thread_test();
	mlog::mlogger->use_thread_id(true);
	double mt_result_thread_id = multi_thread_test();
	mlog::mlogger->use_time(true);
	double mt_result_thread_id_time = multi_thread_test();
	mlog::mlogger->use_position(true);
	double mt_result_thread_id_time_pos = multi_thread_test();

	std::cout << std::endl;
	std::cout << "### single-threaded standard logger test ###"
		  << std::endl;
	std::cout << st_result << "ms for each log statment." << std::endl;
	std::cout << st_result_thread_id
		  << "ms for each log statment with thread id." << std::endl;
	std::cout << st_result_thread_id_time
		  << "ms for each log statment with thread id and timestamp."
		  << std::endl;
	std::cout << st_result_thread_id_time_pos
		  << "ms for each log statment with thread id, timestamp and "
		     "position." << std::endl;
	std::cout << std::endl;
	std::cout << "### multi-threaded standard logger test ###" << std::endl;
	std::cout << mt_result << "ms for each log statment." << std::endl;
	std::cout << mt_result_thread_id
		  << "ms for each log statment with thread id." << std::endl;
	std::cout << mt_result_thread_id_time
		  << "ms for each log statment with thread id and timestamp."
		  << std::endl;
	std::cout << mt_result_thread_id_time_pos
		  << "ms for each log statment with thread id, timestamp and "
		     "position." << std::endl;
}

BOOST_AUTO_TEST_CASE(memory_logger_speed_test) {
	num_loops = 100000;
	mlog::mlogger.reset(new mlog::memory_logger_normal());
	double st_result = single_thread_test();
	mlog::mlogger->use_thread_id(true);
	double st_result_thread_id = single_thread_test();
	mlog::mlogger->use_time(true);
	double st_result_thread_id_time = single_thread_test();
	mlog::mlogger->use_position(true);
	double st_result_thread_id_time_pos = single_thread_test();

	double mt_result = multi_thread_test();
	mlog::mlogger->use_thread_id(true);
	double mt_result_thread_id = multi_thread_test();
	mlog::mlogger->use_time(true);
	double mt_result_thread_id_time = multi_thread_test();
	mlog::mlogger->use_position(true);
	double mt_result_thread_id_time_pos = multi_thread_test();

	std::cout << std::endl;
	std::cout << "### single-threaded memory logger test ###" << std::endl;
	std::cout << st_result << "ms for each log statment." << std::endl;
	std::cout << st_result_thread_id
		  << "ms for each log statment with thread id." << std::endl;
	std::cout << st_result_thread_id_time
		  << "ms for each log statment with thread id and timestamp."
		  << std::endl;
	std::cout << st_result_thread_id_time_pos
		  << "ms for each log statment with thread id, timestamp and "
		     "position." << std::endl;
	std::cout << std::endl;
	std::cout << "### multi-threaded memory logger test ###" << std::endl;
	std::cout << mt_result << "ms for each log statment." << std::endl;
	std::cout << mt_result_thread_id
		  << "ms for each log statment with thread id." << std::endl;
	std::cout << mt_result_thread_id_time
		  << "ms for each log statment with thread id and timestamp."
		  << std::endl;
	std::cout << mt_result_thread_id_time_pos
		  << "ms for each log statment with thread id, timestamp and "
		     "position." << std::endl;
	//*/
}

BOOST_AUTO_TEST_CASE(file_logger_speed_test) {
	num_loops = 100000;
	mlog::mlogger.reset(new mlog::file_logger("log.txt"));
	mlog::mlogger->use_time(false);
	double st_result = single_thread_test();
	mlog::mlogger->use_thread_id(true);
	double st_result_thread_id = single_thread_test();
	mlog::mlogger->use_time(true);
	double st_result_thread_id_time = single_thread_test();
	mlog::mlogger->use_position(true);
	double st_result_thread_id_time_pos = single_thread_test();

	mlog::mlogger.reset(new mlog::file_logger_thread_safe("log.txt"));
	mlog::mlogger->use_time(false);
	double mt_result = multi_thread_test();
	mlog::mlogger->use_thread_id(true);
	double mt_result_thread_id = multi_thread_test();
	mlog::mlogger->use_time(true);
	double mt_result_thread_id_time = multi_thread_test();
	mlog::mlogger->use_position(true);
	double mt_result_thread_id_time_pos = multi_thread_test();

	std::cout << std::endl;
	std::cout << "### single-threaded file logger test ###" << std::endl;
	std::cout << st_result << "ms for each log statment." << std::endl;
	std::cout << st_result_thread_id
		  << "ms for each log statment with thread id." << std::endl;
	std::cout << st_result_thread_id_time
		  << "ms for each log statment with thread id and timestamp."
		  << std::endl;
	std::cout << st_result_thread_id_time_pos
		  << "ms for each log statment with thread id, timestamp and "
		     "position." << std::endl;
	std::cout << std::endl;
	std::cout << "### multi-threaded file logger test ###" << std::endl;
	std::cout << mt_result << "ms for each log statment." << std::endl;
	std::cout << mt_result_thread_id
		  << "ms for each log statment with thread id." << std::endl;
	std::cout << mt_result_thread_id_time
		  << "ms for each log statment with thread id and timestamp."
		  << std::endl;
	std::cout << mt_result_thread_id_time_pos
		  << "ms for each log statment with thread id, timestamp and "
		     "position." << std::endl;
}

BOOST_AUTO_TEST_CASE(memory_logger_test) {
	num_loops = 100000;
	mlog::memory_logger<2048> *mem_log = new mlog::memory_logger<2048>();
	mlog::mlogger.reset(mem_log);
	mlog::mlogger->use_time(false);
	mlog::mlogger->use_thread_id(false);
	mlog::mlogger->use_time(false);

	for (std::size_t i = 0; i < 2048; i++) {
		MLOG_INFO(boost::format("%1%") % i);
	}

	for (std::size_t i = 0; i < 2048; i++) {
		BOOST_CHECK_EQUAL(
		    boost::lexical_cast<std::size_t>((*mem_log)[i].text), i);
	}

	// std::cout << *mem_log << std::endl;
}

#ifdef _MSC_VER
BOOST_AUTO_TEST_CASE(memory_leak) {
	std::cout << "msvc will detect a memory leak at the end of this "
		     "program. - it's a false positive." << std::endl;
}
#endif
// */
<commit_msg>Added a unit test<commit_after>#define BOOST_TEST_MODULE test

#include <boost/test/unit_test.hpp>

#include <mlog/mlog.hpp>
#include <mlog/memory_logger.hpp>
#include <mlog/file_logger.hpp>
#include <thread>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <cmath>

#ifdef _MSC_VER
namespace std {
double log2(double n) {
	// log(n)/log(2) is log2.
	return log(n) / log(2);
}
}
#endif

const int num_threads = 2;
int num_loops = 100000;

void write_some_log_entrys() {
	for (int i = 0; i < num_loops; i++)
		MLOG_INFO("this is a test.");
}

double single_thread_test() {
	boost::posix_time::ptime start =
	    boost::posix_time::microsec_clock::universal_time();
	write_some_log_entrys();
	boost::posix_time::time_duration time =
	    boost::posix_time::microsec_clock::universal_time() - start;
	double ms = time.total_milliseconds() /
		    static_cast<double>(num_loops * num_threads);
	return ms;
}

double multi_thread_test() {
	std::thread threads[num_threads];

	boost::posix_time::ptime start =
	    boost::posix_time::microsec_clock::universal_time();
	for (int i = 0; i < num_threads; ++i)
		threads[i] = std::thread([]() { write_some_log_entrys(); });

	for (auto &t : threads)
		t.join();
	boost::posix_time::time_duration time =
	    boost::posix_time::microsec_clock::universal_time() - start;
	double ms = time.total_milliseconds() /
		    static_cast<double>(num_loops * num_threads);
	return ms;
}

BOOST_AUTO_TEST_CASE(mlog_empty_test) {}

BOOST_AUTO_TEST_CASE(mlog_log2_test) {
	for (unsigned long i = 1; i < 1024 * 1024; i++)
		BOOST_CHECK_EQUAL(static_cast<unsigned long>(std::log2(i)),
				  mlog::log2(i));
}

BOOST_AUTO_TEST_CASE(mlog_memory_logger_1_test) {
	auto *log = new mlog::memory_logger<2>();
	mlog::mlogger.reset(log);
	MLOG_INFO("1");
	MLOG_INFO("2");
	BOOST_CHECK_EQUAL((*log)[0].text, "1");
	BOOST_CHECK_EQUAL((*log)[1].text, "2");
	BOOST_CHECK_EQUAL((*log)[2].text, "1"); // overflow
}

BOOST_AUTO_TEST_CASE(standard_logger_speed_test) {
	num_loops = 1000;
	mlog::mlogger.reset(new mlog::standard_logger());
	double st_result = single_thread_test();
	mlog::mlogger->use_thread_id(true);
	double st_result_thread_id = single_thread_test();
	mlog::mlogger->use_time(true);
	double st_result_thread_id_time = single_thread_test();
	mlog::mlogger->use_position(true);
	double st_result_thread_id_time_pos = single_thread_test();

	mlog::mlogger.reset(new mlog::standard_logger_thread_safe());
	double mt_result = multi_thread_test();
	mlog::mlogger->use_thread_id(true);
	double mt_result_thread_id = multi_thread_test();
	mlog::mlogger->use_time(true);
	double mt_result_thread_id_time = multi_thread_test();
	mlog::mlogger->use_position(true);
	double mt_result_thread_id_time_pos = multi_thread_test();

	std::cout << std::endl;
	std::cout << "### single-threaded standard logger test ###"
		  << std::endl;
	std::cout << st_result << "ms for each log statment." << std::endl;
	std::cout << st_result_thread_id
		  << "ms for each log statment with thread id." << std::endl;
	std::cout << st_result_thread_id_time
		  << "ms for each log statment with thread id and timestamp."
		  << std::endl;
	std::cout << st_result_thread_id_time_pos
		  << "ms for each log statment with thread id, timestamp and "
		     "position." << std::endl;
	std::cout << std::endl;
	std::cout << "### multi-threaded standard logger test ###" << std::endl;
	std::cout << mt_result << "ms for each log statment." << std::endl;
	std::cout << mt_result_thread_id
		  << "ms for each log statment with thread id." << std::endl;
	std::cout << mt_result_thread_id_time
		  << "ms for each log statment with thread id and timestamp."
		  << std::endl;
	std::cout << mt_result_thread_id_time_pos
		  << "ms for each log statment with thread id, timestamp and "
		     "position." << std::endl;
}

BOOST_AUTO_TEST_CASE(memory_logger_speed_test) {
	num_loops = 100000;
	mlog::mlogger.reset(new mlog::memory_logger_normal());
	double st_result = single_thread_test();
	mlog::mlogger->use_thread_id(true);
	double st_result_thread_id = single_thread_test();
	mlog::mlogger->use_time(true);
	double st_result_thread_id_time = single_thread_test();
	mlog::mlogger->use_position(true);
	double st_result_thread_id_time_pos = single_thread_test();

	double mt_result = multi_thread_test();
	mlog::mlogger->use_thread_id(true);
	double mt_result_thread_id = multi_thread_test();
	mlog::mlogger->use_time(true);
	double mt_result_thread_id_time = multi_thread_test();
	mlog::mlogger->use_position(true);
	double mt_result_thread_id_time_pos = multi_thread_test();

	std::cout << std::endl;
	std::cout << "### single-threaded memory logger test ###" << std::endl;
	std::cout << st_result << "ms for each log statment." << std::endl;
	std::cout << st_result_thread_id
		  << "ms for each log statment with thread id." << std::endl;
	std::cout << st_result_thread_id_time
		  << "ms for each log statment with thread id and timestamp."
		  << std::endl;
	std::cout << st_result_thread_id_time_pos
		  << "ms for each log statment with thread id, timestamp and "
		     "position." << std::endl;
	std::cout << std::endl;
	std::cout << "### multi-threaded memory logger test ###" << std::endl;
	std::cout << mt_result << "ms for each log statment." << std::endl;
	std::cout << mt_result_thread_id
		  << "ms for each log statment with thread id." << std::endl;
	std::cout << mt_result_thread_id_time
		  << "ms for each log statment with thread id and timestamp."
		  << std::endl;
	std::cout << mt_result_thread_id_time_pos
		  << "ms for each log statment with thread id, timestamp and "
		     "position." << std::endl;
	//*/
}

BOOST_AUTO_TEST_CASE(file_logger_speed_test) {
	num_loops = 100000;
	mlog::mlogger.reset(new mlog::file_logger("log.txt"));
	mlog::mlogger->use_time(false);
	double st_result = single_thread_test();
	mlog::mlogger->use_thread_id(true);
	double st_result_thread_id = single_thread_test();
	mlog::mlogger->use_time(true);
	double st_result_thread_id_time = single_thread_test();
	mlog::mlogger->use_position(true);
	double st_result_thread_id_time_pos = single_thread_test();

	mlog::mlogger.reset(new mlog::file_logger_thread_safe("log.txt"));
	mlog::mlogger->use_time(false);
	double mt_result = multi_thread_test();
	mlog::mlogger->use_thread_id(true);
	double mt_result_thread_id = multi_thread_test();
	mlog::mlogger->use_time(true);
	double mt_result_thread_id_time = multi_thread_test();
	mlog::mlogger->use_position(true);
	double mt_result_thread_id_time_pos = multi_thread_test();

	std::cout << std::endl;
	std::cout << "### single-threaded file logger test ###" << std::endl;
	std::cout << st_result << "ms for each log statment." << std::endl;
	std::cout << st_result_thread_id
		  << "ms for each log statment with thread id." << std::endl;
	std::cout << st_result_thread_id_time
		  << "ms for each log statment with thread id and timestamp."
		  << std::endl;
	std::cout << st_result_thread_id_time_pos
		  << "ms for each log statment with thread id, timestamp and "
		     "position." << std::endl;
	std::cout << std::endl;
	std::cout << "### multi-threaded file logger test ###" << std::endl;
	std::cout << mt_result << "ms for each log statment." << std::endl;
	std::cout << mt_result_thread_id
		  << "ms for each log statment with thread id." << std::endl;
	std::cout << mt_result_thread_id_time
		  << "ms for each log statment with thread id and timestamp."
		  << std::endl;
	std::cout << mt_result_thread_id_time_pos
		  << "ms for each log statment with thread id, timestamp and "
		     "position." << std::endl;
}

BOOST_AUTO_TEST_CASE(memory_logger_test) {
	num_loops = 100000;
	mlog::memory_logger<2048> *mem_log = new mlog::memory_logger<2048>();
	mlog::mlogger.reset(mem_log);
	mlog::mlogger->use_time(false);
	mlog::mlogger->use_thread_id(false);
	mlog::mlogger->use_time(false);

	for (std::size_t i = 0; i < 2048; i++) {
		MLOG_INFO(boost::format("%1%") % i);
	}

	for (std::size_t i = 0; i < 2048; i++) {
		BOOST_CHECK_EQUAL(
		    boost::lexical_cast<std::size_t>((*mem_log)[i].text), i);
	}

	// std::cout << *mem_log << std::endl;
}

BOOST_AUTO_TEST_CASE(memory_logger_test_small) {
	num_loops = 100000;
	mlog::memory_logger<4> *mem_log = new mlog::memory_logger<4>();
	mlog::mlogger.reset(mem_log);
	mlog::mlogger->use_time(false);
	mlog::mlogger->use_thread_id(false);
	mlog::mlogger->use_time(false);

	for (std::size_t i = 0; i < 1024*1024; i++) {
		MLOG_INFO(boost::format("%1%") % i);
	}

}
#ifdef _MSC_VER
BOOST_AUTO_TEST_CASE(memory_leak) {
	std::cout << "msvc will detect a memory leak at the end of this "
		     "program. - it's a false positive." << std::endl;
}
#endif
// */
<|endoftext|>


<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <iostream>
#include <nix/file/Directory.hpp>
#include "../../include/nix/file/Directory.hpp"
#include "../../include/nix/base/IFile.hpp"

using namespace std;

using namespace boost::filesystem;

namespace nix {
namespace file {

Directory::Directory(const path &location, FileMode mode)
    : loc(location), mode(mode) {
    open_or_create();
    attributes = AttributesFS(loc, mode);
}

Directory::Directory(const string &location, FileMode mode): Directory(path(location.c_str()), mode) {}

void Directory::open_or_create() {
   // path temp = current_path();
   // current_path(parent);
    if (!exists(loc)) {
        if (mode > FileMode::ReadOnly) {
            create_directories(loc);
        } else {
            throw std::logic_error("Trying to create new directory in ReadOnly mode!");
        }
    }
    // current_path(temp);
}

bool Directory::hasAttr(const string &name) const  {
    return attributes.has(name);
}

void Directory::removeAttr(const string &name) {
    attributes.remove(name);
}

string Directory::location() const {
    return loc.string();
}

} // nix::file
} // nix<commit_msg>[file_backend/Directory] cleanup<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <iostream>
#include <nix/file/Directory.hpp>
#include "../../include/nix/file/Directory.hpp"
#include "../../include/nix/base/IFile.hpp"

using namespace std;

using namespace boost::filesystem;

namespace nix {
namespace file {

Directory::Directory(const path &location, FileMode mode)
    : loc(location), mode(mode) {
    open_or_create();
    attributes = AttributesFS(loc, mode);
}

Directory::Directory(const string &location, FileMode mode): Directory(path(location.c_str()), mode) {}

void Directory::open_or_create() {
    if (!exists(loc)) {
        if (mode > FileMode::ReadOnly) {
            create_directories(loc);
        } else {
            throw std::logic_error("Trying to create new directory in ReadOnly mode!");
        }
    }
}

bool Directory::hasAttr(const string &name) const  {
    return attributes.has(name);
}

void Directory::removeAttr(const string &name) {
    attributes.remove(name);
}

string Directory::location() const {
    return loc.string();
}

} // nix::file
} // nix<|endoftext|>


<commit_before>
#include <boost/asio.hpp>
#include <google/protobuf/service.h>
#include <google/protobuf/descriptor.h>

#include "vtrc-bind.h"
#include "vtrc-function.h"

#include "vtrc-common/vtrc-data-queue.h"
#include "vtrc-common/vtrc-hash-iface.h"
#include "vtrc-common/vtrc-transformer-iface.h"
#include "vtrc-common/vtrc-call-context.h"
#include "vtrc-common/vtrc-rpc-controller.h"
#include "vtrc-common/vtrc-random-device.h"

#include "vtrc-protocol-layer-c.h"
#include "vtrc-transport-iface.h"

#include "vtrc-client.h"
#include "vtrc-chrono.h"

#include "protocol/vtrc-auth.pb.h"
#include "protocol/vtrc-rpc-lowlevel.pb.h"

namespace vtrc { namespace client {

    namespace gpb = google::protobuf;

    namespace {
        typedef vtrc::shared_ptr <
            vtrc_rpc_lowlevel::lowlevel_unit
        > lowlevel_unit_sptr;

        typedef vtrc::shared_ptr<gpb::Service> service_str;

    }

    struct protocol_layer_c::impl {

        typedef impl this_type;
        typedef protocol_layer_c parent_type;

        typedef vtrc::function<void (void)> stage_funcion_type;

        common::transport_iface     *connection_;
        protocol_layer_c            *parent_;
        stage_funcion_type           stage_call_;
        vtrc_client                 *client_;

        impl( common::transport_iface *c, vtrc_client *client )
            :connection_(c)
            ,client_(client)
        {
            stage_call_ = vtrc::bind( &this_type::on_hello_call, this );
        }

        void init( )
        {

        }

        common::rpc_service_wrapper_sptr get_service_by_name(
                                                      const std::string &name )
        {
            return common::rpc_service_wrapper_sptr
                        (new common::rpc_service_wrapper(
                                             client_->get_rpc_handler( name )));
        }

        void pop_message( )
        {
            parent_->pop_message( );
        }

        void send_proto_message( const gpb::Message &mess ) const
        {
            std::string s(mess.SerializeAsString( ));
            connection_->write(s.c_str( ), s.size( ) );
        }

        void send_proto_message( const gpb::Message &mess,
                                 common::closure_type closure,
                                 bool on_send ) const
        {
            std::string s(mess.SerializeAsString( ));
            connection_->write(s.c_str( ), s.size( ), closure, on_send );
        }

        void process_event_impl( vtrc_client_wptr client,
                                 lowlevel_unit_sptr llu)
        {
            vtrc_client_sptr c(client.lock( ));
            if( !c ) return;
            parent_->make_call( llu );
        }

        void process_event( lowlevel_unit_sptr &llu )
        {
            client_->get_rpc_service( ).post(
                vtrc::bind( &this_type::process_event_impl, this,
                             client_->weak_from_this( ), llu));
        }

        void process_service( lowlevel_unit_sptr &llu )
        {

        }

        void process_internal( lowlevel_unit_sptr &llu )
        {

        }

        void process_call( lowlevel_unit_sptr &llu )
        {
            parent_->push_rpc_message( llu->id( ), llu );
        }

        void process_callback( lowlevel_unit_sptr &llu )
        {
            parent_->push_rpc_message( llu->id( ), llu );
        }

        void process_invalid( lowlevel_unit_sptr &llu )
        {
//            llu->Clear( );
//            parent_->send_message( *llu );
        }

        void on_ready( bool ready )
        {
            parent_->set_ready( ready );
            client_->on_ready_( );
        }

        void on_rpc_process( )
        {
            while( !parent_->message_queue( ).empty( ) ) {

                std::string &mess (parent_->message_queue( ).front( ));

                bool check = parent_->check_message( mess );

                lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>());

                if( !check ) {

                    vtrc_errors::container *err = llu->mutable_error( );
                    err->set_code(vtrc_errors::ERR_PROTOCOL);
                    err->set_additional("Bad message was received");
                    err->set_fatal( true );

                    parent_->push_rpc_message_all( llu );
                    connection_->close( );

                    return;
                }

                parent_->parse_message( mess, *llu );

                switch( llu->info( ).message_type( ) ) {

                case vtrc_rpc_lowlevel::message_info::MESSAGE_EVENT:
                    process_event( llu );
                    break;
                case vtrc_rpc_lowlevel::message_info::MESSAGE_CALLBACK:
                    process_callback( llu );
                    break;
                case vtrc_rpc_lowlevel::message_info::MESSAGE_SERVICE:
                    process_service( llu );
                    break;
                case vtrc_rpc_lowlevel::message_info::MESSAGE_INTERNAL:
                    process_internal( llu );
                    break;
                case vtrc_rpc_lowlevel::message_info::MESSAGE_CALL:
                case vtrc_rpc_lowlevel::message_info::MESSAGE_INSERTION_CALL:
                    process_call( llu );
                    break;
                default:
                    process_invalid( llu );
                }

                pop_message( );
            }
        }

        void on_server_ready( )
        {

            std::string &mess = parent_->message_queue( ).front( );
            bool check = parent_->check_message( mess );

            vtrc_auth::init_capsule capsule;

            if( check ) {
                parent_->parse_message( mess, capsule );
            } else {
                connection_->close( );
                return;
            }

            pop_message( );

            stage_call_ = vtrc::bind( &this_type::on_rpc_process, this );

            on_ready( true );
        }

        void on_transform_setup( )
        {
            std::string &mess = parent_->message_queue( ).front( );
            bool check = parent_->check_message( mess );

            if( !check ) {
                connection_->close( );
                return;
            }

            vtrc_auth::init_capsule capsule;
            parent_->parse_message( mess, capsule );

            parent_->pop_message( );

            if( !capsule.ready( ) ) {
                connection_->close( );
                return;
            }

            vtrc_auth::transformer_setup tsetup;

            tsetup.ParseFromString( capsule.body( ) );

            std::string key(client_->get_session_key( ));

            std::string s1(tsetup.salt1( ));
            std::string s2(tsetup.salt2( ));

            common::transformers::create_key( key, s1, s2, key );

            common::transformer_iface *new_transformer =
                    common::transformers::erseefor::create( key.c_str( ),
                                                            key.size( ) );

            parent_->change_transformer( new_transformer );

            key.assign( client_->get_session_key( ) );
            common::transformers::generate_key_infos( key, s1, s2, key );

            tsetup.set_salt1( s1 );
            tsetup.set_salt2( s2 );

            common::transformer_iface *new_reverter =
                    common::transformers::erseefor::create( key.c_str( ),
                                                            key.size( ) );

            parent_->change_reverter( new_reverter );

            capsule.set_ready( true );
            capsule.set_body( tsetup.SerializeAsString( ) );

            stage_call_ = vtrc::bind( &this_type::on_server_ready, this );

            send_proto_message( capsule );

        }

        void set_options( const boost::system::error_code &err )
        {
            if( !err ) {
                std::cout << "set opts\n";
                parent_->change_hash_maker(
                   common::hash::create_by_index( vtrc_auth::HASH_CRC_32 ));
            }
        }

        void on_hello_call( )
        {
            std::string &mess = parent_->message_queue( ).front( );
            bool check = parent_->check_message( mess );

            if( !check ) {
                connection_->close( );
                return;
            }

            vtrc_auth::init_capsule capsule;

            parent_->parse_message( mess, capsule );

            if( !capsule.ready( ) ) {
                connection_->close( );
                return;
            }

            pop_message( );

            vtrc_auth::client_selection init;

            capsule.set_ready( true );
            capsule.set_text( "Miten menee?" );

            bool key_set = client_->is_key_set( );

            if( !key_set ) {
                init.set_transform( vtrc_auth::TRANSFORM_NONE );
            } else {
                init.set_transform( vtrc_auth::TRANSFORM_ERSEEFOR );
                init.set_id( client_->get_session_id( ) );
            }

            init.set_hash( vtrc_auth::HASH_CRC_32 );

            capsule.set_body( init.SerializeAsString( ) );

            parent_->change_hash_checker(
               common::hash::create_by_index( vtrc_auth::HASH_CRC_32 ));

            stage_call_ = vtrc::bind(
                        key_set
                        ? &this_type::on_transform_setup
                        : &this_type::on_server_ready, this );

            send_proto_message( capsule,
                                vtrc::bind( &this_type::set_options, this, _1 ),
                                false );

        }

        void data_ready( )
        {
            stage_call_( );
        }

    };

    protocol_layer_c::protocol_layer_c( common::transport_iface *connection,
                                        vtrc::client::vtrc_client *client )
        :common::protocol_layer(connection, true)
        ,impl_(new impl(connection, client))
    {
        impl_->parent_ = this;
    }

    protocol_layer_c::~protocol_layer_c( )
    {
        delete impl_;
    }

    void protocol_layer_c::init( )
    {
        impl_->init( );
    }

    void protocol_layer_c::close( )
    {
        impl_->client_->on_disconnect_( );
    }

    void protocol_layer_c::on_data_ready( )
    {
        impl_->data_ready( );
    }

    common::rpc_service_wrapper_sptr protocol_layer_c::get_service_by_name(
                                                        const std::string &name)
    {
        return impl_->get_service_by_name( name );
    }

}}
<commit_msg>proto<commit_after>
#include <boost/asio.hpp>
#include <google/protobuf/service.h>
#include <google/protobuf/descriptor.h>

#include "vtrc-bind.h"
#include "vtrc-function.h"

#include "vtrc-common/vtrc-data-queue.h"
#include "vtrc-common/vtrc-hash-iface.h"
#include "vtrc-common/vtrc-transformer-iface.h"
#include "vtrc-common/vtrc-call-context.h"
#include "vtrc-common/vtrc-rpc-controller.h"
#include "vtrc-common/vtrc-random-device.h"

#include "vtrc-protocol-layer-c.h"
#include "vtrc-transport-iface.h"

#include "vtrc-client.h"
#include "vtrc-chrono.h"

#include "protocol/vtrc-auth.pb.h"
#include "protocol/vtrc-rpc-lowlevel.pb.h"

namespace vtrc { namespace client {

    namespace gpb = google::protobuf;

    namespace {
        typedef vtrc::shared_ptr <
            vtrc_rpc_lowlevel::lowlevel_unit
        > lowlevel_unit_sptr;

        typedef vtrc::shared_ptr<gpb::Service> service_str;

    }

    struct protocol_layer_c::impl {

        typedef impl this_type;
        typedef protocol_layer_c parent_type;

        typedef vtrc::function<void (void)> stage_funcion_type;

        common::transport_iface     *connection_;
        protocol_layer_c            *parent_;
        stage_funcion_type           stage_call_;
        vtrc_client                 *client_;

        impl( common::transport_iface *c, vtrc_client *client )
            :connection_(c)
            ,client_(client)
        {
            stage_call_ = vtrc::bind( &this_type::on_hello_call, this );
        }

        void init( )
        {

        }

        common::rpc_service_wrapper_sptr get_service_by_name(
                                                      const std::string &name )
        {
            return common::rpc_service_wrapper_sptr
                        (new common::rpc_service_wrapper(
                                             client_->get_rpc_handler( name )));
        }

        void pop_message( )
        {
            parent_->pop_message( );
        }

        void send_proto_message( const gpb::Message &mess ) const
        {
            std::string s(mess.SerializeAsString( ));
            connection_->write(s.c_str( ), s.size( ) );
        }

        void send_proto_message( const gpb::Message &mess,
                                 common::closure_type closure,
                                 bool on_send ) const
        {
            std::string s(mess.SerializeAsString( ));
            connection_->write(s.c_str( ), s.size( ), closure, on_send );
        }

        void process_event_impl( vtrc_client_wptr client,
                                 lowlevel_unit_sptr llu)
        {
            vtrc_client_sptr c(client.lock( ));
            if( !c ) return;
            parent_->make_call( llu );
        }

        void process_event( lowlevel_unit_sptr &llu )
        {
            client_->get_rpc_service( ).post(
                vtrc::bind( &this_type::process_event_impl, this,
                             client_->weak_from_this( ), llu));
        }

        void process_service( lowlevel_unit_sptr &llu )
        {

        }

        void process_internal( lowlevel_unit_sptr &llu )
        {

        }

        void process_call( lowlevel_unit_sptr &llu )
        {
            parent_->push_rpc_message( llu->id( ), llu );
        }

        void process_callback( lowlevel_unit_sptr &llu )
        {
            parent_->push_rpc_message( llu->id( ), llu );
        }

        void process_invalid( lowlevel_unit_sptr &llu )
        {
//            llu->Clear( );
//            parent_->send_message( *llu );
        }

        void on_ready( bool ready )
        {
            parent_->set_ready( ready );
            client_->on_ready_( );
        }

        void on_rpc_process( )
        {
            while( !parent_->message_queue( ).empty( ) ) {

                std::string &mess (parent_->message_queue( ).front( ));

                bool check = parent_->check_message( mess );

                lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>());

                if( !check ) {

                    vtrc_errors::container *err = llu->mutable_error( );
                    err->set_code(vtrc_errors::ERR_PROTOCOL);
                    err->set_additional("Bad message was received");
                    err->set_fatal( true );

                    parent_->push_rpc_message_all( llu );
                    connection_->close( );

                    return;
                }

                parent_->parse_message( mess, *llu );

                switch( llu->info( ).message_type( ) ) {

                case vtrc_rpc_lowlevel::message_info::MESSAGE_EVENT:
                    process_event( llu );
                    break;
                case vtrc_rpc_lowlevel::message_info::MESSAGE_CALLBACK:
                    process_callback( llu );
                    break;
                case vtrc_rpc_lowlevel::message_info::MESSAGE_SERVICE:
                    process_service( llu );
                    break;
                case vtrc_rpc_lowlevel::message_info::MESSAGE_INTERNAL:
                    process_internal( llu );
                    break;
                case vtrc_rpc_lowlevel::message_info::MESSAGE_CALL:
                case vtrc_rpc_lowlevel::message_info::MESSAGE_INSERTION_CALL:
                    process_call( llu );
                    break;
                default:
                    process_invalid( llu );
                }

                pop_message( );
            }
        }

        void on_server_ready( )
        {

            std::string &mess = parent_->message_queue( ).front( );
            bool check = parent_->check_message( mess );

            vtrc_auth::init_capsule capsule;

            if( check ) {
                parent_->parse_message( mess, capsule );
            } else {
                connection_->close( );
                return;
            }

            pop_message( );

            stage_call_ = vtrc::bind( &this_type::on_rpc_process, this );

            on_ready( true );
        }

        void on_transform_setup( )
        {
            using namespace common::transformers;
            std::string &mess = parent_->message_queue( ).front( );
            bool check = parent_->check_message( mess );

            if( !check ) {
                connection_->close( );
                return;
            }

            vtrc_auth::init_capsule capsule;
            parent_->parse_message( mess, capsule );

            parent_->pop_message( );

            if( !capsule.ready( ) ) {
                connection_->close( );
                return;
            }

            vtrc_auth::transformer_setup tsetup;

            tsetup.ParseFromString( capsule.body( ) );

            std::string key(client_->get_session_key( ));

            std::string s1(tsetup.salt1( ));
            std::string s2(tsetup.salt2( ));

            create_key( key, s1, s2, key );

            common::transformer_iface *new_transformer =
                                erseefor::create( key.c_str( ), key.size( ) );

            parent_->change_transformer( new_transformer );

            key.assign( client_->get_session_key( ) );
            generate_key_infos( key, s1, s2, key );

            tsetup.set_salt1( s1 );
            tsetup.set_salt2( s2 );

            common::transformer_iface *new_reverter =
                                erseefor::create( key.c_str( ), key.size( ) );

            parent_->change_reverter( new_reverter );

            capsule.set_ready( true );
            capsule.set_body( tsetup.SerializeAsString( ) );

            stage_call_ = vtrc::bind( &this_type::on_server_ready, this );

            send_proto_message( capsule );

        }

        void set_options( const boost::system::error_code &err )
        {
            if( !err ) {
                std::cout << "set opts\n";
                parent_->change_hash_maker(
                   common::hash::create_by_index( vtrc_auth::HASH_CRC_32 ));
            }
        }

        void on_hello_call( )
        {
            std::string &mess = parent_->message_queue( ).front( );
            bool check = parent_->check_message( mess );

            if( !check ) {
                connection_->close( );
                return;
            }

            vtrc_auth::init_capsule capsule;

            parent_->parse_message( mess, capsule );

            if( !capsule.ready( ) ) {
                connection_->close( );
                return;
            }

            pop_message( );

            vtrc_auth::client_selection init;

            capsule.set_ready( true );
            capsule.set_text( "Miten menee?" );

            bool key_set = client_->is_key_set( );

            if( !key_set ) {
                init.set_transform( vtrc_auth::TRANSFORM_NONE );
            } else {
                init.set_transform( vtrc_auth::TRANSFORM_ERSEEFOR );
                init.set_id( client_->get_session_id( ) );
            }

            init.set_hash( vtrc_auth::HASH_CRC_32 );

            capsule.set_body( init.SerializeAsString( ) );

            parent_->change_hash_checker(
               common::hash::create_by_index( vtrc_auth::HASH_CRC_32 ));

            stage_call_ = vtrc::bind(
                        key_set
                        ? &this_type::on_transform_setup
                        : &this_type::on_server_ready, this );

            send_proto_message( capsule,
                                vtrc::bind( &this_type::set_options, this, _1 ),
                                false );

        }

        void data_ready( )
        {
            stage_call_( );
        }

    };

    protocol_layer_c::protocol_layer_c( common::transport_iface *connection,
                                        vtrc::client::vtrc_client *client )
        :common::protocol_layer(connection, true)
        ,impl_(new impl(connection, client))
    {
        impl_->parent_ = this;
    }

    protocol_layer_c::~protocol_layer_c( )
    {
        delete impl_;
    }

    void protocol_layer_c::init( )
    {
        impl_->init( );
    }

    void protocol_layer_c::close( )
    {
        impl_->client_->on_disconnect_( );
    }

    void protocol_layer_c::on_data_ready( )
    {
        impl_->data_ready( );
    }

    common::rpc_service_wrapper_sptr protocol_layer_c::get_service_by_name(
                                                        const std::string &name)
    {
        return impl_->get_service_by_name( name );
    }

}}
<|endoftext|>


<commit_before>#include <iostream>

static constexpr unsigned getSequenceLength(unsigned number) noexcept
{
        unsigned length = 0;

        while (number != 1) {
                if ((number & 1) == 0) {
                        number >>= 1;
                } else {
                        number = 3 * number + 1;
                }

                ++length;
        }

        return length;
}

int main(int count, char *arguments[])
{
        unsigned number = 999999;
        unsigned maximum = 0;

        for (unsigned i = 999999; i > 0; --i) {
                unsigned length = getSequenceLength(i);

                if (length > maximum) {
                        maximum = length;
                        number = i;
                }
        }

        std::cout << number << '\n';
        return 0;
}<commit_msg>Switch to better variable name<commit_after>#include <iostream>

static constexpr unsigned getSequenceLength(unsigned number) noexcept
{
        unsigned length = 0;

        while (number != 1) {
                if ((number & 1) == 0) {
                        number >>= 1;
                } else {
                        number = 3 * number + 1;
                }

                ++length;
        }

        return length;
}

int main(int count, char *arguments[])
{
        unsigned number = 999999;
        unsigned sequenceLength = 0;

        for (unsigned i = 999999; i > 0; --i) {
                unsigned length = getSequenceLength(i);

                if (length > sequenceLength) {
                        number = i;
                        sequenceLength = length;
                }
        }

        std::cout << number << '\n';
        return 0;
}<|endoftext|>


<commit_before>// Copyright 2012 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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.

#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <exception>
using std::exception;
#include <iomanip>
using std::fixed;
using std::setprecision;
#include <limits>
using std::numeric_limits;
#include <cmath>
#include <ctime>

#include <ArgumentList.hpp>
using isa::utils::ArgumentList;
#include <Observation.hpp>
using AstroData::Observation;
#include <InitializeOpenCL.hpp>
using isa::OpenCL::initializeOpenCL;
#include <CLData.hpp>
using isa::OpenCL::CLData;
#include <utils.hpp>
using isa::utils::same;
#include <Folding.hpp>
using PulsarSearch::Folding;
#include <FoldingCPU.hpp>
using PulsarSearch::folding;
#include <Bins.hpp>
using PulsarSearch::getNrSamplesPerBin;

typedef float dataType;
const string typeName("float");

int main(int argc, char *argv[]) {
  bool print = false;
	unsigned int clPlatformID = 0;
	unsigned int clDeviceID = 0;
	long long unsigned int wrongValues = 0;
	Observation< dataType > observation("FoldingTest", typeName);
	CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true);
	CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true);
	CLData< unsigned int > * readCounterData = new CLData< unsigned int >("ReadCounterData", true);
	CLData< unsigned int > * writeCounterData = new CLData< unsigned int >("WriteCounterData", true);
	CLData< unsigned int > * nrSamplesPerBin = new CLData< unsigned int >("NrSamplesPerBin", true);

	try {
		ArgumentList args(argc, argv);

		clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
		clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");

    print = args.getSwitch("-print");
    observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
    observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
		observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms"));
		observation.setNrPeriods(args.getSwitchArgument< unsigned int >("-periods"));
		observation.setFirstPeriod(args.getSwitchArgument< unsigned int >("-period_first"));
		observation.setPeriodStep(args.getSwitchArgument< unsigned int >("-period_step"));
		observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins"));

	} catch ( exception &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	cl::Context * clContext = new cl::Context();
	vector< cl::Platform > * clPlatforms = new vector< cl::Platform >();
	vector< cl::Device > * clDevices = new vector< cl::Device >();
	vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();

	initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);

	// Allocate memory
	dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());
	foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
	foldedData->blankHostData();
	readCounterData->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins());
	readCounterData->blankHostData();
	writeCounterData->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins());
	writeCounterData->blankHostData();
	vector< unsigned int > * nrSamplesPerBinData = getNrSamplesPerBin(observation);
	nrSamplesPerBin->allocateHostData(*nrSamplesPerBinData);

	dedispersedData->setCLContext(clContext);
	dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	foldedData->setCLContext(clContext);
	foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	readCounterData->setCLContext(clContext);
	readCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	writeCounterData->setCLContext(clContext);
	writeCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	nrSamplesPerBin->setCLContext(clContext);
	nrSamplesPerBin->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	nrSamplesPerBin->setDeviceReadOnly();

	try {
		dedispersedData->allocateDeviceData();
		foldedData->allocateDeviceData();
		foldedData->copyHostToDevice();
		readCounterData->allocateDeviceData();
		readCounterData->copyHostToDevice();
		writeCounterData->allocateDeviceData();
		writeCounterData->copyHostToDevice();
		nrSamplesPerBin->allocateDeviceData();
		nrSamplesPerBin->copyHostToDevice();
	} catch ( OpenCLError &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	srand(time(NULL));
	for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
		for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
			dedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100);
		}
	}

	// Test
	try {
		// Generate kernel
		Folding< dataType > clFold("clFold", typeName);
		clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));
		clFold.setObservation(&observation);
		clFold.setNrSamplesPerBin(nrSamplesPerBin);
		clFold.setNrDMsPerBlock(128);
		clFold.setNrPeriodsPerBlock(2);
		clFold.setNrBinsPerBlock(1);
		clFold.setNrDMsPerThread(2);
		clFold.setNrPeriodsPerThread(2);
		clFold.setNrBinsPerThread(4);
		clFold.generateCode();

		dedispersedData->copyHostToDevice();
		clFold(0, dedispersedData, foldedData, readCounterData, writeCounterData);
		foldedData->copyDeviceToHost();
	} catch ( OpenCLError &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Check
	CLData< dataType > * CPUFolded = new CLData<dataType >("CPUFolded", true);
	CLData< unsigned int > * CPUCounter = new CLData< unsigned int >("CPUCounter", true);
	CPUFolded->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
	CPUCounter->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins());
	CPUCounter->blankHostData();
	folding(0, observation, dedispersedData->getHostData(), CPUFolded->getHostData(), CPUCounter->getHostData());
	for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {
		long long unsigned int wrongValuesBin = 0;

		for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
			for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
				const unsigned int dataItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM;
				if ( !same(CPUFolded->getHostDataItem(dataItem), foldedData->getHostDataItem(dataItem)) ) {
					wrongValues++;
					wrongValuesBin++;
				}
			}
		}

		if ( wrongValuesBin > 0 && print ) {
			cout << "Wrong samples bin " << bin << ": " << wrongValuesBin << " (" << (wrongValuesBin * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << "%)." << endl;
		}
	}

	cout << endl;
  if ( wrongValues > 0 ) {
  	cout << "Wrong samples: " << wrongValues << " (" << (wrongValues * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << "%)." << endl;
  } else {
    cout << "TEST PASSED." << endl;
  }
	cout << endl;

	return 0;
}

<commit_msg>Configuration of OpenCL Folding passed to the test through command line.<commit_after>// Copyright 2012 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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.

#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <exception>
using std::exception;
#include <iomanip>
using std::fixed;
using std::setprecision;
#include <limits>
using std::numeric_limits;
#include <cmath>
#include <ctime>

#include <ArgumentList.hpp>
using isa::utils::ArgumentList;
#include <Observation.hpp>
using AstroData::Observation;
#include <InitializeOpenCL.hpp>
using isa::OpenCL::initializeOpenCL;
#include <CLData.hpp>
using isa::OpenCL::CLData;
#include <utils.hpp>
using isa::utils::same;
#include <Folding.hpp>
using PulsarSearch::Folding;
#include <FoldingCPU.hpp>
using PulsarSearch::folding;
#include <Bins.hpp>
using PulsarSearch::getNrSamplesPerBin;

typedef float dataType;
const string typeName("float");

int main(int argc, char *argv[]) {
  bool print = false;
	unsigned int clPlatformID = 0;
	unsigned int clDeviceID = 0;
  unsigned int nrDMsPerBlock = 0;
  unsigned int nrPeriodsPerBlock = 0;
  unsigned int nrBinsPerBlock = 0;
  unsigned int nrDMsPerThread = 0;
  unsigned int nrPeriodsPerThread = 0;
  unsigned int nrBinsPerThread = 0;
	long long unsigned int wrongValues = 0;
	Observation< dataType > observation("FoldingTest", typeName);
	CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true);
	CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true);
	CLData< unsigned int > * readCounterData = new CLData< unsigned int >("ReadCounterData", true);
	CLData< unsigned int > * writeCounterData = new CLData< unsigned int >("WriteCounterData", true);
	CLData< unsigned int > * nrSamplesPerBin = new CLData< unsigned int >("NrSamplesPerBin", true);

	try {
		ArgumentList args(argc, argv);

		clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
		clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");

    print = args.getSwitch("-print");
    observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
    nrDMsPerBlock = args.getSwitchArgument< unsigned int >("-db");
    nrPeriodsPerBlock = args.getSwitchArgument< unsigned int >("-pb");
    nrBinsPerBlock = args.getSwitchArgument< unsigned int >("-bb");
    nrDMsPerThread = args.getSwitchArgument< unsigned int >("-dt");
    nrPeriodsPerThread = args.getSwitchArgument< unsigned int >("-pt");
    nrBinsPerThread = args.getSwitchArgument< unsigned int >("-bt");
    observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
		observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms"));
		observation.setNrPeriods(args.getSwitchArgument< unsigned int >("-periods"));
		observation.setFirstPeriod(args.getSwitchArgument< unsigned int >("-period_first"));
		observation.setPeriodStep(args.getSwitchArgument< unsigned int >("-period_step"));
		observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins"));

	} catch ( exception &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	cl::Context * clContext = new cl::Context();
	vector< cl::Platform > * clPlatforms = new vector< cl::Platform >();
	vector< cl::Device > * clDevices = new vector< cl::Device >();
	vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();

	initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);

	// Allocate memory
	dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());
	foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
	foldedData->blankHostData();
	readCounterData->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins());
	readCounterData->blankHostData();
	writeCounterData->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins());
	writeCounterData->blankHostData();
	vector< unsigned int > * nrSamplesPerBinData = getNrSamplesPerBin(observation);
	nrSamplesPerBin->allocateHostData(*nrSamplesPerBinData);

	dedispersedData->setCLContext(clContext);
	dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	foldedData->setCLContext(clContext);
	foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	readCounterData->setCLContext(clContext);
	readCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	writeCounterData->setCLContext(clContext);
	writeCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	nrSamplesPerBin->setCLContext(clContext);
	nrSamplesPerBin->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	nrSamplesPerBin->setDeviceReadOnly();

	try {
		dedispersedData->allocateDeviceData();
		foldedData->allocateDeviceData();
		foldedData->copyHostToDevice();
		readCounterData->allocateDeviceData();
		readCounterData->copyHostToDevice();
		writeCounterData->allocateDeviceData();
		writeCounterData->copyHostToDevice();
		nrSamplesPerBin->allocateDeviceData();
		nrSamplesPerBin->copyHostToDevice();
	} catch ( OpenCLError &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	srand(time(NULL));
	for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
		for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
			dedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100);
		}
	}

	// Test
	try {
		// Generate kernel
		Folding< dataType > clFold("clFold", typeName);
		clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));
		clFold.setObservation(&observation);
		clFold.setNrSamplesPerBin(nrSamplesPerBin);
		clFold.setNrDMsPerBlock(nrDMsPerBlock);
		clFold.setNrPeriodsPerBlock(nrPeriodsPerBlock);
		clFold.setNrBinsPerBlock(nrBinsPerBlock);
		clFold.setNrDMsPerThread(nrDMsPerThread);
		clFold.setNrPeriodsPerThread(nrPeriodsPerThread);
		clFold.setNrBinsPerThread(nrBinsPerThread);
		clFold.generateCode();

		dedispersedData->copyHostToDevice();
		clFold(0, dedispersedData, foldedData, readCounterData, writeCounterData);
		foldedData->copyDeviceToHost();
	} catch ( OpenCLError &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Check
	CLData< dataType > * CPUFolded = new CLData<dataType >("CPUFolded", true);
	CLData< unsigned int > * CPUCounter = new CLData< unsigned int >("CPUCounter", true);
	CPUFolded->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
	CPUCounter->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins());
	CPUCounter->blankHostData();
	folding(0, observation, dedispersedData->getHostData(), CPUFolded->getHostData(), CPUCounter->getHostData());
	for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {
		long long unsigned int wrongValuesBin = 0;

		for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
			for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
				const unsigned int dataItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM;
				if ( !same(CPUFolded->getHostDataItem(dataItem), foldedData->getHostDataItem(dataItem)) ) {
					wrongValues++;
					wrongValuesBin++;
				}
			}
		}

		if ( wrongValuesBin > 0 && print ) {
			cout << "Wrong samples bin " << bin << ": " << wrongValuesBin << " (" << (wrongValuesBin * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << "%)." << endl;
		}
	}

	cout << endl;
  if ( wrongValues > 0 ) {
  	cout << "Wrong samples: " << wrongValues << " (" << (wrongValues * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << "%)." << endl;
  } else {
    cout << "TEST PASSED." << endl;
  }
	cout << endl;

	return 0;
}

<|endoftext|>


<commit_before>#include "dbcwriter.h"

#include <string>
#include <fstream>
#include <experimental/filesystem>

#include "fmt/fmtlib.h"

using namespace fmt::literals;

namespace
{

inline void write_header(std::ofstream& fs)
{
  // Empty version and required sections for normal DBC
  fs << "VERSION \"\"\n\nNS_:\n\nBS_:\n\n";
}

inline void write_nodes(std::ofstream& fs, const std::vector<std::string>& nodes)
{
  fs << "BU_:";
  if (!nodes.empty()) {
    fs << " ";
    auto last = std::end(nodes) - 1;
    for (auto it = std::begin(nodes); it != last; ++it)
      fs << *it << ',';
    fs << *last;
  }
  fs << "\n\n";
}

inline void write_frame_def(std::ofstream& fs, const dbc::Frame_def& fd)
{
  // BO_ id name: dlc transmitter
  fs << fmt::format(R"(BO_ {} {}: {} {})", fd.id, fd.name, fd.dlc,
      fd.transmitter.empty() ? "Vector__XXX" : fd.transmitter) << '\n';
}

inline void write_signal_def(std::ofstream& fs, const dbc::Signal_def& sd)
{
  auto to_string = [](auto&& receiver) {
    std::string s{receiver.front()};
    for (auto it = std::begin(receiver) + 1; it != std::end(receiver); ++it) {
      s += ',';
      s += *it;
    }
    return s;
  };

  // SG_ name : pos|len@order_and_type (factor,offset) [min|max] "unit" receiver{, receiver}
  fs << fmt::format(R"(  SG_ {} {}: {}|{}@{}{} ({:.{}f},{:.{}f}) [{:.{}f}|{:.{}f}] "{}" {})",
      sd.name,
      sd.multiplex_switch ? "M " : sd.multiplex_value > 0 ? "m{} "_format(sd.multiplex_value) : "",
      sd.pos,
      sd.len,
      static_cast<int>(sd.order),
      sd.sign == dbc::Value_sign::Signed ? "-" : "+",
      sd.factor,
      sd.meta_data.factor_precision,
      sd.offset,
      sd.meta_data.offset_precision,
      sd.minimum,
      sd.meta_data.minimum_precision,
      sd.maximum,
      sd.meta_data.maximum_precision,
      sd.unit,
      sd.receiver.empty() ? "Vector__XXX" : to_string(sd.receiver)
      ) << '\n';
}

}  // namespace

void dbc::write(const File& dbc_file, std::string_view filepath)
{
  std::ofstream fs{std::string{filepath}};
  if (!fs.is_open())
    throw Write_error{"Could not open file"};

  write_header(fs);
  write_nodes(fs, dbc_file.nodes);

  for (const auto& frame_def : dbc_file.frame_defs) {
    write_frame_def(fs, frame_def);
    for (const auto& signal_def : frame_def.signal_defs) {
      write_signal_def(fs, signal_def);
    }
    fs  << '\n';
  }
}
<commit_msg>Fix multiplex value error<commit_after>#include "dbcwriter.h"

#include <string>
#include <fstream>
#include <experimental/filesystem>

#include "fmt/fmtlib.h"

using namespace fmt::literals;

namespace
{

inline void write_header(std::ofstream& fs)
{
  // Empty version and required sections for normal DBC
  fs << "VERSION \"\"\n\nNS_:\n\nBS_:\n\n";
}

inline void write_nodes(std::ofstream& fs, const std::vector<std::string>& nodes)
{
  fs << "BU_:";
  if (!nodes.empty()) {
    fs << " ";
    auto last = std::end(nodes) - 1;
    for (auto it = std::begin(nodes); it != last; ++it)
      fs << *it << ',';
    fs << *last;
  }
  fs << "\n\n";
}

inline void write_frame_def(std::ofstream& fs, const dbc::Frame_def& fd)
{
  // BO_ id name: dlc transmitter
  fs << fmt::format(R"(BO_ {} {}: {} {})", fd.id, fd.name, fd.dlc,
      fd.transmitter.empty() ? "Vector__XXX" : fd.transmitter) << '\n';
}

inline void write_signal_def(std::ofstream& fs, const dbc::Signal_def& sd)
{
  auto to_string = [](auto&& receiver) {
    std::string s{receiver.front()};
    for (auto it = std::begin(receiver) + 1; it != std::end(receiver); ++it) {
      s += ',';
      s += *it;
    }
    return s;
  };

  // SG_ name : pos|len@order_and_type (factor,offset) [min|max] "unit" receiver{, receiver}
  fs << fmt::format(R"(  SG_ {} {}: {}|{}@{}{} ({:.{}f},{:.{}f}) [{:.{}f}|{:.{}f}] "{}" {})",
      sd.name,
      sd.multiplex_switch ? "M " : sd.multiplex_value >= 0 ? "m{} "_format(sd.multiplex_value) : "",
      sd.pos,
      sd.len,
      static_cast<int>(sd.order),
      sd.sign == dbc::Value_sign::Signed ? "-" : "+",
      sd.factor,
      sd.meta_data.factor_precision,
      sd.offset,
      sd.meta_data.offset_precision,
      sd.minimum,
      sd.meta_data.minimum_precision,
      sd.maximum,
      sd.meta_data.maximum_precision,
      sd.unit,
      sd.receiver.empty() ? "Vector__XXX" : to_string(sd.receiver)
      ) << '\n';
}

}  // namespace

void dbc::write(const File& dbc_file, std::string_view filepath)
{
  std::ofstream fs{std::string{filepath}};
  if (!fs.is_open())
    throw Write_error{"Could not open file"};

  write_header(fs);
  write_nodes(fs, dbc_file.nodes);

  for (const auto& frame_def : dbc_file.frame_defs) {
    write_frame_def(fs, frame_def);
    for (const auto& signal_def : frame_def.signal_defs) {
      write_signal_def(fs, signal_def);
    }
    fs  << '\n';
  }
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkContour.h"
#include "mitkDataNode.h"
#include "mitkContourMapper2D.h"
#include "mitkCommon.h"
#include "mitkStandaloneDataStorage.h"
#include "mitkGlobalInteraction.h"

#include "mitkVtkPropRenderer.h"

#include <fstream>

int mitkContourMapper2DTest(int /*argc*/, char* /*argv*/[])
{
  mitk::Contour::Pointer contour;
  mitk::ContourMapper2D::Pointer contourMapper;
  mitk::DataNode::Pointer node;

  // Global interaction must(!) be initialized if used
  mitk::GlobalInteraction::GetInstance()->Initialize("global");

  contourMapper = mitk::ContourMapper2D::New();
  node = mitk::DataNode::New();
  std::cout << "Testing mitk::ContourMapper2D::New(): ";

  contour = mitk::Contour::New();
  node->SetData(contour);

  if (contour.IsNull()) {
    std::cout << "[FAILED]" << std::endl;
    return EXIT_FAILURE;
  }
  else {
  std::cout<<"[PASSED]"<<std::endl;
  }

  contourMapper->SetDataNode( node );
  contourMapper->Update(NULL);
  mitk::Contour* testContour = (mitk::Contour*)contourMapper->GetInput();
  std::cout << testContour << std::endl;

  mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New();

  ds->Add( node );

  mitk::BoundingBox::Pointer bounds = ds->ComputeBoundingBox();

  std::cout << "bounds: " << bounds << std::endl;

  bounds = ds->ComputeVisibleBoundingBox();
  std::cout << "visible bounds: " << bounds << std::endl;

  vtkRenderWindow* renWin = vtkRenderWindow::New();

  mitk::VtkPropRenderer::Pointer renderer = mitk::VtkPropRenderer::New( "ContourRenderer",renWin, mitk::RenderingManager::GetInstance() );

  std::cout<<"Testing mitk::BaseRenderer::SetData()"<<std::endl;

  renderer->SetDataStorage(ds);

  std::cout<<"[TEST DONE]"<<std::endl;

  renWin->Delete();

  return EXIT_SUCCESS;
}
<commit_msg>Change in ContourMapper2DTest<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkContour.h"
#include "mitkDataNode.h"
#include "mitkContourMapper2D.h"
#include "mitkCommon.h"
#include "mitkStandaloneDataStorage.h"
#include "mitkGlobalInteraction.h"

#include "mitkVtkPropRenderer.h"

#include <fstream>

int mitkContourMapper2DTest(int /*argc*/, char* /*argv*/[])
{
  mitk::Contour::Pointer contour;
  mitk::ContourMapper2D::Pointer contourMapper;
  mitk::DataNode::Pointer node;

  // Global interaction must(!) be initialized if used
  mitk::GlobalInteraction::GetInstance()->Initialize("global");

  contourMapper = mitk::ContourMapper2D::New();
  node = mitk::DataNode::New();
  std::cout << "Testing mitk::ContourMapper2D::New(): ";

  contour = mitk::Contour::New();
  node->SetData(contour);

  if (contour.IsNull()) {
    std::cout << "[FAILED]" << std::endl;
    return EXIT_FAILURE;
  }
  else {
  std::cout<<"[PASSED]"<<std::endl;
  }

  contourMapper->SetDataNode( node );
  contourMapper->Update(NULL);
  mitk::Contour* testContour = (mitk::Contour*)contourMapper->GetInput();
  std::cout << testContour << std::endl;

  mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New();

  ds->Add( node );

  mitk::BoundingBox::Pointer bounds = ds->ComputeBoundingBox();

  std::cout << "bounds: " << bounds << std::endl;

  bounds = ds->ComputeVisibleBoundingBox();
  std::cout << "visible bounds: " << bounds << std::endl;

  vtkRenderWindow* renWin = vtkRenderWindow::New();

  mitk::VtkPropRenderer::Pointer renderer = mitk::VtkPropRenderer::New( "ContourRenderer",renWin, mitk::RenderingManager::GetInstance(),mitk::BaseRenderer::RenderingMode::Standard );

  std::cout<<"Testing mitk::BaseRenderer::SetData()"<<std::endl;

  renderer->SetDataStorage(ds);

  std::cout<<"[TEST DONE]"<<std::endl;

  renWin->Delete();

  return EXIT_SUCCESS;
}<|endoftext|>


<commit_before>/*
 * Scene.cpp
 *
 *  Created on: 24.01.2015
 *      Author: sartz
 */

#include "Scene.hpp"
#include "Tile.hpp"
#include "globals.hpp"
#include <iostream>
#include "GUI.hpp"
#include <math.h>
#include "globals.hpp"
#include "KeyItem.hpp"

Scene::Scene() {
	// TODO Auto-generated constructor stub
	gameBoard.resize(sizeX * sizeY * largeTileSizeX * largeTileSizeY);

}

Scene::~Scene() {
	// TODO Auto-generated destructor stub
}

GameObject* Scene::getTile(int x, int y)
{
	if (x + y*sizeX < (int)gameBoard.size())
	{
		return gameBoard[x + y * sizeX * largeTileSizeX];
	}
	return 0;
}

void Scene::setTile(GameObject* obj, int x, int y)
{
	gameBoard[x + y * sizeX * largeTileSizeX] = obj;
}

void Scene::setGUI(GUI* obj)
{
	gui = obj;
}

const std::vector<GameObject*> &Scene::getGameBoard() const
{
	return gameBoard;
}

void Scene::switchLargeTile(int x1, int y1, int x2, int y2)
{
	int startX1 = x1*largeTileSizeX;
	int startY1 = y1*largeTileSizeY;
	int startX2 = x2*largeTileSizeX;
	int startY2 = y2*largeTileSizeY;

	for (int x=0;x<largeTileSizeX;x++)
	{
		for (int y=0;y<largeTileSizeY;y++)
		{
			sf::Vector2f tmpPos = getTile(startX1+x, startY1+y)->getPosition();
			sf::Vector2f tmpPos2 = getTile(startX2+x, startY2+y)->getPosition();
			getTile(startX2+x, startY2+y)->setPosition(tmpPos.x, tmpPos.y);
			getTile(startX1+x, startY1+y)->setPosition(tmpPos2.x, tmpPos2.y);
		}
	}
}

void Scene::update(sf::Time deltaT)
{
//	if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
//	{
//		sf::Vector2i globalPosition = sf::Mouse::getPosition(window);
//
//		sf::Vector2f localPosition;
//		localPosition.x = 1.f*globalPosition.x/(Tile::pixelSizeX*Tile::tileScaleFactor);
//		localPosition.y = 1.f*globalPosition.y/(Tile::pixelSizeY*Tile::tileScaleFactor);
//		std::cout<<localPosition.x<<", "<<localPosition.y<<std::endl;
//	}
	/*for (std::vector<GameObject*>::iterator it = gameBoard.begin();it != gameBoard.end(); it++)
	{
		(*it)->update(deltaT);
		std::cout << (*it) << std::endl;
	}*/
	for(auto& obj: gameBoard) {
		obj->update(deltaT);
	}

	for(auto& obj: items) {
		obj.update(deltaT);
	}
	player->update(deltaT);
	if (gui != 0)
	{
		gui->update(deltaT);
	}

	/*
	// Text TEST
	sf::Vector2f textPos(32.0f, 32.0f);
	int charSize = 30;

	sf::Font font;
	font.loadFromFile(std::string(PATH) + "fonts/LiberationSerif-Regular.ttf");

	sf::Text Text;
	Text.setFont(font);

	Text.setColor(sf::Color(210, 210, 255));
	Text.setCharacterSize(charSize);
	Text.setPosition(textPos);

	sf::RectangleShape textRect;
	textRect.setOutlineColor(sf::Color::Blue);
	textRect.setOutlineThickness(5);
	textRect.setPosition(textPos.x - 5, textPos.y - 5);
	textRect.setSize(sf::Vector2f(screenWidth - 2* textPos.x + 10, 2 * charSize + 30));
	textRect.setFillColor(sf::Color(0, 0, 250, 50));
	window.draw(textRect);

	// zu Anfang:
	Text.setStyle(sf::Text::Bold);
	Text.setString("Oh no...");
	Text.setStyle(sf::Text::Regular);
	Text.setString("The time machine is broken, doggie!");
	Text.setString("...");
	Text.setString("What do we do now?");
	Text.setColor(sf::Color(210, 255, 210));
	Text.setString("SQOLRK");
	Text.setColor(sf::Color(210, 210, 255));

	// Zeit wird knapp:
	Text.setColor(sf::Color(210, 255, 210));
	Text.setString("LURMK");
	Text.setColor(sf::Color(210, 210, 255));
	Text.setString("You are right we should hurry. The pizza is going cold.");

	// Key aufgesammelt (erstes Level):
	Text.setColor(sf::Color(210, 210, 210));
	Text.setString("A key to another dimension!");
	Text.setColor(sf::Color(210, 210, 255));

	// Uhr aufgesammelt (erstes Level):
	Text.setColor(sf::Color(210, 210, 210));
	Text.setString("When do we do now?");
	Text.setColor(sf::Color(210, 210, 255));

	// Ziel erreicht, kein Key (erstes Level):
	Text.setString("We need a key for this dimension hole!");

	// Ziel erreicht (erstes Level):
	Text.setString("Do you want to leave, Doggie?");
	Text.setColor(sf::Color(210, 255, 210));
	Text.setString("Frravt");
	Text.setColor(sf::Color(210, 210, 255));

	window.draw(Text);
	*/
}

void Scene::leave()
{
	int size = items.size();
	int keysInLevel = 0;
	for(int i = 0;i < size;i++)
	{
		if (dynamic_cast<KeyItem*>(&items[i]))
		{
			keysInLevel++;
		}
	}
	if (keysInLevel > 0)
	{
		return;
	}
	gui->resetCoins();
	gui->resetKeys();
	sceneManager.nextLevel();
}
<commit_msg>besserer var name<commit_after>/*
 * Scene.cpp
 *
 *  Created on: 24.01.2015
 *      Author: sartz
 */

#include "Scene.hpp"
#include "Tile.hpp"
#include "globals.hpp"
#include <iostream>
#include "GUI.hpp"
#include <math.h>
#include "globals.hpp"
#include "KeyItem.hpp"

Scene::Scene() {
	// TODO Auto-generated constructor stub
	gameBoard.resize(sizeX * sizeY * largeTileSizeX * largeTileSizeY);

}

Scene::~Scene() {
	// TODO Auto-generated destructor stub
}

GameObject* Scene::getTile(int x, int y)
{
	if (x + y*sizeX < (int)gameBoard.size())
	{
		return gameBoard[x + y * sizeX * largeTileSizeX];
	}
	return 0;
}

void Scene::setTile(GameObject* obj, int x, int y)
{
	gameBoard[x + y * sizeX * largeTileSizeX] = obj;
}

void Scene::setGUI(GUI* obj)
{
	gui = obj;
}

const std::vector<GameObject*> &Scene::getGameBoard() const
{
	return gameBoard;
}

void Scene::switchLargeTile(int x1, int y1, int x2, int y2)
{
	int startX1 = x1*largeTileSizeX;
	int startY1 = y1*largeTileSizeY;
	int startX2 = x2*largeTileSizeX;
	int startY2 = y2*largeTileSizeY;

	for (int x=0;x<largeTileSizeX;x++)
	{
		for (int y=0;y<largeTileSizeY;y++)
		{
			sf::Vector2f tmpPos = getTile(startX1+x, startY1+y)->getPosition();
			sf::Vector2f tmpPos2 = getTile(startX2+x, startY2+y)->getPosition();
			getTile(startX2+x, startY2+y)->setPosition(tmpPos.x, tmpPos.y);
			getTile(startX1+x, startY1+y)->setPosition(tmpPos2.x, tmpPos2.y);
		}
	}
}

void Scene::update(sf::Time deltaT)
{
//	if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
//	{
//		sf::Vector2i globalPosition = sf::Mouse::getPosition(window);
//
//		sf::Vector2f localPosition;
//		localPosition.x = 1.f*globalPosition.x/(Tile::pixelSizeX*Tile::tileScaleFactor);
//		localPosition.y = 1.f*globalPosition.y/(Tile::pixelSizeY*Tile::tileScaleFactor);
//		std::cout<<localPosition.x<<", "<<localPosition.y<<std::endl;
//	}
	/*for (std::vector<GameObject*>::iterator it = gameBoard.begin();it != gameBoard.end(); it++)
	{
		(*it)->update(deltaT);
		std::cout << (*it) << std::endl;
	}*/
	for(auto& obj: gameBoard) {
		obj->update(deltaT);
	}

	for(auto& obj: items) {
		obj.update(deltaT);
	}
	player->update(deltaT);
	if (gui != 0)
	{
		gui->update(deltaT);
	}

	/*
	// Text TEST
	sf::Vector2f textPos(32.0f, 32.0f);
	int charSize = 30;

	sf::Font font;
	font.loadFromFile(std::string(PATH) + "fonts/LiberationSerif-Regular.ttf");

	sf::Text speech;
	speech.setFont(font);

	speech.setColor(sf::Color(210, 210, 255));
	speech.setCharacterSize(charSize);
	speech.setPosition(textPos);

	sf::RectangleShape textRect;
	textRect.setOutlineColor(sf::Color::Blue);
	textRect.setOutlineThickness(5);
	textRect.setPosition(textPos.x - 5, textPos.y - 5);
	textRect.setSize(sf::Vector2f(screenWidth - 2* textPos.x + 10, 2 * charSize + 30));
	textRect.setFillColor(sf::Color(0, 0, 250, 50));
	window.draw(textRect);

	// zu Anfang:
	speech.setStyle(sf::Text::Bold);
	speech.setString("Oh no...");
	speech.setStyle(sf::Text::Regular);
	speech.setString("The time machine is broken, doggie!");
	speech.setString("...");
	speech.setString("What do we do now?");
	speech.setColor(sf::Color(210, 255, 210));
	speech.setString("SQOLRK");
	speech.setColor(sf::Color(210, 210, 255));

	// Zeit wird knapp:
	speech.setColor(sf::Color(210, 255, 210));
	speech.setString("LURMK");
	speech.setColor(sf::Color(210, 210, 255));
	speech.setString("You are right we should hurry. The pizza is going cold.");

	// Key aufgesammelt (erstes Level):
	speech.setColor(sf::Color(210, 210, 210));
	speech.setString("A key to another dimension!");
	speech.setColor(sf::Color(210, 210, 255));

	// Uhr aufgesammelt (erstes Level):
	speech.setColor(sf::Color(210, 210, 210));
	speech.setString("When do we do now?");
	speech.setColor(sf::Color(210, 210, 255));

	// Ziel erreicht, kein Key (erstes Level):
	speech.setString("We need a key for this dimension hole!");

	// Ziel erreicht (erstes Level):
	speech.setString("Do you want to leave, Doggie?");
	speech.setColor(sf::Color(210, 255, 210));
	speech.setString("Frravt");
	speech.setColor(sf::Color(210, 210, 255));

	window.draw(speech);
	*/
}

void Scene::leave()
{
	int size = items.size();
	int keysInLevel = 0;
	for(int i = 0;i < size;i++)
	{
		if (dynamic_cast<KeyItem*>(&items[i]))
		{
			keysInLevel++;
		}
	}
	if (keysInLevel > 0)
	{
		return;
	}
	gui->resetCoins();
	gui->resetKeys();
	sceneManager.nextLevel();
}
<|endoftext|>