<commit_before>/*
 *  Project:    moba-ambilight
 *
 *  Version:    1.0.0
 *
 *  Copyright (C) 2016 Stefan Paproth <pappi-@gmx.de>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program 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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program. If not, see <http://www.gnu.org/licenses/agpl.txt>.
 *
 */

#include <cstdlib>
#include <boost/shared_ptr.hpp>
#include <getopt.h>
#include <exception>

#include "bridge.h"
#include "handler.h"

#include <config.h>

#include <moba/ipc.h>
#include <moba/log.h>
#include <moba/helper.h>
#include <moba/signalhandler.h>
#include <stdlib.h>

namespace {
    moba::AppData appData = {
        PACKAGE_NAME,
        moba::Version(PACKAGE_VERSION),
        __DATE__,
        __TIME__,
        "",
        0
    };

    struct CmdLineArguments {
        int key;
        moba::IPC::Command action;
        std::string data;
    };
}

class ParseCmdLineException : public std::exception {

    public:
        explicit ParseCmdLineException(const std::string &err) throw() : what_(err) {
        }

        ParseCmdLineException() throw() : what_("Unknown error") {
        }

        virtual ~ParseCmdLineException() throw() {
        }

        virtual const char *what() const throw() {
            return what_.c_str();
        }

    private:
        std::string what_;
};

void printHelp() {
    std::cout << std::endl;
    std::cout << "-k, --key       ipc communication-key" << std::endl;
    std::cout << "-d, --data      [blue];[red];[green];[white];[duration];[wobble{W}]" << std::endl;
    std::cout << "-a, --action    [EMERGENCY_STOP] | [EMERGENCY_RELEASE] | [TEST] | [HALT] | [CONTINUE] | [RESET] | [TERMINATE]" << std::endl;
    std::cout << "-h, --help      shows this help" << std::endl;
    std::cout << "-v, --version   shows version-info" << std::endl;
}

bool parseArguments(int argc, char** argv, CmdLineArguments &args) {
    static struct option longOptions[] = {
        {"key",       required_argument, 0, 'k'},
        {"data",      required_argument, 0, 'd'},
        {"action",    required_argument, 0, 'a'},
        {"help",      no_argument,       0, 'h'},
        {"version",   no_argument,       0, 'v'},
        {NULL,      0, NULL, 0}
    };

    int optionIndex = 0;

    while (true) {
        int c = getopt_long(argc, argv, "k:d:a:hv", longOptions, &optionIndex);
        if(c == -1) {
            break;
        }

        switch (c) {
            case 'k':
                args.key = atoi(optarg);
                break;

            case 'd':
                args.data = std::string(optarg);
                break;

            case 'a':
                args.action = moba::IPC::getCMDFromString(optarg);
                break;

            case 'h':
                printHelp();
                return true;

            case 'v':
                moba::printAppData(appData);
                return true;
        }
    }
    if(args.action == moba::IPC::CMD_RUN && args.data == "") {
        throw ParseCmdLineException("no data given!");
    }
    if(args.action != moba::IPC::CMD_RUN && args.data != "") {
        throw ParseCmdLineException("invalid action given!");
    }
    return false;
}

int main(int argc, char** argv) {
    CmdLineArguments args = {
        moba::IPC::DEFAULT_KEY,
        moba::IPC::CMD_RUN,
        ""
    };

    try {
        if(!parseArguments(argc, argv, args)) {
            return EXIT_SUCCESS;
        }
        moba::IPC ipc(args.key, moba::IPC::TYPE_CLIENT);
        ipc.send(args.data, args.action);
    } catch(std::exception &e) {
        LOG(moba::WARNING) << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
<commit_msg>unneeded headers removed<commit_after>/*
 *  Project:    moba-ambilight
 *
 *  Version:    1.0.0
 *
 *  Copyright (C) 2016 Stefan Paproth <pappi-@gmx.de>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program 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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program. If not, see <http://www.gnu.org/licenses/agpl.txt>.
 *
 */

#include <cstdlib>
#include <getopt.h>
#include <exception>

#include <config.h>

#include <moba/ipc.h>
#include <moba/log.h>
#include <moba/helper.h>
#include <moba/signalhandler.h>

namespace {
    moba::AppData appData = {
        PACKAGE_NAME,
        moba::Version(PACKAGE_VERSION),
        __DATE__,
        __TIME__,
        "",
        0
    };

    struct CmdLineArguments {
        int key;
        moba::IPC::Command action;
        std::string data;
    };
}

class ParseCmdLineException : public std::exception {

    public:
        explicit ParseCmdLineException(const std::string &err) throw() : what_(err) {
        }

        ParseCmdLineException() throw() : what_("Unknown error") {
        }

        virtual ~ParseCmdLineException() throw() {
        }

        virtual const char *what() const throw() {
            return what_.c_str();
        }

    private:
        std::string what_;
};

void printHelp() {
    std::cout << std::endl;
    std::cout << "-k, --key       ipc communication-key" << std::endl;
    std::cout << "-d, --data      [blue];[red];[green];[white];[duration];[wobble{W}]" << std::endl;
    std::cout << "-a, --action    [EMERGENCY_STOP] | [EMERGENCY_RELEASE] | [TEST] | [HALT] | [CONTINUE] | [RESET] | [TERMINATE]" << std::endl;
    std::cout << "-h, --help      shows this help" << std::endl;
    std::cout << "-v, --version   shows version-info" << std::endl;
}

bool parseArguments(int argc, char** argv, CmdLineArguments &args) {
    static struct option longOptions[] = {
        {"key",       required_argument, 0, 'k'},
        {"data",      required_argument, 0, 'd'},
        {"action",    required_argument, 0, 'a'},
        {"help",      no_argument,       0, 'h'},
        {"version",   no_argument,       0, 'v'},
        {NULL,        0,              NULL,   0}
    };

    int optionIndex = 0;

    while (true) {
        int c = getopt_long(argc, argv, "k:d:a:hv", longOptions, &optionIndex);
        if(c == -1) {
            break;
        }

        switch (c) {
            case 'k':
                args.key = atoi(optarg);
                break;

            case 'd':
                args.data = std::string(optarg);
                break;

            case 'a':
                args.action = moba::IPC::getCMDFromString(optarg);
                break;

            case 'h':
                printHelp();
                return true;

            case 'v':
                moba::printAppData(appData);
                return true;
        }
    }
    if(args.action == moba::IPC::CMD_RUN && args.data == "") {
        throw ParseCmdLineException("no data given!");
    }
    if(args.action != moba::IPC::CMD_RUN && args.data != "") {
        throw ParseCmdLineException("invalid action given!");
    }
    return false;
}

int main(int argc, char** argv) {
    CmdLineArguments args = {
        moba::IPC::DEFAULT_KEY,
        moba::IPC::CMD_RUN,
        ""
    };

    try {
        if(!parseArguments(argc, argv, args)) {
            return EXIT_SUCCESS;
        }
        moba::IPC ipc(args.key, moba::IPC::TYPE_CLIENT);
        ipc.send(args.data, args.action);
    } catch(std::exception &e) {
        LOG(moba::WARNING) << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright (c) 2015-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <bench.h>

#include <assert.h>
#include <iostream>
#include <iomanip>
#include <sys/time.h>

benchmark::BenchRunner::BenchmarkMap &benchmark::BenchRunner::benchmarks() {
    static std::map<std::string, benchmark::BenchFunction> benchmarks_map;
    return benchmarks_map;
}

static double gettimedouble(void) {
    struct timeval tv;
    gettimeofday(&tv, nullptr);
    return tv.tv_usec * 0.000001 + tv.tv_sec;
}

benchmark::BenchRunner::BenchRunner(std::string name, benchmark::BenchFunction func)
{
    benchmarks().insert(std::make_pair(name, func));
}

void
benchmark::BenchRunner::RunAll(double elapsedTimeForOne)
{
    std::cout << "#Benchmark" << "," << "count" << "," << "min" << "," << "max" << "," << "average" << "\n";

    for (const auto &p: benchmarks()) {
        State state(p.first, elapsedTimeForOne);
        p.second(state);
    }
}

bool benchmark::State::KeepRunning()
{
    if (count & countMask) {
      ++count;
      return true;
    }
    double now;
    if (count == 0) {
        lastTime = beginTime = now = gettimedouble();
    }
    else {
        now = gettimedouble();
        double elapsed = now - lastTime;
        double elapsedOne = elapsed * countMaskInv;
        if (elapsedOne < minTime) minTime = elapsedOne;
        if (elapsedOne > maxTime) maxTime = elapsedOne;
        if (elapsed*128 < maxElapsed) {
          // If the execution was much too fast (1/128th of maxElapsed), increase the count mask by 8x and restart timing.
          // The restart avoids including the overhead of this code in the measurement.
          countMask = ((countMask<<3)|7) & ((1LL<<60)-1);
          countMaskInv = 1./(countMask+1);
          count = 0;
          minTime = std::numeric_limits<double>::max();
          maxTime = std::numeric_limits<double>::min();
          return true;
        }
        if (elapsed*16 < maxElapsed) {
          uint64_t newCountMask = ((countMask<<1)|1) & ((1LL<<60)-1);
          if ((count & newCountMask)==0) {
              countMask = newCountMask;
              countMaskInv = 1./(countMask+1);
          }
        }
    }
    lastTime = now;
    ++count;

    if (now - beginTime < maxElapsed) return true; // Keep going

    --count;

    assert(count != 0 && "count == 0 => (now == 0 && beginTime == 0) => return above");

    // Output results
    double average = (now-beginTime)/count;
    std::cout << std::fixed << std::setprecision(15) << name << "," << count << "," << minTime << "," << maxTime << "," << average << "\n";

    return false;
}
<commit_msg>Restore default format state of cout after printing with std::fixed/setprecision<commit_after>// Copyright (c) 2015-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <bench.h>

#include <assert.h>
#include <iostream>
#include <iomanip>
#include <sys/time.h>

benchmark::BenchRunner::BenchmarkMap &benchmark::BenchRunner::benchmarks() {
    static std::map<std::string, benchmark::BenchFunction> benchmarks_map;
    return benchmarks_map;
}

static double gettimedouble(void) {
    struct timeval tv;
    gettimeofday(&tv, nullptr);
    return tv.tv_usec * 0.000001 + tv.tv_sec;
}

benchmark::BenchRunner::BenchRunner(std::string name, benchmark::BenchFunction func)
{
    benchmarks().insert(std::make_pair(name, func));
}

void
benchmark::BenchRunner::RunAll(double elapsedTimeForOne)
{
    std::cout << "#Benchmark" << "," << "count" << "," << "min" << "," << "max" << "," << "average" << "\n";

    for (const auto &p: benchmarks()) {
        State state(p.first, elapsedTimeForOne);
        p.second(state);
    }
}

bool benchmark::State::KeepRunning()
{
    if (count & countMask) {
      ++count;
      return true;
    }
    double now;
    if (count == 0) {
        lastTime = beginTime = now = gettimedouble();
    }
    else {
        now = gettimedouble();
        double elapsed = now - lastTime;
        double elapsedOne = elapsed * countMaskInv;
        if (elapsedOne < minTime) minTime = elapsedOne;
        if (elapsedOne > maxTime) maxTime = elapsedOne;
        if (elapsed*128 < maxElapsed) {
          // If the execution was much too fast (1/128th of maxElapsed), increase the count mask by 8x and restart timing.
          // The restart avoids including the overhead of this code in the measurement.
          countMask = ((countMask<<3)|7) & ((1LL<<60)-1);
          countMaskInv = 1./(countMask+1);
          count = 0;
          minTime = std::numeric_limits<double>::max();
          maxTime = std::numeric_limits<double>::min();
          return true;
        }
        if (elapsed*16 < maxElapsed) {
          uint64_t newCountMask = ((countMask<<1)|1) & ((1LL<<60)-1);
          if ((count & newCountMask)==0) {
              countMask = newCountMask;
              countMaskInv = 1./(countMask+1);
          }
        }
    }
    lastTime = now;
    ++count;

    if (now - beginTime < maxElapsed) return true; // Keep going

    --count;

    assert(count != 0 && "count == 0 => (now == 0 && beginTime == 0) => return above");

    // Output results
    double average = (now-beginTime)/count;
    int64_t averageCycles = (nowCycles-beginCycles)/count;
    std::cout << std::fixed << std::setprecision(15) << name << "," << count << "," << minTime << "," << maxTime << "," << average << ","
              << minCycles << "," << maxCycles << "," << averageCycles << "\n";
    std::cout.copyfmt(std::ios(nullptr));

    return false;
}
<|endoftext|>


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

  Library   : Image Registration Toolkit (IRTK)
  Module    : $Id$
  Copyright : Imperial College, Department of Computing
              Visual Information Processing (VIP), 2008 onwards
  Date      : $Date$
  Version   : $Revision$
  Changes   : $Author$

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

#include <irtkImage.h>

#include <irtkHistogram_1D.h>

void usage()
{
  cerr << "Creates a histogram for a specific image" << endl;
  cerr << "Usage: [input] [output] <options>\n" << endl;
  cerr << "where <options> is one or more of the following:\n" << endl;
  cerr << "<-Rx1 pixel>       Region of interest" << endl;
  cerr << "<-Ry1 pixel>       Region of interest" << endl;
  cerr << "<-Rz1 pixel>       Region of interest" << endl;
  cerr << "<-Rx2 pixel>       Region of interest" << endl;
  cerr << "<-Ry2 pixel>       Region of interest" << endl;
  cerr << "<-Rz2 pixel>       Region of interest" << endl;

  exit(1);
}

int main(int argc, char **argv)
{
  int ok, x1, y1, z1, x2, y2, z2;

  char *input_name = NULL;
  char *output_name = NULL;

  // Check command line
  if (argc < 2) {
    usage();
  }

  // Parse image
  input_name  = argv[1];
  argc--;
  argv++;

  // Parse output name
  output_name  = argv[1];
  argc--;
  argv++;

  // Read image
  cout << "Reading image ... "<<input_name <<endl;
  irtkGreyImage input;
  input.Read(input_name);
  cout << "done" << endl;

  // Fix ROI
  x1 = 0;
  y1 = 0;
  z1 = 0;
  x2 = input.GetX();
  y2 = input.GetY();
  z2 = input.GetZ();

  while (argc > 1) {
    ok = False;

    if ((ok == False) && (strcmp(argv[1], "-Rx1") == 0)) {
      argc--;
      argv++;
      x1 = atoi(argv[1]);
      argc--;
      argv++;
      ok = True;
    }
    if ((ok == False) && (strcmp(argv[1], "-Rx2") == 0)) {
      argc--;
      argv++;
      x2 = atoi(argv[1]);
      argc--;
      argv++;
      ok = True;
    }
    if ((ok == False) && (strcmp(argv[1], "-Ry1") == 0)) {
      argc--;
      argv++;
      y1 = atoi(argv[1]);
      argc--;
      argv++;
      ok = True;
    }
    if ((ok == False) && (strcmp(argv[1], "-Ry2") == 0)) {
      argc--;
      argv++;
      y2 = atoi(argv[1]);
      argc--;
      argv++;
      ok = True;
    }
    if ((ok == False) && (strcmp(argv[1], "-Rz1") == 0)) {
      argc--;
      argv++;
      z1 = atoi(argv[1]);
      argc--;
      argv++;
      ok = True;
    }
    if ((ok == False) && (strcmp(argv[1], "-Rz2") == 0)) {
      argc--;
      argv++;
      z2 = atoi(argv[1]);
      argc--;
      argv++;
      ok = True;
    }
    if (ok == False) {
      cerr << "Can not parse argument " << argv[1] << endl;
      usage();
    }
  }

  input = input.GetRegion(x1, y1, z1, x2, y2, z2);

  irtkGreyPixel min ;
  irtkGreyPixel max ;

  input.GetMinMax(&min,&max);

  cout<<"Creating the histogram"<<endl;
  // Create the histogram
  irtkHistogram_1D *hist = new irtkHistogram_1D(double(min) ,double(max) ,1);

  for (int x=0; x < input.GetX(); ++x) {
    for (int y = 0; y < input.GetY(); y++) {
      for (int z = 0; z < input.GetZ(); z++) {
        hist->AddSample(input.Get(x,y,z));
      }
    }
  }

  // Write the histogram
  hist->Write(output_name);

  delete hist;
  return 0;

}
<commit_msg>Updated to reflect changes in histogram classes<commit_after>/*=========================================================================

  Library   : Image Registration Toolkit (IRTK)
  Module    : $Id$
  Copyright : Imperial College, Department of Computing
              Visual Information Processing (VIP), 2008 onwards
  Date      : $Date$
  Version   : $Revision$
  Changes   : $Author$

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

#include <irtkImage.h>

#include <irtkHistogram_1D.h>

void usage()
{
  cerr << "Creates a histogram for a specific image" << endl;
  cerr << "Usage: [input] [output] <options>\n" << endl;
  cerr << "where <options> is one or more of the following:\n" << endl;
  cerr << "<-Rx1 pixel>       Region of interest" << endl;
  cerr << "<-Ry1 pixel>       Region of interest" << endl;
  cerr << "<-Rz1 pixel>       Region of interest" << endl;
  cerr << "<-Rx2 pixel>       Region of interest" << endl;
  cerr << "<-Ry2 pixel>       Region of interest" << endl;
  cerr << "<-Rz2 pixel>       Region of interest" << endl;

  exit(1);
}

int main(int argc, char **argv)
{
  int ok, x1, y1, z1, x2, y2, z2;

  char *input_name = NULL;
  char *output_name = NULL;

  // Check command line
  if (argc < 2) {
    usage();
  }

  // Parse image
  input_name  = argv[1];
  argc--;
  argv++;

  // Parse output name
  output_name  = argv[1];
  argc--;
  argv++;

  // Read image
  cout << "Reading image ... "<<input_name <<endl;
  irtkGreyImage input;
  input.Read(input_name);
  cout << "done" << endl;

  // Fix ROI
  x1 = 0;
  y1 = 0;
  z1 = 0;
  x2 = input.GetX();
  y2 = input.GetY();
  z2 = input.GetZ();

  while (argc > 1) {
    ok = False;

    if ((ok == False) && (strcmp(argv[1], "-Rx1") == 0)) {
      argc--;
      argv++;
      x1 = atoi(argv[1]);
      argc--;
      argv++;
      ok = True;
    }
    if ((ok == False) && (strcmp(argv[1], "-Rx2") == 0)) {
      argc--;
      argv++;
      x2 = atoi(argv[1]);
      argc--;
      argv++;
      ok = True;
    }
    if ((ok == False) && (strcmp(argv[1], "-Ry1") == 0)) {
      argc--;
      argv++;
      y1 = atoi(argv[1]);
      argc--;
      argv++;
      ok = True;
    }
    if ((ok == False) && (strcmp(argv[1], "-Ry2") == 0)) {
      argc--;
      argv++;
      y2 = atoi(argv[1]);
      argc--;
      argv++;
      ok = True;
    }
    if ((ok == False) && (strcmp(argv[1], "-Rz1") == 0)) {
      argc--;
      argv++;
      z1 = atoi(argv[1]);
      argc--;
      argv++;
      ok = True;
    }
    if ((ok == False) && (strcmp(argv[1], "-Rz2") == 0)) {
      argc--;
      argv++;
      z2 = atoi(argv[1]);
      argc--;
      argv++;
      ok = True;
    }
    if (ok == False) {
      cerr << "Can not parse argument " << argv[1] << endl;
      usage();
    }
  }

  input = input.GetRegion(x1, y1, z1, x2, y2, z2);

  irtkGreyPixel min ;
  irtkGreyPixel max ;

  input.GetMinMax(&min,&max);

  cout<<"Creating the histogram"<<endl;
  // Create the histogram
  irtkHistogram_1D<int> *hist = new irtkHistogram_1D<int>(double(min), double(max), 1);

  for (int x=0; x < input.GetX(); ++x) {
    for (int y = 0; y < input.GetY(); y++) {
      for (int z = 0; z < input.GetZ(); z++) {
        hist->AddSample(input.Get(x,y,z));
      }
    }
  }

  // Write the histogram
  hist->Write(output_name);

  delete hist;
  return 0;

}
<|endoftext|>


<commit_before>// Copyright 2005 The RE2 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 tests to make sure numbers are parsed from strings
// correctly.
// Todo: Expand the test to validate strings parsed to the other types
// supported by RE2::Arg class

#include "util/test.h"
#include "re2/re2.h"

namespace re2 {

struct SuccessTable {
  const char * value_string;
  union {
    int64 value_int64;
    uint64 value_uint64;
    int value_int;
    uint32 value_uint32;
    int16 value_int16;
    uint16 value_uint16;
  };
  bool success[6];
};

// Test boundary cases for different integral sizes.
// Specifically I want to make sure that values outside the boundries
// of an integral type will fail and that negative numbers will fail
// for unsigned types. The following table contains the boundaries for
// the various integral types and has entries for whether or not each
// type can contain the given value.
const SuccessTable kSuccessTable[] = {
// string       integer value     short  ushort int    uint   int64  uint64
// 0 to 2^7-1
{ "0",          {0},            { true,  true,  true,  true,  true,  true  }},
{ "127",        {127},          { true,  true,  true,  true,  true,  true  }},

// -1 to -2^7
{ "-1",         {-1},           { true,  false, true,  false, true,  false }},
{ "-128",       {-128},         { true,  false, true,  false, true,  false }},

// 2^7 to 2^8-1
{ "128",        {128},          { true,  true,  true,  true,  true,  true, }},
{ "255",        {255},          { true,  true,  true,  true,  true,  true, }},

// 2^8 to 2^15-1
{ "256",        {256},          { true , true,  true,  true,  true,  true  }},
{ "32767",      {32767},        { true , true,  true,  true,  true,  true  }},

// -2^7-1 to -2^15
{ "-129",       {-129},         { true,  false, true,  false, true,  false }},
{ "-32768",     {-32768},       { true,  false, true,  false, true,  false }},

// 2^15 to 2^16-1
{ "32768",      {32768},        { false, true,  true,  true,  true,  true  }},
{ "65535",      {65535},        { false, true,  true,  true,  true,  true  }},

// 2^16 to 2^31-1
{ "65536",      {65536},        { false, false, true,  true,  true,  true  }},
{ "2147483647", {2147483647},   { false, false, true,  true,  true,  true  }},

// -2^15-1 to -2^31
{ "-32769",     {-32769},       { false, false, true,  false, true,  false }},
{ "-2147483648",
  {0xFFFFFFFF80000000LL},       { false, false, true,  false, true,  false }},

// 2^31 to 2^32-1
{ "2147483648", {2147483648U},  { false, false, false, true,  true,  true  }},
{ "4294967295", {4294967295U},  { false, false, false, true,  true,  true  }},

// 2^32 to 2^63-1
{ "4294967296", {4294967296LL}, { false, false, false, false, true,  true  }},
{ "9223372036854775807",
  {9223372036854775807LL},      { false, false, false, false, true,  true  }},

// -2^31-1 to -2^63
{ "-2147483649",{-2147483649LL},{ false, false, false, false, true,  false }},
{ "-9223372036854775808",
  {0x8000000000000000LL},       { false, false, false, false, true,  false }},

// 2^63 to 2^64-1
{ "9223372036854775808",
  {9223372036854775808ULL},      { false, false, false, false, false, true  }},
{ "18446744073709551615",
  {18446744073709551615ULL},    { false, false, false, false, false, true  }},

// >= 2^64
{ "18446744073709551616",
  {0},                     { false, false, false, false, false, false }},
};

const int kNumStrings = ARRAYSIZE(kSuccessTable);

// It's ugly to use a macro, but we apparently can't use the ASSERT_TRUE_M
// macro outside of a TEST block and this seems to be the only way to
// avoid code duplication.  I can also pull off a couple nice tricks
// using concatenation for the type I'm checking against.
#define PARSE_FOR_TYPE(type, column) {                                   \
  type r;                                                                \
  for ( int i = 0; i < kNumStrings; ++i ) {                              \
    RE2::Arg arg(&r);                                                    \
    const char* const p = kSuccessTable[i].value_string;                 \
    bool retval = arg.Parse(p, strlen(p));                               \
    bool success = kSuccessTable[i].success[column];                     \
    ASSERT_TRUE_M(retval == success,                                     \
      StringPrintf("Parsing '%s' for type " #type " should return %d",   \
                   p, success).c_str());                                 \
    if ( success ) {                                                     \
      ASSERT_EQUALS(r, kSuccessTable[i].value_##type);                                    \
    }                                                                    \
  }                                                                      \
}

TEST(REArgTest, Int16Test) {
  PARSE_FOR_TYPE(int16, 0);
}

TEST(REArgTest, Uint16Test) {
  PARSE_FOR_TYPE(uint16, 1);
}

TEST(REArgTest, IntTest) {
  PARSE_FOR_TYPE(int, 2);
}

TEST(REArgTest, UInt32Test) {
  PARSE_FOR_TYPE(uint32, 3);
}

TEST(REArgTest, Iint64Test) {
  PARSE_FOR_TYPE(int64, 4);
}

TEST(REArgTest, Uint64Test) {
  PARSE_FOR_TYPE(uint64, 5);
}

}  // namespace re2
<commit_msg>re2_arg_test: use a single int64 instead of a union in kSuccessTable. Union only works on little-endian machines.<commit_after>// Copyright 2005 The RE2 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 tests to make sure numbers are parsed from strings
// correctly.
// Todo: Expand the test to validate strings parsed to the other types
// supported by RE2::Arg class

#include "util/test.h"
#include "re2/re2.h"

namespace re2 {

struct SuccessTable {
  const char * value_string;
  int64 value;
  bool success[6];
};

// Test boundary cases for different integral sizes.
// Specifically I want to make sure that values outside the boundries
// of an integral type will fail and that negative numbers will fail
// for unsigned types. The following table contains the boundaries for
// the various integral types and has entries for whether or not each
// type can contain the given value.
const SuccessTable kSuccessTable[] = {
// string       integer value     short  ushort int    uint   int64  uint64
// 0 to 2^7-1
{ "0",          0,              { true,  true,  true,  true,  true,  true  }},
{ "127",        127,            { true,  true,  true,  true,  true,  true  }},

// -1 to -2^7
{ "-1",         -1,             { true,  false, true,  false, true,  false }},
{ "-128",       -128,           { true,  false, true,  false, true,  false }},

// 2^7 to 2^8-1
{ "128",        128,            { true,  true,  true,  true,  true,  true  }},
{ "255",        255,            { true,  true,  true,  true,  true,  true  }},

// 2^8 to 2^15-1
{ "256",        256,            { true,  true,  true,  true,  true,  true  }},
{ "32767",      32767,          { true,  true,  true,  true,  true,  true  }},

// -2^7-1 to -2^15
{ "-129",       -129,           { true,  false, true,  false, true,  false }},
{ "-32768",     -32768,         { true,  false, true,  false, true,  false }},

// 2^15 to 2^16-1
{ "32768",      32768,          { false, true,  true,  true,  true,  true  }},
{ "65535",      65535,          { false, true,  true,  true,  true,  true  }},

// 2^16 to 2^31-1
{ "65536",      65536,          { false, false, true,  true,  true,  true  }},
{ "2147483647", 2147483647,     { false, false, true,  true,  true,  true  }},

// -2^15-1 to -2^31
{ "-32769",     -32769,         { false, false, true,  false, true,  false }},
{ "-2147483648",
  0xFFFFFFFF80000000LL,         { false, false, true,  false, true,  false }},

// 2^31 to 2^32-1
{ "2147483648", 2147483648U,    { false, false, false, true,  true,  true  }},
{ "4294967295", 4294967295U,    { false, false, false, true,  true,  true  }},

// 2^32 to 2^63-1
{ "4294967296", 4294967296LL,   { false, false, false, false, true,  true  }},
{ "9223372036854775807",
  9223372036854775807LL,        { false, false, false, false, true,  true  }},

// -2^31-1 to -2^63
{ "-2147483649", -2147483649LL, { false, false, false, false, true,  false }},
{ "-9223372036854775808",
  0x8000000000000000LL,         { false, false, false, false, true,  false }},

// 2^63 to 2^64-1
{ "9223372036854775808",
  9223372036854775808ULL,       { false, false, false, false, false, true  }},
{ "18446744073709551615",
  18446744073709551615ULL,      { false, false, false, false, false, true  }},

// >= 2^64
{ "18446744073709551616", 0,    { false, false, false, false, false, false }},
};

const int kNumStrings = ARRAYSIZE(kSuccessTable);

// It's ugly to use a macro, but we apparently can't use the ASSERT_TRUE_M
// macro outside of a TEST block and this seems to be the only way to
// avoid code duplication.  I can also pull off a couple nice tricks
// using concatenation for the type I'm checking against.
#define PARSE_FOR_TYPE(type, column) {                                   \
  type r;                                                                \
  for ( int i = 0; i < kNumStrings; ++i ) {                              \
    RE2::Arg arg(&r);                                                    \
    const char* const p = kSuccessTable[i].value_string;                 \
    bool retval = arg.Parse(p, strlen(p));                               \
    bool success = kSuccessTable[i].success[column];                     \
    ASSERT_TRUE_M(retval == success,                                     \
      StringPrintf("Parsing '%s' for type " #type " should return %d",   \
                   p, success).c_str());                                 \
    if ( success ) {                                                     \
      ASSERT_EQUALS(r, kSuccessTable[i].value);                          \
    }                                                                    \
  }                                                                      \
}

TEST(REArgTest, Int16Test) {
  PARSE_FOR_TYPE(int16, 0);
}

TEST(REArgTest, Uint16Test) {
  PARSE_FOR_TYPE(uint16, 1);
}

TEST(REArgTest, IntTest) {
  PARSE_FOR_TYPE(int, 2);
}

TEST(REArgTest, UInt32Test) {
  PARSE_FOR_TYPE(uint32, 3);
}

TEST(REArgTest, Iint64Test) {
  PARSE_FOR_TYPE(int64, 4);
}

TEST(REArgTest, Uint64Test) {
  PARSE_FOR_TYPE(uint64, 5);
}

}  // namespace re2
<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2013
  \file      init_struct_db.cpp
  \authors     (cerevra@gmail.com)
  \authors     (rdo@rk9.bmstu.ru)
  \date      25.01.2013
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator\runtime\src\db\init_struct_db.h"
// --------------------------------------------------------------------------------

InitSructDB::InitSructDB()
{
	generateCreateDBQuery();
	queryExec(m_queryList);
}

void InitSructDB::dropDB()
{
	{
		GeneralDB dbTemp("localhost", "postgres", "postgres", "rdo", 5432);
		dbTemp.queryExec("DROP DATABASE IF EXISTS rdo;");
	}
	QSqlDatabase::removeDatabase("qt_sql_default_connection");
}

void InitSructDB::createDB()
{
	{
		GeneralDB dbTemp("localhost", "postgres", "postgres", "rdo", 5432);
		dbTemp.queryExec("CREATE DATABASE rdo;");
	}
	QSqlDatabase::removeDatabase("qt_sql_default_connection");
}

void InitSructDB::rdoValueTable(QString tableName, QString dataType)
{
	m_queryList.push_back(QString(
		"CREATE TABLE %1("
		"id integer NOT NULL DEFAULT nextval('rdo_value_seq'),"
		"vv %2 NOT NULL,"
		"PRIMARY KEY (id)"
		");")
		.arg(tableName)
		.arg(dataType));

	trigger(tableName,"copy_rdo_value_id");
}

void InitSructDB::dataTypeTable(QString tableName)
{
	m_queryList.push_back(QString(
		"CREATE TABLE %1("
		"id      integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES %1_rv(id)"
		");")
		.arg(tableName));

	trigger(tableName,"copy_type_id");
}

void InitSructDB::trigger(QString tableName, QString functionName)
{
	m_queryList.push_back(QString(
		"CREATE TRIGGER %1_trig "
		"AFTER INSERT ON %1 "
		"FOR EACH ROW "
		"EXECUTE PROCEDURE %2();")
		.arg(tableName)
		.arg(functionName));
}

void InitSructDB::generateCreateDBQuery()
{
	m_queryList.push_back(
		"CREATE TABLE rtp("
		"id       serial,"
		"rtp_name VARCHAR(40) NOT NULL,"
		"rtp_perm boolean NOT NULL,"
		"PRIMARY KEY (id)"
		");");

	m_queryList.push_back(
		"CREATE TABLE list_of_types_of_params("
		"type_id  integer,"
		"table_id integer NOT NULL,"
		"PRIMARY KEY (type_id)"
		");");

	m_queryList.push_back(
		"CREATE TABLE param_of_type("
		"id          serial,"
		"param_name  VARCHAR(40) NOT NULL,"
		"rtp_id      integer,"
		"type_id     integer NOT NULL,"
		"PRIMARY KEY (id,rtp_id),"
		"FOREIGN KEY (rtp_id) REFERENCES rtp(id),"
		"FOREIGN KEY (type_id) REFERENCES list_of_types_of_params"
		");");
//------------------------

//------------------------
	m_queryList.push_back("CREATE SEQUENCE type_of_param_seq;");

	m_queryList.push_back(
		"CREATE FUNCTION copy_type_id() RETURNS TRIGGER AS $trig$ "
		"BEGIN "
		"INSERT INTO list_of_types_of_params VALUES "
		"(NEW.id, NEW.tableoid); "
		"RETURN NULL; "
		"END; "
		"$trig$ LANGUAGE plpgsql; ");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE rdo_value("
		"value_id  integer,"
		"table_id integer NOT NULL,"
		"PRIMARY KEY (value_id)"
		");");

	m_queryList.push_back("CREATE SEQUENCE rdo_value_seq;");

	m_queryList.push_back(
		"CREATE FUNCTION copy_rdo_value_id() RETURNS TRIGGER AS $trig$ "
		"BEGIN "
		"INSERT INTO rdo_value VALUES "
		"(NEW.id, NEW.tableoid); "
		"RETURN NULL; "
		"END; "
		"$trig$ LANGUAGE plpgsql; ");

	rdoValueTable("real_rv","real");
	rdoValueTable("int_rv","integer");
	rdoValueTable("identificator_rv","VARCHAR(40)");
	rdoValueTable("bool_rv","boolean");
	rdoValueTable("string_rv","VARCHAR(40)");
	rdoValueTable("enum_rv","VARCHAR(40)");

	m_queryList.push_back(
		"CREATE TABLE array_rv("
		"id  integer NOT NULL DEFAULT nextval('rdo_value_seq'),"
		"PRIMARY KEY (id)"
		");");

	trigger("array_rv","copy_rdo_value_id");

	m_queryList.push_back(
		"CREATE TABLE array_value("
		"array_id      integer,"
		"array_elem_id serial,"
		"vv_id         integer NOT NULL,"
		"PRIMARY KEY   (array_id, vv_id),"
		"FOREIGN KEY   (array_id) REFERENCES array_rv"
		");");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE real("
		"id          integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val     integer,"
		"min         integer,"
		"max         integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES real_rv(id),"
		"FOREIGN KEY (min) REFERENCES real_rv(id),"
		"FOREIGN KEY (max) REFERENCES real_rv(id)"
		");");

	trigger("real","copy_type_id");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE enum("
		"id          integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val     integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES enum_rv(id)"
		");");

	trigger("enum","copy_type_id");

	m_queryList.push_back(
		"CREATE TABLE enum_valid_value("
		"enum_id     integer,"
		"vv_id       serial,"
		"vv_str      VARCHAR(40) NOT NULL,"
		"vv_int      integer NOT NULL,"
		"PRIMARY KEY (enum_id, vv_id),"
		"FOREIGN KEY (enum_id) REFERENCES enum"
		");");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE int("
		"id          integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val     integer,"
		"min         integer,"
		"max         integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES int_rv(id),"
		"FOREIGN KEY (min) REFERENCES int_rv(id),"
		"FOREIGN KEY (max) REFERENCES int_rv(id)"
		");");

	trigger("int","copy_type_id");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE void("
		"id      integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"PRIMARY KEY (id)"
		");");

	trigger("void","copy_type_id");
//------------------------

	dataTypeTable("identificator");
	dataTypeTable("bool");
	dataTypeTable("string");
}
<commit_msg> - структура БД: rss и параметры<commit_after>/*!
  \copyright (c) RDO-Team, 2013
  \file      init_struct_db.cpp
  \authors     (cerevra@gmail.com)
  \authors     (rdo@rk9.bmstu.ru)
  \date      25.01.2013
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator\runtime\src\db\init_struct_db.h"
// --------------------------------------------------------------------------------

InitSructDB::InitSructDB()
{
	generateCreateDBQuery();
	queryExec(m_queryList);
}

void InitSructDB::dropDB()
{
	{
		GeneralDB dbTemp("localhost", "postgres", "postgres", "rdo", 5432);
		dbTemp.queryExec("DROP DATABASE IF EXISTS rdo;");
	}
	QSqlDatabase::removeDatabase("qt_sql_default_connection");
}

void InitSructDB::createDB()
{
	{
		GeneralDB dbTemp("localhost", "postgres", "postgres", "rdo", 5432);
		dbTemp.queryExec("CREATE DATABASE rdo;");
	}
	QSqlDatabase::removeDatabase("qt_sql_default_connection");
}

void InitSructDB::rdoValueTable(QString tableName, QString dataType)
{
	m_queryList.push_back(QString(
		"CREATE TABLE %1("
		"id integer NOT NULL DEFAULT nextval('rdo_value_seq'),"
		"vv %2 NOT NULL,"
		"PRIMARY KEY (id)"
		");")
		.arg(tableName)
		.arg(dataType));

	trigger(tableName,"copy_rdo_value_id");
}

void InitSructDB::dataTypeTable(QString tableName)
{
	m_queryList.push_back(QString(
		"CREATE TABLE %1("
		"id      integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES %1_rv(id)"
		");")
		.arg(tableName));

	trigger(tableName,"copy_type_id");
}

void InitSructDB::trigger(QString tableName, QString functionName)
{
	m_queryList.push_back(QString(
		"CREATE TRIGGER %1_trig "
		"AFTER INSERT ON %1 "
		"FOR EACH ROW "
		"EXECUTE PROCEDURE %2();")
		.arg(tableName)
		.arg(functionName));
}

void InitSructDB::generateCreateDBQuery()
{
	m_queryList.push_back(
		"CREATE TABLE rtp("
		"id       serial,"
		"rtp_name VARCHAR(40) NOT NULL,"
		"rtp_perm boolean NOT NULL,"
		"PRIMARY KEY (id)"
		");");

	m_queryList.push_back(
		"CREATE TABLE list_of_types_of_params("
		"type_id  integer,"
		"table_id integer NOT NULL,"
		"PRIMARY KEY (type_id)"
		");");

	m_queryList.push_back(
		"CREATE TABLE param_of_type("
		"id          serial,"
		"param_name  VARCHAR(40) NOT NULL,"
		"rtp_id      integer,"
		"type_id     integer NOT NULL,"
		"PRIMARY KEY (id,rtp_id),"
		"FOREIGN KEY (rtp_id) REFERENCES rtp(id),"
		"FOREIGN KEY (type_id) REFERENCES list_of_types_of_params"
		");");
//------------------------

//------------------------
	m_queryList.push_back("CREATE SEQUENCE type_of_param_seq;");

	m_queryList.push_back(
		"CREATE FUNCTION copy_type_id() RETURNS TRIGGER AS $trig$ "
		"BEGIN "
		"INSERT INTO list_of_types_of_params VALUES "
		"(NEW.id, NEW.tableoid); "
		"RETURN NULL; "
		"END; "
		"$trig$ LANGUAGE plpgsql; ");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE rdo_value("
		"value_id  integer,"
		"table_id integer NOT NULL,"
		"PRIMARY KEY (value_id)"
		");");

	m_queryList.push_back("CREATE SEQUENCE rdo_value_seq;");

	m_queryList.push_back(
		"CREATE FUNCTION copy_rdo_value_id() RETURNS TRIGGER AS $trig$ "
		"BEGIN "
		"INSERT INTO rdo_value VALUES "
		"(NEW.id, NEW.tableoid); "
		"RETURN NULL; "
		"END; "
		"$trig$ LANGUAGE plpgsql; ");

	rdoValueTable("real_rv","real");
	rdoValueTable("int_rv","integer");
	rdoValueTable("identificator_rv","VARCHAR(40)");
	rdoValueTable("bool_rv","boolean");
	rdoValueTable("string_rv","VARCHAR(40)");
	rdoValueTable("enum_rv","VARCHAR(40)");

	m_queryList.push_back(
		"CREATE TABLE array_rv("
		"id  integer NOT NULL DEFAULT nextval('rdo_value_seq'),"
		"PRIMARY KEY (id)"
		");");

	trigger("array_rv","copy_rdo_value_id");

	m_queryList.push_back(
		"CREATE TABLE array_value("
		"array_id      integer,"
		"array_elem_id serial,"
		"vv_id         integer NOT NULL,"
		"PRIMARY KEY   (array_id, vv_id),"
		"FOREIGN KEY   (array_id) REFERENCES array_rv"
		");");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE real("
		"id          integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val     integer,"
		"min         integer,"
		"max         integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES real_rv(id),"
		"FOREIGN KEY (min) REFERENCES real_rv(id),"
		"FOREIGN KEY (max) REFERENCES real_rv(id)"
		");");

	trigger("real","copy_type_id");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE enum("
		"id          integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val     integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES enum_rv(id)"
		");");

	trigger("enum","copy_type_id");

	m_queryList.push_back(
		"CREATE TABLE enum_valid_value("
		"enum_id     integer,"
		"vv_id       serial,"
		"vv_str      VARCHAR(40) NOT NULL,"
		"vv_int      integer NOT NULL,"
		"PRIMARY KEY (enum_id, vv_id),"
		"FOREIGN KEY (enum_id) REFERENCES enum"
		");");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE int("
		"id          integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val     integer,"
		"min         integer,"
		"max         integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES int_rv(id),"
		"FOREIGN KEY (min) REFERENCES int_rv(id),"
		"FOREIGN KEY (max) REFERENCES int_rv(id)"
		");");

	trigger("int","copy_type_id");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE void("
		"id      integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"PRIMARY KEY (id)"
		");");

	trigger("void","copy_type_id");

	dataTypeTable("identificator");
	dataTypeTable("bool");
	dataTypeTable("string");
//------------------------

	m_queryList.push_back(
		"CREATE TABLE rss("
		"id      serial,"
		"rtp_id  integer NOT NULL,"
		"name    VARCHAR(40) NOT NULL,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (rtp_id) REFERENCES rtp(id)"
		");");

	m_queryList.push_back(
		"CREATE TABLE rss_param("
		"id       serial,"
		"rss_id   integer NOT NULL,"
		"param_id integer NOT NULL,"
		"value    integer NOT NULL,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (rss_id) REFERENCES rss(id),"
		"FOREIGN KEY (param_id) REFERENCES rsparam_of_types(id),"
		"FOREIGN KEY (value) REFERENCES rdo_value(value_id)"
		");");
}
<|endoftext|>


<commit_before>// ImportDlg.cpp : implementation file
//

#include "stdafx.h"
#include "passwordsafe.h"
#include "ImportDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CImportDlg dialog

CImportDlg::CImportDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CImportDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CImportDlg)
	m_groupName = _T("Imported");
	m_Separator = _T("|");
	m_tab = 0;
	m_group = 0;
	//}}AFX_DATA_INIT
}

void CImportDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CImportDlg)
	DDX_Text(pDX, IDC_GROUP_NAME, m_groupName);
	DDX_Text(pDX, IDC_OTHER_SEPARATOR, m_Separator);
	DDV_MaxChars(pDX, m_Separator, 1);
	DDX_Radio(pDX, IDC_TAB, m_tab);
	DDX_Radio(pDX, IDC_NO_GROUP, m_group);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CImportDlg, CDialog)
	//{{AFX_MSG_MAP(CImportDlg)
	ON_BN_CLICKED(IDC_OTHER, OnOther)
	ON_BN_CLICKED(IDC_COMMA, OnComma)
	ON_BN_CLICKED(IDC_TAB, OnTab)
	ON_BN_CLICKED(IDC_NO_GROUP, OnNoGroup)
	ON_BN_CLICKED(IDC_YES_GROUP, OnYesGroup)
	ON_BN_CLICKED(ID_HELP, OnHelp)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CImportDlg message handlers

void CImportDlg::OnOther()
{
  GetDlgItem(IDC_OTHER_SEPARATOR)->EnableWindow(TRUE);
}

void CImportDlg::OnComma()
{
  GetDlgItem(IDC_OTHER_SEPARATOR)->EnableWindow(FALSE);
  m_Separator = _T(",");
}

void CImportDlg::OnTab()
{
  GetDlgItem(IDC_OTHER_SEPARATOR)->EnableWindow(FALSE);
  m_Separator = _T("\t");
}

void CImportDlg::OnNoGroup()
{
  GetDlgItem(IDC_GROUP_NAME)->EnableWindow(FALSE);
  m_groupName = _T("");
}

void CImportDlg::OnYesGroup()
{
  GetDlgItem(IDC_GROUP_NAME)->EnableWindow(TRUE);
}

void CImportDlg::OnHelp()
{
   ::HtmlHelp(NULL,
              "pwsafe.chm::/html/import.html",
              HH_DISPLAY_TOPIC, 0);
}

void CImportDlg::OnOK()
{
  switch (m_tab) {
  case 0: m_Separator = _T("\t"); UpdateData(FALSE); break;
  case 1: m_Separator = _T(","); UpdateData(FALSE); break;
  default: break; // m_Separator will get value from edit control
  }

  if (m_group == 0) {
    m_groupName = _T("");
    UpdateData(FALSE);
  }

  CDialog::OnOK();
}
<commit_msg>[1145747] The import delimiter is now changeable (Thanks to Roger Hakansson for the patch).<commit_after>// ImportDlg.cpp : implementation file
//

#include "stdafx.h"
#include "passwordsafe.h"
#include "ImportDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CImportDlg dialog

CImportDlg::CImportDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CImportDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CImportDlg)
	m_groupName = _T("Imported");
	m_Separator = _T("|");
	m_tab = 0;
	m_group = 0;
	//}}AFX_DATA_INIT
}

void CImportDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CImportDlg)
	DDX_Text(pDX, IDC_GROUP_NAME, m_groupName);
	DDX_Text(pDX, IDC_OTHER_SEPARATOR, m_Separator);
	DDV_MaxChars(pDX, m_Separator, 1);
	DDX_Radio(pDX, IDC_TAB, m_tab);
	DDX_Radio(pDX, IDC_NO_GROUP, m_group);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CImportDlg, CDialog)
	//{{AFX_MSG_MAP(CImportDlg)
	ON_BN_CLICKED(IDC_OTHER, OnOther)
	ON_BN_CLICKED(IDC_COMMA, OnComma)
	ON_BN_CLICKED(IDC_TAB, OnTab)
	ON_BN_CLICKED(IDC_NO_GROUP, OnNoGroup)
	ON_BN_CLICKED(IDC_YES_GROUP, OnYesGroup)
	ON_BN_CLICKED(ID_HELP, OnHelp)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CImportDlg message handlers

void CImportDlg::OnOther()
{
  GetDlgItem(IDC_OTHER_SEPARATOR)->EnableWindow(TRUE);
  m_tab=2;
}

void CImportDlg::OnComma()
{
  GetDlgItem(IDC_OTHER_SEPARATOR)->EnableWindow(FALSE);
  m_tab=1;
}

void CImportDlg::OnTab()
{
  GetDlgItem(IDC_OTHER_SEPARATOR)->EnableWindow(FALSE);
  m_tab=0;
}

void CImportDlg::OnNoGroup()
{
  GetDlgItem(IDC_GROUP_NAME)->EnableWindow(FALSE);
  m_group=0;
}

void CImportDlg::OnYesGroup()
{
  GetDlgItem(IDC_GROUP_NAME)->EnableWindow(TRUE);
  m_group=1;
}

void CImportDlg::OnHelp()
{
   ::HtmlHelp(NULL,
              "pwsafe.chm::/html/import.html",
              HH_DISPLAY_TOPIC, 0);
}

void CImportDlg::OnOK()
{
  switch (m_tab) {
    case 0: m_Separator = _T("\t"); break;
    case 1: m_Separator = _T(","); break;
    case 2: GetDlgItemText(IDC_OTHER_SEPARATOR,m_Separator); break;
    default: break; // m_Separator will get value from edit control
  }

  if (m_group == 0) {
    m_groupName = _T("");
    UpdateData(FALSE);
  } else {
    GetDlgItemText(IDC_GROUP_NAME,m_groupName);
    UpdateData(FALSE);
  }

  CDialog::OnOK();
}
<|endoftext|>


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

  Program:   Visualization Library
  Module:    DataSet.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
//
// DataSet methods
//
#include <math.h>
#include "DataSet.hh"

// Description:
// Constructor with default bounds (0,1, 0,1, 0,1).
vlDataSet::vlDataSet ()
{
  this->Bounds[0] = 0.0;
  this->Bounds[1] = 1.0;
  this->Bounds[2] = 0.0;
  this->Bounds[3] = 1.0;
  this->Bounds[4] = 0.0;
  this->Bounds[5] = 1.0;
}

// Description:
// Copy constructor.
vlDataSet::vlDataSet (const vlDataSet& ds) :
PointData(ds.PointData)
{
  for (int i=0; i < 6; i++) this->Bounds[i] = ds.Bounds[i];
}

void vlDataSet::Initialize()
{
  this->PointData.Initialize();
  this->Modified();
};

// Description:
// Compute the data bounding box from data points.
void vlDataSet::ComputeBounds()
{
  int i, j;
  float *x;

  if ( this->GetMTime() > this->ComputeTime )
    {
    this->Bounds[0] = this->Bounds[2] = this->Bounds[4] =  LARGE_FLOAT;
    this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -LARGE_FLOAT;
    for (i=0; i<this->GetNumberOfPoints(); i++)
      {
      x = this->GetPoint(i);
      for (j=0; j<3; j++)
        {
        if ( x[j] < this->Bounds[2*j] ) this->Bounds[2*j] = x[j];
        if ( x[j] > this->Bounds[2*j+1] ) this->Bounds[2*j+1] = x[j];
        }
      }

    this->ComputeTime.Modified();
    }
}

// Description:
// Return a pointer to the geometry bounding box in the form
// (xmin,xmax, ymin,ymax, zmin,zmax).
float *vlDataSet::GetBounds()
{
  this->ComputeBounds();
  return this->Bounds;
}

void vlDataSet::GetBounds(float bounds[6])
{
  this->ComputeBounds();
  for (i=0; i<6; i++) bounds[i] = this->Bounds[i];
}

// Description:
// Get the center of the bounding box.
float *vlDataSet::GetCenter()
{
  static float center[3];

  this->ComputeBounds();
  for (int i=0; i<3; i++)
    center[i] = (this->Bounds[2*i+1] + this->Bounds[2*i]) / 2.0;
  return center;
}

void vlDataSet::GetCenter(float center[3])
{
  float *c=this->GetCenter();
  for (i=0; i<3; i++) center[i] = c[i];
}

// Description:
// Return the length of the diagonal of the bounding box.
float vlDataSet::GetLength()
{
  double diff, l=0.0;
  int i;

  this->ComputeBounds();
  for (i=0; i<3; i++)
    {
    diff = this->Bounds[2*i+1] - this->Bounds[2*i];
    l += diff * diff;
    }

  return (float)sqrt(l);
}

unsigned long int vlDataSet::GetMTime()
{
  if ( this->PointData.GetMTime() > this->MTime ) return this->PointData.GetMTime();
  else return this->MTime;
}

void vlDataSet::PrintSelf(ostream& os, vlIndent indent)
{
  if (this->ShouldIPrint(vlDataSet::GetClassName()))
    {
    float *bounds;

    vlObject::PrintSelf(os,indent);

    os << indent << "Number Of Points: " << this->GetNumberOfPoints() << "\n";
    os << indent << "Number Of Cells: " << this->GetNumberOfCells() << "\n";
    os << indent << "Point Data:\n";
    this->PointData.PrintSelf(os,indent.GetNextIndent());
    bounds = this->GetBounds();
    os << indent << "Bounds: \n";
    os << indent << "  Xmin,Xmax: (" <<bounds[0] << ", " << bounds[1] << ")\n";
    os << indent << "  Ymin,Ymax: (" <<bounds[2] << ", " << bounds[3] << ")\n";
    os << indent << "  Zmin,Zmax: (" <<bounds[4] << ", " << bounds[5] << ")\n";
    os << indent << "Compute Time: " <<this->ComputeTime.GetMTime() << "\n";
    }
}

void vlDataSet::GetCellNeighbors(int cellId, vlIdList &ptIds,
                                 vlIdList &cellIds)
{
  int i;
  vlIdList otherCells(MAX_CELL_SIZE);

  // load list with candidate cells, remove current cell
  this->GetPointCells(ptIds.GetId(0),cellIds);
  cellIds.DeleteId(cellId);

  // now perform multiple intersections on list
  if ( cellIds.GetNumberOfIds() > 0 )
    {
    for ( i=1; i < ptIds.GetNumberOfIds(); i++)
      {
      this->GetPointCells(ptIds.GetId(i), otherCells);
      cellIds.IntersectWith(otherCells);
      }
    }
}

void vlDataSet::Squeeze()
{
  this->PointData.Squeeze();
}
<commit_msg>*** empty log message ***<commit_after>/*=========================================================================

  Program:   Visualization Library
  Module:    DataSet.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
//
// DataSet methods
//
#include <math.h>
#include "DataSet.hh"

// Description:
// Constructor with default bounds (0,1, 0,1, 0,1).
vlDataSet::vlDataSet ()
{
  this->Bounds[0] = 0.0;
  this->Bounds[1] = 1.0;
  this->Bounds[2] = 0.0;
  this->Bounds[3] = 1.0;
  this->Bounds[4] = 0.0;
  this->Bounds[5] = 1.0;
}

// Description:
// Copy constructor.
vlDataSet::vlDataSet (const vlDataSet& ds) :
PointData(ds.PointData)
{
  for (int i=0; i < 6; i++) this->Bounds[i] = ds.Bounds[i];
}

void vlDataSet::Initialize()
{
  this->PointData.Initialize();
  this->Modified();
};

// Description:
// Compute the data bounding box from data points.
void vlDataSet::ComputeBounds()
{
  int i, j;
  float *x;

  if ( this->GetMTime() > this->ComputeTime )
    {
    this->Bounds[0] = this->Bounds[2] = this->Bounds[4] =  LARGE_FLOAT;
    this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -LARGE_FLOAT;
    for (i=0; i<this->GetNumberOfPoints(); i++)
      {
      x = this->GetPoint(i);
      for (j=0; j<3; j++)
        {
        if ( x[j] < this->Bounds[2*j] ) this->Bounds[2*j] = x[j];
        if ( x[j] > this->Bounds[2*j+1] ) this->Bounds[2*j+1] = x[j];
        }
      }

    this->ComputeTime.Modified();
    }
}

// Description:
// Return a pointer to the geometry bounding box in the form
// (xmin,xmax, ymin,ymax, zmin,zmax).
float *vlDataSet::GetBounds()
{
  this->ComputeBounds();
  return this->Bounds;
}

void vlDataSet::GetBounds(float bounds[6])
{
  this->ComputeBounds();
  for (int i=0; i<6; i++) bounds[i] = this->Bounds[i];
}

// Description:
// Get the center of the bounding box.
float *vlDataSet::GetCenter()
{
  static float center[3];

  this->ComputeBounds();
  for (int i=0; i<3; i++)
    center[i] = (this->Bounds[2*i+1] + this->Bounds[2*i]) / 2.0;
  return center;
}

void vlDataSet::GetCenter(float center[3])
{
  float *c=this->GetCenter();
  for (int i=0; i<3; i++) center[i] = c[i];
}

// Description:
// Return the length of the diagonal of the bounding box.
float vlDataSet::GetLength()
{
  double diff, l=0.0;
  int i;

  this->ComputeBounds();
  for (i=0; i<3; i++)
    {
    diff = this->Bounds[2*i+1] - this->Bounds[2*i];
    l += diff * diff;
    }

  return (float)sqrt(l);
}

unsigned long int vlDataSet::GetMTime()
{
  if ( this->PointData.GetMTime() > this->MTime ) return this->PointData.GetMTime();
  else return this->MTime;
}

void vlDataSet::PrintSelf(ostream& os, vlIndent indent)
{
  if (this->ShouldIPrint(vlDataSet::GetClassName()))
    {
    float *bounds;

    vlObject::PrintSelf(os,indent);

    os << indent << "Number Of Points: " << this->GetNumberOfPoints() << "\n";
    os << indent << "Number Of Cells: " << this->GetNumberOfCells() << "\n";
    os << indent << "Point Data:\n";
    this->PointData.PrintSelf(os,indent.GetNextIndent());
    bounds = this->GetBounds();
    os << indent << "Bounds: \n";
    os << indent << "  Xmin,Xmax: (" <<bounds[0] << ", " << bounds[1] << ")\n";
    os << indent << "  Ymin,Ymax: (" <<bounds[2] << ", " << bounds[3] << ")\n";
    os << indent << "  Zmin,Zmax: (" <<bounds[4] << ", " << bounds[5] << ")\n";
    os << indent << "Compute Time: " <<this->ComputeTime.GetMTime() << "\n";
    }
}

void vlDataSet::GetCellNeighbors(int cellId, vlIdList &ptIds,
                                 vlIdList &cellIds)
{
  int i;
  vlIdList otherCells(MAX_CELL_SIZE);

  // load list with candidate cells, remove current cell
  this->GetPointCells(ptIds.GetId(0),cellIds);
  cellIds.DeleteId(cellId);

  // now perform multiple intersections on list
  if ( cellIds.GetNumberOfIds() > 0 )
    {
    for ( i=1; i < ptIds.GetNumberOfIds(); i++)
      {
      this->GetPointCells(ptIds.GetId(i), otherCells);
      cellIds.IntersectWith(otherCells);
      }
    }
}

void vlDataSet::Squeeze()
{
  this->PointData.Squeeze();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>

#include "geometry_msgs/PoseArray.h"
#include "pcl/filters/filter.h"
#include "pcl/point_cloud.h"
#include "pcl/point_types.h"
#include "pcl_conversions/pcl_conversions.h"
#include "pcl_ros/transforms.h"
#include "rapid_db/name_db.hpp"
#include "rapid_msgs/GetStaticCloud.h"
#include "rapid_msgs/ListStaticClouds.h"
#include "rapid_msgs/RemoveStaticCloud.h"
#include "rapid_msgs/SaveStaticCloud.h"
#include "rapid_perception/box3d_roi_server.h"
#include "rapid_perception/grouping_pose_estimator.h"
#include "rapid_perception/pose_estimation.h"
#include "rapid_perception/random_heat_mapper.h"
#include "rapid_perception/ransac_pose_estimator.h"
#include "rapid_ros/publisher.h"
#include "rapid_utils/command_line.h"
#include "ros/ros.h"
#include "sensor_msgs/PointCloud2.h"
#include "visualization_msgs/Marker.h"
#include "visualization_msgs/MarkerArray.h"

#include "object_search/capture_roi.h"
#include "object_search/commands.h"
#include "object_search/cloud_database.h"
#include "object_search/estimators.h"

using sensor_msgs::PointCloud2;
using pcl::PointCloud;
using pcl::PointXYZRGB;
using visualization_msgs::Marker;

using namespace object_search;

int main(int argc, char** argv) {
  ros::init(argc, argv, "object_search");
  ros::NodeHandle nh;
  ros::AsyncSpinner spinner(4);
  spinner.start();

  // Build databases
  ros::ServiceClient get_cloud =
      nh.serviceClient<rapid_msgs::GetStaticCloud>("get_static_cloud");
  ros::ServiceClient list_clouds =
      nh.serviceClient<rapid_msgs::ListStaticClouds>("list_static_clouds");
  ros::ServiceClient remove_cloud =
      nh.serviceClient<rapid_msgs::RemoveStaticCloud>("remove_static_cloud");
  ros::ServiceClient save_cloud =
      nh.serviceClient<rapid_msgs::SaveStaticCloud>("save_static_cloud");
  Database object_db("object_search", "objects", get_cloud, list_clouds,
                     remove_cloud, save_cloud);
  Database scene_db("object_search", "scenes", get_cloud, list_clouds,
                    remove_cloud, save_cloud);
  rapid::db::NameDb scene_ndb(nh, "custom_landmarks", "scenes");
  rapid::db::NameDb scene_cloud_ndb(nh, "custom_landmarks", "scene_clouds");
  rapid::db::NameDb landmark_ndb(nh, "custom_landmarks", "landmarks");
  rapid::db::NameDb landmark_cloud_ndb(nh, "custom_landmarks",
                                       "landmark_clouds");

  // Visualization publishers
  ros::Publisher object_pub = nh.advertise<PointCloud2>("/landmark", 1, true);
  ros::Publisher scene_pub = nh.advertise<PointCloud2>("/scene", 1, true);
  ros::Publisher heatmap_pub = nh.advertise<PointCloud2>("/heatmap", 1, true);
  ros::Publisher candidates_pub =
      nh.advertise<PointCloud2>("/candidate_samples", 1, true);
  ros::Publisher alignment_pub =
      nh.advertise<PointCloud2>("/alignment", 1, true);
  ros::Publisher output_pub = nh.advertise<PointCloud2>("/output", 1, true);
  rapid_ros::Publisher<visualization_msgs::Marker> marker_pub(
      nh.advertise<visualization_msgs::Marker>("/visualization_markers", 1,
                                               true));

  // Build ROI server
  rapid::perception::Box3DRoiServer roi_server("roi");
  CaptureRoi capture(&roi_server);

  // Build heat mapper
  // rapid::perception::FpfhHeatMapper* heat_mapper =
  //    new rapid::perception::FpfhHeatMapper();
  // heat_mapper->set_name("fpfh");

  // rapid::perception::TemplateMatchingHeatMapper* heat_mapper =
  //    new rapid::perception::TemplateMatchingHeatMapper();
  // heat_mapper->set_name("template_matching");

  rapid::perception::RandomHeatMapper* heat_mapper =
      new rapid::perception::RandomHeatMapper();
  heat_mapper->set_name("random");
  heat_mapper->set_heatmap_publisher(heatmap_pub);

  // Build pose estimator
  rapid::perception::PoseEstimator pose_estimator(heat_mapper);
  pose_estimator.set_candidates_publisher(candidates_pub);
  pose_estimator.set_alignment_publisher(alignment_pub);
  pose_estimator.set_marker_publisher(&marker_pub);

  rapid::perception::RansacPoseEstimator ransac_estimator;
  ros::Publisher pose_pub =
      nh.advertise<geometry_msgs::PoseArray>("/poses", 1, true);
  ransac_estimator.set_pose_publisher(pose_pub);

  rapid::perception::GroupingPoseEstimator grouping_estimator;
  ros::Publisher corr_pub = nh.advertise<visualization_msgs::MarkerArray>(
      "/correspondences", 1, true);
  ros::Publisher object_keypoints_pub =
      nh.advertise<PointCloud2>("/landmark_keypoints", 1, true);
  ros::Publisher scene_keypoints_pub =
      nh.advertise<PointCloud2>("/scene_keypoints", 1, true);
  grouping_estimator.set_correspondence_publisher(corr_pub);
  grouping_estimator.set_scene_keypoints_publisher(scene_keypoints_pub);
  grouping_estimator.set_object_keypoints_publisher(object_keypoints_pub);

  Estimators estimators;
  estimators.custom = &pose_estimator;
  estimators.ransac = &ransac_estimator;
  estimators.grouping = &grouping_estimator;

  // Build visualizers

  // Build command line
  ListCommand list_landmarks(&landmark_ndb, ListCommand::kLandmarks);
  ListCommand list_scenes(&scene_ndb, ListCommand::kScenes);
  RecordObjectCommand record_object(&object_db, &capture);
  RecordSceneCommand record_scene(&scene_ndb, &scene_cloud_ndb);
  DeleteCommand delete_object(&object_db, "delete object",
                              "<name> - Delete an object");
  DeleteCommand delete_scene(&scene_db, "delete scene",
                             "<name> - Delete a scene");
  UseCommand use_object(&object_db, &estimators, "object", object_pub);
  UseCommand use_scene(&scene_db, &estimators, "scene", scene_pub);
  RunCommand run(&estimators, output_pub);
  SetDebugCommand set_debug(&estimators);

  rapid::utils::CommandLine scene_cli("Scene manager");
  scene_cli.AddCommand(&list_scenes);
  scene_cli.AddCommand(&record_scene);
  scene_cli.AddCommand(&delete_scene);

  EditScenesCommand edit_scenes(scene_cli);

  rapid::utils::CommandLine cli("Custom landmarks CLI");
  cli.AddCommand(&edit_scenes);
  cli.AddCommand(&list_landmarks);
  cli.AddCommand(&record_object);
  cli.AddCommand(&delete_object);
  cli.AddCommand(&use_object);
  cli.AddCommand(&use_scene);
  cli.AddCommand(&run);
  cli.AddCommand(&set_debug);

  while (cli.Next()) {
  }

  spinner.stop();
  return 0;
}
<commit_msg>Use exit command for CLIs.<commit_after>#include <iostream>
#include <string>

#include "geometry_msgs/PoseArray.h"
#include "pcl/filters/filter.h"
#include "pcl/point_cloud.h"
#include "pcl/point_types.h"
#include "pcl_conversions/pcl_conversions.h"
#include "pcl_ros/transforms.h"
#include "rapid_db/name_db.hpp"
#include "rapid_msgs/GetStaticCloud.h"
#include "rapid_msgs/ListStaticClouds.h"
#include "rapid_msgs/RemoveStaticCloud.h"
#include "rapid_msgs/SaveStaticCloud.h"
#include "rapid_perception/box3d_roi_server.h"
#include "rapid_perception/grouping_pose_estimator.h"
#include "rapid_perception/pose_estimation.h"
#include "rapid_perception/random_heat_mapper.h"
#include "rapid_perception/ransac_pose_estimator.h"
#include "rapid_ros/publisher.h"
#include "rapid_utils/command_line.h"
#include "ros/ros.h"
#include "sensor_msgs/PointCloud2.h"
#include "visualization_msgs/Marker.h"
#include "visualization_msgs/MarkerArray.h"

#include "object_search/capture_roi.h"
#include "object_search/commands.h"
#include "object_search/cloud_database.h"
#include "object_search/estimators.h"

using sensor_msgs::PointCloud2;
using pcl::PointCloud;
using pcl::PointXYZRGB;
using visualization_msgs::Marker;

using namespace object_search;

int main(int argc, char** argv) {
  ros::init(argc, argv, "object_search");
  ros::NodeHandle nh;
  ros::AsyncSpinner spinner(4);
  spinner.start();

  // Build databases
  ros::ServiceClient get_cloud =
      nh.serviceClient<rapid_msgs::GetStaticCloud>("get_static_cloud");
  ros::ServiceClient list_clouds =
      nh.serviceClient<rapid_msgs::ListStaticClouds>("list_static_clouds");
  ros::ServiceClient remove_cloud =
      nh.serviceClient<rapid_msgs::RemoveStaticCloud>("remove_static_cloud");
  ros::ServiceClient save_cloud =
      nh.serviceClient<rapid_msgs::SaveStaticCloud>("save_static_cloud");
  Database object_db("object_search", "objects", get_cloud, list_clouds,
                     remove_cloud, save_cloud);
  Database scene_db("object_search", "scenes", get_cloud, list_clouds,
                    remove_cloud, save_cloud);
  rapid::db::NameDb scene_ndb(nh, "custom_landmarks", "scenes");
  rapid::db::NameDb scene_cloud_ndb(nh, "custom_landmarks", "scene_clouds");
  rapid::db::NameDb landmark_ndb(nh, "custom_landmarks", "landmarks");
  rapid::db::NameDb landmark_cloud_ndb(nh, "custom_landmarks",
                                       "landmark_clouds");

  // Visualization publishers
  ros::Publisher object_pub = nh.advertise<PointCloud2>("/landmark", 1, true);
  ros::Publisher scene_pub = nh.advertise<PointCloud2>("/scene", 1, true);
  ros::Publisher heatmap_pub = nh.advertise<PointCloud2>("/heatmap", 1, true);
  ros::Publisher candidates_pub =
      nh.advertise<PointCloud2>("/candidate_samples", 1, true);
  ros::Publisher alignment_pub =
      nh.advertise<PointCloud2>("/alignment", 1, true);
  ros::Publisher output_pub = nh.advertise<PointCloud2>("/output", 1, true);
  rapid_ros::Publisher<visualization_msgs::Marker> marker_pub(
      nh.advertise<visualization_msgs::Marker>("/visualization_markers", 1,
                                               true));

  // Build ROI server
  rapid::perception::Box3DRoiServer roi_server("roi");
  CaptureRoi capture(&roi_server);

  // Build heat mapper
  // rapid::perception::FpfhHeatMapper* heat_mapper =
  //    new rapid::perception::FpfhHeatMapper();
  // heat_mapper->set_name("fpfh");

  // rapid::perception::TemplateMatchingHeatMapper* heat_mapper =
  //    new rapid::perception::TemplateMatchingHeatMapper();
  // heat_mapper->set_name("template_matching");

  rapid::perception::RandomHeatMapper* heat_mapper =
      new rapid::perception::RandomHeatMapper();
  heat_mapper->set_name("random");
  heat_mapper->set_heatmap_publisher(heatmap_pub);

  // Build pose estimator
  rapid::perception::PoseEstimator pose_estimator(heat_mapper);
  pose_estimator.set_candidates_publisher(candidates_pub);
  pose_estimator.set_alignment_publisher(alignment_pub);
  pose_estimator.set_marker_publisher(&marker_pub);

  rapid::perception::RansacPoseEstimator ransac_estimator;
  ros::Publisher pose_pub =
      nh.advertise<geometry_msgs::PoseArray>("/poses", 1, true);
  ransac_estimator.set_pose_publisher(pose_pub);

  rapid::perception::GroupingPoseEstimator grouping_estimator;
  ros::Publisher corr_pub = nh.advertise<visualization_msgs::MarkerArray>(
      "/correspondences", 1, true);
  ros::Publisher object_keypoints_pub =
      nh.advertise<PointCloud2>("/landmark_keypoints", 1, true);
  ros::Publisher scene_keypoints_pub =
      nh.advertise<PointCloud2>("/scene_keypoints", 1, true);
  grouping_estimator.set_correspondence_publisher(corr_pub);
  grouping_estimator.set_scene_keypoints_publisher(scene_keypoints_pub);
  grouping_estimator.set_object_keypoints_publisher(object_keypoints_pub);

  Estimators estimators;
  estimators.custom = &pose_estimator;
  estimators.ransac = &ransac_estimator;
  estimators.grouping = &grouping_estimator;

  // Build visualizers

  // Build command line
  ListCommand list_landmarks(&landmark_ndb, ListCommand::kLandmarks);
  ListCommand list_scenes(&scene_ndb, ListCommand::kScenes);
  RecordObjectCommand record_object(&object_db, &capture);
  RecordSceneCommand record_scene(&scene_ndb, &scene_cloud_ndb);
  DeleteCommand delete_object(&object_db, "delete object",
                              "<name> - Delete an object");
  DeleteCommand delete_scene(&scene_db, "delete scene",
                             "<name> - Delete a scene");
  UseCommand use_object(&object_db, &estimators, "object", object_pub);
  UseCommand use_scene(&scene_db, &estimators, "scene", scene_pub);
  RunCommand run(&estimators, output_pub);
  SetDebugCommand set_debug(&estimators);
  rapid::utils::ExitCommand exit;

  rapid::utils::CommandLine scene_cli("Scene manager");
  scene_cli.AddCommand(&list_scenes);
  scene_cli.AddCommand(&record_scene);
  scene_cli.AddCommand(&delete_scene);
  scene_cli.AddCommand(&exit);

  EditScenesCommand edit_scenes(scene_cli);

  rapid::utils::CommandLine cli("Custom landmarks CLI");
  cli.AddCommand(&edit_scenes);
  cli.AddCommand(&list_landmarks);
  cli.AddCommand(&record_object);
  cli.AddCommand(&delete_object);
  cli.AddCommand(&use_object);
  cli.AddCommand(&use_scene);
  cli.AddCommand(&run);
  cli.AddCommand(&set_debug);
  cli.AddCommand(&exit);

  while (cli.Next()) {
  }

  spinner.stop();
  return 0;
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include "cudarray/common.hpp"

const char *cublasErrorString(cublasStatus_t error){
	switch(error) {
		case CUBLAS_STATUS_SUCCESS :
			return "operation completed successfully";
		case CUBLAS_STATUS_NOT_INITIALIZED :
			return "CUBLAS library not initialized";
		case CUBLAS_STATUS_ALLOC_FAILED :
			return "resource allocation failed";
		case CUBLAS_STATUS_INVALID_VALUE :
			return "unsupported numerical value was passed to function";
		case CUBLAS_STATUS_ARCH_MISMATCH :
			return "function requires an architectural feature absent from \
			the architecture of the device";
		case CUBLAS_STATUS_MAPPING_ERROR :
			return "access to GPU memory space failed";
		case CUBLAS_STATUS_EXECUTION_FAILED :
			return "GPU program failed to execute";
		case CUBLAS_STATUS_INTERNAL_ERROR :
			return "an internal CUBLAS operation failed";
		default :
			return "other cuBLAS error";
	}
}

const char *cufftErrorEnum(cufftResult error) {
    switch (error) {
        case CUFFT_SUCCESS:
            return "CUFFT_SUCCESS";
        case CUFFT_INVALID_PLAN:
            return "CUFFT_INVALID_PLAN";
        case CUFFT_ALLOC_FAILED:
            return "CUFFT_ALLOC_FAILED";
        case CUFFT_INVALID_TYPE:
            return "CUFFT_INVALID_TYPE";
        case CUFFT_INVALID_VALUE:
            return "CUFFT_INVALID_VALUE";
        case CUFFT_INTERNAL_ERROR:
            return "CUFFT_INTERNAL_ERROR";
        case CUFFT_EXEC_FAILED:
            return "CUFFT_EXEC_FAILED";
        case CUFFT_SETUP_FAILED:
            return "CUFFT_SETUP_FAILED";
        case CUFFT_INVALID_SIZE:
            return "CUFFT_INVALID_SIZE";
        case CUFFT_UNALIGNED_DATA:
            return "CUFFT_UNALIGNED_DATA";
		default :
			return "other cuFFT error";
    }
}

inline void cudaSyncCheck(const char *msg, const char *file, const int line) {
  cudaDeviceSynchronize();
  cudaError_t err = cudaGetLastError();
  if (cudaSuccess != err) {
    fprintf(stderr, "%s(%i):\nCUDA error : (%d) %s\n", file, line, (int)err,
            cudaGetErrorString(err));
    fprintf(stderr, "Message : %s\n", msg);
    cudaDeviceReset();
    exit(-1);
  }
}
<commit_msg>minor<commit_after>#include <stdlib.h>
#include <stdio.h>
#include "cudarray/common.hpp"

const char *cublasErrorString(cublasStatus_t error){
	switch(error) {
		case CUBLAS_STATUS_SUCCESS :
			return "operation completed successfully";
		case CUBLAS_STATUS_NOT_INITIALIZED :
			return "CUBLAS library not initialized";
		case CUBLAS_STATUS_ALLOC_FAILED :
			return "resource allocation failed";
		case CUBLAS_STATUS_INVALID_VALUE :
			return "unsupported numerical value was passed to function";
		case CUBLAS_STATUS_ARCH_MISMATCH :
			return "function requires an architectural feature absent from \
			the architecture of the device";
		case CUBLAS_STATUS_MAPPING_ERROR :
			return "access to GPU memory space failed";
		case CUBLAS_STATUS_EXECUTION_FAILED :
			return "GPU program failed to execute";
		case CUBLAS_STATUS_INTERNAL_ERROR :
			return "an internal CUBLAS operation failed";
		default :
			return "other cuBLAS error";
	}
}

const char *cufftErrorEnum(cufftResult error) {
    switch (error) {
        case CUFFT_SUCCESS:
            return "CUFFT_SUCCESS";
        case CUFFT_INVALID_PLAN:
            return "CUFFT_INVALID_PLAN";
        case CUFFT_ALLOC_FAILED:
            return "CUFFT_ALLOC_FAILED";
        case CUFFT_INVALID_TYPE:
            return "CUFFT_INVALID_TYPE";
        case CUFFT_INVALID_VALUE:
            return "CUFFT_INVALID_VALUE";
        case CUFFT_INTERNAL_ERROR:
            return "CUFFT_INTERNAL_ERROR";
        case CUFFT_EXEC_FAILED:
            return "CUFFT_EXEC_FAILED";
        case CUFFT_SETUP_FAILED:
            return "CUFFT_SETUP_FAILED";
        case CUFFT_INVALID_SIZE:
            return "CUFFT_INVALID_SIZE";
        case CUFFT_UNALIGNED_DATA:
            return "CUFFT_UNALIGNED_DATA";
		default :
			return "other cuFFT error";
    }
}

inline void cudaSyncCheck(const char *msg, const char *file, const int line) {
//  cudaDeviceSynchronize();
  cudaError_t err = cudaGetLastError();
  if (cudaSuccess != err) {
    fprintf(stderr, "%s(%i):\nCUDA error : (%d) %s\n", file, line, (int)err,
            cudaGetErrorString(err));
    fprintf(stderr, "Message : %s\n", msg);
    cudaDeviceReset();
    exit(-1);
  }
}
<|endoftext|>


<commit_before>#include "Engine.hpp"
#include "Resources.hpp"
#include <Kunlaboro/EntitySystem.hpp>
#include <Kunlaboro/Component.hpp>
#include <SFML/Window/Event.hpp>

class EngineHandler : public Kunlaboro::Component
{
public:
    EngineHandler(sf::RenderWindow& win, sf::View& ui, sf::View& game) : Kunlaboro::Component("I am an internal component, don't poke me :("), mWin(win), mUi(ui), mGame(game) { }

    void addedToEntity()
    {
        requestMessage("Event.Engine.Init", &EngineHandler::resized);
        requestMessage("Event.Window.Resized", &EngineHandler::resized);
        changeRequestPriority("Event.Window.Resized", -42);
        requestMessage("ExitGame", [this](const Kunlaboro::Message& msg) { mWin.close(); });

        requestMessage("Get.GameView", [this](Kunlaboro::Message& msg) { msg.payload = &mGame; msg.handled = true; });
        requestMessage("Get.UiView", [this](Kunlaboro::Message& msg) { msg.payload = &mUi; msg.handled = true; });
    }

    void resized(const Kunlaboro::Message& msg)
    {
        sf::Vector2u size = mWin.getSize();

        mUi.setSize((sf::Vector2f)size);
        mUi.setCenter((sf::Vector2f)size / 2.f);

        auto gSize = mGame.getSize();
        float aspect = (float)size.x / size.y;

        mGame.setSize(gSize.y * aspect, gSize.y);
    }

private:
    sf::View &mUi, &mGame;
    sf::RenderWindow& mWin;
};

Engine::Engine(Kunlaboro::EntitySystem& sys) : mSystem(sys)
{
    sys.registerComponent("I am an internal component, don't poke me :(", [&]() { return new EngineHandler(mWindow, mUiView, mGameView); });

    auto ent = sys.createEntity();
    sys.addComponent(ent, "I am an internal component, don't poke me :(");
}

Engine::~Engine()
{
}

int Engine::mainLoop()
{
#define KEY(key) case sf::Keyboard::##key##: return #key; break;
    auto keyToString = [](sf::Keyboard::Key k) -> std::string {
        switch(k)
        {
        KEY(W) KEY(A) KEY(S) KEY(D) KEY(Q) KEY(E) KEY(R)
        //KEY(Up) KEY(Down) KEY(Left) KEY(Right)
        KEY(Space) KEY(Return) KEY(Escape)
        KEY(LShift)

        default:
        return "Invalid";
        }
    };
#undef KEY

    mWindow.create(sf::VideoMode(1024,768), Resources::String_Name);

    sf::Event ev;
    sf::Clock timer;

    mSystem.sendGlobalMessage("Event.Engine.Init");
#ifdef _DEBUG
    int fps = 0, frames = 0;
    float frameTime = 0;
#endif
    while (mWindow.isOpen())
    {
        float dt = std::min(timer.restart().asSeconds(), 0.5f);

        while (mWindow.pollEvent(ev))
        {
            switch(ev.type)
            {
            case sf::Event::Closed:
                {
                    Kunlaboro::Message msg(Kunlaboro::Type_Message, nullptr);
                    msg.payload = nullptr;
                    mSystem.sendGlobalMessage(mSystem.getMessageRequestId(Kunlaboro::Reason_Message, "Event.Window.Closed"), msg);
                    if (!msg.handled)
                        mWindow.close();
                } break;
            case sf::Event::GainedFocus: mSystem.sendGlobalMessage("Event.Window.GainedFocus"); break;
            case sf::Event::LostFocus: mSystem.sendGlobalMessage("Event.Window.LostFocus"); break;
            case sf::Event::MouseEntered: mSystem.sendGlobalMessage("Event.Window.MouseEnter"); break;
            case sf::Event::MouseLeft: mSystem.sendGlobalMessage("Event.Window.MouseLeft"); break;
            case sf::Event::Resized: mSystem.sendGlobalMessage("Event.Window.Resized", sf::Vector2u(ev.size.width, ev.size.height)); break;

            case sf::Event::KeyPressed:
            case sf::Event::KeyReleased:
                {
                    Kunlaboro::Message msg(Kunlaboro::Type_Message, nullptr);
                    msg.payload = (ev.type == sf::Event::KeyPressed);
                    mSystem.sendGlobalMessage(mSystem.getMessageRequestId(Kunlaboro::Reason_Message, "Event.Key." + keyToString(ev.key.code)), msg);
                } break;

            case sf::Event::MouseButtonPressed:
            case sf::Event::MouseButtonReleased:
                {
                    bool pressed = ev.type == sf::Event::MouseButtonPressed;

                    Kunlaboro::Message msg(Kunlaboro::Type_Message, nullptr);
                    msg.payload = std::tuple<sf::Mouse::Button, sf::Vector2f, bool>(ev.mouseButton.button, sf::Vector2f(ev.mouseButton.x, ev.mouseButton.y), pressed);
                    mSystem.sendGlobalMessage(mSystem.getMessageRequestId(Kunlaboro::Reason_Message, "Event.Mouse.Click"), msg);
                } break;

            case sf::Event::MouseMoved:
                {
                    auto pos = sf::Vector2f(ev.mouseMove.x, ev.mouseMove.y);
                    Kunlaboro::Message msg(Kunlaboro::Type_Message, nullptr);
                    msg.payload = pos;
                    mSystem.sendGlobalMessage(mSystem.getMessageRequestId(Kunlaboro::Reason_Message, "Event.Mouse.Move"), msg);
                    {
                        sf::Vector2f vS = mGameView.getSize(), vC = mGameView.getCenter(), wS = (sf::Vector2f)mWindow.getSize();
                        sf::FloatRect vR;
                        vR.left = vC.x - vS.x / 2;
                        vR.top = vC.y - vS.y / 2;
                        vR.width = vS.x;
                        vR.height = vS.y;

                        msg.payload = sf::Vector2f(vR.left + vR.width * (pos.x / wS.x), vR.top + vR.height * (pos.y / wS.y));
                    }
                    msg.sender = nullptr;
                    msg.handled = false;
                    mSystem.sendGlobalMessage(mSystem.getMessageRequestId(Kunlaboro::Reason_Message, "Event.Mouse.MoveGame"), msg);
                } break;
            }
        }

        ///\TODO Fixed timestep
        mSystem.sendGlobalMessage("Event.Update", dt);

        mWindow.clear();

        mWindow.setView(mGameView);

        mSystem.sendGlobalMessage("Event.Draw", (sf::RenderTarget*)&mWindow);

        mWindow.setView(mUiView);

        mSystem.sendGlobalMessage("Event.DrawUi", (sf::RenderTarget*)&mWindow);

#ifdef _DEBUG
        frames++;
        frameTime += dt;
        if (frameTime > 1)
        {
            frameTime -= 1;
            fps = frames;
            frames = 0;
        }

        {
            sf::Text debugText("DEBUG", Resources::Font_Dosis, 16);
            char tmp[256];
            sprintf_s(tmp, "FPS: %i\nComponents: %i\nEntities: %i", fps, mSystem.numCom(), mSystem.numEnt());

            debugText.setString(tmp);
            auto rect = debugText.getLocalBounds();
            debugText.setPosition(5, mUiView.getSize().y - rect.height - 10);

            mWindow.draw(debugText);
        }
#endif

        mWindow.display();

        if (dt < 1.f / 60.f)
            sf::sleep(sf::milliseconds(1));
    }

    return 0;
}<commit_msg>Change key macro to be nicer for GCC<commit_after>#include "Engine.hpp"
#include "Resources.hpp"
#include <Kunlaboro/EntitySystem.hpp>
#include <Kunlaboro/Component.hpp>
#include <SFML/Window/Event.hpp>

class EngineHandler : public Kunlaboro::Component
{
public:
    EngineHandler(sf::RenderWindow& win, sf::View& ui, sf::View& game) : Kunlaboro::Component("I am an internal component, don't poke me :("), mWin(win), mUi(ui), mGame(game) { }

    void addedToEntity()
    {
        requestMessage("Event.Engine.Init", &EngineHandler::resized);
        requestMessage("Event.Window.Resized", &EngineHandler::resized);
        changeRequestPriority("Event.Window.Resized", -42);
        requestMessage("ExitGame", [this](const Kunlaboro::Message& msg) { mWin.close(); });

        requestMessage("Get.GameView", [this](Kunlaboro::Message& msg) { msg.payload = &mGame; msg.handled = true; });
        requestMessage("Get.UiView", [this](Kunlaboro::Message& msg) { msg.payload = &mUi; msg.handled = true; });
    }

    void resized(const Kunlaboro::Message& msg)
    {
        sf::Vector2u size = mWin.getSize();

        mUi.setSize((sf::Vector2f)size);
        mUi.setCenter((sf::Vector2f)size / 2.f);

        auto gSize = mGame.getSize();
        float aspect = (float)size.x / size.y;

        mGame.setSize(gSize.y * aspect, gSize.y);
    }

private:
    sf::View &mUi, &mGame;
    sf::RenderWindow& mWin;
};

Engine::Engine(Kunlaboro::EntitySystem& sys) : mSystem(sys)
{
    sys.registerComponent("I am an internal component, don't poke me :(", [&]() { return new EngineHandler(mWindow, mUiView, mGameView); });

    auto ent = sys.createEntity();
    sys.addComponent(ent, "I am an internal component, don't poke me :(");
}

Engine::~Engine()
{
}

int Engine::mainLoop()
{
#define KEY(key) case sf::Keyboard::key: return #key; break;
    auto keyToString = [](sf::Keyboard::Key k) -> std::string {
        switch(k)
        {
        KEY(W) KEY(A) KEY(S) KEY(D) KEY(Q) KEY(E) KEY(R)
        //KEY(Up) KEY(Down) KEY(Left) KEY(Right)
        KEY(Space) KEY(Return) KEY(Escape)
        KEY(LShift)

        default:
        return "Invalid";
        }
    };
#undef KEY

    mWindow.create(sf::VideoMode(1024,768), Resources::String_Name);

    sf::Event ev;
    sf::Clock timer;

    mSystem.sendGlobalMessage("Event.Engine.Init");
#ifdef _DEBUG
    int fps = 0, frames = 0;
    float frameTime = 0;
#endif
    while (mWindow.isOpen())
    {
        float dt = std::min(timer.restart().asSeconds(), 0.5f);

        while (mWindow.pollEvent(ev))
        {
            switch(ev.type)
            {
            case sf::Event::Closed:
                {
                    Kunlaboro::Message msg(Kunlaboro::Type_Message, nullptr);
                    msg.payload = nullptr;
                    mSystem.sendGlobalMessage(mSystem.getMessageRequestId(Kunlaboro::Reason_Message, "Event.Window.Closed"), msg);
                    if (!msg.handled)
                        mWindow.close();
                } break;
            case sf::Event::GainedFocus: mSystem.sendGlobalMessage("Event.Window.GainedFocus"); break;
            case sf::Event::LostFocus: mSystem.sendGlobalMessage("Event.Window.LostFocus"); break;
            case sf::Event::MouseEntered: mSystem.sendGlobalMessage("Event.Window.MouseEnter"); break;
            case sf::Event::MouseLeft: mSystem.sendGlobalMessage("Event.Window.MouseLeft"); break;
            case sf::Event::Resized: mSystem.sendGlobalMessage("Event.Window.Resized", sf::Vector2u(ev.size.width, ev.size.height)); break;

            case sf::Event::KeyPressed:
            case sf::Event::KeyReleased:
                {
                    Kunlaboro::Message msg(Kunlaboro::Type_Message, nullptr);
                    msg.payload = (ev.type == sf::Event::KeyPressed);
                    mSystem.sendGlobalMessage(mSystem.getMessageRequestId(Kunlaboro::Reason_Message, "Event.Key." + keyToString(ev.key.code)), msg);
                } break;

            case sf::Event::MouseButtonPressed:
            case sf::Event::MouseButtonReleased:
                {
                    bool pressed = ev.type == sf::Event::MouseButtonPressed;

                    Kunlaboro::Message msg(Kunlaboro::Type_Message, nullptr);
                    msg.payload = std::tuple<sf::Mouse::Button, sf::Vector2f, bool>(ev.mouseButton.button, sf::Vector2f(ev.mouseButton.x, ev.mouseButton.y), pressed);
                    mSystem.sendGlobalMessage(mSystem.getMessageRequestId(Kunlaboro::Reason_Message, "Event.Mouse.Click"), msg);
                } break;

            case sf::Event::MouseMoved:
                {
                    auto pos = sf::Vector2f(ev.mouseMove.x, ev.mouseMove.y);
                    Kunlaboro::Message msg(Kunlaboro::Type_Message, nullptr);
                    msg.payload = pos;
                    mSystem.sendGlobalMessage(mSystem.getMessageRequestId(Kunlaboro::Reason_Message, "Event.Mouse.Move"), msg);
                    {
                        sf::Vector2f vS = mGameView.getSize(), vC = mGameView.getCenter(), wS = (sf::Vector2f)mWindow.getSize();
                        sf::FloatRect vR;
                        vR.left = vC.x - vS.x / 2;
                        vR.top = vC.y - vS.y / 2;
                        vR.width = vS.x;
                        vR.height = vS.y;

                        msg.payload = sf::Vector2f(vR.left + vR.width * (pos.x / wS.x), vR.top + vR.height * (pos.y / wS.y));
                    }
                    msg.sender = nullptr;
                    msg.handled = false;
                    mSystem.sendGlobalMessage(mSystem.getMessageRequestId(Kunlaboro::Reason_Message, "Event.Mouse.MoveGame"), msg);
                } break;
            }
        }

        ///\TODO Fixed timestep
        mSystem.sendGlobalMessage("Event.Update", dt);

        mWindow.clear();

        mWindow.setView(mGameView);

        mSystem.sendGlobalMessage("Event.Draw", (sf::RenderTarget*)&mWindow);

        mWindow.setView(mUiView);

        mSystem.sendGlobalMessage("Event.DrawUi", (sf::RenderTarget*)&mWindow);

#ifdef _DEBUG
        frames++;
        frameTime += dt;
        if (frameTime > 1)
        {
            frameTime -= 1;
            fps = frames;
            frames = 0;
        }

        {
            sf::Text debugText("DEBUG", Resources::Font_Dosis, 16);
            char tmp[256];
            sprintf_s(tmp, "FPS: %i\nComponents: %i\nEntities: %i", fps, mSystem.numCom(), mSystem.numEnt());

            debugText.setString(tmp);
            auto rect = debugText.getLocalBounds();
            debugText.setPosition(5, mUiView.getSize().y - rect.height - 10);

            mWindow.draw(debugText);
        }
#endif

        mWindow.display();

        if (dt < 1.f / 60.f)
            sf::sleep(sf::milliseconds(1));
    }

    return 0;
}<|endoftext|>


<commit_before>#include "../lexical/Lexical.h"
#include "../syntax/Syntax.h"
#include <iostream>
#include <vector>
#include <string>

using namespace std;
using namespace ecc;

int main() {

    // Lexical analysis phase
    Lexical lexical(
			"resources/src/lexical_state_machine.json",
			"resources/src/lexical_config.json",
            "resources/src/lexical_errors.json");

	std::vector<std::shared_ptr<LexicalToken>> lexicalTokens;
	std::vector<std::string> errorMessages;
	lexical.generateLexicalTokens("resources/src/input.txt", lexicalTokens, errorMessages);

    // Logging
	for(auto token : lexicalTokens)
		cout << *token << endl;
	for(auto token : errorMessages)
		cerr << token << endl;
    if(errorMessages.size() != 0) {
        // A lexical error exist, exit
        cerr << "Exiting program with code 1" << endl;
        return 1;
    }

    // Syntax analysis phase
    Syntax syntax("resources/src/syntax_grammar.txt");

	return 0;
}
<commit_msg>Added first boost log message<commit_after>#include "../lexical/Lexical.h"
#include "../syntax/Syntax.h"
#include <iostream>
#include <vector>
#include <string>

#include <boost/move/utility_core.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/sources/global_logger_storage.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/console.hpp>

namespace logging = boost::log;
namespace src = boost::log::sources;
namespace keywords = boost::log::keywords;
namespace sinks = boost::log::sinks;

using namespace std;
using namespace ecc;

BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULT(ecc_logger, src::logger_mt)

void init_log() {
    logging::add_console_log(
            std::cout,
            boost::log::keywords::format = "[%TimeStamp%]: %Message%"
    );
    logging::add_file_log(
            keywords::file_name = "sample_%N.log",
            keywords::rotation_size = 10 * 1024 * 1024,                                   /* rotate files every 10 MiB... */
            keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0), /* ...or at midnight            */
            keywords::auto_flush = true,
            keywords::format = "[%TimeStamp%]: %Message%"
    );
    logging::add_common_attributes();
}

int main() {

    // Configure the logger
    init_log();

    // Test logging system
    src::logger_mt& lg = ecc_logger::get();
    BOOST_LOG(lg) << "Hello world";

    // Lexical analysis phase
    Lexical lexical(
			"resources/src/lexical_state_machine.json",
			"resources/src/lexical_config.json",
            "resources/src/lexical_errors.json");

	std::vector<std::shared_ptr<LexicalToken>> lexicalTokens;
	std::vector<std::string> errorMessages;
	lexical.generateLexicalTokens("resources/src/input.txt", lexicalTokens, errorMessages);

    // Logging
	for(auto token : lexicalTokens)
		cout << *token << endl;
	for(auto token : errorMessages)
		cerr << token << endl;
    if(errorMessages.size() != 0) {
        // A lexical error exist, exit
        cerr << "Exiting program with code 1" << endl;
        return 1;
    }

    // Syntax analysis phase
    Syntax syntax("resources/src/syntax_grammar.txt");

	return 0;
}
<|endoftext|>


<commit_before>/*!
 *  \file File common.cpp
 *  \brief Implementation of Common class
 *
 *  The class implemented here has methods used by all the other classes
 *
 *  \sa common.hpp
 */

#include <common.hpp>
#include <assert.h>

int debug_count = 0; //!< Global variable used as debug counter

// Hotspot screen positions to be used as shortcuts
// The number on the left is x axis and the right one is y axis
pair<float, float>
    hotspot_positions[] = {
        // TOP_LEFT
        {0.0, 0.0},
        // TOP
        {0.5, 0.0},
        // TOP_RIGHT
        {1.0, 0.0},
        // LEFT
        {0.0, 0.5},
        // CENTER
        {0.5, 0.5},
        // RIGHT
        {1.0, 0.5},
        // BOTTOM_LEFT
        {0.0, 1.0},
        // BOTTOM
        {0.5, 1.0},
        // BOTTOM_RIGHT
        {1.0, 1.0}};

/*!
	@fn       SDL_Color generate_color(int r, int g, int b, int a)
	@brief    Generates color with a alpha channel
	@param    int r, int g, int b, int a
	@return   SDL_Color rgba color value
	@warning  none
*/

SDL_Color generate_color(int red,		// red value, 	range: 0 -> 255
                         int green,		// green value, range: 0 -> 255
                         int blue,		// blue value,	range: 0 -> 255
                         int alpha) {	// alpha value, range: unknown

  LOG_METHOD_START("Common::generate_color");

  LOG_VARIABLE("red", red);
  assert(red >= 0 and red <= 255);

  LOG_VARIABLE("green", green);
  assert(green >= 0 and green <= 255);

  LOG_VARIABLE("blue", blue);
  assert(blue >= 0 and blue <= 255);

  LOG_VARIABLE("alpha", alpha);
  assert(alpha >= 0);

  SDL_Color color; //!< Object with the 4 color values

  color.r = red;
	color.g = green;
	color.b = blue;
	color.a = alpha;

  LOG_METHOD_CLOSE("Common::generate_color", color);
	return color;
}

/*!
	@fn       bool equals(const float &a, const float &b)
	@brief    Compares two float constants and returns the boolean result
	@param    const float &a, const float &b
	@return   boolean value of the comparisson between the two params
  @warning  PRECISION is a constant with 0.0001 as value, it validates the
comparisson between the two float values
*/

bool equals(const float &a, const float &b) {
  LOG_METHOD_START("Common::equals");

  LOG_VARIABLE("a", a);
  LOG_VARIABLE("b", b);

  float fabs_on_params = std::fabs((a - b));

  LOG_METHOD_CLOSE("Common::equals", fabs_on_params <= PRECISION));
  return (fabs_on_params <= PRECISION);
}

/*!
  @fn       float close_distance(const float &from, const float &to,
  const float &change)
	@brief    Function that cannot be comprehended by mere human beings
	@param    const float &from, const float &to, const float &change
	@return   A float result (???)
	@warning  TODO: this method must be refactorated for better understanding
*/

float close_distance(const float &from, const float &to, const float &change) {
  LOG_METHOD_START("Common::close_distance");

  LOG_VARIABLE("from", from);
  LOG_VARIABLE("to", to);
  LOG_VARIABLE("change", change);

	if (abs(from - to) < change) {
		return to;
  }
  else {
    // Do nothing
  }

	if (from > to) {
		return (from - change);
  }
  else {
    // Do nothing
  }

  LOG_METHOD_CLOSE("Common::close_distance", from + change);
  return from + change;
}

/*!
	@fn       string convert_float_to_str(float f)
	@brief    Converts a float number to a string and returns it
	@param    float number f
	@return   The number passed as param transformed in a string
	@warning  none
*/

string convert_float_to_str(float float_number) {
  LOG_METHOD_START("Common::convert_float_to_str");
  LOG_VARIABLE("float_number", float_number);

  char string_to_be_saved[15]; //!< Temporary storage variable for saving chars

  sprintf(string_to_be_saved, "%.2f", float_number);

  LOG_METHOD_CLOSE("Common::convert_float_to_str", string_to_be_saved);
	return string_to_be_saved;
}
<commit_msg>[IMPORTANT CODE] applies technique to file common.cpp<commit_after>/*!
 *  \file File common.cpp
 *  \brief Implementation of Common class
 *
 *  The class implemented here has methods used by all the other classes
 *
 *  \sa common.hpp
 */

#include <common.hpp>
#include <assert.h>

int debug_count = 0; //!< Global variable used as debug counter

/*!
	@fn       SDL_Color generate_color(int r, int g, int b, int a)
	@brief    Generates color with a alpha channel
	@param    int r, int g, int b, int a
	@return   SDL_Color rgba color value
	@warning  none
*/

SDL_Color generate_color(int red,		// red value, 	range: 0 -> 255
                         int green,		// green value, range: 0 -> 255
                         int blue,		// blue value,	range: 0 -> 255
                         int alpha) {	// alpha value, range: unknown

  LOG_METHOD_START("Common::generate_color");

  LOG_VARIABLE("red", red);
  assert(red >= 0 and red <= 255);

  LOG_VARIABLE("green", green);
  assert(green >= 0 and green <= 255);

  LOG_VARIABLE("blue", blue);
  assert(blue >= 0 and blue <= 255);

  LOG_VARIABLE("alpha", alpha);
  assert(alpha >= 0);

  SDL_Color color; //!< Object with the 4 color values

  color.r = red;
	color.g = green;
	color.b = blue;
	color.a = alpha;

  LOG_METHOD_CLOSE("Common::generate_color", color);
	return color;
}

/*!
  @fn       float close_distance(const float &from, const float &to,
  const float &change)
	@brief    Function that cannot be comprehended by mere human beings
	@param    const float &from, const float &to, const float &change
	@return   A float result (???)
	@warning  TODO: this method must be refactorated for better understanding
*/

float close_distance(const float &from, const float &to, const float &change) {
  LOG_METHOD_START("Common::close_distance");

  LOG_VARIABLE("from", from);
  LOG_VARIABLE("to", to);
  LOG_VARIABLE("change", change);

  if (abs(from - to) < change) {
    return to;
  }
  else {
    // Do nothing
  }

  if (from > to) {
    return (from - change);
  }
  else {
    // Do nothing
  }

  LOG_METHOD_CLOSE("Common::close_distance", from + change);
  return from + change;
}

// Hotspot screen positions to be used as shortcuts
// The number on the left is x axis and the right one is y axis
pair<float, float> hotspot_positions[] = {
  // TOP_LEFT
  {0.0, 0.0},
  // TOP
  {0.5, 0.0},
  // TOP_RIGHT
  {1.0, 0.0},
  // LEFT
  {0.0, 0.5},
  // CENTER
  {0.5, 0.5},
  // RIGHT
  {1.0, 0.5},
  // BOTTOM_LEFT
  {0.0, 1.0},
  // BOTTOM
  {0.5, 1.0},
  // BOTTOM_RIGHT
  {1.0, 1.0}
};

/*!
	@fn       bool equals(const float &a, const float &b)
	@brief    Compares two float constants and returns the boolean result
	@param    const float &a, const float &b
	@return   boolean value of the comparisson between the two params
  @warning  PRECISION is a constant with 0.0001 as value, it validates the
comparisson between the two float values
*/

bool equals(const float &a, const float &b) {
  LOG_METHOD_START("Common::equals");

  LOG_VARIABLE("a", a);
  LOG_VARIABLE("b", b);

  float fabs_on_params = std::fabs((a - b));

  LOG_METHOD_CLOSE("Common::equals", fabs_on_params <= PRECISION));
  return (fabs_on_params <= PRECISION);
}

/*!
	@fn       string convert_float_to_str(float f)
	@brief    Converts a float number to a string and returns it
	@param    float number f
	@return   The number passed as param transformed in a string
	@warning  none
*/

string convert_float_to_str(float float_number) {
  LOG_METHOD_START("Common::convert_float_to_str");
  LOG_VARIABLE("float_number", float_number);

  char string_to_be_saved[15]; //!< Temporary storage variable for saving chars

  sprintf(string_to_be_saved, "%.2f", float_number);

  LOG_METHOD_CLOSE("Common::convert_float_to_str", string_to_be_saved);
  return string_to_be_saved;
}
<|endoftext|>