<commit_before>/* Copyright 2010 SPARTA, Inc., dba Cobham Analytic Solutions
 *
 * This file is part of WATCHER.
 *
 *     WATCHER is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Affero General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     WATCHER is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Affero General Public License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Watcher.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <libwatcher/messageStream.h>
#include <libwatcher/dataPointMessage.h>
#include <libwatcher/playbackTimeRange.h>
#include <libwatcher/speedWatcherMessage.h>
#include <libwatcher/seekWatcherMessage.h>
#include <libwatcher/messageTypesAndVersions.h>
#include <libwatcher/listStreamsMessage.h>

#include <logger.h>

#include "watcherMainWindow.h"
#include "watcherConfig.h"
#include "seriesGraphDialog.h"
#include "watcherStreamListDialog.h"

namespace watcher {

namespace config {
    extern int StreamUid;
} // namespace

namespace ui {

INIT_LOGGER(MainWindow, "MainWindow");

Timestamp EpochTS; // the timestamp of the first message in the event stream
Timestamp MaxTS; // the timestamp of the last event in the stream
Timestamp CurrentTS;
MessageStreamPtr MsgStream;

MainWindow::MainWindow() : checkIOThread(0), streamsDialog(0)
{
    TRACE_ENTER();
    TRACE_EXIT();
}

void MainWindow::dataPointHandler(const QString& dataName, const QString& fromID, const QString& /*layer*/, qlonglong when, double value)
{
    TRACE_ENTER();

    SeriesGraphDialog *series;
    SeriesMap::iterator it = seriesMap.find(dataName);
    if (it == seriesMap.end()) {
	LOG_INFO("found new data series " << dataName.toStdString());
	/* not found, create a new menu item */
	series = new SeriesGraphDialog(dataName);
	seriesMap[dataName] = series;
	menuSeries->addAction(dataName, series, SLOT(show()));
	QObject::connect(this, SIGNAL(clockTick(qlonglong)), series, SLOT(handleClock(qlonglong)));
	QObject::connect(series, SIGNAL(seekStream(qlonglong)), this, SLOT(seekStream(qlonglong)));
    } else {
	series = it->second;
    }
    series->dataPoint(fromID, when, value);

    TRACE_EXIT();
}

void MainWindow::checkIO()
{
    TRACE_ENTER();

    MsgStream = MessageStreamPtr(new MessageStream(watcher::config::Server));
    MsgStream->connect(true);
    MsgStream->getMessageTimeRange();
    if (watcher::config::StreamUid == -1) {
	MsgStream->setDescription("data Watcher");
	MsgStream->startStream();
    } else {
	MsgStream->subscribeToStream(watcher::config::StreamUid);
    }

    // We only care about data point (and (some) control) messages.
    MessageStreamFilterPtr f(new MessageStreamFilter);
    unsigned int ourMessageTypes[] = { DATA_POINT_MESSAGE_TYPE, PLAYBACK_TIME_RANGE_MESSAGE_TYPE,
        SPEED_MESSAGE_TYPE, SEEK_MESSAGE_TYPE, LIST_STREAMS_MESSAGE_TYPE };
    for (size_t t=0; t<(sizeof(ourMessageTypes)/sizeof(ourMessageTypes[0])); t++)
        f->addMessageType(ourMessageTypes[t]);
    MsgStream->addMessageFilter(f);

    MessagePtr msg;
    QString layer;
    while (MsgStream->getNextMessage(msg)) {
        if (watcher::event::isFeederEvent(msg->type))
            LOG_DEBUG("Got feeder message of type: " << msg->type);
	if (msg->type == DATA_POINT_MESSAGE_TYPE) {
	    LOG_DEBUG("got DataPointMessage");
	    CurrentTS = msg->timestamp;
	    if (CurrentTS > MaxTS)
		MaxTS = CurrentTS;
	    emit clockTick(msg->timestamp);
	    watcher::event::DataPointMessagePtr dp = boost::dynamic_pointer_cast<DataPointMessage>(msg);
	    // TODO:
	    // - add layer when DataPointMessage supports its
	    // - support data point messages for edges as well
	    emit dataPointReceived(QString::fromStdString(dp->dataName),
		    QString::fromStdString(dp->fromNodeID.to_string()),
		    layer, dp->timestamp, dp->dataPoints.front());
	} else if (msg->type == PLAYBACK_TIME_RANGE_MESSAGE_TYPE) {
	    LOG_DEBUG("got playback time range");
	    watcher::event::PlaybackTimeRangeMessagePtr m = boost::dynamic_pointer_cast<PlaybackTimeRangeMessage>(msg);
	    EpochTS = m->min_;
	    MaxTS = m->max_;
	    LOG_INFO("epoch TS = " << EpochTS << ", max TS = " << MaxTS);
	} else if (msg->type == SPEED_MESSAGE_TYPE) {
	    watcher::event::SpeedMessagePtr sm = boost::dynamic_pointer_cast<SpeedMessage>(msg);
	} else if (msg->type == SEEK_MESSAGE_TYPE) {
	    watcher::event::SeekMessagePtr sm = boost::dynamic_pointer_cast<SeekMessage>(msg);
	} else if (msg->type == LIST_STREAMS_MESSAGE_TYPE) {
	    watcher::event::ListStreamsMessagePtr lsm = boost::dynamic_pointer_cast<ListStreamsMessage>(msg);
	    for (size_t i = 0; i < lsm->evstreams.size(); ++i) {
		EventStreamInfoPtr ev ( lsm->evstreams[i] );
		streamsDialog->addStream(ev->uid, ev->description);
	    }
	} else {
        // GTL - should not happen except at start as we're filtering by message type.
        LOG_WARN("Recv'd unwanted message type");
	}
    }

    TRACE_EXIT();
}

void MainWindow::setup()
{
    TRACE_ENTER();

    setupUi(this);
    QObject::connect(this,
	SIGNAL(dataPointReceived(const QString& , const QString& , const QString& , qlonglong , double )),
       	this,
	SLOT(dataPointHandler(const QString& , const QString& , const QString& , qlonglong , double )));

    QObject::connect(actionChange_Stream, SIGNAL(triggered()), this, SLOT(listStreams()));

    LOG_INFO("spawning checkIO thread");
    checkIOThread = new boost::thread(&MainWindow::checkIO, this);

    TRACE_EXIT();
}

/** Slot for receiving seek requests
 * @param t the watcher::Timestamp value to seek to (milliseconds)
 */
void MainWindow::seekStream(qlonglong t)
{
    TRACE_ENTER();
    LOG_INFO("seeking to " << t);
    MsgStream->setStreamTimeStart(t);
    TRACE_EXIT();
}

/** Slot to open the change stream dialog. */
void MainWindow::listStreams()
{
    TRACE_ENTER();
    if (!streamsDialog) {
	streamsDialog = new WatcherStreamListDialog;
	connect(streamsDialog, SIGNAL(streamChanged(unsigned long)), this, SLOT(selectStream(unsigned long)));
	connect(streamsDialog->refreshButton, SIGNAL(clicked()), this, SLOT(listStreams()));
	connect(streamsDialog, SIGNAL(reconnect()), this, SLOT(reconnect()));
    }
    streamsDialog->treeWidget->clear();
    streamsDialog->show();

    MsgStream->listStreams();
    TRACE_EXIT();
}

/** Slot to select a new stream. */
void MainWindow::selectStream(unsigned long uid)
{
    TRACE_ENTER();
    LOG_INFO("subscribing to new stream uid " << uid);
    MsgStream->clearMessageCache();
    MsgStream->subscribeToStream(uid);
    closeAllGraphs();
    TRACE_EXIT();
}

/** Slot for receiving the reconnect stream signal from the change stream dialog. */
void MainWindow::reconnect()
{
    TRACE_ENTER();
    LOG_INFO("reconnecting to server upon user request");
    MsgStream->clearMessageCache();
    MsgStream->reconnect();
    closeAllGraphs();
    TRACE_EXIT();
}

void MainWindow::closeAllGraphs()
{
    TRACE_ENTER();
    for (SeriesMap::iterator it = seriesMap.begin(); it != seriesMap.end(); ++it)
	it->second->close();
    seriesMap.clear();
    menuSeries->clear();
    TRACE_EXIT();
}

} // ui
} // watcher

// vim:sw=4
<commit_msg>Ensure the connection to watcherd is active before opening the list streams dialog in order to avoid locking up.<commit_after>/* Copyright 2010 SPARTA, Inc., dba Cobham Analytic Solutions
 *
 * This file is part of WATCHER.
 *
 *     WATCHER is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Affero General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     WATCHER is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Affero General Public License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Watcher.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <libwatcher/messageStream.h>
#include <libwatcher/dataPointMessage.h>
#include <libwatcher/playbackTimeRange.h>
#include <libwatcher/speedWatcherMessage.h>
#include <libwatcher/seekWatcherMessage.h>
#include <libwatcher/messageTypesAndVersions.h>
#include <libwatcher/listStreamsMessage.h>

#include <logger.h>

#include "watcherMainWindow.h"
#include "watcherConfig.h"
#include "seriesGraphDialog.h"
#include "watcherStreamListDialog.h"

namespace watcher {

namespace config {
    extern int StreamUid;
} // namespace

namespace ui {

INIT_LOGGER(MainWindow, "MainWindow");

Timestamp EpochTS; // the timestamp of the first message in the event stream
Timestamp MaxTS; // the timestamp of the last event in the stream
Timestamp CurrentTS;
MessageStreamPtr MsgStream;

MainWindow::MainWindow() : checkIOThread(0), streamsDialog(0)
{
    TRACE_ENTER();
    TRACE_EXIT();
}

void MainWindow::dataPointHandler(const QString& dataName, const QString& fromID, const QString& /*layer*/, qlonglong when, double value)
{
    TRACE_ENTER();

    SeriesGraphDialog *series;
    SeriesMap::iterator it = seriesMap.find(dataName);
    if (it == seriesMap.end()) {
	LOG_INFO("found new data series " << dataName.toStdString());
	/* not found, create a new menu item */
	series = new SeriesGraphDialog(dataName);
	seriesMap[dataName] = series;
	menuSeries->addAction(dataName, series, SLOT(show()));
	QObject::connect(this, SIGNAL(clockTick(qlonglong)), series, SLOT(handleClock(qlonglong)));
	QObject::connect(series, SIGNAL(seekStream(qlonglong)), this, SLOT(seekStream(qlonglong)));
    } else {
	series = it->second;
    }
    series->dataPoint(fromID, when, value);

    TRACE_EXIT();
}

void MainWindow::checkIO()
{
    TRACE_ENTER();

    MsgStream = MessageStreamPtr(new MessageStream(watcher::config::Server));
    MsgStream->connect(true);
    MsgStream->getMessageTimeRange();
    if (watcher::config::StreamUid == -1) {
	MsgStream->setDescription("data Watcher");
	MsgStream->startStream();
    } else {
	MsgStream->subscribeToStream(watcher::config::StreamUid);
    }

    // We only care about data point (and (some) control) messages.
    MessageStreamFilterPtr f(new MessageStreamFilter);
    unsigned int ourMessageTypes[] = { DATA_POINT_MESSAGE_TYPE, PLAYBACK_TIME_RANGE_MESSAGE_TYPE,
        SPEED_MESSAGE_TYPE, SEEK_MESSAGE_TYPE, LIST_STREAMS_MESSAGE_TYPE };
    for (size_t t=0; t<(sizeof(ourMessageTypes)/sizeof(ourMessageTypes[0])); t++)
        f->addMessageType(ourMessageTypes[t]);
    MsgStream->addMessageFilter(f);

    MessagePtr msg;
    QString layer;
    while (MsgStream->getNextMessage(msg)) {
        if (watcher::event::isFeederEvent(msg->type))
            LOG_DEBUG("Got feeder message of type: " << msg->type);
	if (msg->type == DATA_POINT_MESSAGE_TYPE) {
	    LOG_DEBUG("got DataPointMessage");
	    CurrentTS = msg->timestamp;
	    if (CurrentTS > MaxTS)
		MaxTS = CurrentTS;
	    emit clockTick(msg->timestamp);
	    watcher::event::DataPointMessagePtr dp = boost::dynamic_pointer_cast<DataPointMessage>(msg);
	    // TODO:
	    // - add layer when DataPointMessage supports its
	    // - support data point messages for edges as well
	    emit dataPointReceived(QString::fromStdString(dp->dataName),
		    QString::fromStdString(dp->fromNodeID.to_string()),
		    layer, dp->timestamp, dp->dataPoints.front());
	} else if (msg->type == PLAYBACK_TIME_RANGE_MESSAGE_TYPE) {
	    LOG_DEBUG("got playback time range");
	    watcher::event::PlaybackTimeRangeMessagePtr m = boost::dynamic_pointer_cast<PlaybackTimeRangeMessage>(msg);
	    EpochTS = m->min_;
	    MaxTS = m->max_;
	    LOG_INFO("epoch TS = " << EpochTS << ", max TS = " << MaxTS);
	} else if (msg->type == SPEED_MESSAGE_TYPE) {
	    watcher::event::SpeedMessagePtr sm = boost::dynamic_pointer_cast<SpeedMessage>(msg);
	} else if (msg->type == SEEK_MESSAGE_TYPE) {
	    watcher::event::SeekMessagePtr sm = boost::dynamic_pointer_cast<SeekMessage>(msg);
	} else if (msg->type == LIST_STREAMS_MESSAGE_TYPE) {
	    watcher::event::ListStreamsMessagePtr lsm = boost::dynamic_pointer_cast<ListStreamsMessage>(msg);
	    for (size_t i = 0; i < lsm->evstreams.size(); ++i) {
		EventStreamInfoPtr ev ( lsm->evstreams[i] );
		streamsDialog->addStream(ev->uid, ev->description);
	    }
	} else {
        // GTL - should not happen except at start as we're filtering by message type.
        LOG_WARN("Recv'd unwanted message type");
	}
    }

    TRACE_EXIT();
}

void MainWindow::setup()
{
    TRACE_ENTER();

    setupUi(this);
    QObject::connect(this,
	SIGNAL(dataPointReceived(const QString& , const QString& , const QString& , qlonglong , double )),
       	this,
	SLOT(dataPointHandler(const QString& , const QString& , const QString& , qlonglong , double )));

    QObject::connect(actionChange_Stream, SIGNAL(triggered()), this, SLOT(listStreams()));

    LOG_INFO("spawning checkIO thread");
    checkIOThread = new boost::thread(&MainWindow::checkIO, this);

    TRACE_EXIT();
}

/** Slot for receiving seek requests
 * @param t the watcher::Timestamp value to seek to (milliseconds)
 */
void MainWindow::seekStream(qlonglong t)
{
    TRACE_ENTER();
    LOG_INFO("seeking to " << t);
    MsgStream->setStreamTimeStart(t);
    TRACE_EXIT();
}

/** Slot to open the change stream dialog. */
void MainWindow::listStreams()
{
    TRACE_ENTER();
    if (MsgStream->connected()) {
	if (!streamsDialog) {
	    streamsDialog = new WatcherStreamListDialog;
	    connect(streamsDialog, SIGNAL(streamChanged(unsigned long)), this, SLOT(selectStream(unsigned long)));
	    connect(streamsDialog->refreshButton, SIGNAL(clicked()), this, SLOT(listStreams()));
	    connect(streamsDialog, SIGNAL(reconnect()), this, SLOT(reconnect()));
	}
	streamsDialog->treeWidget->clear();
	streamsDialog->show();

	MsgStream->listStreams();
    } else {
	LOG_WARN("unable to list streams; not connected to watcherd");
    }
    TRACE_EXIT();
}

/** Slot to select a new stream. */
void MainWindow::selectStream(unsigned long uid)
{
    TRACE_ENTER();
    LOG_INFO("subscribing to new stream uid " << uid);
    if (MsgStream->connected()) {
	MsgStream->clearMessageCache();
	MsgStream->subscribeToStream(uid);
	closeAllGraphs();
    } else {
	LOG_WARN("unable to select stream; not connected to watcherd");
    }
    TRACE_EXIT();
}

/** Slot for receiving the reconnect stream signal from the change stream dialog. */
void MainWindow::reconnect()
{
    TRACE_ENTER();
    LOG_INFO("reconnecting to server upon user request");
    MsgStream->clearMessageCache();
    MsgStream->reconnect();
    closeAllGraphs();
    TRACE_EXIT();
}

void MainWindow::closeAllGraphs()
{
    TRACE_ENTER();
    for (SeriesMap::iterator it = seriesMap.begin(); it != seriesMap.end(); ++it)
	it->second->close();
    seriesMap.clear();
    menuSeries->clear();
    TRACE_EXIT();
}

} // ui
} // watcher

// vim:sw=4
<|endoftext|>


<commit_before>#include <osgGA/KeySwitchCameraManipulator>
#include <osg/Notify>

using namespace osgGA;

void KeySwitchCameraManipulator::addCameraManipulator(int key, std::string name, CameraManipulator *cm)
{
    if(!cm) return;

    _manips[key]=std::make_pair(name,osg::ref_ptr<CameraManipulator>(cm));
    if(!_current.valid()){
        _current=cm;
    }
}

bool KeySwitchCameraManipulator::handle(const GUIEventAdapter& ea,GUIActionAdapter& aa)
{
    if(ea.getEventType()==GUIEventAdapter::KEYBOARD){

        KeyManipMap::iterator it=_manips.find(ea.getKey());
        if(it != _manips.end()){
            osg::notify(osg::INFO)<<"Switching to manipulator: "<<(*it).second.first<<std::endl;
            cout<<"***Switching to manipulator: "<<(*it).second.first<<std::endl;
            it->second.second->setNode(_current->getNode());
            it->second.second->setCamera(_current->getCamera());
            it->second.second->init(ea,aa);
            _current = it->second.second;

            //_cameraManipChangeCallbacks.notify(this);

        }
    }

    return _current->handle(ea,aa);
}

// void KeySwitchCameraManipulator::addCallback(Callback* c)
// {
//     _cameraManipChangeCallbacks.addCallback(c);
// }
//
// void KeySwitchCameraManipulator::removeCallback(Callback* c)
// {
//     _cameraManipChangeCallbacks.removeCallback(c);
// }
<commit_msg>Small std::cout fix<commit_after>#include <osgGA/KeySwitchCameraManipulator>
#include <osg/Notify>

using namespace osgGA;

void KeySwitchCameraManipulator::addCameraManipulator(int key, std::string name, CameraManipulator *cm)
{
    if(!cm) return;

    _manips[key]=std::make_pair(name,osg::ref_ptr<CameraManipulator>(cm));
    if(!_current.valid()){
        _current=cm;
    }
}

bool KeySwitchCameraManipulator::handle(const GUIEventAdapter& ea,GUIActionAdapter& aa)
{
    if(ea.getEventType()==GUIEventAdapter::KEYBOARD){

        KeyManipMap::iterator it=_manips.find(ea.getKey());
        if(it != _manips.end()){
            osg::notify(osg::INFO)<<"Switching to manipulator: "<<(*it).second.first<<std::endl;
            std::cout<<"***Switching to manipulator: "<<(*it).second.first<<std::endl;
            it->second.second->setNode(_current->getNode());
            it->second.second->setCamera(_current->getCamera());
            it->second.second->init(ea,aa);
            _current = it->second.second;

            //_cameraManipChangeCallbacks.notify(this);

        }
    }

    return _current->handle(ea,aa);
}

// void KeySwitchCameraManipulator::addCallback(Callback* c)
// {
//     _cameraManipChangeCallbacks.addCallback(c);
// }
//
// void KeySwitchCameraManipulator::removeCallback(Callback* c)
// {
//     _cameraManipChangeCallbacks.removeCallback(c);
// }
<|endoftext|>


<commit_before>#include<cstdlib>
#include<cstring>
#include<fstream>
#include<vector>

#include"global.h"
#include"config.h"

std::string Config::upackage_root;
std::string Config::ubuild_path;
std::string Config::tarball_path;
std::string Config::source_path;
std::string Config::tracker_path;
std::string Config::cflags;
std::string Config::cxxflags;

void Config::init()
{
    upackage_root = "/var/upackage";

    /* +--------------------------------------------+
     * |Here we are checking to see if the user has |
     * |set the UPACKAGE_ROOT environment variable  |
     * |and if the value set is not ""              |
     * +--------------------------------------------+
     */
    if(getenv("UPACKAGE_ROOT") && strcmp(getenv("UPACKAGE_ROOT"), ""))
    {
        std::string env(getenv("UPACKAGE_ROOT"));

        /* +-----------------------------------------+
         * |Check to see if the user set environment |
         * |variable is correctly terminated by a '/'|
         * +-----------------------------------------+
         */
        if(env[env.size() - 1] == '/')
        {
            upackage_root = env;
        }
        else
        {
            /* +----------------------------------------------+
             * |The environment variable must not be correctly|
             * |terminated, lets fix that and move on.        |
             * +----------------------------------------------+
             */t
            upackage_root = env + "/";
        }
    }

    /* +----------------------------------------------------------+
     * |All of the directories in upackage are under upackage_root|
     * +----------------------------------------------------------+
     */
    /* +-------------------+
     * |These are defaults |
     * +-------------------+
     */
    ubuild_path = upackage_root + "ubuild/";
    tarball_path = upackage_root + "tarballs/";
    source_path = upackage_root + "sources/";
    tracker_path = upackage_root + "packages/";

    cflags = "";
    cxxflags = "";

    /* +--------------------------------------------------+
     * |Now we read in the global config file for upackage|
     * +--------------------------------------------------+
     */
    std::vector<std::string> file = read("/etc/upackage.conf");

    /* +----------------------------------------------------+
     * |If the file size is <= 0 then the file must be empty|
     * +----------------------------------------------------+
     */
    if(file.size() <= 0)
    {
        return;
    }

    /* If we are here, then the file size is > 0, now lets parse it */

    /* +------------------------------------------+
     * |An integer vector for storing line numbers|
     * +------------------------------------------+
     */
    std::vector<int> line;

    /* +------------------------------------------------------+
     * |An integer vector for storing the position of each ':'|
     * +------------------------------------------------------+
     */
    std::vector<int> pos;

    for(int i = 0; i < file.size(); i++)
    {
        /* +---------------------+
         * |Locate all of the ':'|
         * +---------------------+
         */
        if(file[i].find_first_of(":") + 1 > 0)
        {
            /* +----------------------------------------------+
             * |Store the position and line number of each ':'|
             * +----------------------------------------------+
             */
            pos.push_back(file[i].find_first_of(":"));
            line.push_back(i);
        }
    }

    /* +--------------------------------------------+
     * |A string for storing the data before the ':'|
     * +--------------------------------------------+
     */
    std::string key;

    /* +-------------------------------------------+
     * |A string for storing the data after the ':'|
     * +-------------------------------------------+
     */
    std::string value;

    line.push_back(file.size());

    for(int i = 0; i < pos.size(); i++)
    {
        /* +----------------------------------+
         * |The key is the data before the ':'|
         * +----------------------------------+
         */
        key = file[line[i]].substr(0, pos[i]);

        /* +-----------------------------------+
         * |The value is the data after the ':'|
         * +-----------------------------------+
         */
        value = file[line[i]].substr(pos[i] + 1);

        for(int j = line[i] + 1; j < line[i + 1]; j++)
        {
            if(file[j].length() > 0)
            {
                value = value + "\n" + file[j];
            }
        }
        if(!strcmp(key.c_str(), "CFLAGS")
                || !strcmp(key.c_str(), "cflags"))
        {
            cflags = value;
        }
        if(!strcmp(key.c_str(), "CXXFLAGS")
                || !strcmp(key.c_str(), "cxxflags"))
        {
            cxxflags = value;
        }
    }
}

<commit_msg>added do nothting for commented lines in config<commit_after>#include<cstdlib>
#include<cstring>
#include<fstream>
#include<vector>

#include"global.h"
#include"config.h"

std::string Config::upackage_root;
std::string Config::ubuild_path;
std::string Config::tarball_path;
std::string Config::source_path;
std::string Config::tracker_path;
std::string Config::cflags;
std::string Config::cxxflags;

void Config::init()
{
    upackage_root = "/var/upackage/";

    /* +--------------------------------------------+
     * |Here we are checking to see if the user has |
     * |set the UPACKAGE_ROOT environment variable  |
     * |and if the value set is not ""              |
     * +--------------------------------------------+
     */
    if(getenv("UPACKAGE_ROOT") && strcmp(getenv("UPACKAGE_ROOT"), ""))
    {
        std::string env(getenv("UPACKAGE_ROOT"));

        /* +-----------------------------------------+
         * |Check to see if the user set environment |
         * |variable is correctly terminated by a '/'|
         * +-----------------------------------------+
         */
        if(env[env.size() - 1] == '/')
        {
            upackage_root = env;
        }
        else
        {
            /* +----------------------------------------------+
             * |The environment variable must not be correctly|
             * |terminated, lets fix that and move on.        |
             * +----------------------------------------------+
             */
            upackage_root = env + "/";
        }
    }

    /* +----------------------------------------------------------+
     * |All of the directories in upackage are under upackage_root|
     * +----------------------------------------------------------+
     */
    /* +-------------------+
     * |These are defaults |
     * +-------------------+
     */
    ubuild_path = upackage_root + "ubuild/";
    tarball_path = upackage_root + "tarballs/";
    source_path = upackage_root + "sources/";
    tracker_path = upackage_root + "packages/";

    cflags = "";
    cxxflags = "";

    /* +--------------------------------------------------+
     * |Now we read in the global config file for upackage|
     * +--------------------------------------------------+
     */
    std::vector<std::string> file = read("upackage.conf");

    /* +----------------------------------------------------+
     * |If the file size is <= 0 then the file must be empty|
     * +----------------------------------------------------+
     */
    if(file.size() <= 0)
    {
        return;
    }

    /* If we are here, then the file size is > 0, now lets parse it */

    /* +------------------------------------------+
     * |An integer vector for storing line numbers|
     * +------------------------------------------+
     */
    std::vector<int> line;

    /* +------------------------------------------------------+
     * |An integer vector for storing the position of each ':'|
     * +------------------------------------------------------+
     */
    std::vector<int> pos;

    for(int i = 0; i < file.size(); i++)
    {
        /* +----------------------------+
         * |Do nothing with line[0] == # |
         * +----------------------------+
         */
        file[i] = file[i].substr(0, file[i].find_first_of("#"));

        /* +---------------------+
         * |Locate all of the ':'|
         * +---------------------+
         */
        if(file[i].find_first_of(":") + 1 > 0)
        {
            /* +----------------------------------------------+
             * |Store the position and line number of each ':'|
             * +----------------------------------------------+
             */
            pos.push_back(file[i].find_first_of(":"));
            line.push_back(i);
        }
    }

    /* +--------------------------------------------+
     * |A string for storing the data before the ':'|
     * +--------------------------------------------+
     */
    std::string key;

    /* +-------------------------------------------+
     * |A string for storing the data after the ':'|
     * +-------------------------------------------+
     */
    std::string value;

    line.push_back(file.size());

    for(int i = 0; i < pos.size(); i++)
    {
        /* +----------------------------------+
         * |The key is the data before the ':'|
         * +----------------------------------+
         */
        key = file[line[i]].substr(0, pos[i]);

        /* +-----------------------------------+
         * |The value is the data after the ':'|
         * +-----------------------------------+
         */
        value = file[line[i]].substr(pos[i] + 1);

        for(int j = line[i] + 1; j < line[i + 1]; j++)
        {
            if(file[j].length() > 0)
            {
                value = value + "\n" + file[j];
            }
        }
        if(!strcmp(key.c_str(), "CFLAGS")
                || !strcmp(key.c_str(), "cflags"))
        {
            cflags = value;
        }
        if(!strcmp(key.c_str(), "CXXFLAGS")
                || !strcmp(key.c_str(), "cxxflags"))
        {
            cxxflags = value;
        }
    }
}

<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>

#include "Scorpio/parse-option.hpp"

#include "board.hpp"
#include "config.hpp"

namespace roadagain
{

Config::Config() : color_(true), automatic_(false), player_(BLACK), level_(EASY)
{
}

Config& Config::instance()
{
    static Config instance_;
    return (instance_);
}

bool Config::init(int argc, char** argv)
{
    scorpio::OptionParser parser(argc, argv);

    parser.add_option(AUTOMATIC_STR);
    parser.add_option(COLOR_STR, true);
    parser.add_option(LEVEL_STR, true);
    parser.add_option(LOG_STR, true);
    parser.add_option(HELP_STR);
    parser.add_option(BLACK_STR);
    parser.add_option(WHITE_STR);

    std::vector<scorpio::Option> options = parser.parse();
    int size = options.size();
    for (int i = 0; i < size; i++){
        if (!options[i].available){
            continue;
        }
        if (options[i].name == HELP_STR){
            help();
        }
        else if (options[i].name == AUTOMATIC_STR){
            automatic_ = true;
        }
        else if (options[i].name == COLOR_STR){
            if (options[i].value == ALWAYS_STR || options[i].value == AUTO_STR){
                color_ = true;
            }
            else if (options[i].value == NEVER_STR){
                color_ = false;
            }
            else {
                std::puts("color option can be only 1 of 3 values: always, auto, never");
                return (false);
            }
        }
        else if (options[i].name == LEVEL_STR){
            if (options[i].value == EASY_STR){
                level_ = EASY;
            }
            else if (options[i].value == HARD_STR){
                level_ = HARD;
            }
            else {
                std::puts("level option cna be only 1 of 2 values: easy, hard");
                return (false);
            }
        }
        else if (options[i].name == LOG_STR){
            if (options[i].value.empty()){
                std::puts("log option needs filename");
                return (false);
            }
            else {
                log_file_ = options[i].value;
            }
        }
        else if (options[i].name == BLACK_STR){
            player_ = BLACK;
        }
        else if (options[i].name == WHITE_STR){
            player_ = WHITE;
        }
        else {
            std::printf("Unknown option: %s\n", options[i].name.c_str());
            return (false);
        }
    }

    return (true);
}

void Config::help()
{
    std::puts("Usage: reversi [options] [color]");
    std::puts("Reversi game for one person's play.");
    std::puts("Options:");
    std::puts("  --automatic    Play automatically.");
    std::puts("  --color[=WHEN] Colorize the output; ");
    std::puts("                 WHEN can be 'always' (default if omitted), 'auto', or 'never'.");
    std::puts("  --help         Print this help and exit successfully.");
    std::puts("");
    std::puts("Color must be 'black' or 'white'.");
    std::puts("Default color is black.");

    std::exit(0);
}

bool Config::color() const
{
    return (color_);
}

bool Config::automatic() const
{
    return (automatic_);
}

BoardState Config::player() const
{
    if (automatic_){
        return (EMPTY);
    }
    else {
        return (player_);
    }
}

Level Config::level() const
{
    return (level_);
}

const std::string Config::BLACK_STR("black");
const std::string Config::WHITE_STR("white");
const std::string Config::AUTOMATIC_STR("--automatic");
const std::string Config::COLOR_STR("--color");
const std::string Config::ALWAYS_STR("always");
const std::string Config::AUTO_STR("auto");
const std::string Config::NEVER_STR("never");
const std::string Config::LEVEL_STR("--level");
const std::string Config::EASY_STR("easy");
const std::string Config::HARD_STR("hard");
const std::string Config::LOG_STR("--log");
const std::string Config::HELP_STR("--help");

}
<commit_msg>Fixed typo in level error message<commit_after>#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>

#include "Scorpio/parse-option.hpp"

#include "board.hpp"
#include "config.hpp"

namespace roadagain
{

Config::Config() : color_(true), automatic_(false), player_(BLACK), level_(EASY)
{
}

Config& Config::instance()
{
    static Config instance_;
    return (instance_);
}

bool Config::init(int argc, char** argv)
{
    scorpio::OptionParser parser(argc, argv);

    parser.add_option(AUTOMATIC_STR);
    parser.add_option(COLOR_STR, true);
    parser.add_option(LEVEL_STR, true);
    parser.add_option(LOG_STR, true);
    parser.add_option(HELP_STR);
    parser.add_option(BLACK_STR);
    parser.add_option(WHITE_STR);

    std::vector<scorpio::Option> options = parser.parse();
    int size = options.size();
    for (int i = 0; i < size; i++){
        if (!options[i].available){
            continue;
        }
        if (options[i].name == HELP_STR){
            help();
        }
        else if (options[i].name == AUTOMATIC_STR){
            automatic_ = true;
        }
        else if (options[i].name == COLOR_STR){
            if (options[i].value == ALWAYS_STR || options[i].value == AUTO_STR){
                color_ = true;
            }
            else if (options[i].value == NEVER_STR){
                color_ = false;
            }
            else {
                std::puts("color option can be only 1 of 3 values: always, auto, never");
                return (false);
            }
        }
        else if (options[i].name == LEVEL_STR){
            if (options[i].value == EASY_STR){
                level_ = EASY;
            }
            else if (options[i].value == HARD_STR){
                level_ = HARD;
            }
            else {
                std::puts("level option can be only 1 of 2 values: easy, hard");
                return (false);
            }
        }
        else if (options[i].name == LOG_STR){
            if (options[i].value.empty()){
                std::puts("log option needs filename");
                return (false);
            }
            else {
                log_file_ = options[i].value;
            }
        }
        else if (options[i].name == BLACK_STR){
            player_ = BLACK;
        }
        else if (options[i].name == WHITE_STR){
            player_ = WHITE;
        }
        else {
            std::printf("Unknown option: %s\n", options[i].name.c_str());
            return (false);
        }
    }

    return (true);
}

void Config::help()
{
    std::puts("Usage: reversi [options] [color]");
    std::puts("Reversi game for one person's play.");
    std::puts("Options:");
    std::puts("  --automatic    Play automatically.");
    std::puts("  --color[=WHEN] Colorize the output; ");
    std::puts("                 WHEN can be 'always' (default if omitted), 'auto', or 'never'.");
    std::puts("  --help         Print this help and exit successfully.");
    std::puts("");
    std::puts("Color must be 'black' or 'white'.");
    std::puts("Default color is black.");

    std::exit(0);
}

bool Config::color() const
{
    return (color_);
}

bool Config::automatic() const
{
    return (automatic_);
}

BoardState Config::player() const
{
    if (automatic_){
        return (EMPTY);
    }
    else {
        return (player_);
    }
}

Level Config::level() const
{
    return (level_);
}

const std::string Config::BLACK_STR("black");
const std::string Config::WHITE_STR("white");
const std::string Config::AUTOMATIC_STR("--automatic");
const std::string Config::COLOR_STR("--color");
const std::string Config::ALWAYS_STR("always");
const std::string Config::AUTO_STR("auto");
const std::string Config::NEVER_STR("never");
const std::string Config::LEVEL_STR("--level");
const std::string Config::EASY_STR("easy");
const std::string Config::HARD_STR("hard");
const std::string Config::LOG_STR("--log");
const std::string Config::HELP_STR("--help");

}
<|endoftext|>


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

#include <avalanche/voterecord.h>

#include <test/util/setup_common.h>

#include <boost/test/unit_test.hpp>

using namespace avalanche;

NodeId nextNodeId(NodeId &nodeid) {
    nodeid++;
    if (nodeid >= 8) {
        nodeid = 0;
    }
    return nodeid;
}

BOOST_FIXTURE_TEST_SUITE(voterecord_tests, TestingSetup)

#define REGISTER_VOTE_AND_CHECK(vr, vote, state, finalized, stale, confidence) \
    vr.registerVote(nextNodeId(nodeid), vote);                                 \
    BOOST_CHECK_EQUAL(vr.isAccepted(), state);                                 \
    BOOST_CHECK_EQUAL(vr.hasFinalized(), finalized);                           \
    BOOST_CHECK_EQUAL(vr.isStale(), stale);                                    \
    BOOST_CHECK_EQUAL(vr.getConfidence(), confidence);

BOOST_AUTO_TEST_CASE(vote_record) {
    NodeId nodeid = -1;
    VoteRecord vraccepted(true);

    // Check initial state.
    BOOST_CHECK_EQUAL(vraccepted.isAccepted(), true);
    BOOST_CHECK_EQUAL(vraccepted.hasFinalized(), false);
    BOOST_CHECK_EQUAL(vraccepted.isStale(), false);
    BOOST_CHECK_EQUAL(vraccepted.getConfidence(), 0);

    VoteRecord vr(false);

    // Check initial state.
    BOOST_CHECK_EQUAL(vr.isAccepted(), false);
    BOOST_CHECK_EQUAL(vr.hasFinalized(), false);
    BOOST_CHECK_EQUAL(vr.isStale(), false);
    BOOST_CHECK_EQUAL(vr.getConfidence(), 0);

    // We need to register 6 positive votes before we start counting.
    for (int i = 0; i < 6; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 0, false, false, false, 0);
    }

    // Next vote will flip state, and confidence will increase as long as we
    // vote yes.
    REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, 0);

    // A single neutral vote do not change anything.
    REGISTER_VOTE_AND_CHECK(vr, -1, true, false, false, 1);
    for (int i = 2; i < 8; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, i);
    }

    // Two neutral votes will stall progress.
    REGISTER_VOTE_AND_CHECK(vr, -1, true, false, false, 7);
    REGISTER_VOTE_AND_CHECK(vr, -1, true, false, false, 7);
    for (int i = 2; i < 8; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, 7);
    }

    // Now confidence will increase as long as we vote yes.
    for (int i = 8; i < AVALANCHE_FINALIZATION_SCORE; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, i);
    }

    // The next vote will finalize the decision.
    REGISTER_VOTE_AND_CHECK(vr, 1, true, true, false,
                            AVALANCHE_FINALIZATION_SCORE);

    // Now that we have two no votes, confidence stop increasing.
    for (int i = 0; i < 5; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 1, true, true, false,
                                AVALANCHE_FINALIZATION_SCORE);
    }

    // Next vote will flip state, and confidence will increase as long as we
    // vote no.
    REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, 0);

    // A single neutral vote do not change anything.
    REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 1);
    for (int i = 2; i < 8; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, i);
    }

    // Two neutral votes will stall progress.
    REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 7);
    REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 7);
    for (int i = 2; i < 8; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, 7);
    }

    // Now confidence will increase as long as we vote no.
    for (int i = 8; i < AVALANCHE_FINALIZATION_SCORE; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, i);
    }

    // The next vote will finalize the decision.
    REGISTER_VOTE_AND_CHECK(vr, 0, false, true, false,
                            AVALANCHE_FINALIZATION_SCORE);

    // Check that inflight accounting work as expected.
    VoteRecord vrinflight(false);
    for (int i = 0; i < 2 * AVALANCHE_MAX_INFLIGHT_POLL; i++) {
        bool shouldPoll = vrinflight.shouldPoll();
        BOOST_CHECK_EQUAL(shouldPoll, i < AVALANCHE_MAX_INFLIGHT_POLL);
        BOOST_CHECK_EQUAL(vrinflight.registerPoll(), shouldPoll);
    }

    // Clear various number of inflight requests and check everything behaves as
    // expected.
    for (int i = 1; i < AVALANCHE_MAX_INFLIGHT_POLL; i++) {
        vrinflight.clearInflightRequest(i);
        BOOST_CHECK(vrinflight.shouldPoll());

        for (int j = 1; j < i; j++) {
            BOOST_CHECK(vrinflight.registerPoll());
            BOOST_CHECK(vrinflight.shouldPoll());
        }

        BOOST_CHECK(vrinflight.registerPoll());
        BOOST_CHECK(!vrinflight.shouldPoll());
    }
}

// Test some cases where confidence never advances
BOOST_AUTO_TEST_CASE(stale_vote_always_inconclusive) {
    NodeId nodeid = -1;
    // Setup a record that is inconclusive so far
    VoteRecord vr(false);

    for (uint32_t i = 0; i < AVALANCHE_VOTE_STALE_THRESHOLD / 8; i++) {
        // Vote randomly, but such that there's always enough neutral votes to
        // not gain confidence.
        for (auto j = 0; j < 6; j++) {
            REGISTER_VOTE_AND_CHECK(vr, InsecureRand32(), false, false, false,
                                    0);
        }
        REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 0);
        REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 0);
    }

    // Vote record becomes stale after too many rounds of inconclusive voting
    REGISTER_VOTE_AND_CHECK(vr, -1, false, false, true, 0);
}

// Test all cases where records reach a specific confidence level and then go
// stale.
BOOST_AUTO_TEST_CASE(stale_vote_at_all_confidence_levels) {
    NodeId nodeid = -1;

    for (uint32_t vote = 0; vote <= 1; vote++) {
        for (uint32_t confidence = 0; confidence < AVALANCHE_FINALIZATION_SCORE;
             confidence++) {
            VoteRecord vr(!vote);

            // Prepare to increase confidence with some votes
            for (auto i = 0; i < 5; i++) {
                REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, 0);
            }

            // Increase to target confidence
            for (uint32_t i = 0; i < confidence; i++) {
                REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, i);
            }

            uint32_t remainingVotes =
                AVALANCHE_VOTE_STALE_THRESHOLD - confidence - 5;

            // Special case where staying at confidence of 1 requires a
            // different vote between agreeing votes
            if (confidence == 1) {
                REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, false, 0);
                REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, 1);
                remainingVotes -= 2;
            }

            // Vote neutral until stale
            if (confidence >
                AVALANCHE_VOTE_STALE_THRESHOLD / AVALANCHE_VOTE_STALE_FACTOR) {
                remainingVotes =
                    confidence * AVALANCHE_VOTE_STALE_FACTOR - confidence - 5;
            }
            for (uint32_t i = 0; i < remainingVotes; i++) {
                REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, false,
                                        confidence);
            }
            REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, true, confidence);
        }
    }
}

// Test some cases where confidence may flip flop and then goes stale.
BOOST_AUTO_TEST_CASE(stale_vote_random_then_inconclusive) {
    NodeId nodeid = -1;
    VoteRecord vr(false);

    for (uint32_t i = 0; i < AVALANCHE_FINALIZATION_SCORE - 14; i++) {
        // Vote randomly. Confidence changes are ok.
        vr.registerVote(nextNodeId(nodeid), InsecureRand32());
        BOOST_CHECK_EQUAL(vr.hasFinalized(), false);
        BOOST_CHECK_EQUAL(vr.isStale(), false);
    }

    // Reset confidence, no matter what it is right now
    for (uint32_t i = 0; i < 7; i++) {
        vr.registerVote(nextNodeId(nodeid), 0);
    }
    for (uint32_t i = 0; i < 7; i++) {
        vr.registerVote(nextNodeId(nodeid), 1);
    }
    BOOST_CHECK_EQUAL(vr.hasFinalized(), false);
    BOOST_CHECK_EQUAL(vr.isStale(), false);

    // Remainder of votes are neutral
    for (uint32_t i = 0;
         i < AVALANCHE_VOTE_STALE_THRESHOLD - AVALANCHE_FINALIZATION_SCORE;
         i++) {
        REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 1);
    }

    // Vote record becomes stale after too many rounds of voting
    REGISTER_VOTE_AND_CHECK(vr, -1, false, false, true, 1);
}

// Test all cases where confidence flips as much as possible, ending at all
// possible confidence levels.
BOOST_AUTO_TEST_CASE(stale_vote_with_confidence_flips) {
    NodeId nodeid = -1;

    // Start testing with yes or no votes
    for (uint32_t voteInit = 0; voteInit <= 1; voteInit++) {
        // Test stalling at all confidence levels
        for (auto offset = 0; offset < AVALANCHE_FINALIZATION_SCORE; offset++) {
            uint32_t vote = voteInit;
            VoteRecord vr(!vote);
            uint32_t count = 0;

            // Offset with neutral votes
            for (auto i = 0; i < offset; i++) {
                REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, false, 0);
                count++;
            }

            // Prepare to increase confidence with some votes
            for (auto i = 0; i < 5; i++) {
                REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, 0);
                count++;
            }

            while (true) {
                // Increase confidence as fast as possible
                for (uint32_t i = 0; i < AVALANCHE_FINALIZATION_SCORE - 1;
                     i++) {
                    if (i <= AVALANCHE_VOTE_STALE_THRESHOLD /
                                 AVALANCHE_VOTE_STALE_FACTOR &&
                        count >= AVALANCHE_VOTE_STALE_THRESHOLD) {
                        REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, true,
                                                i);
                        goto finalsanitycheck;
                    }
                    if (i > AVALANCHE_VOTE_STALE_THRESHOLD /
                                AVALANCHE_VOTE_STALE_FACTOR &&
                        count >= i * AVALANCHE_VOTE_STALE_FACTOR) {
                        REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, true,
                                                i);
                        goto finalsanitycheck;
                    }

                    REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, i);
                    count++;
                }

                // Flip the vote
                if (vote++ >= 1) {
                    vote = 0;
                }

                // Reset confidence
                for (auto i = 0; i < 6; i++) {
                    if (count >= (AVALANCHE_FINALIZATION_SCORE - 1) *
                                     AVALANCHE_VOTE_STALE_FACTOR) {
                        REGISTER_VOTE_AND_CHECK(vr, vote, vote, false, true,
                                                AVALANCHE_FINALIZATION_SCORE);
                        goto finalsanitycheck;
                    }

                    REGISTER_VOTE_AND_CHECK(vr, vote, vote, false, false,
                                            AVALANCHE_FINALIZATION_SCORE - 1);
                    count++;
                }

                // If this fails, we are probably infinite looping for some
                // reason
                BOOST_CHECK(count <= AVALANCHE_FINALIZATION_SCORE *
                                         AVALANCHE_VOTE_STALE_FACTOR);
            }

        finalsanitycheck:
            BOOST_CHECK(vr.isStale());
        }
    }
}

BOOST_AUTO_TEST_CASE(duplicate_votes) {
    VoteRecord vr(true);
    NodeId nodeid = -1;

    // Register some votes, expecting confidence to increase
    for (auto i = 0; i < 7; i++) {
        BOOST_CHECK_EQUAL(vr.getConfidence(), 0);
        BOOST_CHECK(!vr.registerVote(nextNodeId(nodeid), 0));
    }
    BOOST_CHECK_EQUAL(vr.getConfidence(), 1);

    // Multiple duplicate votes do not advance confidence
    for (auto i = 0; i < 8; i++) {
        BOOST_CHECK(!vr.registerVote(nodeid, 0));
        BOOST_CHECK_EQUAL(vr.getConfidence(), 1);
    }

    // Register more votes with duplicates mixed in. Confidence should only
    // increase when duplicates are not used.
    auto expectedConfidence = 1;
    for (auto i = 0; i < 8; i++) {
        BOOST_CHECK(!vr.registerVote(nodeid, 0));
        BOOST_CHECK_EQUAL(vr.getConfidence(), expectedConfidence);
        for (auto j = i; j < 8; j++) {
            BOOST_CHECK(!vr.registerVote(nextNodeId(nodeid), 0));
            BOOST_CHECK_EQUAL(vr.getConfidence(), ++expectedConfidence);
        }
    }

    // Register enough votes to get just before finalization
    for (auto i = 0; i < 90; i++) {
        BOOST_CHECK(!vr.registerVote(nextNodeId(nodeid), 0));
        BOOST_CHECK_EQUAL(vr.getConfidence(), ++expectedConfidence);
    }

    // Sanity check that finalization occurs on the expected vote
    BOOST_CHECK(vr.registerVote(nextNodeId(nodeid), 0));
    BOOST_CHECK(vr.hasFinalized());
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>[avalanche] Set voterecord_tests node ID using a fixture<commit_after>// Copyright (c) 2018-2022 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <avalanche/voterecord.h>

#include <test/util/setup_common.h>

#include <boost/test/unit_test.hpp>

using namespace avalanche;

struct VoteRecordFixture {
    NodeId currentNodeId = -1;

    NodeId nextNodeId() {
        currentNodeId++;
        if (currentNodeId >= 8) {
            currentNodeId = 0;
        }
        return currentNodeId;
    }
};

BOOST_FIXTURE_TEST_SUITE(voterecord_tests, VoteRecordFixture)

#define REGISTER_VOTE_AND_CHECK(vr, vote, state, finalized, stale, confidence) \
    vr.registerVote(nextNodeId(), vote);                                       \
    BOOST_CHECK_EQUAL(vr.isAccepted(), state);                                 \
    BOOST_CHECK_EQUAL(vr.hasFinalized(), finalized);                           \
    BOOST_CHECK_EQUAL(vr.isStale(), stale);                                    \
    BOOST_CHECK_EQUAL(vr.getConfidence(), confidence);

BOOST_AUTO_TEST_CASE(vote_record) {
    VoteRecord vraccepted(true);

    // Check initial state.
    BOOST_CHECK_EQUAL(vraccepted.isAccepted(), true);
    BOOST_CHECK_EQUAL(vraccepted.hasFinalized(), false);
    BOOST_CHECK_EQUAL(vraccepted.isStale(), false);
    BOOST_CHECK_EQUAL(vraccepted.getConfidence(), 0);

    VoteRecord vr(false);

    // Check initial state.
    BOOST_CHECK_EQUAL(vr.isAccepted(), false);
    BOOST_CHECK_EQUAL(vr.hasFinalized(), false);
    BOOST_CHECK_EQUAL(vr.isStale(), false);
    BOOST_CHECK_EQUAL(vr.getConfidence(), 0);

    // We need to register 6 positive votes before we start counting.
    for (int i = 0; i < 6; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 0, false, false, false, 0);
    }

    // Next vote will flip state, and confidence will increase as long as we
    // vote yes.
    REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, 0);

    // A single neutral vote do not change anything.
    REGISTER_VOTE_AND_CHECK(vr, -1, true, false, false, 1);
    for (int i = 2; i < 8; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, i);
    }

    // Two neutral votes will stall progress.
    REGISTER_VOTE_AND_CHECK(vr, -1, true, false, false, 7);
    REGISTER_VOTE_AND_CHECK(vr, -1, true, false, false, 7);
    for (int i = 2; i < 8; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, 7);
    }

    // Now confidence will increase as long as we vote yes.
    for (int i = 8; i < AVALANCHE_FINALIZATION_SCORE; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, i);
    }

    // The next vote will finalize the decision.
    REGISTER_VOTE_AND_CHECK(vr, 1, true, true, false,
                            AVALANCHE_FINALIZATION_SCORE);

    // Now that we have two no votes, confidence stop increasing.
    for (int i = 0; i < 5; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 1, true, true, false,
                                AVALANCHE_FINALIZATION_SCORE);
    }

    // Next vote will flip state, and confidence will increase as long as we
    // vote no.
    REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, 0);

    // A single neutral vote do not change anything.
    REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 1);
    for (int i = 2; i < 8; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, i);
    }

    // Two neutral votes will stall progress.
    REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 7);
    REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 7);
    for (int i = 2; i < 8; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, 7);
    }

    // Now confidence will increase as long as we vote no.
    for (int i = 8; i < AVALANCHE_FINALIZATION_SCORE; i++) {
        REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, i);
    }

    // The next vote will finalize the decision.
    REGISTER_VOTE_AND_CHECK(vr, 0, false, true, false,
                            AVALANCHE_FINALIZATION_SCORE);

    // Check that inflight accounting work as expected.
    VoteRecord vrinflight(false);
    for (int i = 0; i < 2 * AVALANCHE_MAX_INFLIGHT_POLL; i++) {
        bool shouldPoll = vrinflight.shouldPoll();
        BOOST_CHECK_EQUAL(shouldPoll, i < AVALANCHE_MAX_INFLIGHT_POLL);
        BOOST_CHECK_EQUAL(vrinflight.registerPoll(), shouldPoll);
    }

    // Clear various number of inflight requests and check everything behaves as
    // expected.
    for (int i = 1; i < AVALANCHE_MAX_INFLIGHT_POLL; i++) {
        vrinflight.clearInflightRequest(i);
        BOOST_CHECK(vrinflight.shouldPoll());

        for (int j = 1; j < i; j++) {
            BOOST_CHECK(vrinflight.registerPoll());
            BOOST_CHECK(vrinflight.shouldPoll());
        }

        BOOST_CHECK(vrinflight.registerPoll());
        BOOST_CHECK(!vrinflight.shouldPoll());
    }
}

// Test some cases where confidence never advances
BOOST_AUTO_TEST_CASE(stale_vote_always_inconclusive) {
    // Setup a record that is inconclusive so far
    VoteRecord vr(false);

    for (uint32_t i = 0; i < AVALANCHE_VOTE_STALE_THRESHOLD / 8; i++) {
        // Vote randomly, but such that there's always enough neutral votes to
        // not gain confidence.
        for (auto j = 0; j < 6; j++) {
            REGISTER_VOTE_AND_CHECK(vr, InsecureRand32(), false, false, false,
                                    0);
        }
        REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 0);
        REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 0);
    }

    // Vote record becomes stale after too many rounds of inconclusive voting
    REGISTER_VOTE_AND_CHECK(vr, -1, false, false, true, 0);
}

// Test all cases where records reach a specific confidence level and then go
// stale.
BOOST_AUTO_TEST_CASE(stale_vote_at_all_confidence_levels) {
    for (uint32_t vote = 0; vote <= 1; vote++) {
        for (uint32_t confidence = 0; confidence < AVALANCHE_FINALIZATION_SCORE;
             confidence++) {
            VoteRecord vr(!vote);

            // Prepare to increase confidence with some votes
            for (auto i = 0; i < 5; i++) {
                REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, 0);
            }

            // Increase to target confidence
            for (uint32_t i = 0; i < confidence; i++) {
                REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, i);
            }

            uint32_t remainingVotes =
                AVALANCHE_VOTE_STALE_THRESHOLD - confidence - 5;

            // Special case where staying at confidence of 1 requires a
            // different vote between agreeing votes
            if (confidence == 1) {
                REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, false, 0);
                REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, 1);
                remainingVotes -= 2;
            }

            // Vote neutral until stale
            if (confidence >
                AVALANCHE_VOTE_STALE_THRESHOLD / AVALANCHE_VOTE_STALE_FACTOR) {
                remainingVotes =
                    confidence * AVALANCHE_VOTE_STALE_FACTOR - confidence - 5;
            }
            for (uint32_t i = 0; i < remainingVotes; i++) {
                REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, false,
                                        confidence);
            }
            REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, true, confidence);
        }
    }
}

// Test some cases where confidence may flip flop and then goes stale.
BOOST_AUTO_TEST_CASE(stale_vote_random_then_inconclusive) {
    VoteRecord vr(false);

    for (uint32_t i = 0; i < AVALANCHE_FINALIZATION_SCORE - 14; i++) {
        // Vote randomly. Confidence changes are ok.
        vr.registerVote(nextNodeId(), InsecureRand32());
        BOOST_CHECK_EQUAL(vr.hasFinalized(), false);
        BOOST_CHECK_EQUAL(vr.isStale(), false);
    }

    // Reset confidence, no matter what it is right now
    for (uint32_t i = 0; i < 7; i++) {
        vr.registerVote(nextNodeId(), 0);
    }
    for (uint32_t i = 0; i < 7; i++) {
        vr.registerVote(nextNodeId(), 1);
    }
    BOOST_CHECK_EQUAL(vr.hasFinalized(), false);
    BOOST_CHECK_EQUAL(vr.isStale(), false);

    // Remainder of votes are neutral
    for (uint32_t i = 0;
         i < AVALANCHE_VOTE_STALE_THRESHOLD - AVALANCHE_FINALIZATION_SCORE;
         i++) {
        REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 1);
    }

    // Vote record becomes stale after too many rounds of voting
    REGISTER_VOTE_AND_CHECK(vr, -1, false, false, true, 1);
}

// Test all cases where confidence flips as much as possible, ending at all
// possible confidence levels.
BOOST_AUTO_TEST_CASE(stale_vote_with_confidence_flips) {
    // Start testing with yes or no votes
    for (uint32_t voteInit = 0; voteInit <= 1; voteInit++) {
        // Test stalling at all confidence levels
        for (auto offset = 0; offset < AVALANCHE_FINALIZATION_SCORE; offset++) {
            uint32_t vote = voteInit;
            VoteRecord vr(!vote);
            uint32_t count = 0;

            // Offset with neutral votes
            for (auto i = 0; i < offset; i++) {
                REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, false, 0);
                count++;
            }

            // Prepare to increase confidence with some votes
            for (auto i = 0; i < 5; i++) {
                REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, 0);
                count++;
            }

            while (true) {
                // Increase confidence as fast as possible
                for (uint32_t i = 0; i < AVALANCHE_FINALIZATION_SCORE - 1;
                     i++) {
                    if (i <= AVALANCHE_VOTE_STALE_THRESHOLD /
                                 AVALANCHE_VOTE_STALE_FACTOR &&
                        count >= AVALANCHE_VOTE_STALE_THRESHOLD) {
                        REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, true,
                                                i);
                        goto finalsanitycheck;
                    }
                    if (i > AVALANCHE_VOTE_STALE_THRESHOLD /
                                AVALANCHE_VOTE_STALE_FACTOR &&
                        count >= i * AVALANCHE_VOTE_STALE_FACTOR) {
                        REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, true,
                                                i);
                        goto finalsanitycheck;
                    }

                    REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, i);
                    count++;
                }

                // Flip the vote
                if (vote++ >= 1) {
                    vote = 0;
                }

                // Reset confidence
                for (auto i = 0; i < 6; i++) {
                    if (count >= (AVALANCHE_FINALIZATION_SCORE - 1) *
                                     AVALANCHE_VOTE_STALE_FACTOR) {
                        REGISTER_VOTE_AND_CHECK(vr, vote, vote, false, true,
                                                AVALANCHE_FINALIZATION_SCORE);
                        goto finalsanitycheck;
                    }

                    REGISTER_VOTE_AND_CHECK(vr, vote, vote, false, false,
                                            AVALANCHE_FINALIZATION_SCORE - 1);
                    count++;
                }

                // If this fails, we are probably infinite looping for some
                // reason
                BOOST_CHECK(count <= AVALANCHE_FINALIZATION_SCORE *
                                         AVALANCHE_VOTE_STALE_FACTOR);
            }

        finalsanitycheck:
            BOOST_CHECK(vr.isStale());
        }
    }
}

BOOST_AUTO_TEST_CASE(duplicate_votes) {
    VoteRecord vr(true);

    // Register some votes, expecting confidence to increase
    for (auto i = 0; i < 7; i++) {
        BOOST_CHECK_EQUAL(vr.getConfidence(), 0);
        BOOST_CHECK(!vr.registerVote(nextNodeId(), 0));
    }
    BOOST_CHECK_EQUAL(vr.getConfidence(), 1);

    // Multiple duplicate votes do not advance confidence
    for (auto i = 0; i < 8; i++) {
        BOOST_CHECK(!vr.registerVote(currentNodeId, 0));
        BOOST_CHECK_EQUAL(vr.getConfidence(), 1);
    }

    // Register more votes with duplicates mixed in. Confidence should only
    // increase when duplicates are not used.
    auto expectedConfidence = 1;
    for (auto i = 0; i < 8; i++) {
        BOOST_CHECK(!vr.registerVote(currentNodeId, 0));
        BOOST_CHECK_EQUAL(vr.getConfidence(), expectedConfidence);
        for (auto j = i; j < 8; j++) {
            BOOST_CHECK(!vr.registerVote(nextNodeId(), 0));
            BOOST_CHECK_EQUAL(vr.getConfidence(), ++expectedConfidence);
        }
    }

    // Register enough votes to get just before finalization
    for (auto i = 0; i < 90; i++) {
        BOOST_CHECK(!vr.registerVote(nextNodeId(), 0));
        BOOST_CHECK_EQUAL(vr.getConfidence(), ++expectedConfidence);
    }

    // Sanity check that finalization occurs on the expected vote
    BOOST_CHECK(vr.registerVote(nextNodeId(), 0));
    BOOST_CHECK(vr.hasFinalized());
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/**********************************************************************************
 * Copyright (C) 2011 by Hugo Stefan Kaus Puhlmann                                *
 * Permission is hereby granted, free of charge, to any person obtaining a copy   *
 * of this software and associated documentation files (the "Software"), to deal  *
 * in the Software without restriction, including without limitation the rights   *
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell      *
 * copies of the Software, and to permit persons to whom the Software is          *
 * furnished to do so, subject to the following conditions:                       *
 *                                                                                *
 * The above copyright notice and this permission notice shall be included in     *
 * all copies or substantial portions of the Software.                            *
 *                                                                                *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR     *
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,       *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE    *
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER         *
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  *
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN      *
 * THE SOFTWARE.                                                                  *
 *********************************************************************************/

#include <GL/glfw.h>
#include "GameWorld.hpp"
#include "PlayerShip.hpp"
#include "../math/vector.hpp"
#include <ctime>
#include <cstdlib>
#include <GL/glu.h>

int main()
{
   glfwInit();
   glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
   glfwOpenWindow(800, 800, 8, 8, 8, 8, 24, 8, GLFW_WINDOW);

   using hstefan::game::GameWorld;
   using hstefan::game::PlayerShip;
   using namespace hstefan::math;

   GameWorld* world = GameWorld::getInstance();
   PlayerShip* ship = new PlayerShip(makeVec(400,400,1), 800, 800);
   world->addObject(ship);
   bool running = true;

   double last_render = 0;
   double last_update = 0;

   double frame_interval = 1.f/60.f;
   double update_interval = 1.f/90.f;

   double cur_time = 0;
   glClearColor(0.f, 0.f, 0.f, 1.f);
   glMatrixMode(GL_PROJECTION);
   //glPushMatrix();
   glLoadIdentity();
   //float proj[16] = {2/800, 0, 0, 0, 0, 2/800, 0, 0, 0, 0, 1, 0, -400, -400, 0, 1};
   //glLoadMatrixf(proj);
   gluOrtho2D(0, 800, 0, 800);
   while(running)
   {
      cur_time = glfwGetTime();

      if(glfwGetKey(GLFW_KEY_ESC) == GLFW_PRESS)
         break;
      if(cur_time - last_render > frame_interval)
      {
         last_render = glfwGetTime();
         glClear(GL_COLOR_BUFFER_BIT);
         world->render();
         glfwSwapBuffers();
      }

      if(cur_time - last_update > update_interval)
      {
         world->update();
         last_update = glfwGetTime();
      }
      glfwSleep(update_interval - (cur_time + glfwGetTime()));
      running = glfwGetWindowParam(GLFW_OPENED) != 0;
   }

   glfwTerminate();
}
<commit_msg>last version<commit_after>/**********************************************************************************
 * Copyright (C) 2011 by Hugo Stefan Kaus Puhlmann                                *
 * Permission is hereby granted, free of charge, to any person obtaining a copy   *
 * of this software and associated documentation files (the "Software"), to deal  *
 * in the Software without restriction, including without limitation the rights   *
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell      *
 * copies of the Software, and to permit persons to whom the Software is          *
 * furnished to do so, subject to the following conditions:                       *
 *                                                                                *
 * The above copyright notice and this permission notice shall be included in     *
 * all copies or substantial portions of the Software.                            *
 *                                                                                *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR     *
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,       *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE    *
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER         *
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  *
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN      *
 * THE SOFTWARE.                                                                  *
 *********************************************************************************/

#include <GL/glfw.h>
#include "GameWorld.hpp"
#include "PlayerShip.hpp"
#include "../math/vector.hpp"
#include <ctime>
#include <cstdlib>
//#include <GL/glu.h>

int main()
{
   glfwInit();
   glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
   glfwOpenWindow(800, 800, 8, 8, 8, 8, 24, 8, GLFW_WINDOW);

   using hstefan::game::GameWorld;
   using hstefan::game::PlayerShip;
   using namespace hstefan::math;

   GameWorld* world = GameWorld::getInstance();
   PlayerShip* ship = new PlayerShip(makeVec(400,400,1), 800, 800);
   world->addObject(ship);
   bool running = true;

   double last_render = 0;
   double last_update = 0;

   double frame_interval = 1.f/60.f;
   double update_interval = 1.f/90.f;

   double cur_time = 0;
   glClearColor(0.f, 0.f, 0.f, 1.f);
   glMatrixMode(GL_PROJECTION);
   glPushMatrix();
   glLoadIdentity();
   float proj[16] = {2/800, 0, 0, 0, 0, 2/800, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1};
   glLoadMatrixf(proj);
   //gluOrtho2D(0, 800, 0, 800);
   while(running)
   {
      cur_time = glfwGetTime();

      if(glfwGetKey(GLFW_KEY_ESC) == GLFW_PRESS)
         break;
      if(cur_time - last_render > frame_interval)
      {
         last_render = glfwGetTime();
         glClear(GL_COLOR_BUFFER_BIT);
         world->render();
         glfwSwapBuffers();
      }

      if(cur_time - last_update > update_interval)
      {
         world->update();
         last_update = glfwGetTime();
      }
      glfwSleep(update_interval - (cur_time + glfwGetTime()));
      running = glfwGetWindowParam(GLFW_OPENED) != 0;
   }

   glfwTerminate();
}
<|endoftext|>


<commit_before>/**
*  Copyright (C) 2015 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "repo_settings_credentials.h"

//------------------------------------------------------------------------------
using namespace repo::settings;
//------------------------------------------------------------------------------

QString CREDENTIALS = "token";
QString CREDENTIALS_ARRAY = "tokens";

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

RepoSettingsCredentials::RepoSettingsCredentials() : QSettings()
{
    qRegisterMetaType<repo::RepoCredentials>();
}

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

void RepoSettingsCredentials::writeCredentials(QList<repo::RepoCredentials> &credentials)
{
    beginWriteArray(CREDENTIALS_ARRAY);
    for (int i = 0; i < credentials.size(); ++i)
    {
        setArrayIndex(i);
        QVariant var;
        var.setValue(credentials.at(i));
        setValue(CREDENTIALS, var);
    }
    endArray();
}

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

QList<repo::RepoCredentials> RepoSettingsCredentials::readCredentials()
{
    int size = beginReadArray(CREDENTIALS_ARRAY);
    QList<repo::RepoCredentials> credentialsList;
    for (int i = 0; i < size; ++i) {
        setArrayIndex(i);
        repo::RepoCredentials credentials = value(CREDENTIALS).value<repo::RepoCredentials>();
        credentialsList.append(credentials);
        emit credentialsAt(i, credentials);
    }
    endArray();
    return credentialsList;
}
<commit_msg>#51 Fixed compilation errors.<commit_after>/**
*  Copyright (C) 2015 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "repo_settings_credentials.h"

//------------------------------------------------------------------------------
using namespace repo::settings;
//------------------------------------------------------------------------------

const QString RepoSettingsCredentials::CREDENTIALS = "credentials";
const QString RepoSettingsCredentials::CREDENTIALS_ARRAY = "credentials_array";

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

RepoSettingsCredentials::RepoSettingsCredentials() : QSettings()
{
    qRegisterMetaType<repo::RepoCredentials>();
}

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

void RepoSettingsCredentials::writeCredentials(QList<repo::RepoCredentials> &credentials)
{
    beginWriteArray(CREDENTIALS_ARRAY);
    for (int i = 0; i < credentials.size(); ++i)
    {
        setArrayIndex(i);
        QVariant var;
        var.setValue(credentials.at(i));
        setValue(CREDENTIALS, var);
    }
    endArray();
}

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

QList<repo::RepoCredentials> RepoSettingsCredentials::readCredentials()
{
    int size = beginReadArray(CREDENTIALS_ARRAY);
    QList<repo::RepoCredentials> credentialsList;
    for (int i = 0; i < size; ++i) {
        setArrayIndex(i);
        repo::RepoCredentials credentials = value(CREDENTIALS).value<repo::RepoCredentials>();
        credentialsList.append(credentials);
//        emit credentialsAt(i, credentials);
    }
    endArray();
    return credentialsList;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include "controller.h"
#include "fpshandler.h"

#include <stdlib.h>

Controller::Controller()
{
    running = true;
    window = new Window();
    model = new Model;
}

Controller::~Controller()
{
    delete window;
    delete model;
    delete current_view;
	if (player != nullptr)
	{
		delete player;
		player=nullptr;
	}
}

void Controller::run()
{
    Controller &controller = getController();
    controller.setView("mainmenu");
    FpsHandler clock;
    while (controller.running)
    {
        clock.start();
        controller.window->eventLoop();
        controller.window->renderFrame();
        clock.delay();
    }
}

void Controller::event(std::string event_name)
{
    Controller &controller = getController();
    if (controller.current_view_name == "mainmenu")
    {
        controller.mainMenuEvent(event_name);
    }
    else if (controller.current_view_name == "new_game")
    {
        controller.newGameEvent(event_name);
    }
    else if (controller.current_view_name == "settings")
    {
        controller.settingsEvent(event_name);
    }
    else
    {
        std::cout << "error, view \"" << controller.current_view_name << "\" is invalid\n";
    }
}

void Controller::mainMenuEvent(std::string event_name)
{
    if (event_name == "NEW_GAME")
    {
        startNewGame();
        player = new Character();
		loadStats(player);
    }
    else if (event_name == "SETTINGS")
    {
        setView("settings");
    }
    else if (event_name == "EXIT_GAME")
    {
        setDone();
    }
    else
    {
        std::cout << "error, unexpected command:" << std::setw(10) << event_name << std::endl;
    }
}

void Controller::newGameEvent(std::string event_name)
{
	if (event_name == "BACK")
	{
        delete player;
		player = nullptr;
		setView("mainmenu");
	}
	else if (event_name == "DEC_STRENGTH")
	{
        player->decStrength();
		current_view->setText("{points_value}", asText(player->getPoints()));
		current_view->setText("{strength_value}", asText(player->getStrength()));
	}
	else if (event_name == "INC_STRENGTH")
	{
        player->incStrength();
		current_view->setText("{points_value}", asText(player->getPoints()));
		current_view->setText("{strength_value}", asText(player->getStrength()));
	}
    else if (event_name == "DEC_DEXTERITY")
    {
        player->decDexterity();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{dexterity_value}", asText(player->getDexterity()));
    }
    else if (event_name == "INC_DEXTERITY")
    {
        player->incDexterity();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{dexterity_value}", asText(player->getDexterity()));
    }
    else if (event_name == "DEC_AGILITY")
    {
        player->decAgility();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{agility_value}", asText(player->getAgility()));
    }
    else if (event_name == "INC_AGILITY")
    {
        player->incAgility();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{agility_value}", asText(player->getAgility()));
    }
    else if (event_name == "DEC_WISDOM")
    {
        player->decWisdom();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{wisdom_value}", asText(player->getWisdom()));
    }
    else if (event_name == "INC_WISDOM")
    {
        player->incWisdom();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{wisdom_value}", asText(player->getWisdom()));
    }
    else if (event_name == "DEC_INTELIGENCE")
    {
        player->decInteligence();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{inteligence_value}", asText(player->getInteligence()));
    }
    else if (event_name == "INC_INTELIGENCE")
    {
        player->incInteligence();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{inteligence_value}", asText(player->getInteligence()));
    }
    else if (event_name == "DEC_CHARISMA")
    {
        player->decCharisma();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{charisma_value}", asText(player->getCharisma()));
    }
    else if (event_name == "INC_CHARISMA")
    {
        player->incCharisma();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{charisma_value}", asText(player->getCharisma()));
    }
	else if (event_name == "START_GAME")
	{
		setView("mainmenu");
		addView("player_card", true);
	}
	else
    {
        std::cout << "error, unexpected command:" << std::setw(10) << event_name << std::endl;
    }
}

void Controller::settingsEvent(std::string event_name)
{
    if (event_name == "BACK")
    {
        setView("mainmenu");
    }
    else if (event_name.substr(0, 9) == "LANGUAGE_")
    {
        std::cout << "new language: " << event_name.substr(9) << std::endl;
        model->setLanguage(event_name.substr(9));
        setView("settings");
    }
    else
    {
        std::cout << "cut: " << event_name.substr(0, 8) << std::endl;
        std::cout << "error, unexpected command:" << std::setw(10) << event_name << std::endl;
    }
}

void Controller::startNewGame()
{
    std::cout << "new game starting\n";
    setView("new_game");
}

void Controller::setView(std::string view)
{
    std::cout << "changed view to: " << std::setw(10) << view << std::endl;
    current_view_name = view;
    current_view = model->getXml("view_" + view);
    window->setView(current_view);
}

void Controller::addView(std::string view, bool deactivation)
{
	View* v;
	if (deactivation)
	{
		v = model->getXml("view_blockade");
		current_view->extendView(v);
	}
	v = model->getXml("view_" + view);
	current_view->extendView(v);
	window->updateClickmap();
}

void Controller::delView()
{
	current_view->removeLastView();
	window->updateClickmap();
}

void Controller::setDone()
{
    getController().running = false;
}

Controller &Controller::getController()
{
    static Controller controller;
    return controller;
}

std::string Controller::asText(int number)
{
    char buff[3];
    snprintf(buff, sizeof(buff), "%d", number);
    return buff;
}

void Controller::loadStats(Character *character)
{
	current_view->setText("{points_value}", asText(character->getPoints()));
    current_view->setText("{strength_value}", asText(character->getStrength()));
    current_view->setText("{dexterity_value}", asText(character->getDexterity()));
    current_view->setText("{agility_value}", asText(character->getAgility()));
    current_view->setText("{wisdom_value}", asText(character->getWisdom()));
    current_view->setText("{inteligence_value}", asText(character->getInteligence()));
    current_view->setText("{charisma_value}", asText(character->getCharisma()));
}

<commit_msg>bugfix<commit_after>#include <iostream>
#include <iomanip>
#include "controller.h"
#include "fpshandler.h"

#include <stdlib.h>

Controller::Controller()
{
    running = true;
    window = new Window();
    model = new Model;
}

Controller::~Controller()
{
    delete window;
    delete model;
    delete current_view;
	if (player != nullptr)
	{
		delete player;
		player=nullptr;
	}
}

void Controller::run()
{
    Controller &controller = getController();
    controller.setView("mainmenu");
    FpsHandler clock;
    while (controller.running)
    {
        clock.start();
        controller.window->eventLoop();
        controller.window->renderFrame();
        clock.delay();
    }
}

void Controller::event(std::string event_name)
{
    Controller &controller = getController();
    if (controller.current_view_name == "mainmenu")
    {
        controller.mainMenuEvent(event_name);
    }
    else if (controller.current_view_name == "new_game")
    {
        controller.newGameEvent(event_name);
    }
    else if (controller.current_view_name == "settings")
    {
        controller.settingsEvent(event_name);
    }
    else
    {
        std::cout << "error, view \"" << controller.current_view_name << "\" is invalid\n";
    }
}

void Controller::mainMenuEvent(std::string event_name)
{
    if (event_name == "NEW_GAME")
    {
        startNewGame();
        player = new Character();
		loadStats(player);
    }
    else if (event_name == "SETTINGS")
    {
        setView("settings");
    }
    else if (event_name == "EXIT_GAME")
    {
        setDone();
    }
    else
    {
        std::cout << "error, unexpected command:" << std::setw(10) << event_name << std::endl;
    }
}

void Controller::newGameEvent(std::string event_name)
{
	if (event_name == "BACK")
	{
        delete player;
		player = nullptr;
		setView("mainmenu");
	}
	else if (event_name == "DEC_STRENGTH")
	{
        player->decStrength();
		current_view->setText("{points_value}", asText(player->getPoints()));
		current_view->setText("{strength_value}", asText(player->getStrength()));
	}
	else if (event_name == "INC_STRENGTH")
	{
        player->incStrength();
		current_view->setText("{points_value}", asText(player->getPoints()));
		current_view->setText("{strength_value}", asText(player->getStrength()));
	}
    else if (event_name == "DEC_DEXTERITY")
    {
        player->decDexterity();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{dexterity_value}", asText(player->getDexterity()));
    }
    else if (event_name == "INC_DEXTERITY")
    {
        player->incDexterity();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{dexterity_value}", asText(player->getDexterity()));
    }
    else if (event_name == "DEC_AGILITY")
    {
        player->decAgility();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{agility_value}", asText(player->getAgility()));
    }
    else if (event_name == "INC_AGILITY")
    {
        player->incAgility();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{agility_value}", asText(player->getAgility()));
    }
    else if (event_name == "DEC_WISDOM")
    {
        player->decWisdom();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{wisdom_value}", asText(player->getWisdom()));
    }
    else if (event_name == "INC_WISDOM")
    {
        player->incWisdom();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{wisdom_value}", asText(player->getWisdom()));
    }
    else if (event_name == "DEC_INTELIGENCE")
    {
        player->decInteligence();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{inteligence_value}", asText(player->getInteligence()));
    }
    else if (event_name == "INC_INTELIGENCE")
    {
        player->incInteligence();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{inteligence_value}", asText(player->getInteligence()));
    }
    else if (event_name == "DEC_CHARISMA")
    {
        player->decCharisma();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{charisma_value}", asText(player->getCharisma()));
    }
    else if (event_name == "INC_CHARISMA")
    {
        player->incCharisma();
		current_view->setText("{points_value}", asText(player->getPoints()));
        current_view->setText("{charisma_value}", asText(player->getCharisma()));
    }
	else if (event_name == "START_GAME")
	{
		setView("mainmenu");
		addView("player_card", false);
	}
	else
    {
        std::cout << "error, unexpected command:" << std::setw(10) << event_name << std::endl;
    }
}

void Controller::settingsEvent(std::string event_name)
{
    if (event_name == "BACK")
    {
        setView("mainmenu");
    }
    else if (event_name.substr(0, 9) == "LANGUAGE_")
    {
        std::cout << "new language: " << event_name.substr(9) << std::endl;
        model->setLanguage(event_name.substr(9));
        setView("settings");
    }
    else
    {
        std::cout << "cut: " << event_name.substr(0, 8) << std::endl;
        std::cout << "error, unexpected command:" << std::setw(10) << event_name << std::endl;
    }
}

void Controller::startNewGame()
{
    std::cout << "new game starting\n";
    setView("new_game");
}

void Controller::setView(std::string view)
{
    std::cout << "changed view to: " << std::setw(10) << view << std::endl;
    current_view_name = view;
    current_view = model->getXml("view_" + view);
    window->setView(current_view);
}

void Controller::addView(std::string view, bool deactivation)
{
	View* v;
	if (deactivation)
	{
		v = model->getXml("view_blockade");
		current_view->extendView(v);
	}
	v = model->getXml("view_" + view);
	current_view->extendView(v);
	window->updateClickmap();
}

void Controller::delView()
{
	current_view->removeLastView();
	window->updateClickmap();
}

void Controller::setDone()
{
    getController().running = false;
}

Controller &Controller::getController()
{
    static Controller controller;
    return controller;
}

std::string Controller::asText(int number)
{
    char buff[3];
    snprintf(buff, sizeof(buff), "%d", number);
    return buff;
}

void Controller::loadStats(Character *character)
{
	current_view->setText("{points_value}", asText(character->getPoints()));
    current_view->setText("{strength_value}", asText(character->getStrength()));
    current_view->setText("{dexterity_value}", asText(character->getDexterity()));
    current_view->setText("{agility_value}", asText(character->getAgility()));
    current_view->setText("{wisdom_value}", asText(character->getWisdom()));
    current_view->setText("{inteligence_value}", asText(character->getInteligence()));
    current_view->setText("{charisma_value}", asText(character->getCharisma()));
}

<|endoftext|>


<commit_before><commit_msg>Fix of the initial locale set.<commit_after><|endoftext|>


<commit_before>/*
farrtl.cpp

८। 㭪権 ࠡ  : new/delete/malloc/realloc/free
*/

/* Revision: 1.02 05.07.2000 $ */

/*
Modify:
  03.07.2000 IS
    ! 祭 ᥣ 䠩  ஥
  04.07.2000 SVS
    ! 뤥  ⢥ ᠬ筮 !
  05.07.2000 IS
    !   ஢ப,   ᠫ ,    ࠢ
      , ᫨ ८। new/delete :-(((
*/

#ifdef __cplusplus
extern "C" {
#endif
typedef unsigned size_t;

void *malloc(size_t size);
void *realloc(void *block, size_t size);
void free(void *block);

#ifdef __cplusplus
}
#endif

#include "headers.hpp"
#pragma hdrstop

static HANDLE FARHeapForNew=NULL;

void *malloc(size_t size)
{
  void *p;
  if(!FARHeapForNew) FARHeapForNew=GetProcessHeap();
  if(FARHeapForNew) p=HeapAlloc(FARHeapForNew,HEAP_ZERO_MEMORY,size);
//  if(p==NULL)MessageBox(NULL,"NULL","p",0);
  return p;
}

void *realloc(void *block, size_t size)
{
  void *p;
  if(!FARHeapForNew) FARHeapForNew=GetProcessHeap();
  if(FARHeapForNew)
   {
    if (block) p=HeapReAlloc(FARHeapForNew,HEAP_ZERO_MEMORY,block,size);
    else p=HeapAlloc(FARHeapForNew,HEAP_ZERO_MEMORY, size);
   }
//  if(p==NULL)MessageBox(NULL,"NULL","p",0);
  return p;
}

void free(void *block)
{
  if(!FARHeapForNew) FARHeapForNew=GetProcessHeap();
  if(FARHeapForNew) HeapFree(FARHeapForNew,0,block);
}

#if 0 //  ⮣ ࠡ⠥,      稭
void *operator new(size_t sz)
 {
  extern new_handler _new_handler;
  void *p;
  sz=sz?sz:1;
  while((p=malloc(sz))==NULL)
   {
    if(_new_handler!=NULL)_new_handler();
    else break;
   }
  return p;
 }
void operator delete(void *v)
 {
  if(v)free(v);
 }
void *operator new[](size_t sz)
 {
  extern new_handler _new_handler;
  void *p;
  sz=sz?sz:1;
  while((p=malloc(sz))==NULL)
   {
    if(_new_handler!=NULL)_new_handler();
    else break;
   }
  return p;
 }
void operator delete[](void *v)
 {
  if(v)free(v);
 }
#endif
<commit_msg>FAR patch 00047.farrtl.cpp Дата              : 11.07.2000 Сделал            : Valentin Skirdin Описание          : Более разумное (с запасом) распределение памяти. Измененные файлы  : farrtl.cpp Состав            : farrtl.cpp.47.diff                     47.farrtl.cpp.txt Основан на патче  : 46 Дополнение        :<commit_after>/*
farrtl.cpp

८। 㭪権 ࠡ  : new/delete/malloc/realloc/free
*/

/* Revision: 1.03 11.07.2000 $ */

/*
Modify:
  03.07.2000 IS
    ! 祭 ᥣ 䠩  ஥
  04.07.2000 SVS
    ! 뤥  ⢥ ᠬ筮 !
  05.07.2000 IS
    !   ஢ப,   ᠫ ,    ࠢ
      , ᫨ ८। new/delete :-(((
  11.07.2000 SVS

*/

#ifdef __cplusplus
extern "C" {
#endif
typedef unsigned size_t;

void *malloc(size_t size);
void *realloc(void *block, size_t size);
void free(void *block);

#ifdef __cplusplus
}
#endif

#include "headers.hpp"
#pragma hdrstop

#define MEM_DELTA	1023

static HANDLE FARHeapForNew=NULL;

void *malloc(size_t size)
{
  return realloc(NULL,size);
}

void *realloc(void *block, size_t size)
{
  void *p=NULL;
  int size2;

  if(!FARHeapForNew) FARHeapForNew=GetProcessHeap();

  if(FARHeapForNew)
  {
    if(!size)
      HeapFree(FARHeapForNew,0,block);
    else if (!block) //   ࠧ  ⮫쪮, ᪮쪮
                     // . - 뫮 譥 室  筮 맮
      p=HeapAlloc(FARHeapForNew,HEAP_ZERO_MEMORY, size);
    else
    {
      p=block;
      // Required size, alligned to MEM_DELTA
      size  = (size + MEM_DELTA) & (~MEM_DELTA);
      // Current allocated size
      size2 = HeapSize(FARHeapForNew,0,block);
      if (size  > size2 ||          // ᨫ , 祬 ॠ쭮 뤥
          size2 - size > MEM_DELTA) //  ᢮  ࠧ஬  MEM_DELTA
        p=HeapReAlloc(FARHeapForNew,HEAP_ZERO_MEMORY,block,size);
      // else
      /*
          祣.   娯 㦥 뤥   ࠧ    ண .
           ணࠬ ⠥,  ந諨 ...
      */
    }
  }
  return p;
}

void free(void *block)
{
  if(!FARHeapForNew) FARHeapForNew=GetProcessHeap();
  if(FARHeapForNew) HeapFree(FARHeapForNew,0,block);
}

#if 0 //  ⮣ ࠡ⠥,      稭
void *operator new(size_t sz)
 {
  extern new_handler _new_handler;
  void *p;
  sz=sz?sz:1;
  while((p=malloc(sz))==NULL)
   {
    if(_new_handler!=NULL)_new_handler();
    else break;
   }
  return p;
 }
void operator delete(void *v)
 {
  if(v)free(v);
 }
void *operator new[](size_t sz)
 {
  extern new_handler _new_handler;
  void *p;
  sz=sz?sz:1;
  while((p=malloc(sz))==NULL)
   {
    if(_new_handler!=NULL)_new_handler();
    else break;
   }
  return p;
 }
void operator delete[](void *v)
 {
  if(v)free(v);
 }
#endif
<|endoftext|>