<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007, Image Engine Design Inc. 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 Image Engine Design nor the names of any
//       other contributors to this software 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 OWNER 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.
//
//////////////////////////////////////////////////////////////////////////

// This include needs to be the very first to prevent problems with warnings
// regarding redefinition of _POSIX_C_SOURCE
#include <boost/python.hpp>

// System includes
#include <string>
#include <stdexcept>

#include <OpenEXR/ImathEuler.h>

#include "IECore/bindings/ImathVecBinding.h"
#include "IECore/bindings/IECoreBinding.h"

using namespace boost::python;
using namespace Imath;
using namespace std;

namespace IECore
{

template<typename T>
void bindEuler(const char *bindName);

void bindImathEuler()
{
	bindEuler<float>("Eulerf");
	bindEuler<double>("Eulerd");
}

#define DEFINEEULERSTRSPECIALISATION( EULER )\
\
template<>\
std::string repr<EULER>( EULER &x )\
{\
	std::stringstream s;\
	s << #EULER << "( ";\
	for( unsigned i=0; i<EULER::dimensions(); i++ )\
	{\
		s << x[i];\
		if( i!=EULER::dimensions()-1 )\
		{\
			s << ", ";\
		}\
	}\
	s << " )";\
	return s.str();\
}\
\
template<>\
std::string str<EULER>( EULER &x )\
{\
	std::stringstream s;\
	for( unsigned i=0; i<EULER::dimensions(); i++ )\
	{\
		s << x[i];\
		if( i!=EULER::dimensions()-1 )\
		{\
			s << " ";\
		}\
	}\
	return s.str();\
}\

DEFINEEULERSTRSPECIALISATION( Eulerf );
DEFINEEULERSTRSPECIALISATION( Eulerd );

template<typename T>
struct EulerHelper
{
	static tuple angleOrder( Euler<T> &e )
	{
		int i, j, k;
		e.angleOrder( i, j, k );

		return make_tuple( i, j, k );
	}

	static tuple angleMapping( Euler<T> &e )
	{
		int i, j, k;
		e.angleMapping( i, j, k );

		return make_tuple( i, j, k );
	}
};

template<typename T>
void bindEuler(const char *bindName)
{
	/// We need these typedefs so we can instantiate the "optional" and "enum_" templates.
	// Without them, the enums defined in Imath::Euler aren't types.
	typedef typename Euler<T>::Order OrderType;
	typedef typename Euler<T>::InputLayout InputLayoutType;
	typedef typename Euler<T>::Axis AxisType;

	void (Euler<T>::*extractM33)(const Matrix33<T>&) = &Euler<T>::extract;
	void (Euler<T>::*extractM44)(const Matrix44<T>&) = &Euler<T>::extract;
	void (Euler<T>::*extractQuat)(const Quat<T>&) = &Euler<T>::extract;

	object euler = class_< Euler<T>, bases< Vec3<T> > >(bindName)

		.def( init<>() )
		.def( init< const Euler<T> & >() )
		.def( init< OrderType >() )
		.def( init< const Vec3<T> &, optional< OrderType, InputLayoutType > >() )
		.def( init< T, T, T, optional< OrderType, InputLayoutType > >() )
		.def( init< const Euler<T> &, optional< OrderType > >() )
		.def( init< const Matrix33<T> &, optional< OrderType > > () )
		.def( init< const Matrix44<T> &, optional< OrderType > > () )

		.def( "__str__", &IECore::str<Euler<T> > )
		.def( "__repr__", &IECore::repr<Euler<T> > )

		.def( "legal", &Euler<T>::legal ).staticmethod("legal")

		.def( "setXYZVector", &Euler<T>::setXYZVector )

		.def( "order", &Euler<T>::order )
		.def( "setOrder", &Euler<T>::setOrder )

		.def( "set", &Euler<T>::set )

		.def( "extract", extractM33 )
		.def( "extract", extractM44 )
		.def( "extract", extractQuat )

		.def( "toMatrix33", &Euler<T>::toMatrix33 )
		.def( "toMatrix44", &Euler<T>::toMatrix44 )
		.def( "toQuat", &Euler<T>::toQuat )
		.def( "toXYZVector", &Euler<T>::toXYZVector )

		.def( "angleOrder", &EulerHelper<T>::angleOrder )
		.def( "angleMapping", &EulerHelper<T>::angleOrder )

		.def( "angleMod", &Euler<T>::angleMod ).staticmethod("angleMod")
		.def( "simpleXYZRotation", &Euler<T>::simpleXYZRotation ).staticmethod("simpleXYZRotation")
		.def( "nearestRotation", &Euler<T>::simpleXYZRotation ).staticmethod("nearestRotation")

		.def( "makeNear", &Euler<T>::makeNear )

		.def( "frameStatic", &Euler<T>::frameStatic )
		.def( "initialRepeated", &Euler<T>::initialRepeated )
		.def( "parityEven", &Euler<T>::parityEven )
		.def( "initialAxis", &Euler<T>::initialAxis )
	;

	scope eulerScope (euler );

	enum_< OrderType >( "Order" )
		.value( "XYZ", Euler<T>::XYZ )
		.value( "XZY", Euler<T>::XZY )
		.value( "YZX", Euler<T>::YZX )
		.value( "YXZ", Euler<T>::YXZ )
		.value( "ZXY", Euler<T>::ZXY )
		.value( "ZYX", Euler<T>::ZYX )

		.value( "XZX", Euler<T>::XZX )
		.value( "XYX", Euler<T>::XYX )
		.value( "YXY", Euler<T>::YXY )
		.value( "YZY", Euler<T>::YZY )
		.value( "ZYZ", Euler<T>::ZYZ )
		.value( "ZXZ", Euler<T>::ZXZ )

		.value( "XYZr", Euler<T>::XYZr )
		.value( "XZYr", Euler<T>::XZYr )
		.value( "YZXr", Euler<T>::YZXr )
		.value( "YXZr", Euler<T>::YXZr )
		.value( "ZXYr", Euler<T>::ZXYr )
		.value( "ZYXr", Euler<T>::ZYXr )

		.value( "XZXr", Euler<T>::XZXr )
		.value( "XYXr", Euler<T>::XYXr )
		.value( "YXYr", Euler<T>::YXYr )
		.value( "YZYr", Euler<T>::YZYr )
		.value( "ZYZr", Euler<T>::ZYZr )
		.value( "ZXZr", Euler<T>::ZXZr )

		.value( "Default", Euler<T>::Default )
	;

	enum_< InputLayoutType >( "InputLayout" )
		.value( "XYZLayout", Euler<T>::XYZLayout )
		.value( "IJKLayout", Euler<T>::IJKLayout )
	;

	enum_< AxisType >( "Axis" )
		.value( "X", Euler<T>::X )
		.value( "Y", Euler<T>::Y )
		.value( "Z", Euler<T>::Z )
	;
}

}
<commit_msg>Fixed simpleXYZRotation/nearestRotation bindings<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007, Image Engine Design Inc. 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 Image Engine Design nor the names of any
//       other contributors to this software 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 OWNER 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.
//
//////////////////////////////////////////////////////////////////////////

// This include needs to be the very first to prevent problems with warnings
// regarding redefinition of _POSIX_C_SOURCE
#include <boost/python.hpp>

// System includes
#include <string>
#include <stdexcept>

#include <OpenEXR/ImathEuler.h>

#include "IECore/bindings/ImathVecBinding.h"
#include "IECore/bindings/IECoreBinding.h"

using namespace boost::python;
using namespace Imath;
using namespace std;

namespace IECore
{

template<typename T>
void bindEuler(const char *bindName);

void bindImathEuler()
{
	bindEuler<float>("Eulerf");
	bindEuler<double>("Eulerd");
}

#define DEFINEEULERSTRSPECIALISATION( EULER )\
\
template<>\
std::string repr<EULER>( EULER &x )\
{\
	std::stringstream s;\
	s << #EULER << "( ";\
	for( unsigned i=0; i<EULER::dimensions(); i++ )\
	{\
		s << x[i];\
		if( i!=EULER::dimensions()-1 )\
		{\
			s << ", ";\
		}\
	}\
	s << " )";\
	return s.str();\
}\
\
template<>\
std::string str<EULER>( EULER &x )\
{\
	std::stringstream s;\
	for( unsigned i=0; i<EULER::dimensions(); i++ )\
	{\
		s << x[i];\
		if( i!=EULER::dimensions()-1 )\
		{\
			s << " ";\
		}\
	}\
	return s.str();\
}\

DEFINEEULERSTRSPECIALISATION( Eulerf );
DEFINEEULERSTRSPECIALISATION( Eulerd );

template<typename T>
struct EulerHelper
{
	typedef typename Euler<T>::Order OrderType;

	static tuple angleOrder( Euler<T> &e )
	{
		int i, j, k;
		e.angleOrder( i, j, k );

		return make_tuple( i, j, k );
	}

	static tuple angleMapping( Euler<T> &e )
	{
		int i, j, k;
		e.angleMapping( i, j, k );

		return make_tuple( i, j, k );
	}

	Vec3<T> simpleXYZRotation( Vec3<T> &xyzRot, const Vec3<T> targetXyzRot )
	{
		Euler<T>::simpleXYZRotation( xyzRot, targetXyzRot );

		return xyzRot;
	}

	Vec3<T> nearestRotation( Vec3<T> &xyzRot, const Vec3<T> &targetXyzRot, OrderType order )
	{
		Euler<T>::nearestRotation( xyzRot, targetXyzRot, order );

		return xyzRot;
	}

	Vec3<T> nearestRotation( Vec3<T> &xyzRot, const Vec3<T> &targetXyzRot )
	{
		return nearestRotation( xyzRot, targetXyzRot, (OrderType)(Euler<T>::XYZ) );
	}
};

template<typename T>
void bindEuler(const char *bindName)
{
	/// We need these typedefs so we can instantiate the "optional" and "enum_" templates.
	// Without them, the enums defined in Imath::Euler aren't types.
	typedef typename Euler<T>::Order OrderType;
	typedef typename Euler<T>::InputLayout InputLayoutType;
	typedef typename Euler<T>::Axis AxisType;

	void (Euler<T>::*extractM33)(const Matrix33<T>&) = &Euler<T>::extract;
	void (Euler<T>::*extractM44)(const Matrix44<T>&) = &Euler<T>::extract;
	void (Euler<T>::*extractQuat)(const Quat<T>&) = &Euler<T>::extract;

	Vec3<T> (EulerHelper<T>::*nearestRotation1)( Vec3<T> &, const Vec3<T> &, OrderType )= &EulerHelper<T>::nearestRotation;
	Vec3<T> (EulerHelper<T>::*nearestRotation2)( Vec3<T> &, const Vec3<T> & )= &EulerHelper<T>::nearestRotation;

	object euler = class_< Euler<T>, bases< Vec3<T> > >(bindName)

		.def( init<>() )
		.def( init< const Euler<T> & >() )
		.def( init< OrderType >() )
		.def( init< const Vec3<T> &, optional< OrderType, InputLayoutType > >() )
		.def( init< T, T, T, optional< OrderType, InputLayoutType > >() )
		.def( init< const Euler<T> &, optional< OrderType > >() )
		.def( init< const Matrix33<T> &, optional< OrderType > > () )
		.def( init< const Matrix44<T> &, optional< OrderType > > () )

		.def( "__str__", &IECore::str<Euler<T> > )
		.def( "__repr__", &IECore::repr<Euler<T> > )

		.def( "legal", &Euler<T>::legal ).staticmethod("legal")

		.def( "setXYZVector", &Euler<T>::setXYZVector )

		.def( "order", &Euler<T>::order )
		.def( "setOrder", &Euler<T>::setOrder )

		.def( "set", &Euler<T>::set )

		.def( "extract", extractM33 )
		.def( "extract", extractM44 )
		.def( "extract", extractQuat )

		.def( "toMatrix33", &Euler<T>::toMatrix33 )
		.def( "toMatrix44", &Euler<T>::toMatrix44 )
		.def( "toQuat", &Euler<T>::toQuat )
		.def( "toXYZVector", &Euler<T>::toXYZVector )

		.def( "angleOrder", &EulerHelper<T>::angleOrder )
		.def( "angleMapping", &EulerHelper<T>::angleOrder )

		.def( "angleMod", &Euler<T>::angleMod ).staticmethod("angleMod")
		.def( "simpleXYZRotation", &EulerHelper<T>::simpleXYZRotation ).staticmethod("simpleXYZRotation")
		.def( "nearestRotation", nearestRotation1 ).staticmethod("nearestRotation")
		.def( "nearestRotation", nearestRotation2 ).staticmethod("nearestRotation")

		.def( "makeNear", &Euler<T>::makeNear )

		.def( "frameStatic", &Euler<T>::frameStatic )
		.def( "initialRepeated", &Euler<T>::initialRepeated )
		.def( "parityEven", &Euler<T>::parityEven )
		.def( "initialAxis", &Euler<T>::initialAxis )
	;

	scope eulerScope (euler );

	enum_< OrderType >( "Order" )
		.value( "XYZ", Euler<T>::XYZ )
		.value( "XZY", Euler<T>::XZY )
		.value( "YZX", Euler<T>::YZX )
		.value( "YXZ", Euler<T>::YXZ )
		.value( "ZXY", Euler<T>::ZXY )
		.value( "ZYX", Euler<T>::ZYX )

		.value( "XZX", Euler<T>::XZX )
		.value( "XYX", Euler<T>::XYX )
		.value( "YXY", Euler<T>::YXY )
		.value( "YZY", Euler<T>::YZY )
		.value( "ZYZ", Euler<T>::ZYZ )
		.value( "ZXZ", Euler<T>::ZXZ )

		.value( "XYZr", Euler<T>::XYZr )
		.value( "XZYr", Euler<T>::XZYr )
		.value( "YZXr", Euler<T>::YZXr )
		.value( "YXZr", Euler<T>::YXZr )
		.value( "ZXYr", Euler<T>::ZXYr )
		.value( "ZYXr", Euler<T>::ZYXr )

		.value( "XZXr", Euler<T>::XZXr )
		.value( "XYXr", Euler<T>::XYXr )
		.value( "YXYr", Euler<T>::YXYr )
		.value( "YZYr", Euler<T>::YZYr )
		.value( "ZYZr", Euler<T>::ZYZr )
		.value( "ZXZr", Euler<T>::ZXZr )

		.value( "Default", Euler<T>::Default )
	;

	enum_< InputLayoutType >( "InputLayout" )
		.value( "XYZLayout", Euler<T>::XYZLayout )
		.value( "IJKLayout", Euler<T>::IJKLayout )
	;

	enum_< AxisType >( "Axis" )
		.value( "X", Euler<T>::X )
		.value( "Y", Euler<T>::Y )
		.value( "Z", Euler<T>::Z )
	;
}

}
<|endoftext|>


<commit_before>#include "message.hpp"

string DebugPrint(string const & t)
{
  string res;
  res.push_back('\'');
  for (string::const_iterator it = t.begin(); it != t.end(); ++it)
  {
    static char const toHex[] = "0123456789abcdef";
    unsigned char const c = static_cast<unsigned char>(*it);
    if (c >= ' ' && c <= '~')
      res.push_back(*it);
    else
    {
      res.push_back('\\');
      res.push_back(toHex[c >> 4]);
      res.push_back(toHex[c & 0xf]);
    }
  }
  res.push_back('\'');
  return res;
}
<commit_msg>Logger fix - print original UTF-8 strings<commit_after>#include "message.hpp"

string DebugPrint(string const & t)
{
//  string res;
//  res.push_back('\'');
//  for (string::const_iterator it = t.begin(); it != t.end(); ++it)
//  {
//    static char const toHex[] = "0123456789abcdef";
//    unsigned char const c = static_cast<unsigned char>(*it);
//    if (c >= ' ' && c <= '~')
//      res.push_back(*it);
//    else
//    {
//      res.push_back('\\');
//      res.push_back(toHex[c >> 4]);
//      res.push_back(toHex[c & 0xf]);
//    }
//  }
//  res.push_back('\'');
  // Simply print UTF-8 string. Our computers (finally) supports it.
  return t;
}
<|endoftext|>


<commit_before>#include <boost/program_options.hpp>
#include <iostream>
#include "data/GraphSerializer.hpp"
#include "data/PathSerializer.hpp"
#include "data/ConfigSerializer.hpp"
#include "genetic/GeneticSolver.hpp"
#include "genetic/GeneticAnalyser.hpp"
#include "net/PopulationExchanger.hpp"
#include "utils/Random.hpp"

namespace po = boost::program_options;

tsp::Graph graph;
tsp::GeneticSolver solver(graph);
tsp::Config cfg;
tsp::PopulationExchanger *ex = NULL;

static int parseArguments(int argc, char **argv)
{
    po::variables_map vm;
    po::options_description desc("Allowed Options");
    desc.add_options()
    ("help,h", "show help text")
    ("config,c", po::value<std::string>(), "config file")
    ("infile,i", po::value<std::string>(), "graph definition file")
    ("outfile,o", po::value<std::string>(), "path output file")
    ("generations,g", po::value<unsigned int>(),
     "amount of generations to be calculated")
    ("population,p", po::value<unsigned int>(), "population size")
    ("start,s", po::value<unsigned int>(), "start node")
    ("elitism,e", po::value<double>(), "elitism rate")
    ("mutation,m", po::value<double>(), "mutation chance")
    ("fitness,f", po::value<unsigned int>(), "fitness power")
    ("exchange,x", po::value<double>(), "exchange rate")
    ("network,n", "activate MPI network mode")
    ;
    try {
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);
    } catch(std::exception &e) {
        std::cout << e.what() << "\n";
        return 1;
    }

    // check if required options were given
    bool hasConfig = vm.count("config");
    bool hasOpt = vm.count("infile") &&
                  vm.count("outfile") &&
                  vm.count("generations") &&
                  vm.count("population") &&
                  vm.count("start") &&
                  vm.count("elitism") &&
                  vm.count("mutation") &&
                  vm.count("fitness");
    bool hasHelp = vm.count("help");
    if(hasHelp || !(hasConfig || hasOpt)) {
        std::cout << desc << "\n";
        return 1;
    }

    // create network component if we are in network mode
    if(vm.count("network")) {
        std::cout << "Network mode activated.\n";
        ex = new tsp::PopulationExchanger(argc, argv);

        // seed the random number generator with our rank and time
        tsp::Random::shakeRNG(ex->getRank() * std::time(0));

        // if we are not master then return here and
        // receive config through network
        if(!ex->isMaster())
            return 0;
    }

    // load config file if specified
    if(hasConfig) {
        std::cout << "Loading Config from '" << vm["config"].as<std::string>() <<
                  "' ...";
        std::cout.flush();
        if(!tsp::ConfigSerializer::load(cfg, vm["config"].as<std::string>())) {
            std::cout << " Failed\n";
            return 1;
        }
        std::cout << " Done\n";
    }

    // set all config parameters
    if(vm.count("exchange"))
        cfg.exchangeRate = vm["exchange"].as<double>();
    if(vm.count("infile"))
        cfg.graphFile = vm["infile"].as<std::string>();
    if(vm.count("outfile"))
        cfg.pathFile = vm["outfile"].as<std::string>();
    if(vm.count("generations"))
        cfg.generationCount = vm["generations"].as<unsigned int>();
    if(vm.count("population"))
        cfg.gaSettings.populationSize = vm["population"].as<unsigned int>();
    if(vm.count("start"))
        cfg.gaSettings.startNode = vm["start"].as<unsigned int>();
    if(vm.count("elitism"))
        cfg.gaSettings.elitismRate = vm["elitism"].as<double>();
    if(vm.count("mutation"))
        cfg.gaSettings.mutationChance = vm["mutation"].as<double>();
    if(vm.count("fitness"))
        cfg.gaSettings.fitnessPow = vm["fitness"].as<unsigned int>();

    return 0;
}

static void exchangeConfig()
{
    if(ex == NULL)
        return;

    ex->exchangeConfig(cfg);
    ex->setExchangeCount(cfg.exchangeRate * cfg.gaSettings.populationSize);

    return;
}

static void printParameters()
{
    std::cout << "Parameters\n";
    std::cout << "  graph file: " << cfg.graphFile << "\n";
    std::cout << "  path file: " << cfg.pathFile << "\n";
    std::cout << "  generation count: " << cfg.generationCount << "\n";
    std::cout << "  population size: " << cfg.gaSettings.populationSize << "\n";
    std::cout << "  start node: " << cfg.gaSettings.startNode << "\n";
    std::cout << "  elitism rate: " << cfg.gaSettings.elitismRate << "\n";
    std::cout << "  mutation chance: " << cfg.gaSettings.mutationChance << "\n";
    std::cout << "  fitness power: " << cfg.gaSettings.fitnessPow << "\n";
    std::cout << "  exchange rate: " << cfg.exchangeRate << "\n";
}

static int loadGraph()
{
    std::cout << "Loading Graph ...";
    std::cout.flush();
    if(!tsp::GraphSerializer::load(graph, cfg.graphFile)) {
        std::cout << " Failed\n";
        return 1;
    }
    std::cout << " Done\n";

    return 0;
}

static void runAlgorithm()
{
    std::cout << "Initializing solver...";
    std::cout.flush();
    solver.setSettings(cfg.gaSettings);
    solver.init();
    std::cout << " Done\n";

    tsp::GeneticAnalyser analyser(graph);
    for(unsigned int i = 0; i < cfg.generationCount; ++i) {

        std::cout << "Calculating Generation " << i + 1 << "... ";
        std::cout.flush();
        solver.nextGeneration();
        std::cout << " Done\n";

        if(ex != NULL) {
            std::cout << "Exchanging individuals ... ";
            std::cout.flush();
            ex->exchange(solver.getPopulation());
            std::cout << "Done\n";
        }

        std::cout << "Updating fitness ... ";
        std::cout.flush();
        solver.updateFitness();
        std::cout << "Done\n";

        std::cout << "  Best Distance: " << analyser.getBestDistance(
                      solver.getPopulation()) << "\n";
        std::cout << "  Mean Distance: " << analyser.getMeanDistance(
                      solver.getPopulation()) << "\n";
        std::cout << "  Best Fitness: " << analyser.getBestFitness(
                      solver.getPopulation()) << "\n";
        std::cout << "  Mean Fitness: " << analyser.getMeanFitness(
                      solver.getPopulation()) << "\n";
        std::cout << "  Best Norm. Fitness: " << analyser.getBestNormalizedFitness(
                      solver.getPopulation()) << "\n";
    }

    if(ex != NULL) {
        std::cout << "Gathering best individuals ... ";
        std::cout.flush();
        ex->gather(solver.getPopulation());
        solver.updateFitness();
        std::cout << "Done\n";

        if(ex->isMaster()) {
            std::cout << "=============================\n";
            std::cout << "Final Results\n";
            std::cout << "  Best Distance: " <<  analyser.getBestDistance(
                          solver.getPopulation()) << "\n";
        }
    }
}

static int savePath()
{

    if(ex != NULL && !ex->isMaster())
        return 0;

    std::cout << "Saving Path ...";
    std::cout.flush();
    if(!tsp::PathSerializer::save(
                solver.getPopulation().getBestIndividual().getPath(),
                cfg.pathFile)) {
        std::cout << " Failed\n";
        return 1;
    }

    std::cout << " Done\n";

    return 0;
}

int main(int argc, char **argv)
{
    tsp::Random::shakeRNG();

    int ret = parseArguments(argc, argv);
    if(ret)
        return ret;

    exchangeConfig();
    printParameters();

    ret = loadGraph();
    if(ret)
        return ret;

    runAlgorithm();

    ret = savePath();
    if(ret)
        return ret;

    if(ex != NULL)
        delete ex;

    return 0;
}
<commit_msg>Implement quiet mode<commit_after>#include <boost/program_options.hpp>
#include <iostream>
#include "data/GraphSerializer.hpp"
#include "data/PathSerializer.hpp"
#include "data/ConfigSerializer.hpp"
#include "genetic/GeneticSolver.hpp"
#include "genetic/GeneticAnalyser.hpp"
#include "net/PopulationExchanger.hpp"
#include "utils/Random.hpp"

#define LOG_ALWS std::cout << "[ALWS] "
#define LOG_INFO if(!logQuiet) std::cout << "[INFO] "
#define LOG_ERR std::cerr << "[ERROR] "

namespace po = boost::program_options;

tsp::Graph graph;
tsp::GeneticSolver solver(graph);
tsp::Config cfg;
tsp::PopulationExchanger *ex = NULL;
bool logQuiet = false;

static int parseArguments(int argc, char **argv)
{
    po::variables_map vm;
    po::options_description desc("Allowed Options");
    desc.add_options()
    ("help,h", "show help text")
    ("quiet,q", "activate quiet mode")
    ("config,c", po::value<std::string>(), "config file")
    ("infile,i", po::value<std::string>(), "graph definition file")
    ("outfile,o", po::value<std::string>(), "path output file")
    ("generations,g", po::value<unsigned int>(),
     "amount of generations to be calculated")
    ("population,p", po::value<unsigned int>(), "population size")
    ("start,s", po::value<unsigned int>(), "start node")
    ("elitism,e", po::value<double>(), "elitism rate")
    ("mutation,m", po::value<double>(), "mutation chance")
    ("fitness,f", po::value<unsigned int>(), "fitness power")
    ("exchange,x", po::value<double>(), "exchange rate")
    ("network,n", "activate MPI network mode")
    ;
    try {
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);
    } catch(std::exception &e) {
        std::cout << e.what() << "\n";
        return 1;
    }

    // check if required options were given
    bool hasConfig = vm.count("config");
    bool hasOpt = vm.count("infile") &&
                  vm.count("outfile") &&
                  vm.count("generations") &&
                  vm.count("population") &&
                  vm.count("start") &&
                  vm.count("elitism") &&
                  vm.count("mutation") &&
                  vm.count("fitness");
    bool hasHelp = vm.count("help");
    if(hasHelp || !(hasConfig || hasOpt)) {
        std::cout << desc << "\n";
        return 1;
    }

    logQuiet = vm.count("quiet") > 0;

    // create network component if we are in network mode
    if(vm.count("network")) {
        LOG_INFO << "Network mode activated.\n";
        ex = new tsp::PopulationExchanger(argc, argv);

        // seed the random number generator with our rank and time
        tsp::Random::shakeRNG(ex->getRank() * std::time(0));

        // if we are not master then return here and
        // receive config through network
        if(!ex->isMaster())
            return 0;
    }

    // load config file if specified
    if(hasConfig) {
        LOG_INFO << "Loading Config from '" << vm["config"].as<std::string>() <<
                  "' ...\n";
        if(!tsp::ConfigSerializer::load(cfg, vm["config"].as<std::string>())) {
            LOG_ERR << " Failed\n";
            return 1;
        }
    }

    // set all config parameters
    if(vm.count("exchange"))
        cfg.exchangeRate = vm["exchange"].as<double>();
    if(vm.count("infile"))
        cfg.graphFile = vm["infile"].as<std::string>();
    if(vm.count("outfile"))
        cfg.pathFile = vm["outfile"].as<std::string>();
    if(vm.count("generations"))
        cfg.generationCount = vm["generations"].as<unsigned int>();
    if(vm.count("population"))
        cfg.gaSettings.populationSize = vm["population"].as<unsigned int>();
    if(vm.count("start"))
        cfg.gaSettings.startNode = vm["start"].as<unsigned int>();
    if(vm.count("elitism"))
        cfg.gaSettings.elitismRate = vm["elitism"].as<double>();
    if(vm.count("mutation"))
        cfg.gaSettings.mutationChance = vm["mutation"].as<double>();
    if(vm.count("fitness"))
        cfg.gaSettings.fitnessPow = vm["fitness"].as<unsigned int>();

    return 0;
}

static void exchangeConfig()
{
    if(ex == NULL)
        return;

    ex->exchangeConfig(cfg);
    ex->setExchangeCount(cfg.exchangeRate * cfg.gaSettings.populationSize);

    return;
}

static void printParameters()
{
    LOG_INFO << "Parameters\n";
    LOG_INFO << "  graph file: " << cfg.graphFile << "\n";
    LOG_INFO << "  path file: " << cfg.pathFile << "\n";
    LOG_INFO << "  generation count: " << cfg.generationCount << "\n";
    LOG_INFO << "  population size: " << cfg.gaSettings.populationSize << "\n";
    LOG_INFO << "  start node: " << cfg.gaSettings.startNode << "\n";
    LOG_INFO << "  elitism rate: " << cfg.gaSettings.elitismRate << "\n";
    LOG_INFO << "  mutation chance: " << cfg.gaSettings.mutationChance << "\n";
    LOG_INFO << "  fitness power: " << cfg.gaSettings.fitnessPow << "\n";
    LOG_INFO << "  exchange rate: " << cfg.exchangeRate << "\n";
}

static void printCurrentGen(tsp::GeneticAnalyser &analyser)
{
    LOG_INFO << "  Best Distance: " << analyser.getBestDistance(
                  solver.getPopulation()) << "\n";
    LOG_INFO << "  Mean Distance: " << analyser.getMeanDistance(
                  solver.getPopulation()) << "\n";
    LOG_INFO << "  Best Fitness: " << analyser.getBestFitness(
                  solver.getPopulation()) << "\n";
    LOG_INFO << "  Mean Fitness: " << analyser.getMeanFitness(
                  solver.getPopulation()) << "\n";
    LOG_INFO << "  Best Norm. Fitness: " << analyser.getBestNormalizedFitness(
                  solver.getPopulation()) << "\n";
}

static int loadGraph()
{
    LOG_INFO << "Loading Graph ...\n";
    if(!tsp::GraphSerializer::load(graph, cfg.graphFile)) {
        LOG_ERR << " Failed\n";
        return 1;
    }

    return 0;
}

static void runAlgorithm()
{
    if(ex == NULL || ex->isMaster()) {
        LOG_ALWS << "Solving TSP ...\n";
    }

    LOG_INFO << "Initializing solver...";
    solver.setSettings(cfg.gaSettings);
    solver.init();

    tsp::GeneticAnalyser analyser(graph);
    for(unsigned int i = 0; i < cfg.generationCount; ++i) {

        LOG_INFO << "Calculating Generation " << i + 1 << "...\n";
        solver.nextGeneration();

        if(ex != NULL) {
            LOG_INFO << "Exchanging individuals ...\n";
            ex->exchange(solver.getPopulation());
        }

        LOG_INFO << "Updating fitness ...\n";
        solver.updateFitness();

        printCurrentGen(analyser);
    }

    if(ex != NULL) {
        LOG_ALWS << "Gathering best individuals ...\n";
        ex->gather(solver.getPopulation());
        solver.updateFitness();
    }

    if(ex == NULL || ex->isMaster()) {
        LOG_ALWS << "=============================\n";
        LOG_ALWS << "Final Results\n";
        LOG_ALWS << "  Best Distance: " <<  analyser.getBestDistance(
                      solver.getPopulation()) << "\n";
    }
}

static int savePath()
{

    if(ex != NULL && !ex->isMaster())
        return 0;

    LOG_ALWS << "Saving Path ...\n";
    if(!tsp::PathSerializer::save(
                solver.getPopulation().getBestIndividual().getPath(),
                cfg.pathFile)) {
        std::cout << " Failed\n";
        return 1;
    }

    return 0;
}

int main(int argc, char **argv)
{
    tsp::Random::shakeRNG();

    int ret = parseArguments(argc, argv);
    if(ret)
        return ret;

    exchangeConfig();
    printParameters();

    ret = loadGraph();
    if(ret)
        return ret;

    runAlgorithm();

    ret = savePath();
    if(ret)
        return ret;

    if(ex != NULL)
        delete ex;

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file contains unit tests for PEImage.

#include "testing/gtest/include/gtest/gtest.h"
#include "base/pe_image.h"

// Just counts the number of invocations.
bool ExportsCallback(const PEImage &image,
                     DWORD ordinal,
                     DWORD hint,
                     LPCSTR name,
                     PVOID function,
                     LPCSTR forward,
                     PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool ImportsCallback(const PEImage &image,
                     LPCSTR module,
                     DWORD ordinal,
                     LPCSTR name,
                     DWORD hint,
                     PIMAGE_THUNK_DATA iat,
                     PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool SectionsCallback(const PEImage &image,
                       PIMAGE_SECTION_HEADER header,
                       PVOID section_start,
                       DWORD section_size,
                       PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool RelocsCallback(const PEImage &image,
                    WORD type,
                    PVOID address,
                    PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool ImportChunksCallback(const PEImage &image,
                          LPCSTR module,
                          PIMAGE_THUNK_DATA name_table,
                          PIMAGE_THUNK_DATA iat,
                          PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool DelayImportChunksCallback(const PEImage &image,
                               PImgDelayDescr delay_descriptor,
                               LPCSTR module,
                               PIMAGE_THUNK_DATA name_table,
                               PIMAGE_THUNK_DATA iat,
                               PIMAGE_THUNK_DATA bound_iat,
                               PIMAGE_THUNK_DATA unload_iat,
                               PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// We'll be using some known values for the tests.
enum Value {
  sections = 0,
  imports_dlls,
  delay_dlls,
  exports,
  imports,
  delay_imports,
  relocs
};

// Retrieves the expected value from advapi32.dll based on the OS.
int GetExpectedValue(Value value, DWORD os) {
  const int xp_delay_dlls = 2;
  const int xp_exports = 675;
  const int xp_imports = 422;
  const int xp_delay_imports = 8;
  const int xp_relocs = 9180;
  const int vista_delay_dlls = 4;
  const int vista_exports = 799;
  const int vista_imports = 476;
  const int vista_delay_imports = 24;
  const int vista_relocs = 10188;
  const int w2k_delay_dlls = 0;
  const int w2k_exports = 566;
  const int w2k_imports = 357;
  const int w2k_delay_imports = 0;
  const int w2k_relocs = 7388;

  // Contains the expected value, for each enumerated property (Value), and the
  // OS version: [Value][os_version]
  const int expected[][3] = {
    {4, 4, 4},
    {3, 3, 3},
    {w2k_delay_dlls, xp_delay_dlls, vista_delay_dlls},
    {w2k_exports, xp_exports, vista_exports},
    {w2k_imports, xp_imports, vista_imports},
    {w2k_delay_imports, xp_delay_imports, vista_delay_imports},
    {w2k_relocs, xp_relocs, vista_relocs}
  };

  if (value > relocs)
    return 0;
  if (50 == os)
    os = 0;  // 5.0
  else if (51 == os || 52 == os)
    os = 1;
  else if (os >= 60)
    os = 2;  // 6.x
  else
    return 0;

  return expected[value][os];
}

// Tests that we are able to enumerate stuff from a PE file, and that
// the actual number of items found is within the expected range.
TEST(PEImageTest, EnumeratesPE) {
  HMODULE module = LoadLibrary(L"advapi32.dll");
  ASSERT_TRUE(NULL != module);

  PEImage pe(module);
  int count = 0;
  EXPECT_TRUE(pe.VerifyMagic());

  DWORD os = pe.GetNTHeaders()->OptionalHeader.MajorOperatingSystemVersion;
  os = os * 10 + pe.GetNTHeaders()->OptionalHeader.MinorOperatingSystemVersion;

  pe.EnumSections(SectionsCallback, &count);
  EXPECT_EQ(GetExpectedValue(sections, os), count);

  count = 0;
  pe.EnumImportChunks(ImportChunksCallback, &count);
  EXPECT_EQ(GetExpectedValue(imports_dlls, os), count);

  count = 0;
  pe.EnumDelayImportChunks(DelayImportChunksCallback, &count);
  EXPECT_EQ(GetExpectedValue(delay_dlls, os), count);

  count = 0;
  pe.EnumExports(ExportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(exports, os) - 20);
  EXPECT_LT(count, GetExpectedValue(exports, os) + 100);

  count = 0;
  pe.EnumAllImports(ImportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(imports, os) - 20);
  EXPECT_LT(count, GetExpectedValue(imports, os) + 100);

  count = 0;
  pe.EnumAllDelayImports(ImportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(delay_imports, os) - 2);
  EXPECT_LT(count, GetExpectedValue(delay_imports, os) + 8);

  count = 0;
  pe.EnumRelocs(RelocsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(relocs, os) - 150);
  EXPECT_LT(count, GetExpectedValue(relocs, os) + 1500);

  FreeLibrary(module);
}

// Tests that we can locate an specific exported symbol, by name and by ordinal.
TEST(PEImageTest, RetrievesExports) {
  HMODULE module = LoadLibrary(L"advapi32.dll");
  ASSERT_TRUE(NULL != module);

  PEImage pe(module);
  WORD ordinal;

  EXPECT_TRUE(pe.GetProcOrdinal("RegEnumKeyExW", &ordinal));

  FARPROC address1 = pe.GetProcAddress("RegEnumKeyExW");
  FARPROC address2 = pe.GetProcAddress(reinterpret_cast<char*>(ordinal));
  EXPECT_TRUE(address1 != NULL);
  EXPECT_TRUE(address2 != NULL);
  EXPECT_TRUE(address1 == address2);

  FreeLibrary(module);
}

<commit_msg>Silence this unit test on Windows 2003 until bug 2732 is fixed. Review URL: http://codereview.chromium.org/4335<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file contains unit tests for PEImage.

#include "testing/gtest/include/gtest/gtest.h"
#include "base/pe_image.h"
#include "base/win_util.h"

// Just counts the number of invocations.
bool ExportsCallback(const PEImage &image,
                     DWORD ordinal,
                     DWORD hint,
                     LPCSTR name,
                     PVOID function,
                     LPCSTR forward,
                     PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool ImportsCallback(const PEImage &image,
                     LPCSTR module,
                     DWORD ordinal,
                     LPCSTR name,
                     DWORD hint,
                     PIMAGE_THUNK_DATA iat,
                     PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool SectionsCallback(const PEImage &image,
                       PIMAGE_SECTION_HEADER header,
                       PVOID section_start,
                       DWORD section_size,
                       PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool RelocsCallback(const PEImage &image,
                    WORD type,
                    PVOID address,
                    PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool ImportChunksCallback(const PEImage &image,
                          LPCSTR module,
                          PIMAGE_THUNK_DATA name_table,
                          PIMAGE_THUNK_DATA iat,
                          PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool DelayImportChunksCallback(const PEImage &image,
                               PImgDelayDescr delay_descriptor,
                               LPCSTR module,
                               PIMAGE_THUNK_DATA name_table,
                               PIMAGE_THUNK_DATA iat,
                               PIMAGE_THUNK_DATA bound_iat,
                               PIMAGE_THUNK_DATA unload_iat,
                               PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// We'll be using some known values for the tests.
enum Value {
  sections = 0,
  imports_dlls,
  delay_dlls,
  exports,
  imports,
  delay_imports,
  relocs
};

// Retrieves the expected value from advapi32.dll based on the OS.
int GetExpectedValue(Value value, DWORD os) {
  const int xp_delay_dlls = 2;
  const int xp_exports = 675;
  const int xp_imports = 422;
  const int xp_delay_imports = 8;
  const int xp_relocs = 9180;
  const int vista_delay_dlls = 4;
  const int vista_exports = 799;
  const int vista_imports = 476;
  const int vista_delay_imports = 24;
  const int vista_relocs = 10188;
  const int w2k_delay_dlls = 0;
  const int w2k_exports = 566;
  const int w2k_imports = 357;
  const int w2k_delay_imports = 0;
  const int w2k_relocs = 7388;

  // Contains the expected value, for each enumerated property (Value), and the
  // OS version: [Value][os_version]
  const int expected[][3] = {
    {4, 4, 4},
    {3, 3, 3},
    {w2k_delay_dlls, xp_delay_dlls, vista_delay_dlls},
    {w2k_exports, xp_exports, vista_exports},
    {w2k_imports, xp_imports, vista_imports},
    {w2k_delay_imports, xp_delay_imports, vista_delay_imports},
    {w2k_relocs, xp_relocs, vista_relocs}
  };

  if (value > relocs)
    return 0;
  if (50 == os)
    os = 0;  // 5.0
  else if (51 == os || 52 == os)
    os = 1;
  else if (os >= 60)
    os = 2;  // 6.x
  else
    return 0;

  return expected[value][os];
}

// Tests that we are able to enumerate stuff from a PE file, and that
// the actual number of items found is within the expected range.
TEST(PEImageTest, EnumeratesPE) {
  // Windows Server 2003 is not supported as a test environment for this test.
  if (win_util::GetWinVersion() == win_util::WINVERSION_SERVER_2003)
    return;
  HMODULE module = LoadLibrary(L"advapi32.dll");
  ASSERT_TRUE(NULL != module);

  PEImage pe(module);
  int count = 0;
  EXPECT_TRUE(pe.VerifyMagic());

  DWORD os = pe.GetNTHeaders()->OptionalHeader.MajorOperatingSystemVersion;
  os = os * 10 + pe.GetNTHeaders()->OptionalHeader.MinorOperatingSystemVersion;

  pe.EnumSections(SectionsCallback, &count);
  EXPECT_EQ(GetExpectedValue(sections, os), count);

  count = 0;
  pe.EnumImportChunks(ImportChunksCallback, &count);
  EXPECT_EQ(GetExpectedValue(imports_dlls, os), count);

  count = 0;
  pe.EnumDelayImportChunks(DelayImportChunksCallback, &count);
  EXPECT_EQ(GetExpectedValue(delay_dlls, os), count);

  count = 0;
  pe.EnumExports(ExportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(exports, os) - 20);
  EXPECT_LT(count, GetExpectedValue(exports, os) + 100);

  count = 0;
  pe.EnumAllImports(ImportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(imports, os) - 20);
  EXPECT_LT(count, GetExpectedValue(imports, os) + 100);

  count = 0;
  pe.EnumAllDelayImports(ImportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(delay_imports, os) - 2);
  EXPECT_LT(count, GetExpectedValue(delay_imports, os) + 8);

  count = 0;
  pe.EnumRelocs(RelocsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(relocs, os) - 150);
  EXPECT_LT(count, GetExpectedValue(relocs, os) + 1500);

  FreeLibrary(module);
}

// Tests that we can locate an specific exported symbol, by name and by ordinal.
TEST(PEImageTest, RetrievesExports) {
  HMODULE module = LoadLibrary(L"advapi32.dll");
  ASSERT_TRUE(NULL != module);

  PEImage pe(module);
  WORD ordinal;

  EXPECT_TRUE(pe.GetProcOrdinal("RegEnumKeyExW", &ordinal));

  FARPROC address1 = pe.GetProcAddress("RegEnumKeyExW");
  FARPROC address2 = pe.GetProcAddress(reinterpret_cast<char*>(ordinal));
  EXPECT_TRUE(address1 != NULL);
  EXPECT_TRUE(address2 != NULL);
  EXPECT_TRUE(address1 == address2);

  FreeLibrary(module);
}

<|endoftext|>


<commit_before>#ifndef STATICDB_BIT_SINK_HPP
#define STATICDB_BIT_SINK_HPP

#include <silicium/sink/sink.hpp>
#include <staticdb/values.hpp>

namespace staticdb
{
	template <class ByteSink>
	struct bits_to_byte_sink
	{
		typedef values::bit element_type;
		typedef typename ByteSink::error_type error_type;

		bits_to_byte_sink()
		    : m_buffered_bits(0)
		{
		}

		explicit bits_to_byte_sink(ByteSink bytes)
		    : m_bytes(std::move(bytes))
		    , m_buffered_bits(0)
		{
		}

		error_type append(Si::iterator_range<element_type const *> data)
		{
			for (element_type value : data)
			{
				error_type error = append_bit(value);
				if (error)
				{
					return error;
				}
			}
			return error_type();
		}

		std::size_t buffered_bits() const
		{
			return m_buffered_bits;
		}

	private:

		ByteSink m_bytes;
		std::uint8_t m_next_byte;
		std::uint_fast8_t m_buffered_bits;

		enum
		{
			bits_in_byte = 8
		};

		error_type append_bit(values::bit value)
		{
			if (m_buffered_bits == 0)
			{
				m_next_byte = 0;
			}
			m_next_byte |= static_cast<std::uint8_t>((value.is_set ? 1u : 0u) << (7u - m_buffered_bits));
			++m_buffered_bits;
			if (m_buffered_bits != bits_in_byte)
			{
				return error_type();
			}
			error_type error = Si::append(m_bytes, static_cast<typename ByteSink::element_type>(m_next_byte));
			if (!error)
			{
				m_buffered_bits = 0;
			}
			return error;
		}
	};

	template <class ByteSink>
	auto make_bits_to_byte_sink(ByteSink &&bytes)
	{
		return bits_to_byte_sink<typename std::decay<ByteSink>::type>(std::forward<ByteSink>(bytes));
	}
}

#endif
<commit_msg>provide explicit return type<commit_after>#ifndef STATICDB_BIT_SINK_HPP
#define STATICDB_BIT_SINK_HPP

#include <silicium/sink/sink.hpp>
#include <staticdb/values.hpp>

namespace staticdb
{
	template <class ByteSink>
	struct bits_to_byte_sink
	{
		typedef values::bit element_type;
		typedef typename ByteSink::error_type error_type;

		bits_to_byte_sink()
		    : m_buffered_bits(0)
		{
		}

		explicit bits_to_byte_sink(ByteSink bytes)
		    : m_bytes(std::move(bytes))
		    , m_buffered_bits(0)
		{
		}

		error_type append(Si::iterator_range<element_type const *> data)
		{
			for (element_type value : data)
			{
				error_type error = append_bit(value);
				if (error)
				{
					return error;
				}
			}
			return error_type();
		}

		std::size_t buffered_bits() const
		{
			return m_buffered_bits;
		}

	private:

		ByteSink m_bytes;
		std::uint8_t m_next_byte;
		std::uint_fast8_t m_buffered_bits;

		enum
		{
			bits_in_byte = 8
		};

		error_type append_bit(values::bit value)
		{
			if (m_buffered_bits == 0)
			{
				m_next_byte = 0;
			}
			m_next_byte |= static_cast<std::uint8_t>((value.is_set ? 1u : 0u) << (7u - m_buffered_bits));
			++m_buffered_bits;
			if (m_buffered_bits != bits_in_byte)
			{
				return error_type();
			}
			error_type error = Si::append(m_bytes, static_cast<typename ByteSink::element_type>(m_next_byte));
			if (!error)
			{
				m_buffered_bits = 0;
			}
			return error;
		}
	};

	template <class ByteSink>
	auto make_bits_to_byte_sink(ByteSink &&bytes)
		-> bits_to_byte_sink<typename std::decay<ByteSink>::type>
	{
		return bits_to_byte_sink<typename std::decay<ByteSink>::type>(std::forward<ByteSink>(bytes));
	}
}

#endif
<|endoftext|>


<commit_before>/*
 * meego-handset-pin
 * Copyright © 2011, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include "pinapplication.h"

#include "simdialog.h"
#include "simdefines.h"

#include "sim_32x32.xpm"

PinApplication::PinApplication(int &argc, char **argv, int version) :
    QApplication(argc, argv, version)
{
    mSimIf = NULL;
    mSimProperties = NULL;
    mPinTypeRequired = "none";
    mPinRetries = 0;
    setQuitOnLastWindowClosed ( false );
}

PinApplication::~PinApplication()
{
    if (mSimProperties != NULL)
        delete mSimProperties;
    // mSimIf is deleted from main.cpp
}

bool PinApplication::registerPinPropertyChanged(SimIf *simIf)
{
    mSimIf = simIf;
    if (mSimProperties != NULL)
        delete mSimProperties;
    mSimProperties = new SimOfonoProperties(mSimIf);
    // Connect simIf signals
    return connect(mSimIf, SIGNAL(PropertyChanged(QString, QDBusVariant)), this, SLOT(simPropertyChanged(QString, QDBusVariant)));
}

void PinApplication::simPropertyChanged(const QString &property, const QDBusVariant &value)
{
    qDebug() << "simPropertyChanged: " << property << " variant string : " << value.variant().toString();
    if (mSimProperties != NULL)
        delete mSimProperties;
    mSimProperties = new SimOfonoProperties(mSimIf);
    qDebug() << "property : " << property;

    // Getting which 'pin/puk...' code is requested
    if (property == "PinRequired") {
        mPinTypeRequired = value.variant().toString();
    }

    // Getting remaining retries
    if (property == "Retries") {
        QMap<QString, uchar> simRetryProperty;

        simRetryProperty = mSimProperties->getRetryProperties();
        mPinRetries = simRetryProperty[mPinTypeRequired];
        qDebug() << "Retries=" << QString::number((int)mPinRetries);
    }

    // Check error / bad cases
    if (mPinTypeRequired.isNull() || mPinRetries == 0) {
        qDebug() << "Exit!" << " mPinTypeRequired:" << mPinTypeRequired << " mPinRetries:" << mPinRetries;
        return;
    }
    else if (property == "PinRequired" && value.variant().toString() == "none") {
        qDebug() << "Exit!" << " property == 'PinRequired':" << value.variant().toString();
        return;
    }

    // Displaying 'pin/puk...' code dialog and send response to modem
    QDBusPendingReply<> enterPinCall;
    QString text;
    if (mPinRetries > 1)
        text = " remaining tries left";
    else
        text = " remaining try left";
    SimDialog dlg(mPinTypeRequired + " code required!\n" + QString::number((int)mPinRetries) + text, "qrc:/SimPassword.qml");

    dlg.setHideTyping(true);
    dlg.initView();
    dlg.exec();

    AgentResponse ret = dlg.getAgentResponse();
    switch (ret) {
    case Ok:
        qDebug() << "EnterPin: " << mPinTypeRequired << " : " << dlg.getResponseData().toString();
        enterPinCall = mSimIf->EnterPin(mPinTypeRequired, dlg.getResponseData().toString());
        enterPinCall.waitForFinished();
        if (enterPinCall.isError()) {
            QDBusError dbusError = enterPinCall.error();
            qDebug() << "Bad Pin Code!";
        }
        break;
    case Cancel:
        break;
    default:
        Q_ASSERT(false);
    }
}
<commit_msg>meego-handset-pin: Bug fix (multiple Pin code dialog)<commit_after>/*
 * meego-handset-pin
 * Copyright © 2011, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include "pinapplication.h"

#include "simdialog.h"
#include "simdefines.h"

#include "sim_32x32.xpm"

PinApplication::PinApplication(int &argc, char **argv, int version) :
    QApplication(argc, argv, version)
{
    mSimIf = NULL;
    mSimProperties = NULL;
    mPinTypeRequired = "none";
    mPinRetries = 0;
    setQuitOnLastWindowClosed ( false );
}

PinApplication::~PinApplication()
{
    if (mSimProperties != NULL)
        delete mSimProperties;
    // mSimIf is deleted from main.cpp
}

bool PinApplication::registerPinPropertyChanged(SimIf *simIf)
{
    mSimIf = simIf;
    if (mSimProperties != NULL)
        delete mSimProperties;
    mSimProperties = new SimOfonoProperties(mSimIf);
    // Connect simIf signals
    return connect(mSimIf, SIGNAL(PropertyChanged(QString, QDBusVariant)), this, SLOT(simPropertyChanged(QString, QDBusVariant)));
}

void PinApplication::simPropertyChanged(const QString &property, const QDBusVariant &value)
{
    qDebug() << "simPropertyChanged: " << property << " variant string : " << value.variant().toString();
    if (mSimProperties != NULL)
        delete mSimProperties;
    mSimProperties = new SimOfonoProperties(mSimIf);

    // Getting which 'pin/puk...' code is requested
    if (property == "PinRequired") {
        mPinTypeRequired = value.variant().toString();
    }

    // Getting remaining retries
    if (property == "Retries") {
        QMap<QString, uchar> simRetryProperty;

        simRetryProperty = mSimProperties->getRetryProperties();
        mPinRetries = simRetryProperty[mPinTypeRequired];
		qDebug() << "simPropertyChanged: Retries=" << QString::number((int)mPinRetries);
    }

    // Check error / bad cases
    if (mPinTypeRequired.isNull() || mPinRetries == 0) {
		qDebug() << "simPropertyChanged: Exit!" << " mPinTypeRequired:" << mPinTypeRequired << " mPinRetries:" << mPinRetries;
        return;
    }
	else if (property == "PinRequired" && value.variant().toString() == "none") {
		qDebug() << "simPropertyChanged: Exit!" << " property == 'PinRequired':" << value.variant().toString();
		return;
	}
	if (property != "PinRequired" && property != "Retries") {
		qDebug() << "simPropertyChanged: Exit!" << " property (" << property << ") is not 'PinRequired' nor Retries";
		return;
	}

    // Displaying 'pin/puk...' code dialog and send response to modem
    QDBusPendingReply<> enterPinCall;
    QString text;
    if (mPinRetries > 1)
        text = " remaining tries left";
    else
        text = " remaining try left";
    SimDialog dlg(mPinTypeRequired + " code required!\n" + QString::number((int)mPinRetries) + text, "qrc:/SimPassword.qml");

    dlg.setHideTyping(true);
    dlg.initView();
    dlg.exec();

    AgentResponse ret = dlg.getAgentResponse();
    switch (ret) {
    case Ok:
        qDebug() << "EnterPin: " << mPinTypeRequired << " : " << dlg.getResponseData().toString();
        enterPinCall = mSimIf->EnterPin(mPinTypeRequired, dlg.getResponseData().toString());
        enterPinCall.waitForFinished();
        if (enterPinCall.isError()) {
            QDBusError dbusError = enterPinCall.error();
			qDebug() << "simPropertyChanged: Bad Pin Code!";
        }
        break;
    case Cancel:
        break;
    default:
        Q_ASSERT(false);
    }
}
<|endoftext|>


<commit_before>// SDL-based graphical plotter application that plots an expression.
// William Immendorf - 2016

#include <iostream>
#include <string>
#include <vector>

#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>

#include "color.hpp"
#include "varequation.hpp"

const int screen_width = 800;
const int screen_height = 600;

const int x_scale = 20;
const int y_scale = 20;

SDL_Window* window = nullptr;
SDL_GLContext gl_context;

// Initialize SDL
bool init();

// Initalize GL subsystem
bool initGL();

// Initalize renderer (required before running other functions)
void renderInit();

// Render grid to screen
void renderGrid();

// Render line, given a VariableEquation
void renderLine(EquParser::VariableEquation & equation);

// Close SDL and free memory
void close();

bool init()
{
	bool success = true;

	// Attempt to initialize SDL, log error on failure
	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		// Oops, something happened with SDL
		std::cerr << "Cannot initalize SDL. Reason: " << SDL_GetError() << std::endl;
		success = false;
	}
	else
	{
		// Use OpenGL 2.1
		SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 2 );
		SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );

		// We've made it this far, so let's create the main window
		window = SDL_CreateWindow("Graphic Plotter", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screen_width, screen_height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
		if (window == nullptr)
		{
			// No window, so log the reason why and get out of here
			std::cerr << "Cannot create window. Reason: " << SDL_GetError() << std::endl;
			success = false;
		}
		else
		{
			// Now create the OpenGL context
			gl_context = SDL_GL_CreateContext(window);
			if (gl_context == nullptr)
			{
				std::cerr << "Unable to initalize OpenGL context! Reason: " << SDL_GetError() << std::endl;
				success = false;
			}
			else
			{
				// Enable Vsync
				if (SDL_GL_SetSwapInterval(1) < 0)
				{
					std::clog << "Warning: Vsync not enabled. Reason: " << SDL_GetError() << std::endl;
				}

				// Now actually initialize GL
				if (!initGL())
				{
					success = false;
				}
			}
		}
	}
	return success;
}

bool initGL()
{
	// Set up orthographic projection
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0.0, screen_width, 0.0, screen_height, 1.0, -1.0);

	// Set up modelview matrix
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	// Set clear color to pure white
	glClearColor(1.f, 1.f, 1.f, 1.f);

	// Check for any errors
	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
	{
		std::cerr << "Cannot initalize OpenGL!" << std::endl;
		return false;
	}

	return true;
}

void renderInit()
{
	glClear(GL_COLOR_BUFFER_BIT);

	// Reset and select modelview matrix
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	// Move created objects to center of screen
	glTranslatef(screen_width / 2.f, screen_height / 2.f, 0.f);
}

void renderGrid()
{
	// Set drawing color
	glColor3f(0.f, 0.f, 0.f);

	// Render origin lines
	glLineWidth(4);
	glBegin(GL_LINES);
		glVertex2f(0, -(screen_height / 2.f));
		glVertex2f(0, (screen_height / 2.f));
		glVertex2f(-(screen_width / 2.f), 0);
		glVertex2f((screen_width / 2.f), 0);
	glEnd();

	// Render guide points
	glPointSize(3);
	int y_start = -(screen_height / 2) + (screen_height / y_scale);
	int x_start = -(screen_width / 2) + (screen_width / x_scale);
	glBegin(GL_POINTS);
		for (int y = y_start; y < (screen_height / 2); y += (screen_height / y_scale))
		{
			for (int x = x_start; x < (screen_width / 2); x += (screen_width / x_scale))
				glVertex2f(x, y);
		}
	glEnd();
}

void renderLine(EquParser::VariableEquation & equation, const EquParser::Color color)
{
	// Set drawing color
	glColor3f(color.red, color.green, color.blue);

	int pixels_to_x = (screen_width / x_scale);

	glLineWidth(2);
	glBegin(GL_LINE_STRIP);
		for (int x = -(x_scale / 2); x <= (x_scale / 2); ++x)
		{
			for (int offset = x * pixels_to_x; offset < (pixels_to_x * (x + 2)); ++offset)
			{
				double x_difference = offset / (double) pixels_to_x;
				equation.x(x + x_difference);
				glVertex2d((x * pixels_to_x) + offset, equation.evaluate() * (screen_height / (double) y_scale));
			}
		}
	glEnd();
}

void close()
{
	SDL_DestroyWindow(window);
	window = nullptr;

	SDL_Quit();
}

int main(int argc, char* argv[])
{
	using std::cout;
	using std::cin;
	using std::endl;
	using EquParser::VariableEquation;

	unsigned int equation_count = 0;
	bool input_valid = false;
	cout << "Enter how many equations to plot: ";
	while (!input_valid)
	{
		cin >> equation_count;
		if (!cin) // invalid input
		{
			cin.clear();
			cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
			cout << "Invalid input. Enter how many equations to plot: ";
		}
		else
		{
			input_valid = true;
		}
	}

	cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	std::string expression;

	struct ColorVarEq { VariableEquation equation; EquParser::Color color; };
	std::vector<ColorVarEq> equation_vector;
	for (int i = 0; i < equation_count; ++i)
	{
		cout << "Enter an expression: ";
		getline(cin, expression);
		VariableEquation equation(expression);
		cout << "Avaliable colors:" << endl;
		for (int j = 0; j < sizeof(EquParser::Colors) / sizeof(*EquParser::Colors); j++)
			cout << EquParser::Colors[j].name << " (" << j << ")" << endl;
		cout << "Select a color: ";
		int color_select;
		cin >> color_select; // TODO: Error correcting
	  cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
		equation_vector.push_back({equation, EquParser::Colors[color_select]});
		cout << equation << endl;
	}

	if (init())
	{
	  std::cout << "Plotting graphical equation, hit ESC or close window to continue" << std::endl;
		bool quit = false;

		SDL_Event e;

		while (!quit)
		{
			while (SDL_PollEvent(&e) != 0)
			{
				if (e.type == SDL_QUIT)
					quit = true;
				else if (e.type == SDL_KEYDOWN)
				{
					if (e.key.keysym.sym == SDLK_ESCAPE)
						quit = true;
				}
			}
			renderInit();
			renderGrid();
			for (ColorVarEq equation_color : equation_vector)
				renderLine(equation_color.equation, equation_color.color);
			SDL_GL_SwapWindow(window);
		}
	}

	close();
}
<commit_msg>Add error checking for color selecting<commit_after>// SDL-based graphical plotter application that plots an expression.
// William Immendorf - 2016

#include <iostream>
#include <string>
#include <vector>

#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>

#include "color.hpp"
#include "varequation.hpp"

const int screen_width = 800;
const int screen_height = 600;

const int x_scale = 20;
const int y_scale = 20;

SDL_Window* window = nullptr;
SDL_GLContext gl_context;

// Initialize SDL
bool init();

// Initalize GL subsystem
bool initGL();

// Initalize renderer (required before running other functions)
void renderInit();

// Render grid to screen
void renderGrid();

// Render line, given a VariableEquation
void renderLine(EquParser::VariableEquation & equation);

// Close SDL and free memory
void close();

bool init()
{
	bool success = true;

	// Attempt to initialize SDL, log error on failure
	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		// Oops, something happened with SDL
		std::cerr << "Cannot initalize SDL. Reason: " << SDL_GetError() << std::endl;
		success = false;
	}
	else
	{
		// Use OpenGL 2.1
		SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 2 );
		SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );

		// We've made it this far, so let's create the main window
		window = SDL_CreateWindow("Graphic Plotter", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screen_width, screen_height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
		if (window == nullptr)
		{
			// No window, so log the reason why and get out of here
			std::cerr << "Cannot create window. Reason: " << SDL_GetError() << std::endl;
			success = false;
		}
		else
		{
			// Now create the OpenGL context
			gl_context = SDL_GL_CreateContext(window);
			if (gl_context == nullptr)
			{
				std::cerr << "Unable to initalize OpenGL context! Reason: " << SDL_GetError() << std::endl;
				success = false;
			}
			else
			{
				// Enable Vsync
				if (SDL_GL_SetSwapInterval(1) < 0)
				{
					std::clog << "Warning: Vsync not enabled. Reason: " << SDL_GetError() << std::endl;
				}

				// Now actually initialize GL
				if (!initGL())
				{
					success = false;
				}
			}
		}
	}
	return success;
}

bool initGL()
{
	// Set up orthographic projection
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0.0, screen_width, 0.0, screen_height, 1.0, -1.0);

	// Set up modelview matrix
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	// Set clear color to pure white
	glClearColor(1.f, 1.f, 1.f, 1.f);

	// Check for any errors
	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
	{
		std::cerr << "Cannot initalize OpenGL!" << std::endl;
		return false;
	}

	return true;
}

void renderInit()
{
	glClear(GL_COLOR_BUFFER_BIT);

	// Reset and select modelview matrix
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	// Move created objects to center of screen
	glTranslatef(screen_width / 2.f, screen_height / 2.f, 0.f);
}

void renderGrid()
{
	// Set drawing color
	glColor3f(0.f, 0.f, 0.f);

	// Render origin lines
	glLineWidth(4);
	glBegin(GL_LINES);
		glVertex2f(0, -(screen_height / 2.f));
		glVertex2f(0, (screen_height / 2.f));
		glVertex2f(-(screen_width / 2.f), 0);
		glVertex2f((screen_width / 2.f), 0);
	glEnd();

	// Render guide points
	glPointSize(3);
	int y_start = -(screen_height / 2) + (screen_height / y_scale);
	int x_start = -(screen_width / 2) + (screen_width / x_scale);
	glBegin(GL_POINTS);
		for (int y = y_start; y < (screen_height / 2); y += (screen_height / y_scale))
		{
			for (int x = x_start; x < (screen_width / 2); x += (screen_width / x_scale))
				glVertex2f(x, y);
		}
	glEnd();
}

void renderLine(EquParser::VariableEquation & equation, const EquParser::Color color)
{
	// Set drawing color
	glColor3f(color.red, color.green, color.blue);

	int pixels_to_x = (screen_width / x_scale);

	glLineWidth(2);
	glBegin(GL_LINE_STRIP);
		for (int x = -(x_scale / 2); x <= (x_scale / 2); ++x)
		{
			for (int offset = x * pixels_to_x; offset < (pixels_to_x * (x + 2)); ++offset)
			{
				double x_difference = offset / (double) pixels_to_x;
				equation.x(x + x_difference);
				glVertex2d((x * pixels_to_x) + offset, equation.evaluate() * (screen_height / (double) y_scale));
			}
		}
	glEnd();
}

void close()
{
	SDL_DestroyWindow(window);
	window = nullptr;

	SDL_Quit();
}

int main(int argc, char* argv[])
{
	using std::cout;
	using std::cin;
	using std::endl;
	using EquParser::VariableEquation;

	unsigned int equation_count = 0;
	bool input_valid = false;
	cout << "Enter how many equations to plot: ";
	while (!input_valid)
	{
		cin >> equation_count;
		if (!cin) // invalid input
		{
			cin.clear();
			cout << "Invalid input. Enter how many equations to plot: ";
		}
		else
		{
			input_valid = true;
		}
		cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}
	std::string expression;

	struct ColorVarEq { VariableEquation equation; EquParser::Color color; };
	std::vector<ColorVarEq> equation_vector;
	for (int i = 0; i < equation_count; ++i)
	{
		cout << "Enter an expression: ";
		getline(cin, expression);
		VariableEquation equation(expression);
		cout << "Avaliable colors:" << endl;
		for (int j = 0; j < sizeof(EquParser::Colors) / sizeof(*EquParser::Colors); j++)
			cout << EquParser::Colors[j].name << " (" << j << ")" << endl;
		bool color_selected = false;
		cout << "Select a color: ";
		while (!color_selected)
		{
			int color_select;
			cin >> color_select;
			if (color_select > ((sizeof(EquParser::Colors) / sizeof(*EquParser::Colors)) - 1) || color_select < 0 || !cin)
			{
				cin.clear();
				cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
				cout << "Invalid response, select a color: ";
			}
			else
			{
				equation_vector.push_back({equation, EquParser::Colors[color_select]});
				color_selected = true;
			}
		}
		cout << equation << endl;
		cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}

	if (init())
	{
	  std::cout << "Plotting graphical equation, hit ESC or close window to continue" << std::endl;
		bool quit = false;

		SDL_Event e;

		while (!quit)
		{
			while (SDL_PollEvent(&e) != 0)
			{
				if (e.type == SDL_QUIT)
					quit = true;
				else if (e.type == SDL_KEYDOWN)
				{
					if (e.key.keysym.sym == SDLK_ESCAPE)
						quit = true;
				}
			}
			renderInit();
			renderGrid();
			for (ColorVarEq equation_color : equation_vector)
				renderLine(equation_color.equation, equation_color.color);
			SDL_GL_SwapWindow(window);
		}
	}

	close();
}
<|endoftext|>


<commit_before>#include <QApplication>
#include <QSettings>
#include <QIcon>

#include <QDebug>

#include "appcontroller.h"
#include "appwindow.h"
#include "secondarywindow.h"
#include "widgets/librarywidget.h"
#include "widgets/secondary/loginwidget.h"
#include "widgets/secondary/settingswidget.h"

AppController::AppController(QObject* parent)
    : QObject(parent)
    , settingsWindow(NULL)
    , loginWithApiKey(false)
{
    setupSettings();
    api = new ItchioApi(this, settings->apiUrl());

    setupTrayIcon();
    setupAppWindow();

    if (settings->autoLogin() && settings->hasValidApiKey()) {
        api->loginWithApiKey(settings->apiKey(), [this](bool success, QString err) {
            if (success) {
                onLogin();
            } else {
                onAutoLoginFailure(err);
            }
        });

        loginWithApiKey = true;
    } else {
        setupLogin();
    }
}

void AppController::setupSettings()
{
    settingsFile = "itchio.ini";
    settings = new AppSettings(settingsFile, QSettings::IniFormat, this);
}

void AppController::quit()
{
    settings->enableStartMaximized(appWindow->isMaximized);
    settings->setWindowGeometry(appWindow->saveGeometry());
    settings->setWindowOldSize(appWindow->oldSize);
    settings->setWindowOldPosition(appWindow->oldPosition);

    if (settings->autoLogin()) {
        settings->setApiKey(api->userKey);
        settings->setUsername(api->userName);
    }

    QCoreApplication::exit();
}

void AppController::showSettings()
{
    settingsWindow = new SecondaryWindow(new SettingsWidget(this), this);

    settingsWindow->show();
    settingsWindow->raise();
}

void AppController::trayIconDoubleClick(QSystemTrayIcon::ActivationReason reason)
{
    if (reason == QSystemTrayIcon::DoubleClick && !appWindow->isVisible()) {
        appWindow->showWindow();
    }
}

void AppController::setupTrayIcon()
{
    trayIcon = new QSystemTrayIcon(this);

    trayIcon->setIcon(QIcon(":/images/images/itchio-icon-16.png"));
    trayIcon->show();
}

void AppController::setupTrayIconMenu(bool beforeLogin)
{
    trayIconMenu = new QMenu();
    trayIcon->setContextMenu(trayIconMenu);

    if (!beforeLogin) {
        QAction* actionSettings = new QAction("Settings", this);
        trayIconMenu->addAction(actionSettings);
        connect(actionSettings, SIGNAL(triggered()), this, SLOT(showSettings()));

        trayIconMenu->addSeparator();
    }

    QAction* actionQuit = new QAction("Quit", this);
    trayIconMenu->addAction(actionQuit);
    connect(actionQuit, SIGNAL(triggered()), this, SLOT(quit()));

    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(trayIconDoubleClick(QSystemTrayIcon::ActivationReason)));
}

void AppController::showTrayIconNotification(TrayNotifications::Notifications notification, QString data)
{
    if (settings->showTrayNotifications()) {
        if((notification == TrayNotifications::LIBRARY_UPDATE &&
            settings->showLibraryUpdateNotifications()) ||
                (notification == TrayNotifications::DOWNLOAD_FINISHED &&
                 settings->showDownloadFinishedNotifications()) ||
                (notification == TrayNotifications::GAME_UPDATE_AVAILABLE &&
                 settings->showGameUpdateAvailableNotifications())){

            trayIcon->showMessage(TrayNotifications::toString(notification),
                                  data, QSystemTrayIcon::NoIcon, 5000);
        }

    }
}

void AppController::setupLogin()
{
    settings->setApiKey("");
    api->userKey = "";

    setupTrayIconMenu(true);

    loginWindow = new SecondaryWindow(new LoginWidget(qobject_cast<QWidget*>(this), this), this);
    loginWindow->show();
}

void AppController::setupAppWindow()
{
    appWindow = new AppWindow(this);
}

void AppController::onLogin()
{
    setupTrayIconMenu();

    if (!loginWithApiKey) {
        loginWindow->deleteLater();
        loginWindow->close();
    }

    appWindow->setupLibrary();
}

void AppController::onAutoLoginFailure(QString)
{
    setupLogin();
}
<commit_msg>Settings moved to app directory,.<commit_after>#include <QApplication>
#include <QSettings>
#include <QIcon>

#include <QDebug>

#include "appcontroller.h"
#include "appwindow.h"
#include "secondarywindow.h"
#include "widgets/librarywidget.h"
#include "widgets/secondary/loginwidget.h"
#include "widgets/secondary/settingswidget.h"

AppController::AppController(QObject* parent)
    : QObject(parent)
    , settingsWindow(NULL)
    , loginWithApiKey(false)
{
    setupSettings();
    api = new ItchioApi(this, settings->apiUrl());

    setupTrayIcon();
    setupAppWindow();

    if (settings->autoLogin() && settings->hasValidApiKey()) {
        api->loginWithApiKey(settings->apiKey(), [this](bool success, QString err) {
            if (success) {
                onLogin();
            } else {
                onAutoLoginFailure(err);
            }
        });

        loginWithApiKey = true;
    } else {
        setupLogin();
    }
}

void AppController::setupSettings()
{
    settingsFile = QCoreApplication::applicationDirPath() + "/itchio.ini";
    settings = new AppSettings(settingsFile, QSettings::IniFormat, this);
}

void AppController::quit()
{
    settings->enableStartMaximized(appWindow->isMaximized);
    settings->setWindowGeometry(appWindow->saveGeometry());
    settings->setWindowOldSize(appWindow->oldSize);
    settings->setWindowOldPosition(appWindow->oldPosition);

    if (settings->autoLogin()) {
        settings->setApiKey(api->userKey);
        settings->setUsername(api->userName);
    }

    QCoreApplication::exit();
}

void AppController::showSettings()
{
    settingsWindow = new SecondaryWindow(new SettingsWidget(this), this);

    settingsWindow->show();
    settingsWindow->raise();
}

void AppController::trayIconDoubleClick(QSystemTrayIcon::ActivationReason reason)
{
    if (reason == QSystemTrayIcon::DoubleClick && !appWindow->isVisible()) {
        appWindow->showWindow();
    }
}

void AppController::setupTrayIcon()
{
    trayIcon = new QSystemTrayIcon(this);

    trayIcon->setIcon(QIcon(":/images/images/itchio-icon-16.png"));
    trayIcon->show();
}

void AppController::setupTrayIconMenu(bool beforeLogin)
{
    trayIconMenu = new QMenu();
    trayIcon->setContextMenu(trayIconMenu);

    if (!beforeLogin) {
        QAction* actionSettings = new QAction("Settings", this);
        trayIconMenu->addAction(actionSettings);
        connect(actionSettings, SIGNAL(triggered()), this, SLOT(showSettings()));

        trayIconMenu->addSeparator();
    }

    QAction* actionQuit = new QAction("Quit", this);
    trayIconMenu->addAction(actionQuit);
    connect(actionQuit, SIGNAL(triggered()), this, SLOT(quit()));

    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(trayIconDoubleClick(QSystemTrayIcon::ActivationReason)));
}

void AppController::showTrayIconNotification(TrayNotifications::Notifications notification, QString data)
{
    if (settings->showTrayNotifications()) {
        if((notification == TrayNotifications::LIBRARY_UPDATE &&
            settings->showLibraryUpdateNotifications()) ||
                (notification == TrayNotifications::DOWNLOAD_FINISHED &&
                 settings->showDownloadFinishedNotifications()) ||
                (notification == TrayNotifications::GAME_UPDATE_AVAILABLE &&
                 settings->showGameUpdateAvailableNotifications())){

            trayIcon->showMessage(TrayNotifications::toString(notification),
                                  data, QSystemTrayIcon::NoIcon, 5000);
        }

    }
}

void AppController::setupLogin()
{
    settings->setApiKey("");
    api->userKey = "";

    setupTrayIconMenu(true);

    loginWindow = new SecondaryWindow(new LoginWidget(qobject_cast<QWidget*>(this), this), this);
    loginWindow->show();
}

void AppController::setupAppWindow()
{
    appWindow = new AppWindow(this);
}

void AppController::onLogin()
{
    setupTrayIconMenu();

    if (!loginWithApiKey) {
        loginWindow->deleteLater();
        loginWindow->close();
    }

    appWindow->setupLibrary();
}

void AppController::onAutoLoginFailure(QString)
{
    setupLogin();
}
<|endoftext|>