<commit_before>#include "qca.hpp"
#include "utilities.hpp"
#include <map>

/*
 * TODO
 * ----
 *
 * * P-P for three plaquets (bond system)
 * * P-P with dead cell (bond and qf)
 * * energies with dead cell? -- shouldn't make much difference
 * * grand canonical
 *    * number of electrons per cell for different a and b
 *    * number of electrons, considering Vext or dead cell
 *    * P-P
 * * compare energy, P-P for bond, qf, gc
 *
 *
 *
 * Output for the following command does not look correct to me:
 * ./runQca -m bondDP -p 1 -P 0 -Pext 0,1,2,3 -a 1,2 -E
 */

class EpsilonLess
{
public:
    EpsilonLess (double e_ = 1E-10)
    : e(e_)
    {}

    bool operator() (double a, double b)
    {
        return b-a > e;
    }
private:
    double e;
};

CommandLineOptions setupCLOptions ()
{
    CommandLineOptions o;
    o.add("help", "h", "Print this help message.")
     .add("model", "m", "Which QCA model to use. Options are: bond, bondDP, quarter, quarterDP, grand, grandDP.")
     .add("", "p", "Number of plaquets.")
     .add("", "t", "Hopping parameter.")
     .add("", "td", "Diagonal hopping parameter.")
     .add("", "ti", "Inter-plaquet hopping parameter.")
     .add("", "V0", "On-site coulomb repulsion (Hubbard U).")
     .add("", "mu", "Chemical potential.")
     .add("", "Vext", "External potential.")
     .add("", "Pext", "External, 'driving' polarisation of a 'dead plaquet' to the left of the linear chain system.")
     .add("", "a", "Intra-plaquet spacing.")
     .add("", "b", "Inter-plaquet spacing.")
     .add("", "beta", "Inverse temperature.")
     .add("energy-spectrum", "E", "Calculate the energy spectrum.")
     .add("polarisation", "P", "Calculate the polarisation for specified plaquet(s).")
     .add("particle-number", "N", "Calculate the particle number for the specified plaquet or the total particle number.");

    o["p"].setDefault(1);
    o["t"].setDefault(1);
    o["td"].setDefault(0);
    o["ti"].setDefault(0);
    o["V0"].setDefault(0);
    o["mu"].setDefault(0);
    o["Vext"].setDefault(0);
    o["Pext"].setDefault(0);
    o["a"].setDefault(1);
    o["b"].setDefault(1.75);
    o["beta"].setDefault(1);

    return o;
}

void printUsage (CommandLineOptions& o)
{
    std::cerr << "Usage: " << std::endl;
    std::cerr << o.usage();
}

enum OutputMode {Header, Line, None};

template<class System>
class Measurement
{
public:
    Measurement (OptionSection o_)
    : o(o_), s(o_), needHeader(true), globalFirst(true)
    {
        for (OptionSection::OptionsType::iterator i=o.getOptions().begin(); i!=o.getOptions().end(); i++)
            outputConfig[i->getName()] = Header;
        outputConfig["energy-spectrum"] = None;
        outputConfig["polarisation"] = None;
        outputConfig["particle-number"] = None;
        outputConfig["help"] = None;
    }

    void setParam (const std::string& param, const OptionValue& value)
    {
        o[param] = value;
        if (outputConfig[param] == Header)
            needHeader = true;
    }

    void measure (const std::string& param, const OptionValue& value)
    {
        setParam(param, value);
        measure();
    }

    void measure ()
    {
        s.setParameters(o);
        s.update();

        if (o["energy-spectrum"].isSet())
            measureEnergies();
        if (o["polarisation"].isSet())
            measurePolarisation();
        if (o["particle-number"].isSet())
            measureParticleNumber();

        store();
    }

    void measureEnergies ()
    {
        E.resize(0);
        typedef std::map<double, int, EpsilonLess> myMap;
        typedef myMap::const_iterator mapIt;
        myMap evs;
        for (int i=0; i<s.energies().size(); i++)
            evs[s.energies()(i)]++;
        for (mapIt i=evs.begin(); i!=evs.end(); i++)
        {
            std::vector<double> v(3);
            v[0] = i->first;
            v[1] = i->first - s.Emin();
            v[2] = i->second;
            E.push_back(v);
        }
    }

    void measurePolarisation ()
    {
        P.resize(0);
        std::vector<size_t> ps = o["polarisation"];
        for (size_t i=0; i<ps.size(); i++)
        {
            if (ps[i] >= s.N_p)
            {
                std::cerr << std::endl << "Polarisation: There is no plaquet "
                    << ps[i] << " in this system." << std::endl;
                std::exit(EXIT_FAILURE);
            }
            P.push_back(s.measure(o["beta"], s.P(ps[i])));
        }
    }

    void measureParticleNumber ()
    {
        //TODO o["particle-number"].isSize_t() or isBool() would be uselful
        size_t p;
        try
        {
            p = o["particle-number"];
            if (p >= s.N_p)
            {
                std::cerr << std::endl << "Particle number: There is no plaquet "
                    << p << " in this system." << std::endl;
                std::exit(EXIT_FAILURE);
            }
            N = s.measure(o["beta"], s.N(p));
        }
        catch (ConversionException e)
        {
            N = s.ensembleAverage(o["beta"], s.N());
        }
    }

    void store ()
    {
        // always print energy spectrum as a separate block
        if (o["energy-spectrum"].isSet())
        {
            printHeaderAll();
            std::cout << "# " << std::endl << "# E\tE-Emin\tDegeneracy" << std::endl;
            for (size_t i=0; i<E.size(); i++)
                std::cout << E[i][0] << "\t" << E[i][1] << "\t" << E[i][2] << std::endl;
            std::cout << std::endl;
        }

        if (o["polarisation"].isSet() || o["particle-number"].isSet())
        {
            if (needHeader)
            {
                printHeader();

                std::cout << "# " << std::endl << "# ";
                bool first = true;
                for (typename OutputMap::const_iterator i=outputConfig.begin(); i!=outputConfig.end(); i++)
                    if (i->second == Line)
                    {
                        if (!first) std::cout << "\t";
                        else first = false;
                        std::cout << i->first;
                    }
                if (o["polarisation"].isSet())
                {
                    std::vector<size_t> ps = o["polarisation"];
                    for (size_t i=0; i<ps.size(); i++)
                    {
                        if (!first) std::cout << "\t";
                        else first = false;
                        std::cout << "P" << ps[i];
                    }
                }
                if (o["particle-number"].isSet())
                {
                    if (!first) std::cout << "\t";
                    else first = false;

                    try
                    {
                        size_t p;
                        p = o["particle-number"];
                        std::cout << "N" << p;
                    }
                    catch (ConversionException e)
                    {
                        std::cout << "N";
                    }
                }
                std::cout << std::endl;

                needHeader = false;
            }

            bool first = true;
            for (typename OutputMap::const_iterator i=outputConfig.begin(); i!=outputConfig.end(); i++)
                if (i->second == Line)
                {
                    if (!first) std::cout << "\t";
                    else first = false;
                    std::cout << o[i->first];
                }
            if (o["polarisation"].isSet())
                for (size_t j=0; j<P.size(); j++)
                {
                    if (!first) std::cout << "\t";
                    else first = false;
                    std::cout << P[j];
                }
            if (o["particle-number"].isSet())
            {
                if (!first) std::cout << "\t";
                else first = false;
                std::cout << N;
            }
            std::cout << std::endl;
        }
    }

    void printHeader ()
    {
        if (!globalFirst) std::cout << std::endl;
        else globalFirst = false;
        for (OptionSection::OptionsType::iterator i=o.getOptions().begin(); i!=o.getOptions().end(); i++)
            if (outputConfig[i->getName()] == Header)
                std::cout << "# " << i->getName() << " = " << i->getValue() << std::endl;
    }

    void printHeaderAll ()
    {
        if (!globalFirst) std::cout << std::endl;
        else globalFirst = false;
        for (OptionSection::OptionsType::iterator i=o.getOptions().begin(); i!=o.getOptions().end(); i++)
            if (outputConfig[i->getName()] != None)
                std::cout << "# " << i->getName() << " = " << i->getValue() << std::endl;
    }

    void setOutputMode (std::string param, OutputMode mode)
    {
        outputConfig[param] = mode;
    }

private:
    OptionSection o;
    System s;

    std::vector<std::vector<double> > E;
    std::vector<double> P;
    double N;

    bool needHeader, globalFirst;
    typedef std::map<std::string, OutputMode> OutputMap;
    OutputMap outputConfig;
    std::vector<std::string> changed;
};

bool comparePair (const std::pair<std::string, size_t>& p1,
                  const std::pair<std::string, size_t>& p2)
{
    return p1.second < p2.second;
}

template<class Measurement>
void runMeasurement (Measurement& M, CommandLineOptions& opts, const std::vector<std::pair<std::string, size_t> >& params, size_t pos)
{
    const std::string pName = params[pos].first;
    if (pos+1 == params.size() && params[pos].second > 1)
        M.setOutputMode(pName, Line);

    std::vector<double> v = opts[pName];
    for (size_t i=0; i<v.size(); i++)
    {
        M.setParam(pName, v[i]);
        if (pos+1<params.size())
            runMeasurement(M, opts, params, pos+1);
        else
            M.measure();
    }
}

template<class System>
void run (CommandLineOptions& opts)
{
    const char* pnamesv[] = {"t","td","ti","V0","mu","Vext","Pext","a","b","beta"};
    size_t pnamesc = 10;
    std::vector<std::pair<std::string, size_t> > params;
    for (size_t i=0; i<pnamesc; i++)
    {
        std::pair<std::string, size_t> p;
        p.first = pnamesv[i];
        std::vector<double> v = opts[pnamesv[i]];
        p.second = v.size();
        params.push_back(p);
    }

    std::sort(params.begin(), params.end(), comparePair);

    OptionSection cOpts(opts);
    cOpts["t"] = 1;
    cOpts["td"] = 0;
    cOpts["ti"] = 0;
    cOpts["V0"] = 0;
    cOpts["mu"] = 0;
    cOpts["Vext"] = 0;
    cOpts["Pext"] = 0;
    cOpts["a"] = 1;
    cOpts["b"] = 1.75;
    cOpts["beta"] = 1;
    Measurement<System> M(cOpts);
    runMeasurement(M, opts, params, 0);
}

int main(int argc, const char** argv)
{
    CommandLineOptions opts = setupCLOptions();
    try {
        opts.parse(argc, argv);
    }
    catch (CommandLineOptionsException e)
    {
        std::cerr << e.what() << std::endl << std::endl;
        printUsage(opts);
        std::exit(EXIT_FAILURE);
    }

    if (opts["help"].isSet())
    {
        printUsage(opts);
        std::exit(EXIT_SUCCESS);
    }

    if (opts["model"] == "bond")
        run<DQcaBondPlain>(opts);
    else if (opts["model"] == "quarterfilling" || opts["model"] == "quarter" ||
             opts["model"] == "qf")
        run<DQcaQuarterFillingPlain>(opts);
    else if (opts["model"] == "grandcanonical" || opts["model"] == "grand")
        run<DQcaGrandCanonicalPlain>(opts);
    else if (opts["model"] == "bondDP")
        run<DQcaBondDeadPlaquet>(opts);
    else if (opts["model"] == "quarterfillingDP" || opts["model"] == "quarterDP" ||
             opts["model"] == "qfDP")
        run<DQcaQuarterFillingDeadPlaquet>(opts);
    else if (opts["model"] == "grandcanonicalDP" || opts["model"] == "grandDP")
        run<DQcaGrandCanonicalDeadPlaquet>(opts);
    else
    {
        printUsage(opts);
        std::cerr << std::endl << "Please specify a model." << std::endl;
        std::exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}
<commit_msg>Measure particle number for multiple plaquets.<commit_after>#include "qca.hpp"
#include "utilities.hpp"
#include <map>

/*
 * TODO
 * ----
 *
 * * P-P for three plaquets (bond system)
 * * P-P with dead cell (bond and qf)
 * * energies with dead cell? -- shouldn't make much difference
 * * grand canonical
 *    * number of electrons per cell for different a and b
 *    * number of electrons, considering Vext or dead cell
 *    * P-P
 * * compare energy, P-P for bond, qf, gc
 *
 *
 *
 * Output for the following command does not look correct to me:
 * ./runQca -m bondDP -p 1 -P 0 -Pext 0,1,2,3 -a 1,2 -E
 */

class EpsilonLess
{
public:
    EpsilonLess (double e_ = 1E-10)
    : e(e_)
    {}

    bool operator() (double a, double b)
    {
        return b-a > e;
    }
private:
    double e;
};

CommandLineOptions setupCLOptions ()
{
    CommandLineOptions o;
    o.add("help", "h", "Print this help message.")
     .add("model", "m", "Which QCA model to use. Options are: bond, bondDP, quarter, quarterDP, grand, grandDP.")
     .add("", "p", "Number of plaquets.")
     .add("", "t", "Hopping parameter.")
     .add("", "td", "Diagonal hopping parameter.")
     .add("", "ti", "Inter-plaquet hopping parameter.")
     .add("", "V0", "On-site coulomb repulsion (Hubbard U).")
     .add("", "mu", "Chemical potential.")
     .add("", "Vext", "External potential.")
     .add("", "Pext", "External, 'driving' polarisation of a 'dead plaquet' to the left of the linear chain system.")
     .add("", "a", "Intra-plaquet spacing.")
     .add("", "b", "Inter-plaquet spacing.")
     .add("", "beta", "Inverse temperature.")
     .add("energy-spectrum", "E", "Calculate the energy spectrum.")
     .add("polarisation", "P", "Calculate the polarisation for the specified plaquet(s).")
     .add("particle-number", "N", "Calculate the particle number for the specified plaquet(s).");

    o["p"].setDefault(1);
    o["t"].setDefault(1);
    o["td"].setDefault(0);
    o["ti"].setDefault(0);
    o["V0"].setDefault(0);
    o["mu"].setDefault(0);
    o["Vext"].setDefault(0);
    o["Pext"].setDefault(0);
    o["a"].setDefault(1);
    o["b"].setDefault(1.75);
    o["beta"].setDefault(1);

    return o;
}

void printUsage (CommandLineOptions& o)
{
    std::cerr << "Usage: " << std::endl;
    std::cerr << o.usage();
}

enum OutputMode {Header, Line, None};

template<class System>
class Measurement
{
public:
    Measurement (OptionSection o_)
    : o(o_), s(o_), needHeader(true), globalFirst(true)
    {
        for (OptionSection::OptionsType::iterator i=o.getOptions().begin(); i!=o.getOptions().end(); i++)
            outputConfig[i->getName()] = Header;
        outputConfig["energy-spectrum"] = None;
        outputConfig["polarisation"] = None;
        outputConfig["particle-number"] = None;
        outputConfig["help"] = None;
    }

    void setParam (const std::string& param, const OptionValue& value)
    {
        o[param] = value;
        if (outputConfig[param] == Header)
            needHeader = true;
    }

    void measure (const std::string& param, const OptionValue& value)
    {
        setParam(param, value);
        measure();
    }

    void measure ()
    {
        s.setParameters(o);
        s.update();

        if (o["energy-spectrum"].isSet())
            measureEnergies();
        if (o["polarisation"].isSet())
            measurePolarisation();
        if (o["particle-number"].isSet())
            measureParticleNumber();

        store();
    }

    void measureEnergies ()
    {
        E.resize(0);
        typedef std::map<double, int, EpsilonLess> myMap;
        typedef myMap::const_iterator mapIt;
        myMap evs;
        for (int i=0; i<s.energies().size(); i++)
            evs[s.energies()(i)]++;
        for (mapIt i=evs.begin(); i!=evs.end(); i++)
        {
            std::vector<double> v(3);
            v[0] = i->first;
            v[1] = i->first - s.Emin();
            v[2] = i->second;
            E.push_back(v);
        }
    }

    void measurePolarisation ()
    {
        P.resize(0);
        std::vector<size_t> ps = o["polarisation"];
        for (size_t i=0; i<ps.size(); i++)
        {
            if (ps[i] >= s.N_p)
            {
                std::cerr << std::endl << "Polarisation: There is no plaquet "
                    << ps[i] << " in this system." << std::endl;
                std::exit(EXIT_FAILURE);
            }
            P.push_back(s.measure(o["beta"], s.P(ps[i])));
        }
    }

    void measureParticleNumber ()
    {
        N.resize(0);
        std::vector<size_t> ns = o["particle-number"];
        for (size_t i=0; i<ns.size(); i++)
        {
            if (ns[i] >= s.N_p)
            {
                std::cerr << std::endl << "Particle number: There is no plaquet "
                    << ns[i] << " in this system." << std::endl;
                std::exit(EXIT_FAILURE);
            }
            N.push_back(s.measure(o["beta"], s.N(ns[i])));
        }
    }

    void store ()
    {
        // always print energy spectrum as a separate block
        if (o["energy-spectrum"].isSet())
        {
            printHeaderAll();
            std::cout << "# " << std::endl << "# E\tE-Emin\tDegeneracy" << std::endl;
            for (size_t i=0; i<E.size(); i++)
                std::cout << E[i][0] << "\t" << E[i][1] << "\t" << E[i][2] << std::endl;
            std::cout << std::endl;
        }

        if (o["polarisation"].isSet() || o["particle-number"].isSet())
        {
            if (needHeader)
            {
                printHeader();

                std::cout << "# " << std::endl << "# ";
                bool first = true;
                for (typename OutputMap::const_iterator i=outputConfig.begin(); i!=outputConfig.end(); i++)
                    if (i->second == Line)
                    {
                        if (!first) std::cout << "\t";
                        else first = false;
                        std::cout << i->first;
                    }
                if (o["polarisation"].isSet())
                {
                    std::vector<size_t> ps = o["polarisation"];
                    for (size_t i=0; i<ps.size(); i++)
                    {
                        if (!first) std::cout << "\t";
                        else first = false;
                        std::cout << "P" << ps[i];
                    }
                }
                if (o["particle-number"].isSet())
                {
                    std::vector<size_t> ns = o["particle-number"];
                    for (size_t i=0; i<ns.size(); i++)
                    {
                        if (!first) std::cout << "\t";
                        else first = false;
                        std::cout << "N" << ns[i];
                    }
                }
                std::cout << std::endl;

                needHeader = false;
            }

            bool first = true;
            for (typename OutputMap::const_iterator i=outputConfig.begin(); i!=outputConfig.end(); i++)
                if (i->second == Line)
                {
                    if (!first) std::cout << "\t";
                    else first = false;
                    std::cout << o[i->first];
                }
            if (o["polarisation"].isSet())
                for (size_t j=0; j<P.size(); j++)
                {
                    if (!first) std::cout << "\t";
                    else first = false;
                    std::cout << P[j];
                }
            if (o["particle-number"].isSet())
                for (size_t j=0; j<N.size(); j++)
                {
                    if (!first) std::cout << "\t";
                    else first = false;
                    std::cout << N[j];
                }
            std::cout << std::endl;
        }
    }

    void printHeader ()
    {
        if (!globalFirst) std::cout << std::endl;
        else globalFirst = false;
        for (OptionSection::OptionsType::iterator i=o.getOptions().begin(); i!=o.getOptions().end(); i++)
            if (outputConfig[i->getName()] == Header)
                std::cout << "# " << i->getName() << " = " << i->getValue() << std::endl;
    }

    void printHeaderAll ()
    {
        if (!globalFirst) std::cout << std::endl;
        else globalFirst = false;
        for (OptionSection::OptionsType::iterator i=o.getOptions().begin(); i!=o.getOptions().end(); i++)
            if (outputConfig[i->getName()] != None)
                std::cout << "# " << i->getName() << " = " << i->getValue() << std::endl;
    }

    void setOutputMode (std::string param, OutputMode mode)
    {
        outputConfig[param] = mode;
    }

private:
    OptionSection o;
    System s;

    std::vector<std::vector<double> > E;
    std::vector<double> P;
    std::vector<double> N;

    bool needHeader, globalFirst;
    typedef std::map<std::string, OutputMode> OutputMap;
    OutputMap outputConfig;
    std::vector<std::string> changed;
};

bool comparePair (const std::pair<std::string, size_t>& p1,
                  const std::pair<std::string, size_t>& p2)
{
    return p1.second < p2.second;
}

template<class Measurement>
void runMeasurement (Measurement& M, CommandLineOptions& opts, const std::vector<std::pair<std::string, size_t> >& params, size_t pos)
{
    const std::string pName = params[pos].first;
    if (pos+1 == params.size() && params[pos].second > 1)
        M.setOutputMode(pName, Line);

    std::vector<double> v = opts[pName];
    for (size_t i=0; i<v.size(); i++)
    {
        M.setParam(pName, v[i]);
        if (pos+1<params.size())
            runMeasurement(M, opts, params, pos+1);
        else
            M.measure();
    }
}

template<class System>
void run (CommandLineOptions& opts)
{
    const char* pnamesv[] = {"t","td","ti","V0","mu","Vext","Pext","a","b","beta"};
    size_t pnamesc = 10;
    std::vector<std::pair<std::string, size_t> > params;
    for (size_t i=0; i<pnamesc; i++)
    {
        std::pair<std::string, size_t> p;
        p.first = pnamesv[i];
        std::vector<double> v = opts[pnamesv[i]];
        p.second = v.size();
        params.push_back(p);
    }

    std::sort(params.begin(), params.end(), comparePair);

    OptionSection cOpts(opts);
    cOpts["t"] = 1;
    cOpts["td"] = 0;
    cOpts["ti"] = 0;
    cOpts["V0"] = 0;
    cOpts["mu"] = 0;
    cOpts["Vext"] = 0;
    cOpts["Pext"] = 0;
    cOpts["a"] = 1;
    cOpts["b"] = 1.75;
    cOpts["beta"] = 1;
    Measurement<System> M(cOpts);
    runMeasurement(M, opts, params, 0);
}

int main(int argc, const char** argv)
{
    CommandLineOptions opts = setupCLOptions();
    try {
        opts.parse(argc, argv);
    }
    catch (CommandLineOptionsException e)
    {
        std::cerr << e.what() << std::endl << std::endl;
        printUsage(opts);
        std::exit(EXIT_FAILURE);
    }

    if (opts["help"].isSet())
    {
        printUsage(opts);
        std::exit(EXIT_SUCCESS);
    }

    if (opts["model"] == "bond")
        run<DQcaBondPlain>(opts);
    else if (opts["model"] == "quarterfilling" || opts["model"] == "quarter" ||
             opts["model"] == "qf")
        run<DQcaQuarterFillingPlain>(opts);
    else if (opts["model"] == "grandcanonical" || opts["model"] == "grand")
        run<DQcaGrandCanonicalPlain>(opts);
    else if (opts["model"] == "bondDP")
        run<DQcaBondDeadPlaquet>(opts);
    else if (opts["model"] == "quarterfillingDP" || opts["model"] == "quarterDP" ||
             opts["model"] == "qfDP")
        run<DQcaQuarterFillingDeadPlaquet>(opts);
    else if (opts["model"] == "grandcanonicalDP" || opts["model"] == "grandDP")
        run<DQcaGrandCanonicalDeadPlaquet>(opts);
    else
    {
        printUsage(opts);
        std::cerr << std::endl << "Please specify a model." << std::endl;
        std::exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string.h>
#include <boost/tokenizer.hpp>
#include <vector>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
using namespace boost;

void parseinator(vector<string> input, string& command, string& argument, int& position);
void commandifier(string command, string argument);

class Connector
{
    public:
    Connector();
    ~Connector();
    bool run;
    virtual void runNext(bool succeed)= 0;
};

Connector::Connector()
{
    run = false;
}

Connector::~Connector()
{
}

class And: public Connector
{
    void runNext(bool succeed);
};

void And::runNext(bool succeed)
{
    if(succeed)
        run = true;
    else
        run = false;
}

class Or: public Connector
{
    void runNext(bool succeed);
};

void Or::runNext(bool succeed)
{
    if(succeed)
        run = false;
    else
        run = true;
}

class Do: public Connector
{
    void runNext(bool succeed);
};

void Do::runNext(bool succeed)
{
    run = true;
}
int main()
{
    string str;
    string command;
    string argument;
    char hostname[100];
    int position = 0;
    cout<<getlogin();
    gethostname(hostname,sizeof hostname);
    cout<<"@"<<hostname<<"$ ";
    getline(cin, str);
    vector<string> instruction;
    typedef tokenizer<boost::char_separator<char> > Tok;
    char_separator<char> sep; // default constructed
    Tok tok(str, sep);
    for(Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter)
        instruction.push_back(*tok_iter);
    for(int i = 0; i < instruction.size(); i++)
        cout << instruction[i] << endl;
    for(; position < instruction.size();)
    {
        parseinator(instruction, command, argument, position);
        commandifier(command, argument);
        command = "";
        argument = "";
    }
}

void parseinator(vector<string> input, string& command, string& argument, int& position)
{
    command = input[position];
    position++;
    for(; position < input.size(); position++)
    {
        if(input[position] == ";")
        {

            position++;
            break;
        }
        if(input[position] == "|" || input[position] == "&")
        {
            position += 2;
            break;
        }
        if(input[position] == "#")
        {
            position = input.size();
            break;
        }
        argument += input[position];
        argument += " ";
    }
}

void commandifier(string command, string argument)
{
    const char * const_command = command.c_str();
    char char_command[command.size()];
    const char * const_argument = argument.c_str();
    char char_argument[argument.size()];
    strcpy (char_command, const_command);
    strcpy (char_argument, const_argument);
    char * args[3] = { char_command, char_argument, NULL} ;
    pid_t c_pid, pid;
    int status;

    c_pid = fork();

    if( c_pid < 0)
    {
        perror("fork failed");
        exit(1);
    }

    else if (c_pid == 0)
    {

        printf("Child: executing ls\n");
        execvp( args[0], args);
        if(execvp( args[0], args) == -1)
        {

        }
        perror("execve failed");

    }
    else if (c_pid > 0)
    {
        if( (pid = wait(&status)) < 0)
        {
            perror("wait");
            exit(1);
        }

        printf("Parent: finished\n");

    }
   // return 0;
}
<commit_msg>working program except minor issues with connectors<commit_after>#include <iostream>
#include <string.h>
#include <boost/tokenizer.hpp>
#include <vector>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
using namespace boost;

class Connector
{
public:
    Connector();
    ~Connector();
    bool run;
    int type;
    bool runNext();
};

Connector::Connector()
{
    run = true;
    type = 0;
}

Connector::~Connector()
{
}
bool Connector::runNext()
{
    if (type == 1)
    {
        if(!run)
        {
            return false;
        }
    }
    else if(type == 2)
    {
        if(run)
        {
            return false;
        }
    }
    return true;
}

void parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect);
void commandifier(string  command, string  argument, Connector& connect);

int main()
{

    string str;
    string command;
    string argument;
    Connector connect;
    char hostname[100];
    int position = 0;
    while(true)
    {
        cout<<getlogin();
        gethostname(hostname,sizeof hostname);
        cout<<"@"<<hostname<<"$ ";
        getline(cin, str);
        if (str == "exit")
            break;
        vector<string> instruction;
        typedef tokenizer<boost::char_separator<char> > Tok;
        char_separator<char> sep; // default constructed
        Tok tok(str, sep);
        for(Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter)
            instruction.push_back(*tok_iter);
       // for(int i = 0; i < instruction.size(); i++)
        //    cout << instruction[i] << endl;
        parseinator(instruction, command, argument, position, connect);
        commandifier(command, argument, connect);
        command = "";
        argument = "";
        for(; position < instruction.size();)
        {
            parseinator(instruction, command, argument, position, connect);
            if(connect.runNext())
                commandifier(command, argument, connect);
            command = "";
            argument = "";
        }
        position = 0;
    }
    return 0;
}

void parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect)
{
    command = input[position];
    position++;
    for(; position < input.size(); position++)
    {

        if(input[position] == "-")
        {
            while(input[position] != ";" && input[position] != "|" && input[position] != "&" && position+1 < input.size())
            {
                argument += input[position];
                position++;
            }
            if(position+1 == input.size())
            {
                argument += input[position];
                position++;
                break;
            }
        }
        if(input[position] == ";")
        {
            position++;
            break;
        }
        if(input[position] == "&")
        {
            connect.type = 1;
            position += 2;
            break;
        }
        if(input[position] == "|")
        {
            connect.type = 2;
            position += 2;
            break;
        }
        if(input[position] == "#")
        {
            position = input.size();
            break;
        }
        argument += input[position];
        argument += " ";
    }
}

void commandifier(string command, string argument, Connector& connect)
{
    cout << "i be command >>" << command << "<< i be argument >>" << argument << "<<" << endl;
    const char * const_command = command.c_str();
    char char_command[command.size()];
    const char * const_argument = argument.c_str();
    char char_argument[argument.size()];
    strcpy (char_command, const_command);
    strcpy (char_argument, const_argument);
    char * args[2];
    char * args1[3];
    bool no_arg = true;
    bool failed = false;
    cout<<argument.size();
    if(argument.size() ==0)
	args = { char_command, NULL};
    else
    {
	no_arg = false;
	args1 = { char_command, char_argument, NULL} ;
    }
    pid_t c_pid, pid;
    int status;

    c_pid = fork();

    if( c_pid < 0)
    {
        perror("fork failed");
        exit(1);
    }

    else if (c_pid == 0)
    {

        printf("Child: executing ls\n");
 	if(no_arg)
	{
        	execvp( args[0], args);
        	if(execvp( args[0], args) == -1)
                {
                    perror("execve failed");
                    connect.run = false;
                    failed = true;
                }
	}
	else
	{
 		execv(args1[0],args1);
		if(execvp(args1[0],args1) == -1)
                {
                    perror("exeve failed");
                    connect.run = false;
                    failed = true;
                }
	}
    }
    else if (c_pid > 0)
    {
        if( (pid = wait(&status)) < 0)
        {
            perror("wait");
            exit(1);
        }

        printf("Parent: finished\n");

    }
    if(!failed)
        connect.run = true;
   // return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

#include "acmacs-base/argc-argv.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "tree.hh"
#include "tree-export.hh"

// ----------------------------------------------------------------------

int main(int argc, const char* argv[])
{
    using namespace std::string_literals;
    try {
        argc_argv args(argc, argv,
                       {
                           {"--db-dir", ""},
                           {"--seqdb", ""},

                           {"-v", false},
                           {"--verbose", false},
                           {"-h", false},
                           {"--help", false},
                       });

        if (args["-h"] || args["--help"] || args.number_of_arguments() != 2) {
            throw std::runtime_error("Usage: "s + args.program() + " [options] <tree.json> <chart.ace>\n" + args.usage_options());
        }
        const bool verbose = args["-v"] || args["--verbose"];
        seqdb::setup_dbs(args["--db-dir"], verbose ? seqdb::report::yes : seqdb::report::no);
        if (args["--seqdb"])
            seqdb::setup(args["--seqdb"], verbose ? seqdb::report::yes : seqdb::report::no);

        std::shared_ptr<acmacs::chart::Chart> chart = acmacs::chart::import_from_file(args[1], acmacs::chart::Verify::None, report_time::No);
        Tree tree = tree::tree_import(args[0], chart);

        auto report_antigens = [](const Node& node, std::string path) {
            if (node.draw.matched_antigens)
                std::cout << std::setw(30) << std::left << path << ' ' << std::setw(4) << node.draw.matched_antigens << ' ' << std::setw(4) << node.subtree.size() << ' ' << find_first_leaf(node).seq_id << '\n';
        };

        tree::iterate_pre_path(tree, report_antigens);

        return 0;
    }
    catch (std::exception& err) {
        std::cerr << "ERROR: " << err.what() << '\n';
        return 1;
    }
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>tree-chart-sections<commit_after>#include <iostream>

#include "acmacs-base/argc-argv.hh"
#include "acmacs-base/stream.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "tree.hh"
#include "tree-export.hh"

// ----------------------------------------------------------------------

int main(int argc, const char* argv[])
{
    using namespace std::string_literals;
    try {
        argc_argv args(argc, argv,
                       {
                           {"--db-dir", ""},
                           {"--seqdb", ""},

                           {"--group-threshold", 10, "minimum nuber of antigens in the group"},
                           {"--group-series-sets", "", "write group-series-set-v1 json"},

                           {"-v", false},
                           {"--verbose", false},
                           {"-h", false},
                           {"--help", false},
                       });

        if (args["-h"] || args["--help"] || args.number_of_arguments() != 2) {
            throw std::runtime_error("Usage: "s + args.program() + " [options] <tree.json> <chart.ace>\n" + args.usage_options());
        }
        const bool verbose = args["-v"] || args["--verbose"];
        seqdb::setup_dbs(args["--db-dir"], verbose ? seqdb::report::yes : seqdb::report::no);
        if (args["--seqdb"])
            seqdb::setup(args["--seqdb"], verbose ? seqdb::report::yes : seqdb::report::no);

        std::shared_ptr<acmacs::chart::Chart> chart = acmacs::chart::import_from_file(args[1], acmacs::chart::Verify::None, report_time::No);
        Tree tree = tree::tree_import(args[0], chart);

        if (args["--group-series-sets"]) {
            using group_t = std::pair<std::string, std::vector<size_t>>;
            using groups_t = std::vector<group_t>;
            groups_t groups;
            const size_t max_in_group = tree.draw.matched_antigens / 3 * 2;
            auto make_groups = [&groups, max_in_group, threshold = static_cast<size_t>(args["--group-threshold"])](const Node& node, std::string path) {
                if (node.draw.matched_antigens >= threshold && node.draw.matched_antigens < max_in_group) {
                    auto& group = groups.emplace_back(path, std::vector<size_t>{});
                    tree::iterate_leaf(node, [&group](const Node& node2) {
                        if (node2.draw.chart_antigen_index)
                            group.second.push_back(*node2.draw.chart_antigen_index);
                    });
                }
            };
            tree::iterate_pre_path(tree, make_groups);
            for (const auto& group : groups)
                std::cout << std::setw(30) << std::left << group.first << ' ' << group.second << '\n';
        }
        else {
            auto report_antigens = [](const Node& node, std::string path) {
                if (node.draw.matched_antigens)
                    std::cout << std::setw(30) << std::left << path << ' ' << std::setw(4) << node.draw.matched_antigens << ' ' << std::setw(4) << node.subtree.size() << ' '
                              << find_first_leaf(node).seq_id << '\n';
            };

            tree::iterate_pre_path(tree, report_antigens);
        }
        return 0;
    }
    catch (std::exception& err) {
        std::cerr << "ERROR: " << err.what() << '\n';
        return 1;
    }
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <boost/thread/thread.hpp>
#include "mongodb_store/SetParam.h"

#include <actionlib/server/simple_action_server.h>
#include <calibrate_chest/CalibrateCameraAction.h>

#include <sensor_msgs/JointState.h>

class CalibrateCameraServer {
private:

    //bool do_calibrate; // register and unregister instead
    ros::NodeHandle n;
    actionlib::SimpleActionServer<calibrate_chest::CalibrateCameraAction> server;
    std::string action_name;
    ros::ServiceClient client;
    //ros::Subscriber sub;
    std::string camera_topic;
    calibrate_chest::CalibrateCameraFeedback feedback;
    calibrate_chest::CalibrateCameraResult result;

public:

    CalibrateCameraServer(const std::string& name, const std::string& camera_name) :
        //do_calibrate(false),
        server(n, name, boost::bind(&CalibrateCameraServer::execute_cb, this, _1), false),
        action_name(name),
        client(n.serviceClient<mongodb_store::SetParam>("/config_manager/set_param")),
        camera_topic(camera_name + "/depth/points")
    {
        //sub = n.subscribe(camera_topic, 1, &CalibrateCameraServer::msg_callback, this);
        server.start();
    }

private:

    bool is_inlier(const Eigen::Vector3f& point, const Eigen::Vector4f plane, double threshold) const
    {
        return fabs(point.dot(plane.segment<3>(0)) + plane(3)) < threshold;
    }

    void plot_best_plane(const pcl::PointCloud<pcl::PointXYZ>& points, const Eigen::Vector4f plane, double threshold) const
    {
        pcl::PointCloud<pcl::PointXYZ>::Ptr inlier_cloud(new pcl::PointCloud<pcl::PointXYZ>());
        pcl::PointCloud<pcl::PointXYZ>::Ptr outlier_cloud(new pcl::PointCloud<pcl::PointXYZ>());

        for (int i = 0; i < points.size(); ++i) {
            if (is_inlier(points[i].getVector3fMap(), plane, threshold)) {
                inlier_cloud->push_back(points[i]);
            }
            else {
                outlier_cloud->push_back(points[i]);
            }
        }

        pcl::visualization::PCLVisualizer viewer("3D Viewer");
        viewer.setBackgroundColor(0, 0, 0);
        viewer.addCoordinateSystem(1.0);
        viewer.initCameraParameters();

        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> inlier_color_handler(inlier_cloud, 255, 0, 0);
        viewer.addPointCloud(inlier_cloud, inlier_color_handler, "inliers");

        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> outlier_color_handler(outlier_cloud, 0, 0, 255);
        viewer.addPointCloud(outlier_cloud, outlier_color_handler, "outliers");

        while (!viewer.wasStopped())
        {
            viewer.spinOnce(100);
            boost::this_thread::sleep(boost::posix_time::microseconds(100000));
        }

    }

    void compute_plane(Eigen::Vector4f& plane, const pcl::PointCloud<pcl::PointXYZ>& points, int* inds) const
    {
        Eigen::Vector3f first = points[inds[1]].getVector3fMap() - points[inds[0]].getVector3fMap();
        Eigen::Vector3f second = points[inds[2]].getVector3fMap() - points[inds[0]].getVector3fMap();
        Eigen::Vector3f normal = first.cross(second);
        normal.normalize();
        plane.segment<3>(0) = normal;
        plane(3) = -normal.dot(points[inds[0]].getVector3fMap());
    }

    void extract_height_and_angle(const Eigen::Vector4f& plane)
    {
        feedback.status = "Checking and saving calibration...";
        server.publishFeedback(feedback);

        ROS_INFO("Ground plane: %f, %f, %f, %f", plane(0), plane(1), plane(2), plane(3));
        double dist = fabs(plane(3)/plane(2)); // distance along z axis
        double height = fabs(plane(3)/plane.segment<3>(0).squaredNorm()); // height
        ROS_INFO("Distance to plane along camera axis: %f", dist);
        ROS_INFO("Height above ground: %f", height);
        double angle = asin(height/dist);
        double angle_deg = 180.0f*angle/M_PI;
        ROS_INFO("Angle radians: %f", angle);
        ROS_INFO("Angle degrees: %f", angle_deg);

        result.angle = angle_deg;
        result.height = height;

        if (fabs(45.0f - angle_deg) > 3.0f) {
            result.status = "Angle not close enough to 45 degrees.";
            server.setAborted(result);
            return;
        }

        mongodb_store::SetParam srv;
        char buffer[250];

        // store height above ground in datacentre
        ros::param::set("/chest_xtion_height", height);
        sprintf(buffer, "{\"path\":\"/chest_xtion_height\",\"value\":%f}", height);
        srv.request.param = buffer;
        if (!client.call(srv)) {
            ROS_ERROR("Failed to call set height, is config manager running?");
        }

        // store angle between camera and horizontal plane
        ros::param::set("/chest_xtion_angle", angle);
        sprintf(buffer, "{\"path\":\"/chest_xtion_angle\",\"value\":%f}", angle);
        srv.request.param = buffer;
        if (!client.call(srv)) {
            ROS_ERROR("Failed to call set angle, is config manager running?");
        }

        result.status = "Successfully computed and saved calibration.";
        server.setSucceeded(result);
    }

    void publish_calibration()
    {
        feedback.status = "Publishing calibration...";
        feedback.progress = 0.0f;

        // get calibration with respect to ground plane from the calibrate_chest node
        double height, angle;
        n.param<double>("/chest_xtion_height", height, 1.10f); // get the height calibration
        n.param<double>("/chest_xtion_angle", angle, 0.72f); // get the angle calibration

        ros::Rate rate(1.0f);
        ros::Publisher pub = n.advertise<sensor_msgs::JointState>("/chest_calibration_publisher/state", 1);

        int counter = 0; // only publish for the first 10 secs, transforms will stay in tf
        while (n.ok() && counter < 5) {
            sensor_msgs::JointState joint_state;
            joint_state.header.stamp = ros::Time::now();
            joint_state.name.resize(2);
            joint_state.position.resize(2);
            joint_state.velocity.resize(2);
            joint_state.name[0] = "chest_xtion_height_joint";
            joint_state.name[1] = "chest_xtion_tilt_joint";
            joint_state.position[0] = height;
            joint_state.position[1] = angle;
            joint_state.velocity[0] = 0;
            joint_state.velocity[1] = 0;
            pub.publish(joint_state);
            rate.sleep();
            ++counter;

            feedback.progress = float(counter+1)/5.0f;
            server.publishFeedback(feedback);
        }

        ROS_INFO("Stopping to publish chest transform after 10 seconds, quitting...");

        result.status = "Published calibration.";
        result.angle = 180.0f/M_PI*angle;
        result.height = height;
        server.setSucceeded(result);
    }

public:

    void msg_callback(const sensor_msgs::PointCloud2::ConstPtr& msg)
    {
        //if (!do_calibrate) {
        //    return;
        //}
        //do_calibrate = false;

        feedback.status = "Calibrating...";
        feedback.progress = 0.0f;
        server.publishFeedback(feedback);

        ROS_INFO("Got a pointcloud, calibrating...");
        pcl::PointCloud<pcl::PointXYZ> cloud;
        pcl::fromROSMsg(*msg, cloud);

        int nbr = cloud.size();

        int max = 1000; // ransac iterations
        double threshold = 0.02; // threshold for plane inliers

        Eigen::Vector4f best_plane; // best plane parameters found
        int best_inliers = -1; // best number of inliers

        int inds[3];

        Eigen::Vector4f plane;
        int inliers;
        for (int i = 0; i < max; ++i) {

            for (int j = 0; j < 3; ++j) {
                inds[j] = rand() % nbr; // get a random point
            }

            // check that the points aren't the same
            if (inds[0] == inds[1] || inds[0] == inds[2] || inds[1] == inds[2]) {
                continue;
            }

            compute_plane(plane, cloud, inds);
            inliers = 0;
            for (int j = 0; j < nbr; j += 30) { // count number of inliers
                if (is_inlier(cloud[j].getVector3fMap(), plane, threshold)) {
                    ++inliers;
                }
            }

            if (inliers > best_inliers) {
                best_plane = plane;
                best_inliers = inliers;
            }

            if (i % 10 == 0) {
                feedback.progress = float(i+1)/float(max);
                server.publishFeedback(feedback);
            }
        }

        extract_height_and_angle(best_plane); // find parameters and feed them to datacentre
        //plot_best_plane(cloud, best_plane, threshold); // visually evaluate plane fit
    }

    void execute_cb(const calibrate_chest::CalibrateCameraGoalConstPtr& goal)
    {
        if (goal->command == "calibrate") {
            sensor_msgs::PointCloud2::ConstPtr msg = ros::topic::waitForMessage<sensor_msgs::PointCloud2>(camera_topic, n);
            if (msg) {
                msg_callback(msg);
            }
            else {
                result.status = "Did not receive any point cloud.";
                server.setAborted(result);
            }
        }
        else if (goal->command == "publish") {
            publish_calibration();
        }
        else {
            result.status = "Enter command \"calibrate\" or \"publish\".";
            server.setAborted(result);
        }
    }
};

int main(int argc, char** argv)
{
    ros::init(argc, argv, "calibrate_chest");
    CalibrateCameraServer calibrate(ros::this_node::getName(), "chest_xtion");
    ros::spin();

	return 0;
}
<commit_msg>Polishing<commit_after>#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <boost/thread/thread.hpp>
#include "mongodb_store/SetParam.h"

#include <actionlib/server/simple_action_server.h>
#include <calibrate_chest/CalibrateCameraAction.h>

#include <sensor_msgs/JointState.h>

class CalibrateCameraServer {
private:

    //bool do_calibrate; // register and unregister instead
    ros::NodeHandle n;
    actionlib::SimpleActionServer<calibrate_chest::CalibrateCameraAction> server;
    std::string action_name;
    ros::ServiceClient client;
    //ros::Subscriber sub;
    std::string camera_topic;
    calibrate_chest::CalibrateCameraFeedback feedback;
    calibrate_chest::CalibrateCameraResult result;

public:

    CalibrateCameraServer(const std::string& name, const std::string& camera_name) :
        //do_calibrate(false),
        server(n, name, boost::bind(&CalibrateCameraServer::execute_cb, this, _1), false),
        action_name(name),
        client(n.serviceClient<mongodb_store::SetParam>("/config_manager/set_param")),
        camera_topic(camera_name + "/depth/points")
    {
        //sub = n.subscribe(camera_topic, 1, &CalibrateCameraServer::msg_callback, this);
        server.start();
    }

private:

    bool is_inlier(const Eigen::Vector3f& point, const Eigen::Vector4f plane, double threshold) const
    {
        return fabs(point.dot(plane.segment<3>(0)) + plane(3)) < threshold;
    }

    void plot_best_plane(const pcl::PointCloud<pcl::PointXYZ>& points, const Eigen::Vector4f plane, double threshold) const
    {
        pcl::PointCloud<pcl::PointXYZ>::Ptr inlier_cloud(new pcl::PointCloud<pcl::PointXYZ>());
        pcl::PointCloud<pcl::PointXYZ>::Ptr outlier_cloud(new pcl::PointCloud<pcl::PointXYZ>());

        for (int i = 0; i < points.size(); ++i) {
            if (is_inlier(points[i].getVector3fMap(), plane, threshold)) {
                inlier_cloud->push_back(points[i]);
            }
            else {
                outlier_cloud->push_back(points[i]);
            }
        }

        pcl::visualization::PCLVisualizer viewer("3D Viewer");
        viewer.setBackgroundColor(0, 0, 0);
        viewer.addCoordinateSystem(1.0);
        viewer.initCameraParameters();

        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> inlier_color_handler(inlier_cloud, 255, 0, 0);
        viewer.addPointCloud(inlier_cloud, inlier_color_handler, "inliers");

        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> outlier_color_handler(outlier_cloud, 0, 0, 255);
        viewer.addPointCloud(outlier_cloud, outlier_color_handler, "outliers");

        while (!viewer.wasStopped())
        {
            viewer.spinOnce(100);
            boost::this_thread::sleep(boost::posix_time::microseconds(100000));
        }

    }

    void compute_plane(Eigen::Vector4f& plane, const pcl::PointCloud<pcl::PointXYZ>& points, int* inds) const
    {
        Eigen::Vector3f first = points[inds[1]].getVector3fMap() - points[inds[0]].getVector3fMap();
        Eigen::Vector3f second = points[inds[2]].getVector3fMap() - points[inds[0]].getVector3fMap();
        Eigen::Vector3f normal = first.cross(second);
        normal.normalize();
        plane.segment<3>(0) = normal;
        plane(3) = -normal.dot(points[inds[0]].getVector3fMap());
    }

    void extract_height_and_angle(const Eigen::Vector4f& plane)
    {
        feedback.status = "Checking and saving calibration...";
        server.publishFeedback(feedback);

        ROS_INFO("Ground plane: %f, %f, %f, %f", plane(0), plane(1), plane(2), plane(3));
        double dist = fabs(plane(3)/plane(2)); // distance along z axis
        double height = fabs(plane(3)/plane.segment<3>(0).squaredNorm()); // height
        ROS_INFO("Distance to plane along camera axis: %f", dist);
        ROS_INFO("Height above ground: %f", height);
        double angle = asin(height/dist);
        double angle_deg = 180.0f*angle/M_PI;
        ROS_INFO("Angle radians: %f", angle);
        ROS_INFO("Angle degrees: %f", angle_deg);

        result.angle = angle_deg;
        result.height = height;

        if (fabs(45.0f - angle_deg) > 3.0f) {
            result.status = "Angle not close enough to 45 degrees.";
            server.setAborted(result);
            return;
        }

        mongodb_store::SetParam srv;
        char buffer[250];

        // store height above ground in datacentre
        ros::param::set("/chest_xtion_height", height);
        sprintf(buffer, "{\"path\":\"/chest_xtion_height\",\"value\":%f}", height);
        srv.request.param = buffer;
        if (!client.call(srv)) {
            ROS_ERROR("Failed to call set height, is config manager running?");
        }

        // store angle between camera and horizontal plane
        ros::param::set("/chest_xtion_angle", angle);
        sprintf(buffer, "{\"path\":\"/chest_xtion_angle\",\"value\":%f}", angle);
        srv.request.param = buffer;
        if (!client.call(srv)) {
            ROS_ERROR("Failed to call set angle, is config manager running?");
        }

        result.status = "Successfully computed and saved calibration.";
        server.setSucceeded(result);
    }

    void publish_calibration()
    {
        feedback.status = "Publishing calibration...";
        feedback.progress = 0.0f;

        // get calibration with respect to ground plane from the calibrate_chest node
        double height, angle;
        n.param<double>("/chest_xtion_height", height, 1.10f); // get the height calibration
        n.param<double>("/chest_xtion_angle", angle, 0.72f); // get the angle calibration

        ros::Rate rate(1.0f);
        ros::Publisher pub = n.advertise<sensor_msgs::JointState>("/chest_calibration_publisher/state", 1);

        int counter = 0; // only publish for the first 10 secs, transforms will stay in tf
        while (n.ok() && counter < 5) {
            sensor_msgs::JointState joint_state;
            joint_state.header.stamp = ros::Time::now();
            joint_state.name.resize(2);
            joint_state.position.resize(2);
            joint_state.velocity.resize(2);
            joint_state.name[0] = "chest_xtion_height_joint";
            joint_state.name[1] = "chest_xtion_tilt_joint";
            joint_state.position[0] = height;
            joint_state.position[1] = angle;
            joint_state.velocity[0] = 0;
            joint_state.velocity[1] = 0;
            pub.publish(joint_state);

            feedback.progress = float(counter+1)/5.0f;
            server.publishFeedback(feedback);

            rate.sleep();
            ++counter;
        }

        ROS_INFO("Stopping to publish chest transform after 5 seconds, quitting...");

        result.status = "Published calibration.";
        result.angle = 180.0f/M_PI*angle;
        result.height = height;
        server.setSucceeded(result);
    }

public:

    void msg_callback(const sensor_msgs::PointCloud2::ConstPtr& msg)
    {
        //if (!do_calibrate) {
        //    return;
        //}
        //do_calibrate = false;

        feedback.status = "Calibrating...";
        feedback.progress = 0.0f;
        server.publishFeedback(feedback);

        ROS_INFO("Got a pointcloud, calibrating...");
        pcl::PointCloud<pcl::PointXYZ> cloud;
        pcl::fromROSMsg(*msg, cloud);

        int nbr = cloud.size();

        int max = 1000; // ransac iterations
        double threshold = 0.02; // threshold for plane inliers

        Eigen::Vector4f best_plane; // best plane parameters found
        int best_inliers = -1; // best number of inliers

        int inds[3];

        Eigen::Vector4f plane;
        int inliers;
        for (int i = 0; i < max; ++i) {

            for (int j = 0; j < 3; ++j) {
                inds[j] = rand() % nbr; // get a random point
            }

            // check that the points aren't the same
            if (inds[0] == inds[1] || inds[0] == inds[2] || inds[1] == inds[2]) {
                continue;
            }

            compute_plane(plane, cloud, inds);
            inliers = 0;
            for (int j = 0; j < nbr; j += 30) { // count number of inliers
                if (is_inlier(cloud[j].getVector3fMap(), plane, threshold)) {
                    ++inliers;
                }
            }

            if (inliers > best_inliers) {
                best_plane = plane;
                best_inliers = inliers;
            }

            if (i % 10 == 0 || i == max - 1) {
                feedback.progress = float(i+1)/float(max);
                server.publishFeedback(feedback);
            }
        }

        extract_height_and_angle(best_plane); // find parameters and feed them to datacentre
        //plot_best_plane(cloud, best_plane, threshold); // visually evaluate plane fit
    }

    void execute_cb(const calibrate_chest::CalibrateCameraGoalConstPtr& goal)
    {
        if (goal->command == "calibrate") {
            sensor_msgs::PointCloud2::ConstPtr msg = ros::topic::waitForMessage<sensor_msgs::PointCloud2>(camera_topic, n);
            if (msg) {
                msg_callback(msg);
            }
            else {
                result.status = "Did not receive any point cloud.";
                server.setAborted(result);
            }
        }
        else if (goal->command == "publish") {
            publish_calibration();
        }
        else {
            result.status = "Enter command \"calibrate\" or \"publish\".";
            server.setAborted(result);
        }
    }
};

int main(int argc, char** argv)
{
    ros::init(argc, argv, "calibrate_chest");
    CalibrateCameraServer calibrate(ros::this_node::getName(), "chest_xtion");
    ros::spin();

	return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2007-2020 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * 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.
 *
 * 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
 * FOUNDATION 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.
 */

#include "FailingResourceLoader.hxx"
#include "widget/Inline.hxx"
#include "widget/Widget.hxx"
#include "widget/Request.hxx"
#include "widget/Resolver.hxx"
#include "widget/Context.hxx"
#include "bp/XmlProcessor.hxx"
#include "uri/Dissect.hxx"
#include "HttpResponseHandler.hxx"
#include "istream/istream.hxx"
#include "istream/istream_iconv.hxx"
#include "pool/pool.hxx"
#include "pool/SharedPtr.hxx"
#include "PInstance.hxx"
#include "bp/session/Session.hxx"
#include "util/Cancellable.hxx"
#include "stopwatch.hxx"

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

const char *
Widget::GetLogName() const noexcept
{
	return "dummy";
}

StringView
Widget::LoggerDomain::GetDomain() const noexcept
{
	return "dummy";
}

UnusedIstreamPtr
istream_iconv_new(gcc_unused struct pool &pool, UnusedIstreamPtr input,
		  gcc_unused const char *tocode,
		  gcc_unused const char *fromcode) noexcept
{
	return input;
}

void
Widget::DiscardForFocused() noexcept
{
}

void
Widget::Cancel() noexcept
{
}

void
Widget::CheckHost(const char *, const char *) const
{
}

RealmSessionLease
WidgetContext::GetRealmSession() const
{
	return nullptr;
}

void
session_put(Session *session gcc_unused) noexcept
{
}

void
Widget::LoadFromSession(gcc_unused RealmSession &session) noexcept
{
}

void
widget_http_request(gcc_unused struct pool &pool,
		    gcc_unused Widget &widget,
		    SharedPoolPtr<WidgetContext>,
		    const StopwatchPtr &,
		    HttpResponseHandler &handler,
		    gcc_unused CancellablePointer &cancel_ptr) noexcept
{
	handler.InvokeError(std::make_exception_ptr(std::runtime_error("Test")));
}

struct TestOperation final : Cancellable {
	/* virtual methods from class Cancellable */
	void Cancel() noexcept override {
	}
};

void
ResolveWidget(struct pool &pool,
	      gcc_unused Widget &widget,
	      WidgetRegistry &,
	      gcc_unused WidgetResolverCallback callback,
	      CancellablePointer &cancel_ptr) noexcept
{
	auto to = NewFromPool<TestOperation>(pool);
	cancel_ptr = *to;
}

static void
test_abort_resolver()
{
	PInstance instance;
	const char *uri;
	bool ret;
	DissectedUri dissected_uri;

	FailingResourceLoader resource_loader;

	auto pool = pool_new_linear(instance.root_pool, "test", 4096);

	auto ctx = SharedPoolPtr<WidgetContext>::Make
		(*pool, instance.event_loop,
		 resource_loader, resource_loader,
		 nullptr,
		 nullptr, nullptr,
		 "localhost:8080",
		 "localhost:8080",
		 "/beng.html",
		 "http://localhost:8080/beng.html",
		 "/beng.html",
		 nullptr,
		 nullptr,
		 SessionId{}, "foo",
		 nullptr);

	uri = "/beng.html";
	ret = dissected_uri.Parse(uri);
	if (!ret) {
		fprintf(stderr, "uri_parse() failed\n");
		exit(2);
	}

	Widget widget(pool, nullptr);

	auto istream = embed_inline_widget(*pool, std::move(ctx),
					   nullptr, false, widget);
}

int
main(int, char **)
{
	test_abort_resolver();
}
<commit_msg>test/t_wembed: add parent widget to fix crash<commit_after>/*
 * Copyright 2007-2020 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * 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.
 *
 * 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
 * FOUNDATION 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.
 */

#include "FailingResourceLoader.hxx"
#include "widget/Inline.hxx"
#include "widget/Widget.hxx"
#include "widget/Request.hxx"
#include "widget/Resolver.hxx"
#include "widget/Context.hxx"
#include "bp/XmlProcessor.hxx"
#include "uri/Dissect.hxx"
#include "HttpResponseHandler.hxx"
#include "istream/istream.hxx"
#include "istream/istream_iconv.hxx"
#include "pool/pool.hxx"
#include "pool/SharedPtr.hxx"
#include "PInstance.hxx"
#include "bp/session/Session.hxx"
#include "util/Cancellable.hxx"
#include "stopwatch.hxx"

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

const char *
Widget::GetLogName() const noexcept
{
	return "dummy";
}

StringView
Widget::LoggerDomain::GetDomain() const noexcept
{
	return "dummy";
}

UnusedIstreamPtr
istream_iconv_new(gcc_unused struct pool &pool, UnusedIstreamPtr input,
		  gcc_unused const char *tocode,
		  gcc_unused const char *fromcode) noexcept
{
	return input;
}

void
Widget::DiscardForFocused() noexcept
{
}

void
Widget::Cancel() noexcept
{
}

void
Widget::CheckHost(const char *, const char *) const
{
}

RealmSessionLease
WidgetContext::GetRealmSession() const
{
	return nullptr;
}

void
session_put(Session *session gcc_unused) noexcept
{
}

void
Widget::LoadFromSession(gcc_unused RealmSession &session) noexcept
{
}

void
widget_http_request(gcc_unused struct pool &pool,
		    gcc_unused Widget &widget,
		    SharedPoolPtr<WidgetContext>,
		    const StopwatchPtr &,
		    HttpResponseHandler &handler,
		    gcc_unused CancellablePointer &cancel_ptr) noexcept
{
	handler.InvokeError(std::make_exception_ptr(std::runtime_error("Test")));
}

struct TestOperation final : Cancellable {
	/* virtual methods from class Cancellable */
	void Cancel() noexcept override {
	}
};

void
ResolveWidget(struct pool &pool,
	      gcc_unused Widget &widget,
	      WidgetRegistry &,
	      gcc_unused WidgetResolverCallback callback,
	      CancellablePointer &cancel_ptr) noexcept
{
	auto to = NewFromPool<TestOperation>(pool);
	cancel_ptr = *to;
}

static void
test_abort_resolver()
{
	PInstance instance;
	const char *uri;
	bool ret;
	DissectedUri dissected_uri;

	FailingResourceLoader resource_loader;

	auto pool = pool_new_linear(instance.root_pool, "test", 4096);

	auto ctx = SharedPoolPtr<WidgetContext>::Make
		(*pool, instance.event_loop,
		 resource_loader, resource_loader,
		 nullptr,
		 nullptr, nullptr,
		 "localhost:8080",
		 "localhost:8080",
		 "/beng.html",
		 "http://localhost:8080/beng.html",
		 "/beng.html",
		 nullptr,
		 nullptr,
		 SessionId{}, "foo",
		 nullptr);

	uri = "/beng.html";
	ret = dissected_uri.Parse(uri);
	if (!ret) {
		fprintf(stderr, "uri_parse() failed\n");
		exit(2);
	}

	const auto root_widget = MakeRootWidget(pool, "foo");
	Widget widget(pool, nullptr);
	widget.parent = root_widget.get();

	auto istream = embed_inline_widget(*pool, std::move(ctx),
					   nullptr, false, widget);
}

int
main(int, char **)
{
	test_abort_resolver();
}
<|endoftext|>


<commit_before>
/// Cint macro to test writing of mathcore Lorentz Vectors in a Tree

void mathcoreLV() {

  int nEvents = 10000;

  write(nEvents);

  read();
}

void write(int n) {

  gSystem->Load("libMathCore");
  gSystem->Load("libPhysics");
  using namespace ROOT::Math;

  TRandom R;
  TStopwatch timer;

  TFile f1("mathcoreLV.root","RECREATE");

  // create tree
  TTree t1("t1","Tree with new LorentzVector");

  std::vector<ROOT::Math::XYZTVector>  tracks;
  std::vector<ROOT::Math::XYZTVector> * pTracks = &tracks;
  t1.Branch("tracks","std::vector<XYZTVector>",&pTracks);

  timer.Start();
  for (int i = 0; i < n; ++i) {
    int nPart = R.Poisson(5);
    pTracks->clear();
    pTracks->reserve(nPart);
    for (int j = 0; j < nPart; ++j) {
      double Px = R.Gaus(0,10);
      double Py = R.Gaus(0,10);
      double Pz = R.Gaus(0,10);
      double E  = TMath::Max(R.Gaus(100,30),0.0);
      XYZTVector v1(Px,Py,Pz,E);
      pTracks->push_back(v1);
    }
    t1.Fill();
  }

  f1.Write();
  timer.Stop();
  std::cout << " Time for new Vector " << timer.RealTime() << "  " << timer.CpuTime() << std::endl;

  t1.Print();
}

void read() {

  gSystem->Load("libMathCore");
  gSystem->Load("libPhysics");
  using namespace ROOT::Math;

  TRandom R;
  TStopwatch timer;

  TH1D * h1 = new TH1D("h1","total energy  of event ",100,0,1000);
  TH1D * h2 = new TH1D("h2","Track Energy",100,0,200);
  TH1D * h3 = new TH1D("h2","Number of track per event",20,0,20);

  TFile f1("mathcoreLV.root");

  // create tree
  TTree *t1 = (TTree*)f1.Get("t1");

  std::vector<ROOT::Math::XYZTVector> * pTracks = 0;
  t1->SetBranchAddress("tracks",&pTracks);

  timer.Start();
  int n = (int) t1->GetEntries();
  std::cout << " Tree Entries " << n << std::endl;
  double etot=0;
  for (int i = 0; i < n; ++i) {
    t1->GetEntry(i);
    int ntrk = pTracks->size();
    h3->Fill(ntrk);
    XYZTVector q;
    for (int j = 0; j < ntrk; ++j) {
      XYZTVector v = (*pTracks)[j];
      q += v;
      h2->Fill(v.E());
    }
    h1->Fill(q.M() );
  }

  timer.Stop();
  std::cout << " Time for new Vector " << timer.RealTime() << "  " << timer.CpuTime() << std::endl;

  TCanvas *c1 = new TCanvas("c1","demo of Trees",10,10,600,800);
  c1->Divide(1,3);
  c1->cd(1);
  h1->Draw();
  c1->cd(2);
  h2->Draw();
  c1->cd(3);
  h3->Draw();

}

<commit_msg>fix the problem with SetBranchAdress on Linux<commit_after>
/// Cint macro to test writing of mathcore Lorentz Vectors in a Tree

void mathcoreLV() {

  int nEvents = 10000;

  write(nEvents);

  read();
}

void write(int n) {

  gSystem->Load("libMathCore");
  gSystem->Load("libPhysics");
  using namespace ROOT::Math;

  TRandom R;
  TStopwatch timer;

  TFile f1("mathcoreLV.root","RECREATE");

  // create tree
  TTree t1("t1","Tree with new LorentzVector");

  std::vector<ROOT::Math::XYZTVector>  tracks;
  std::vector<ROOT::Math::XYZTVector> * pTracks = &tracks;
  t1.Branch("tracks","std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > >",&pTracks);

  timer.Start();
  for (int i = 0; i < n; ++i) {
    int nPart = R.Poisson(5);
    pTracks->clear();
    pTracks->reserve(nPart);
    for (int j = 0; j < nPart; ++j) {
      double Px = R.Gaus(0,10);
      double Py = R.Gaus(0,10);
      double Pz = R.Gaus(0,10);
      double E  = TMath::Max(R.Gaus(100,30),0.0);
      XYZTVector v1(Px,Py,Pz,E);
      pTracks->push_back(v1);
    }
    t1.Fill();
  }

  f1.Write();
  timer.Stop();
  std::cout << " Time for new Vector " << timer.RealTime() << "  " << timer.CpuTime() << std::endl;

  t1.Print();
}

void read() {

  gSystem->Load("libMathCore");
  gSystem->Load("libPhysics");
  using namespace ROOT::Math;

  TRandom R;
  TStopwatch timer;

  TH1D * h1 = new TH1D("h1","total energy  of event ",100,0,1000);
  TH1D * h2 = new TH1D("h2","Track Energy",100,0,200);
  TH1D * h3 = new TH1D("h2","Number of track per event",20,0,20);

  TFile f1("mathcoreLV.root");

  // create tree
  TTree *t1 = (TTree*)f1.Get("t1");

  std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * pTracks = 0;
  t1->SetBranchAddress("tracks",&pTracks);

  timer.Start();
  int n = (int) t1->GetEntries();
  std::cout << " Tree Entries " << n << std::endl;
  double etot=0;
  for (int i = 0; i < n; ++i) {
    t1->GetEntry(i);
    int ntrk = pTracks->size();
    h3->Fill(ntrk);
    XYZTVector q;
    for (int j = 0; j < ntrk; ++j) {
      XYZTVector v = (*pTracks)[j];
      q += v;
      h2->Fill(v.E());
    }
    h1->Fill(q.M() );
  }

  timer.Stop();
  std::cout << " Time for new Vector " << timer.RealTime() << "  " << timer.CpuTime() << std::endl;

  TCanvas *c1 = new TCanvas("c1","demo of Trees",10,10,600,800);
  c1->Divide(1,3);
  c1->cd(1);
  h1->Draw();
  c1->cd(2);
  h2->Draw();
  c1->cd(3);
  h3->Draw();

}

<|endoftext|>


<commit_before>#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace std;
using namespace boost::filesystem;
using namespace boost::posix_time;

#define STATS 0
#define LIST 1
#define ALL 2

#define STATS_ARG "--stats"
#define LIST_ARG "--list"
#define ALL_ARG "--all"

int main(int argc, char* argv[])
{
	if (argc < 2)
	{
		// If no input file argument provided - error
		cout << "Input file missing!\n";
		cout << "Try again: " << argv[0] << " <filename> --optionalArgument\n";
		cout << "\n";
		// Arguments info:
		cout << "--stats\nOutputs statistical information about time stamp anomalies.\n";
		cout << "--list\nOutputs lines with erroneous time stamps along with line numbers.\n";
		cout << "--all\nOutputs lines with erroneous time stamps along with line numbers and statistical information about time stamp anomalies.\n";

		return -1;
	}

	try
	{
		path p(argv[1]);
		if (exists(p))
		{
			if (!is_regular_file(p))
			{
				cout << "Not regular file provided!\n";

				return -1;
			}

			// Open file after checking that it exists and is regular
			std::ifstream file(p.c_str());
			long fileLines = count(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), '\n') + 1;

			// Go back to beginning of file
			file.clear();
			file.seekg(0, ios::beg);

			// Reading every line into vector
			string str;
			vector<string> lines;
			while (getline(file, str))
			{
				lines.push_back(str);
			}

			// Parsing date-time and checking for errors
			const locale loc = locale(locale::classic(), new time_input_facet("%Y-%m-%d %H:%M:%s"));
			ptime* lastNormalTimestamp = NULL;
			vector<int> invalidTimestampsLines;
			int i, totalInvalidTimestamps = 0;

			for (i = 0; i < fileLines; ++i)
			{
				// PARSING PART
				string lineDate = lines[i].substr(0, 23);
				istringstream is(lineDate);
				is.imbue(loc);
				ptime currentTimestamp;
				is >> currentTimestamp;

				// ERROR CHECKING PART
				if (lastNormalTimestamp != NULL
					&& (lastNormalTimestamp->time_of_day() > currentTimestamp.time_of_day()
						|| lastNormalTimestamp->date() > currentTimestamp.date()))
				{
					invalidTimestampsLines.push_back(i);
					totalInvalidTimestamps++;
				}
				else
				{
					free(lastNormalTimestamp);
					lastNormalTimestamp = new ptime(currentTimestamp);
				}
			}

			// Checking additional action argument:
			int action = STATS;
			if (argc > 2 && strcmp(argv[2], STATS_ARG) != 0)
			{
				if (strcmp(argv[2], LIST_ARG) != 0 && strcmp(argv[2], ALL_ARG) != 0)
				{
					cout << "Wrong action. Default action '--stats' selected instead.";
				}
				else
				{
					action = ALL;
					if (strcmp(argv[2], LIST_ARG) == 0)
					{
						action = LIST;
					}
				}
			}

			if (action == STATS || action == ALL)
			{
				cout << "Number of lines:\n" << fileLines << "\n";
				cout << "Invalid time stamps at line(s):\n";

				bool isRange = false;
				string output;
				for (i = 0; i < totalInvalidTimestamps; ++i)
				{
					// Starting point ("x")
					if (!isRange)
					{
						output = to_string(invalidTimestampsLines[i] + 1);
					}

					// Check if next line number is next to this to form a range ("x-")
					if (i + 1 != totalInvalidTimestamps && !isRange
						&& invalidTimestampsLines[i + 1] + 1 == invalidTimestampsLines[i] + 2)
					{
						isRange = true;
						output += "-";
					}

					if (isRange)
					{
						// Check if there is no more line numbers in this range to close it ("x-y")
						if (i + 1 == totalInvalidTimestamps || invalidTimestampsLines[i + 1] + 1 != invalidTimestampsLines[i] + 2)
						{
							output += to_string(invalidTimestampsLines[i] + 1);
							isRange = false;
						}
						else { continue; }
					}

					cout << output << "\n";
				}

				cout << "\n";
			}

			if (action == LIST || action == ALL)
			{
				int currentInvalidTimestampLine;
				for (i = 0; i < totalInvalidTimestamps; ++i)
				{
					currentInvalidTimestampLine = invalidTimestampsLines[i];
					// Normal entry before the invalid timestamp
					if (currentInvalidTimestampLine > 0
						&& (i == 0 || invalidTimestampsLines[i - 1] != currentInvalidTimestampLine - 1))
					{
						cout << "[" << currentInvalidTimestampLine << "] " + lines[currentInvalidTimestampLine - 1] << "\n";
					}

					// Invalid timestamp entry
					cout << "[" << currentInvalidTimestampLine + 1 << "] " + lines[currentInvalidTimestampLine] << "\n";

					// Normal entry after invalid timestamp
					if (currentInvalidTimestampLine + 1 < fileLines
						&& (i + 1 == totalInvalidTimestamps || invalidTimestampsLines[i + 1] != currentInvalidTimestampLine + 1))
					{
						cout << "[" << currentInvalidTimestampLine + 2 << "] " + lines[currentInvalidTimestampLine + 1] << "\n";
						cout << "---" << "\n";
					}
				}
			}
		}
		else
		{
			cout << "File does not exist!\n";

			return -1;
		}
	}
	catch (const filesystem_error& ex)
	{
		cout << "Error occured!\n" << ex.what() << '\n';

		return -1;
	}

	return 0;
}
<commit_msg>Refactoring<commit_after>#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace std;
using namespace boost::filesystem;
using namespace boost::posix_time;

#define STATS 0
#define LIST 1
#define ALL 2

#define STATS_ARG "--stats"
#define LIST_ARG "--list"
#define ALL_ARG "--all"

int checkTSForErrors(int fileLinesAmount, vector<string> linesVector, vector<int> *invalidTimestampsLines);
void showStats(int fileLinesAmount, vector<int> invalidTimestampsLines, int totalInvalidTimestamps);
void showList(int fileLinesAmount, vector<string> linesVector, vector<int> invalidTimestampsLines, int totalInvalidTimestamps);

int main(int argc, char* argv[])
{
	// If no input file argument provided - show error message
	if (argc < 2)
	{
		cout << "Input file missing!\n";
		cout << "Try again: " << argv[0] << " <filename> --optionalArgument\n";
		cout << "\n";
		// Arguments info:
		cout << "--stats\nOutputs statistical information about time stamp anomalies.\n";
		cout << "--list\nOutputs lines with erroneous time stamps along with line numbers.\n";
		cout << "--all\nOutputs lines with erroneous time stamps along with line numbers and statistical information about time stamp anomalies.\n";

		return -1;
	}

	vector<string> linesVector;
	long fileLines;

	try
	{
		path p(argv[1]);
		if (exists(p))
		{
			if (!is_regular_file(p))
			{
				cout << "Not regular file provided!\n";

				return -1;
			}

			// Open file after checking that it exists and is regular
			std::ifstream file(p.c_str());
			fileLines = count(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), '\n') + 1;

			// Go back to beginning of file
			file.clear();
			file.seekg(0, ios::beg);

			// Reading every line into vector
			string str;
			while (getline(file, str)) linesVector.push_back(str);
		}
		else
		{
			cout << "File does not exist!\n";

			return -1;
		}
	}
	catch (const filesystem_error& ex)
	{
		cout << "File reading error!\n" << ex.what() << '\n';

		return -1;
	}

	// Checking additional action argument:
	int action = STATS;
	if (argc > 2 && strcmp(argv[2], STATS_ARG) != 0)
	{
		if (strcmp(argv[2], LIST_ARG) != 0 && strcmp(argv[2], ALL_ARG) != 0)
		{
			cout << "Wrong action. Default action '--stats' selected instead.";
		}
		else
		{
			action = ALL;
			if (strcmp(argv[2], LIST_ARG) == 0) action = LIST;
		}
	}

	vector<int> invalidTimestampsLines;
	int totalInvalidTimestamps = checkTSForErrors(fileLines, linesVector, &invalidTimestampsLines);

	if (action == STATS || action == ALL) showStats(fileLines, invalidTimestampsLines, totalInvalidTimestamps);
	if (action == LIST || action == ALL) showList(fileLines, linesVector, invalidTimestampsLines, totalInvalidTimestamps);

	return 0;
}

int checkTSForErrors(int fileLinesAmount, vector<string> lines, vector<int> *invalidTimestampsLines)
{
	const locale loc = locale(locale::classic(), new time_input_facet("%Y-%m-%d %H:%M:%s"));
	ptime* lastNormalTimestamp = NULL;
	ptime currentTimestamp;
	int i, totalInvalidTimestamps = 0;
	for (i = 0; i < fileLinesAmount; ++i)
	{
		// PARSING PART
		string lineDate = lines[i].substr(0, 23);
		istringstream is(lineDate);
		is.imbue(loc);
		is >> currentTimestamp;

		// ERROR CHECKING PART
		if (lastNormalTimestamp != NULL
			&& (lastNormalTimestamp->time_of_day() > currentTimestamp.time_of_day()
				|| lastNormalTimestamp->date() > currentTimestamp.date()))
		{
			invalidTimestampsLines->push_back(i);
			totalInvalidTimestamps++;
		}
		else
		{
			free(lastNormalTimestamp);
			lastNormalTimestamp = new ptime(currentTimestamp);
		}
	}

	return totalInvalidTimestamps;
}

void showStats(int fileLinesAmount, vector<int> invalidTimestampsLines, int totalInvalidTimestamps)
{
	cout << "Number of lines:\n" << fileLinesAmount << "\n";
	cout << "Invalid time stamps at line(s):\n";

	bool isRange = false;
	string output;
	int i;
	for (i = 0; i < totalInvalidTimestamps; ++i)
	{
		// Starting point ("x")
		if (!isRange) output = to_string(invalidTimestampsLines[i] + 1);

		// Check if next line number is next to this to form a range ("x-")
		if (i + 1 != totalInvalidTimestamps && !isRange
			&& invalidTimestampsLines[i + 1] + 1 == invalidTimestampsLines[i] + 2)
		{
			isRange = true;
			output += "-";
		}

		if (isRange)
		{
			// Check if there is no more line numbers in this range to close it ("x-y")
			if (i + 1 == totalInvalidTimestamps || invalidTimestampsLines[i + 1] + 1 != invalidTimestampsLines[i] + 2)
			{
				output += to_string(invalidTimestampsLines[i] + 1);
				isRange = false;
			}
			else { continue; }
		}

		cout << output << "\n";
	}

	cout << "\n";
}

void showList(int fileLinesAmount, vector<string> lines, vector<int> invalidTimestampsLines, int totalInvalidTimestamps)
{
	int i, currentInvalidTimestampLine;
	for (i = 0; i < totalInvalidTimestamps; ++i)
	{
		currentInvalidTimestampLine = invalidTimestampsLines[i];

		// Normal entry before the invalid timestamp
		if (currentInvalidTimestampLine > 0
			&& (i == 0 || invalidTimestampsLines[i - 1] != currentInvalidTimestampLine - 1))
		{
			cout << "[" << currentInvalidTimestampLine << "] " + lines[currentInvalidTimestampLine - 1] << "\n";
		}

		// Invalid timestamp entry
		cout << "[" << currentInvalidTimestampLine + 1 << "] " + lines[currentInvalidTimestampLine] << "\n";

		// Normal entry after invalid timestamp
		if (currentInvalidTimestampLine + 1 < fileLinesAmount
			&& (i + 1 == totalInvalidTimestamps || invalidTimestampsLines[i + 1] != currentInvalidTimestampLine + 1))
		{
			cout << "[" << currentInvalidTimestampLine + 2 << "] " + lines[currentInvalidTimestampLine + 1] << "\n";
			cout << "---" << "\n";
		}
	}
}<|endoftext|>


<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
*
* based on the Null Theme Engine for Gtk+.
* Copyright (c) 2008 Robert Staudinger
*
* This  library is free  software; you can  redistribute it and/or
* modify it  under  the terms  of the  GNU Lesser  General  Public
* License  as published  by the Free  Software  Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* 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., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include "oxygenanimations.h"

#include <cassert>

namespace Oxygen
{

    //! unregister widget on destruction
    void Animations::destroyRegisteredWidget( GtkWidget* widget, GdkEvent* event, gpointer data )
    { Oxygen::Animations::instance().unregisterWidget( widget ); }

    //____________________________________________________________________________________________
    Animations& Animations::instance( void )
    {
        static Animations singleton;
        return singleton;
    }

    //_________________________________________
    Animations::~Animations( void )
    {

        delete _comboBoxEngine;

    }

    //____________________________________________________________________________________________
    void Animations::registerWidget( GtkWidget* widget )
    {

        if( _allWidgets.find( widget ) != _allWidgets.end() ) return;

        WidgetData data;
        data._destroyId = g_signal_connect( widget, "destroy", G_CALLBACK( destroyRegisteredWidget ), 0L );
        data._styleChangeId = g_signal_connect( widget, "style-set", G_CALLBACK( destroyRegisteredWidget ), 0L );
        _allWidgets.insert( std::make_pair( widget, data ) );

    }

    //____________________________________________________________________________________________
    void Animations::unregisterWidget( GtkWidget* widget )
    {

        // find in map
        WidgetMap::iterator iter( _allWidgets.find( widget ) );
        assert( iter != _allWidgets.end() );

        // disconnect signal
        g_signal_handler_disconnect(G_OBJECT(widget), iter->second._destroyId );
        g_signal_handler_disconnect(G_OBJECT(widget), iter->second._styleChangeId );

        // erase from map
        _allWidgets.erase( widget );

        // erase from all maps
        for( BaseEngine::List::iterator iter = _engines.begin(); iter != _engines.end(); iter++ )
        { (*iter)->unregisterWidget( widget ); }

    }

    //_________________________________________
    Animations::Animations( void )
    {

        // create engines
        registerEngine( _comboBoxEngine = new ComboBoxEngine( this ) );
        registerEngine( _menuShellEngine = new MenuShellEngine( this ) );
        registerEngine( _lineEditEngine = new LineEditEngine( this ) );

    }

}
<commit_msg>added some debug information. properly delete engines in destructor.<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
*
* based on the Null Theme Engine for Gtk+.
* Copyright (c) 2008 Robert Staudinger
*
* This  library is free  software; you can  redistribute it and/or
* modify it  under  the terms  of the  GNU Lesser  General  Public
* License  as published  by the Free  Software  Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* 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., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include "oxygenanimations.h"
#include "../config.h"

#include <cassert>
#include <iostream>

namespace Oxygen
{

    //! unregister widget on destruction
    void Animations::destroyRegisteredWidget( GtkWidget* widget, GdkEvent* event, gpointer data )
    { Oxygen::Animations::instance().unregisterWidget( widget ); }

    //____________________________________________________________________________________________
    Animations& Animations::instance( void )
    {
        static Animations singleton;
        return singleton;
    }

    //_________________________________________
    Animations::~Animations( void )
    {

        delete _comboBoxEngine;
        delete _menuShellEngine;
        delete _lineEditEngine;

    }

    //____________________________________________________________________________________________
    void Animations::registerWidget( GtkWidget* widget )
    {

        if( _allWidgets.find( widget ) != _allWidgets.end() ) return;

        #ifdef OXYGEN_DEBUG
        std::cout << "Oxygen::Animations::registerWidget - " << widget << std::endl;
        #endif

        WidgetData data;
        data._destroyId = g_signal_connect( widget, "destroy", G_CALLBACK( destroyRegisteredWidget ), 0L );
        data._styleChangeId = g_signal_connect( widget, "style-set", G_CALLBACK( destroyRegisteredWidget ), 0L );
        _allWidgets.insert( std::make_pair( widget, data ) );

    }

    //____________________________________________________________________________________________
    void Animations::unregisterWidget( GtkWidget* widget )
    {

        #ifdef OXYGEN_DEBUG
        std::cout << "Oxygen::Animations::unregisterWidget - " << widget << std::endl;
        #endif

        // find in map
        WidgetMap::iterator iter( _allWidgets.find( widget ) );
        assert( iter != _allWidgets.end() );

        // disconnect signal
        g_signal_handler_disconnect(G_OBJECT(widget), iter->second._destroyId );
        g_signal_handler_disconnect(G_OBJECT(widget), iter->second._styleChangeId );

        // erase from map
        _allWidgets.erase( widget );

        // erase from all maps
        for( BaseEngine::List::iterator iter = _engines.begin(); iter != _engines.end(); iter++ )
        { (*iter)->unregisterWidget( widget ); }

    }

    //_________________________________________
    Animations::Animations( void )
    {

        // create engines
        registerEngine( _comboBoxEngine = new ComboBoxEngine( this ) );
        registerEngine( _menuShellEngine = new MenuShellEngine( this ) );
        registerEngine( _lineEditEngine = new LineEditEngine( this ) );

    }

}
<|endoftext|>