<commit_before>////////////////////////////////////////////////////////////////////////////////
///
/// SoundStretch main routine.
///
/// Author        : Copyright (c) Olli Parviainen
/// Author e-mail : oparviai 'at' iki.fi
/// SoundTouch WWW: http://www.surina.net/soundtouch
///
////////////////////////////////////////////////////////////////////////////////
//
// Last changed  : $Date$
// File revision : $Revision: 4 $
//
// $Id$
//
////////////////////////////////////////////////////////////////////////////////
//
// License :
//
//  SoundTouch audio processing library
//  Copyright (c) Olli Parviainen
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
////////////////////////////////////////////////////////////////////////////////

#include <stdexcept>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "RunParameters.h"
#include "WavFile.h"
#include "SoundTouch.h"
#include "BPMDetect.h"

using namespace soundtouch;
using namespace std;

// Processing chunk size (size chosen to be divisible by 2, 4, 6, 8, 10, 12, 14, 16 channels ...)
#define BUFF_SIZE           6720

#if _WIN32
    #include <io.h>
    #include <fcntl.h>

    // Macro for Win32 standard input/output stream support: Sets a file stream into binary mode
    #define SET_STREAM_TO_BIN_MODE(f) (_setmode(_fileno(f), _O_BINARY))
#else
    // Not needed for GNU environment...
    #define SET_STREAM_TO_BIN_MODE(f) {}
#endif

static const char _helloText[] =
    "\n"
    "   SoundStretch v%s -  Written by Olli Parviainen 2001 - 2014\n"
    "==================================================================\n"
    "author e-mail: <oparviai"
    "@"
    "iki.fi> - WWW: http://www.surina.net/soundtouch\n"
    "\n"
    "This program is subject to (L)GPL license. Run \"soundstretch -license\" for\n"
    "more information.\n"
    "\n";

static void openFiles(WavInFile **inFile, WavOutFile **outFile, const RunParameters *params)
{
    int bits, samplerate, channels;

    if (strcmp(params->inFileName, "stdin") == 0)
    {
        // used 'stdin' as input file
        SET_STREAM_TO_BIN_MODE(stdin);
        *inFile = new WavInFile(stdin);
    }
    else
    {
        // open input file...
        *inFile = new WavInFile(params->inFileName);
    }

    // ... open output file with same sound parameters
    bits = (int)(*inFile)->getNumBits();
    samplerate = (int)(*inFile)->getSampleRate();
    channels = (int)(*inFile)->getNumChannels();

    if (params->outFileName)
    {
        if (strcmp(params->outFileName, "stdout") == 0)
        {
            SET_STREAM_TO_BIN_MODE(stdout);
            *outFile = new WavOutFile(stdout, samplerate, bits, channels);
        }
        else
        {
            *outFile = new WavOutFile(params->outFileName, samplerate, bits, channels);
        }
    }
    else
    {
        *outFile = NULL;
    }
}

// Sets the 'SoundTouch' object up according to input file sound format &
// command line parameters
static void setup(SoundTouch *pSoundTouch, const WavInFile *inFile, const RunParameters *params)
{
    int sampleRate;
    int channels;

    sampleRate = (int)inFile->getSampleRate();
    channels = (int)inFile->getNumChannels();
    pSoundTouch->setSampleRate(sampleRate);
    pSoundTouch->setChannels(channels);

    pSoundTouch->setTempoChange(params->tempoDelta);
    pSoundTouch->setPitchSemiTones(params->pitchDelta);
    pSoundTouch->setRateChange(params->rateDelta);

    pSoundTouch->setSetting(SETTING_USE_QUICKSEEK, params->quick);
    pSoundTouch->setSetting(SETTING_USE_AA_FILTER, !(params->noAntiAlias));

    if (params->speech)
    {
        // use settings for speech processing
        pSoundTouch->setSetting(SETTING_SEQUENCE_MS, 40);
        pSoundTouch->setSetting(SETTING_SEEKWINDOW_MS, 15);
        pSoundTouch->setSetting(SETTING_OVERLAP_MS, 8);
        fprintf(stderr, "Tune processing parameters for speech processing.\n");
    }

    // print processing information
    if (params->outFileName)
    {
#ifdef SOUNDTOUCH_INTEGER_SAMPLES
        fprintf(stderr, "Uses 16bit integer sample type in processing.\n\n");
#else
    #ifndef SOUNDTOUCH_FLOAT_SAMPLES
        #error "Sampletype not defined"
    #endif
        fprintf(stderr, "Uses 32bit floating point sample type in processing.\n\n");
#endif
        // print processing information only if outFileName given i.e. some processing will happen
        fprintf(stderr, "Processing the file with the following changes:\n");
        fprintf(stderr, "  tempo change = %+g %%\n", params->tempoDelta);
        fprintf(stderr, "  pitch change = %+g semitones\n", params->pitchDelta);
        fprintf(stderr, "  rate change  = %+g %%\n\n", params->rateDelta);
        fprintf(stderr, "Working...");
    }
    else
    {
        // outFileName not given
        fprintf(stderr, "Warning: output file name missing, won't output anything.\n\n");
    }

    fflush(stderr);
}

// Processes the sound
static void process(SoundTouch *pSoundTouch, WavInFile *inFile, WavOutFile *outFile)
{
    int nSamples;
    int nChannels;
    int buffSizeSamples;
    SAMPLETYPE sampleBuffer[BUFF_SIZE];

    if ((inFile == NULL) || (outFile == NULL)) return;  // nothing to do.

    nChannels = (int)inFile->getNumChannels();
    assert(nChannels > 0);
    buffSizeSamples = BUFF_SIZE / nChannels;

    // Process samples read from the input file
    while (inFile->eof() == 0)
    {
        int num;

        // Read a chunk of samples from the input file
        num = inFile->read(sampleBuffer, BUFF_SIZE);
        nSamples = num / (int)inFile->getNumChannels();

        // Feed the samples into SoundTouch processor
        pSoundTouch->putSamples(sampleBuffer, nSamples);

        // Read ready samples from SoundTouch processor & write them output file.
        // NOTES:
        // - 'receiveSamples' doesn't necessarily return any samples at all
        //   during some rounds!
        // - On the other hand, during some round 'receiveSamples' may have more
        //   ready samples than would fit into 'sampleBuffer', and for this reason
        //   the 'receiveSamples' call is iterated for as many times as it
        //   outputs samples.
        do
        {
            nSamples = pSoundTouch->receiveSamples(sampleBuffer, buffSizeSamples);
            outFile->write(sampleBuffer, nSamples * nChannels);
        } while (nSamples != 0);
    }

    // Now the input file is processed, yet 'flush' few last samples that are
    // hiding in the SoundTouch's internal processing pipeline.
    pSoundTouch->flush();
    do
    {
        nSamples = pSoundTouch->receiveSamples(sampleBuffer, buffSizeSamples);
        outFile->write(sampleBuffer, nSamples * nChannels);
    } while (nSamples != 0);
}

// Detect BPM rate of inFile and adjust tempo setting accordingly if necessary
static void detectBPM(WavInFile *inFile, RunParameters *params)
{
    float bpmValue;
    int nChannels;
    BPMDetect bpm(inFile->getNumChannels(), inFile->getSampleRate());
    SAMPLETYPE sampleBuffer[BUFF_SIZE];

    // detect bpm rate
    fprintf(stderr, "Detecting BPM rate...");
    fflush(stderr);

    nChannels = (int)inFile->getNumChannels();
    assert(BUFF_SIZE % nChannels == 0);

    // Process the 'inFile' in small blocks, repeat until whole file has
    // been processed
    while (inFile->eof() == 0)
    {
        int num, samples;

        // Read sample data from input file
        num = inFile->read(sampleBuffer, BUFF_SIZE);

        // Enter the new samples to the bpm analyzer class
        samples = num / nChannels;
        bpm.inputSamples(sampleBuffer, samples);
    }

    // Now the whole song data has been analyzed. Read the resulting bpm.
    bpmValue = bpm.getBpm();
    fprintf(stderr, "Done!\n");

    // rewind the file after bpm detection
    inFile->rewind();

    if (bpmValue > 0)
    {
        fprintf(stderr, "Detected BPM rate %.1f\n\n", bpmValue);
    }
    else
    {
        fprintf(stderr, "Couldn't detect BPM rate.\n\n");
        return;
    }

    if (params->goalBPM > 0)
    {
        // adjust tempo to given bpm
        params->tempoDelta = (params->goalBPM / bpmValue - 1.0f) * 100.0f;
        fprintf(stderr, "The file will be converted to %.1f BPM\n\n", params->goalBPM);
    }
}

int main(const int nParams, const char * const paramStr[])
{
    WavInFile *inFile;
    WavOutFile *outFile;
    RunParameters *params;
    SoundTouch soundTouch;

    fprintf(stderr, _helloText, SoundTouch::getVersionString());

    try
    {
        // Parse command line parameters
        params = new RunParameters(nParams, paramStr);

        // Open input & output files
        openFiles(&inFile, &outFile, params);

        if (params->detectBPM == true)
        {
            // detect sound BPM (and adjust processing parameters
            //  accordingly if necessary)
            detectBPM(inFile, params);
        }

        // Setup the 'SoundTouch' object for processing the sound
        setup(&soundTouch, inFile, params);

        // clock_t cs = clock();    // for benchmarking processing duration
        // Process the sound
        process(&soundTouch, inFile, outFile);
        // clock_t ce = clock();    // for benchmarking processing duration
        // printf("duration: %lf\n", (double)(ce-cs)/CLOCKS_PER_SEC);

        // Close WAV file handles & dispose of the objects
        delete inFile;
        delete outFile;
        delete params;

        fprintf(stderr, "Done!\n");
    }
    catch (const runtime_error &e)
    {
        // An exception occurred during processing, display an error message
        fprintf(stderr, "%s\n", e.what());
        return -1;
    }

    return 0;
}
<commit_msg>Change year<commit_after>////////////////////////////////////////////////////////////////////////////////
///
/// SoundStretch main routine.
///
/// Author        : Copyright (c) Olli Parviainen
/// Author e-mail : oparviai 'at' iki.fi
/// SoundTouch WWW: http://www.surina.net/soundtouch
///
////////////////////////////////////////////////////////////////////////////////
//
// Last changed  : $Date$
// File revision : $Revision: 4 $
//
// $Id$
//
////////////////////////////////////////////////////////////////////////////////
//
// License :
//
//  SoundTouch audio processing library
//  Copyright (c) Olli Parviainen
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
////////////////////////////////////////////////////////////////////////////////

#include <stdexcept>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "RunParameters.h"
#include "WavFile.h"
#include "SoundTouch.h"
#include "BPMDetect.h"

using namespace soundtouch;
using namespace std;

// Processing chunk size (size chosen to be divisible by 2, 4, 6, 8, 10, 12, 14, 16 channels ...)
#define BUFF_SIZE           6720

#if _WIN32
    #include <io.h>
    #include <fcntl.h>

    // Macro for Win32 standard input/output stream support: Sets a file stream into binary mode
    #define SET_STREAM_TO_BIN_MODE(f) (_setmode(_fileno(f), _O_BINARY))
#else
    // Not needed for GNU environment...
    #define SET_STREAM_TO_BIN_MODE(f) {}
#endif

static const char _helloText[] =
    "\n"
    "   SoundStretch v%s -  Written by Olli Parviainen 2001 - 2015\n"
    "==================================================================\n"
    "author e-mail: <oparviai"
    "@"
    "iki.fi> - WWW: http://www.surina.net/soundtouch\n"
    "\n"
    "This program is subject to (L)GPL license. Run \"soundstretch -license\" for\n"
    "more information.\n"
    "\n";

static void openFiles(WavInFile **inFile, WavOutFile **outFile, const RunParameters *params)
{
    int bits, samplerate, channels;

    if (strcmp(params->inFileName, "stdin") == 0)
    {
        // used 'stdin' as input file
        SET_STREAM_TO_BIN_MODE(stdin);
        *inFile = new WavInFile(stdin);
    }
    else
    {
        // open input file...
        *inFile = new WavInFile(params->inFileName);
    }

    // ... open output file with same sound parameters
    bits = (int)(*inFile)->getNumBits();
    samplerate = (int)(*inFile)->getSampleRate();
    channels = (int)(*inFile)->getNumChannels();

    if (params->outFileName)
    {
        if (strcmp(params->outFileName, "stdout") == 0)
        {
            SET_STREAM_TO_BIN_MODE(stdout);
            *outFile = new WavOutFile(stdout, samplerate, bits, channels);
        }
        else
        {
            *outFile = new WavOutFile(params->outFileName, samplerate, bits, channels);
        }
    }
    else
    {
        *outFile = NULL;
    }
}

// Sets the 'SoundTouch' object up according to input file sound format &
// command line parameters
static void setup(SoundTouch *pSoundTouch, const WavInFile *inFile, const RunParameters *params)
{
    int sampleRate;
    int channels;

    sampleRate = (int)inFile->getSampleRate();
    channels = (int)inFile->getNumChannels();
    pSoundTouch->setSampleRate(sampleRate);
    pSoundTouch->setChannels(channels);

    pSoundTouch->setTempoChange(params->tempoDelta);
    pSoundTouch->setPitchSemiTones(params->pitchDelta);
    pSoundTouch->setRateChange(params->rateDelta);

    pSoundTouch->setSetting(SETTING_USE_QUICKSEEK, params->quick);
    pSoundTouch->setSetting(SETTING_USE_AA_FILTER, !(params->noAntiAlias));

    if (params->speech)
    {
        // use settings for speech processing
        pSoundTouch->setSetting(SETTING_SEQUENCE_MS, 40);
        pSoundTouch->setSetting(SETTING_SEEKWINDOW_MS, 15);
        pSoundTouch->setSetting(SETTING_OVERLAP_MS, 8);
        fprintf(stderr, "Tune processing parameters for speech processing.\n");
    }

    // print processing information
    if (params->outFileName)
    {
#ifdef SOUNDTOUCH_INTEGER_SAMPLES
        fprintf(stderr, "Uses 16bit integer sample type in processing.\n\n");
#else
    #ifndef SOUNDTOUCH_FLOAT_SAMPLES
        #error "Sampletype not defined"
    #endif
        fprintf(stderr, "Uses 32bit floating point sample type in processing.\n\n");
#endif
        // print processing information only if outFileName given i.e. some processing will happen
        fprintf(stderr, "Processing the file with the following changes:\n");
        fprintf(stderr, "  tempo change = %+g %%\n", params->tempoDelta);
        fprintf(stderr, "  pitch change = %+g semitones\n", params->pitchDelta);
        fprintf(stderr, "  rate change  = %+g %%\n\n", params->rateDelta);
        fprintf(stderr, "Working...");
    }
    else
    {
        // outFileName not given
        fprintf(stderr, "Warning: output file name missing, won't output anything.\n\n");
    }

    fflush(stderr);
}

// Processes the sound
static void process(SoundTouch *pSoundTouch, WavInFile *inFile, WavOutFile *outFile)
{
    int nSamples;
    int nChannels;
    int buffSizeSamples;
    SAMPLETYPE sampleBuffer[BUFF_SIZE];

    if ((inFile == NULL) || (outFile == NULL)) return;  // nothing to do.

    nChannels = (int)inFile->getNumChannels();
    assert(nChannels > 0);
    buffSizeSamples = BUFF_SIZE / nChannels;

    // Process samples read from the input file
    while (inFile->eof() == 0)
    {
        int num;

        // Read a chunk of samples from the input file
        num = inFile->read(sampleBuffer, BUFF_SIZE);
        nSamples = num / (int)inFile->getNumChannels();

        // Feed the samples into SoundTouch processor
        pSoundTouch->putSamples(sampleBuffer, nSamples);

        // Read ready samples from SoundTouch processor & write them output file.
        // NOTES:
        // - 'receiveSamples' doesn't necessarily return any samples at all
        //   during some rounds!
        // - On the other hand, during some round 'receiveSamples' may have more
        //   ready samples than would fit into 'sampleBuffer', and for this reason
        //   the 'receiveSamples' call is iterated for as many times as it
        //   outputs samples.
        do
        {
            nSamples = pSoundTouch->receiveSamples(sampleBuffer, buffSizeSamples);
            outFile->write(sampleBuffer, nSamples * nChannels);
        } while (nSamples != 0);
    }

    // Now the input file is processed, yet 'flush' few last samples that are
    // hiding in the SoundTouch's internal processing pipeline.
    pSoundTouch->flush();
    do
    {
        nSamples = pSoundTouch->receiveSamples(sampleBuffer, buffSizeSamples);
        outFile->write(sampleBuffer, nSamples * nChannels);
    } while (nSamples != 0);
}

// Detect BPM rate of inFile and adjust tempo setting accordingly if necessary
static void detectBPM(WavInFile *inFile, RunParameters *params)
{
    float bpmValue;
    int nChannels;
    BPMDetect bpm(inFile->getNumChannels(), inFile->getSampleRate());
    SAMPLETYPE sampleBuffer[BUFF_SIZE];

    // detect bpm rate
    fprintf(stderr, "Detecting BPM rate...");
    fflush(stderr);

    nChannels = (int)inFile->getNumChannels();
    assert(BUFF_SIZE % nChannels == 0);

    // Process the 'inFile' in small blocks, repeat until whole file has
    // been processed
    while (inFile->eof() == 0)
    {
        int num, samples;

        // Read sample data from input file
        num = inFile->read(sampleBuffer, BUFF_SIZE);

        // Enter the new samples to the bpm analyzer class
        samples = num / nChannels;
        bpm.inputSamples(sampleBuffer, samples);
    }

    // Now the whole song data has been analyzed. Read the resulting bpm.
    bpmValue = bpm.getBpm();
    fprintf(stderr, "Done!\n");

    // rewind the file after bpm detection
    inFile->rewind();

    if (bpmValue > 0)
    {
        fprintf(stderr, "Detected BPM rate %.1f\n\n", bpmValue);
    }
    else
    {
        fprintf(stderr, "Couldn't detect BPM rate.\n\n");
        return;
    }

    if (params->goalBPM > 0)
    {
        // adjust tempo to given bpm
        params->tempoDelta = (params->goalBPM / bpmValue - 1.0f) * 100.0f;
        fprintf(stderr, "The file will be converted to %.1f BPM\n\n", params->goalBPM);
    }
}

int main(const int nParams, const char * const paramStr[])
{
    WavInFile *inFile;
    WavOutFile *outFile;
    RunParameters *params;
    SoundTouch soundTouch;

    fprintf(stderr, _helloText, SoundTouch::getVersionString());

    try
    {
        // Parse command line parameters
        params = new RunParameters(nParams, paramStr);

        // Open input & output files
        openFiles(&inFile, &outFile, params);

        if (params->detectBPM == true)
        {
            // detect sound BPM (and adjust processing parameters
            //  accordingly if necessary)
            detectBPM(inFile, params);
        }

        // Setup the 'SoundTouch' object for processing the sound
        setup(&soundTouch, inFile, params);

        // clock_t cs = clock();    // for benchmarking processing duration
        // Process the sound
        process(&soundTouch, inFile, outFile);
        // clock_t ce = clock();    // for benchmarking processing duration
        // printf("duration: %lf\n", (double)(ce-cs)/CLOCKS_PER_SEC);

        // Close WAV file handles & dispose of the objects
        delete inFile;
        delete outFile;
        delete params;

        fprintf(stderr, "Done!\n");
    }
    catch (const runtime_error &e)
    {
        // An exception occurred during processing, display an error message
        fprintf(stderr, "%s\n", e.what());
        return -1;
    }

    return 0;
}
<|endoftext|>


<commit_before>/*!
    \file console.cpp
    \brief Console management implementation
    \author Ivan Shynkarenka
    \date 29.07.2015
    \copyright MIT License
*/

#include "benchmark/console.h"

#include <cstdio>

#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif

namespace CppBenchmark {

std::ostream& operator<<(std::ostream& stream, Color color)
{
    Console::SetColor(color);
    return stream;
}

std::ostream& operator<<(std::ostream& stream, std::pair<Color, Color> colors)
{
    Console::SetColor(colors.first, colors.second);
    return stream;
}

void Console::SetColor(Color color, Color background)
{
#if defined(_WIN32) || defined(_WIN64)
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, (((WORD)color) & 0x0F) + ((((WORD)background) & 0x0F) << 4));
#elif defined(unix) || defined(__unix) || defined(__unix__)
    const char* colors[] =
    {
        "\033[22;30m",  // Black color
        "\033[22;34m",  // Blue color
        "\033[22;32m",  // Green color
        "\033[22;36m",  // Cyan color
        "\033[22;31m",  // Red color
        "\033[22;35m",  // Magenta color
        "\033[22;33m",  // Brown color
        "\033[22;37m",  // Grey color
        "\033[01;30m",  // Dark grey color
        "\033[01;34m",  // Light blue color
        "\033[01;32m",  // Light green color
        "\033[01;36m",  // Light cyan color
        "\033[01;31m",  // Light red color
        "\033[01;35m",  // Light magenta color
        "\033[01;33m",  // Yellow color
        "\033[01;37m"   // White color
    };
    const char* backgrounds[] =
    {
        "\033[00000m",  // Black color
        "\033[02;44m",  // Blue color
        "\033[02;42m",  // Green color
        "\033[02;46m",  // Cyan color
        "\033[02;41m",  // Red color
        "\033[02;45m",  // Magenta color
        "\033[02;43m",  // Brown color
        "\033[02;47m",  // Grey color
        "\033[01;40m",  // Dark grey color
        "\033[01;44m",  // Light blue color
        "\033[01;42m",  // Light green color
        "\033[01;46m",  // Light cyan color
        "\033[01;41m",  // Light red color
        "\033[01;45m",  // Light magenta color
        "\033[01;43m",  // Yellow color
        "\033[01;47m"   // White color
    };
    std::fwrite(backgrounds[(int)background - (int)Color::BLACK], 1, 8, stdout);
    std::fwrite(colors[(int)color - (int)Color::BLACK], 1, 8, stdout);
#endif
}

} // namespace CppBenchmark
<commit_msg>Bugfixing<commit_after>/*!
    \file console.cpp
    \brief Console management implementation
    \author Ivan Shynkarenka
    \date 29.07.2015
    \copyright MIT License
*/

#include "benchmark/console.h"

#include <cstdio>

#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif

namespace CppBenchmark {

std::ostream& operator<<(std::ostream& stream, Color color)
{
    Console::SetColor(color);
    return stream;
}

std::ostream& operator<<(std::ostream& stream, std::pair<Color, Color> colors)
{
    Console::SetColor(colors.first, colors.second);
    return stream;
}

void Console::SetColor(Color color, Color background)
{
#if defined(_WIN32) || defined(_WIN64)
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, (((WORD)color) & 0x0F) + ((((WORD)background) & 0x0F) << 4));
#elif defined(unix) || defined(__unix) || defined(__unix__)
    const char* colors[] =
    {
        "\033[22;30m",  // Black color
        "\033[22;34m",  // Blue color
        "\033[22;32m",  // Green color
        "\033[22;36m",  // Cyan color
        "\033[22;31m",  // Red color
        "\033[22;35m",  // Magenta color
        "\033[22;33m",  // Brown color
        "\033[22;37m",  // Grey color
        "\033[01;30m",  // Dark grey color
        "\033[01;34m",  // Light blue color
        "\033[01;32m",  // Light green color
        "\033[01;36m",  // Light cyan color
        "\033[01;31m",  // Light red color
        "\033[01;35m",  // Light magenta color
        "\033[01;33m",  // Yellow color
        "\033[01;37m"   // White color
    };
    const char* backgrounds[] =
    {
        "\033[00000m",  // Black color
        "\033[02;44m",  // Blue color
        "\033[02;42m",  // Green color
        "\033[02;46m",  // Cyan color
        "\033[02;41m",  // Red color
        "\033[02;45m",  // Magenta color
        "\033[02;43m",  // Brown color
        "\033[02;47m",  // Grey color
        "\033[00;40m",  // Dark grey color
        "\033[00;44m",  // Light blue color
        "\033[00;42m",  // Light green color
        "\033[00;46m",  // Light cyan color
        "\033[00;41m",  // Light red color
        "\033[00;45m",  // Light magenta color
        "\033[00;43m",  // Yellow color
        "\033[00;47m"   // White color
    };
    std::fwrite(backgrounds[(int)background - (int)Color::BLACK], 1, 8, stdout);
    std::fwrite(colors[(int)color - (int)Color::BLACK], 1, 8, stdout);
#endif
}

} // namespace CppBenchmark
<|endoftext|>


<commit_before>
#pragma once
#include <cxx-image/index.hxx>

#include <limits>

const double MAX_DOUBLE = std::numeric_limits<double>::max();

namespace slic
{

};

<commit_msg>Update index to match documentation<commit_after>
#pragma once
#include <cxx-image/index.hxx>

#include <limits>

namespace slic
{
    const double MAX_DOUBLE = std::numeric_limits<double>::max();

    class Point
    {
    public:
        unsigned int label;

        Point ( unsigned int _label = 0 )
            : label(_label)
        { }

        virtual ~Point ( ) { }
    };

};

<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string.h>

#include "Rtypes.h"
#include "AliHLTTPCCAClusterData.h"
#include "AliHLTTPCCAMCInfo.h"
#include "AliHLTTPCClusterMCData.h"
#include "AliHLTTPCCAParam.h"
#include "AliHLTTPCGMPhysicalTrackModel.h"
#include "AliHLTTPCGMPropagator.h"
#include "AliHLTTPCCAStandaloneFramework.h"
#include "AliHLTTPCGMMerger.h"

#include "../cmodules/qconfig.h"
#include "TRandom.h"
#include "TMath.h"
#include "TH1F.h"
#include "TFile.h"
#include "TCanvas.h"
#include "TPad.h"

#include "include.h"

#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

struct GenCluster
{
  int fSector;
  int fRow;
  int fMCID;
  float fX;
  float fY;
  float fZ;
  unsigned int fId;
};

const double kTwoPi = TMath::TwoPi();//2.*kPi;
const double kSliceDAngle = kTwoPi/18.;
const double kSliceAngleOffset = kSliceDAngle/2;

int GetSlice( double GlobalPhi )
{
  double phi = GlobalPhi;
  //  std::cout<<" GetSlice: phi = "<<phi<<std::endl;

  if( phi >= kTwoPi ) phi -= kTwoPi;
  if( phi < 0 ) phi+= kTwoPi;
  return (int) ( phi / kSliceDAngle );
}

int GetDSlice( double LocalPhi )
{
  return GetSlice( LocalPhi + kSliceAngleOffset );
}

double GetSliceAngle( int iSlice )
{
  return kSliceAngleOffset + iSlice*kSliceDAngle;
}

int RecalculateSlice( AliHLTTPCGMPhysicalTrackModel &t, int &iSlice )
{
  double phi = atan2( t.GetY(), t.GetX() );
  //  std::cout<<" recalculate: phi = "<<phi<<std::endl;
  int dSlice = GetDSlice( phi );

  if( dSlice == 0 ) return 0; // nothing to do

  //  std::cout<<" dSlice = "<<dSlice<<std::endl;
  double dAlpha = dSlice*kSliceDAngle;
  // rotate track on angle dAlpha

  t.Rotate(dAlpha);

  iSlice+=dSlice;
  if( iSlice>=18 ) iSlice-=18;
  return 1;
}

double GetGaus( double sigma )
{
  double x = 0;
  do{
    x = gRandom->Gaus(0.,sigma);
    if( fabs(x)<=3.5*sigma ) break;
  } while(1);
  return x;
}

static TH1F* hClusterError[3][2]={{0,0},{0,0},{0,0}};

void InitEventGenerator()
{
  const char* rows[3] = {"0-63","128-159","64-127"};
  for( int i=0; i<3; i++){
    for( int j=0; j<2; j++){
      char name[1024], title[1024];

      sprintf(name, "clError%s%d", (j==0 ?"Y" :"Z"), i);

      sprintf(title, "Cluster %s Error for rows %s",(j==0 ?"Y" :"Z"), rows[i]);

      hClusterError[i][j] = new TH1F(name, title, 1000, 0., .7 );
      hClusterError[i][j]->GetXaxis()->SetTitle("Cluster Error [cm]");
    }
  }
}

void FinishEventGenerator()
{
  TFile* tout = new TFile("generator.root", "RECREATE");
  TCanvas *c = new TCanvas("ClusterErrors","Cluste rErrors",0,0,700,700.*2./3.);
  c->Divide(3,2);
  int ipad=1;
  for( int j=0; j<2; j++){
    for( int i=0; i<3; i++){
      c->cd(ipad++);
      int k=i;
      if( i==1 ) k=2;
      if( i==2 ) k = 1;
      if( tout ) hClusterError[k][j]->Write();
      gPad->SetLogy();
      hClusterError[k][j]->Draw();
      //delete hClusterError[i][j];
      //hClusterError[i][j]=0;
    }
  }
  c->Print("plots/clusterErrors.pdf");
  delete c;
  if (tout){
    tout->Close();
    delete tout;
  }
}

int GenerateEvent(const AliHLTTPCCAParam& sliceParam, char* filename)
{
  static int iEvent = -1;
  iEvent++;
  if( iEvent==0 ){
    gRandom->SetSeed(configStandalone.seed);
  }

  std::ofstream out;
  out.open(filename, std::ofstream::binary);
  if (out.fail())
    {
      printf("Error opening file\n");
      return(1);
    }

  int nTracks = configStandalone.configEG.numberOfTracks; //Number of MC tracks, must be at least as large as the largest fMCID assigned above
  cout<<"NTracks "<<nTracks<<endl;
  std::vector<AliHLTTPCCAMCInfo> mcInfo(nTracks);
  memset(mcInfo.data(), 0, nTracks * sizeof(mcInfo[0]));

  //double Bz = sliceParam.ConstBz();
  //std::cout<<"Bz[kG] = "<<sliceParam.BzkG()<<std::endl;

  AliHLTTPCGMPropagator prop;
  {
    prop.SetToyMCEventsFlag( kTRUE );
    AliHLTTPCCAStandaloneFramework &hlt = AliHLTTPCCAStandaloneFramework::Instance();
    const AliHLTTPCGMMerger &merger = hlt.Merger();
    prop.SetPolynomialField( merger.pField() );
  }

  //  const double kCLight = 0.000299792458;
  //Bz*=kCLight;

  std::vector<GenCluster> vClusters;
  int clusterId = 0; //Here we count up the cluster ids we fill (must be unique).
  //gRandom->SetSeed(0);
  //unsigned int seed = gRandom->GetSeed();

  for (int itr = 0; itr < nTracks; itr++){
    // std::cout<<"Track "<<itr<<":"<<std::endl;
    //gRandom->SetSeed(seed);

    mcInfo[itr].fPID = -100; //-100: Unknown / other, 0: Electron, 1, Muon, 2: Pion, 3: Kaon, 4: Proton
    mcInfo[itr].fCharge = 1;
    mcInfo[itr].fPrim = 1; //Primary particle
    mcInfo[itr].fPrimDaughters = 0; //Primary particle with daughters in the TPC
    mcInfo[itr].fX = 0; //Position of MC track at entry of TPC / first hit in the TPC
    mcInfo[itr].fY = 0;
    mcInfo[itr].fZ = 0;
    mcInfo[itr].fPx = 0; //Momentum of MC track at that position
    mcInfo[itr].fPy = 0;
    mcInfo[itr].fPz = 0;

    AliHLTTPCGMPhysicalTrackModel t;
    double dphi = kTwoPi/nTracks;
    double phi = kSliceAngleOffset + dphi*itr;
    double eta = gRandom->Uniform(-1.5,1.5);

    double theta = 2*TMath::ATan(1./TMath::Exp(eta));
    double lambda = theta-TMath::Pi()/2;
    //double theta = gRandom->Uniform(-60,60)*TMath::Pi()/180.;
    double pt = .08*std::pow(10,gRandom->Uniform(0,2.2));

    double q = 1.;
    int iSlice = GetSlice( phi );
    phi = phi - GetSliceAngle( iSlice );

    //std::cout<<"phi = "<<phi<<std::endl;
    double x0 = cos(phi);
    double y0 = sin(phi);
    double z0 = tan(lambda);
    t.Set( x0, y0, z0, pt*x0, pt*y0, pt*z0, q);

    if( RecalculateSlice(t,iSlice) !=0 ){
      std::cout<<"Initial slice wrong!!!"<<std::endl;
      //exit(0);
    }

    for( int iRow=0; iRow<sliceParam.NRows(); iRow++ ){
      //if( iRow>=50 ) break; //SG!!!
      float xRow = sliceParam.RowX( iRow );
      // transport to row
      int err = 0;
      for( int itry=0; itry<1; itry++ ){
	float B[3];
	prop.GetBxByBz( GetSliceAngle( iSlice ), t.GetX(), t.GetY(), t.GetZ(), B );
	float dLp=0;
	err = t.PropagateToXBxByBz( xRow, B[0], B[1], B[2], dLp );
	if( err ){
	  std::cout<<"Can not propagate to x = "<<xRow<<std::endl;
	  t.Print();
	  break;
	}
	if( fabs(t.GetZ())>=250. ){
	  std::cout<<"Can not propagate to x = "<<xRow<<": Z outside the volume"<<std::endl;
	  t.Print();
	  err = -1;
	  break;
	}
	// rotate track coordinate system to current sector
	int isNewSlice = RecalculateSlice(t,iSlice);
	if( !isNewSlice ) break;
	else{
	  std::cout<<"track "<<itr<<": new slice "<<iSlice<<" at row "<<iRow<<std::endl;
	}
      }
      if( err ) break;
      //std::cout<<" track "<<itr<<": Slice "<<iSlice<<" row "<<iRow<<" params :"<<std::endl;
      //t.Print();
      // track at row iRow, slice iSlice
      if( iRow==0 ){ // store MC track at first row
	//std::cout<<std::setprecision( 20 );
	//std::cout<<"track "<<itr<<": x "<<t.X()<<" y "<<t.Y()<<" z "<<t.Z()<<std::endl;
	AliHLTTPCGMPhysicalTrackModel tg(t); // global coordinates
	tg.Rotate( - GetSliceAngle( iSlice ));

	mcInfo[itr].fPID = 2; // pion
	mcInfo[itr].fCharge = 3*q;
	mcInfo[itr].fX = tg.GetX(); //Position of MC track at entry of TPC / first hit in the TPC
	mcInfo[itr].fY = tg.GetY();
	mcInfo[itr].fZ = tg.GetZ();
	mcInfo[itr].fPx = tg.GetPx(); //Momentum of MC track at that position
	mcInfo[itr].fPy = tg.GetPy();
	mcInfo[itr].fPz = tg.GetPz();
	// std::cout<<" mc Z = "<<tg.GetZ()<<std::endl;
      }

      // create cluster
      GenCluster c;
      float sigmaY = 0.3;
      float sigmaZ = 0.5;
      const int rowType = iRow < 64 ? 0 : iRow < 128 ? 2 : 1;
      t.UpdateValues();
      //sliceParam.GetClusterErrors2v1( rowType, t.GetZ(), t.GetSinPhi(), t.GetCosPhi(), t.GetDzDs(), sigmaY, sigmaZ );
      sliceParam.GetClusterErrors2( rowType, t.GetZ(), t.GetSinPhi(), t.GetCosPhi(), t.GetDzDs(), sigmaY, sigmaZ );
      sigmaY = sqrt(sigmaY);
      sigmaZ = sqrt(sigmaZ);
      hClusterError[rowType][0]->Fill(sigmaY);
      hClusterError[rowType][1]->Fill(sigmaZ);
      //std::cout<<sigmaY<<" "<<sigmaY<<std::endl;
      //if( sigmaY > 0.5 ) sigmaY = 0.5;
      //if( sigmaZ > 0.5 ) sigmaZ = 0.5;
      c.fSector = (t.GetZ()>=0.) ?iSlice :iSlice+18;
      c.fRow = iRow;
      c.fMCID = itr;
      c.fX = t.GetX();
      c.fY = t.GetY() + GetGaus(sigmaY);
      c.fZ = t.GetZ() + GetGaus(sigmaZ);
      c.fId = clusterId++;
      vClusters.push_back(c);
    } // iRow
  } // itr

  std::vector<AliHLTTPCClusterMCLabel> labels;

  for (int iSector = 0;iSector < 36;iSector++) //HLT Sector numbering, sectors go from 0 to 35, all spanning all rows from 0 to 158.
    {
      int nNumberOfHits = 0;
      for( unsigned int i=0; i<vClusters.size(); i++ ) if( vClusters[i].fSector==iSector ) nNumberOfHits++;
      //For every sector we first have to fill the number of hits in this sector to the file
      out.write((char*) &nNumberOfHits, sizeof(nNumberOfHits));

      AliHLTTPCCAClusterData::Data* clusters = new AliHLTTPCCAClusterData::Data[nNumberOfHits];
      int icl=0;
      for( unsigned int i=0; i<vClusters.size(); i++ ){
	GenCluster &c = vClusters[i];
	if( c.fSector==iSector ){
	  clusters[icl].fId = c.fId;
	  clusters[icl].fRow = c.fRow; //We fill one hit per TPC row
	  clusters[icl].fX = c.fX;
	  clusters[icl].fY = c.fY;
	  clusters[icl].fZ = c.fZ;
	  clusters[icl].fAmp = 100; //Arbitrary amplitude
	  icl++;
	  AliHLTTPCClusterMCLabel clusterLabel;
	  for (int j = 0;j < 3;j++){
	    clusterLabel.fClusterID[j].fMCID = -1;
	    clusterLabel.fClusterID[j].fWeight = 0;
	  }
	  clusterLabel.fClusterID[0].fMCID = c.fMCID;
	  clusterLabel.fClusterID[0].fWeight = 1;
	  labels.push_back( clusterLabel);
	}
      }
      out.write((char*) clusters, sizeof(clusters[0]) * nNumberOfHits);
      delete clusters;
    }

  //Create vector with cluster MC labels, clusters are counter from 0 to clusterId in the order they have been written above. No separation in slices.

  out.write((const char*) labels.data(), labels.size() * sizeof(labels[0]));
  labels.clear();

  out.write((const char*) &nTracks, sizeof(nTracks));
  out.write((const char*) mcInfo.data(), nTracks * sizeof(mcInfo[0]));
  mcInfo.clear();

  out.close();
  return(0);
}
<commit_msg>compilation fix<commit_after>#include <iostream>
#include <fstream>
#include <string.h>

#include "Rtypes.h"
#include "AliHLTTPCCAClusterData.h"
#include "AliHLTTPCCAMCInfo.h"
#include "AliHLTTPCClusterMCData.h"
#include "AliHLTTPCCAParam.h"
#include "AliHLTTPCGMPhysicalTrackModel.h"
#include "AliHLTTPCGMPropagator.h"
#include "AliHLTTPCCAStandaloneFramework.h"
#include "AliHLTTPCGMMerger.h"

#include "../cmodules/qconfig.h"
#include "TRandom.h"
#include "TMath.h"
#include "TH1F.h"
#include "TFile.h"
#include "TCanvas.h"
#include "TPad.h"

#include "include.h"

#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

struct GenCluster
{
  int fSector;
  int fRow;
  int fMCID;
  float fX;
  float fY;
  float fZ;
  unsigned int fId;
};

const double kTwoPi = TMath::TwoPi();//2.*kPi;
const double kSliceDAngle = kTwoPi/18.;
const double kSliceAngleOffset = kSliceDAngle/2;

int GetSlice( double GlobalPhi )
{
  double phi = GlobalPhi;
  //  std::cout<<" GetSlice: phi = "<<phi<<std::endl;

  if( phi >= kTwoPi ) phi -= kTwoPi;
  if( phi < 0 ) phi+= kTwoPi;
  return (int) ( phi / kSliceDAngle );
}

int GetDSlice( double LocalPhi )
{
  return GetSlice( LocalPhi + kSliceAngleOffset );
}

double GetSliceAngle( int iSlice )
{
  return kSliceAngleOffset + iSlice*kSliceDAngle;
}

int RecalculateSlice( AliHLTTPCGMPhysicalTrackModel &t, int &iSlice )
{
  double phi = atan2( t.GetY(), t.GetX() );
  //  std::cout<<" recalculate: phi = "<<phi<<std::endl;
  int dSlice = GetDSlice( phi );

  if( dSlice == 0 ) return 0; // nothing to do

  //  std::cout<<" dSlice = "<<dSlice<<std::endl;
  double dAlpha = dSlice*kSliceDAngle;
  // rotate track on angle dAlpha

  t.Rotate(dAlpha);

  iSlice+=dSlice;
  if( iSlice>=18 ) iSlice-=18;
  return 1;
}

double GetGaus( double sigma )
{
  double x = 0;
  do{
    x = gRandom->Gaus(0.,sigma);
    if( fabs(x)<=3.5*sigma ) break;
  } while(1);
  return x;
}

static TH1F* hClusterError[3][2]={{0,0},{0,0},{0,0}};

void InitEventGenerator()
{
  const char* rows[3] = {"0-63","128-159","64-127"};
  for( int i=0; i<3; i++){
    for( int j=0; j<2; j++){
      char name[1024], title[1024];

      sprintf(name, "clError%s%d", (j==0 ?"Y" :"Z"), i);

      sprintf(title, "Cluster %s Error for rows %s",(j==0 ?"Y" :"Z"), rows[i]);

      hClusterError[i][j] = new TH1F(name, title, 1000, 0., .7 );
      hClusterError[i][j]->GetXaxis()->SetTitle("Cluster Error [cm]");
    }
  }
}

void FinishEventGenerator()
{
  TFile* tout = new TFile("generator.root", "RECREATE");
  TCanvas *c = new TCanvas("ClusterErrors","Cluste rErrors",0,0,700,700.*2./3.);
  c->Divide(3,2);
  int ipad=1;
  for( int j=0; j<2; j++){
    for( int i=0; i<3; i++){
      c->cd(ipad++);
      int k=i;
      if( i==1 ) k=2;
      if( i==2 ) k = 1;
      if( tout ) hClusterError[k][j]->Write();
      gPad->SetLogy();
      hClusterError[k][j]->Draw();
      //delete hClusterError[i][j];
      //hClusterError[i][j]=0;
    }
  }
  c->Print("plots/clusterErrors.pdf");
  delete c;
  if (tout){
    tout->Close();
    delete tout;
  }
}

int GenerateEvent(const AliHLTTPCCAParam& sliceParam, char* filename)
{
  static int iEvent = -1;
  iEvent++;
  if( iEvent==0 ){
    gRandom->SetSeed(configStandalone.seed);
  }

  std::ofstream out;
  out.open(filename, std::ofstream::binary);
  if (out.fail())
    {
      printf("Error opening file\n");
      return(1);
    }

  int nTracks = configStandalone.configEG.numberOfTracks; //Number of MC tracks, must be at least as large as the largest fMCID assigned above
  cout<<"NTracks "<<nTracks<<endl;
  std::vector<AliHLTTPCCAMCInfo> mcInfo(nTracks);
  memset(mcInfo.data(), 0, nTracks * sizeof(mcInfo[0]));

  //double Bz = sliceParam.ConstBz();
  //std::cout<<"Bz[kG] = "<<sliceParam.BzkG()<<std::endl;

  AliHLTTPCGMPropagator prop;
  {
    prop.SetToyMCEventsFlag( kTRUE );
    AliHLTTPCCAStandaloneFramework &hlt = AliHLTTPCCAStandaloneFramework::Instance();
    const AliHLTTPCGMMerger &merger = hlt.Merger();
    prop.SetPolynomialField( merger.pField() );
  }

  //  const double kCLight = 0.000299792458;
  //Bz*=kCLight;

  std::vector<GenCluster> vClusters;
  int clusterId = 0; //Here we count up the cluster ids we fill (must be unique).
  //gRandom->SetSeed(0);
  //unsigned int seed = gRandom->GetSeed();

  for (int itr = 0; itr < nTracks; itr++){
    // std::cout<<"Track "<<itr<<":"<<std::endl;
    //gRandom->SetSeed(seed);

    mcInfo[itr].fPID = -100; //-100: Unknown / other, 0: Electron, 1, Muon, 2: Pion, 3: Kaon, 4: Proton
    mcInfo[itr].fCharge = 1;
    mcInfo[itr].fPrim = 1; //Primary particle
    mcInfo[itr].fPrimDaughters = 0; //Primary particle with daughters in the TPC
    mcInfo[itr].fX = 0; //Position of MC track at entry of TPC / first hit in the TPC
    mcInfo[itr].fY = 0;
    mcInfo[itr].fZ = 0;
    mcInfo[itr].fPx = 0; //Momentum of MC track at that position
    mcInfo[itr].fPy = 0;
    mcInfo[itr].fPz = 0;

    AliHLTTPCGMPhysicalTrackModel t;
    double dphi = kTwoPi/nTracks;
    double phi = kSliceAngleOffset + dphi*itr;
    double eta = gRandom->Uniform(-1.5,1.5);

    double theta = 2*TMath::ATan(1./TMath::Exp(eta));
    double lambda = theta-TMath::Pi()/2;
    //double theta = gRandom->Uniform(-60,60)*TMath::Pi()/180.;
    double pt = .08*std::pow(10,gRandom->Uniform(0,2.2));

    double q = 1.;
    int iSlice = GetSlice( phi );
    phi = phi - GetSliceAngle( iSlice );

    //std::cout<<"phi = "<<phi<<std::endl;
    double x0 = cos(phi);
    double y0 = sin(phi);
    double z0 = tan(lambda);
    t.Set( x0, y0, z0, pt*x0, pt*y0, pt*z0, q);

    if( RecalculateSlice(t,iSlice) !=0 ){
      std::cout<<"Initial slice wrong!!!"<<std::endl;
      //exit(0);
    }

    for( int iRow=0; iRow<sliceParam.NRows(); iRow++ ){
      //if( iRow>=50 ) break; //SG!!!
      float xRow = sliceParam.RowX( iRow );
      // transport to row
      int err = 0;
      for( int itry=0; itry<1; itry++ ){
	float B[3];
	prop.GetBxByBz( GetSliceAngle( iSlice ), t.GetX(), t.GetY(), t.GetZ(), B );
	float dLp=0;
	err = t.PropagateToXBxByBz( xRow, B[0], B[1], B[2], dLp );
	if( err ){
	  std::cout<<"Can not propagate to x = "<<xRow<<std::endl;
	  t.Print();
	  break;
	}
	if( fabs(t.GetZ())>=250. ){
	  std::cout<<"Can not propagate to x = "<<xRow<<": Z outside the volume"<<std::endl;
	  t.Print();
	  err = -1;
	  break;
	}
	// rotate track coordinate system to current sector
	int isNewSlice = RecalculateSlice(t,iSlice);
	if( !isNewSlice ) break;
	else{
	  std::cout<<"track "<<itr<<": new slice "<<iSlice<<" at row "<<iRow<<std::endl;
	}
      }
      if( err ) break;
      //std::cout<<" track "<<itr<<": Slice "<<iSlice<<" row "<<iRow<<" params :"<<std::endl;
      //t.Print();
      // track at row iRow, slice iSlice
      if( iRow==0 ){ // store MC track at first row
	//std::cout<<std::setprecision( 20 );
	//std::cout<<"track "<<itr<<": x "<<t.X()<<" y "<<t.Y()<<" z "<<t.Z()<<std::endl;
	AliHLTTPCGMPhysicalTrackModel tg(t); // global coordinates
	tg.Rotate( - GetSliceAngle( iSlice ));

	mcInfo[itr].fPID = 2; // pion
	mcInfo[itr].fCharge = 3*q;
	mcInfo[itr].fX = tg.GetX(); //Position of MC track at entry of TPC / first hit in the TPC
	mcInfo[itr].fY = tg.GetY();
	mcInfo[itr].fZ = tg.GetZ();
	mcInfo[itr].fPx = tg.GetPx(); //Momentum of MC track at that position
	mcInfo[itr].fPy = tg.GetPy();
	mcInfo[itr].fPz = tg.GetPz();
	// std::cout<<" mc Z = "<<tg.GetZ()<<std::endl;
      }

      // create cluster
      GenCluster c;
      float sigmaY = 0.3;
      float sigmaZ = 0.5;
      const int rowType = iRow < 64 ? 0 : iRow < 128 ? 2 : 1;
      t.UpdateValues();
      //sliceParam.GetClusterErrors2v1( rowType, t.GetZ(), t.GetSinPhi(), t.GetCosPhi(), t.GetDzDs(), sigmaY, sigmaZ );
      sliceParam.GetClusterErrors( rowType, t.GetZ(), t.GetSinPhi(), t.GetCosPhi(), t.GetDzDs(), sigmaY, sigmaZ );
      hClusterError[rowType][0]->Fill(sigmaY);
      hClusterError[rowType][1]->Fill(sigmaZ);
      //std::cout<<sigmaY<<" "<<sigmaY<<std::endl;
      //if( sigmaY > 0.5 ) sigmaY = 0.5;
      //if( sigmaZ > 0.5 ) sigmaZ = 0.5;
      c.fSector = (t.GetZ()>=0.) ?iSlice :iSlice+18;
      c.fRow = iRow;
      c.fMCID = itr;
      c.fX = t.GetX();
      c.fY = t.GetY() + GetGaus(sigmaY);
      c.fZ = t.GetZ() + GetGaus(sigmaZ);
      c.fId = clusterId++;
      vClusters.push_back(c);
    } // iRow
  } // itr

  std::vector<AliHLTTPCClusterMCLabel> labels;

  for (int iSector = 0;iSector < 36;iSector++) //HLT Sector numbering, sectors go from 0 to 35, all spanning all rows from 0 to 158.
    {
      int nNumberOfHits = 0;
      for( unsigned int i=0; i<vClusters.size(); i++ ) if( vClusters[i].fSector==iSector ) nNumberOfHits++;
      //For every sector we first have to fill the number of hits in this sector to the file
      out.write((char*) &nNumberOfHits, sizeof(nNumberOfHits));

      AliHLTTPCCAClusterData::Data* clusters = new AliHLTTPCCAClusterData::Data[nNumberOfHits];
      int icl=0;
      for( unsigned int i=0; i<vClusters.size(); i++ ){
	GenCluster &c = vClusters[i];
	if( c.fSector==iSector ){
	  clusters[icl].fId = c.fId;
	  clusters[icl].fRow = c.fRow; //We fill one hit per TPC row
	  clusters[icl].fX = c.fX;
	  clusters[icl].fY = c.fY;
	  clusters[icl].fZ = c.fZ;
	  clusters[icl].fAmp = 100; //Arbitrary amplitude
	  icl++;
	  AliHLTTPCClusterMCLabel clusterLabel;
	  for (int j = 0;j < 3;j++){
	    clusterLabel.fClusterID[j].fMCID = -1;
	    clusterLabel.fClusterID[j].fWeight = 0;
	  }
	  clusterLabel.fClusterID[0].fMCID = c.fMCID;
	  clusterLabel.fClusterID[0].fWeight = 1;
	  labels.push_back( clusterLabel);
	}
      }
      out.write((char*) clusters, sizeof(clusters[0]) * nNumberOfHits);
      delete clusters;
    }

  //Create vector with cluster MC labels, clusters are counter from 0 to clusterId in the order they have been written above. No separation in slices.

  out.write((const char*) labels.data(), labels.size() * sizeof(labels[0]));
  labels.clear();

  out.write((const char*) &nTracks, sizeof(nTracks));
  out.write((const char*) mcInfo.data(), nTracks * sizeof(mcInfo[0]));
  mcInfo.clear();

  out.close();
  return(0);
}
<|endoftext|>


<commit_before>#include "OStreamServerLog.h"

#include <iostream>
#include <iomanip>

using namespace HTTP::ServerLog;

const char *GetMethodName(HTTP::METHOD Method)
{
	switch (Method)
	{
	case HTTP::METHOD_GET: return "GET ";
	case HTTP::METHOD_POST: return "POST";
	case HTTP::METHOD_HEAD: return "HEAD";
	default: return "-";
	}
}

void PrintBandwidth(std::ostream &Target, double Value)
{
	std::streamsize PrevPrec=Target.precision(1);
	if (Value>1024*1024*2)
		Target << std::fixed << Value/(1024*1024) << " MB/s";
	else if (Value>1024*2)
		Target << std::fixed << Value/1024 << " kB/s";
	else
		Target << std::fixed << Value << " B/s";
	Target.precision(PrevPrec);
}

void OStream::OnConnection(void *Connection, unsigned int SourceAddr, bool IsAllowed)
{
	if (IsAllowed)
	{
		ConnDataHolder &CurrHolder=ConnMap[Connection];

		char AddrBuff[20];
		sprintf(AddrBuff,"%u.%u.%u.%u",
			(SourceAddr >> 24),
			(SourceAddr >> 16) & 0xFF,
			(SourceAddr >>  8) & 0xFF,
			(SourceAddr >>  0) & 0xFF);

		CurrHolder.SourceAddr=AddrBuff;
		CurrHolder.SourceAddr.append((4*3+3)-CurrHolder.SourceAddr.length(),' ');
	}
}

void OStream::OnConnectionFinished(void *Connection)
{
	boost::unordered_map<void *,ConnDataHolder>::iterator FindI=ConnMap.find(Connection);
	if (FindI!=ConnMap.end())
	{
		if (FindI->second.IsWebSocket)
		{
			TargetS <<
				FindI->second.SourceAddr << " WebSocketClose" <<
				std::endl;
		}

		ConnMap.erase(FindI);
	}
}

void OStream::OnRequest(void *Connection, HTTP::METHOD Method, const std::string &Resource, const HTTP::QueryParams &Query, const std::vector<HTTP::Header> &HeaderA,
	unsigned long long ContentLength, const unsigned char *ContentBuff, const unsigned char *ContentBuffEnd,
	unsigned int ResponseCode, unsigned long long ResponseLength,
	double ReqTime, double RespTime,
	void *UpgradeConn)
{
	boost::unordered_map<void *,ConnDataHolder>::iterator FindI=ConnMap.find(Connection);

	if (FindI!=ConnMap.end())
	{
		TargetS <<
			FindI->second.SourceAddr << " " <<
			GetMethodName(Method) << " " <<
			Resource << " (" << ContentLength << "; ";
		PrintBandwidth(TargetS,ContentLength/ReqTime);
		TargetS << "): "
			<< ResponseCode << " (" << ResponseLength << "; ";
		PrintBandwidth(TargetS,ResponseLength/RespTime);
		TargetS << ")" <<
			std::endl;

		if ((UpgradeConn) && (FindI->second.IsWebSocket))
		{
			ConnMap[UpgradeConn]=FindI->second;
			ConnMap.erase(FindI);
		}
	}
}

void OStream::OnWebSocket(void *Connection, const std::string &Resource, bool IsSuccess, const char *Origin, const char *SubProtocol)
{
	if (IsSuccess)
	{
		ConnDataHolder &CurrHolder=ConnMap[Connection];

		TargetS <<
			CurrHolder.SourceAddr << " WebSocket " <<
			(Origin ? Origin : "") << ": " <<
			(SubProtocol ? SubProtocol : "-") <<
			std::endl;

		CurrHolder.IsWebSocket=true;
	}
}
<commit_msg>OStreamServerLog: refactor<commit_after>#include "OStreamServerLog.h"

#include <iostream>
#include <iomanip>

using namespace HTTP::ServerLog;

const char *GetMethodName(HTTP::METHOD Method)
{
	switch (Method)
	{
	case HTTP::METHOD_GET: return "GET ";
	case HTTP::METHOD_POST: return "POST";
	case HTTP::METHOD_HEAD: return "HEAD";
	default: return "-";
	}
}

void PrintTransferSpeed(std::ostream &Target, double Value)
{
	std::streamsize PrevPrec=Target.precision(1);
	if (Value>1024*1024*2)
		Target << std::fixed << Value/(1024*1024) << " MB/s";
	else if (Value>1024*2)
		Target << std::fixed << Value/1024 << " kB/s";
	else
		Target << std::fixed << Value << " B/s";
	Target.precision(PrevPrec);
}

void OStream::OnConnection(void *Connection, unsigned int SourceAddr, bool IsAllowed)
{
	if (IsAllowed)
	{
		ConnDataHolder &CurrHolder=ConnMap[Connection];

		char AddrBuff[20];
		sprintf(AddrBuff,"%u.%u.%u.%u",
			(SourceAddr >> 24),
			(SourceAddr >> 16) & 0xFF,
			(SourceAddr >>  8) & 0xFF,
			(SourceAddr >>  0) & 0xFF);

		CurrHolder.SourceAddr=AddrBuff;
		CurrHolder.SourceAddr.append((4*3+3)-CurrHolder.SourceAddr.length(),' ');
	}
}

void OStream::OnConnectionFinished(void *Connection)
{
	boost::unordered_map<void *,ConnDataHolder>::iterator FindI=ConnMap.find(Connection);
	if (FindI!=ConnMap.end())
	{
		if (FindI->second.IsWebSocket)
		{
			TargetS <<
				FindI->second.SourceAddr << " WebSocketClose" <<
				std::endl;
		}

		ConnMap.erase(FindI);
	}
}

void OStream::OnRequest(void *Connection, HTTP::METHOD Method, const std::string &Resource, const HTTP::QueryParams &Query, const std::vector<HTTP::Header> &HeaderA,
	unsigned long long ContentLength, const unsigned char *ContentBuff, const unsigned char *ContentBuffEnd,
	unsigned int ResponseCode, unsigned long long ResponseLength,
	double ReqTime, double RespTime,
	void *UpgradeConn)
{
	boost::unordered_map<void *,ConnDataHolder>::iterator FindI=ConnMap.find(Connection);

	if (FindI!=ConnMap.end())
	{
		TargetS <<
			FindI->second.SourceAddr << " " <<
			GetMethodName(Method) << " " <<
			Resource << " (" << ContentLength << "; ";
		PrintTransferSpeed(TargetS,ContentLength/ReqTime);
		TargetS << "): "
			<< ResponseCode << " (" << ResponseLength << "; ";
		PrintTransferSpeed(TargetS,ResponseLength/RespTime);
		TargetS << ")" <<
			std::endl;

		if ((UpgradeConn) && (FindI->second.IsWebSocket))
		{
			ConnMap[UpgradeConn]=FindI->second;
			ConnMap.erase(FindI);
		}
	}
}

void OStream::OnWebSocket(void *Connection, const std::string &Resource, bool IsSuccess, const char *Origin, const char *SubProtocol)
{
	if (IsSuccess)
	{
		ConnDataHolder &CurrHolder=ConnMap[Connection];

		TargetS <<
			CurrHolder.SourceAddr << " WebSocket " <<
			(Origin ? Origin : "") << ": " <<
			(SubProtocol ? SubProtocol : "-") <<
			std::endl;

		CurrHolder.IsWebSocket=true;
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperChoiceParameter.h"
#include "otbWrapperListViewParameter.h"
#include "otbWrapperBoolParameter.h"
#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperTypes.h"
#include "otbWrapperApplication.h"

#include <vector>
#include <string>
#include <iostream>
#include <cassert>
#include <fstream>

int main(int argc, char* argv[])
{
  if (argc < 3)
    {
      std::cerr << "Usage : " << argv[0] << " name OTB_APPLICATION_PATH" << std::endl;
      return EXIT_FAILURE;
    }

  using namespace otb::Wrapper;

  const std::string module(argv[1]);

  /* TestApplication is removed in CMakeLists.txt */
#if 0
  if (module == "TestApplication")
    return EXIT_SUCCESS;
#endif

  ApplicationRegistry::AddApplicationPath(argv[2]);
  Application::Pointer appli =  ApplicationRegistry::CreateApplicationFaster(module.c_str());

  assert(!appli.IsNull());

  appli->Init();

  std::map<ParameterType, std::string> parameterTypeToString;

  parameterTypeToString[ParameterType_Empty] = "QgsProcessingParameterBoolean";
  parameterTypeToString[ParameterType_Bool] = "QgsProcessingParameterBoolean";
  parameterTypeToString[ParameterType_Int] = "QgsProcessingParameterNumber";
  parameterTypeToString[ParameterType_Float] = "QgsProcessingParameterNumber";
  parameterTypeToString[ParameterType_RAM] = "QgsProcessingParameterNumber";
  parameterTypeToString[ParameterType_Radius] = "QgsProcessingParameterNumber";
  parameterTypeToString[ParameterType_Choice] = "OTBParameterChoice";
  parameterTypeToString[ParameterType_String] = "QgsProcessingParameterString";
  parameterTypeToString[ParameterType_InputImage] = "QgsProcessingParameterRasterLayer";
  parameterTypeToString[ParameterType_InputFilename] = "QgsProcessingParameterFile";
  parameterTypeToString[ParameterType_InputImageList] = "QgsProcessingParameterMultipleLayers";
  parameterTypeToString[ParameterType_InputVectorData] = "QgsProcessingParameterVectorLayer";
  parameterTypeToString[ParameterType_InputFilenameList] = "QgsProcessingParameterMultipleLayers";
  parameterTypeToString[ParameterType_InputVectorDataList] = "QgsProcessingParameterMultipleLayers";
  parameterTypeToString[ParameterType_OutputImage] = "QgsProcessingParameterRasterDestination";
  parameterTypeToString[ParameterType_OutputVectorData] = "QgsProcessingParameterVectorDestination";
  parameterTypeToString[ParameterType_OutputFilename] = "QgsProcessingParameterFileDestination";
  parameterTypeToString[ParameterType_Directory] = "QgsProcessingParameterFile";
  //TODO
  parameterTypeToString[ParameterType_StringList] = "QgsProcessingParameterString";

  const std::vector<std::string> appKeyList = appli->GetParametersKeys(true);
  const unsigned int nbOfParam = appKeyList.size();

  std::ofstream dFile;
  dFile.open (module + ".txt", std::ios::out);

  std::string output_parameter_name;
  bool hasRasterOutput = false;
  for (unsigned int i = 0; i < nbOfParam; i++)
    {
      Parameter::Pointer param = appli->GetParameterByKey(appKeyList[i]);
      if (param->GetMandatory())
	{
	  ParameterType type = appli->GetParameterType(appKeyList[i]);
	  if (type == ParameterType_OutputImage )
	    {
	      output_parameter_name = appKeyList[i];
	      hasRasterOutput = true;
	    }
	}
    }

  if(output_parameter_name.empty())
    dFile << module << std::endl;
  else
    dFile << module << "|" <<  output_parameter_name << std::endl;

  dFile << appli->GetDescription() << std::endl;
  const std::string group = appli->GetDocTags().size() > 0 ? appli->GetDocTags()[0] : "UNCLASSIFIED";
  dFile << group << std::endl;

  for (unsigned int i = 0; i < nbOfParam; i++)
    {
      const std::string name = appKeyList[i];

      Parameter::Pointer param = appli->GetParameterByKey(name);
      ParameterType type = appli->GetParameterType(name);
      const std::string description = param->GetName();
      const std::string qgis_type = parameterTypeToString[type];

      //ListView parameters types are added as N number of QgsParameterBoolean where N being
      //number of items in a listview.
      //Example case: RadiometricIndices application
      //For next update of plugin code ListView can use custom widget wrapper and behave
      //exactly like OTB.
      if(type == ParameterType_ListView)
	{
	  ListViewParameter *lparam = dynamic_cast<ListViewParameter*>(param.GetPointer());
	  for( unsigned int c = 0; c < lparam->GetNbChoices(); ++c )
	    dFile << "QgsProcessingParameterBoolean|"
		  << lparam->GetChoiceKey(c)  << "|"
		  << lparam->GetChoiceName(c)
		  << "|False|True" << std::endl;
	}

      if (  type == ParameterType_Group  ||
	    type == ParameterType_OutputProcessXML  ||
	    type == ParameterType_InputProcessXML  ||
	    type == ParameterType_ListView ||
	    type == ParameterType_RAM
	    )
	{
	  // group parameter cannot have any value.
	  //outxml and inxml parameters are not relevant for QGIS and is considered a bit noisy
	  //ram is added by qgis-otb processing provider plugin as an advanced parameter for all apps
	  //listview is a special case. We indeed add them to descriptor file but with different logic.
	  continue;
	}

      assert(!qgis_type.empty());
      if(qgis_type.empty())
	{
	  std::cerr << "No mapping found for parameter '" <<name <<"' type=" << type << std::endl;
	  return EXIT_FAILURE;
	}

      bool isDestination = false;

      dFile << qgis_type << "|" << name << "|" << description;

      std::string default_value = "None";
      if (type == ParameterType_Int)
	{
	  dFile << "|QgsProcessingParameterNumber.Integer";
	  default_value = param->HasValue() ? appli->GetParameterAsString(name): "0";
	}
      else if (type == ParameterType_Float)
	{
	  dFile << "|QgsProcessingParameterNumber.Double";
	  default_value = param->HasValue() ? appli->GetParameterAsString(name): "0";
	}
      else if (type == ParameterType_Radius)
	{
	  dFile << "|QgsProcessingParameterNumber.Integer";
	  default_value = param->HasValue() ? appli->GetParameterAsString(name): "0";
	}
      else if(type == ParameterType_InputFilename)
	{
	  dFile << "|QgsProcessingParameterFile.File|txt";
	}
      else if(type == ParameterType_Directory)
	{
	  dFile << "|QgsProcessingParameterFile.Folder|False";
	}
      else if (type == ParameterType_InputImageList)
	{
	   dFile << "|3";
	}
      else if (type == ParameterType_InputVectorDataList)
	{
	  dFile << "|-1";
	}
      else if (type == ParameterType_InputVectorData)
	{
	  dFile << "|-1";
	}
      else if(type == ParameterType_InputFilenameList)
	{
	  dFile << "|4";
	}
      else if (type == ParameterType_InputImage)
	{
	  //default is None and nothing to add to dFile
	}
      else if(type ==ParameterType_String)
	{
	  //default is None and nothing to add to dFile
	}
      else if(type ==ParameterType_StringList)
	{
	  //default is None and nothing to add to dFile
	}
      else if(type == ParameterType_Bool)
	{
	  //BoolParameter *bparam = dynamic_cast<BoolParameter*>(param.GetPointer());
	  //default_value = bparam->GetValueAsString();
	  default_value =  appli->GetParameterAsString(name);
	}
      else if(type == ParameterType_Choice)
	{
	  std::vector<std::string>  key_list  = appli->GetChoiceKeys(name);
	  std::string values = "";
	  for( auto k : key_list)
	    values += k + ";";

	  values.pop_back();
	  dFile << "|" << values ;
	  ChoiceParameter *cparam = dynamic_cast<ChoiceParameter*>(param.GetPointer());
	  default_value = std::to_string(cparam->GetValue());
	}
      else if(type == ParameterType_OutputVectorData ||
	      type == ParameterType_OutputImage ||
	      type == ParameterType_OutputFilename)
	{
	  //no need for default_value, optional and extra fields in dFile
	  //if parameter is a destination type. qgis_type|name|description is enough.
	  //so we simply set isDestination to true and skip to end to append a new line.
	  isDestination =  true;
	}
      else
	{
     	  std::cout << "ERROR: default_value is empty for '" << name << "' type='" << qgis_type << "'" << std::endl;
	  return EXIT_FAILURE;
	}

      if (!isDestination)
	{
	  //const char*  optional = param->GetMandatory() ? "False" : "True";
	  std::string optional;
	  if (param->GetMandatory())
	    if (param->HasValue())
	      {
		optional = "True";
	      }
	    else{
	      optional = "False";
	    }
	  else {
	    optional = "True";
	  }

	  dFile << "|" << default_value << "|" << optional;
	}
      dFile << std::endl;
   }

  dFile.close();

  std::ofstream indexFile;
  indexFile.open ("algs.txt", std::ios::out | std::ios::app );
  indexFile << group << "|" << module << std::endl;
  indexFile.close();
  return EXIT_SUCCESS;
}

<commit_msg>ENH: add optional arg for output dir<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperChoiceParameter.h"
#include "otbWrapperListViewParameter.h"
#include "otbWrapperBoolParameter.h"
#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperTypes.h"
#include "otbWrapperApplication.h"

#include <vector>
#include <string>
#include <iostream>
#include <cassert>
#include <fstream>

int main(int argc, char* argv[])
{
  if (argc < 3)
    {
      std::cerr << "Usage : " << argv[0] << " name OTB_APPLICATION_PATH [out_dir]" << std::endl;
      return EXIT_FAILURE;
    }

  using namespace otb::Wrapper;

  const std::string module(argv[1]);

  /* TestApplication is removed in CMakeLists.txt */
#if 0
  if (module == "TestApplication")
    return EXIT_SUCCESS;
#endif

  ApplicationRegistry::AddApplicationPath(argv[2]);
  Application::Pointer appli =  ApplicationRegistry::CreateApplicationFaster(module.c_str());

  assert(!appli.IsNull());

  appli->Init();

  std::map<ParameterType, std::string> parameterTypeToString;

  parameterTypeToString[ParameterType_Empty] = "QgsProcessingParameterBoolean";
  parameterTypeToString[ParameterType_Bool] = "QgsProcessingParameterBoolean";
  parameterTypeToString[ParameterType_Int] = "QgsProcessingParameterNumber";
  parameterTypeToString[ParameterType_Float] = "QgsProcessingParameterNumber";
  parameterTypeToString[ParameterType_RAM] = "QgsProcessingParameterNumber";
  parameterTypeToString[ParameterType_Radius] = "QgsProcessingParameterNumber";
  parameterTypeToString[ParameterType_Choice] = "OTBParameterChoice";
  parameterTypeToString[ParameterType_String] = "QgsProcessingParameterString";
  parameterTypeToString[ParameterType_InputImage] = "QgsProcessingParameterRasterLayer";
  parameterTypeToString[ParameterType_InputFilename] = "QgsProcessingParameterFile";
  parameterTypeToString[ParameterType_InputImageList] = "QgsProcessingParameterMultipleLayers";
  parameterTypeToString[ParameterType_InputVectorData] = "QgsProcessingParameterVectorLayer";
  parameterTypeToString[ParameterType_InputFilenameList] = "QgsProcessingParameterMultipleLayers";
  parameterTypeToString[ParameterType_InputVectorDataList] = "QgsProcessingParameterMultipleLayers";
  parameterTypeToString[ParameterType_OutputImage] = "QgsProcessingParameterRasterDestination";
  parameterTypeToString[ParameterType_OutputVectorData] = "QgsProcessingParameterVectorDestination";
  parameterTypeToString[ParameterType_OutputFilename] = "QgsProcessingParameterFileDestination";
  parameterTypeToString[ParameterType_Directory] = "QgsProcessingParameterFile";
  //TODO
  parameterTypeToString[ParameterType_StringList] = "QgsProcessingParameterString";

  const std::vector<std::string> appKeyList = appli->GetParametersKeys(true);
  const unsigned int nbOfParam = appKeyList.size();

  std::string output_file = module + ".txt";
  std::string  algs_txt = "algs.txt";
  if (argc > 3) {
   #if defined(WIN32)
   std::string output_dir = std::string(argv[3]) + "\\";
   #else
   std::string output_dir = std::string(argv[3]) + "/";
   #endif
    output_file = output_dir + module + ".txt";
    algs_txt = output_dir +  "algs.txt";
    }

  #if 0
  std::cout << "output_file: " << output_file << std::endl;
  std::cout << "algs_txt: " << algs_txt << std::endl;
  #endif
  std::ofstream dFile;
  dFile.open (output_file, std::ios::out);
  std::cerr << "Writing " << output_file << std::endl;

  std::string output_parameter_name;
  bool hasRasterOutput = false;
  for (unsigned int i = 0; i < nbOfParam; i++)
    {
      Parameter::Pointer param = appli->GetParameterByKey(appKeyList[i]);
      if (param->GetMandatory())
	{
	  ParameterType type = appli->GetParameterType(appKeyList[i]);
	  if (type == ParameterType_OutputImage )
	    {
	      output_parameter_name = appKeyList[i];
	      hasRasterOutput = true;
	    }
	}
    }

  if(output_parameter_name.empty())
    dFile << module << std::endl;
  else
    dFile << module << "|" <<  output_parameter_name << std::endl;

  dFile << appli->GetDescription() << std::endl;
  const std::string group = appli->GetDocTags().size() > 0 ? appli->GetDocTags()[0] : "UNCLASSIFIED";
  dFile << group << std::endl;

  for (unsigned int i = 0; i < nbOfParam; i++)
    {
      const std::string name = appKeyList[i];

      Parameter::Pointer param = appli->GetParameterByKey(name);
      ParameterType type = appli->GetParameterType(name);
      const std::string description = param->GetName();
      const std::string qgis_type = parameterTypeToString[type];

      //ListView parameters types are added as N number of QgsParameterBoolean where N being
      //number of items in a listview.
      //Example case: RadiometricIndices application
      //For next update of plugin code ListView can use custom widget wrapper and behave
      //exactly like OTB.
      if(type == ParameterType_ListView)
	{
	  ListViewParameter *lparam = dynamic_cast<ListViewParameter*>(param.GetPointer());
	  for( unsigned int c = 0; c < lparam->GetNbChoices(); ++c )
	    dFile << "QgsProcessingParameterBoolean|"
		  << lparam->GetChoiceKey(c)  << "|"
		  << lparam->GetChoiceName(c)
		  << "|False|True" << std::endl;
	}

      if (  type == ParameterType_Group  ||
	    type == ParameterType_OutputProcessXML  ||
	    type == ParameterType_InputProcessXML  ||
	    type == ParameterType_ListView ||
	    type == ParameterType_RAM
	    )
	{
	  // group parameter cannot have any value.
	  //outxml and inxml parameters are not relevant for QGIS and is considered a bit noisy
	  //ram is added by qgis-otb processing provider plugin as an advanced parameter for all apps
	  //listview is a special case. We indeed add them to descriptor file but with different logic.
	  continue;
	}

      assert(!qgis_type.empty());
      if(qgis_type.empty())
	{
	  std::cerr << "No mapping found for parameter '" <<name <<"' type=" << type << std::endl;
	  return EXIT_FAILURE;
	}

      bool isDestination = false;

      dFile << qgis_type << "|" << name << "|" << description;

      std::string default_value = "None";
      if (type == ParameterType_Int)
	{
	  dFile << "|QgsProcessingParameterNumber.Integer";
	  default_value = param->HasValue() ? appli->GetParameterAsString(name): "0";
	}
      else if (type == ParameterType_Float)
	{
	  dFile << "|QgsProcessingParameterNumber.Double";
	  default_value = param->HasValue() ? appli->GetParameterAsString(name): "0";
	}
      else if (type == ParameterType_Radius)
	{
	  dFile << "|QgsProcessingParameterNumber.Integer";
	  default_value = param->HasValue() ? appli->GetParameterAsString(name): "0";
	}
      else if(type == ParameterType_InputFilename)
	{
	  dFile << "|QgsProcessingParameterFile.File|txt";
	}
      else if(type == ParameterType_Directory)
	{
	  dFile << "|QgsProcessingParameterFile.Folder|False";
	}
      else if (type == ParameterType_InputImageList)
	{
	   dFile << "|3";
	}
      else if (type == ParameterType_InputVectorDataList)
	{
	  dFile << "|-1";
	}
      else if (type == ParameterType_InputVectorData)
	{
	  dFile << "|-1";
	}
      else if(type == ParameterType_InputFilenameList)
	{
	  dFile << "|4";
	}
      else if (type == ParameterType_InputImage)
	{
	  //default is None and nothing to add to dFile
	}
      else if(type ==ParameterType_String)
	{
	  //default is None and nothing to add to dFile
	}
      else if(type ==ParameterType_StringList)
	{
	  //default is None and nothing to add to dFile
	}
      else if(type == ParameterType_Bool)
	{
	  //BoolParameter *bparam = dynamic_cast<BoolParameter*>(param.GetPointer());
	  //default_value = bparam->GetValueAsString();
	  default_value =  appli->GetParameterAsString(name);
	}
      else if(type == ParameterType_Choice)
	{
	  std::vector<std::string>  key_list  = appli->GetChoiceKeys(name);
	  std::string values = "";
	  for( auto k : key_list)
	    values += k + ";";

	  values.pop_back();
	  dFile << "|" << values ;
	  ChoiceParameter *cparam = dynamic_cast<ChoiceParameter*>(param.GetPointer());
	  default_value = std::to_string(cparam->GetValue());
	}
      else if(type == ParameterType_OutputVectorData ||
	      type == ParameterType_OutputImage ||
	      type == ParameterType_OutputFilename)
	{
	  //no need for default_value, optional and extra fields in dFile
	  //if parameter is a destination type. qgis_type|name|description is enough.
	  //so we simply set isDestination to true and skip to end to append a new line.
	  isDestination =  true;
	}
      else
	{
     	  std::cout << "ERROR: default_value is empty for '" << name << "' type='" << qgis_type << "'" << std::endl;
	  return EXIT_FAILURE;
	}

      if (!isDestination)
	{
	  //const char*  optional = param->GetMandatory() ? "False" : "True";
	  std::string optional;
	  if (param->GetMandatory())
	    if (param->HasValue())
	      {
		optional = "True";
	      }
	    else{
	      optional = "False";
	    }
	  else {
	    optional = "True";
	  }

	  dFile << "|" << default_value << "|" << optional;
	}
      dFile << std::endl;
   }

  dFile.close();

  std::ofstream indexFile;
  indexFile.open (algs_txt, std::ios::out | std::ios::app );
  indexFile << group << "|" << module << std::endl;
  indexFile.close();
  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#include "BrowserObjectAPI.h"
#include "variant_list.h"
#include "DOM/JSAPI_DOMDocument.h"

#include "Mozilla/MozillaUI.h"
#ifdef _WIN32
#include "Win/WindowsUI.h"
#endif

#include "esteidAPI.h"
#include "JSUtil.h"

#define REGISTER_METHOD(a)      JS_REGISTER_METHOD(esteidAPI, a)
#define REGISTER_RO_PROPERTY(a) JS_REGISTER_RO_PROPERTY(esteidAPI, a)

#define ESTEID_DEBUG printf

// FIXME: Set error codes
#define ESTEID_ERROR_FROMCARD(e) { \
    ESTEID_DEBUG("Card error: %s\n", e.what()); \
    throw FB::script_error(e.what()); }
#define ESTEID_ERROR_CARD_ERROR(m) { \
    ESTEID_DEBUG("Card error: %s\n", m); \
    throw FB::script_error(m); }
#define ESTEID_ERROR_INVALID_ARG { \
    throw FB::script_error("Invalid argument"); }
#define ESTEID_ERROR_USER_ABORT { \
    throw FB::script_error("User cancelled operation"); }

esteidAPI::esteidAPI(FB::BrowserHostWrapper *host) :
    m_host(host), m_authCert(NULL), m_signCert(NULL),
    m_service(EstEIDService::getInstance())
{
    ESTEID_DEBUG("esteidAPI::esteidAPI()\n");

    REGISTER_METHOD(getVersion);
    REGISTER_METHOD(sign);

/*  FIXME: Investigate if this is needed at all?
    registerEvent("OnCardInserted");
    registerEvent("OnCardRemoved");
    registerEvent("OnReadersChanged");
*/

/*  FIXME: Those will be catched by firebreath itself for
           NPAPI plugins, but how about ActiveX?
    REGISTER_METHOD(addEventListener);
    REGISTER_METHOD(removeEventListener);
*/

    REGISTER_RO_PROPERTY(authCert);
    REGISTER_RO_PROPERTY(signCert);
    REGISTER_RO_PROPERTY(lastName);
    REGISTER_RO_PROPERTY(firstName);
    REGISTER_RO_PROPERTY(middleName);
    REGISTER_RO_PROPERTY(sex);
    REGISTER_RO_PROPERTY(citizenship);
    REGISTER_RO_PROPERTY(birthDate);
    REGISTER_RO_PROPERTY(personalID);
    REGISTER_RO_PROPERTY(documentID);
    REGISTER_RO_PROPERTY(expiryDate);
    REGISTER_RO_PROPERTY(placeOfBirth);
    REGISTER_RO_PROPERTY(issuedDate);
    REGISTER_RO_PROPERTY(residencePermit);
    REGISTER_RO_PROPERTY(comment1);
    REGISTER_RO_PROPERTY(comment2);
    REGISTER_RO_PROPERTY(comment3);
    REGISTER_RO_PROPERTY(comment4);

    /* Try to access Mozilla UI */
    m_UI = GetMozillaUI();

    /* Use platform specific UI if browser specific is not found */
    if(!m_UI) {
#ifdef _WIN32
        ESTEID_DEBUG("GetMozillaUI failed; trying to load WindowsUI\n");
        m_UI = new WindowsUI();
#endif
#ifdef SUCKOSX
        m_UI = new MacUI();
#endif
#ifdef UNIX_MUFF
       m_UI = new GtkUI();
#endif
    }

#if 0
    /* Die if UI initialization fails */
    if(!m_UI)
        throw FB::script_error("Unable to load plugin user interface");
#endif

    m_service->AddObserver(this);
}

esteidAPI::~esteidAPI()
{
    ESTEID_DEBUG("esteidAPI::~esteidAPI()\n");

    m_service->RemoveObserver(this);
}

PluginUI* esteidAPI::GetMozillaUI()
{
    if(!m_host) return NULL;

    /* Check if we are running under NPAPI */
    FB::Npapi::NpapiBrowserHost *nphost = \
      dynamic_cast<FB::Npapi::NpapiBrowserHost*> (m_host.ptr());

    if(!nphost) return NULL;

    ESTEID_DEBUG("findUI: detected NPAPI\n");

    /* Check for Mozilla */
    nsISupports *sm = NULL, *dw = NULL;
    nphost->GetValue(NPNVserviceManager, &sm);
    nphost->GetValue(NPNVDOMWindow, &dw);
    if(sm && dw) {
        try {
            return new MozillaUI(sm, dw);
        }
        catch(std::runtime_error &e) {
            ESTEID_DEBUG("%s\n", e.what());
            return NULL;
        }
    }

    return NULL;
}

void esteidAPI::onMessage(EstEIDService::msgType e, readerID i) {
    //const char *evtname;
    std::string evtname;

    switch(e) {
        case EstEIDService::CARD_INSERTED:   evtname = "OnCardInserted";  break;
        case EstEIDService::CARD_REMOVED:    evtname = "OnCardRemoved";   break;
        case EstEIDService::READERS_CHANGED: evtname = "OnReadersChanged";break;
        default: throw std::runtime_error("Invalid message type"); break;
    }
    ESTEID_DEBUG("onMessage: %s %d\n", evtname.c_str(), i);

    /* FIXME: Prefixing every event name with an additional "on" is a bloody
              hack. We either need to fix firebreath or our JS API spec. */
    FireEvent("on" + evtname, FB::variant_list_of(i));
}

void esteidAPI::UpdatePersonalData()
{
    RTERROR_TO_SCRIPT(m_service->readPersonalData(m_pdata));
}

// TODO: Optimize memory usage. Don't create new object if cert hasn't changed.
FB::JSOutObject esteidAPI::get_authCert()
{
    RTERROR_TO_SCRIPT(
        return new CertificateAPI(m_host, m_service->getAuthCert()));
}

FB::JSOutObject esteidAPI::get_signCert()
{
    RTERROR_TO_SCRIPT(
        return new CertificateAPI(m_host, m_service->getSignCert()));
}

std::string esteidAPI::getVersion()
{
    return "0.x.y";
}

std::string esteidAPI::sign(std::string hash, std::string url) {
    int tries;
    bool retrying = false, pinpad;

    // FIXME: This shouldn't happen. Remove this line after constructor is fixed
    if(!m_UI) throw FB::script_error("No UI, can't prompt for PIN");

    /* Extract subject line from Certificate */
    std::string subject = \
        static_cast<CertificateAPI*>(get_signCert().ptr())->get_CN();

    try {
        pinpad = m_service->hasSecurePinEntry();
    } catch(std::runtime_error &e) {
        ESTEID_ERROR_FROMCARD(e);
    }

    // FIXME: Implement!
    std::string pageUrl = "";

    // FIXME: Hardcoded SHA1 support
    if(hash.length() != 40)
        ESTEID_ERROR_INVALID_ARG("Invalid hash");

    if(!url.length())
        ESTEID_ERROR_INVALID_ARG("Partial document URL must be specified");

    while(true) {
        std::string pin;

        tries = getPin2RetryCount();

        if(tries <= 0) {
            // This card is locked!
            m_UI->ShowPinBlockedMessage(2);
            ESTEID_ERROR_CARD_ERROR("PIN2 locked");
        }

        if(pinpad) {
            // FIXME: Implement
            throw FB::script_error("Unable to use PinPAD (yet)");
        } else {
            pin = m_UI->PromptForSignPIN(subject, url, hash, pageUrl,
                                         pinpad, retrying, tries);
            if(!pin.length()) {
                ESTEID_DEBUG("sign: got empty PIN from UI\n");
                ESTEID_ERROR_USER_ABORT;
            }

            try {
                return m_service->signSHA1(hash, EstEidCard::SIGN, pin);
            } catch(AuthError &e) {
                if(e.m_aborted) {
                    ESTEID_DEBUG("sign: cancel pressed on PinPAD\n");
                    ESTEID_ERROR_USER_ABORT;
                }
            } catch(std::runtime_error &e) {
                ESTEID_ERROR_FROMCARD(e);
            }
        }
        retrying = true;
    }
}

int esteidAPI::getPin2RetryCount() {
    try {
        byte puk, pin1, pin2;
        m_service->getRetryCounts(puk, pin1, pin2);
        return pin2;
    } catch(std::runtime_error &e) {
        ESTEID_ERROR_FROMCARD(e);
    }
}

#define ESTEID_WHITELIST_REQUIRED

#define ESTEID_PD_GETTER_IMP(index, attr) \
    std::string esteidAPI::get_##attr() { \
            ESTEID_WHITELIST_REQUIRED; \
        UpdatePersonalData(); \
        if(m_pdata.size() <= index) \
            throw FB::script_error("PD index out of range"); \
        return m_pdata[index]; \
    }

ESTEID_PD_GETTER_IMP(EstEidCard::SURNAME,         lastName)
ESTEID_PD_GETTER_IMP(EstEidCard::FIRSTNAME,       firstName);
ESTEID_PD_GETTER_IMP(EstEidCard::MIDDLENAME,      middleName);
ESTEID_PD_GETTER_IMP(EstEidCard::SEX,             sex);
ESTEID_PD_GETTER_IMP(EstEidCard::CITIZEN,         citizenship);
ESTEID_PD_GETTER_IMP(EstEidCard::BIRTHDATE,       birthDate);
ESTEID_PD_GETTER_IMP(EstEidCard::ID,              personalID);
ESTEID_PD_GETTER_IMP(EstEidCard::DOCUMENTID,      documentID);
ESTEID_PD_GETTER_IMP(EstEidCard::EXPIRY,          expiryDate);
ESTEID_PD_GETTER_IMP(EstEidCard::BIRTHPLACE,      placeOfBirth);
ESTEID_PD_GETTER_IMP(EstEidCard::ISSUEDATE,       issuedDate);
ESTEID_PD_GETTER_IMP(EstEidCard::RESIDENCEPERMIT, residencePermit);
ESTEID_PD_GETTER_IMP(EstEidCard::COMMENT1,        comment1);
ESTEID_PD_GETTER_IMP(EstEidCard::COMMENT2,        comment2);
ESTEID_PD_GETTER_IMP(EstEidCard::COMMENT3,        comment3);
ESTEID_PD_GETTER_IMP(EstEidCard::COMMENT4,        comment4);
<commit_msg>plugins/browser: Fixed getVersion() to show actual version number<commit_after>#include "BrowserObjectAPI.h"
#include "variant_list.h"
#include "DOM/JSAPI_DOMDocument.h"
#include "config.h"

#include "Mozilla/MozillaUI.h"
#ifdef _WIN32
#include "Win/WindowsUI.h"
#endif

#include "esteidAPI.h"
#include "JSUtil.h"

#define REGISTER_METHOD(a)      JS_REGISTER_METHOD(esteidAPI, a)
#define REGISTER_RO_PROPERTY(a) JS_REGISTER_RO_PROPERTY(esteidAPI, a)

#define ESTEID_DEBUG printf

// FIXME: Set error codes
#define ESTEID_ERROR_FROMCARD(e) { \
    ESTEID_DEBUG("Card error: %s\n", e.what()); \
    throw FB::script_error(e.what()); }
#define ESTEID_ERROR_CARD_ERROR(m) { \
    ESTEID_DEBUG("Card error: %s\n", m); \
    throw FB::script_error(m); }
#define ESTEID_ERROR_INVALID_ARG { \
    throw FB::script_error("Invalid argument"); }
#define ESTEID_ERROR_USER_ABORT { \
    throw FB::script_error("User cancelled operation"); }

esteidAPI::esteidAPI(FB::BrowserHostWrapper *host) :
    m_host(host), m_authCert(NULL), m_signCert(NULL),
    m_service(EstEIDService::getInstance())
{
    ESTEID_DEBUG("esteidAPI::esteidAPI()\n");

    REGISTER_METHOD(getVersion);
    REGISTER_METHOD(sign);

/*  FIXME: Investigate if this is needed at all?
    registerEvent("OnCardInserted");
    registerEvent("OnCardRemoved");
    registerEvent("OnReadersChanged");
*/

/*  FIXME: Those will be catched by firebreath itself for
           NPAPI plugins, but how about ActiveX?
    REGISTER_METHOD(addEventListener);
    REGISTER_METHOD(removeEventListener);
*/

    REGISTER_RO_PROPERTY(authCert);
    REGISTER_RO_PROPERTY(signCert);
    REGISTER_RO_PROPERTY(lastName);
    REGISTER_RO_PROPERTY(firstName);
    REGISTER_RO_PROPERTY(middleName);
    REGISTER_RO_PROPERTY(sex);
    REGISTER_RO_PROPERTY(citizenship);
    REGISTER_RO_PROPERTY(birthDate);
    REGISTER_RO_PROPERTY(personalID);
    REGISTER_RO_PROPERTY(documentID);
    REGISTER_RO_PROPERTY(expiryDate);
    REGISTER_RO_PROPERTY(placeOfBirth);
    REGISTER_RO_PROPERTY(issuedDate);
    REGISTER_RO_PROPERTY(residencePermit);
    REGISTER_RO_PROPERTY(comment1);
    REGISTER_RO_PROPERTY(comment2);
    REGISTER_RO_PROPERTY(comment3);
    REGISTER_RO_PROPERTY(comment4);

    /* Try to access Mozilla UI */
    m_UI = GetMozillaUI();

    /* Use platform specific UI if browser specific is not found */
    if(!m_UI) {
#ifdef _WIN32
        ESTEID_DEBUG("GetMozillaUI failed; trying to load WindowsUI\n");
        m_UI = new WindowsUI();
#endif
#ifdef SUCKOSX
        m_UI = new MacUI();
#endif
#ifdef UNIX_MUFF
       m_UI = new GtkUI();
#endif
    }

#if 0
    /* Die if UI initialization fails */
    if(!m_UI)
        throw FB::script_error("Unable to load plugin user interface");
#endif

    m_service->AddObserver(this);
}

esteidAPI::~esteidAPI()
{
    ESTEID_DEBUG("esteidAPI::~esteidAPI()\n");

    m_service->RemoveObserver(this);
}

PluginUI* esteidAPI::GetMozillaUI()
{
    if(!m_host) return NULL;

    /* Check if we are running under NPAPI */
    FB::Npapi::NpapiBrowserHost *nphost = \
      dynamic_cast<FB::Npapi::NpapiBrowserHost*> (m_host.ptr());

    if(!nphost) return NULL;

    ESTEID_DEBUG("findUI: detected NPAPI\n");

    /* Check for Mozilla */
    nsISupports *sm = NULL, *dw = NULL;
    nphost->GetValue(NPNVserviceManager, &sm);
    nphost->GetValue(NPNVDOMWindow, &dw);
    if(sm && dw) {
        try {
            return new MozillaUI(sm, dw);
        }
        catch(std::runtime_error &e) {
            ESTEID_DEBUG("%s\n", e.what());
            return NULL;
        }
    }

    return NULL;
}

void esteidAPI::onMessage(EstEIDService::msgType e, readerID i) {
    //const char *evtname;
    std::string evtname;

    switch(e) {
        case EstEIDService::CARD_INSERTED:   evtname = "OnCardInserted";  break;
        case EstEIDService::CARD_REMOVED:    evtname = "OnCardRemoved";   break;
        case EstEIDService::READERS_CHANGED: evtname = "OnReadersChanged";break;
        default: throw std::runtime_error("Invalid message type"); break;
    }
    ESTEID_DEBUG("onMessage: %s %d\n", evtname.c_str(), i);

    /* FIXME: Prefixing every event name with an additional "on" is a bloody
              hack. We either need to fix firebreath or our JS API spec. */
    FireEvent("on" + evtname, FB::variant_list_of(i));
}

void esteidAPI::UpdatePersonalData()
{
    RTERROR_TO_SCRIPT(m_service->readPersonalData(m_pdata));
}

// TODO: Optimize memory usage. Don't create new object if cert hasn't changed.
FB::JSOutObject esteidAPI::get_authCert()
{
    RTERROR_TO_SCRIPT(
        return new CertificateAPI(m_host, m_service->getAuthCert()));
}

FB::JSOutObject esteidAPI::get_signCert()
{
    RTERROR_TO_SCRIPT(
        return new CertificateAPI(m_host, m_service->getSignCert()));
}

std::string esteidAPI::getVersion()
{
    return FBSTRING_PLUGIN_VERSION;
}

std::string esteidAPI::sign(std::string hash, std::string url) {
    int tries;
    bool retrying = false, pinpad;

    // FIXME: This shouldn't happen. Remove this line after constructor is fixed
    if(!m_UI) throw FB::script_error("No UI, can't prompt for PIN");

    /* Extract subject line from Certificate */
    std::string subject = \
        static_cast<CertificateAPI*>(get_signCert().ptr())->get_CN();

    try {
        pinpad = m_service->hasSecurePinEntry();
    } catch(std::runtime_error &e) {
        ESTEID_ERROR_FROMCARD(e);
    }

    // FIXME: Implement!
    std::string pageUrl = "";

    // FIXME: Hardcoded SHA1 support
    if(hash.length() != 40)
        ESTEID_ERROR_INVALID_ARG("Invalid hash");

    if(!url.length())
        ESTEID_ERROR_INVALID_ARG("Partial document URL must be specified");

    while(true) {
        std::string pin;

        tries = getPin2RetryCount();

        if(tries <= 0) {
            // This card is locked!
            m_UI->ShowPinBlockedMessage(2);
            ESTEID_ERROR_CARD_ERROR("PIN2 locked");
        }

        if(pinpad) {
            // FIXME: Implement
            throw FB::script_error("Unable to use PinPAD (yet)");
        } else {
            pin = m_UI->PromptForSignPIN(subject, url, hash, pageUrl,
                                         pinpad, retrying, tries);
            if(!pin.length()) {
                ESTEID_DEBUG("sign: got empty PIN from UI\n");
                ESTEID_ERROR_USER_ABORT;
            }

            try {
                return m_service->signSHA1(hash, EstEidCard::SIGN, pin);
            } catch(AuthError &e) {
                if(e.m_aborted) {
                    ESTEID_DEBUG("sign: cancel pressed on PinPAD\n");
                    ESTEID_ERROR_USER_ABORT;
                }
            } catch(std::runtime_error &e) {
                ESTEID_ERROR_FROMCARD(e);
            }
        }
        retrying = true;
    }
}

int esteidAPI::getPin2RetryCount() {
    try {
        byte puk, pin1, pin2;
        m_service->getRetryCounts(puk, pin1, pin2);
        return pin2;
    } catch(std::runtime_error &e) {
        ESTEID_ERROR_FROMCARD(e);
    }
}

#define ESTEID_WHITELIST_REQUIRED

#define ESTEID_PD_GETTER_IMP(index, attr) \
    std::string esteidAPI::get_##attr() { \
            ESTEID_WHITELIST_REQUIRED; \
        UpdatePersonalData(); \
        if(m_pdata.size() <= index) \
            throw FB::script_error("PD index out of range"); \
        return m_pdata[index]; \
    }

ESTEID_PD_GETTER_IMP(EstEidCard::SURNAME,         lastName)
ESTEID_PD_GETTER_IMP(EstEidCard::FIRSTNAME,       firstName);
ESTEID_PD_GETTER_IMP(EstEidCard::MIDDLENAME,      middleName);
ESTEID_PD_GETTER_IMP(EstEidCard::SEX,             sex);
ESTEID_PD_GETTER_IMP(EstEidCard::CITIZEN,         citizenship);
ESTEID_PD_GETTER_IMP(EstEidCard::BIRTHDATE,       birthDate);
ESTEID_PD_GETTER_IMP(EstEidCard::ID,              personalID);
ESTEID_PD_GETTER_IMP(EstEidCard::DOCUMENTID,      documentID);
ESTEID_PD_GETTER_IMP(EstEidCard::EXPIRY,          expiryDate);
ESTEID_PD_GETTER_IMP(EstEidCard::BIRTHPLACE,      placeOfBirth);
ESTEID_PD_GETTER_IMP(EstEidCard::ISSUEDATE,       issuedDate);
ESTEID_PD_GETTER_IMP(EstEidCard::RESIDENCEPERMIT, residencePermit);
ESTEID_PD_GETTER_IMP(EstEidCard::COMMENT1,        comment1);
ESTEID_PD_GETTER_IMP(EstEidCard::COMMENT2,        comment2);
ESTEID_PD_GETTER_IMP(EstEidCard::COMMENT3,        comment3);
ESTEID_PD_GETTER_IMP(EstEidCard::COMMENT4,        comment4);
<|endoftext|>


<commit_before>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file gaussian_filter_kf_test.cpp
 * \date Febuary 2015
 * \author Jan Issac (jan.issac@gmail.com)
 */

#include <gtest/gtest.h>
#include "../typecast.hpp"

#include <Eigen/Dense>

#include "gaussian_filter_test_suite.hpp"
#include <fl/util/meta.hpp>
#include <fl/filter/gaussian/gaussian_filter.hpp>

using namespace fl;

template <int StateDimension, int InputDimension, int ObsrvDimension>
struct UnscentedKalmanFilterTestConfiguration
{
    enum: signed int
    {
        StateDim = StateDimension,
        InputDim = InputDimension,
        ObsrvDim = ObsrvDimension
    };

    template <typename StateTransitionModel, typename ObservationModel>
    struct FilterDefinition
    {
        //typedef SigmaPointQuadrature<UnscentedTransform> Quadrature;
        typedef UnscentedQuadrature Quadrature;

        typedef GaussianFilter<
                        StateTransitionModel,
                        ObservationModel,
                        Quadrature
                > Type;
    };

    template <typename F, typename H>
    static typename FilterDefinition<F, H>::Type create_filter(F&& f, H&& h)
    {
        return typename FilterDefinition<F, H>::Type(
            f, h, UnscentedQuadrature());
    }
};

typedef ::testing::Types<
            StaticTest<UnscentedKalmanFilterTestConfiguration<3, 1, 2>>/*,
            StaticTest<UnscentedKalmanFilterTestConfiguration<3, 3, 10>>,
            StaticTest<UnscentedKalmanFilterTestConfiguration<10, 10, 20>>,

            DynamicTest<UnscentedKalmanFilterTestConfiguration<3, 1, 2>>,
            DynamicTest<UnscentedKalmanFilterTestConfiguration<3, 3, 10>>,
            DynamicTest<UnscentedKalmanFilterTestConfiguration<10, 10, 20>>*/
        > TestTypes;

INSTANTIATE_TYPED_TEST_CASE_P(UnscentedKalmanFilterTest,
                              GaussianFilterTest,
                              TestTypes);
<commit_msg>Re-added all tests<commit_after>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file gaussian_filter_kf_test.cpp
 * \date Febuary 2015
 * \author Jan Issac (jan.issac@gmail.com)
 */

#include <gtest/gtest.h>
#include "../typecast.hpp"

#include <Eigen/Dense>

#include "gaussian_filter_test_suite.hpp"
#include <fl/util/meta.hpp>
#include <fl/filter/gaussian/gaussian_filter.hpp>

using namespace fl;

template <int StateDimension, int InputDimension, int ObsrvDimension>
struct UnscentedKalmanFilterTestConfiguration
{
    enum: signed int
    {
        StateDim = StateDimension,
        InputDim = InputDimension,
        ObsrvDim = ObsrvDimension
    };

    template <typename StateTransitionModel, typename ObservationModel>
    struct FilterDefinition
    {
        //typedef SigmaPointQuadrature<UnscentedTransform> Quadrature;
        typedef UnscentedQuadrature Quadrature;

        typedef GaussianFilter<
                        StateTransitionModel,
                        ObservationModel,
                        Quadrature
                > Type;
    };

    template <typename F, typename H>
    static typename FilterDefinition<F, H>::Type create_filter(F&& f, H&& h)
    {
        return typename FilterDefinition<F, H>::Type(
            f, h, UnscentedQuadrature());
    }
};

typedef ::testing::Types<
            StaticTest<UnscentedKalmanFilterTestConfiguration<3, 1, 2>>,
            StaticTest<UnscentedKalmanFilterTestConfiguration<3, 3, 10>>,
            StaticTest<UnscentedKalmanFilterTestConfiguration<10, 10, 20>>,

            DynamicTest<UnscentedKalmanFilterTestConfiguration<3, 1, 2>>,
            DynamicTest<UnscentedKalmanFilterTestConfiguration<3, 3, 10>>,
            DynamicTest<UnscentedKalmanFilterTestConfiguration<10, 10, 20>>
        > TestTypes;

INSTANTIATE_TYPED_TEST_CASE_P(UnscentedKalmanFilterTest,
                              GaussianFilterTest,
                              TestTypes);
<|endoftext|>