<commit_before>#ifndef AMGCL_PRECONDITIONER_DUMMY_HPP
#define AMGCL_PRECONDITIONER_DUMMY_HPP

/*
The MIT License

Copyright (c) 2012-2017 Denis Demidov <dennis.demidov@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * \file   amgcl/preconditioner/dummy.hpp
 * \author Denis Demidov <dennis.demidov@gmail.com>
 * \brief  Dummy preconditioner (identity matrix).
 */

#include <boost/shared_ptr.hpp>
#include <amgcl/backend/builtin.hpp>
#include <amgcl/util.hpp>

namespace amgcl {
namespace preconditioner {

template <class Backend>
class dummy {
    public:
        typedef Backend backend_type;

        typedef typename Backend::matrix  matrix;
        typedef typename Backend::vector  vector;
        typedef typename Backend::value_type value_type;
        typedef typename backend::builtin<value_type>::matrix build_matrix;

        typedef detail::empty_params params;
        typedef typename Backend::params backend_params;

        template <class Matrix>
        dummy(
                const Matrix &M,
                const params& = params(),
                const backend_params &bprm = backend_params()
                )
            : A(Backend::copy_matrix(boost::make_shared<build_matrix>(M), bprm))
        {
        }

        dummy(
                boost::shared_ptr<build_matrix> M,
                const params& = params(),
                const backend_params &bprm = backend_params()
                )
            : A(Backend::copy_matrix(M, bprm))
        {
        }

        template <class Vec1, class Vec2>
        void apply(
                const Vec1 &rhs,
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
                Vec2       &x
#else
                Vec2       &&x
#endif
                ) const
        {
            backend::copy(rhs, x);
        }

        const matrix& system_matrix() const {
            return *A;
        }
    private:
        boost::shared_ptr<matrix>   A;

        friend std::ostream& operator<<(std::ostream &os, const dummy &p) {
            os << "identity matrix as preconditioner" << std::endl;
            os << "  unknowns: " << backend::rows(p.system_matrix()) << std::endl;
            os << "  nonzeros: " << backend::nonzeros(p.system_matrix()) << std::endl;

            return os;
        }
};

} // namespace preconditioner
} // namespace amgcl
#endif
<commit_msg>Resolve namespace ambiguity<commit_after>#ifndef AMGCL_PRECONDITIONER_DUMMY_HPP
#define AMGCL_PRECONDITIONER_DUMMY_HPP

/*
The MIT License

Copyright (c) 2012-2017 Denis Demidov <dennis.demidov@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * \file   amgcl/preconditioner/dummy.hpp
 * \author Denis Demidov <dennis.demidov@gmail.com>
 * \brief  Dummy preconditioner (identity matrix).
 */

#include <boost/shared_ptr.hpp>
#include <amgcl/backend/builtin.hpp>
#include <amgcl/util.hpp>

namespace amgcl {
namespace preconditioner {

template <class Backend>
class dummy {
    public:
        typedef Backend backend_type;

        typedef typename Backend::matrix  matrix;
        typedef typename Backend::vector  vector;
        typedef typename Backend::value_type value_type;
        typedef typename backend::builtin<value_type>::matrix build_matrix;

        typedef amgcl::detail::empty_params params;
        typedef typename Backend::params backend_params;

        template <class Matrix>
        dummy(
                const Matrix &M,
                const params& = params(),
                const backend_params &bprm = backend_params()
                )
            : A(Backend::copy_matrix(boost::make_shared<build_matrix>(M), bprm))
        {
        }

        dummy(
                boost::shared_ptr<build_matrix> M,
                const params& = params(),
                const backend_params &bprm = backend_params()
                )
            : A(Backend::copy_matrix(M, bprm))
        {
        }

        template <class Vec1, class Vec2>
        void apply(
                const Vec1 &rhs,
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
                Vec2       &x
#else
                Vec2       &&x
#endif
                ) const
        {
            backend::copy(rhs, x);
        }

        const matrix& system_matrix() const {
            return *A;
        }
    private:
        boost::shared_ptr<matrix>   A;

        friend std::ostream& operator<<(std::ostream &os, const dummy &p) {
            os << "identity matrix as preconditioner" << std::endl;
            os << "  unknowns: " << backend::rows(p.system_matrix()) << std::endl;
            os << "  nonzeros: " << backend::nonzeros(p.system_matrix()) << std::endl;

            return os;
        }
};

} // namespace preconditioner
} // namespace amgcl
#endif
<|endoftext|>


<commit_before>#include "installercontroller.h"

#include <QProcess>
#include <QtTest>

static const QString configFile = SRCDIR + QStringLiteral("../../../installer/config/config.xml");
static const QString configScript = SRCDIR + QStringLiteral("../../../installer/config/controller.qs");
static const QString pkgFile = SRCDIR + QStringLiteral("../../../installer/packages/de.skycoder42.QtAutoUpdaterTestInstaller/meta/package.xml");
static const QString binarycreator = BINDIR + QStringLiteral("binarycreator");
static const QString repogen = BINDIR + QStringLiteral("repogen");

InstallerController::InstallerController(QObject *parent) :
	QObject(parent),
	_version(1, 0, 0),
	_buildDir()
{
	setVersion(_version);
}

void InstallerController::createRepository()
{
	auto res = QProcess::execute(repogen, {"--update-new-components", "-p", _buildDir.path() + "/packages", _buildDir.path() + "/repository"});
	QCOMPARE(res, 0);
}

void InstallerController::createInstaller()
{
	QFile configSrc(configFile);
	QFile configOut(_buildDir.path() + "/config.xml");

	QVERIFY(configSrc.open(QIODevice::ReadOnly | QIODevice::Text));
	QVERIFY(configOut.open(QIODevice::WriteOnly | QIODevice::Text));
	auto src = QString::fromUtf8(configSrc.readAll());
	configOut.write(src
					.arg(_buildDir.path() + "/install")
					.arg(_buildDir.path())
					.toUtf8());
	configSrc.close();
	configOut.close();

	auto res = QProcess::execute(binarycreator, {"-n", "-c", configOut.fileName(), "-p", _buildDir.path() + "/packages", _buildDir.path() + "/QtAutoUpdaterTestInstaller"});
	QCOMPARE(res, 0);
}

void InstallerController::installLocal()
{
	auto res = QProcess::execute(_buildDir.path() + "/QtAutoUpdaterTestInstaller", {"--script", configScript});
	QCOMPARE(res, 0);
}

void InstallerController::runUpdater()
{

}

QVersionNumber InstallerController::version() const
{
	return _version;
}

QString InstallerController::maintenanceToolPath() const
{
	return _buildDir.path() + "/install";
}

void InstallerController::setVersion(QVersionNumber version)
{
	_version = version;

	QDir tDir(_buildDir.path());
	QVERIFY(tDir.mkpath("packages/de.skycoder42.QtAutoUpdaterTestInstaller/meta"));
	QVERIFY(tDir.mkpath("packages/de.skycoder42.QtAutoUpdaterTestInstaller/data"));

	QFile pkgSrc(pkgFile);
	QFile pkgOut(_buildDir.path() + "/packages/de.skycoder42.QtAutoUpdaterTestInstaller/meta/package.xml");

	QVERIFY(pkgSrc.open(QIODevice::ReadOnly | QIODevice::Text));
	QVERIFY(pkgOut.open(QIODevice::WriteOnly | QIODevice::Text));
	auto src = QString::fromUtf8(pkgSrc.readAll());
	pkgOut.write(src.arg(_version.toString()).toUtf8());
	pkgSrc.close();
	pkgOut.close();

	QFile dataFile(_buildDir.path() + "/packages/de.skycoder42.QtAutoUpdaterTestInstaller/data/version.txt");
	QVERIFY(dataFile.open(QIODevice::WriteOnly | QIODevice::Text));
	dataFile.write(_version.toString().toUtf8());
	dataFile.close();
}
<commit_msg>more debug logs<commit_after>#include "installercontroller.h"

#include <QProcess>
#include <QtTest>

static const QString configFile = SRCDIR + QStringLiteral("../../../installer/config/config.xml");
static const QString configScript = SRCDIR + QStringLiteral("../../../installer/config/controller.qs");
static const QString pkgFile = SRCDIR + QStringLiteral("../../../installer/packages/de.skycoder42.QtAutoUpdaterTestInstaller/meta/package.xml");
static const QString binarycreator = BINDIR + QStringLiteral("binarycreator");
static const QString repogen = BINDIR + QStringLiteral("repogen");

InstallerController::InstallerController(QObject *parent) :
	QObject(parent),
	_version(1, 0, 0),
	_buildDir()
{
	setVersion(_version);
}

void InstallerController::createRepository()
{
	qDebug() << "Creating repository";
	auto res = QProcess::execute(repogen, {"--update-new-components", "-p", _buildDir.path() + "/packages", _buildDir.path() + "/repository"});
	QCOMPARE(res, 0);
}

void InstallerController::createInstaller()
{
	qDebug() << "Creating installer";
	QFile configSrc(configFile);
	QFile configOut(_buildDir.path() + "/config.xml");

	QVERIFY(configSrc.open(QIODevice::ReadOnly | QIODevice::Text));
	QVERIFY(configOut.open(QIODevice::WriteOnly | QIODevice::Text));
	auto src = QString::fromUtf8(configSrc.readAll());
	configOut.write(src
					.arg(_buildDir.path() + "/install")
					.arg(_buildDir.path())
					.toUtf8());
	configSrc.close();
	configOut.close();

	auto res = QProcess::execute(binarycreator, {"-n", "-c", configOut.fileName(), "-p", _buildDir.path() + "/packages", _buildDir.path() + "/QtAutoUpdaterTestInstaller"});
	QCOMPARE(res, 0);
}

void InstallerController::installLocal()
{
	qDebug() << "Installing example";
	auto res = QProcess::execute(_buildDir.path() + "/QtAutoUpdaterTestInstaller", {"--script", configScript});
	QCOMPARE(res, 0);
}

void InstallerController::runUpdater()
{
	qDebug() << "Running updater";
}

QVersionNumber InstallerController::version() const
{
	return _version;
}

QString InstallerController::maintenanceToolPath() const
{
	return _buildDir.path() + "/install";
}

void InstallerController::setVersion(QVersionNumber version)
{
	qDebug() << "Updating repository version";
	_version = version;

	QDir tDir(_buildDir.path());
	QVERIFY(tDir.mkpath("packages/de.skycoder42.QtAutoUpdaterTestInstaller/meta"));
	QVERIFY(tDir.mkpath("packages/de.skycoder42.QtAutoUpdaterTestInstaller/data"));

	QFile pkgSrc(pkgFile);
	QFile pkgOut(_buildDir.path() + "/packages/de.skycoder42.QtAutoUpdaterTestInstaller/meta/package.xml");

	QVERIFY(pkgSrc.open(QIODevice::ReadOnly | QIODevice::Text));
	QVERIFY(pkgOut.open(QIODevice::WriteOnly | QIODevice::Text));
	auto src = QString::fromUtf8(pkgSrc.readAll());
	pkgOut.write(src.arg(_version.toString()).toUtf8());
	pkgSrc.close();
	pkgOut.close();

	QFile dataFile(_buildDir.path() + "/packages/de.skycoder42.QtAutoUpdaterTestInstaller/data/version.txt");
	QVERIFY(dataFile.open(QIODevice::WriteOnly | QIODevice::Text));
	dataFile.write(_version.toString().toUtf8());
	dataFile.close();
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <opencv/cxcore.h>
#include <std_msgs/Float64.h>
#include <std_msgs/String.h>
#include <scan2image/ScanImage.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sensor_msgs/LaserScan.h>
#include <algorithm>
#include "scan2image.h"

#include "calibration_camera_lidar/projection_matrix.h"
#include <sensor_msgs/CameraInfo.h>

#if 1 // AXE
#define XSTR(x) #x
#define STR(x) XSTR(x)
#endif

static cv::Mat cameraExtrinsicMat;
static cv::Mat cameraMat;
static cv::Mat distCoeff;
static cv::Size imageSize;

ros::Publisher transformed_point_data;
static bool isProjection;
static bool isIntrinsic;
Scan_image scan_image;

void trans_depth_points_to_image_points(Scan_points_dataset* scan_points_dataset, Image_points_dataset* image_points_dataset)
{
    float camera_x;
    float camera_y;
    float camera_z;
    int i;

    for(i = 0; i < (int)scan_points_dataset->scan_points.x.size(); i++) {

        /*
         * Coordinate transformation. Change from laser range finder coordinate to camera coordinate
         */
        camera_x = (cameraExtrinsicMat.at<double>(0,0) * scan_points_dataset->scan_points.x.at(i)*1000
                    + cameraExtrinsicMat.at<double>(0,1) * scan_points_dataset->scan_points.y.at(i)*1000
                    + cameraExtrinsicMat.at<double>(0,2) * scan_points_dataset->scan_points.z.at(i)*1000)
            + (cameraExtrinsicMat.at<double>(0,3));
        camera_y = (cameraExtrinsicMat.at<double>(1,0) * scan_points_dataset->scan_points.x.at(i)*1000
                    + cameraExtrinsicMat.at<double>(1,1) * scan_points_dataset->scan_points.y.at(i)*1000
                    + cameraExtrinsicMat.at<double>(1,2) * scan_points_dataset->scan_points.z.at(i)*1000)
            + (cameraExtrinsicMat.at<double>(1,3));
        camera_z = (cameraExtrinsicMat.at<double>(2,0) * scan_points_dataset->scan_points.x.at(i)*1000
                    + cameraExtrinsicMat.at<double>(2,1) * scan_points_dataset->scan_points.y.at(i)*1000
                    + cameraExtrinsicMat.at<double>(2,2) * scan_points_dataset->scan_points.z.at(i)*1000)
            + (cameraExtrinsicMat.at<double>(2,3));
        if (camera_z >= 0.0) {
            /*
             * Projection transformation. Change from camera coordinate to image coordinate
             */
            image_points_dataset->image_points.x.push_back((camera_x * cameraMat.at<double>(0,0) / camera_z) + cameraMat.at<double>(0,2));
            image_points_dataset->image_points.y.push_back((camera_y * cameraMat.at<double>(1,1) / camera_z) + cameraMat.at<double>(1,2));
            /*
             * Calculate euclidean distance from the camera to objects
             */
            image_points_dataset->distance.push_back(sqrt(camera_x * camera_x + camera_y * camera_y + camera_z * camera_z) * 100); //unit of length is centimeter

            /*
             * Copy to intensity
             */
            if(!(scan_points_dataset->intensity.empty())){
                image_points_dataset->intensity.push_back(scan_points_dataset->intensity.at(i));
            }
        }
    }
}

static void projection_callback(const calibration_camera_lidar::projection_matrix& msg)
{
    printf("projection\n");

	cameraExtrinsicMat = cv::Mat(4,4,CV_64F);
	for (int row=0; row<4; row++) {
		for (int col=0; col<4; col++) {
			cameraExtrinsicMat.at<double>(row, col) = msg.projection_matrix[row * 4 + col];
            printf("%f\t", cameraExtrinsicMat.at<double>(row, col));
		}
        printf("\n");
	}
    isProjection = true;
}

static void intrinsic_callback(const sensor_msgs::CameraInfo& msg)
{
    printf("intrinsic\n");

    if (!isIntrinsic || imageSize.height != msg.height || imageSize.width != msg.width) {
        if (isIntrinsic) {
            free(scan_image.distance);
            free(scan_image.intensity);
        }
        scan_image.distance = (float *)calloc(msg.height * msg.width, sizeof(float));
        scan_image.intensity = (float *)calloc(msg.height * msg.width, sizeof(float));
        scan_image.max_y = NO_DATA;
        scan_image.min_y = NO_DATA;

    }

	imageSize.height = msg.height;
	imageSize.width = msg.width;

	cameraMat = cv::Mat(3,3, CV_64F);
	for (int row=0; row<3; row++) {
		for (int col=0; col<3; col++) {
			cameraMat.at<double>(row, col) = msg.K[row * 3 + col];
            printf("%f\t", cameraMat.at<double>(row, col));
		}
        printf("\n");
	}

	distCoeff = cv::Mat(1,5,CV_64F);
	for (int col=0; col<5; col++) {
		distCoeff.at<double>(col) = msg.D[col];
	}
    isIntrinsic = true;
}

void scanCallback(const sensor_msgs::LaserScan::ConstPtr& msg)
{
    if (!(isIntrinsic && isProjection)){
        return;
    }

    static Scan_points_dataset scan_points_dataset;
    static Image_points_dataset image_points_dataset;
    int i;

//    ROS_INFO("angle_min[%f]\nangle_max:[%f]\nangle_increment:[%f]\ntime_increment:[%f]\nscan_time:[%f]\nrange_min:[%f]\nrange_max:[%f]\n", msg->angle_min * 180 / 3.141592, msg->angle_max * 180 / 3.141592, msg->angle_increment * 180 / 3.141592, msg->time_increment, msg->scan_time, msg->range_min, msg->range_max);

    /*
     * Initialize
     */
    scan_points_dataset.scan_points.x.resize(msg->ranges.size());
    scan_points_dataset.scan_points.y.resize(msg->ranges.size());
    scan_points_dataset.scan_points.z.resize(msg->ranges.size());
    scan_points_dataset.intensity.resize(msg->intensities.size());
    image_points_dataset.image_points.x.clear();
    image_points_dataset.image_points.y.clear();
    image_points_dataset.distance.clear();
    image_points_dataset.intensity.clear();

    /*
     * Change to three dimentional coordinate. And copy intensity
     */
    for(i = 0; i < (int)msg->ranges.size(); i++) {
        scan_points_dataset.scan_points.x.at(i) = msg->ranges.at(i) * sin(msg->angle_min + msg->angle_increment * i); //unit of length is meter
        scan_points_dataset.scan_points.y.at(i) = 0; //unit of length is meter
        scan_points_dataset.scan_points.z.at(i) = msg->ranges.at(i) * cos(msg->angle_min + msg->angle_increment * i); //unit of length is meter
        if(!(msg->intensities.empty())){
            scan_points_dataset.intensity.at(i) = msg->intensities.at(i);
        }
    }

    /*
     * Change from laser range finder coordinate to image coordinate
     */
    trans_depth_points_to_image_points(&scan_points_dataset, &image_points_dataset);

    /*
     * Judge out of image frame. And Determine max_y and min_y
     */
    for (i = 0; i < (int)image_points_dataset.image_points.x.size(); i++) {
        /* Judge NaN */
        if(isnan(image_points_dataset.image_points.x.at(i)) == 1 || isnan(image_points_dataset.image_points.y.at(i)) == 1) {
            std::cout <<"Not a Number is i:" << i << std::endl;
            continue;
        }
        /* Judge out of X-axis image */
        if(0 > (int)image_points_dataset.image_points.x.at(i) || (int)image_points_dataset.image_points.x.at(i) > imageSize.width - 1) {
            continue;
        }
        /* Judge out of Y-axis image */
        if(0 > (int)image_points_dataset.image_points.y.at(i) || (int)image_points_dataset.image_points.y.at(i) > imageSize.height - 1) {
            continue;
        }

        scan_image.distance[(int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i)] = image_points_dataset.distance.at(i);

        if(!msg->intensities.empty()){
            scan_image.intensity[(int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i)] = image_points_dataset.intensity.at(i);
        }

        if ((scan_image.max_y < (int)image_points_dataset.image_points.y.at(i)) || (scan_image.max_y == NO_DATA)) {
            scan_image.max_y = (int)image_points_dataset.image_points.y.at(i);
        } else if ((scan_image.min_y > (int)image_points_dataset.image_points.y.at(i)) || (scan_image.min_y == NO_DATA)) {
            scan_image.min_y = (int)image_points_dataset.image_points.y.at(i);
        }
    }

    /*
     * Create message(Topic)
     */
    scan2image::ScanImage scan_image_msg;
    scan_image_msg.header = msg->header;
    scan_image_msg.distance.assign(scan_image.distance, scan_image.distance + imageSize.width * imageSize.height);
    scan_image_msg.intensity.assign(scan_image.intensity, scan_image.intensity + imageSize.width * imageSize.height);
    scan_image_msg.max_y = scan_image.max_y;
    scan_image_msg.min_y = scan_image.min_y;

    /*
     * Publish message(Topic)
     */
    transformed_point_data.publish(scan_image_msg);

    /*
     * Init zero
     */
    memset(scan_image.distance, 0, imageSize.width * imageSize.height);
    memset(scan_image.intensity, 0, imageSize.width * imageSize.height);
    scan_image.max_y = NO_DATA;
    scan_image.min_y = NO_DATA;
}

int main(int argc, char **argv)
{
    isProjection = false;
    isIntrinsic = false;
    ros::init(argc, argv, "scan2image");
    ros::NodeHandle n;
    ros::Subscriber sub = n.subscribe("scan", 1, scanCallback);
    ros::Subscriber projection_sub = n.subscribe("projection_matrix", 1, projection_callback);
    ros::Subscriber intrinsic_sub = n.subscribe("camera/camera_info", 1, intrinsic_callback);
    transformed_point_data = n.advertise<scan2image::ScanImage>("scan_image", 1);

    ros::spin();

    free(scan_image.distance);
    free(scan_image.intensity);
    return 0;
}
<commit_msg>fixed bug of scan2image the third argument in memset() is wrong<commit_after>#include <ros/ros.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <opencv/cxcore.h>
#include <std_msgs/Float64.h>
#include <std_msgs/String.h>
#include <scan2image/ScanImage.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sensor_msgs/LaserScan.h>
#include <algorithm>
#include "scan2image.h"

#include "calibration_camera_lidar/projection_matrix.h"
#include <sensor_msgs/CameraInfo.h>

#if 1 // AXE
#define XSTR(x) #x
#define STR(x) XSTR(x)
#endif

static cv::Mat cameraExtrinsicMat;
static cv::Mat cameraMat;
static cv::Mat distCoeff;
static cv::Size imageSize;

ros::Publisher transformed_point_data;
static bool isProjection;
static bool isIntrinsic;
Scan_image scan_image;

void trans_depth_points_to_image_points(Scan_points_dataset* scan_points_dataset, Image_points_dataset* image_points_dataset)
{
    float camera_x;
    float camera_y;
    float camera_z;
    int i;

    for(i = 0; i < (int)scan_points_dataset->scan_points.x.size(); i++) {

        /*
         * Coordinate transformation. Change from laser range finder coordinate to camera coordinate
         */
        camera_x = (cameraExtrinsicMat.at<double>(0,0) * scan_points_dataset->scan_points.x.at(i)*1000
                    + cameraExtrinsicMat.at<double>(0,1) * scan_points_dataset->scan_points.y.at(i)*1000
                    + cameraExtrinsicMat.at<double>(0,2) * scan_points_dataset->scan_points.z.at(i)*1000)
            + (cameraExtrinsicMat.at<double>(0,3));
        camera_y = (cameraExtrinsicMat.at<double>(1,0) * scan_points_dataset->scan_points.x.at(i)*1000
                    + cameraExtrinsicMat.at<double>(1,1) * scan_points_dataset->scan_points.y.at(i)*1000
                    + cameraExtrinsicMat.at<double>(1,2) * scan_points_dataset->scan_points.z.at(i)*1000)
            + (cameraExtrinsicMat.at<double>(1,3));
        camera_z = (cameraExtrinsicMat.at<double>(2,0) * scan_points_dataset->scan_points.x.at(i)*1000
                    + cameraExtrinsicMat.at<double>(2,1) * scan_points_dataset->scan_points.y.at(i)*1000
                    + cameraExtrinsicMat.at<double>(2,2) * scan_points_dataset->scan_points.z.at(i)*1000)
            + (cameraExtrinsicMat.at<double>(2,3));
        if (camera_z >= 0.0) {
            /*
             * Projection transformation. Change from camera coordinate to image coordinate
             */
            image_points_dataset->image_points.x.push_back((camera_x * cameraMat.at<double>(0,0) / camera_z) + cameraMat.at<double>(0,2));
            image_points_dataset->image_points.y.push_back((camera_y * cameraMat.at<double>(1,1) / camera_z) + cameraMat.at<double>(1,2));
            /*
             * Calculate euclidean distance from the camera to objects
             */
            image_points_dataset->distance.push_back(sqrt(camera_x * camera_x + camera_y * camera_y + camera_z * camera_z) * 100); //unit of length is centimeter

            /*
             * Copy to intensity
             */
            if(!(scan_points_dataset->intensity.empty())){
                image_points_dataset->intensity.push_back(scan_points_dataset->intensity.at(i));
            }
        }
    }
}

static void projection_callback(const calibration_camera_lidar::projection_matrix& msg)
{
    printf("projection\n");

	cameraExtrinsicMat = cv::Mat(4,4,CV_64F);
	for (int row=0; row<4; row++) {
		for (int col=0; col<4; col++) {
			cameraExtrinsicMat.at<double>(row, col) = msg.projection_matrix[row * 4 + col];
            printf("%f\t", cameraExtrinsicMat.at<double>(row, col));
		}
        printf("\n");
	}
    isProjection = true;
}

static void intrinsic_callback(const sensor_msgs::CameraInfo& msg)
{
    printf("intrinsic\n");

    if (!isIntrinsic || imageSize.height != msg.height || imageSize.width != msg.width) {
        if (isIntrinsic) {
            free(scan_image.distance);
            free(scan_image.intensity);
        }
        scan_image.distance = (float *)calloc(msg.height * msg.width, sizeof(float));
        scan_image.intensity = (float *)calloc(msg.height * msg.width, sizeof(float));
        scan_image.max_y = NO_DATA;
        scan_image.min_y = NO_DATA;

    }

	imageSize.height = msg.height;
	imageSize.width = msg.width;

	cameraMat = cv::Mat(3,3, CV_64F);
	for (int row=0; row<3; row++) {
		for (int col=0; col<3; col++) {
			cameraMat.at<double>(row, col) = msg.K[row * 3 + col];
            printf("%f\t", cameraMat.at<double>(row, col));
		}
        printf("\n");
	}

	distCoeff = cv::Mat(1,5,CV_64F);
	for (int col=0; col<5; col++) {
		distCoeff.at<double>(col) = msg.D[col];
	}
    isIntrinsic = true;
}

void scanCallback(const sensor_msgs::LaserScan::ConstPtr& msg)
{
    if (!(isIntrinsic && isProjection)){
        return;
    }

    static Scan_points_dataset scan_points_dataset;
    static Image_points_dataset image_points_dataset;
    int i;

//    ROS_INFO("angle_min[%f]\nangle_max:[%f]\nangle_increment:[%f]\ntime_increment:[%f]\nscan_time:[%f]\nrange_min:[%f]\nrange_max:[%f]\n", msg->angle_min * 180 / 3.141592, msg->angle_max * 180 / 3.141592, msg->angle_increment * 180 / 3.141592, msg->time_increment, msg->scan_time, msg->range_min, msg->range_max);

    /*
     * Initialize
     */
    scan_points_dataset.scan_points.x.resize(msg->ranges.size());
    scan_points_dataset.scan_points.y.resize(msg->ranges.size());
    scan_points_dataset.scan_points.z.resize(msg->ranges.size());
    scan_points_dataset.intensity.resize(msg->intensities.size());
    image_points_dataset.image_points.x.clear();
    image_points_dataset.image_points.y.clear();
    image_points_dataset.distance.clear();
    image_points_dataset.intensity.clear();

    /*
     * Change to three dimentional coordinate. And copy intensity
     */
    for(i = 0; i < (int)msg->ranges.size(); i++) {
        scan_points_dataset.scan_points.x.at(i) = msg->ranges.at(i) * sin(msg->angle_min + msg->angle_increment * i); //unit of length is meter
        scan_points_dataset.scan_points.y.at(i) = 0; //unit of length is meter
        scan_points_dataset.scan_points.z.at(i) = msg->ranges.at(i) * cos(msg->angle_min + msg->angle_increment * i); //unit of length is meter
        if(!(msg->intensities.empty())){
            scan_points_dataset.intensity.at(i) = msg->intensities.at(i);
        }
    }

    /*
     * Change from laser range finder coordinate to image coordinate
     */
    trans_depth_points_to_image_points(&scan_points_dataset, &image_points_dataset);

    /*
     * Judge out of image frame. And Determine max_y and min_y
     */
    for (i = 0; i < (int)image_points_dataset.image_points.x.size(); i++) {
        /* Judge NaN */
        if(isnan(image_points_dataset.image_points.x.at(i)) == 1 || isnan(image_points_dataset.image_points.y.at(i)) == 1) {
            std::cout <<"Not a Number is i:" << i << std::endl;
            continue;
        }
        /* Judge out of X-axis image */
        if(0 > (int)image_points_dataset.image_points.x.at(i) || (int)image_points_dataset.image_points.x.at(i) > imageSize.width - 1) {
            continue;
        }
        /* Judge out of Y-axis image */
        if(0 > (int)image_points_dataset.image_points.y.at(i) || (int)image_points_dataset.image_points.y.at(i) > imageSize.height - 1) {
            continue;
        }

        scan_image.distance[(int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i)] = image_points_dataset.distance.at(i);

        if(!msg->intensities.empty()){
            scan_image.intensity[(int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i)] = image_points_dataset.intensity.at(i);
        }

        if ((scan_image.max_y < (int)image_points_dataset.image_points.y.at(i)) || (scan_image.max_y == NO_DATA)) {
            scan_image.max_y = (int)image_points_dataset.image_points.y.at(i);
        } else if ((scan_image.min_y > (int)image_points_dataset.image_points.y.at(i)) || (scan_image.min_y == NO_DATA)) {
            scan_image.min_y = (int)image_points_dataset.image_points.y.at(i);
        }
    }

    /*
     * Create message(Topic)
     */
    scan2image::ScanImage scan_image_msg;
    scan_image_msg.header = msg->header;
    scan_image_msg.distance.assign(scan_image.distance, scan_image.distance + imageSize.width * imageSize.height);
    scan_image_msg.intensity.assign(scan_image.intensity, scan_image.intensity + imageSize.width * imageSize.height);
    scan_image_msg.max_y = scan_image.max_y;
    scan_image_msg.min_y = scan_image.min_y;

    /*
     * Publish message(Topic)
     */
    transformed_point_data.publish(scan_image_msg);

    /*
     * Init zero
     */
    memset(scan_image.distance, 0, sizeof(float) * imageSize.width * imageSize.height);
    memset(scan_image.intensity, 0, sizeof(float) * imageSize.width * imageSize.height);
    scan_image.max_y = NO_DATA;
    scan_image.min_y = NO_DATA;
}

int main(int argc, char **argv)
{
    isProjection = false;
    isIntrinsic = false;
    ros::init(argc, argv, "scan2image");
    ros::NodeHandle n;
    ros::Subscriber sub = n.subscribe("scan", 1, scanCallback);
    ros::Subscriber projection_sub = n.subscribe("projection_matrix", 1, projection_callback);
    ros::Subscriber intrinsic_sub = n.subscribe("camera/camera_info", 1, intrinsic_callback);
    transformed_point_data = n.advertise<scan2image::ScanImage>("scan_image", 1);

    ros::spin();

    free(scan_image.distance);
    free(scan_image.intensity);
    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: GenericConfigurationChangeRequest.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-03 15:47:04 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "precompiled_sd.hxx"

#include "GenericConfigurationChangeRequest.hxx"

#include "framework/FrameworkHelper.hxx"

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing::framework;

using ::rtl::OUString;

namespace sd { namespace framework {

GenericConfigurationChangeRequest::GenericConfigurationChangeRequest (
    const Reference<XResourceId>& rxResourceId,
    Mode eMode) throw(::com::sun::star::lang::IllegalArgumentException)
    : GenericConfigurationChangeRequestInterfaceBase(MutexOwner::maMutex),
      mxResourceId(rxResourceId),
      meMode(eMode)
{
    if ( ! rxResourceId.is() || rxResourceId->getResourceURL().getLength()==0)
        throw ::com::sun::star::lang::IllegalArgumentException();
}

GenericConfigurationChangeRequest::~GenericConfigurationChangeRequest (void) throw()
{
}

void SAL_CALL GenericConfigurationChangeRequest::execute (
    const Reference<XConfiguration>& rxConfiguration)
    throw (RuntimeException)
{
    if (rxConfiguration.is())
    {
        switch (meMode)
        {
            case Activation:
                rxConfiguration->addResource(mxResourceId);
                break;

            case Deactivation:
                rxConfiguration->removeResource(mxResourceId);
                break;
        }
    }
}

OUString SAL_CALL GenericConfigurationChangeRequest::getName (void)
    throw (RuntimeException)
{
    return OUString::createFromAscii("GenericConfigurationChangeRequest ")
        + OUString::createFromAscii(meMode==Activation ? "activate " : "deactivate ")
        + FrameworkHelper::ResourceIdToString(mxResourceId);
}

void SAL_CALL GenericConfigurationChangeRequest::setName (const OUString& rsName)
    throw (RuntimeException)
{
    (void)rsName;
    // Ignored.
}

} } // end of namespace sd::framework

<commit_msg>INTEGRATION: CWS presenterview (1.2.22); FILE MERGED 2007/07/24 10:58:28 af 1.2.22.1: #i18486# Fixed resync problems.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: GenericConfigurationChangeRequest.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2008-04-03 13:30:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "precompiled_sd.hxx"

#include "GenericConfigurationChangeRequest.hxx"

#include "framework/FrameworkHelper.hxx"

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing::framework;

using ::rtl::OUString;

namespace sd { namespace framework {

GenericConfigurationChangeRequest::GenericConfigurationChangeRequest (
    const Reference<XResourceId>& rxResourceId,
    const Mode eMode) throw(::com::sun::star::lang::IllegalArgumentException)
    : GenericConfigurationChangeRequestInterfaceBase(MutexOwner::maMutex),
      mxResourceId(rxResourceId),
      meMode(eMode)
{
    if ( ! rxResourceId.is() || rxResourceId->getResourceURL().getLength()==0)
        throw ::com::sun::star::lang::IllegalArgumentException();
}

GenericConfigurationChangeRequest::~GenericConfigurationChangeRequest (void) throw()
{
}

void SAL_CALL GenericConfigurationChangeRequest::execute (
    const Reference<XConfiguration>& rxConfiguration)
    throw (RuntimeException)
{
    if (rxConfiguration.is())
    {
        switch (meMode)
        {
            case Activation:
                rxConfiguration->addResource(mxResourceId);
                break;

            case Deactivation:
                rxConfiguration->removeResource(mxResourceId);
                break;
        }
    }
}

OUString SAL_CALL GenericConfigurationChangeRequest::getName (void)
    throw (RuntimeException)
{
    return OUString::createFromAscii("GenericConfigurationChangeRequest ")
        + OUString::createFromAscii(meMode==Activation ? "activate " : "deactivate ")
        + FrameworkHelper::ResourceIdToString(mxResourceId);
}

void SAL_CALL GenericConfigurationChangeRequest::setName (const OUString& rsName)
    throw (RuntimeException)
{
    (void)rsName;
    // Ignored.
}

} } // end of namespace sd::framework

<|endoftext|>


<commit_before>#include <string>
#include <fstream>
#include <sstream>
#include <vector>
size_t letterI(const char letter, const bool is_capital) {
	int first_letter_code = static_cast<int>(is_capital ? L'А' : L'а');
	if (letter > (is_capital ? L'Е' : L'е')) {
		return static_cast<int>(letter) - first_letter_code + 2;
	}
	else {
		if (letter == (is_capital ? L'Ё' : L'ё')) {
			return 7;
		}
		return static_cast<int>(letter) - first_letter_code + 1;
	}
}
struct person {
	std::string surname;
	std::string name;
	size_t year;
	size_t i(size_t sort_i) const {
		if (sort_i < surname.length()) {
			return letterI(surname[sort_i], sort_i == 0);
		}
		else {
			return 0;
		}
	}
};
std::ostream & operator<<(std::ostream & output, person const & _person)
{
	output << _person.surname << " ";
	output << _person.name << " ";
	output << _person.year;
	return output;
}
std::istream & operator>>(std::istream & input, person & _person)
{
	input >> _person.surname;
	input >> _person.name;
	input >> _person.year;
	return input;
}
using Buckets = std::vector<std::vector<person>>;
using Persons = std::vector<person>;
class Persons_File {
public:
	Persons_File() : is_empty(true), file_size(0) {
		;
	}
	std::string file_name;
	bool is_empty;
	size_t file_size;
	std::fstream stream;
	void openNew(std::string _file_name) {
		file_name = _file_name;
		stream.open(file_name, std::ios::out);
	}
	void addToSize(person _person) {
		file_size += _person.surname.size();
		file_size += _person.name.size();
		file_size += sizeof(_person.year);
		file_size += 1 + 1 + 2;
	}
};
using Output_Files = std::vector<std::ofstream>;

class Database_Sorter {
	bool is_database_empty;
	std::string database_file_name;
	std::string vault_file_name;
public:
	Database_Sorter(std::string database_file_name, std::string output_file_name, size_t _RAM_amount)
		: database_file_name(database_file_name),
		database_file(database_file_name),
		output_file(output_file_name),
		RAM_amount(_RAM_amount),
		is_database_empty(true)
	{
		vault_file_name = "F:\\1\\temp_files\\";
	}
	void sortDatabase() {
		sortFile(database_file, database_file_name, RAM_amount + 1, 0);
	}

	~Database_Sorter() {
		database_file.close();
		output_file.close();
	}
private:
	void sortFile(std::ifstream & file, std::string file_name, size_t file_size, size_t sort_i) {
		if (file_size < RAM_amount) {

		}
		else {
			std::vector<Persons_File> persons_files = stuffPersonsToFiles(file, file_name, sort_i);
			for (size_t i = 0; i < persons_files.size(); i++) {
				if (persons_files[i].file_size != 0) {
					std::ifstream temp_file(persons_files[i].file_name);
					try {
						sortFile(temp_file, persons_files[i].file_name, persons_files[i].file_size, sort_i + 1);
					}
					catch (...) {
						system("pause");
						throw;
					}
					temp_file.close();
				}
			}
		}
	}

	void RAMsort(std::ifstream & file, size_t sort_i) {
		persons_outputted = 0;
		persons.clear();
		readFileIntoRAM(file);
		sortPersons(persons, sort_i);
	}
	void readFileIntoRAM(std::ifstream & file) {
		while (!file.eof()) {
			person current_person;
			file >> current_person;
			persons.push_back(current_person);
		}
	}
	void sortPersons(Persons const & entered_persons, size_t sort_i) {
		Buckets buckets = stuffPersonsToBuckets(entered_persons, sort_i);
		if (isOnlyOneBucketFull(buckets, entered_persons, sort_i)) {
			outputBucket(entered_persons, output_file);
		}
		else {
			sortBuckets(buckets, sort_i + 1);
		}
	}
	Buckets stuffPersonsToBuckets(Persons const & persons, size_t sort_i) {
		Buckets buckets(34);
		for (auto person : persons) {
			size_t currentI = person.i(sort_i);
			buckets[currentI].push_back(person);
		}
		return buckets;
	}
	bool isOnlyOneBucketFull(Buckets const & buckets, Persons const & persons, size_t sort_i) {
		size_t first_bucket_i = persons[0].i(sort_i);
		return buckets[first_bucket_i].size() == persons.size();
	}
	void outputBucket(Persons const & bucket, std::ofstream & sorted_persons_file) {
		for (auto person : bucket) {
			outputPerson(person);
		}
	}
	void outputPerson(person _person) {
		if (is_database_empty) {
			is_database_empty = false;
		}
		else {
			output_file << std::endl;
		}
		output_file << _person;
		persons_outputted++;
	}
	void sortBuckets(Buckets const & buckets, size_t sort_i) {
		for (auto bucket : buckets) {
			if (!bucket.empty()) {
				sortPersons(bucket, sort_i);
			}
		}
	}

	std::vector<Persons_File> stuffPersonsToFiles(std::ifstream & base_file, std::string base_file_name, size_t sort_i) {
		std::vector<Persons_File> files = createDerivedFiles(base_file_name);
		while (!base_file.eof()) {
			person current_person;
			base_file >> current_person;
			size_t currentI = current_person.i(sort_i);
			if (files[currentI].is_empty) {
				files[currentI].is_empty = false;
			}
			else {
				files[currentI].stream << std::endl;
			}
			files[currentI].stream << current_person;
			files[currentI].addToSize(current_person);
		}
		for (size_t i = 0; i < files.size(); i++) {
			files[i].stream.close();
		}
		return files;
	}
	std::vector<Persons_File> createDerivedFiles(std::string base_file_name) {
		std::vector<Persons_File> files(34);
		for (size_t i = 0; i < files.size(); i++) {
			std::stringstream string_stream;
			std::string str;
			if (base_file_name == database_file_name) {
				string_stream << vault_file_name << i << ".txt";
			}
			else {
				string_stream << base_file_name << "_" << i << ".txt";
			}
			string_stream >> str;
			files[i].openNew(str);
		}
		return files;
	}
	std::vector<person> persons;
	size_t persons_outputted;
	std::ifstream database_file;
	std::ofstream output_file;
	size_t RAM_amount;
};
<commit_msg>Update Database_Sorter.hpp<commit_after>#include <string>
#include <fstream>
#include <sstream>
#include <vector>
char russian_letters[6];
size_t letterI(const char letter, const bool is_capital) {
	int first_letter_code = static_cast<int>(is_capital ? russian_letters[0] : russian_letters[1]);
	if (letter > (is_capital ? russian_letters[2] : russian_letters[3])) {
		size_t result = static_cast<int>(letter) - first_letter_code + 2;
		return result;
	}
	else {
		if (letter == (is_capital ? russian_letters[4] : russian_letters[5])) {
			return 7;
		}
		size_t result = static_cast<int>(letter) - first_letter_code + 2;
		return result;
	}
}
struct person {
	std::string surname;
	std::string name;
	size_t year;
	size_t i(size_t sort_i) const {
		if (sort_i < surname.length()) {
			return letterI(surname[sort_i], sort_i == 0);
		}
		else {
			return 0;
		}
	}
};
std::ostream & operator<<(std::ostream & output, person const & _person)
{
	output << _person.surname << " ";
	output << _person.name << " ";
	output << _person.year;
	return output;
}
std::istream & operator>>(std::istream & input, person & _person)
{
	input >> _person.surname;
	input >> _person.name;
	input >> _person.year;
	return input;
}
using Buckets = std::vector<std::vector<person>>;
using Persons = std::vector<person>;
class Persons_File {
public:
	Persons_File() : is_empty(true), file_size(0) {
		;
	}
	std::string file_name;
	bool is_empty;
	size_t file_size;
	std::fstream stream;
	void openNew(std::string _file_name) {
		file_name = _file_name;
		stream.open(file_name, std::ios::out);
	}
	void addToSize(person _person) {
		file_size += _person.surname.size();
		file_size += _person.name.size();
		file_size += sizeof(_person.year);
		file_size += 1 + 1 + 2;
	}
};
using Output_Files = std::vector<std::ofstream>;

class Database_Sorter {
	bool is_database_empty;
	std::string database_file_name;
	std::string vault_file_name;
public:
	Database_Sorter(std::string database_file_name, std::string output_file_name, size_t _RAM_amount)
		: database_file_name(database_file_name),
		database_file(database_file_name),
		output_file(output_file_name),
		RAM_amount(_RAM_amount),
		is_database_empty(true)
	{
		vault_file_name = "F:\\1\\temp_files\\";
	}
	void sortDatabase() {
		sortFile(database_file, database_file_name, RAM_amount + 1, 0);
	}

	~Database_Sorter() {
		database_file.close();
		output_file.close();
	}
private:
	void sortFile(std::ifstream & file, std::string file_name, size_t file_size, size_t sort_i) {
		if (file_size < RAM_amount) {
			RAMsort(file, sort_i);
		}
		else {
			std::vector<Persons_File> persons_files = stuffPersonsToFiles(file, file_name, sort_i);
			for (size_t i = 0; i < persons_files.size(); i++) {
				if (persons_files[i].file_size != 0) {
					std::ifstream temp_file(persons_files[i].file_name);
					sortFile(temp_file, persons_files[i].file_name, persons_files[i].file_size, sort_i + 1);
					temp_file.close();
				}
			}
		}
	}

	void RAMsort(std::ifstream & file, size_t sort_i) {
		persons_outputted = 0;
		persons.clear();
		readFileIntoRAM(file);
		sortPersons(persons, sort_i);
	}
	void readFileIntoRAM(std::ifstream & file) {
		while (!file.eof()) {
			person current_person;
			file >> current_person;
			persons.push_back(current_person);
		}
	}
	void sortPersons(Persons const & entered_persons, size_t sort_i) {
		Buckets buckets = stuffPersonsToBuckets(entered_persons, sort_i);
		if (isOnlyOneBucketFull(buckets, entered_persons, sort_i)) {
			outputBucket(entered_persons, output_file);
		}
		else {
			sortBuckets(buckets, sort_i + 1);
		}
	}
	Buckets stuffPersonsToBuckets(Persons const & persons, size_t sort_i) {
		Buckets buckets(34);
		for (auto person : persons) {
			size_t currentI = person.i(sort_i);
			buckets[currentI].push_back(person);
		}
		return buckets;
	}
	bool isOnlyOneBucketFull(Buckets const & buckets, Persons const & persons, size_t sort_i) {
		size_t first_bucket_i = persons[0].i(sort_i);
		return buckets[first_bucket_i].size() == persons.size();
	}
	void outputBucket(Persons const & bucket, std::ofstream & sorted_persons_file) {
		for (auto person : bucket) {
			outputPerson(person);
		}
	}
	void outputPerson(person _person) {
		if (is_database_empty) {
			is_database_empty = false;
		}
		else {
			output_file << std::endl;
		}
		output_file << _person;
		persons_outputted++;
	}
	void sortBuckets(Buckets const & buckets, size_t sort_i) {
		for (auto bucket : buckets) {
			if (!bucket.empty()) {
				sortPersons(bucket, sort_i);
			}
		}
	}

	std::vector<Persons_File> stuffPersonsToFiles(std::ifstream & base_file, std::string base_file_name, size_t sort_i) {
		std::vector<Persons_File> files = createDerivedFiles(base_file_name);
		while (!base_file.eof()) {
			person current_person;
			base_file >> current_person;
			size_t currentI = current_person.i(sort_i);
			if (files[currentI].is_empty) {
				files[currentI].is_empty = false;
			}
			else {
				files[currentI].stream << std::endl;
			}
			files[currentI].stream << current_person;
			files[currentI].addToSize(current_person);
		}
		for (size_t i = 0; i < files.size(); i++) {
			files[i].stream.close();
		}
		return files;
	}
	std::vector<Persons_File> createDerivedFiles(std::string base_file_name) {
		std::vector<Persons_File> files(34);
		for (size_t i = 0; i < files.size(); i++) {
			std::stringstream string_stream;
			std::string str;
			if (base_file_name == database_file_name) {
				string_stream << vault_file_name << i << ".txt";
			}
			else {
				string_stream << base_file_name << "_" << i << ".txt";
			}
			string_stream >> str;
			files[i].openNew(str);
		}
		return files;
	}
	std::vector<person> persons;
	size_t persons_outputted;
	std::ifstream database_file;
	std::ofstream output_file;
	size_t RAM_amount;
};
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
//    you must not claim that you wrote the original software.
//    If you use this software in a product, an acknowledgment
//    in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
//    and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////

#ifndef RESOURCE_MANAGER_HPP
#define RESOURCE_MANAGER_HPP

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////

#include <BaseResource.hpp>
#include <functional>
#include <string>
#include <memory>
#include <map>
#include <list>
#include <queue>

namespace rm
{

typedef std::shared_ptr<BaseResource> resource_ptr;

enum class LoadMode
{
    Queue,
    Block,
};

class ResourceManager
{
public:
    ResourceManager();
    virtual ~ResourceManager();

    template<class T>
    void initResource(std::string path);
    template<class T>
    std::shared_ptr<T> loadResource(std::string name, LoadMode mode);
    template<class T>
    std::shared_ptr<T> getResource(std::string name);
    void unloadResource(std::string name, LoadMode mode);
    void reloadResource(std::string name);

    void initPack(std::string path);
    void loadPack(std::string path, LoadMode mode);
    void unloadPack (std::string path, LoadMode mode);
    void reloadPack(std::string path);
    void switchPack(std::string path, std::string path);

    template<class T>
    void createErrorResource(std::string path);
    template<class T>
    std::shared_ptr<T> getErrorResource();

	void init(bool useNullForErrorRes);
    void update();
    void cleanupUnused();
    bool isLoading();
    size_t getNumToLoad();
    std::list<resource_ptr> listAll();
    size_t getRamUse();
    size_t genNumResources();
    void setLoadCompleteCallback(std::function callback);

private:
    std::map<std::string, resource_ptr> resources;
    std::map<std::string, resource_ptr> errorResources;
    std::queue<resource_ptr> loadingQueue;
	std::queue<resource_ptr> unloadQueue;
	std::queue<resource_ptr> reloadQueue;
	bool useNullForErrorRes;

    std::function loadCompleteCallback;

    void loadFromQueue();
    void unloadFromQueue();
    void reloadFromQueue();
};

#endif //RESOURCE_MANAGER_HPP<commit_msg>made ResourceManager monostate<commit_after>////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
//    you must not claim that you wrote the original software.
//    If you use this software in a product, an acknowledgment
//    in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
//    and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////

#ifndef RESOURCE_MANAGER_HPP
#define RESOURCE_MANAGER_HPP

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////

#include <BaseResource.hpp>
#include <functional>
#include <string>
#include <memory>
#include <map>
#include <list>
#include <queue>

namespace rm
{

typedef std::shared_ptr<BaseResource> resource_ptr;

enum class LoadMode
{
    Queue,
    Block,
};

class ResourceManager
{
public:
    template<class T>
    static void initResource(std::string path);
    template<class T>
    static std::shared_ptr<T> loadResource(std::string name, LoadMode mode);
    template<class T>
    static std::shared_ptr<T> getResource(std::string name);
    static void unloadResource(std::string name, LoadMode mode);
    static void reloadResource(std::string name);

    static void initPack(std::string path);
    static void loadPack(std::string path, LoadMode mode);
    static void unloadPack (std::string path, LoadMode mode);
    static void reloadPack(std::string path);
    static void switchPack(std::string path, std::string path);

    template<class T>
    static void createErrorResource(std::string path);
    template<class T>
    static std::shared_ptr<T> getErrorResource();

	static void init(bool useNullForErrorRes);
    static void update();
    static void cleanupUnused();
    static bool isLoading();
    static size_t getNumToLoad();
    static std::list<resource_ptr> listAll();
    static size_t getRamUse();
    static size_t genNumResources();
    static void setLoadCompleteCallback(std::function callback);

private:
    static std::map<std::string, resource_ptr> resources;
    static std::map<std::string, resource_ptr> errorResources;
    static std::queue<resource_ptr> loadingQueue;
	static std::queue<resource_ptr> unloadQueue;
	static std::queue<resource_ptr> reloadQueue;
	static bool useNullForErrorRes;

    static std::function loadCompleteCallback;

    static void loadFromQueue();
    static void unloadFromQueue();
    static void reloadFromQueue();
};

#endif //RESOURCE_MANAGER_HPP<|endoftext|>


<commit_before>//
//  File:	GeneratedBlock.cpp
//  Class	GeneratedBlock
//  Author	Jonatan Rapp & Alexander Hederstaf
//			All code is my own except where credited to others.
//
//  Copyright © 2012 Catch22. All Rights Reserved.
//
//  Date: Oct 10, 2012
//
//  Description:
//
//
#include "GeneratedBlock.hpp"

GeneratedBlock::GeneratedBlock(int dy, Blocktype type)
{
	this->dy = dy;
	this->type = type;
}

GeneratedBlock::~GeneratedBlock()
{

}

bool operator==(GeneratedBlock const& lhsBlock, GeneratedBlock const& rhsBlock)
{
	return lhsBlock.dy == rhsBlock.dy && lhsBlock.type == rhsBlock.type;
}

bool operator<(GeneratedBlock const& lhsBlock, GeneratedBlock const& rhsBlock)
{
	/*
	 * return value based on type and dY to order
	 * the GeneratedBlocks.
	 */
	int thisValue = lhsBlock.dy*3 + lhsBlock.type == INCLINE ? 0 : lhsBlock.type == HORIZONTAL ? 1 : 2;
	int otherValue = rhsBlock.dy*3 + rhsBlock.type == INCLINE ? 0 : rhsBlock.type == HORIZONTAL ? 1 : 2;
	return thisValue < otherValue;
}
<commit_msg>Small fix in operator< overload  - Added parantheses to properly calculate order values.<commit_after>//
//  File:	GeneratedBlock.cpp
//  Class	GeneratedBlock
//  Author	Jonatan Rapp & Alexander Hederstaf
//			All code is my own except where credited to others.
//
//  Copyright © 2012 Catch22. All Rights Reserved.
//
//  Date: Oct 10, 2012
//
//  Description:
//
//
#include "GeneratedBlock.hpp"
#include <stdio.h>

GeneratedBlock::GeneratedBlock(int dy, Blocktype type)
{
	this->dy = dy;
	this->type = type;
}

GeneratedBlock::~GeneratedBlock()
{

}

bool operator==(GeneratedBlock const& lhsBlock, GeneratedBlock const& rhsBlock)
{
	return lhsBlock.dy == rhsBlock.dy && lhsBlock.type == rhsBlock.type;
}

bool operator<(GeneratedBlock const& lhsBlock, GeneratedBlock const& rhsBlock)
{
	/*
	 * return value based on type and dY to order
	 * the GeneratedBlocks.
	 */
	int thisValue = lhsBlock.dy*3 + (lhsBlock.type == INCLINE ? 0 : lhsBlock.type == HORIZONTAL ? 1 : 2);
	int otherValue = rhsBlock.dy*3 + (rhsBlock.type == INCLINE ? 0 : rhsBlock.type == HORIZONTAL ? 1 : 2);
	return thisValue < otherValue;
}
<|endoftext|>


<commit_before># ifndef SPL_1D_SIGNAL_HH
# define SPL_1D_SIGNAL_HH

# include "NDSignal.hh"
# include "Point.hh"
# include <vector>

namespace spl{
  template<typename V>
    struct Signal1D;

  namespace global{
    template<>
      template<typename V>
      struct traits<Signal1D<V> >
      {
        typedef V value_type;
        typedef Point1D point_type;
        typedef Domain<1> domain_type;
        typedef V sub_type;
        typedef Signal1D<V> concrete_type;
      };

    template<typename oldType, typename newVal>
      struct mute<Signal1D<oldType>,oldType,newVal>
      {
        typedef Signal1D<newVal> res;
      };
  }//!global

  /* **
   * Signal1D is a signal defined by only one dimension.
   * This structure is more like a 1D array.
   */
  template <typename V>
    struct Signal1D : public NDSignal<Signal1D<V> >
  {
    typedef NDSignal<Signal1D<V> > parent;

    Signal1D(unsigned w);
    Signal1D(Domain<1> dom);
    Signal1D(const spl::Signal1D<V> &sig);

    V& operator()(unsigned x)
    {
      return at_impl(traits_point_type(Signal1D<V>)(x));
    }

    const V& operator()(unsigned x) const
    {
      return at_impl(traits_point_type(Signal1D<V>)(x));
    }

    private:

    V& at_impl(const traits_point_type(Signal1D<V>)& p)
    {
      return _data[p._x];
    }

    const V& at_impl(const traits_point_type(Signal1D<V>)& p) const
    {
      return _data[p._x];
    }

    public:

    const unsigned length() const
    {
      return parent::_domain[0];
    }

    explicit operator V* ()
    {
      return _data;
    }

    explicit operator const V* () const
    {
      return _data;
    }

    Signal1D clone_impl() const
    {
      Signal1D ret(this->domain());
      for_each_lin(ret, x)
        ret(x) = (*this)(x);
      return ret;
    }

    private:
    V *_data;
  };
}//!spl

#include "1DSignal.hxx"

# endif

<commit_msg>Likewise<commit_after># ifndef SPL_1D_SIGNAL_HH
# define SPL_1D_SIGNAL_HH

# include "NDSignal.hh"
# include "Point.hh"
# include <vector>

namespace spl{
  template<typename V>
    struct Signal1D;

  namespace global{
    template<>
      template<typename V>
      struct traits<Signal1D<V> >
      {
        typedef V value_type;
        typedef Point1D point_type;
        typedef Domain<1> domain_type;
        typedef V sub_type;
        typedef Signal1D<V> concrete_type;
      };

    template<typename oldType, typename newVal>
      struct mute<Signal1D<oldType>,oldType,newVal>
      {
        typedef Signal1D<newVal> res;
      };
  }//!global

  /* **
   * Signal1D is a signal defined by only one dimension.
   * This structure is more like a 1D array.
   */
  template <typename V>
    struct Signal1D : public NDSignal<Signal1D<V> >
  {
    typedef NDSignal<Signal1D<V> > parent;

    Signal1D(unsigned w);
    Signal1D(Domain<1> dom);
    Signal1D(const spl::Signal1D<V> &sig);

    V& operator()(unsigned x)
    {
      return at_impl(traits_point_type(Signal1D<V>)(x));
    }

    const V& operator()(unsigned x) const
    {
      return at_impl(traits_point_type(Signal1D<V>)(x));
    }

    private:

    V& at_impl(const traits_point_type(Signal1D<V>)& p)
    {
      return _data[p._x];
    }

    const V& at_impl(const traits_point_type(Signal1D<V>)& p) const
    {
      return _data[p._x];
    }

    public:

    const unsigned length() const
    {
      return parent::_domain[0];
    }

    explicit operator V* ()
    {
      return _data;
    }

    explicit operator const V* () const
    {
      return _data;
    }

    Signal1D clone_impl() const
    {
      Signal1D ret(this->domain());
      for_each_lin(ret, x)
        ret(x) = (*this)(x);
      return ret;
    }

    private:
    V *_data;

    template <typename T>
    friend struct NDSignal;
  };
}//!spl

#include "1DSignal.hxx"

# endif

<|endoftext|>


<commit_before>/*
Copyright (c) 2015,  Benjamin YanXiang Huang
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of yxbh nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once

#include <chrono>
#include <type_traits>

/**
 * @class ElapsedTimer
 * @brief
 *  A simple std::chrono based timer for measuring elapsed time.
 *  Use any of the std::chrono duration type to create a new ElapsedTimer.
 */
template<class Duration_T = std::chrono::milliseconds,
         class Test = typename std::enable_if<
             std::is_same<Duration_T, std::chrono::microseconds>::value ||
             std::is_same<Duration_T, std::chrono::milliseconds>::value ||
             std::is_same<Duration_T, std::chrono::seconds>::value
         >::type
     >
class ElapsedTimer
{
public:
    typedef Duration_T                          DurationType;
    typedef std::chrono::high_resolution_clock  ClockType;
    typedef ClockType::time_point               TimePointType;

private:
    DurationType    m_Duration;
    TimePointType   m_BeforeTP, m_AfterTP;

public:
    ElapsedTimer(void)
        : m_Duration(0), m_BeforeTP(ClockType::now()), m_AfterTP(m_BeforeTP) {}

    /** @return the elapsed time as the templated duration type. */
    inline DurationType elapsed(void)
    {
        m_AfterTP = ClockType::now();
        m_Duration += std::chrono::duration_cast<DurationType>(m_AfterTP - m_BeforeTP);
        m_BeforeTP = m_AfterTP;
        return m_Duration;
    }

    inline void restart(void)
    {
        m_BeforeTP = ClockType::now();
        m_Duration = DurationType(0);
    }
};<commit_msg>add ElapsedTimer to bh namespace<commit_after>/*
Copyright (c) 2015,  Benjamin YanXiang Huang
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of yxbh nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once

#include <chrono>
#include <type_traits>

namespace bh
{

/**
 * @class ElapsedTimer
 * @brief
 *  A simple std::chrono based timer for measuring elapsed time.
 *  Use any of the std::chrono duration type to create a new ElapsedTimer.
 */
template<class Duration_T = std::chrono::milliseconds,
         class Test = typename std::enable_if<
             std::is_same<Duration_T, std::chrono::microseconds>::value ||
             std::is_same<Duration_T, std::chrono::milliseconds>::value ||
             std::is_same<Duration_T, std::chrono::seconds>::value
         >::type
     >
class ElapsedTimer
{
public:
    typedef Duration_T                          DurationType;
    typedef std::chrono::high_resolution_clock  ClockType;
    typedef ClockType::time_point               TimePointType;

private:
    DurationType    m_Duration;
    TimePointType   m_BeforeTP, m_AfterTP;

public:
    ElapsedTimer(void)
        : m_Duration(0), m_BeforeTP(ClockType::now()), m_AfterTP(m_BeforeTP) {}

    /** @return the elapsed time as the templated duration type. */
    inline DurationType elapsed(void)
    {
        m_AfterTP = ClockType::now();
        m_Duration += std::chrono::duration_cast<DurationType>(m_AfterTP - m_BeforeTP);
        m_BeforeTP = m_AfterTP;
        return m_Duration;
    }

    inline void restart(void)
    {
        m_BeforeTP = ClockType::now();
        m_Duration = DurationType(0);
    }
}; // ElapsedTimer class

} // bh namespace<|endoftext|>


<commit_before>/* nobleNote, a note taking application
 * Copyright (C) 2012 Christian Metscher <hakaishi@web.de>,
                      Fabian Deuchler <Taiko000@gmail.com>

 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.

 * nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'.
 */

#include "textformattingtoolbar.h"
#include <QAction>
#include <QApplication>
#include <QColorDialog>
#include <QInputDialog>

TextFormattingToolbar::TextFormattingToolbar(QTextEdit * textEdit, QWidget *parent) :
    QToolBar(parent), textEdit_(textEdit)
{
    setWindowTitle(tr("Format actions"));
    setObjectName(tr("Formattoolbar"));

    actionTextBold = new QAction(QIcon::fromTheme("format-text-bold",
      QIcon(":bold")), tr("&Bold"), this);
    actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B);
    actionTextBold->setPriority(QAction::LowPriority);
    QFont bold;
    bold.setBold(true);
    actionTextBold->setFont(bold);
    connect(actionTextBold, SIGNAL(triggered()), this, SLOT(boldText()));
    addAction(actionTextBold);
    actionTextBold->setCheckable(true);

    actionTextItalic = new QAction(QIcon::fromTheme("format-text-italic",
      QIcon(":italic")), tr("&Italic"), this);
    actionTextItalic->setPriority(QAction::LowPriority);
    actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I);
    QFont italic;
    italic.setItalic(true);
    actionTextItalic->setFont(italic);
    connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(italicText()));
    addAction(actionTextItalic);
    actionTextItalic->setCheckable(true);

    actionTextUnderline = new QAction(QIcon::fromTheme("format-text-underline",
      QIcon(":underlined")), tr("&Underline"), this);
    actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U);
    actionTextUnderline->setPriority(QAction::LowPriority);
    QFont underline;
    underline.setUnderline(true);
    actionTextUnderline->setFont(underline);
    connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(underlinedText()));
    addAction(actionTextUnderline);
    actionTextUnderline->setCheckable(true);

    actionTextStrikeOut = new QAction(QIcon::fromTheme("format-text-strikethrough",
      QIcon(":strikedout")), tr("&Strike Out"), this);
    actionTextStrikeOut->setShortcut(Qt::CTRL + Qt::Key_S);
    actionTextStrikeOut->setPriority(QAction::LowPriority);
    QFont strikeOut;
    strikeOut.setStrikeOut(true);
    actionTextStrikeOut->setFont(strikeOut);
    connect(actionTextStrikeOut, SIGNAL(triggered()), this, SLOT(strikedOutText()));
    addAction(actionTextStrikeOut);
    actionTextStrikeOut->setCheckable(true);

    actionInsertHyperlink = new QAction(QIcon::fromTheme("emblem-web",QIcon(":hyperlink")),tr("&Hyperlink"),this);
    actionInsertHyperlink->setShortcut(Qt::CTRL + Qt::Key_K); // word shortcut
    actionInsertHyperlink->setPriority(QAction::LowPriority);
    connect(actionInsertHyperlink,SIGNAL(triggered()),this,SLOT(insertHyperlink()));
    addAction(actionInsertHyperlink);

    actionClearFormatting = new QAction(QIcon::fromTheme("TODO",QIcon(":clearFormatting")),tr("&Clear formatting"),this);
    actionClearFormatting->setPriority(QAction::LowPriority);
    actionClearFormatting->setShortcut(Qt::CTRL + Qt::Key_Space); // ms word clear font formatting shortcut
    connect(actionClearFormatting,SIGNAL(triggered()),this,SLOT(clearCharFormat()));
    addAction(actionClearFormatting);

    QPixmap textPix(16, 16);
    textPix.fill(textEdit_->palette().windowText().color());
    actionTextColor = new QAction(textPix, tr("&Text color..."), this);
    connect(actionTextColor, SIGNAL(triggered()), this, SLOT(coloredText()));
    addAction(actionTextColor);

    QPixmap bPix(16, 16);
    bPix.fill(textEdit_->palette().base().color());
    actionTextBColor = new QAction(bPix, tr("&Background color..."), this);
    connect(actionTextBColor, SIGNAL(triggered()), this, SLOT(markedText()));
    addAction(actionTextBColor);

    fontComboBox = new QFontComboBox(this);
    fontComboBox->setFocusPolicy(Qt::TabFocus);
    addWidget(fontComboBox);
    connect(fontComboBox, SIGNAL(activated(QString)), this, SLOT(fontOfText(QString)));

    fontSizeComboBox = new QComboBox(this);
    fontSizeComboBox->setFocusPolicy(Qt::TabFocus);
    fontSizeComboBox->setObjectName("comboSize");
    addWidget(fontSizeComboBox);
    fontSizeComboBox->setEditable(true);
    connect(fontSizeComboBox, SIGNAL(activated(QString)), this, SLOT(pointSizeOfText(QString)));

    QFontDatabase db;
    foreach(int size, db.standardSizes())
      fontSizeComboBox->addItem(QString::number(size));

    connect(textEdit_, SIGNAL(currentCharFormatChanged(QTextCharFormat)), this,
      SLOT(getFontAndPointSizeOfText(QTextCharFormat)));
}

void TextFormattingToolbar::mergeFormatOnWordOrSelection(const QTextCharFormat &format){
     QTextCursor cursor = textEdit_->textCursor();
     if(!cursor.hasSelection() && !cursor.atBlockStart() && !cursor.atBlockEnd())
       cursor.select(QTextCursor::WordUnderCursor);
     cursor.mergeCharFormat(format);
     textEdit_->mergeCurrentCharFormat(format);
}

void TextFormattingToolbar::clearCharFormat()
{
    QTextCursor cursor = textEdit_->textCursor();
    if(!cursor.hasSelection() && !cursor.atBlockStart() && !cursor.atBlockEnd())
      cursor.select(QTextCursor::WordUnderCursor);
    cursor.setCharFormat(QTextCharFormat());
}

void TextFormattingToolbar::getFontAndPointSizeOfText(const QTextCharFormat &format){
     QFont f = format.font();
     fontComboBox->setCurrentIndex(fontComboBox->findText(QFontInfo(f).family()));
     fontSizeComboBox->setCurrentIndex(fontSizeComboBox->findText(QString::number(f.pointSize())));
     actionTextBold->setChecked(f.bold());
     actionTextItalic->setChecked(f.italic());
     actionTextUnderline->setChecked(f.underline());
     actionTextStrikeOut->setChecked(f.strikeOut());
     QPixmap textPix(16,16);
     if(format.foreground().style() == Qt::NoBrush)
       textPix.fill(textEdit_->palette().windowText().color());
     else
       textPix.fill(format.foreground().color());
     actionTextColor->setIcon(textPix);
     QPixmap bPix(16,16);
     if(format.background().style() == Qt::NoBrush)
       bPix.fill(textEdit_->palette().base().color());
     else
       bPix.fill(format.background().color());
     actionTextBColor->setIcon(bPix);
}

void TextFormattingToolbar::boldText(){
     QTextCharFormat fmt;
     fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal);
     mergeFormatOnWordOrSelection(fmt);
}

void TextFormattingToolbar::italicText(){
     QTextCharFormat fmt;
     fmt.setFontItalic(actionTextItalic->isChecked());
     mergeFormatOnWordOrSelection(fmt);
}

void TextFormattingToolbar::underlinedText(){
     QTextCharFormat fmt;
     fmt.setFontUnderline(actionTextUnderline->isChecked());
     mergeFormatOnWordOrSelection(fmt);
}

void TextFormattingToolbar::strikedOutText(){
    QTextCharFormat fmt;
    fmt.setFontStrikeOut(actionTextStrikeOut->isChecked());
    mergeFormatOnWordOrSelection(fmt);
}

void TextFormattingToolbar::coloredText(){
     QColor col = QColorDialog::getColor(textEdit_->textColor(), this);
     if(!col.isValid())
       return;
     QTextCharFormat fmt;
     fmt.setForeground(QBrush(col,Qt::SolidPattern));
     mergeFormatOnWordOrSelection(fmt);
     QPixmap pix(16, 16);
     pix.fill(col);
     actionTextColor->setIcon(pix);
}

void TextFormattingToolbar::markedText(){
     QColor col = QColorDialog::getColor(textEdit_->textBackgroundColor(), this);
     if(!col.isValid())
       return;
     QTextCharFormat fmt;
     fmt.setBackground(QBrush(col,Qt::SolidPattern));
     mergeFormatOnWordOrSelection(fmt);
     QPixmap pix(16, 16);
     pix.fill(col);
     actionTextBColor->setIcon(pix);
}

void TextFormattingToolbar::insertHyperlink()
{
    QTextCursor cursor = textEdit_->textCursor();

    QString selectedText = cursor.selectedText();

    bool ok;
    QString link = QInputDialog::getText(textEdit_,tr("Insert hyperlink"),tr("Addr&ess:"),QLineEdit::Normal,selectedText,&ok);
    if(!ok)
        return;
/*TODO: de-formatting
    if(link.isEmpty){
      resetFonts()//or something like that
      return;
    }*/

/*TODO: check if link/e-mail is valid with the following regexps
QRegExp(">\\b((((https?|ftp)://)|(www\\.))[a-zA-Z0-9_\\.\\-\\?]+)\\b(<?)" , Qt::CaseInsensitive)
QRegExp(">\\b([a-zA-Z0-9_\\.\\-]+@[a-zA-Z0-9_\\.\\-]+)\\b(<?)", Qt::CaseInsensitive)
*/
    if(selectedText.isEmpty())
        selectedText = link;

    if(link.contains("@"))
      cursor.insertHtml(""+selectedText+"");
    else
      cursor.insertHtml(""+selectedText+"");
}

void TextFormattingToolbar::fontOfText(const QString &f){
     QTextCharFormat fmt;
     fmt.setFontFamily(f);
     mergeFormatOnWordOrSelection(fmt);
}

void TextFormattingToolbar::pointSizeOfText(const QString &p){
     qreal pointSize = p.toFloat();
     if(p.toFloat() > 0){
       QTextCharFormat fmt;
       fmt.setFontPointSize(pointSize);
       mergeFormatOnWordOrSelection(fmt);
     }
}

void TextFormattingToolbar::setFont(QFont font)
{
     fontComboBox->setCurrentFont(font);
     fontSizeComboBox->setCurrentIndex(fontSizeComboBox->findText(QString::number(
       font.pointSize())));
}
<commit_msg>fixed text formatting and clearing<commit_after>/* nobleNote, a note taking application
 * Copyright (C) 2012 Christian Metscher <hakaishi@web.de>,
                      Fabian Deuchler <Taiko000@gmail.com>

 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.

 * nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'.
 */

#include "textformattingtoolbar.h"
#include <QAction>
#include <QApplication>
#include <QColorDialog>
#include <QInputDialog>
#include <QTextBlock>
#include <QDebug>
TextFormattingToolbar::TextFormattingToolbar(QTextEdit * textEdit, QWidget *parent) :
    QToolBar(parent), textEdit_(textEdit)
{
    setWindowTitle(tr("Format actions"));
    setObjectName(tr("Formattoolbar"));

    actionTextBold = new QAction(QIcon::fromTheme("format-text-bold",
      QIcon(":bold")), tr("&Bold"), this);
    actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B);
    actionTextBold->setPriority(QAction::LowPriority);
    QFont bold;
    bold.setBold(true);
    actionTextBold->setFont(bold);
    connect(actionTextBold, SIGNAL(triggered()), this, SLOT(boldText()));
    addAction(actionTextBold);
    actionTextBold->setCheckable(true);

    actionTextItalic = new QAction(QIcon::fromTheme("format-text-italic",
      QIcon(":italic")), tr("&Italic"), this);
    actionTextItalic->setPriority(QAction::LowPriority);
    actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I);
    QFont italic;
    italic.setItalic(true);
    actionTextItalic->setFont(italic);
    connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(italicText()));
    addAction(actionTextItalic);
    actionTextItalic->setCheckable(true);

    actionTextUnderline = new QAction(QIcon::fromTheme("format-text-underline",
      QIcon(":underlined")), tr("&Underline"), this);
    actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U);
    actionTextUnderline->setPriority(QAction::LowPriority);
    QFont underline;
    underline.setUnderline(true);
    actionTextUnderline->setFont(underline);
    connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(underlinedText()));
    addAction(actionTextUnderline);
    actionTextUnderline->setCheckable(true);

    actionTextStrikeOut = new QAction(QIcon::fromTheme("format-text-strikethrough",
      QIcon(":strikedout")), tr("&Strike Out"), this);
    actionTextStrikeOut->setShortcut(Qt::CTRL + Qt::Key_S);
    actionTextStrikeOut->setPriority(QAction::LowPriority);
    QFont strikeOut;
    strikeOut.setStrikeOut(true);
    actionTextStrikeOut->setFont(strikeOut);
    connect(actionTextStrikeOut, SIGNAL(triggered()), this, SLOT(strikedOutText()));
    addAction(actionTextStrikeOut);
    actionTextStrikeOut->setCheckable(true);

    actionInsertHyperlink = new QAction(QIcon::fromTheme("emblem-web",QIcon(":hyperlink")),tr("&Hyperlink"),this);
    actionInsertHyperlink->setShortcut(Qt::CTRL + Qt::Key_K); // word shortcut
    actionInsertHyperlink->setPriority(QAction::LowPriority);
    connect(actionInsertHyperlink,SIGNAL(triggered()),this,SLOT(insertHyperlink()));
    addAction(actionInsertHyperlink);

    actionClearFormatting = new QAction(QIcon::fromTheme("TODO",QIcon(":clearFormatting")),tr("&Clear formatting"),this);
    actionClearFormatting->setPriority(QAction::LowPriority);
    actionClearFormatting->setShortcut(Qt::CTRL + Qt::Key_Space); // ms word clear font formatting shortcut
    connect(actionClearFormatting,SIGNAL(triggered()),this,SLOT(clearCharFormat()));
    addAction(actionClearFormatting);

    QPixmap textPix(16, 16);
    textPix.fill(textEdit_->palette().windowText().color());
    actionTextColor = new QAction(textPix, tr("&Text color..."), this);
    connect(actionTextColor, SIGNAL(triggered()), this, SLOT(coloredText()));
    addAction(actionTextColor);

    QPixmap bPix(16, 16);
    bPix.fill(textEdit_->palette().base().color());
    actionTextBColor = new QAction(bPix, tr("&Background color..."), this);
    connect(actionTextBColor, SIGNAL(triggered()), this, SLOT(markedText()));
    addAction(actionTextBColor);

    fontComboBox = new QFontComboBox(this);
    fontComboBox->setFocusPolicy(Qt::TabFocus);
    addWidget(fontComboBox);
    connect(fontComboBox, SIGNAL(activated(QString)), this, SLOT(fontOfText(QString)));

    fontSizeComboBox = new QComboBox(this);
    fontSizeComboBox->setFocusPolicy(Qt::TabFocus);
    fontSizeComboBox->setObjectName("comboSize");
    addWidget(fontSizeComboBox);
    fontSizeComboBox->setEditable(true);
    connect(fontSizeComboBox, SIGNAL(activated(QString)), this, SLOT(pointSizeOfText(QString)));

    QFontDatabase db;
    foreach(int size, db.standardSizes())
      fontSizeComboBox->addItem(QString::number(size));

    connect(textEdit_, SIGNAL(currentCharFormatChanged(QTextCharFormat)), this,
      SLOT(getFontAndPointSizeOfText(QTextCharFormat)));
}

void TextFormattingToolbar::mergeFormatOnWordOrSelection(const QTextCharFormat &format){
     QTextCursor cursor = textEdit_->textCursor();
     QString block = cursor.block().text();
     if(!cursor.atBlockStart() && !cursor.atBlockEnd())
       if(!(block.at(cursor.positionInBlock()) == ' ') && !(block.at(cursor.positionInBlock()-1) == ' '))
         cursor.select(QTextCursor::WordUnderCursor);
     cursor.mergeCharFormat(format);
     textEdit_->mergeCurrentCharFormat(format);
}

void TextFormattingToolbar::clearCharFormat()
{
     QTextCursor cursor = textEdit_->textCursor();
     QString block = cursor.block().text();
     if(!cursor.atBlockStart() && !cursor.atBlockEnd())
       if(!(block.at(cursor.positionInBlock()) == ' ') && !(block.at(cursor.positionInBlock()-1) == ' '))
         cursor.select(QTextCursor::WordUnderCursor);
     cursor.setCharFormat(QTextCharFormat());
     textEdit_->setCurrentCharFormat(QTextCharFormat());
}

void TextFormattingToolbar::getFontAndPointSizeOfText(const QTextCharFormat &format){
     QFont f = format.font();
     fontComboBox->setCurrentIndex(fontComboBox->findText(QFontInfo(f).family()));
     fontSizeComboBox->setCurrentIndex(fontSizeComboBox->findText(QString::number(f.pointSize())));
     actionTextBold->setChecked(f.bold());
     actionTextItalic->setChecked(f.italic());
     actionTextUnderline->setChecked(f.underline());
     actionTextStrikeOut->setChecked(f.strikeOut());
     QPixmap textPix(16,16);
     if(format.foreground().style() == Qt::NoBrush)
       textPix.fill(textEdit_->palette().windowText().color());
     else
       textPix.fill(format.foreground().color());
     actionTextColor->setIcon(textPix);
     QPixmap bPix(16,16);
     if(format.background().style() == Qt::NoBrush)
       bPix.fill(textEdit_->palette().base().color());
     else
       bPix.fill(format.background().color());
     actionTextBColor->setIcon(bPix);
}

void TextFormattingToolbar::boldText(){
     QTextCharFormat fmt;
     fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal);
     mergeFormatOnWordOrSelection(fmt);
}

void TextFormattingToolbar::italicText(){
     QTextCharFormat fmt;
     fmt.setFontItalic(actionTextItalic->isChecked());
     mergeFormatOnWordOrSelection(fmt);
}

void TextFormattingToolbar::underlinedText(){
     QTextCharFormat fmt;
     fmt.setFontUnderline(actionTextUnderline->isChecked());
     mergeFormatOnWordOrSelection(fmt);
}

void TextFormattingToolbar::strikedOutText(){
    QTextCharFormat fmt;
    fmt.setFontStrikeOut(actionTextStrikeOut->isChecked());
    mergeFormatOnWordOrSelection(fmt);
}

void TextFormattingToolbar::coloredText(){
     QColor col = QColorDialog::getColor(textEdit_->textColor(), this);
     if(!col.isValid())
       return;
     QTextCharFormat fmt;
     fmt.setForeground(QBrush(col,Qt::SolidPattern));
     mergeFormatOnWordOrSelection(fmt);
     QPixmap pix(16, 16);
     pix.fill(col);
     actionTextColor->setIcon(pix);
}

void TextFormattingToolbar::markedText(){
     QColor col = QColorDialog::getColor(textEdit_->textBackgroundColor(), this);
     if(!col.isValid())
       return;
     QTextCharFormat fmt;
     fmt.setBackground(QBrush(col,Qt::SolidPattern));
     mergeFormatOnWordOrSelection(fmt);
     QPixmap pix(16, 16);
     pix.fill(col);
     actionTextBColor->setIcon(pix);
}

void TextFormattingToolbar::insertHyperlink()
{
    QTextCursor cursor = textEdit_->textCursor();

    QString selectedText = cursor.selectedText();

    bool ok;
    QString link = QInputDialog::getText(textEdit_,tr("Insert hyperlink"),tr("Addr&ess:"),QLineEdit::Normal,selectedText,&ok);
    if(!ok)
        return;
/*TODO: de-formatting
    if(link.isEmpty){
      resetFonts()//or something like that
      return;
    }*/

/*TODO: check if link/e-mail is valid with the following regexps
QRegExp(">\\b((((https?|ftp)://)|(www\\.))[a-zA-Z0-9_\\.\\-\\?]+)\\b(<?)" , Qt::CaseInsensitive)
QRegExp(">\\b([a-zA-Z0-9_\\.\\-]+@[a-zA-Z0-9_\\.\\-]+)\\b(<?)", Qt::CaseInsensitive)
*/
    if(selectedText.isEmpty())
        selectedText = link;

    if(link.contains("@"))
      cursor.insertHtml(""+selectedText+"");
    else
      cursor.insertHtml(""+selectedText+"");
}

void TextFormattingToolbar::fontOfText(const QString &f){
     QTextCharFormat fmt;
     fmt.setFontFamily(f);
     mergeFormatOnWordOrSelection(fmt);
}

void TextFormattingToolbar::pointSizeOfText(const QString &p){
     qreal pointSize = p.toFloat();
     if(p.toFloat() > 0){
       QTextCharFormat fmt;
       fmt.setFontPointSize(pointSize);
       mergeFormatOnWordOrSelection(fmt);
     }
}

void TextFormattingToolbar::setFont(QFont font)
{
     fontComboBox->setCurrentFont(font);
     fontSizeComboBox->setCurrentIndex(fontSizeComboBox->findText(QString::number(
       font.pointSize())));
}
<|endoftext|>