<commit_before>#ifndef RECURSE_HPP
#define RECURSE_HPP

#include <QCoreApplication>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QHash>
#include <QStringBuilder>
#include <QVector>
#include "request.hpp"
#include "response.hpp"

#include <functional>
using std::function;
using std::bind;
using std::ref;

typedef function<void(Request &request, Response &response, function<void()> next)> next_f;

//!
//! \brief The Recurse class
//! main class of the app
//!
class Recurse : public QObject
{
public:

    Recurse(int & argc, char ** argv, QObject *parent = NULL);
    ~Recurse();

    bool listen(quint64 port, QHostAddress address = QHostAddress::Any);
    void use(next_f next);

private:
    QCoreApplication app;
    QTcpServer m_tcp_server;
    quint64 m_port;
    QVector<next_f> m_middleware;
    int current_middleware = 0;
    void m_next(Request &request, Response &response);
    void http_parse(Request &request);
    QString http_build_header(const Response &response);
};

Recurse::Recurse(int & argc, char ** argv, QObject *parent) : app(argc, argv)
{
    Q_UNUSED(parent);
};

Recurse::~Recurse()
{

};

//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! \param port tcp server port
//! \param address tcp server listening address
//!
//! \return true on success
//!
bool Recurse::listen(quint64 port, QHostAddress address)
{
    m_port = port;
    int bound = m_tcp_server.listen(address, port);
    if (!bound)
        return false;

    connect(&m_tcp_server, &QTcpServer::newConnection, [this] {
        qDebug() << "client connected";
        QTcpSocket *client = m_tcp_server.nextPendingConnection();

        connect(client, &QTcpSocket::readyRead, [this, client] {
            Request request;
            Response response;

            request.data = client->readAll();
            http_parse(request);

            qDebug() << "client request: " << request.data;

            if (m_middleware.count() > 0)
                m_middleware[current_middleware](request, response, bind(&Recurse::m_next, this, ref(request), ref(response)));

            current_middleware = 0;
            QString header;

            response.method = request.method;
            response.proto = request.proto;

            if (response.status == 0)
                response.status = 200;

            header = http_build_header(response);
            QString response_data = header + response.body;

            // send response to the client
            qint64 check = client->write(response_data.toStdString().c_str(), response_data.size());

            qDebug() << "socket write debug:" << check;
            client->close();
        });
    });

    return app.exec();
};

//!
//! \brief Recurse::m_next
//! call next middleware
//!
void Recurse::m_next(Request &request, Response &response)
{
    qDebug() << "calling next:" << current_middleware << " num:" << m_middleware.size();

    if (++current_middleware >= m_middleware.size()) {
        return;
    };

    m_middleware[current_middleware](request, response, bind(&Recurse::m_next, this, ref(request), ref(response)));

};

//!
//! \brief Recurse::use
//! add new middleware
//!
//! \param f middleware function that will be called later
//!
void Recurse::use(next_f f)
{
    m_middleware.push_back(f);
};

//!
//! \brief Recurse::http_parse
//! parse http data
//!
//! \param data reference to data received from the tcp connection
//!
void Recurse::http_parse(Request &request)
{
    QStringList data_list = request.data.split("\r\n");
    bool is_body = false;

    for (int i = 0; i < data_list.size(); ++i) {
        if (is_body) {
            request.body.append(data_list.at(i));
            continue;
        }

        QStringList entity_item = data_list.at(i).split(":");

        if (entity_item.length() < 2 && entity_item.at(0).size() < 1 && !is_body) {
            is_body = true;
            continue;
        }
        else if (i == 0 && entity_item.length() < 2) {
            QStringList first_line = entity_item.at(0).split(" ");
            request.method = first_line.at(0);
            request.url = first_line.at(1).trimmed();
            request.proto = first_line.at(2).trimmed();
            continue;
        }

        request.header[entity_item.at(0).toLower()] = entity_item.at(1).trimmed();
    }

    qDebug() << "request object populated: " << request.method << request.url << request.header << request.proto << request.body;
};

//!
//! \brief Recurse::http_build_header
//! build http header for response
//!
//! \param response reference to the Response instance
//!
QString Recurse::http_build_header(const Response &response)
{
    QString header = response.proto % " " % QString::number(response.status) % " "
        % response.http_codes[response.status] % "\r\n";

    // set default header fields
    QHash<QString, QString>::const_iterator i;

    for (i = response.default_headers.constBegin(); i != response.default_headers.constEnd(); ++i) {
        if (i.key() == "content-length" && response.header[i.key()] == "")
            header += i.key() % ": " % QString::number(response.body.size()) % "\r\n";
        else if (response.header[i.key()] == "")
            header += i.key() % ": " % i.value() % "\r\n";
    }

    // set user-defined header fields
    QHash<QString, QString>::const_iterator j;

    for (j = response.header.constBegin(); j != response.header.constEnd(); ++j) {
        header += j.key() % ": " % j.value() % "\r\n";
    }

    qDebug() << "response header" << header;

    return header + "\r\n";
}

#endif // RECURSE_HPP
<commit_msg>store connections in a QHash which gets instantiated with an application<commit_after>#ifndef RECURSE_HPP
#define RECURSE_HPP

#include <QCoreApplication>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QHash>
#include <QStringBuilder>
#include <QVector>
#include "request.hpp"
#include "response.hpp"

#include <functional>
using std::function;
using std::bind;
using std::ref;

typedef function<void(Request &request, Response &response, function<void()> next)> next_f;

//!
//! \brief The Recurse class
//! main class of the app
//!
class Recurse : public QObject
{
public:

    Recurse(int & argc, char ** argv, QObject *parent = NULL);
    ~Recurse();

    bool listen(quint64 port, QHostAddress address = QHostAddress::Any);
    void use(next_f next);

private:
    QCoreApplication app;
    QTcpServer m_tcp_server;

    quint64 m_port;
    QVector<next_f> m_middleware;
    int current_middleware = 0;
    void m_next(int &socket_id);
    void http_parse(Request &request);
    QString http_build_header(const Response &response);

    struct Client {
        QTcpSocket *socket;
        Request request;
        Response response;
    };

    QHash<int, Client> connections;
};

Recurse::Recurse(int & argc, char ** argv, QObject *parent) : app(argc, argv)
{
    Q_UNUSED(parent);
};

Recurse::~Recurse()
{

};

//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! \param port tcp server port
//! \param address tcp server listening address
//!
//! \return true on success
//!
bool Recurse::listen(quint64 port, QHostAddress address)
{
    m_port = port;
    int bound = m_tcp_server.listen(address, port);
    if (!bound)
        return false;

    connect(&m_tcp_server, &QTcpServer::newConnection, [this] {
        qDebug() << "client connected";
        int socket_id = rand();

        connections[socket_id] = {
             m_tcp_server.nextPendingConnection()
        };

        connect(connections[socket_id].socket, &QTcpSocket::readyRead, [this, socket_id] {
            connections[socket_id].request.data = connections[socket_id].socket->readAll();
            http_parse(connections[socket_id].request);

            qDebug() << "client request: " << connections[socket_id].request.data;

            if (m_middleware.count() > 0)
                m_middleware[current_middleware](
                    connections[socket_id].request,
                    connections[socket_id].response,
                    bind(&Recurse::m_next, this, socket_id));

            current_middleware = 0;
            QString header;

            connections[socket_id].response.method = connections[socket_id].request.method;
            connections[socket_id].response.proto = connections[socket_id].request.proto;

            if (connections[socket_id].response.status == 0)
                connections[socket_id].response.status = 200;

            header = http_build_header(connections[socket_id].response);
            QString response_data = header + connections[socket_id].response.body;

            // send response to the client
            qint64 check = connections[socket_id].socket->write(
                response_data.toStdString().c_str(),
                response_data.size());

            qDebug() << "socket write debug:" << check;
            connections[socket_id].socket->close();
        });
    });

    return app.exec();
};

//!
//! \brief Recurse::m_next
//! call next middleware
//!
void Recurse::m_next(int &socket_id)
{
    qDebug() << "calling next:" << current_middleware << " num:" << m_middleware.size();

    if (++current_middleware >= m_middleware.size()) {
        return;
    };

    m_middleware[current_middleware](
        connections[socket_id].request,
        connections[socket_id].response,
        bind(&Recurse::m_next, this, socket_id));
};

//!
//! \brief Recurse::use
//! add new middleware
//!
//! \param f middleware function that will be called later
//!
void Recurse::use(next_f f)
{
    m_middleware.push_back(f);
};

//!
//! \brief Recurse::http_parse
//! parse http data
//!
//! \param data reference to data received from the tcp connection
//!
void Recurse::http_parse(Request &request)
{
    QStringList data_list = request.data.split("\r\n");
    bool is_body = false;

    for (int i = 0; i < data_list.size(); ++i) {
        if (is_body) {
            request.body.append(data_list.at(i));
            continue;
        }

        QStringList entity_item = data_list.at(i).split(":");

        if (entity_item.length() < 2 && entity_item.at(0).size() < 1 && !is_body) {
            is_body = true;
            continue;
        }
        else if (i == 0 && entity_item.length() < 2) {
            QStringList first_line = entity_item.at(0).split(" ");
            request.method = first_line.at(0);
            request.url = first_line.at(1).trimmed();
            request.proto = first_line.at(2).trimmed();
            continue;
        }

        request.header[entity_item.at(0).toLower()] = entity_item.at(1).trimmed();
    }

    qDebug() << "request object populated: " << request.method << request.url << request.header << request.proto << request.body;
};

//!
//! \brief Recurse::http_build_header
//! build http header for response
//!
//! \param response reference to the Response instance
//!
QString Recurse::http_build_header(const Response &response)
{
    QString header = response.proto % " " % QString::number(response.status) % " "
        % response.http_codes[response.status] % "\r\n";

    // set default header fields
    QHash<QString, QString>::const_iterator i;

    for (i = response.default_headers.constBegin(); i != response.default_headers.constEnd(); ++i) {
        if (i.key() == "content-length" && response.header[i.key()] == "")
            header += i.key() % ": " % QString::number(response.body.size()) % "\r\n";
        else if (response.header[i.key()] == "")
            header += i.key() % ": " % i.value() % "\r\n";
    }

    // set user-defined header fields
    QHash<QString, QString>::const_iterator j;

    for (j = response.header.constBegin(); j != response.header.constEnd(); ++j) {
        header += j.key() % ": " % j.value() % "\r\n";
    }

    qDebug() << "response header" << header;

    return header + "\r\n";
}

#endif // RECURSE_HPP
<|endoftext|>


<commit_before>/* Filename: intelhex.cc
 * Routines for reading/writing Intel INHX8M and INHX32 files
 * Copyright Brandon Fosdick 2001
 * This software and all of its components are available under the BSD License
 * For a copy of the BSD License see http://www.freebsd.org
 * */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "intelhex.h"

namespace intelhex
{

	hex_data::hex_data()
	{
		format = HEX_FORMAT_INHX8M;
	}

	//Extend the data block array by one element
	//	and return a pointer to the new element
	dblock* hex_data::new_block()
	{
		dblock b;
		blocks.push_back(b);
		return &blocks.back();
	}

	//Extend the data block array by one element
	//	and return a pointer to the new element
	//	Initialize the element with address and length
	dblock* hex_data::add_block(uint16_t address, uint16_t length)
	{
		dblock db;	//A list of pointers would be faster, but this isn't too bad
		blocks.push_back(db);
		blocks.back().first = address;
		blocks.back().second.resize(length);
		return &blocks.back();
	}

	//Array access operator
	//Assumes that the blocks have been sorted by address in ascending order
	uint16_t &hex_data::operator[](uint16_t addr)
	{
		//Start at the end of the list and find the first (last) block with an address
		//	less than addr
		lst_dblock::reverse_iterator i = blocks.rbegin();
		while( (i!=blocks.rend()) && (i->first > addr))
			++i;
		if(i==blocks.rend())	//If a suitable block wasn't found, return something
			return blocks.begin()->second[0];
		return i->second[addr - i->first];
	}

	//	Delete all allocated memory
	void hex_data::cleanup()
	{
		format = HEX_FORMAT_INHX8M;
		blocks.clear();
	}

	//Load a hex file from disk
	//Destroys any data that has already been loaded
	bool	hex_data::load(const char *path)
	{
		FILE	*fp;
		unsigned int	hi, lo, address, count, rtype, i, j;
		dblock	*db;		//Temporary pointer

		if( (fp=fopen(path, "r"))==NULL )
		{
			printf("%s: Can't open %s\n", __FUNCTION__, path);
			return false;
		}

		cleanup();		//First, clean house

		//Start parsing the file
		while(!feof(fp))
		{
			if(fgetc(fp)==':')	//First character of every line should be ':'
			{
				fscanf(fp, "%2x", &count);			//Read in byte count
				fscanf(fp, "%4x", &address);		//Read in address
				fscanf(fp, "%2x", &rtype);			//Read type

	/*			printf("Count: %02X\t", count);
				printf("Address: %04X\t", address);
				printf("Type: %02X\n", rtype);
				*/
				count /= 2;								//Convert byte count to word count
				address /= 2;							//Byte address to word address

				switch(rtype)	//What type of record?
				{
					case 0: 	//Data block so store it
						db = add_block(address, count);	//Make a data block
						for(i=0; i<count; i++)				//Read all of the data bytes
						{
							fscanf(fp, "%2x", &lo);			//Low byte
							fscanf(fp, "%2x", &hi);			//High byte
							db->second[i] = ((hi<<8)&0xFF00) | (lo&0x00FF);	//Assemble the word
						}
						break;
					case 1:	//EOF
						break;
					case 2:	//Segment address record (INHX32)
						break;
					case 4:	//Linear address record (INHX32)
						break;
				}
				fscanf(fp,"%*[^\n]\n");		//Ignore the checksum and the newline
			}
			else
			{
				printf("%s: Bad line\n", __FUNCTION__);
				fscanf(fp, "%*[^\n]\n");	//Ignore the rest of the line
			}
		}
		fclose(fp);

		blocks.sort();		//Sort the data blocks by address (ascending)
		return true;
	}

	//Write all data to a file
	void	hex_data::write(const char *path)
	{
		FILE	*fp;
//		int i, j;
		u_int8_t	checksum;

		if( (fp=fopen(path, "w"))==NULL )
		{
			printf("%s: Can't open %s\n", __FUNCTION__, path);
			return;
		}

		truncate(8);				//Truncate each record to length=8
		blocks.sort();				//Sort the data blocks by address (ascending)

		for(lst_dblock::iterator i=blocks.begin(); i!=blocks.end(); i++)
		{
			checksum = 0;
			if(i->first < 0x2100)
			{	//Program memory and fuses require special consideration
				fprintf(fp, ":%02X%04X00", i->second.size()*2, i->first*2);	//Record length and address
				for(int j=0; j<i->second.size(); j++)	//Store the data bytes, LSB first, ASCII HEX
				{
					fprintf(fp, "%02X%02X", i->second[j] & 0x00FF, (i->second[j]>>8) & 0x00FF);
					checksum += i->second[j];
				}
			}
			else	//EEPROM can just be written out
			{
				fprintf(fp, ":%02X%04X00", i->second.size(), i->first);	//Record length and address
				for(int j=0; j<i->second.size(); j++)	//Store the data bytes, LSB first, ASCII HEX
				{
					fprintf(fp, "%02X", i->second[j] & 0x00FF);
					checksum += i->second[j];
				}
			}
			fprintf(fp, "00\n");	//Bogus checksum and a newline
		}
		fprintf(fp, ":00000001FF\n");	//EOF marker
		fclose(fp);
	}

	//Truncate all of the blocks to a given length
	void	hex_data::truncate(uint16_t len)
	{
		for(lst_dblock::iterator i=blocks.begin(); i!=blocks.end(); i++)
			if(i->second.size() > len)
			{
				dblock db;
				blocks.push_back(db);	//Append a new block
				blocks.back().first = i->first + len;	//Give the new block an address
				blocks.back().second.assign(&i->second[len], i->second.end());	//Insert the extra bytes into the new block
				i->second.resize(len);	//Truncate the original block
			}
	}

}<commit_msg>Added write(ostream&) for outputting to a string<commit_after>/* Filename: intelhex.cc
 * Routines for reading/writing Intel INHX8M and INHX32 files
 * Copyright Brandon Fosdick 2001
 * This software and all of its components are available under the BSD License
 * For a copy of the BSD License see http://www.freebsd.org
 * */

#include <iostream>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "intelhex.h"

namespace intelhex
{

	hex_data::hex_data()
	{
		format = HEX_FORMAT_INHX8M;
	}

	//Extend the data block array by one element
	//	and return a pointer to the new element
	dblock* hex_data::new_block()
	{
		dblock b;
		blocks.push_back(b);
		return &blocks.back();
	}

	//Extend the data block array by one element
	//	and return a pointer to the new element
	//	Initialize the element with address and length
	dblock* hex_data::add_block(uint16_t address, uint16_t length)
	{
		dblock db;	//A list of pointers would be faster, but this isn't too bad
		blocks.push_back(db);
		blocks.back().first = address;
		blocks.back().second.resize(length);
		return &blocks.back();
	}

	//Array access operator
	//Assumes that the blocks have been sorted by address in ascending order
	uint16_t &hex_data::operator[](uint16_t addr)
	{
		//Start at the end of the list and find the first (last) block with an address
		//	less than addr
		lst_dblock::reverse_iterator i = blocks.rbegin();
		while( (i!=blocks.rend()) && (i->first > addr))
			++i;
		if(i==blocks.rend())	//If a suitable block wasn't found, return something
			return blocks.begin()->second[0];
		return i->second[addr - i->first];
	}

	//	Delete all allocated memory
	void hex_data::cleanup()
	{
		format = HEX_FORMAT_INHX8M;
		blocks.clear();
	}

	//Load a hex file from disk
	//Destroys any data that has already been loaded
	bool	hex_data::load(const char *path)
	{
		FILE	*fp;
		unsigned int	hi, lo, address, count, rtype, i, j;
		dblock	*db;		//Temporary pointer

		if( (fp=fopen(path, "r"))==NULL )
		{
			printf("%s: Can't open %s\n", __FUNCTION__, path);
			return false;
		}

		cleanup();		//First, clean house

		//Start parsing the file
		while(!feof(fp))
		{
			if(fgetc(fp)==':')	//First character of every line should be ':'
			{
				fscanf(fp, "%2x", &count);			//Read in byte count
				fscanf(fp, "%4x", &address);		//Read in address
				fscanf(fp, "%2x", &rtype);			//Read type

	/*			printf("Count: %02X\t", count);
				printf("Address: %04X\t", address);
				printf("Type: %02X\n", rtype);
				*/
				count /= 2;								//Convert byte count to word count
				address /= 2;							//Byte address to word address

				switch(rtype)	//What type of record?
				{
					case 0: 	//Data block so store it
						db = add_block(address, count);	//Make a data block
						for(i=0; i<count; i++)				//Read all of the data bytes
						{
							fscanf(fp, "%2x", &lo);			//Low byte
							fscanf(fp, "%2x", &hi);			//High byte
							db->second[i] = ((hi<<8)&0xFF00) | (lo&0x00FF);	//Assemble the word
						}
						break;
					case 1:	//EOF
						break;
					case 2:	//Segment address record (INHX32)
						break;
					case 4:	//Linear address record (INHX32)
						break;
				}
				fscanf(fp,"%*[^\n]\n");		//Ignore the checksum and the newline
			}
			else
			{
				printf("%s: Bad line\n", __FUNCTION__);
				fscanf(fp, "%*[^\n]\n");	//Ignore the rest of the line
			}
		}
		fclose(fp);

		blocks.sort();		//Sort the data blocks by address (ascending)
		return true;
	}

	//Write all data to a file
	void	hex_data::write(const char *path)
	{
		ofstream	ofs(path);
		write(ofs);
	}

	//Write all data to an output stream
	void	hex_data::write(ostream &os)
	{
		uint8_t	checksum;

		truncate(8);				//Truncate each record to length=8 (purely asthetic)
		blocks.sort();				//Sort the data blocks by address (ascending)

		os.setf(ios::hex, ios::basefield);	//Set the stream to ouput hex instead of decimal
		os.setf(ios::uppercase);				//Use uppercase hex notation
		os.fill('0');								//Pad with zeroes

		for(lst_dblock::iterator i=blocks.begin(); i!=blocks.end(); i++)
		{
			checksum = 0;
			if(i->first < 0x2100)
			{	//Program memory and fuses require special consideration
				os << ':';	//Every line begins with ':'
				os.width(2);
				os << i->second.size()*2;	//Record length
				os.width(4);
				os << static_cast<uint16_t>(i->first*2);	//Address
				os << "00";											//Record type
				for(int j=0; j<i->second.size(); j++)	//Store the data bytes, LSB first, ASCII HEX
				{
					os.width(2);
					os << (i->second[j] & 0x00FF);
					os.width(2);
					os << ((i->second[j]>>8) & 0x00FF);
					checksum += i->second[j];
				}
			}
			else	//EEPROM can just be written out
			{
				os.width(2);
				os << i->second.size();		//Record length
				os.width(4);
				os << i->first << "00";		//Address and record type
				for(int j=0; j<i->second.size(); j++)	//Store the data bytes, LSB first, ASCII HEX
				{
					os.width(2);
					os << (i->second[j] & 0x00FF);
					checksum += i->second[j];
				}
			}
			os.width(2);
			os << static_cast<int>(checksum);	//Bogus checksum byte
			os << endl;
		}
		os << ":00000001FF\n";			//EOF marker
	}

	//Truncate all of the blocks to a given length
	void	hex_data::truncate(uint16_t len)
	{
		for(lst_dblock::iterator i=blocks.begin(); i!=blocks.end(); i++)
			if(i->second.size() > len)
			{
				dblock db;
				blocks.push_back(db);	//Append a new block
				blocks.back().first = i->first + len;	//Give the new block an address
				blocks.back().second.assign(&i->second[len], i->second.end());	//Insert the extra bytes into the new block
				i->second.resize(len);	//Truncate the original block
			}
	}

}<|endoftext|>


<commit_before>#ifndef V_SMC_SAMPLER_HPP
#define V_SMC_SAMPLER_HPP

#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include <gsl/gsl_cblas.h>
#include <boost/function.hpp>
#include <vDist/rng/gsl.hpp>
#include <vDist/tool/buffer.hpp>
#include <vSMC/history.hpp>
#include <vSMC/monitor.hpp>
#include <vSMC/particle.hpp>

namespace vSMC {

template <typename T>
class Sampler
{
    public :

    /// The type of particle values
    typedef T value_type;
    /// The type of partiles
    typedef Particle<T> particle_type;
    /// The type of initialize callable objects
    typedef boost::function<std::size_t
        (Particle<T> &, void *)> init_type;
    /// The type of move callable objects
    typedef boost::function<std::size_t
        (std::size_t, Particle<T> &)> move_type;
    /// The type of importance sampling integral
    typedef boost::function<void
        (std::size_t, const Particle<T> &, double *, void *)> integral_type;
    /// The type of path sampling integration
    typedef boost::function<double
        (std::size_t, const Particle<T> &, double *)> path_type;

    /// \brief Sampler does not have a default constructor
    ///
    /// \param N The number of particles
    /// \param init The functor used to initialize the particles
    /// \param move The functor used to move the particles and weights
    /// \param hist_mode The history storage mode. See HistoryMode
    /// \param rs_scheme The resampling scheme. See ResampleScheme
    /// \param seed The seed for the reampling RNG. See documentation of vDist
    /// \param brng The basic RNG for resampling RNG. See documentation of GSL
    Sampler (
            std::size_t N,
            const init_type &init, const move_type &move,
            const typename Particle<T>::copy_type &copy,
            HistoryMode hist_mode = HISTORY_RAM,
            ResampleScheme rs_scheme = RESIDUAL,
            double rs_threshold = 0.5,
            const int seed = V_DIST_SEED,
            const gsl_rng_type *brng = V_DIST_GSL_BRNG) :
        initialized(false), init_particle(init), move_particle(move),
        rng(seed, brng), scheme(rs_scheme), threshold(rs_threshold* N),
        particle(N, copy), iter_num(0), mode(hist_mode), history(hist_mode),
        integrate_tmp(N), path_integral(NULL), path_estimate(0) {}

    /// \brief Get ESS
    ///
    /// \return The ESS value of the latest iteration
    double ESS () const
    {
        return ess_history.back();
    }

    /// \brief Get all ESS
    ///
    /// \return History of ESS for all iterations
    std::vector<double> ESS_history () const
    {
        return ess_history;
    }

    /// \brief Get indicator of resampling
    ///
    /// \return A bool value, \b true if the latest iteration was resampled
    bool was_resampled () const
    {
        return resample_history.back();
    }

    /// \brief Get history of resampling
    ///
    /// \return History of resampling for all iterations
    std::vector<bool> was_resampled_history () const
    {
        return resample_history;
    }

    /// \brief Get accept count
    ///
    /// \return The accept count of the latest iteration
    std::size_t accept_count () const
    {
        return accept_history.back();
    }

    /// \brief Get history of accept count
    ///
    /// \return History of accept count for all iterations
    std::vector<std::size_t> accept_count_history () const
    {
        return accept_history;
    }

    /// \brief Read only access to the particle set
    ///
    /// \return A const reference to the latest particle set.
    /// \note Any operations that change the state of the sampler (e.g., an
    /// iteration) may invalidate the reference.
    const Particle<T> &getParticle () const
    {
        return particle;
    }

    /// \brief (Re)initialize the particle set
    ///
    /// \param param Additional parameters passed to initialization functor,
    /// the default is NULL
    void initialize (void *param = NULL)
    {
        history.clear();
        ess_history.clear();
        resample_history.clear();
        accept_history.clear();

        for (typename std::map<std::string, Monitor<T> >::iterator
                imap = monitor.begin(); imap != monitor.end(); ++imap)
            imap->second.clear();

        path_sample.clear();
        path_width.clear();

        iter_num = 0;
        accept_history.push_back(init_particle(particle, param));
        post_move();

        initialized = true;
    }

    /// \brief Perform iteration
    void iterate ()
    {
        if (!initialized)
            throw std::runtime_error(
                    "ERROR: vSMC::Sampler::iterate: "
                    "Sampler has not been initialized yet");

        ++iter_num;
        accept_history.push_back(move_particle(iter_num, particle));
        post_move();
    }

    /// \brief Perform iteration
    ///
    /// \param n The number of iterations to be performed
    void iterate (std::size_t n)
    {
        for (std::size_t i = 0; i != n; ++i)
            iterate();
    }

    /// \brief Perform importance sampling integration
    ///
    /// \param intgral The functor used to compute the integrands
    /// \param param Additional parameters to be passed to integral
    double integrate (integral_type integral, void *param) const
    {
        std::size_t n = particle.size();
        integral(iter_num, particle, integrate_tmp, param);

        return cblas_ddot(n, particle.get_weight_ptr(), 1, integrate_tmp, 1);
    }

    /// \brief Add a monitor, similar to \b monitor in \b BUGS
    ///
    /// \param name The name of the monitor
    /// \param integral The functor used to compute the integrands
    void add_monitor (const std::string &name,
            const typename Monitor<T>::integral_type &integral)
    {
        monitor.insert(
                typename std::map<std::string, Monitor<T> >::value_type(
                    name, Monitor<T>(integral, particle.size())));
    }

    /// \brief Get the iteration index of a monitor
    ///
    /// \param The name of the monitor
    /// \return A vector of the monitor index
    typename Monitor<T>::index_type get_monitor_index (
            const std::string &name) const
    {
        return monitor.find(name)->second.get_index();
    }

    /// \brief Get the record of Monite Carlo integration of a monitor
    ///
    /// \param name The name of the monitor
    /// \return A vector of the monitor record
    typename Monitor<T>::record_type get_monitor_record (
            const std::string &name) const
    {
        return monitor.find(name)->second.get_record();
    }

    /// \brief Get both the iteration index and record of a monitor
    typename Monitor<T>::value_type get_monitor_value (
            const std::string &name) const
    {
        return monitor.find(name)->second.get();
    }

    /// \brief Erase a monitor by name
    ///
    /// \param name The name of the monitor
    void erase_monitor (const std::string &name)
    {
        monitor.erase(name);
    }

    /// \brief Clear all monitors
    void clear_monitor ()
    {
        monitor.clear();
    }

    /// \brief Set the path sampling integral
    ///
    /// \param integral The functor used to compute the integrands
    void set_path_sampling (path_type integral)
    {
        path_integral = integral;
    }

    /// \brief Stop path sampling
    void clear_path_sampling ()
    {
        path_integral = NULL;
    }

    /// \brief Get the results of path sampling
    double get_path_sampling () const
    {
        return 0;
    }

    private :

    /// Initialization indicator
    bool initialized;

    /// Initialization and movement
    init_type init_particle;
    move_type move_particle;

    /// Resampling
    vDist::RngGSL rng;
    ResampleScheme scheme;
    double threshold;

    /// Particle sets
    Particle<T> particle;
    std::size_t iter_num;
    std::vector<double> ess_history;
    std::vector<bool> resample_history;
    std::vector<std::size_t> accept_history;

    /// History
    HistoryMode mode;
    History<T> history;

    /// Monte Carlo estimation by integration
    mutable vDist::tool::Buffer<double> integrate_tmp;
    std::map<std::string, Monitor<T> > monitor;

    /// Path sampling
    path_type path_integral;
    std::vector<double> path_sample;
    std::vector<double> path_width;
    double path_estimate;

    void post_move ()
    {
        bool res_indicator = false;
        if (particle.ESS() < threshold) {
            res_indicator = true;
            particle.resample(scheme, rng.get_rng());
        }
        ess_history.push_back(particle.ESS());
        resample_history.push_back(res_indicator);

        if (mode != HISTORY_NONE)
            history.push_back(particle);

        for (typename std::map<std::string, Monitor<T> >::iterator
                imap = monitor.begin(); imap != monitor.end(); ++imap) {
            if (!imap->second.empty())
                imap->second.eval(iter_num, particle);
        }

        if (!path_integral.empty()) {
            double width;
            path_sample.push_back(eval_path(width));
            path_width.push_back(width);
        }
    }

    double eval_path (double &width)
    {
        width = path_integral(iter_num, particle, integrate_tmp);
        return cblas_ddot(particle.size(),
                particle.get_weight_ptr(), 1, integrate_tmp, 1);
    }
}; // class Sampler

} // namespace vSMC

#endif // V_SMC_SAMPLER_HPP
<commit_msg>add normal model<commit_after>#ifndef V_SMC_SAMPLER_HPP
#define V_SMC_SAMPLER_HPP

#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include <gsl/gsl_cblas.h>
#include <boost/function.hpp>
#include <vDist/rng/gsl.hpp>
#include <vDist/tool/buffer.hpp>
#include <vSMC/history.hpp>
#include <vSMC/monitor.hpp>
#include <vSMC/particle.hpp>

namespace vSMC {

template <typename T>
class Sampler
{
    public :

    /// The type of particle values
    typedef T value_type;
    /// The type of partiles
    typedef Particle<T> particle_type;
    /// The type of initialize callable objects
    typedef boost::function<std::size_t
        (Particle<T> &, void *)> init_type;
    /// The type of move callable objects
    typedef boost::function<std::size_t
        (std::size_t, Particle<T> &)> move_type;
    /// The type of importance sampling integral
    typedef boost::function<void
        (std::size_t, const Particle<T> &, double *, void *)> integral_type;
    /// The type of path sampling integration
    typedef boost::function<double
        (std::size_t, const Particle<T> &, double *)> path_type;

    /// \brief Sampler does not have a default constructor
    ///
    /// \param N The number of particles
    /// \param init The functor used to initialize the particles
    /// \param move The functor used to move the particles and weights
    /// \param hist_mode The history storage mode. See HistoryMode
    /// \param rs_scheme The resampling scheme. See ResampleScheme
    /// \param seed The seed for the reampling RNG. See documentation of vDist
    /// \param brng The basic RNG for resampling RNG. See documentation of GSL
    Sampler (
            std::size_t N,
            const init_type &init, const move_type &move,
            const typename Particle<T>::copy_type &copy,
            HistoryMode hist_mode = HISTORY_RAM,
            ResampleScheme rs_scheme = RESIDUAL,
            double rs_threshold = 0.5,
            const int seed = V_DIST_SEED,
            const gsl_rng_type *brng = V_DIST_GSL_BRNG) :
        initialized(false), init_particle(init), move_particle(move),
        rng(seed, brng), scheme(rs_scheme), threshold(rs_threshold* N),
        particle(N, copy), iter_num(0), mode(hist_mode), history(hist_mode),
        integrate_tmp(N), path_integral(NULL), path_estimate(0) {}

    /// \brief Get ESS
    ///
    /// \return The ESS value of the latest iteration
    double ESS () const
    {
        return ess_history.back();
    }

    /// \brief Get all ESS
    ///
    /// \return History of ESS for all iterations
    std::vector<double> ESS_history () const
    {
        return ess_history;
    }

    /// \brief Get indicator of resampling
    ///
    /// \return A bool value, \b true if the latest iteration was resampled
    bool was_resampled () const
    {
        return resample_history.back();
    }

    /// \brief Get history of resampling
    ///
    /// \return History of resampling for all iterations
    std::vector<bool> was_resampled_history () const
    {
        return resample_history;
    }

    /// \brief Get accept count
    ///
    /// \return The accept count of the latest iteration
    std::size_t accept_count () const
    {
        return accept_history.back();
    }

    /// \brief Get history of accept count
    ///
    /// \return History of accept count for all iterations
    std::vector<std::size_t> accept_count_history () const
    {
        return accept_history;
    }

    /// \brief Read only access to the particle set
    ///
    /// \return A const reference to the latest particle set.
    /// \note Any operations that change the state of the sampler (e.g., an
    /// iteration) may invalidate the reference.
    const Particle<T> &getParticle () const
    {
        return particle;
    }

    /// \brief (Re)initialize the particle set
    ///
    /// \param param Additional parameters passed to initialization functor,
    /// the default is NULL
    void initialize (void *param = NULL)
    {
        history.clear();
        ess_history.clear();
        resample_history.clear();
        accept_history.clear();

        for (typename std::map<std::string, Monitor<T> >::iterator
                imap = monitor.begin(); imap != monitor.end(); ++imap)
            imap->second.clear();

        path_sample.clear();
        path_width.clear();

        iter_num = 0;
        accept_history.push_back(init_particle(particle, param));
        post_move();

        initialized = true;
    }

    /// \brief Perform iteration
    void iterate ()
    {
        if (!initialized)
            throw std::runtime_error(
                    "ERROR: vSMC::Sampler::iterate: "
                    "Sampler has not been initialized yet");

        ++iter_num;
        accept_history.push_back(move_particle(iter_num, particle));
        post_move();
    }

    /// \brief Perform iteration
    ///
    /// \param n The number of iterations to be performed
    void iterate (std::size_t n)
    {
        for (std::size_t i = 0; i != n; ++i)
            iterate();
    }

    /// \brief Perform importance sampling integration
    ///
    /// \param intgral The functor used to compute the integrands
    double integrate (typename Monitor<T>::integral_type integral) const
    {
        std::size_t n = particle.size();
        integral(iter_num, particle, integrate_tmp);

        return cblas_ddot(n, particle.get_weight_ptr(), 1, integrate_tmp, 1);
    }

    /// \brief Perform importance sampling integration
    ///
    /// \param intgral The functor used to compute the integrands
    /// \param param Additional parameters to be passed to integral
    double integrate (integral_type integral, void *param) const
    {
        std::size_t n = particle.size();
        integral(iter_num, particle, integrate_tmp, param);

        return cblas_ddot(n, particle.get_weight_ptr(), 1, integrate_tmp, 1);
    }

    /// \brief Add a monitor, similar to \b monitor in \b BUGS
    ///
    /// \param name The name of the monitor
    /// \param integral The functor used to compute the integrands
    void add_monitor (const std::string &name,
            const typename Monitor<T>::integral_type &integral)
    {
        monitor.insert(
                typename std::map<std::string, Monitor<T> >::value_type(
                    name, Monitor<T>(integral, particle.size())));
    }

    /// \brief Get the iteration index of a monitor
    ///
    /// \param The name of the monitor
    /// \return A vector of the monitor index
    typename Monitor<T>::index_type get_monitor_index (
            const std::string &name) const
    {
        return monitor.find(name)->second.get_index();
    }

    /// \brief Get the record of Monite Carlo integration of a monitor
    ///
    /// \param name The name of the monitor
    /// \return A vector of the monitor record
    typename Monitor<T>::record_type get_monitor_record (
            const std::string &name) const
    {
        return monitor.find(name)->second.get_record();
    }

    /// \brief Get both the iteration index and record of a monitor
    typename Monitor<T>::value_type get_monitor_value (
            const std::string &name) const
    {
        return monitor.find(name)->second.get();
    }

    /// \brief Erase a monitor by name
    ///
    /// \param name The name of the monitor
    void erase_monitor (const std::string &name)
    {
        monitor.erase(name);
    }

    /// \brief Clear all monitors
    void clear_monitor ()
    {
        monitor.clear();
    }

    /// \brief Set the path sampling integral
    ///
    /// \param integral The functor used to compute the integrands
    void set_path_sampling (path_type integral)
    {
        path_integral = integral;
    }

    /// \brief Stop path sampling
    void clear_path_sampling ()
    {
        path_integral = NULL;
    }

    /// \brief Get the results of path sampling
    double get_path_sampling () const
    {
        return 0;
    }

    private :

    /// Initialization indicator
    bool initialized;

    /// Initialization and movement
    init_type init_particle;
    move_type move_particle;

    /// Resampling
    vDist::RngGSL rng;
    ResampleScheme scheme;
    double threshold;

    /// Particle sets
    Particle<T> particle;
    std::size_t iter_num;
    std::vector<double> ess_history;
    std::vector<bool> resample_history;
    std::vector<std::size_t> accept_history;

    /// History
    HistoryMode mode;
    History<T> history;

    /// Monte Carlo estimation by integration
    mutable vDist::tool::Buffer<double> integrate_tmp;
    std::map<std::string, Monitor<T> > monitor;

    /// Path sampling
    path_type path_integral;
    std::vector<double> path_sample;
    std::vector<double> path_width;
    double path_estimate;

    void post_move ()
    {
        bool res_indicator = false;
        if (particle.ESS() < threshold) {
            res_indicator = true;
            particle.resample(scheme, rng.get_rng());
        }
        ess_history.push_back(particle.ESS());
        resample_history.push_back(res_indicator);

        if (mode != HISTORY_NONE)
            history.push_back(particle);

        for (typename std::map<std::string, Monitor<T> >::iterator
                imap = monitor.begin(); imap != monitor.end(); ++imap) {
            if (!imap->second.empty())
                imap->second.eval(iter_num, particle);
        }

        if (!path_integral.empty()) {
            double width;
            path_sample.push_back(eval_path(width));
            path_width.push_back(width);
        }
    }

    double eval_path (double &width)
    {
        width = path_integral(iter_num, particle, integrate_tmp);
        return cblas_ddot(particle.size(),
                particle.get_weight_ptr(), 1, integrate_tmp, 1);
    }
}; // class Sampler

} // namespace vSMC

#endif // V_SMC_SAMPLER_HPP
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "s60mediametadataprovider.h"
#include "s60mediaplayersession.h"
#include <QtCore/qdebug.h>

S60MediaMetaDataProvider::S60MediaMetaDataProvider(MS60MediaPlayerResolver& mediaPlayerResolver, QObject *parent)
    : QMetaDataControl(parent)
    , m_mediaPlayerResolver(mediaPlayerResolver)
    , m_session(NULL)
{
}

S60MediaMetaDataProvider::~S60MediaMetaDataProvider()
{
}

bool S60MediaMetaDataProvider::isMetaDataAvailable() const
{
    m_session = m_mediaPlayerResolver.PlayerSession();
    if (m_session)
       return m_session->isMetadataAvailable();
    return false;
}

bool S60MediaMetaDataProvider::isWritable() const
{
    return false;
}

QVariant S60MediaMetaDataProvider::metaData(QtMediaServices::MetaData key) const
{
    m_session = m_mediaPlayerResolver.PlayerSession();
    if (m_session && m_session->isMetadataAvailable())
        return m_session->metaData(metaDataKeyAsString(key));
    return QVariant();
}

void S60MediaMetaDataProvider::setMetaData(QtMediaServices::MetaData key, QVariant const &value)
{
    Q_UNUSED(key);
    Q_UNUSED(value);
}
QList<QtMediaServices::MetaData> S60MediaMetaDataProvider::availableMetaData() const
{
    m_session = m_mediaPlayerResolver.PlayerSession();
    QList<QtMediaServices::MetaData> metaDataTags;
    if (m_session && m_session->isMetadataAvailable()) {
        for (int i = QtMediaServices::Title; i <= QtMediaServices::DeviceSettingDescription; i++) {
            QString metaData = metaDataKeyAsString((QtMediaServices::MetaData)i);
            if (!metaData.isEmpty()) {
                if (!m_session->metaData(metaData).toString().isEmpty()) {
                    metaDataTags.append((QtMediaServices::MetaData)i);
                }
            }
        }
    }
    return metaDataTags;
}

QVariant S60MediaMetaDataProvider::extendedMetaData(const QString &key) const
{
    m_session = m_mediaPlayerResolver.PlayerSession();
    if (m_session && m_session->isMetadataAvailable())
        return m_session->metaData(key);
    return QVariant();
}

void S60MediaMetaDataProvider::setExtendedMetaData(const QString &key, QVariant const &value)
{
    Q_UNUSED(key);
    Q_UNUSED(value);
}

QStringList S60MediaMetaDataProvider::availableExtendedMetaData() const
{
    m_session = m_mediaPlayerResolver.PlayerSession();
    if (m_session && m_session->isMetadataAvailable())
        return m_session->availableMetaData().keys();
    return QStringList();
}

QString S60MediaMetaDataProvider::metaDataKeyAsString(QtMediaServices::MetaData key) const
{
    switch(key) {
        case QtMediaServices::Title: return "title";
        case QtMediaServices::AlbumArtist: return "artist";
        case QtMediaServices::Comment: return "comment";
        case QtMediaServices::Genre: return "genre";
        case QtMediaServices::Year: return "year";
        case QtMediaServices::Copyright: return "copyright";
        case QtMediaServices::AlbumTitle: return "album";
        case QtMediaServices::Composer: return "composer";
        case QtMediaServices::TrackNumber: return "albumtrack";
        case QtMediaServices::AudioBitRate: return "audiobitrate";
        case QtMediaServices::VideoBitRate: return "videobitrate";
        case QtMediaServices::Duration: return "duration";
        case QtMediaServices::MediaType: return "contenttype";
        case QtMediaServices::SubTitle: // TODO: Find the matching metadata keys
        case QtMediaServices::Description:
        case QtMediaServices::Category:
        case QtMediaServices::Date:
        case QtMediaServices::UserRating:
        case QtMediaServices::Keywords:
        case QtMediaServices::Language:
        case QtMediaServices::Publisher:
        case QtMediaServices::ParentalRating:
        case QtMediaServices::RatingOrganisation:
        case QtMediaServices::Size:
        case QtMediaServices::AudioCodec:
        case QtMediaServices::AverageLevel:
        case QtMediaServices::ChannelCount:
        case QtMediaServices::PeakValue:
        case QtMediaServices::SampleRate:
        case QtMediaServices::Author:
        case QtMediaServices::ContributingArtist:
        case QtMediaServices::Conductor:
        case QtMediaServices::Lyrics:
        case QtMediaServices::Mood:
        case QtMediaServices::TrackCount:
        case QtMediaServices::CoverArtUrlSmall:
        case QtMediaServices::CoverArtUrlLarge:
        case QtMediaServices::Resolution:
        case QtMediaServices::PixelAspectRatio:
        case QtMediaServices::VideoFrameRate:
        case QtMediaServices::VideoCodec:
        case QtMediaServices::PosterUrl:
        case QtMediaServices::ChapterNumber:
        case QtMediaServices::Director:
        case QtMediaServices::LeadPerformer:
        case QtMediaServices::Writer:
        case QtMediaServices::CameraManufacturer:
        case QtMediaServices::CameraModel:
        case QtMediaServices::Event:
        case QtMediaServices::Subject:
        default:
            break;
    }

    return QString();
}
<commit_msg>Symbian: Changed backend to support recently added QtMediaServices::CoverArtImage metadata key.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "s60mediametadataprovider.h"
#include "s60mediaplayersession.h"
#include <QtCore/qdebug.h>

S60MediaMetaDataProvider::S60MediaMetaDataProvider(MS60MediaPlayerResolver& mediaPlayerResolver, QObject *parent)
    : QMetaDataControl(parent)
    , m_mediaPlayerResolver(mediaPlayerResolver)
    , m_session(NULL)
{
}

S60MediaMetaDataProvider::~S60MediaMetaDataProvider()
{
}

bool S60MediaMetaDataProvider::isMetaDataAvailable() const
{
    m_session = m_mediaPlayerResolver.PlayerSession();
    if (m_session)
       return m_session->isMetadataAvailable();
    return false;
}

bool S60MediaMetaDataProvider::isWritable() const
{
    return false;
}

QVariant S60MediaMetaDataProvider::metaData(QtMediaServices::MetaData key) const
{
    m_session = m_mediaPlayerResolver.PlayerSession();
    if (m_session && m_session->isMetadataAvailable())
        return m_session->metaData(metaDataKeyAsString(key));
    return QVariant();
}

void S60MediaMetaDataProvider::setMetaData(QtMediaServices::MetaData key, QVariant const &value)
{
    Q_UNUSED(key);
    Q_UNUSED(value);
}
QList<QtMediaServices::MetaData> S60MediaMetaDataProvider::availableMetaData() const
{
    m_session = m_mediaPlayerResolver.PlayerSession();
    QList<QtMediaServices::MetaData> metaDataTags;
    if (m_session && m_session->isMetadataAvailable()) {
        for (int i = QtMediaServices::Title; i <= QtMediaServices::DeviceSettingDescription; i++) {
            QString metaData = metaDataKeyAsString((QtMediaServices::MetaData)i);
            if (!metaData.isEmpty()) {
                if (!m_session->metaData(metaData).toString().isEmpty()) {
                    metaDataTags.append((QtMediaServices::MetaData)i);
                }
            }
        }
    }
    return metaDataTags;
}

QVariant S60MediaMetaDataProvider::extendedMetaData(const QString &key) const
{
    m_session = m_mediaPlayerResolver.PlayerSession();
    if (m_session && m_session->isMetadataAvailable())
        return m_session->metaData(key);
    return QVariant();
}

void S60MediaMetaDataProvider::setExtendedMetaData(const QString &key, QVariant const &value)
{
    Q_UNUSED(key);
    Q_UNUSED(value);
}

QStringList S60MediaMetaDataProvider::availableExtendedMetaData() const
{
    m_session = m_mediaPlayerResolver.PlayerSession();
    if (m_session && m_session->isMetadataAvailable())
        return m_session->availableMetaData().keys();
    return QStringList();
}

QString S60MediaMetaDataProvider::metaDataKeyAsString(QtMediaServices::MetaData key) const
{
    switch(key) {
        case QtMediaServices::Title: return "title";
        case QtMediaServices::AlbumArtist: return "artist";
        case QtMediaServices::Comment: return "comment";
        case QtMediaServices::Genre: return "genre";
        case QtMediaServices::Year: return "year";
        case QtMediaServices::Copyright: return "copyright";
        case QtMediaServices::AlbumTitle: return "album";
        case QtMediaServices::Composer: return "composer";
        case QtMediaServices::TrackNumber: return "albumtrack";
        case QtMediaServices::AudioBitRate: return "audiobitrate";
        case QtMediaServices::VideoBitRate: return "videobitrate";
        case QtMediaServices::Duration: return "duration";
        case QtMediaServices::MediaType: return "contenttype";
        case QtMediaServices::CoverArtImage: return "attachedpicture";
        case QtMediaServices::SubTitle: // TODO: Find the matching metadata keys
        case QtMediaServices::Description:
        case QtMediaServices::Category:
        case QtMediaServices::Date:
        case QtMediaServices::UserRating:
        case QtMediaServices::Keywords:
        case QtMediaServices::Language:
        case QtMediaServices::Publisher:
        case QtMediaServices::ParentalRating:
        case QtMediaServices::RatingOrganisation:
        case QtMediaServices::Size:
        case QtMediaServices::AudioCodec:
        case QtMediaServices::AverageLevel:
        case QtMediaServices::ChannelCount:
        case QtMediaServices::PeakValue:
        case QtMediaServices::SampleRate:
        case QtMediaServices::Author:
        case QtMediaServices::ContributingArtist:
        case QtMediaServices::Conductor:
        case QtMediaServices::Lyrics:
        case QtMediaServices::Mood:
        case QtMediaServices::TrackCount:
        case QtMediaServices::CoverArtUrlSmall:
        case QtMediaServices::CoverArtUrlLarge:
        case QtMediaServices::Resolution:
        case QtMediaServices::PixelAspectRatio:
        case QtMediaServices::VideoFrameRate:
        case QtMediaServices::VideoCodec:
        case QtMediaServices::PosterUrl:
        case QtMediaServices::ChapterNumber:
        case QtMediaServices::Director:
        case QtMediaServices::LeadPerformer:
        case QtMediaServices::Writer:
        case QtMediaServices::CameraManufacturer:
        case QtMediaServices::CameraModel:
        case QtMediaServices::Event:
        case QtMediaServices::Subject:
        default:
            break;
    }

    return QString();
}
<|endoftext|>


<commit_before>#include "sensorsConfigurationWidget.h"
#include "ui_sensorsConfigurationWidget.h"
#include "../../../../qrkernel/settingsManager.h"

using namespace qReal::interpreters::robots;
using namespace qReal::interpreters::robots::details;

SensorsConfigurationWidget::SensorsConfigurationWidget(bool autosaveMode, QWidget *parent)
	: QWidget(parent)
	, mUi(new Ui::SensorsConfigurationWidget)
{
	mUi->setupUi(this);
	reinitValues();
	refresh();
	if (autosaveMode) {
		startChangesListening();
	}
}

SensorsConfigurationWidget::~SensorsConfigurationWidget()
{
	delete mUi;
}

void SensorsConfigurationWidget::startChangesListening()
{
	connect(mUi->port1ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save()));
	connect(mUi->port2ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save()));
	connect(mUi->port3ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save()));
	connect(mUi->port4ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save()));
}

void SensorsConfigurationWidget::reinitValues()
{
	QStringList sensorNames;
	sensorNames << tr("Unused")
			<< tr("Touch sensor (boolean value)")
			<< tr("Touch sensor (raw value)")
			<< tr("Sonar sensor")
			<< tr("Light sensor")
			<< tr("Color sensor (full colors)")
			<< tr("Color sensor (red)")
			<< tr("Color sensor (green)")
			<< tr("Color sensor (blue)")
			<< tr("Color sensor (passive)")
			<< tr("Sound sensor")
			<< tr("gyroscope(passive)")
			<< tr("aks(passive)")
	;

	mUi->port1ComboBox->clear();
	mUi->port2ComboBox->clear();
	mUi->port3ComboBox->clear();
	mUi->port4ComboBox->clear();
	mUi->port1ComboBox->addItems(sensorNames);
	mUi->port2ComboBox->addItems(sensorNames);
	mUi->port3ComboBox->addItems(sensorNames);
	mUi->port4ComboBox->addItems(sensorNames);
}

void SensorsConfigurationWidget::changeEvent(QEvent *e)
{
	switch (e->type()) {
	case QEvent::LanguageChange: {
		retranslateUi();
		break;
	}
	default:
		break;
	}
}

void SensorsConfigurationWidget::refresh()
{
	sensorType::SensorTypeEnum const port1 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port1SensorType").toInt());
	sensorType::SensorTypeEnum const port2 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port2SensorType").toInt());
	sensorType::SensorTypeEnum const port3 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port3SensorType").toInt());
	sensorType::SensorTypeEnum const port4 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port4SensorType").toInt());

	mUi->port1ComboBox->setCurrentIndex(port1);
	mUi->port2ComboBox->setCurrentIndex(port2);
	mUi->port3ComboBox->setCurrentIndex(port3);
	mUi->port4ComboBox->setCurrentIndex(port4);
}

void SensorsConfigurationWidget::save()
{
	SettingsManager::setValue("port1SensorType", selectedPort1Sensor());
	SettingsManager::setValue("port2SensorType", selectedPort2Sensor());
	SettingsManager::setValue("port3SensorType", selectedPort3Sensor());
	SettingsManager::setValue("port4SensorType", selectedPort4Sensor());
	emit saved();
}

void SensorsConfigurationWidget::retranslateUi()
{
	mUi->retranslateUi(this);
	reinitValues();
}

sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort1Sensor() const
{
	return static_cast<sensorType::SensorTypeEnum>(mUi->port1ComboBox->currentIndex());
}

sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort2Sensor() const
{
	return static_cast<sensorType::SensorTypeEnum>(mUi->port2ComboBox->currentIndex());
}

sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort3Sensor() const
{
	return static_cast<sensorType::SensorTypeEnum>(mUi->port3ComboBox->currentIndex());
}

sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort4Sensor() const
{
	return static_cast<sensorType::SensorTypeEnum>(mUi->port4ComboBox->currentIndex());
}
<commit_msg>someChanges<commit_after>#include "sensorsConfigurationWidget.h"
#include "ui_sensorsConfigurationWidget.h"
#include "../../../../qrkernel/settingsManager.h"

using namespace qReal::interpreters::robots;
using namespace qReal::interpreters::robots::details;

SensorsConfigurationWidget::SensorsConfigurationWidget(bool autosaveMode, QWidget *parent)
	: QWidget(parent)
	, mUi(new Ui::SensorsConfigurationWidget)
{
	mUi->setupUi(this);
	reinitValues();
	refresh();
	if (autosaveMode) {
		startChangesListening();
	}
}

SensorsConfigurationWidget::~SensorsConfigurationWidget()
{
	delete mUi;
}

void SensorsConfigurationWidget::startChangesListening()
{
	connect(mUi->port1ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save()));
	connect(mUi->port2ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save()));
	connect(mUi->port3ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save()));
	connect(mUi->port4ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save()));
}

void SensorsConfigurationWidget::reinitValues()
{
	QStringList sensorNames;
	sensorNames << tr("Unused")
			<< tr("Touch sensor (boolean value)")
			<< tr("Touch sensor (raw value)")
			<< tr("Sonar sensor")
			<< tr("Light sensor")
			<< tr("Color sensor (full colors)")
			<< tr("Color sensor (red)")
			<< tr("Color sensor (green)")
			<< tr("Color sensor (blue)")
			<< tr("Color sensor (passive)")
			<< tr("Sound sensor")
			<< tr("Gyroscope")
			<< tr("Accelerometer")
	;

	mUi->port1ComboBox->clear();
	mUi->port2ComboBox->clear();
	mUi->port3ComboBox->clear();
	mUi->port4ComboBox->clear();
	mUi->port1ComboBox->addItems(sensorNames);
	mUi->port2ComboBox->addItems(sensorNames);
	mUi->port3ComboBox->addItems(sensorNames);
	mUi->port4ComboBox->addItems(sensorNames);
}

void SensorsConfigurationWidget::changeEvent(QEvent *e)
{
	switch (e->type()) {
	case QEvent::LanguageChange: {
		retranslateUi();
		break;
	}
	default:
		break;
	}
}

void SensorsConfigurationWidget::refresh()
{
	sensorType::SensorTypeEnum const port1 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port1SensorType").toInt());
	sensorType::SensorTypeEnum const port2 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port2SensorType").toInt());
	sensorType::SensorTypeEnum const port3 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port3SensorType").toInt());
	sensorType::SensorTypeEnum const port4 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port4SensorType").toInt());

	mUi->port1ComboBox->setCurrentIndex(port1);
	mUi->port2ComboBox->setCurrentIndex(port2);
	mUi->port3ComboBox->setCurrentIndex(port3);
	mUi->port4ComboBox->setCurrentIndex(port4);
}

void SensorsConfigurationWidget::save()
{
	SettingsManager::setValue("port1SensorType", selectedPort1Sensor());
	SettingsManager::setValue("port2SensorType", selectedPort2Sensor());
	SettingsManager::setValue("port3SensorType", selectedPort3Sensor());
	SettingsManager::setValue("port4SensorType", selectedPort4Sensor());
	emit saved();
}

void SensorsConfigurationWidget::retranslateUi()
{
	mUi->retranslateUi(this);
	reinitValues();
}

sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort1Sensor() const
{
	return static_cast<sensorType::SensorTypeEnum>(mUi->port1ComboBox->currentIndex());
}

sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort2Sensor() const
{
	return static_cast<sensorType::SensorTypeEnum>(mUi->port2ComboBox->currentIndex());
}

sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort3Sensor() const
{
	return static_cast<sensorType::SensorTypeEnum>(mUi->port3ComboBox->currentIndex());
}

sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort4Sensor() const
{
	return static_cast<sensorType::SensorTypeEnum>(mUi->port4ComboBox->currentIndex());
}
<|endoftext|>


<commit_before>#include <mpi.h>

#include <iostream>
#include <vector>

// using TCLAP for command line parsing
#include <tclap/CmdLine.h>

// parallel block decomposition of a file
#include <mxx/file.hpp>

// suffix array construction
#include <suffix_array.hpp>
#include <alphabet.hpp> // for random DNA

#include <timer.hpp>

void benchmark_k(const std::string& local_str, int k, MPI_Comm comm)
{
    int p, rank;
    MPI_Comm_size(comm, &p);
    MPI_Comm_rank(comm, &rank);
    timer t;

    typedef suffix_array<std::string::const_iterator, std::size_t, false> sa_t;

    {
        // without LCP and fast
        std::string method_name = "reg-fast-nolcp";
        double start = t.get_ms();
        sa_t sa(local_str.begin(), local_str.end(), comm);
        sa.construct(true, k);
        double time = t.get_ms() - start;
        if (rank == 0)
            std::cout << p << ";" << method_name << ";" << time << std::endl;
    }
    {
        // without LCP and slow
        std::string method_name = "reg-nolcp";
        double start = t.get_ms();
        sa_t sa(local_str.begin(), local_str.end(), comm);
        sa.construct(false, k);
        double time = t.get_ms() - start;
        if (rank == 0)
            std::cout << p << ";" << method_name << ";" << time << std::endl;
    }
    // TODO: array construction with multiple
}

int main(int argc, char *argv[])
{
    // set up MPI
    MPI_Init(&argc, &argv);
    int p, rank;
    MPI_Comm_size(MPI_COMM_WORLD, &p);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    try {
    // define commandline usage
    TCLAP::CmdLine cmd("Benchmark different suffix array construction variants.");
    TCLAP::ValueArg<std::string> fileArg("f", "file", "Input filename.", true, "", "filename");
    TCLAP::ValueArg<std::size_t> randArg("r", "random", "Random input size", true, 0, "size");
    cmd.xorAdd(fileArg, randArg);
    TCLAP::ValueArg<int> iterArg("i", "iterations", "Number of iterations to run", false, 1, "num");
    cmd.add(iterArg);
    TCLAP::ValueArg<int> kArg("k", "kmer-size", "The size of the `k` in the intial sorting.", false, 0, "size");
    cmd.add(kArg);
    cmd.parse(argc, argv);

    std::string local_str;
    if (fileArg.getValue() != "")
    {
        local_str = mxx::file_block_decompose(fileArg.getValue().c_str());
    }
    else
    {
        // TODO: proper parallel random generation!!
        local_str = rand_dna(randArg.getValue(), rank);
    }

    // run all benchmarks
    for (int i = 0; i < iterArg.getValue(); ++i)
        benchmark_k(local_str, kArg.getValue(), MPI_COMM_WORLD);

    // catch any TCLAP exception
    } catch (TCLAP::ArgException& e) {
        std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
    }

    // finalize MPI
    MPI_Finalize();
    return 0;
}
<commit_msg>psac: output of `k` during benchmark<commit_after>#include <mpi.h>

#include <iostream>
#include <vector>

// using TCLAP for command line parsing
#include <tclap/CmdLine.h>

// parallel block decomposition of a file
#include <mxx/file.hpp>

// suffix array construction
#include <suffix_array.hpp>
#include <alphabet.hpp> // for random DNA

#include <timer.hpp>

void benchmark_k(const std::string& local_str, int k, MPI_Comm comm)
{
    int p, rank;
    MPI_Comm_size(comm, &p);
    MPI_Comm_rank(comm, &rank);
    timer t;

    typedef suffix_array<std::string::const_iterator, std::size_t, false> sa_t;

    {
        // without LCP and fast
        std::string method_name = "reg-fast-nolcp";
        double start = t.get_ms();
        sa_t sa(local_str.begin(), local_str.end(), comm);
        sa.construct(true, k);
        double time = t.get_ms() - start;
        if (rank == 0)
            std::cout << p << ";" << method_name << ";" << k << ";" << time << std::endl;
    }
    {
        // without LCP and slow
        std::string method_name = "reg-nolcp";
        double start = t.get_ms();
        sa_t sa(local_str.begin(), local_str.end(), comm);
        sa.construct(false, k);
        double time = t.get_ms() - start;
        if (rank == 0)
            std::cout << p << ";" << method_name << ";" << k << ";" << time << std::endl;
    }
    // TODO: array construction with multiple
}

int main(int argc, char *argv[])
{
    // set up MPI
    MPI_Init(&argc, &argv);
    int p, rank;
    MPI_Comm_size(MPI_COMM_WORLD, &p);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    try {
    // define commandline usage
    TCLAP::CmdLine cmd("Benchmark different suffix array construction variants.");
    TCLAP::ValueArg<std::string> fileArg("f", "file", "Input filename.", true, "", "filename");
    TCLAP::ValueArg<std::size_t> randArg("r", "random", "Random input size", true, 0, "size");
    cmd.xorAdd(fileArg, randArg);
    TCLAP::ValueArg<int> iterArg("i", "iterations", "Number of iterations to run", false, 1, "num");
    cmd.add(iterArg);
    TCLAP::ValueArg<int> kArg("k", "kmer-size", "The size of the `k` in the intial sorting.", false, 0, "size");
    cmd.add(kArg);
    cmd.parse(argc, argv);

    std::string local_str;
    if (fileArg.getValue() != "")
    {
        local_str = mxx::file_block_decompose(fileArg.getValue().c_str());
    }
    else
    {
        // TODO: proper parallel random generation!!
        local_str = rand_dna(randArg.getValue(), rank);
    }

    // run all benchmarks
    for (int i = 0; i < iterArg.getValue(); ++i)
        benchmark_k(local_str, kArg.getValue(), MPI_COMM_WORLD);

    // catch any TCLAP exception
    } catch (TCLAP::ArgException& e) {
        std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
    }

    // finalize MPI
    MPI_Finalize();
    return 0;
}
<|endoftext|>


<commit_before>/**
 * @file   ArgumentParserTest.cpp
 * @brief  ArgumentParser class tester.
 * @author zer0
 * @date   2019-10-09
 */

#include <gtest/gtest.h>
#include <libtbag/string/ArgumentParser.hpp>

using namespace libtbag;
using namespace libtbag::string;

using ap = ArgumentParser;
using at = ArgumentParser::ActionType;

TEST(ArgumentParserTest, Add)
{
    ArgumentParser parser;
    ASSERT_EQ(E_SUCCESS, parser.add({{"-d", "--device"},
                                     ArgumentParser::ActionType::AT_STORE,
                                     "device"}));
    ASSERT_EQ(E_SUCCESS, parser.add(ap::const_value=2,
                                    ap::default_value=1,
                                    ap::store_const,
                                    ap::name="--input-type",
                                    ap::name="-t",
                                    ap::dest="input_type"));
    ASSERT_EQ(E_SUCCESS, parser.add("type", at::AT_STORE, "type"));
}

TEST(ArgumentParserTest, Optional_01)
{
    ArgumentParser parser;
    ASSERT_EQ(E_SUCCESS, parser.add({{"-d", "--device"},
                                     ArgumentParser::ActionType::AT_STORE,
                                     "device"}));

    auto const result1 = parser.parse("program -d 0");
    ASSERT_EQ(E_SUCCESS, result1.code);
    ASSERT_EQ(1, result1.value.optional.size());
    ASSERT_STREQ("0", result1.value.optional.at("device").c_str());
    ASSERT_EQ(0, result1.value.positional.size());
    ASSERT_EQ(0, result1.value.remain.size());

    auto const result2 = parser.parse("program --device=1");
    ASSERT_EQ(E_SUCCESS, result2.code);
    ASSERT_EQ(1, result2.value.optional.size());
    ASSERT_STREQ("1", result2.value.optional.at("device").c_str());
    ASSERT_EQ(0, result2.value.positional.size());
    ASSERT_EQ(0, result2.value.remain.size());

    auto const result3 = parser.parse("program --device 2");
    ASSERT_EQ(E_SUCCESS, result3.code);
    ASSERT_EQ(1, result3.value.optional.size());
    ASSERT_STREQ("2", result3.value.optional.at("device").c_str());
    ASSERT_EQ(0, result3.value.positional.size());
    ASSERT_EQ(0, result3.value.remain.size());

    auto const result4 = parser.parse("program --device");
    ASSERT_EQ(E_ILLSTATE, result4.code);

    auto const result5 = parser.parse("program test");
    ASSERT_EQ(E_SUCCESS, result5.code);
    ASSERT_EQ(0, result5.value.optional.size());
    ASSERT_EQ(0, result5.value.positional.size());
    ASSERT_EQ(1, result5.value.remain.size());
    ASSERT_STREQ("test", result5.value.remain[0].c_str());
}

TEST(ArgumentParserTest, Optional_02)
{
    ArgumentParser parser;
    ASSERT_EQ(E_SUCCESS, parser.add(ap::const_value=2,
                                    ap::default_value=1,
                                    ap::store_const,
                                    ap::name="--device",
                                    ap::name="-d",
                                    ap::dest="device"));

    auto const result1 = parser.parse("program --device 3 test1 test2");
    ASSERT_EQ(E_SUCCESS, result1.code);
    ASSERT_EQ(1, result1.value.optional.size());
    ASSERT_STREQ("2", result1.value.optional.at("device").c_str());
    ASSERT_EQ(0, result1.value.positional.size());
    ASSERT_EQ(3, result1.value.remain.size());
    ASSERT_STREQ("3", result1.value.remain[0].c_str());
    ASSERT_STREQ("test1", result1.value.remain[1].c_str());
    ASSERT_STREQ("test2", result1.value.remain[2].c_str());

    auto const result2 = parser.parse("program");
    ASSERT_EQ(1, result2.value.optional.size());
    ASSERT_STREQ("1", result2.value.optional.at("device").c_str());
    ASSERT_EQ(0, result2.value.positional.size());
    ASSERT_EQ(0, result2.value.remain.size());

    auto const result3 = parser.parse("program -d");
    ASSERT_EQ(1, result3.value.optional.size());
    ASSERT_STREQ("2", result3.value.optional.at("device").c_str());
    ASSERT_EQ(0, result3.value.positional.size());
    ASSERT_EQ(0, result3.value.remain.size());
}

TEST(ArgumentParserTest, Positional_01)
{
    ArgumentParser parser;
    ASSERT_EQ(E_SUCCESS, parser.add("type", at::AT_STORE, "type"));

    auto const result1 = parser.parse("program bool test1 test2");
    ASSERT_EQ(E_SUCCESS, result1.code);
    ASSERT_EQ(0, result1.value.optional.size());
    ASSERT_EQ(1, result1.value.positional.size());
    ASSERT_STREQ("bool", result1.value.positional.at("type").c_str());
    ASSERT_EQ(2, result1.value.remain.size());
    ASSERT_STREQ("test1", result1.value.remain[0].c_str());
    ASSERT_STREQ("test2", result1.value.remain[1].c_str());

    auto const result2 = parser.parse("program");
    ASSERT_EQ(E_ILLARGS, result2.code);
}

TEST(ArgumentParserTest, Positional_02)
{
    ArgumentParser parser;
    ASSERT_EQ(E_SUCCESS, parser.add(ap::name="aa1"));
    ASSERT_EQ(E_SUCCESS, parser.add(ap::name="aa2", ap::default_value=100));

    auto const result1 = parser.parse("program val1");
    ASSERT_EQ(E_SUCCESS, result1.code);
    ASSERT_EQ(0, result1.value.optional.size());
    ASSERT_EQ(2, result1.value.positional.size());
    ASSERT_STREQ("val1", result1.value.positional.at("aa1").c_str());
    ASSERT_STREQ("100", result1.value.positional.at("aa2").c_str());
    ASSERT_EQ(0, result1.value.remain.size());

    auto const result2 = parser.parse("program val1 val2");
    ASSERT_EQ(E_SUCCESS, result2.code);
    ASSERT_EQ(0, result2.value.optional.size());
    ASSERT_EQ(2, result2.value.positional.size());
    ASSERT_STREQ("val1", result2.value.positional.at("aa1").c_str());
    ASSERT_STREQ("val2", result2.value.positional.at("aa2").c_str());
    ASSERT_EQ(0, result2.value.remain.size());

    auto const result3 = parser.parse("program");
    ASSERT_EQ(E_ILLARGS, result3.code);
}

struct ArgumentParserTestFixture : public testing::Test
{
    ArgumentParser parser;

    void SetUp() override
    {
        parser.add(ap::name="--input", ap::name="-i");
        parser.add(ap::name="--output", ap::name="-o");
        parser.add(ap::name="--threshold", ap::name="-t", ap::default_value=0.5);
        parser.add(ap::name="--verbose", ap::name="-v", ap::store_const, ap::const_value=true);
        parser.add(ap::name="cmd1");
        parser.add(ap::name="cmd2", ap::default_value="empty");
    }

    void TearDown() override
    {
        // EMPTY.
    }
};

TEST_F(ArgumentParserTestFixture, Default)
{
    auto const result1 = parser.parse("program -i test -o result -v -t 0.7 kkk zzz xxx");
    ASSERT_EQ(E_SUCCESS, result1.code);
    ASSERT_EQ(4, result1.value.optional.size());
    ASSERT_STREQ("test", result1.value.optional.at("input").c_str());
    ASSERT_STREQ("result", result1.value.optional.at("output").c_str());
    ASSERT_STREQ("1", result1.value.optional.at("verbose").c_str());
    ASSERT_STREQ("0.7", result1.value.optional.at("threshold").c_str());
    ASSERT_EQ(2, result1.value.positional.size());
    ASSERT_STREQ("kkk", result1.value.positional.at("cmd1").c_str());
    ASSERT_STREQ("zzz", result1.value.positional.at("cmd2").c_str());
    ASSERT_EQ(1, result1.value.remain.size());
    ASSERT_STREQ("xxx", result1.value.remain[0].c_str());
}

<commit_msg>Create ArgumentParserTestFixture.StopParsing tester.<commit_after>/**
 * @file   ArgumentParserTest.cpp
 * @brief  ArgumentParser class tester.
 * @author zer0
 * @date   2019-10-09
 */

#include <gtest/gtest.h>
#include <libtbag/string/ArgumentParser.hpp>

using namespace libtbag;
using namespace libtbag::string;

using ap = ArgumentParser;
using at = ArgumentParser::ActionType;

TEST(ArgumentParserTest, Add)
{
    ArgumentParser parser;
    ASSERT_EQ(E_SUCCESS, parser.add({{"-d", "--device"},
                                     ArgumentParser::ActionType::AT_STORE,
                                     "device"}));
    ASSERT_EQ(E_SUCCESS, parser.add(ap::const_value=2,
                                    ap::default_value=1,
                                    ap::store_const,
                                    ap::name="--input-type",
                                    ap::name="-t",
                                    ap::dest="input_type"));
    ASSERT_EQ(E_SUCCESS, parser.add("type", at::AT_STORE, "type"));
}

TEST(ArgumentParserTest, Optional_01)
{
    ArgumentParser parser;
    ASSERT_EQ(E_SUCCESS, parser.add({{"-d", "--device"},
                                     ArgumentParser::ActionType::AT_STORE,
                                     "device"}));

    auto const result1 = parser.parse("program -d 0");
    ASSERT_EQ(E_SUCCESS, result1.code);
    ASSERT_EQ(1, result1.value.optional.size());
    ASSERT_STREQ("0", result1.value.optional.at("device").c_str());
    ASSERT_EQ(0, result1.value.positional.size());
    ASSERT_EQ(0, result1.value.remain.size());

    auto const result2 = parser.parse("program --device=1");
    ASSERT_EQ(E_SUCCESS, result2.code);
    ASSERT_EQ(1, result2.value.optional.size());
    ASSERT_STREQ("1", result2.value.optional.at("device").c_str());
    ASSERT_EQ(0, result2.value.positional.size());
    ASSERT_EQ(0, result2.value.remain.size());

    auto const result3 = parser.parse("program --device 2");
    ASSERT_EQ(E_SUCCESS, result3.code);
    ASSERT_EQ(1, result3.value.optional.size());
    ASSERT_STREQ("2", result3.value.optional.at("device").c_str());
    ASSERT_EQ(0, result3.value.positional.size());
    ASSERT_EQ(0, result3.value.remain.size());

    auto const result4 = parser.parse("program --device");
    ASSERT_EQ(E_ILLSTATE, result4.code);

    auto const result5 = parser.parse("program test");
    ASSERT_EQ(E_SUCCESS, result5.code);
    ASSERT_EQ(0, result5.value.optional.size());
    ASSERT_EQ(0, result5.value.positional.size());
    ASSERT_EQ(1, result5.value.remain.size());
    ASSERT_STREQ("test", result5.value.remain[0].c_str());
}

TEST(ArgumentParserTest, Optional_02)
{
    ArgumentParser parser;
    ASSERT_EQ(E_SUCCESS, parser.add(ap::const_value=2,
                                    ap::default_value=1,
                                    ap::store_const,
                                    ap::name="--device",
                                    ap::name="-d",
                                    ap::dest="device"));

    auto const result1 = parser.parse("program --device 3 test1 test2");
    ASSERT_EQ(E_SUCCESS, result1.code);
    ASSERT_EQ(1, result1.value.optional.size());
    ASSERT_STREQ("2", result1.value.optional.at("device").c_str());
    ASSERT_EQ(0, result1.value.positional.size());
    ASSERT_EQ(3, result1.value.remain.size());
    ASSERT_STREQ("3", result1.value.remain[0].c_str());
    ASSERT_STREQ("test1", result1.value.remain[1].c_str());
    ASSERT_STREQ("test2", result1.value.remain[2].c_str());

    auto const result2 = parser.parse("program");
    ASSERT_EQ(1, result2.value.optional.size());
    ASSERT_STREQ("1", result2.value.optional.at("device").c_str());
    ASSERT_EQ(0, result2.value.positional.size());
    ASSERT_EQ(0, result2.value.remain.size());

    auto const result3 = parser.parse("program -d");
    ASSERT_EQ(1, result3.value.optional.size());
    ASSERT_STREQ("2", result3.value.optional.at("device").c_str());
    ASSERT_EQ(0, result3.value.positional.size());
    ASSERT_EQ(0, result3.value.remain.size());
}

TEST(ArgumentParserTest, Positional_01)
{
    ArgumentParser parser;
    ASSERT_EQ(E_SUCCESS, parser.add("type", at::AT_STORE, "type"));

    auto const result1 = parser.parse("program bool test1 test2");
    ASSERT_EQ(E_SUCCESS, result1.code);
    ASSERT_EQ(0, result1.value.optional.size());
    ASSERT_EQ(1, result1.value.positional.size());
    ASSERT_STREQ("bool", result1.value.positional.at("type").c_str());
    ASSERT_EQ(2, result1.value.remain.size());
    ASSERT_STREQ("test1", result1.value.remain[0].c_str());
    ASSERT_STREQ("test2", result1.value.remain[1].c_str());

    auto const result2 = parser.parse("program");
    ASSERT_EQ(E_ILLARGS, result2.code);
}

TEST(ArgumentParserTest, Positional_02)
{
    ArgumentParser parser;
    ASSERT_EQ(E_SUCCESS, parser.add(ap::name="aa1"));
    ASSERT_EQ(E_SUCCESS, parser.add(ap::name="aa2", ap::default_value=100));

    auto const result1 = parser.parse("program val1");
    ASSERT_EQ(E_SUCCESS, result1.code);
    ASSERT_EQ(0, result1.value.optional.size());
    ASSERT_EQ(2, result1.value.positional.size());
    ASSERT_STREQ("val1", result1.value.positional.at("aa1").c_str());
    ASSERT_STREQ("100", result1.value.positional.at("aa2").c_str());
    ASSERT_EQ(0, result1.value.remain.size());

    auto const result2 = parser.parse("program val1 val2");
    ASSERT_EQ(E_SUCCESS, result2.code);
    ASSERT_EQ(0, result2.value.optional.size());
    ASSERT_EQ(2, result2.value.positional.size());
    ASSERT_STREQ("val1", result2.value.positional.at("aa1").c_str());
    ASSERT_STREQ("val2", result2.value.positional.at("aa2").c_str());
    ASSERT_EQ(0, result2.value.remain.size());

    auto const result3 = parser.parse("program");
    ASSERT_EQ(E_ILLARGS, result3.code);
}

struct ArgumentParserTestFixture : public testing::Test
{
    ArgumentParser parser;

    void SetUp() override
    {
        parser.add(ap::name="--input", ap::name="-i");
        parser.add(ap::name="--output", ap::name="-o");
        parser.add(ap::name="--threshold", ap::name="-t", ap::default_value=0.5);
        parser.add(ap::name="--verbose", ap::name="-v", ap::store_const, ap::const_value=true);
        parser.add(ap::name="cmd1");
        parser.add(ap::name="cmd2", ap::default_value="empty");
    }

    void TearDown() override
    {
        // EMPTY.
    }
};

TEST_F(ArgumentParserTestFixture, Parse_Complex)
{
    auto const result = parser.parse("program -i test kkk -o result zzz -v xxx -t 0.7 vvv");
    ASSERT_EQ(E_SUCCESS, result.code);
    ASSERT_EQ(4, result.value.optional.size());
    ASSERT_STREQ("test", result.value.optional.at("input").c_str());
    ASSERT_STREQ("result", result.value.optional.at("output").c_str());
    ASSERT_STREQ("1", result.value.optional.at("verbose").c_str());
    ASSERT_STREQ("0.7", result.value.optional.at("threshold").c_str());
    ASSERT_EQ(2, result.value.positional.size());
    ASSERT_STREQ("kkk", result.value.positional.at("cmd1").c_str());
    ASSERT_STREQ("zzz", result.value.positional.at("cmd2").c_str());
    ASSERT_EQ(2, result.value.remain.size());
    ASSERT_STREQ("xxx", result.value.remain[0].c_str());
    ASSERT_STREQ("vvv", result.value.remain[1].c_str());
}

TEST_F(ArgumentParserTestFixture, StopParsing)
{
    auto const result = parser.parse("program kkk -o result -- -v -t 0.7 kkk zzz xxx");
    ASSERT_EQ(E_SUCCESS, result.code);
    ASSERT_EQ(2, result.value.optional.size());
    ASSERT_STREQ("result", result.value.optional.at("output").c_str());
    ASSERT_STREQ("0.5", result.value.optional.at("threshold").substr(0, 3).c_str());
    ASSERT_EQ(2, result.value.positional.size());
    ASSERT_STREQ("kkk", result.value.positional.at("cmd1").c_str());
    ASSERT_STREQ("empty", result.value.positional.at("cmd2").c_str());
    ASSERT_EQ(6, result.value.remain.size());
    ASSERT_STREQ("-v", result.value.remain[0].c_str());
    ASSERT_STREQ("-t", result.value.remain[1].c_str());
    ASSERT_STREQ("0.7", result.value.remain[2].c_str());
    ASSERT_STREQ("kkk", result.value.remain[3].c_str());
    ASSERT_STREQ("zzz", result.value.remain[4].c_str());
    ASSERT_STREQ("xxx", result.value.remain[5].c_str());
}

<|endoftext|>


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

#ifndef _SVSTOR_HXX
#include <sot/storage.hxx>
#endif

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _MySVXACORR_HXX
#include "svxacorr.hxx"
#endif

class SvXMLAutoCorrectImport : public SvXMLImport
{
protected:

    // This method is called after the namespace map has been updated, but
    // before a context for the current element has been pushed.
    virtual SvXMLImportContext *CreateContext( sal_uInt16 nPrefix,
                  const ::rtl::OUString& rLocalName,
                  const ::com::sun::star::uno::Reference<
                    ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
public:
    SvxAutocorrWordList     *pAutocorr_List;
    SvxAutoCorrect          &rAutoCorrect;
    com::sun::star::uno::Reference < com::sun::star::embed::XStorage > xStorage;
    //SvStorageRef            &rStorage;

    // #110680#
    SvXMLAutoCorrectImport(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
        SvxAutocorrWordList *pNewAutocorr_List,
        SvxAutoCorrect &rNewAutoCorrect,
        const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& rNewStorage);

    ~SvXMLAutoCorrectImport ( void ) throw ();
};

class SvXMLWordListContext : public SvXMLImportContext
{
private:
    SvXMLAutoCorrectImport & rLocalRef;
public:
    SvXMLWordListContext ( SvXMLAutoCorrectImport& rImport,
                           sal_uInt16 nPrefix,
                           const rtl::OUString& rLocalName,
                           const ::com::sun::star::uno::Reference<
                           ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
    virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
                           const rtl::OUString& rLocalName,
                           const ::com::sun::star::uno::Reference<
                           ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
    ~SvXMLWordListContext ( void );
};

class SvXMLWordContext : public SvXMLImportContext
{
private:
    SvXMLAutoCorrectImport & rLocalRef;
public:
    SvXMLWordContext ( SvXMLAutoCorrectImport& rImport,
                           sal_uInt16 nPrefix,
                           const rtl::OUString& rLocalName,
                           const ::com::sun::star::uno::Reference<
                           ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
    ~SvXMLWordContext ( void );
};

class SvXMLExceptionListImport : public SvXMLImport
{
protected:

    // This method is called after the namespace map has been updated, but
    // before a context for the current element has been pushed.
    virtual SvXMLImportContext *CreateContext( sal_uInt16 nPrefix,
                  const ::rtl::OUString& rLocalName,
                  const ::com::sun::star::uno::Reference<
                    ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
public:
    SvStringsISortDtor  &rList;

    // #110680#
    SvXMLExceptionListImport(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
        SvStringsISortDtor & rNewList );

    ~SvXMLExceptionListImport ( void ) throw ();
};

class SvXMLExceptionListContext : public SvXMLImportContext
{
private:
    SvXMLExceptionListImport & rLocalRef;
public:
    SvXMLExceptionListContext ( SvXMLExceptionListImport& rImport,
                           sal_uInt16 nPrefix,
                           const rtl::OUString& rLocalName,
                           const ::com::sun::star::uno::Reference<
                           ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
    virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
                           const rtl::OUString& rLocalName,
                           const ::com::sun::star::uno::Reference<
                           ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
    ~SvXMLExceptionListContext ( void );
};

class SvXMLExceptionContext : public SvXMLImportContext
{
private:
    SvXMLExceptionListImport & rLocalRef;
public:
    SvXMLExceptionContext ( SvXMLExceptionListImport& rImport,
                           sal_uInt16 nPrefix,
                           const rtl::OUString& rLocalName,
                           const ::com::sun::star::uno::Reference<
                           ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
    ~SvXMLExceptionContext ( void );
};

#endif
<commit_msg>INTEGRATION: CWS vgbugs07 (1.9.876); FILE MERGED 2007/06/04 13:26:47 vg 1.9.876.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SvXMLAutoCorrectImport.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 17:53:22 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SV_XMLAUTOCORRECTIMPORT_HXX
#define _SV_XMLAUTOCORRECTIMPORT_HXX

#ifndef _SVSTOR_HXX
#include <sot/storage.hxx>
#endif

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _MySVXACORR_HXX
#include <svx/svxacorr.hxx>
#endif

class SvXMLAutoCorrectImport : public SvXMLImport
{
protected:

    // This method is called after the namespace map has been updated, but
    // before a context for the current element has been pushed.
    virtual SvXMLImportContext *CreateContext( sal_uInt16 nPrefix,
                  const ::rtl::OUString& rLocalName,
                  const ::com::sun::star::uno::Reference<
                    ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
public:
    SvxAutocorrWordList     *pAutocorr_List;
    SvxAutoCorrect          &rAutoCorrect;
    com::sun::star::uno::Reference < com::sun::star::embed::XStorage > xStorage;
    //SvStorageRef            &rStorage;

    // #110680#
    SvXMLAutoCorrectImport(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
        SvxAutocorrWordList *pNewAutocorr_List,
        SvxAutoCorrect &rNewAutoCorrect,
        const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& rNewStorage);

    ~SvXMLAutoCorrectImport ( void ) throw ();
};

class SvXMLWordListContext : public SvXMLImportContext
{
private:
    SvXMLAutoCorrectImport & rLocalRef;
public:
    SvXMLWordListContext ( SvXMLAutoCorrectImport& rImport,
                           sal_uInt16 nPrefix,
                           const rtl::OUString& rLocalName,
                           const ::com::sun::star::uno::Reference<
                           ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
    virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
                           const rtl::OUString& rLocalName,
                           const ::com::sun::star::uno::Reference<
                           ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
    ~SvXMLWordListContext ( void );
};

class SvXMLWordContext : public SvXMLImportContext
{
private:
    SvXMLAutoCorrectImport & rLocalRef;
public:
    SvXMLWordContext ( SvXMLAutoCorrectImport& rImport,
                           sal_uInt16 nPrefix,
                           const rtl::OUString& rLocalName,
                           const ::com::sun::star::uno::Reference<
                           ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
    ~SvXMLWordContext ( void );
};

class SvXMLExceptionListImport : public SvXMLImport
{
protected:

    // This method is called after the namespace map has been updated, but
    // before a context for the current element has been pushed.
    virtual SvXMLImportContext *CreateContext( sal_uInt16 nPrefix,
                  const ::rtl::OUString& rLocalName,
                  const ::com::sun::star::uno::Reference<
                    ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
public:
    SvStringsISortDtor  &rList;

    // #110680#
    SvXMLExceptionListImport(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
        SvStringsISortDtor & rNewList );

    ~SvXMLExceptionListImport ( void ) throw ();
};

class SvXMLExceptionListContext : public SvXMLImportContext
{
private:
    SvXMLExceptionListImport & rLocalRef;
public:
    SvXMLExceptionListContext ( SvXMLExceptionListImport& rImport,
                           sal_uInt16 nPrefix,
                           const rtl::OUString& rLocalName,
                           const ::com::sun::star::uno::Reference<
                           ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
    virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
                           const rtl::OUString& rLocalName,
                           const ::com::sun::star::uno::Reference<
                           ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
    ~SvXMLExceptionListContext ( void );
};

class SvXMLExceptionContext : public SvXMLImportContext
{
private:
    SvXMLExceptionListImport & rLocalRef;
public:
    SvXMLExceptionContext ( SvXMLExceptionListImport& rImport,
                           sal_uInt16 nPrefix,
                           const rtl::OUString& rLocalName,
                           const ::com::sun::star::uno::Reference<
                           ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
    ~SvXMLExceptionContext ( void );
};

#endif
<|endoftext|>