<commit_before>/**
 * @file pot.cpp
 *
 *
 * @date May 25, 2015
 * @author Tack
 */

#include <boost/lexical_cast.hpp>
#include <math.h>

#include "pot.h"
#include "plugin_factory.h"
#include "logger_factory.h"
#include "level.h"
#include "forecast_time.h"
#include "regular_grid.h"
#include "util.h"
#include "matrix.h"

using namespace std;
using namespace himan::plugin;

pot::pot()
{
    itsClearTextFormula = "complex formula";

    itsLogger = logger_factory::Instance()->GetLog("pot");
}

void pot::Process(std::shared_ptr<const plugin_configuration> conf)
{
    Init(conf);

    /*
     * Set target parameter properties
     * - name PARM_NAME, this name is found from neons. For example: T-K
     * - univ_id UNIV_ID, newbase-id, ie code table 204
     * - grib1 id must be in database
     * - grib2 descriptor X'Y'Z, http://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_table4-2.shtml
     *
     */

    // param theRequestedParam(PARM_NAME, UNIV_ID, GRIB2DISCIPLINE, GRIB2CATEGORY, GRIB2NUMBER);
    param POT("POT-PRCNT", 12100, 0, 19, 2);
    // If this param is also used as a source param for other calculations
    // (like for example dewpoint, relative humidity), unit should also be
    // specified

    POT.Unit(kPrcnt);

    SetParams({POT});

    Start();
}

/*
 * Calculate()
 *
 * This function does the actual calculation.
 */

void pot::Calculate(info_t myTargetInfo, unsigned short threadIndex)
{

    /*
     * Required source parameters
     */

    const param CapeParam("CAPE-JKG");
    const param RainParam("RRR-KGM2");
    // ----

    // Current time and level as given to this thread

    forecast_time forecastTime = myTargetInfo->Time();
    level forecastLevel = myTargetInfo->Level();
    forecast_type forecastType = myTargetInfo->ForecastType();

    auto myThreadedLogger = logger_factory::Instance()->GetLog("pot_pluginThread #" + boost::lexical_cast<string> (threadIndex));

    myThreadedLogger->Debug("Calculating time " + static_cast<string> (forecastTime.ValidDateTime()) + " level " + static_cast<string> (forecastLevel));

    info_t CAPEInfo, RRInfo;

    CAPEInfo = Fetch(forecastTime, forecastLevel, CapeParam, forecastType, false);
    RRInfo = Fetch(forecastTime, forecastLevel, RainParam, forecastType, false);

    if (!(CAPEInfo && RRInfo))
    {
        myThreadedLogger->Info("Skipping step " + boost::lexical_cast<string> (forecastTime.Step()) + ", level " + static_cast<string> (forecastLevel));
        return;
    }

    // käytetään sadeparametrina mallin sateen alueellista keskiarvoa, jotta diskreettejä sadeolioita saadaan vähän levitettyä ympäristöön, tässä toimisi paremmin esim. 30 km säde.
    // Filter RR
    himan::matrix<double> filter_kernel(3,3,1,kFloatMissing);
    filter_kernel.Fill(1/9);
    himan::matrix<double> filtered_RR = util::Filter2D(RRInfo->Data(), filter_kernel);
    RRInfo->Grid()->Data(filtered_RR);

    string deviceType = "CPU";

    LOCKSTEP(myTargetInfo, CAPEInfo, RRInfo)
    {
	double POT;
        double CAPE_ec = CAPEInfo->Value();
        double RR = RRInfo->Value();
        double LAT = myTargetInfo->LatLon().Y();

	double PoLift_ec = 0;
	double PoThermoDyn_ec = 0;

	// Määritetään salamointi vs. CAPE riippuvuutta varten tarvitaan CAPEn ala- ja ylärajoille yhtälöt. Ala- ja ylärajat muuttuvat leveyspiirin funktiona.
	double lat_abs = abs(LAT);
	double cape_low = -25*lat_abs + 1225;
	double cape_high = -40*lat_abs + 3250;

	// Kiinnitetään cape_low ja high levespiirien 25...45  ulkopuolella vakioarvoihin.
	if (lat_abs <25)
	{
		cape_low = 600;
		cape_high = 2000;
	}

	if (lat_abs > 45)
	{
		cape_low = 100;
		cape_high = 1000;
	}

	// CAPE-arvot skaalataan arvoihin 1....10. Ala- ja ylärajat muuttuvat leveyspiirin funktiona.
	double k =  9/(cape_high - cape_low);
	double scaled_cape = 1;
        if (CAPE_ec >= cape_low) scaled_cape = k*CAPE_ec + (1- k*cape_low);

	assert( scaled_cape > 0);

	// Leikataan skaalatun CAPEN arvot, jotka menevät yli 10
	if (scaled_cape >10) scaled_cape = 10;

	//Ukkosta suosivan termodynamiikan todennäköisyys
	PoThermoDyn_ec = 0.4343 * log(scaled_cape);      //salamoinnin todennäköisyys kasvaa logaritmisesti CAPE-arvojen kasvaessa.

	// Laukaisevan tekijän (Lift) todennäköisyys kasvaa ennustetun sateen intensiteetin funktiona.
	// Perustelu: Konvektioparametrisointi (eli malli saa nollasta poikkeavaa sademäärää) malleissa käynnistyy useimmiten alueilla, missä mallissa on konvergenssia tai liftiä tarjolla

	if (RR >= 0.05 && RR <= 5)
	{
		PoLift_ec  = 0.217147241 * log(RR) + 0.650514998;  // Funktio kasvaa nopeasti logaritmisesti nollasta ykköseen
	}

	if (RR > 5)
	{
		PoLift_ec  = 1;
	}

	//POT on ainesosiensa todennäköisyyksien tulo
	POT = PoLift_ec * PoThermoDyn_ec * 100;

        //return result
        myTargetInfo->Value(POT);
    }

    myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string> (myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<string> (myTargetInfo->Data().Size()));

}
<commit_msg>Bugfix<commit_after>/**
 * @file pot.cpp
 *
 *
 * @date May 25, 2015
 * @author Tack
 */

#include <boost/lexical_cast.hpp>
#include <math.h>

#include "pot.h"
#include "plugin_factory.h"
#include "logger_factory.h"
#include "level.h"
#include "forecast_time.h"
#include "regular_grid.h"
#include "util.h"
#include "matrix.h"

using namespace std;
using namespace himan::plugin;

pot::pot()
{
    itsClearTextFormula = "complex formula";

    itsLogger = logger_factory::Instance()->GetLog("pot");
}

void pot::Process(std::shared_ptr<const plugin_configuration> conf)
{
    Init(conf);

    /*
     * Set target parameter properties
     * - name PARM_NAME, this name is found from neons. For example: T-K
     * - univ_id UNIV_ID, newbase-id, ie code table 204
     * - grib1 id must be in database
     * - grib2 descriptor X'Y'Z, http://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_table4-2.shtml
     *
     */

    // param theRequestedParam(PARM_NAME, UNIV_ID, GRIB2DISCIPLINE, GRIB2CATEGORY, GRIB2NUMBER);
    param POT("POT-PRCNT", 12100, 0, 19, 2);
    // If this param is also used as a source param for other calculations
    // (like for example dewpoint, relative humidity), unit should also be
    // specified

    POT.Unit(kPrcnt);

    SetParams({POT});

    Start();
}

/*
 * Calculate()
 *
 * This function does the actual calculation.
 */

void pot::Calculate(info_t myTargetInfo, unsigned short threadIndex)
{

    /*
     * Required source parameters
     */

    const param CapeParam("CAPE-JKG");
    const param RainParam("RRR-KGM2");
    // ----

    // Current time and level as given to this thread

    forecast_time forecastTime = myTargetInfo->Time();
    level forecastLevel = myTargetInfo->Level();
    forecast_type forecastType = myTargetInfo->ForecastType();

    auto myThreadedLogger = logger_factory::Instance()->GetLog("pot_pluginThread #" + boost::lexical_cast<string> (threadIndex));

    myThreadedLogger->Debug("Calculating time " + static_cast<string> (forecastTime.ValidDateTime()) + " level " + static_cast<string> (forecastLevel));

    info_t CAPEInfo, RRInfo;

    CAPEInfo = Fetch(forecastTime, forecastLevel, CapeParam, forecastType, false);
    RRInfo = Fetch(forecastTime, forecastLevel, RainParam, forecastType, false);

    if (!(CAPEInfo && RRInfo))
    {
        myThreadedLogger->Info("Skipping step " + boost::lexical_cast<string> (forecastTime.Step()) + ", level " + static_cast<string> (forecastLevel));
        return;
    }

    // käytetään sadeparametrina mallin sateen alueellista keskiarvoa, jotta diskreettejä sadeolioita saadaan vähän levitettyä ympäristöön, tässä toimisi paremmin esim. 30 km säde.
    // Filter RR
    himan::matrix<double> filter_kernel(3,3,1,kFloatMissing);
    filter_kernel.Fill(1.0/9.0);
    himan::matrix<double> filtered_RR = util::Filter2D(RRInfo->Data(), filter_kernel);
    RRInfo->Grid()->Data(filtered_RR);

    string deviceType = "CPU";

    LOCKSTEP(myTargetInfo, CAPEInfo, RRInfo)
    {
	double POT;
        double CAPE_ec = CAPEInfo->Value();
        double RR = RRInfo->Value();
        double LAT = myTargetInfo->LatLon().Y();

	double PoLift_ec = 0;
	double PoThermoDyn_ec = 0;

	// Määritetään salamointi vs. CAPE riippuvuutta varten tarvitaan CAPEn ala- ja ylärajoille yhtälöt. Ala- ja ylärajat muuttuvat leveyspiirin funktiona.
	double lat_abs = abs(LAT);
	double cape_low = -25*lat_abs + 1225;
	double cape_high = -40*lat_abs + 3250;

	// Kiinnitetään cape_low ja high levespiirien 25...45  ulkopuolella vakioarvoihin.
	if (lat_abs <25)
	{
		cape_low = 600;
		cape_high = 2000;
	}

	if (lat_abs > 45)
	{
		cape_low = 100;
		cape_high = 1000;
	}

	// CAPE-arvot skaalataan arvoihin 1....10. Ala- ja ylärajat muuttuvat leveyspiirin funktiona.
	double k =  9/(cape_high - cape_low);
	double scaled_cape = 1;
        if (CAPE_ec >= cape_low) scaled_cape = k*CAPE_ec + (1- k*cape_low);

	assert( scaled_cape > 0);

	// Leikataan skaalatun CAPEN arvot, jotka menevät yli 10
	if (scaled_cape >10) scaled_cape = 10;

	//Ukkosta suosivan termodynamiikan todennäköisyys
	PoThermoDyn_ec = 0.4343 * log(scaled_cape);      //salamoinnin todennäköisyys kasvaa logaritmisesti CAPE-arvojen kasvaessa.

	// Laukaisevan tekijän (Lift) todennäköisyys kasvaa ennustetun sateen intensiteetin funktiona.
	// Perustelu: Konvektioparametrisointi (eli malli saa nollasta poikkeavaa sademäärää) malleissa käynnistyy useimmiten alueilla, missä mallissa on konvergenssia tai liftiä tarjolla

	if (RR >= 0.05 && RR <= 5)
	{
		PoLift_ec  = 0.217147241 * log(RR) + 0.650514998;  // Funktio kasvaa nopeasti logaritmisesti nollasta ykköseen
	}

	if (RR > 5)
	{
		PoLift_ec  = 1;
	}

	//POT on ainesosiensa todennäköisyyksien tulo
	POT = PoLift_ec * PoThermoDyn_ec * 100;

        //return result
        myTargetInfo->Value(POT);
    }

    myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string> (myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<string> (myTargetInfo->Data().Size()));

}
<|endoftext|>


<commit_before>#include <rpc/server.h>
#include <test/test_bitcoin.h>
#include <util.h>

#include <cstdint>
#include <vector>

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(server_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(server_IsDeprecatedRPCEnabled) {
    ArgsManager testArgs;
    const char *argv_test[] = {"bitcoind", "-deprecatedrpc=foo",
                               "-deprecatedrpc=bar"};

    testArgs.ParseParameters(3, (char **)argv_test);
    BOOST_CHECK(IsDeprecatedRPCEnabled(testArgs, "foo") == true);
    BOOST_CHECK(IsDeprecatedRPCEnabled(testArgs, "bar") == true);
    BOOST_CHECK(IsDeprecatedRPCEnabled(testArgs, "bob") == false);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Add license blurb to server_tests<commit_after>// Copyright (c) 2019 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <rpc/server.h>
#include <test/test_bitcoin.h>
#include <util.h>

#include <cstdint>
#include <vector>

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(server_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(server_IsDeprecatedRPCEnabled) {
    ArgsManager testArgs;
    const char *argv_test[] = {"bitcoind", "-deprecatedrpc=foo",
                               "-deprecatedrpc=bar"};

    testArgs.ParseParameters(3, (char **)argv_test);
    BOOST_CHECK(IsDeprecatedRPCEnabled(testArgs, "foo") == true);
    BOOST_CHECK(IsDeprecatedRPCEnabled(testArgs, "bar") == true);
    BOOST_CHECK(IsDeprecatedRPCEnabled(testArgs, "bob") == false);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include "ipfs.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QElapsedTimer>
#include <QEventLoop>
#include <QUrl>
#include <QProcess>
#include <QRegExp>
#include <QStandardPaths>
#include <QDir>
#include <QDebug>

#include "directory.h"

/*
 * PlanUML
 * @startuml
 *
 * [*] --> LAUNCH_DAEMON
 * LAUNCH_DAEMON --> RUNNING : read stdin
 * RUNNING --> LAUNCH_DAEMON : crash
 * RUNNING --> QUITTING
 *
 * @enduml
 */

Q_GLOBAL_STATIC(Ipfs, singleton)

enum IpfsState : short
{
    LAUNCH_DAEMON,
    RUNNING,
    QUITTING
};

Ipfs::Ipfs()
    : state_(LAUNCH_DAEMON),
      manager_(new QNetworkAccessManager()),
      daemon_process_(NULL),
      cli_process_(NULL),
      api_ip_("127.0.0.1"),
      api_port_("5001"),
      log_reply_(NULL)
{
    launch_daemon();
}

Ipfs::~Ipfs()
{
    this->state_ = QUITTING;

    if(log_reply_)
    {
        log_reply_->abort();
        log_reply_->deleteLater();
    }

    if(daemon_process_)
    {
        daemon_process_->terminate();
        if(!daemon_process_->waitForFinished())
        {
            daemon_process_->kill();
        }
        daemon_process_->deleteLater();
    }
    manager_->deleteLater();
}

Ipfs *Ipfs::instance()
{
    return singleton();
}

QUrl Ipfs::api_url(const QString &command)
{
    return QUrl(QString("http://%1:%2/api/v0/%3")
                .arg(api_ip_, api_port_, command));
}

IpfsAccess *Ipfs::query(const QUrl &url)
{
    IpfsAccess *access = new IpfsAccess();
    access->timer = new QElapsedTimer();
    access->request = new QNetworkRequest(url);

    // If not connected to the daemon, pill up the requests in a buffer
    if(online())
        launch_access((access));
    else
        access_buffer_ << access;

    return access;
}

bool Ipfs::online() const
{
    return state_ == RUNNING;
}

bool Ipfs::is_object_local(const IpfsHash &hash) const
{
    return local_objects_.contains(hash);
}

void Ipfs::init_commands()
{
    id.init();
    stats.init();
    swarm.init();
    version.init();
}

void Ipfs::launch_daemon()
{
    state_ = LAUNCH_DAEMON;

    // Add a custom repo location
    QDir dir(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/repo");
    qDebug() << "Repo path: " << dir.absolutePath();

    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    env.insert("IPFS_PATH", dir.absolutePath());

    if(cli_process_ == NULL)
    {
        cli_process_ = new QProcess();
        cli_process_->setProcessEnvironment(env);
    }

    // Initialize the repo if needed
    if(!dir.exists())
    {
        dir.mkpath(".");

        // ipfs should be in the PATH
        cli_process_->start("ipfs", QStringList() << "init");
        cli_process_->waitForFinished();

        qDebug() << "Repo initialized";
    }

    // Configure the HTTP API addresse
    cli_process_->start("ipfs", QStringList() << "config" << "Addresses.API" << "/ip4/127.0.0.1/tcp/4280");
    cli_process_->waitForFinished();
    api_port_ = "4280";
    qDebug() << "HTTP API set to /ip4/127.0.0.1/tcp/4280";

    // Add the API url to the CORS config to avoid 403
    cli_process_->start("ipfs",
        QStringList() << "config"
            << "--json"
            << "API.HTTPHeaders"
            << "{\"Access-Control-Allow-Origin\" : [\"http://127.0.0.1\", \"http://127.0.0.1:4280\"]}");
    cli_process_->waitForFinished();
    qDebug() << "Configured CORS";

    daemon_process_ = new QProcess(this);

    connect(daemon_process_, SIGNAL(started()),
            this, SLOT(daemon_started()));
    connect(daemon_process_, SIGNAL(error(QProcess::ProcessError)),
            this, SLOT(daemon_error(QProcess::ProcessError)));
    connect(daemon_process_, SIGNAL(finished(int,QProcess::ExitStatus)),
            this, SLOT(daemon_finished(int,QProcess::ExitStatus)));
    connect(daemon_process_, SIGNAL(readyReadStandardOutput()),
            this, SLOT(daemon_stdout()));
    connect(daemon_process_, SIGNAL(readyReadStandardError()),
            this, SLOT(daemon_stderr()));

    // ipfs should be in the PATH
    daemon_process_->setProcessEnvironment(env);
    daemon_process_->start("ipfs", QStringList() << "daemon");
}

void Ipfs::launch_access(IpfsAccess *access)
{
    access->timer->start();
    access->reply = manager_->get(*access->request);

    connect(access->reply, &QNetworkReply::finished,
            this, [this, access]()
    {
        if(access->reply->error())
        {
            qDebug() << "http error: " << access->reply->errorString() << endl;
            qDebug() << "request: " << access->request->url() << endl;

            if(this->state_ == RUNNING)
            {
                // TODO: restart process ?
            }

            delete access;

            return;
        }

        QString url = access->request->url().toString().remove(QRegExp("^.*/v0/"));
        qDebug() << url << access->timer->elapsed() << "ms";

        emit access->finished();
    });
}

void Ipfs::on_online()
{
    // Configure the various log level we need
    cli_process_->start("ipfs", QStringList() << "log" << "level" << "all" << "info");
    cli_process_->waitForFinished();

    init_commands();

    // Refresh local objects
    RefsReply *refs_reply = refs.local();
    connect(refs_reply, &RefsReply::finished,
            this, [this, refs_reply]()
    {
        qDebug() << refs_reply->refs.size() << " obj";

        foreach (IpfsHash hash, refs_reply->refs)
        {
            if(this->local_objects_.contains(hash))
            {
                this->local_objects_.remove(hash);
            }
            else
            {
                emit objectAdded(hash);
            }
        }

        foreach (IpfsHash hash, this->local_objects_)
        {
            emit objectRemoved(hash);
        }

        this->local_objects_ = refs_reply->refs;
    });

    request_logs();

    while(!access_buffer_.empty())
    {
        launch_access(access_buffer_.dequeue());
    }
}

void Ipfs::request_logs()
{
    if(log_reply_)
    {
        log_reply_->deleteLater();
    }

    QUrl url = api_url("log/tail");
    QNetworkRequest request(url);

    log_reply_ = manager_->get(request);

    connect(log_reply_, SIGNAL(readyRead()),
            this, SLOT(daemon_logevent()));
}

void Ipfs::daemon_started()
{
    qDebug() << "daemon started";
}

void Ipfs::daemon_error(QProcess::ProcessError error)
{
    qDebug() << "daemon error " << error;
    if(state_ == RUNNING && daemon_process_->state() == QProcess::NotRunning)
    {
        // TODO: restart process
    }
}

void Ipfs::daemon_finished(int exit_code, QProcess::ExitStatus exit_status)
{
    qDebug() << "daemon finished exit code: " << exit_code
             << "exit status: " << exit_status;

    if(state_ == RUNNING && daemon_process_->state() == QProcess::NotRunning)
    {
        // TODO: restart process
    }
}

void Ipfs::daemon_stdout()
{
    QByteArray raw = daemon_process_->readAllStandardOutput();
    QTextStream stdout(&raw);

    while (!stdout.atEnd())
    {
        QString line = stdout.readLine();

        qDebug() << line;

        if(state_ == LAUNCH_DAEMON)
        {
            QRegExp regex("^Daemon is ready$");
            if(regex.indexIn(line) >= 0)
            {
                state_ = RUNNING;
                on_online();
            }
        }
    }
}

// Ipfs daemon output its log on stderr
void Ipfs::daemon_stderr()
{
    QByteArray raw = daemon_process_->readAllStandardError();
    QTextStream stderr(&raw);

    while (!stderr.atEnd())
    {
        QString line = stderr.readLine();
        qDebug() << line;
    }
}

void Ipfs::daemon_logevent()
{
    QByteArray raw = log_reply_->readAll();
    QTextStream log(&raw);
    while(!log.atEnd())
    {
        QString line = log.readLine();

        QRegExp added(".*Added block.*");
        if(added.indexIn(line) >= 0)
        {
            QJsonObject json = QJsonDocument::fromJson(line.toUtf8()).object();
            try
            {
                const IpfsHash hash(json.value("key").toString());
                local_objects_.insert(hash);
                emit objectAdded(hash);
                qDebug() << "added " << hash;
            }
            catch(std::exception& e)
            {
                qDebug() << e.what() << line;
            }
        }

        QRegExp removed(".*Removed block.*");
        if(removed.indexIn(line) >= 0)
        {
            QJsonObject json = QJsonDocument::fromJson(line.toUtf8()).object();
            try
            {
                const IpfsHash hash(json.value("key").toString());
                local_objects_.remove(hash);
                qDebug() << "removed" << hash;
                emit objectRemoved(hash);
            }
            catch(std::exception& e)
            {
                qDebug() << e.what() << line;
            }
        }
    }
}

IpfsAccess::~IpfsAccess()
{
    delete this->request;
    this->reply->deleteLater();
    delete this->timer;
}

const QJsonObject IpfsAccess::json()
{
    QString str = this->reply->readAll();

    QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8());
    return doc.object();
}
<commit_msg>fix parsing added block twice<commit_after>#include "ipfs.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QElapsedTimer>
#include <QEventLoop>
#include <QUrl>
#include <QProcess>
#include <QRegExp>
#include <QStandardPaths>
#include <QDir>
#include <QDebug>

#include "directory.h"

/*
 * PlanUML
 * @startuml
 *
 * [*] --> LAUNCH_DAEMON
 * LAUNCH_DAEMON --> RUNNING : read stdin
 * RUNNING --> LAUNCH_DAEMON : crash
 * RUNNING --> QUITTING
 *
 * @enduml
 */

Q_GLOBAL_STATIC(Ipfs, singleton)

enum IpfsState : short
{
    LAUNCH_DAEMON,
    RUNNING,
    QUITTING
};

Ipfs::Ipfs()
    : state_(LAUNCH_DAEMON),
      manager_(new QNetworkAccessManager()),
      daemon_process_(NULL),
      cli_process_(NULL),
      api_ip_("127.0.0.1"),
      api_port_("5001"),
      log_reply_(NULL)
{
    launch_daemon();
}

Ipfs::~Ipfs()
{
    this->state_ = QUITTING;

    if(log_reply_)
    {
        log_reply_->abort();
        log_reply_->deleteLater();
    }

    if(daemon_process_)
    {
        daemon_process_->terminate();
        if(!daemon_process_->waitForFinished())
        {
            daemon_process_->kill();
        }
        daemon_process_->deleteLater();
    }
    manager_->deleteLater();
}

Ipfs *Ipfs::instance()
{
    return singleton();
}

QUrl Ipfs::api_url(const QString &command)
{
    return QUrl(QString("http://%1:%2/api/v0/%3")
                .arg(api_ip_, api_port_, command));
}

IpfsAccess *Ipfs::query(const QUrl &url)
{
    IpfsAccess *access = new IpfsAccess();
    access->timer = new QElapsedTimer();
    access->request = new QNetworkRequest(url);

    // If not connected to the daemon, pill up the requests in a buffer
    if(online())
        launch_access((access));
    else
        access_buffer_ << access;

    return access;
}

bool Ipfs::online() const
{
    return state_ == RUNNING;
}

bool Ipfs::is_object_local(const IpfsHash &hash) const
{
    return local_objects_.contains(hash);
}

void Ipfs::init_commands()
{
    id.init();
    stats.init();
    swarm.init();
    version.init();
}

void Ipfs::launch_daemon()
{
    state_ = LAUNCH_DAEMON;

    // Add a custom repo location
    QDir dir(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/repo");
    qDebug() << "Repo path: " << dir.absolutePath();

    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    env.insert("IPFS_PATH", dir.absolutePath());

    if(cli_process_ == NULL)
    {
        cli_process_ = new QProcess();
        cli_process_->setProcessEnvironment(env);
    }

    // Initialize the repo if needed
    if(!dir.exists())
    {
        dir.mkpath(".");

        // ipfs should be in the PATH
        cli_process_->start("ipfs", QStringList() << "init");
        cli_process_->waitForFinished();

        qDebug() << "Repo initialized";
    }

    // Configure the HTTP API addresse
    cli_process_->start("ipfs", QStringList() << "config" << "Addresses.API" << "/ip4/127.0.0.1/tcp/4280");
    cli_process_->waitForFinished();
    api_port_ = "4280";
    qDebug() << "HTTP API set to /ip4/127.0.0.1/tcp/4280";

    // Add the API url to the CORS config to avoid 403
    cli_process_->start("ipfs",
        QStringList() << "config"
            << "--json"
            << "API.HTTPHeaders"
            << "{\"Access-Control-Allow-Origin\" : [\"http://127.0.0.1\", \"http://127.0.0.1:4280\"]}");
    cli_process_->waitForFinished();
    qDebug() << "Configured CORS";

    daemon_process_ = new QProcess(this);

    connect(daemon_process_, SIGNAL(started()),
            this, SLOT(daemon_started()));
    connect(daemon_process_, SIGNAL(error(QProcess::ProcessError)),
            this, SLOT(daemon_error(QProcess::ProcessError)));
    connect(daemon_process_, SIGNAL(finished(int,QProcess::ExitStatus)),
            this, SLOT(daemon_finished(int,QProcess::ExitStatus)));
    connect(daemon_process_, SIGNAL(readyReadStandardOutput()),
            this, SLOT(daemon_stdout()));
    connect(daemon_process_, SIGNAL(readyReadStandardError()),
            this, SLOT(daemon_stderr()));

    // ipfs should be in the PATH
    daemon_process_->setProcessEnvironment(env);
    daemon_process_->start("ipfs", QStringList() << "daemon");
}

void Ipfs::launch_access(IpfsAccess *access)
{
    access->timer->start();
    access->reply = manager_->get(*access->request);

    connect(access->reply, &QNetworkReply::finished,
            this, [this, access]()
    {
        if(access->reply->error())
        {
            qDebug() << "http error: " << access->reply->errorString() << endl;
            qDebug() << "request: " << access->request->url() << endl;

            if(this->state_ == RUNNING)
            {
                // TODO: restart process ?
            }

            delete access;

            return;
        }

        QString url = access->request->url().toString().remove(QRegExp("^.*/v0/"));
        qDebug() << url << access->timer->elapsed() << "ms";

        emit access->finished();
    });
}

void Ipfs::on_online()
{
    // Configure the various log level we need
    cli_process_->start("ipfs", QStringList() << "log" << "level" << "all" << "info");
    cli_process_->waitForFinished();

    init_commands();

    // Refresh local objects
    RefsReply *refs_reply = refs.local();
    connect(refs_reply, &RefsReply::finished,
            this, [this, refs_reply]()
    {
        qDebug() << refs_reply->refs.size() << " obj";

        foreach (IpfsHash hash, refs_reply->refs)
        {
            if(this->local_objects_.contains(hash))
            {
                this->local_objects_.remove(hash);
            }
            else
            {
                emit objectAdded(hash);
            }
        }

        foreach (IpfsHash hash, this->local_objects_)
        {
            emit objectRemoved(hash);
        }

        this->local_objects_ = refs_reply->refs;
    });

    request_logs();

    while(!access_buffer_.empty())
    {
        launch_access(access_buffer_.dequeue());
    }
}

void Ipfs::request_logs()
{
    if(log_reply_)
    {
        log_reply_->deleteLater();
    }

    QUrl url = api_url("log/tail");
    QNetworkRequest request(url);

    log_reply_ = manager_->get(request);

    connect(log_reply_, SIGNAL(readyRead()),
            this, SLOT(daemon_logevent()));
}

void Ipfs::daemon_started()
{
    qDebug() << "daemon started";
}

void Ipfs::daemon_error(QProcess::ProcessError error)
{
    qDebug() << "daemon error " << error;
    if(state_ == RUNNING && daemon_process_->state() == QProcess::NotRunning)
    {
        // TODO: restart process
    }
}

void Ipfs::daemon_finished(int exit_code, QProcess::ExitStatus exit_status)
{
    qDebug() << "daemon finished exit code: " << exit_code
             << "exit status: " << exit_status;

    if(state_ == RUNNING && daemon_process_->state() == QProcess::NotRunning)
    {
        // TODO: restart process
    }
}

void Ipfs::daemon_stdout()
{
    QByteArray raw = daemon_process_->readAllStandardOutput();
    QTextStream stdout(&raw);

    while (!stdout.atEnd())
    {
        QString line = stdout.readLine();

        qDebug() << line;

        if(state_ == LAUNCH_DAEMON)
        {
            QRegExp regex("^Daemon is ready$");
            if(regex.indexIn(line) >= 0)
            {
                state_ = RUNNING;
                on_online();
            }
        }
    }
}

// Ipfs daemon output its log on stderr
void Ipfs::daemon_stderr()
{
    QByteArray raw = daemon_process_->readAllStandardError();
    QTextStream stderr(&raw);

    while (!stderr.atEnd())
    {
        QString line = stderr.readLine();
        qDebug() << line;
    }
}

void Ipfs::daemon_logevent()
{
    QByteArray raw = log_reply_->readAll();
    QTextStream log(&raw);
    while(!log.atEnd())
    {
        QString line = log.readLine();

        QRegExp added(".*Added block Begin.*");
        if(added.indexIn(line) >= 0)
        {
            QJsonObject json = QJsonDocument::fromJson(line.toUtf8()).object();
            try
            {
                const IpfsHash hash(json.value("key").toString());
                local_objects_.insert(hash);
                emit objectAdded(hash);
                qDebug() << "added " << hash;
            }
            catch(std::exception& e)
            {
                qDebug() << e.what() << line;
            }
        }

        QRegExp removed(".*Removed block.*");
        if(removed.indexIn(line) >= 0)
        {
            QJsonObject json = QJsonDocument::fromJson(line.toUtf8()).object();
            try
            {
                const IpfsHash hash(json.value("key").toString());
                local_objects_.remove(hash);
                qDebug() << "removed" << hash;
                emit objectRemoved(hash);
            }
            catch(std::exception& e)
            {
                qDebug() << e.what() << line;
            }
        }
    }
}

IpfsAccess::~IpfsAccess()
{
    delete this->request;
    this->reply->deleteLater();
    delete this->timer;
}

const QJsonObject IpfsAccess::json()
{
    QString str = this->reply->readAll();

    QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8());
    return doc.object();
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <stdlib.h>
#include <unistd.h>

#include <sys/user.h>
#include <sys/sysctl.h>
#include <sys/queue.h>
#include <libprocstat.h>

#include <osquery/tables.h>
#include <osquery/logger.h>

namespace osquery {
namespace tables {

/**
 * A helper function to retrieve processes using libprocstat(3). It is the
 * responsibility of the caller to call procstat_freeprocs() and
 * procstat_close() when done.
 *
 * Returns the number of processes in the "procs" list. On failure, returns 0
 * and sets pstat and procs to NULL.
 *
 * Errors are not well exposed in some of the calls in libprocstat(3). This is
 * a bit of a bummer as libkvm(3) is much better in that respect but I would
 * rather use libprocstat(3) as it provides a nicer abstraction.
 */
unsigned int getProcesses(QueryContext& context,
                          struct procstat** pstat,
                          struct kinfo_proc** procs) {
  std::set<std::string> pids;
  unsigned int cnt = 0;

  *pstat = procstat_open_sysctl();
  if (*pstat == nullptr) {
    TLOG << "Problem in procstat_open_sysctl()";
    return 0;
  }

  if (context.constraints["pid"].exists()) {
    pids = context.constraints["pid"].getAll(EQUALS);

    // Generate data for all pids in the vector.
    // If there are comparison constraints this could apply the operator
    // before generating the process structure.
    for (const auto& pid : pids) {
      *procs = procstat_getprocs(*pstat, KERN_PROC_PID, std::stoi(pid), &cnt);
      if (*procs == nullptr) {
        TLOG << "Problem retrieving processes.";
        procstat_close(*pstat);
        *pstat = nullptr;
        return 0;
      }
    }
  } else {
    // Get all PIDS.
    *procs = procstat_getprocs(*pstat, KERN_PROC_PROC, 0, &cnt);
    if (*procs == nullptr) {
      TLOG << "Problem retrieving processes.";
      procstat_close(*pstat);
      *pstat = nullptr;
      return 0;
    }
  }

  return cnt;
}

/**
 * Helper function to cleanup the libprocstat(3) pointers used.
 */
void procstatCleanup(struct procstat* pstat, struct kinfo_proc* procs) {
  if (procs != nullptr) {
    procstat_freeprocs(pstat, procs);
  }

  if (pstat != nullptr) {
    procstat_close(pstat);
  }
}

}
}
<commit_msg>Chase constraint changes introduced in #1170.<commit_after>/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <stdlib.h>
#include <unistd.h>

#include <sys/user.h>
#include <sys/sysctl.h>
#include <sys/queue.h>
#include <libprocstat.h>

#include <osquery/tables.h>
#include <osquery/logger.h>

namespace osquery {
namespace tables {

/**
 * A helper function to retrieve processes using libprocstat(3). It is the
 * responsibility of the caller to call procstat_freeprocs() and
 * procstat_close() when done.
 *
 * Returns the number of processes in the "procs" list. On failure, returns 0
 * and sets pstat and procs to NULL.
 *
 * Errors are not well exposed in some of the calls in libprocstat(3). This is
 * a bit of a bummer as libkvm(3) is much better in that respect but I would
 * rather use libprocstat(3) as it provides a nicer abstraction.
 */
unsigned int getProcesses(QueryContext& context,
                          struct procstat** pstat,
                          struct kinfo_proc** procs) {
  std::set<std::string> pids;
  unsigned int cnt = 0;

  *pstat = procstat_open_sysctl();
  if (*pstat == nullptr) {
    TLOG << "Problem in procstat_open_sysctl()";
    return 0;
  }

  if (context.constraints["pid"].exists(EQUALS)) {
    pids = context.constraints["pid"].getAll(EQUALS);

    // Generate data for all pids in the vector.
    // If there are comparison constraints this could apply the operator
    // before generating the process structure.
    for (const auto& pid : pids) {
      *procs = procstat_getprocs(*pstat, KERN_PROC_PID, std::stoi(pid), &cnt);
      if (*procs == nullptr) {
        TLOG << "Problem retrieving processes.";
        procstat_close(*pstat);
        *pstat = nullptr;
        return 0;
      }
    }
  } else {
    // Get all PIDS.
    *procs = procstat_getprocs(*pstat, KERN_PROC_PROC, 0, &cnt);
    if (*procs == nullptr) {
      TLOG << "Problem retrieving processes.";
      procstat_close(*pstat);
      *pstat = nullptr;
      return 0;
    }
  }

  return cnt;
}

/**
 * Helper function to cleanup the libprocstat(3) pointers used.
 */
void procstatCleanup(struct procstat* pstat, struct kinfo_proc* procs) {
  if (procs != nullptr) {
    procstat_freeprocs(pstat, procs);
  }

  if (pstat != nullptr) {
    procstat_close(pstat);
  }
}

}
}
<|endoftext|>


<commit_before>#include "TEveManager.h"
#include "TEveScene.h"
#include "TEveProjectionManager.h"
#include "TEveBrowser.h"
#include "TGLViewer.h"
#include "TEveViewer.h"
#include "TEveEventManager.h"

#include "AliHLTEvePhos.h"
#include "AliHLTEveEmcal.h"
#include "AliHLTEveTPC.h"
#include "AliHLTEveHLT.h"
#include "AliHLTEveITS.h"
#include "AliHLTEveISPD.h"
#include "AliHLTEveISSD.h"
#include "AliHLTEveISDD.h"
#include "AliHLTEveTRD.h"
#include "AliHLTEveMuon.h"
#include "AliHLTEveAny.h"

#include "AliEveHLTEventManager.h"
#include "AliEveHOMERManager.h"
#include "AliEveEventBuffer.h"

#include "TList.h"
#include "TTimer.h"

#include "TThread.h"

ClassImp(AliEveHLTEventManager);

AliEveHLTEventManager::AliEveHLTEventManager() :
  TEveElementList("Event Manager"),
  fGeoManager(NULL),
  fEveManager(NULL),
  fRPhiManager(NULL),
  fRhoZManager(NULL),
  fRPhiEventScene(NULL),
  fRhoZEventScene(NULL),
  fRhoZViewer(NULL),
  fRPhiViewer(NULL),
  fTimer(NULL),
  fPhosElement(NULL),
  fEmcalElement(NULL),
  fTPCElement(NULL),
  fHLTElement(NULL),
  fITSElement(NULL),
  fISPDElement(NULL),
  fISSDElement(NULL),
  fISDDElement(NULL),
  fTRDElement(NULL),
  fMuonElement(NULL),
  fAnyElement(NULL),
  fEventLoopStarted(kFALSE),
  fCenterProjectionsAtPrimaryVertex(kFALSE),
  fShowBarrel(kTRUE),
  fShowMuon(kFALSE),
  fRunNumber(-1),
  fEventId(-1)
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt

  fTimer = new TTimer();
  fTimer->Connect("Timeout()", "AliEveHLTEventManager", this, "NextEvent()" );

}

AliEveHLTEventManager::~AliEveHLTEventManager() {

  //DestroyElements();
  //DestroyDetectorElements();

}

void AliEveHLTEventManager::DestroyDetectorElements(){
  //See header file for documentation

  if (fPhosElement)
    delete fPhosElement;
  fPhosElement = NULL;

  if(fEmcalElement)
    delete fEmcalElement;
  fEmcalElement = NULL;

  if(fTPCElement)
    delete fTPCElement;
  fTPCElement = NULL;

  if(fHLTElement)
    delete fHLTElement;
  fHLTElement = NULL;

  if(fITSElement)
    delete fITSElement;
  fITSElement = NULL;

  if(fISSDElement)
    delete fISSDElement;
  fISSDElement = NULL;

  if(fISDDElement)
    delete fISDDElement;
  fISDDElement = NULL;

  if(fISPDElement)
    delete fISPDElement;
  fISPDElement = NULL;

  if(fTRDElement)
    delete fTRDElement;
  fTRDElement = NULL;

  if(fMuonElement)
    delete fMuonElement;
  fMuonElement = NULL;

  if(fAnyElement)
    delete fAnyElement;
  fAnyElement = NULL;

}

///_______________________________________________________________________________________
void AliEveHLTEventManager::ConnectEventBuffer() {
  GetEventBuffer()->ConnectToSource();
}

///___________________________________________________________________________________________
void AliEveHLTEventManager::StartBufferMonitor() {
  AliEveEventBuffer * buffer = GetEventBuffer();
  buffer->StartBufferMonitor();
}

//______________________________________________________________________________________________
Int_t AliEveHLTEventManager::ProcessEvent(AliESDEvent * event) {

  //We have a new event, reset display items (need to check if there really is anything interesting in event before resetting. ie not just histos)

  gEve->DisableRedraw();

  // -- Set EventID in Window Title
  TString winTitle("Eve Main Window");
  SetRunNumber(event->GetRunNumber());
  SetEventId(GetEventBuffer()->GetEventId());
  winTitle += Form("-- Run Number: %d", GetRunNumber());
  winTitle += Form("-- Event ID : 0x%016lX ", GetEventId() );
  GetEveManager()->GetBrowser()->SetWindowName(winTitle);

  cout << "reset()"<<endl;

  cout << "process()"<<endl;
  if(!fHLTElement) {
    fHLTElement = new AliHLTEveHLT();
    fHLTElement->SetEventManager(this);
    gEve->AddElement(fHLTElement);
 }
  fHLTElement->ProcessEsdEvent(event);

  if(!fPhosElement) CreatePhosElement();
  fPhosElement->ProcessEvent(event);

  if(!fEmcalElement) CreateEmcalElement();
  fEmcalElement->ProcessEvent(event);

  gEve->Redraw3D(0, 1);
  gEve->EnableRedraw();

  return 0;

}

//______________________________________________________________________________________________
Int_t AliEveHLTEventManager::ProcessEvent(TList * blockList) {

  //We have a new event, reset display items (need to check if there really is anything interesting in event before resetting. ie not just histos)

  if(!blockList) {
    cout << "Block list is NULL pointer, return " << endl;
    return -1;
  }

  AliHLTHOMERBlockDesc * block = NULL;
  TIter next(blockList);
  while ((block = (AliHLTHOMERBlockDesc*)next())) {
    cout <<"Process Block"<<endl;
    ProcessBlock(block);
  }

  return 0;

}
///___________________________________________________________________________________________

void AliEveHLTEventManager::ProcessBlock(AliHLTHOMERBlockDesc * block) {
  //See header file for documentation

#if 1//DEBUG
  printf( "------------------- xxxxxxxxxxxxxxx ----------------------\n");
  printf( "Detector           : %s\n", block->GetDetector().Data() );
  printf( "Datatype           : %s\n", block->GetDataType().Data() );
  if (block->IsTObject() )
    printf( "Is TObject of class: %s\n", block->GetClassName().Data() );
  printf( "------------------- xxxxxxxxxxxxxxx ----------------------\n");
#endif

  if(fShowBarrel) {

    if ( ! block->GetDetector().CompareTo("PHOS") ) {
      if(!fPhosElement) CreatePhosElement();
      fPhosElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("EMCA") ) {
      if(!fEmcalElement) CreateEmcalElement();
      fEmcalElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("TPC") ) {
      if(!fTPCElement) CreateTPCElement();
      fTPCElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("HLT") ) {
      if(!fHLTElement) CreateHLTElement();

      if(!block->GetDataType().CompareTo("ALIESDV0")) {
	AliESDEvent * event = dynamic_cast<AliESDEvent *>(block->GetTObject());
	if(event) {
	  ProcessEvent(event);
	}
      } else {
	fHLTElement->ProcessBlock(block);
      }
    }

    else if ( ! block->GetDetector().CompareTo("ITS") ) {
      if(!fITSElement) CreateITSElement();
      fITSElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("ISDD") ) {
      if(!fISDDElement) CreateISDDElement();
      fISDDElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("ISPD") ) {
      if(!fISPDElement) CreateISPDElement();
      fISPDElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("ISSD") ) {
      if(!fISSDElement) CreateISSDElement();
      fISSDElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("TRD") ) {
      if(!fTRDElement) CreateTRDElement();
      fTRDElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("MUON") ) {
      //Do Nothing
    } else {
      if(!fAnyElement) {
	fAnyElement = new AliHLTEveAny();
	fAnyElement->SetEventManager(this);
      }
      fAnyElement->ProcessBlock(block);
    }

  }

  if(fShowMuon) {
    if ( ! block->GetDetector().CompareTo("MUON") ) {
      if(!fMuonElement) {
	fMuonElement = new AliHLTEveMuon();
	fMuonElement->SetEventManager(this);
	gEve->AddElement(fMuonElement);
      }
      fMuonElement->ProcessBlock(block);
    }
  }

}

void AliEveHLTEventManager::ResetDisplay () {
  //See header file for documentation

 if(fPhosElement)
   fPhosElement->ResetElements();

 if(fEmcalElement)
   fEmcalElement->ResetElements();

 if(fTPCElement)
   fTPCElement->ResetElements();

 if(fHLTElement)
   fHLTElement->ResetElements();

 if(fITSElement)
   fITSElement->ResetElements();

 if(fISPDElement)
   fISPDElement->ResetElements();

 if(fISDDElement)
   fISDDElement->ResetElements();

 if(fISSDElement)
   fISSDElement->ResetElements();

 if (fTRDElement)
   fTRDElement->ResetElements();

 if(fAnyElement)
   fAnyElement->ResetElements();

 if(fMuonElement)
   fMuonElement->ResetElements();

}

void AliEveHLTEventManager::PrintScreens() {
//   //See header file for documentation

  fEveManager->GetDefaultGLViewer()->SavePicture(Form("%d_0x%016lX_3D.gif", fRunNumber, GetEventId()));
  fRhoZViewer->GetGLViewer()->SavePicture(Form("%d_0x%016lX_RhoZ.gif", fRunNumber, GetEventId()));
  fRPhiViewer->GetGLViewer()->SavePicture(Form("%d_0x%016lX_RPhi.gif", fRunNumber, GetEventId()));
  return;
}

void AliEveHLTEventManager::StartLoop() {
  //See header file for documentation
  //fTimer->SetCommand("NextEvent()", "AliEveHLTEventManager", this);
  NextEvent();
  SetEventLoopStarted(kTRUE);
  fTimer->Start(15000);
}

void AliEveHLTEventManager::StopLoop() {
  //See header file for documentation
  fTimer->Stop();
  SetEventLoopStarted(kFALSE);
}

// void AliEveHLTEventManager::NavigateBack() {

//   if (fHomerManager->NavigateEventBufferBack()) {
//     //return -1;
//   } else {

//     TList * blockList = fHomerManager->GetBlockList();
//     if(blockList) {
//       ProcessEvent(blockList);
//     } else {
//       cout << "BALLE Error blocklist NULL pointer even though it's navigateable"<<endl;
//     }
//   }

// }

// void AliEveHLTEventManager::NavigateFwd() {

//   if (fHomerManager->NavigateEventBufferFwd()) {
//     cout << "No event available" << endl;
//     return;
//     //return -1;
//   } else {
//     cout << "Getting block list" << endl;
//     TList * blockList = fHomerManager->GetBlockList();
//     if (blockList){
//       ProcessEvent(blockList);
//     } else {
//       cout << "blockList is NULL pointer"<<endl;
//     }
//   }

// }

void  AliEveHLTEventManager::UpdateDisplay() {
  //See header file for documentation
  if(fPhosElement) fPhosElement->UpdateElements();
  if(fEmcalElement) fEmcalElement->UpdateElements();
  if(fTPCElement) fTPCElement->UpdateElements();
  if(fHLTElement) fHLTElement->UpdateElements();
  if(fITSElement) fITSElement->UpdateElements();
  if(fISSDElement) fISSDElement->UpdateElements();
  if(fISDDElement) fISDDElement->UpdateElements();
  if(fISPDElement) fISPDElement->UpdateElements();
  if(fTRDElement) fTRDElement->UpdateElements();
  if(fAnyElement) fAnyElement->UpdateElements();
  if(fMuonElement) fMuonElement->UpdateElements();

  //==============================================================================
  // -- Import global scene into projection scenes
  //==============================================================================

  Double_t x[3] = { 0, 0, 0 };

  TEveElement* top = GetEveManager()->GetCurrentEvent();

  if (fRPhiManager && top) {
    fRPhiEventScene->DestroyElements();
    if (fCenterProjectionsAtPrimaryVertex)
      fRPhiManager->SetCenter(x[0], x[1], x[2]);
    fRPhiManager->ImportElements(top, fRPhiEventScene);
  }

  if (fRhoZManager && top) {
    fRhoZEventScene->DestroyElements();
    if (fCenterProjectionsAtPrimaryVertex)
      fRhoZManager->SetCenter(x[0], x[1], x[2]);
    fRhoZManager->ImportElements(top, fRhoZEventScene);
  }

  //Redraw the display
  GetEveManager()->Redraw3D(0,1); // (0, 1)
  GetEveManager()->EnableRedraw();

}

void AliEveHLTEventManager::SaveEveryThing() {

  PrintScreens();

  GetEventBuffer()->WriteToFile(GetRunNumber());
  //Save everything to file
  //fEventBuffer->SaveBlockList();
  //fEventBuffer->SaveAsyncBlockList();

}

void AliEveHLTEventManager::CreatePhosElement() {
  fPhosElement = new AliHLTEvePhos();
  fPhosElement->SetEventManager(this);
  gEve->AddElement(fPhosElement);
}

void AliEveHLTEventManager::CreateEmcalElement() {
  fEmcalElement = new AliHLTEveEmcal();
  fEmcalElement->SetEventManager(this);
  gEve->AddElement(fEmcalElement);
}
void AliEveHLTEventManager::CreateTPCElement() {
  fTPCElement = new AliHLTEveTPC();
  fTPCElement->SetEventManager(this);
  gEve->AddElement(fTPCElement);
}
void AliEveHLTEventManager::CreateITSElement() {
  fITSElement = new AliHLTEveITS();
  fITSElement->SetEventManager(this);
  gEve->AddElement(fITSElement);
}
void AliEveHLTEventManager::CreateISPDElement() {
  fISPDElement = new AliHLTEveISPD();
  fISPDElement->SetEventManager(this);
  gEve->AddElement(fISPDElement);
}
void AliEveHLTEventManager::CreateISDDElement() {
  fISDDElement = new AliHLTEveISDD();
  fISDDElement->SetEventManager(this);
  gEve->AddElement(fISSDElement);
}
void AliEveHLTEventManager::CreateISSDElement() {
  fISSDElement = new AliHLTEveISSD();
  fISSDElement->SetEventManager(this);
  gEve->AddElement(fISSDElement);
}
void AliEveHLTEventManager::CreateTRDElement() {
  fTRDElement = new AliHLTEveTRD();
  fTRDElement->SetEventManager(this);
  gEve->AddElement(fTRDElement);
}
void AliEveHLTEventManager::CreateHLTElement() {
  fHLTElement = new AliHLTEveHLT();
  fHLTElement->SetEventManager(this);
  gEve->AddElement(fHLTElement);
}

<commit_msg>increase buffer loop time<commit_after>#include "TEveManager.h"
#include "TEveScene.h"
#include "TEveProjectionManager.h"
#include "TEveBrowser.h"
#include "TGLViewer.h"
#include "TEveViewer.h"
#include "TEveEventManager.h"

#include "AliHLTEvePhos.h"
#include "AliHLTEveEmcal.h"
#include "AliHLTEveTPC.h"
#include "AliHLTEveHLT.h"
#include "AliHLTEveITS.h"
#include "AliHLTEveISPD.h"
#include "AliHLTEveISSD.h"
#include "AliHLTEveISDD.h"
#include "AliHLTEveTRD.h"
#include "AliHLTEveMuon.h"
#include "AliHLTEveAny.h"

#include "AliEveHLTEventManager.h"
#include "AliEveHOMERManager.h"
#include "AliEveEventBuffer.h"

#include "TList.h"
#include "TTimer.h"

#include "TThread.h"

ClassImp(AliEveHLTEventManager);

AliEveHLTEventManager::AliEveHLTEventManager() :
  TEveElementList("Event Manager"),
  fGeoManager(NULL),
  fEveManager(NULL),
  fRPhiManager(NULL),
  fRhoZManager(NULL),
  fRPhiEventScene(NULL),
  fRhoZEventScene(NULL),
  fRhoZViewer(NULL),
  fRPhiViewer(NULL),
  fTimer(NULL),
  fPhosElement(NULL),
  fEmcalElement(NULL),
  fTPCElement(NULL),
  fHLTElement(NULL),
  fITSElement(NULL),
  fISPDElement(NULL),
  fISSDElement(NULL),
  fISDDElement(NULL),
  fTRDElement(NULL),
  fMuonElement(NULL),
  fAnyElement(NULL),
  fEventLoopStarted(kFALSE),
  fCenterProjectionsAtPrimaryVertex(kFALSE),
  fShowBarrel(kTRUE),
  fShowMuon(kFALSE),
  fRunNumber(-1),
  fEventId(-1)
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt

  fTimer = new TTimer();
  fTimer->Connect("Timeout()", "AliEveHLTEventManager", this, "NextEvent()" );

}

AliEveHLTEventManager::~AliEveHLTEventManager() {

  //DestroyElements();
  //DestroyDetectorElements();

}

void AliEveHLTEventManager::DestroyDetectorElements(){
  //See header file for documentation

  if (fPhosElement)
    delete fPhosElement;
  fPhosElement = NULL;

  if(fEmcalElement)
    delete fEmcalElement;
  fEmcalElement = NULL;

  if(fTPCElement)
    delete fTPCElement;
  fTPCElement = NULL;

  if(fHLTElement)
    delete fHLTElement;
  fHLTElement = NULL;

  if(fITSElement)
    delete fITSElement;
  fITSElement = NULL;

  if(fISSDElement)
    delete fISSDElement;
  fISSDElement = NULL;

  if(fISDDElement)
    delete fISDDElement;
  fISDDElement = NULL;

  if(fISPDElement)
    delete fISPDElement;
  fISPDElement = NULL;

  if(fTRDElement)
    delete fTRDElement;
  fTRDElement = NULL;

  if(fMuonElement)
    delete fMuonElement;
  fMuonElement = NULL;

  if(fAnyElement)
    delete fAnyElement;
  fAnyElement = NULL;

}

///_______________________________________________________________________________________
void AliEveHLTEventManager::ConnectEventBuffer() {
  GetEventBuffer()->ConnectToSource();
}

///___________________________________________________________________________________________
void AliEveHLTEventManager::StartBufferMonitor() {
  AliEveEventBuffer * buffer = GetEventBuffer();
  buffer->StartBufferMonitor();
}

//______________________________________________________________________________________________
Int_t AliEveHLTEventManager::ProcessEvent(AliESDEvent * event) {

  //We have a new event, reset display items (need to check if there really is anything interesting in event before resetting. ie not just histos)

  gEve->DisableRedraw();

  // -- Set EventID in Window Title
  TString winTitle("Eve Main Window");
  SetRunNumber(event->GetRunNumber());
  SetEventId(GetEventBuffer()->GetEventId());
  winTitle += Form("-- Run Number: %d", GetRunNumber());
  winTitle += Form("-- Event ID : 0x%016lX ", GetEventId() );
  GetEveManager()->GetBrowser()->SetWindowName(winTitle);

  cout << "reset()"<<endl;

  cout << "process()"<<endl;
  if(!fHLTElement) {
    fHLTElement = new AliHLTEveHLT();
    fHLTElement->SetEventManager(this);
    gEve->AddElement(fHLTElement);
 }
  fHLTElement->ProcessEsdEvent(event);

  if(!fPhosElement) CreatePhosElement();
  fPhosElement->ProcessEvent(event);

  if(!fEmcalElement) CreateEmcalElement();
  fEmcalElement->ProcessEvent(event);

  gEve->Redraw3D(0, 1);
  gEve->EnableRedraw();

  return 0;

}

//______________________________________________________________________________________________
Int_t AliEveHLTEventManager::ProcessEvent(TList * blockList) {

  //We have a new event, reset display items (need to check if there really is anything interesting in event before resetting. ie not just histos)

  if(!blockList) {
    cout << "Block list is NULL pointer, return " << endl;
    return -1;
  }

  AliHLTHOMERBlockDesc * block = NULL;
  TIter next(blockList);
  while ((block = (AliHLTHOMERBlockDesc*)next())) {
    cout <<"Process Block"<<endl;
    ProcessBlock(block);
  }

  return 0;

}
///___________________________________________________________________________________________

void AliEveHLTEventManager::ProcessBlock(AliHLTHOMERBlockDesc * block) {
  //See header file for documentation

#if 1//DEBUG
  printf( "------------------- xxxxxxxxxxxxxxx ----------------------\n");
  printf( "Detector           : %s\n", block->GetDetector().Data() );
  printf( "Datatype           : %s\n", block->GetDataType().Data() );
  if (block->IsTObject() )
    printf( "Is TObject of class: %s\n", block->GetClassName().Data() );
  printf( "------------------- xxxxxxxxxxxxxxx ----------------------\n");
#endif

  if(fShowBarrel) {

    if ( ! block->GetDetector().CompareTo("PHOS") ) {
      if(!fPhosElement) CreatePhosElement();
      fPhosElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("EMCA") ) {
      if(!fEmcalElement) CreateEmcalElement();
      fEmcalElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("TPC") ) {
      if(!fTPCElement) CreateTPCElement();
      fTPCElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("HLT") ) {
      if(!fHLTElement) CreateHLTElement();

      if(!block->GetDataType().CompareTo("ALIESDV0")) {
	AliESDEvent * event = dynamic_cast<AliESDEvent *>(block->GetTObject());
	if(event) {
	  ProcessEvent(event);
	}
      } else {
	fHLTElement->ProcessBlock(block);
      }
    }

    else if ( ! block->GetDetector().CompareTo("ITS") ) {
      if(!fITSElement) CreateITSElement();
      fITSElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("ISDD") ) {
      if(!fISDDElement) CreateISDDElement();
      fISDDElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("ISPD") ) {
      if(!fISPDElement) CreateISPDElement();
      fISPDElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("ISSD") ) {
      if(!fISSDElement) CreateISSDElement();
      fISSDElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("TRD") ) {
      if(!fTRDElement) CreateTRDElement();
      fTRDElement->ProcessBlock(block);
    }

    else if ( ! block->GetDetector().CompareTo("MUON") ) {
      //Do Nothing
    } else {
      if(!fAnyElement) {
	fAnyElement = new AliHLTEveAny();
	fAnyElement->SetEventManager(this);
      }
      fAnyElement->ProcessBlock(block);
    }

  }

  if(fShowMuon) {
    if ( ! block->GetDetector().CompareTo("MUON") ) {
      if(!fMuonElement) {
	fMuonElement = new AliHLTEveMuon();
	fMuonElement->SetEventManager(this);
	gEve->AddElement(fMuonElement);
      }
      fMuonElement->ProcessBlock(block);
    }
  }

}

void AliEveHLTEventManager::ResetDisplay () {
  //See header file for documentation

 if(fPhosElement)
   fPhosElement->ResetElements();

 if(fEmcalElement)
   fEmcalElement->ResetElements();

 if(fTPCElement)
   fTPCElement->ResetElements();

 if(fHLTElement)
   fHLTElement->ResetElements();

 if(fITSElement)
   fITSElement->ResetElements();

 if(fISPDElement)
   fISPDElement->ResetElements();

 if(fISDDElement)
   fISDDElement->ResetElements();

 if(fISSDElement)
   fISSDElement->ResetElements();

 if (fTRDElement)
   fTRDElement->ResetElements();

 if(fAnyElement)
   fAnyElement->ResetElements();

 if(fMuonElement)
   fMuonElement->ResetElements();

}

void AliEveHLTEventManager::PrintScreens() {
//   //See header file for documentation

  fEveManager->GetDefaultGLViewer()->SavePicture(Form("%d_0x%016lX_3D.gif", fRunNumber, GetEventId()));
  fRhoZViewer->GetGLViewer()->SavePicture(Form("%d_0x%016lX_RhoZ.gif", fRunNumber, GetEventId()));
  fRPhiViewer->GetGLViewer()->SavePicture(Form("%d_0x%016lX_RPhi.gif", fRunNumber, GetEventId()));
  return;
}

void AliEveHLTEventManager::StartLoop() {
  //See header file for documentation
  //fTimer->SetCommand("NextEvent()", "AliEveHLTEventManager", this);
  NextEvent();
  SetEventLoopStarted(kTRUE);
  fTimer->Start(45000);
}

void AliEveHLTEventManager::StopLoop() {
  //See header file for documentation
  fTimer->Stop();
  SetEventLoopStarted(kFALSE);
}

// void AliEveHLTEventManager::NavigateBack() {

//   if (fHomerManager->NavigateEventBufferBack()) {
//     //return -1;
//   } else {

//     TList * blockList = fHomerManager->GetBlockList();
//     if(blockList) {
//       ProcessEvent(blockList);
//     } else {
//       cout << "BALLE Error blocklist NULL pointer even though it's navigateable"<<endl;
//     }
//   }

// }

// void AliEveHLTEventManager::NavigateFwd() {

//   if (fHomerManager->NavigateEventBufferFwd()) {
//     cout << "No event available" << endl;
//     return;
//     //return -1;
//   } else {
//     cout << "Getting block list" << endl;
//     TList * blockList = fHomerManager->GetBlockList();
//     if (blockList){
//       ProcessEvent(blockList);
//     } else {
//       cout << "blockList is NULL pointer"<<endl;
//     }
//   }

// }

void  AliEveHLTEventManager::UpdateDisplay() {
  //See header file for documentation
  if(fPhosElement) fPhosElement->UpdateElements();
  if(fEmcalElement) fEmcalElement->UpdateElements();
  if(fTPCElement) fTPCElement->UpdateElements();
  if(fHLTElement) fHLTElement->UpdateElements();
  if(fITSElement) fITSElement->UpdateElements();
  if(fISSDElement) fISSDElement->UpdateElements();
  if(fISDDElement) fISDDElement->UpdateElements();
  if(fISPDElement) fISPDElement->UpdateElements();
  if(fTRDElement) fTRDElement->UpdateElements();
  if(fAnyElement) fAnyElement->UpdateElements();
  if(fMuonElement) fMuonElement->UpdateElements();

  //==============================================================================
  // -- Import global scene into projection scenes
  //==============================================================================

  Double_t x[3] = { 0, 0, 0 };

  TEveElement* top = GetEveManager()->GetCurrentEvent();

  if (fRPhiManager && top) {
    fRPhiEventScene->DestroyElements();
    if (fCenterProjectionsAtPrimaryVertex)
      fRPhiManager->SetCenter(x[0], x[1], x[2]);
    fRPhiManager->ImportElements(top, fRPhiEventScene);
  }

  if (fRhoZManager && top) {
    fRhoZEventScene->DestroyElements();
    if (fCenterProjectionsAtPrimaryVertex)
      fRhoZManager->SetCenter(x[0], x[1], x[2]);
    fRhoZManager->ImportElements(top, fRhoZEventScene);
  }

  //Redraw the display
  GetEveManager()->Redraw3D(0,1); // (0, 1)
  GetEveManager()->EnableRedraw();

}

void AliEveHLTEventManager::SaveEveryThing() {

  PrintScreens();

  GetEventBuffer()->WriteToFile(GetRunNumber());
  //Save everything to file
  //fEventBuffer->SaveBlockList();
  //fEventBuffer->SaveAsyncBlockList();

}

void AliEveHLTEventManager::CreatePhosElement() {
  fPhosElement = new AliHLTEvePhos();
  fPhosElement->SetEventManager(this);
  gEve->AddElement(fPhosElement);
}

void AliEveHLTEventManager::CreateEmcalElement() {
  fEmcalElement = new AliHLTEveEmcal();
  fEmcalElement->SetEventManager(this);
  gEve->AddElement(fEmcalElement);
}
void AliEveHLTEventManager::CreateTPCElement() {
  fTPCElement = new AliHLTEveTPC();
  fTPCElement->SetEventManager(this);
  gEve->AddElement(fTPCElement);
}
void AliEveHLTEventManager::CreateITSElement() {
  fITSElement = new AliHLTEveITS();
  fITSElement->SetEventManager(this);
  gEve->AddElement(fITSElement);
}
void AliEveHLTEventManager::CreateISPDElement() {
  fISPDElement = new AliHLTEveISPD();
  fISPDElement->SetEventManager(this);
  gEve->AddElement(fISPDElement);
}
void AliEveHLTEventManager::CreateISDDElement() {
  fISDDElement = new AliHLTEveISDD();
  fISDDElement->SetEventManager(this);
  gEve->AddElement(fISSDElement);
}
void AliEveHLTEventManager::CreateISSDElement() {
  fISSDElement = new AliHLTEveISSD();
  fISSDElement->SetEventManager(this);
  gEve->AddElement(fISSDElement);
}
void AliEveHLTEventManager::CreateTRDElement() {
  fTRDElement = new AliHLTEveTRD();
  fTRDElement->SetEventManager(this);
  gEve->AddElement(fTRDElement);
}
void AliEveHLTEventManager::CreateHLTElement() {
  fHLTElement = new AliHLTEveHLT();
  fHLTElement->SetEventManager(this);
  gEve->AddElement(fHLTElement);
}

<|endoftext|>


<commit_before>/**\file
 *
 * \copyright
 * Copyright (c) 2015, ef.gy Project Members
 * \copyright
 * 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:
 * \copyright
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * \copyright
 * 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.
 *
 * \see Project Documentation: https://ef.gy/documentation/libefgy
 * \see Project Source Code: https://github.com/ef-gy/libefgy
 */

#define ASIO_DISABLE_THREADS
#include <ef.gy/irc.h>

using namespace efgy;
using asio::ip::tcp;

class processor {
public:
};

/**\brief Main function for the IRC demo
 *
 * This is the main function for the IRC Hello World demo.
 *
 * \param[in] argc Process argument count.
 * \param[in] argv Process argument vector
 *
 * \returns 0 when nothing bad happened, 1 otherwise.
 */
int main(int argc, char *argv[]) {
  try {
    if (argc != 3) {
      std::cerr << "Usage: irc-hello <host> <port>\n";
      return 1;
    }

    asio::io_service io_service;
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(argv[1], argv[2]);
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    tcp::resolver::iterator end;

    if (endpoint_iterator != end) {
      tcp::endpoint endpoint = *endpoint_iterator;
      net::irc::server<tcp, processor> s(io_service, endpoint);

      io_service.run();
    }

    return 0;
  }
  catch (std::exception & e) {
    std::cerr << "Exception: " << e.what() << "\n";
  }
  catch (std::system_error & e) {
    std::cerr << "System Error: " << e.what() << "\n";
  }

  return 1;
}
<commit_msg>add a basic processor and expand the IRC server to support client connection handling and the basics of numeric messages<commit_after>/**\file
 *
 * \copyright
 * Copyright (c) 2015, ef.gy Project Members
 * \copyright
 * 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:
 * \copyright
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * \copyright
 * 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.
 *
 * \see Project Documentation: https://ef.gy/documentation/libefgy
 * \see Project Source Code: https://github.com/ef-gy/libefgy
 */

#define ASIO_DISABLE_THREADS
#include <ef.gy/irc.h>

using namespace efgy;
using asio::ip::tcp;

/**\brief Main function for the IRC demo
 *
 * This is the main function for the IRC Hello World demo.
 *
 * \param[in] argc Process argument count.
 * \param[in] argv Process argument vector
 *
 * \returns 0 when nothing bad happened, 1 otherwise.
 */
int main(int argc, char *argv[]) {
  try {
    if (argc != 3) {
      std::cerr << "Usage: irc-hello <host> <port>\n";
      return 1;
    }

    asio::io_service io_service;
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(argv[1], argv[2]);
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    tcp::resolver::iterator end;

    if (endpoint_iterator != end) {
      tcp::endpoint endpoint = *endpoint_iterator;
      net::irc::server<tcp> s(io_service, endpoint);

      io_service.run();
    }

    return 0;
  }
  catch (std::exception & e) {
    std::cerr << "Exception: " << e.what() << "\n";
  }
  catch (std::system_error & e) {
    std::cerr << "System Error: " << e.what() << "\n";
  }

  return 1;
}
<|endoftext|>


<commit_before>/*
* Copyright (C) 2008-2011 J-P Nurmi <jpnurmi@gmail.com>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
* License for more details.
*/

#include "ircprefix.h"
#include <QRegExp>

/*!
    \class IrcPrefix ircprefix.h <IrcPrefix>
    \brief The IrcPrefix class is a helper class for handling IRC message prefixes.

    An IRC message prefix as specified in RFC 1459:

    <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]

 */

/*!
    \fn QString IrcPrefix::name() const
    Returns the name.

    <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]

 */

/*!
    \fn void IrcPrefix::setName(const QString& name)
    Sets the name.

    <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]

 */

/*!
    \fn QString IrcPrefix::user() const
    Returns the user.

    <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]

 */

/*!
    \fn void IrcPrefix::setUser(const QString& user)
    Sets the user.

    <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]

 */

/*!
    \fn QString IrcPrefix::host() const
    Returns the host.

    <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]

 */

/*!
    \fn void IrcPrefix::setHost(const QString& host)
    Sets the host.

    <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]

 */

/*!
    Constructs a new IrcPrefix, optionally initializing to \a prefix.
 */
IrcPrefix::IrcPrefix(const QString& prefix)
{
    setPrefix(prefix);
}

/*!
    Returns \c true if the prefix is valid; otherwise \c false.

    A prefix is considered valid if the name is not empty.
 */
bool IrcPrefix::isValid() const
{
    return !n.isEmpty();
}

/*!
    Returns \c true if the prefix is a user prefix; otherwise \c false.

    A prefix is considered as user prefix if either user or host is not empty.
 */
bool IrcPrefix::isUser() const
{
    return isValid() && (!u.isEmpty() || !h.isEmpty());
}

/*!
    Returns the whole prefix.
 */
QString IrcPrefix::prefix() const
{
    if (!isValid())
        return QString();

    QString pfx = n;
    if (!u.isEmpty()) pfx += "!" + u;
    if (!h.isEmpty()) pfx += "@" + h;
    return pfx;
}

/*!
    Sets the whole prefix.

    \warning Overrides any existing name, user or host.
 */
void IrcPrefix::setPrefix(const QString& prefix)
{
    QRegExp rx("([^!\\s]+)(![^@\\s]+)(@\\S+)");
    bool match = rx.exactMatch(prefix.trimmed());
    n = match ? rx.cap(1) : QString();
    u = match ? rx.cap(2).mid(1) : QString();
    h = match ? rx.cap(3).mid(1) : QString();
}
<commit_msg>IrcPrefix docs: fixed unsupported xml/html tag -warnings<commit_after>/*
* Copyright (C) 2008-2011 J-P Nurmi <jpnurmi@gmail.com>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
* License for more details.
*/

#include "ircprefix.h"
#include <QRegExp>

/*!
    \class IrcPrefix ircprefix.h <IrcPrefix>
    \brief The IrcPrefix class is a helper class for handling IRC message prefixes.

    An IRC message prefix as specified in RFC 1459:

    <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]

 */

/*!
    \fn QString IrcPrefix::name() const
    Returns the name.

    <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]

 */

/*!
    \fn void IrcPrefix::setName(const QString& name)
    Sets the name.

    <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]

 */

/*!
    \fn QString IrcPrefix::user() const
    Returns the user.

    <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]

 */

/*!
    \fn void IrcPrefix::setUser(const QString& user)
    Sets the user.

    <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]

 */

/*!
    \fn QString IrcPrefix::host() const
    Returns the host.

    <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]

 */

/*!
    \fn void IrcPrefix::setHost(const QString& host)
    Sets the host.

    <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]

 */

/*!
    Constructs a new IrcPrefix, optionally initializing to \a prefix.
 */
IrcPrefix::IrcPrefix(const QString& prefix)
{
    setPrefix(prefix);
}

/*!
    Returns \c true if the prefix is valid; otherwise \c false.

    A prefix is considered valid if the name is not empty.
 */
bool IrcPrefix::isValid() const
{
    return !n.isEmpty();
}

/*!
    Returns \c true if the prefix is a user prefix; otherwise \c false.

    A prefix is considered as user prefix if either user or host is not empty.
 */
bool IrcPrefix::isUser() const
{
    return isValid() && (!u.isEmpty() || !h.isEmpty());
}

/*!
    Returns the whole prefix.
 */
QString IrcPrefix::prefix() const
{
    if (!isValid())
        return QString();

    QString pfx = n;
    if (!u.isEmpty()) pfx += "!" + u;
    if (!h.isEmpty()) pfx += "@" + h;
    return pfx;
}

/*!
    Sets the whole prefix.

    \warning Overrides any existing name, user or host.
 */
void IrcPrefix::setPrefix(const QString& prefix)
{
    QRegExp rx("([^!\\s]+)(![^@\\s]+)(@\\S+)");
    bool match = rx.exactMatch(prefix.trimmed());
    n = match ? rx.cap(1) : QString();
    u = match ? rx.cap(2).mid(1) : QString();
    h = match ? rx.cap(3).mid(1) : QString();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ManifestExport.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: mtg $ $Date: 2001-11-15 20:20:18 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/

#ifndef _MANIFEST_EXPORT_HXX
#define _MANIFEST_EXPORT_HXX

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

namespace com { namespace sun { namespace star {
    namespace beans { struct PropertyValue;}
    namespace xml { namespace sax { class XDocumentHandler; } }
} } }
class ManifestExport
{
public:
    ManifestExport(com::sun::star::uno::Reference < com::sun::star::xml::sax::XDocumentHandler > xHandler, const com::sun::star::uno::Sequence < com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue > > &rManList);
};

#endif
<commit_msg>INTEGRATION: CWS oasisbf4 (1.2.184); FILE MERGED 2005/01/11 12:22:00 mav 1.2.184.1: #i38186# provide correct namespace information<commit_after>/*************************************************************************
 *
 *  $RCSfile: ManifestExport.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-27 11:17:55 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/

#ifndef _MANIFEST_EXPORT_HXX
#define _MANIFEST_EXPORT_HXX

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

namespace com { namespace sun { namespace star {
    namespace beans { struct PropertyValue;}
    namespace xml { namespace sax { class XDocumentHandler; } }
} } }
class ManifestExport
{
public:
    ManifestExport(com::sun::star::uno::Reference < com::sun::star::xml::sax::XDocumentHandler > xHandler, const com::sun::star::uno::Sequence < com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue > > &rManList );
};

#endif

<|endoftext|>


<commit_before>#include <Arduino.h>
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <time.h>

#include "Configuration.h"
#include "state.h"
#include "providers.h"
#include "dbg.h"

const char host[] PROGMEM = "api.openweathermap.org";
static bool forecast;

void OpenWeatherMap::on_connect(WiFiClient &client, bool conds) {
	client.print(F("/data/2.5/"));
	if (conds)
		client.print(F("weather"));
	else
		client.print(F("forecast"));

	if (cfg.nearest) {
		client.print(F("?lat="));
		client.print(cfg.lat);
		client.print(F("&lon="));
		client.print(cfg.lon);
	} else {
		client.print(F("?q="));
		client.print(cfg.station);
	}

	if (!conds)
		client.print(F("&cnt=16"));

	client.print(F("&appid="));
	client.print(cfg.key);
	client.print(F("&units="));
	if (cfg.metric)
		client.print(F("metric"));
	else
		client.print(F("imperial"));
}

static bool update_conditions(JsonObject &root, struct Conditions &c) {
	time_t epoch = (time_t)root[F("dt")];
	if (c.epoch == epoch)
		return false;

	c.epoch = epoch;

	JsonObject &w = root[F("weather")][0];
	const char *desc = w[F("description")] | "";
	int l = strlen(desc);
	if (l >= sizeof(c.weather) || l == 0)
		desc = w[F("main")] | "";
	strlcpy(c.weather, desc, sizeof(c.weather));
	strlcpy(c.icon, w[F("icon")] | "", sizeof(c.icon));

	JsonObject &main = root[F("main")];
	c.temp = main[F("temp")];
	c.feelslike = main[F("temp_min")];	// hmmm
	c.pressure = main[F("pressure")];
	c.humidity = main[F("humidity")];

	JsonObject &wind = root[F("wind")];
	c.wind = ceil(float(wind[F("speed")]) * 3.6);
	c.wind_degrees = wind[F("deg")];

	JsonObject &sys = root["sys"];
	time_t sunrise = (time_t)sys["sunrise"];
	struct tm *sr = gmtime(&sunrise);
	c.sunrise_hour = sr->tm_hour;
	c.sunrise_minute = sr->tm_min;

	time_t sunset = (time_t)sys["sunset"];
	struct tm *ss = gmtime(&sunset);
	c.sunset_hour = ss->tm_hour;
	c.sunset_minute = ss->tm_min;

	strlcpy(c.city, root[F("name")] | "", sizeof(c.city));
	strlcat(c.city, ", ", sizeof(c.city));
	strlcat(c.city, sys[F("country")], sizeof(c.city));
	return true;
}

const unsigned cbytes = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(1) + 2*JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(6) + JSON_OBJECT_SIZE(12) + 956;

bool OpenWeatherMap::fetch_conditions(struct Conditions &conditions) {
	WiFiClient client;
	bool ret = false;

	if (connect_and_get(client, host, true)) {
		DynamicJsonBuffer buffer(cbytes);
		JsonObject &root = buffer.parseObject(client);
		if (ret = root.success()) {
			update_conditions(root, conditions);
			DBG(print(F("Done ")));
			DBG(println(buffer.size()));
		} else {
			ERR(println(F("Failed to parse!")));
			stats.parse_failures++;
		}
	}
	client.stop();
	return ret;
}

static void update_forecasts(JsonObject &root, struct Forecast fs[], int n) {
	int cnt = root[F("cnt")];
	JsonArray &list = root[F("list")];

	for (int i = 0, j = 0; i < n && j < cnt; i++, j += 2) {
		struct Forecast &f = fs[i];

		JsonObject &fc = list[j];
		f.epoch = fc[F("dt")];

		JsonObject &main = fc[F("main")];
		f.temp_high = main[F("temp_max")];
		f.temp_low = main[F("temp_min")];
		f.humidity = main[F("humidity")];

		JsonObject &weather = fc[F("weather")][0];
		strlcpy(f.conditions, weather[F("description")], sizeof(f.conditions));
		strlcpy(f.icon, weather[F("icon")], sizeof(f.icon));

		JsonObject &wind = fc[F("wind")];
		f.wind_degrees = wind[F("deg")];
		f.ave_wind = ceil(float(wind[F("speed")]) * 3.6);
	}
}

const unsigned fbytes = 16*JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(16) + 2*JSON_OBJECT_SIZE(0) + 46*JSON_OBJECT_SIZE(1) + 17*JSON_OBJECT_SIZE(2) + 17*JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + 32*JSON_OBJECT_SIZE(8) + 12603;

bool OpenWeatherMap::fetch_forecasts(struct Forecast forecasts[], int days) {
	WiFiClient client;
	bool ret = false;

	forecast = true;
	if (connect_and_get(client, host, false)) {
		DynamicJsonBuffer buffer(fbytes);
		JsonObject &root = buffer.parseObject(client);
		if (ret = root.success()) {
			update_forecasts(root, forecasts, days);
			DBG(print(F("Done ")));
			DBG(println(buffer.size()));
		} else {
			ERR(println(F("Failed to parse!")));
			stats.parse_failures++;
		}
	}
	forecast = false;
	client.stop();
	return ret;
}
<commit_msg>bugfix<commit_after>#include <Arduino.h>
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <time.h>

#include "Configuration.h"
#include "state.h"
#include "providers.h"
#include "dbg.h"

const char host[] PROGMEM = "api.openweathermap.org";
static bool forecast;

void OpenWeatherMap::on_connect(WiFiClient &client, bool conds) {
	client.print(F("/data/2.5/"));
	if (conds)
		client.print(F("weather"));
	else
		client.print(F("forecast"));

	if (cfg.nearest) {
		client.print(F("?lat="));
		client.print(cfg.lat);
		client.print(F("&lon="));
		client.print(cfg.lon);
	} else {
		client.print(F("?q="));
		client.print(cfg.station);
	}

	if (!conds)
		client.print(F("&cnt=16"));

	client.print(F("&appid="));
	client.print(cfg.key);
	client.print(F("&units="));
	if (cfg.metric)
		client.print(F("metric"));
	else
		client.print(F("imperial"));
}

static bool update_conditions(JsonObject &root, struct Conditions &c) {
	time_t epoch = (time_t)root[F("dt")];
	if (epoch <= c.epoch)
		return false;

	stats.num_updates++;
	if (c.epoch)
		stats.update(epoch - c.epoch);
	c.epoch = epoch;

	JsonObject &w = root[F("weather")][0];
	const char *desc = w[F("description")] | "";
	int l = strlen(desc);
	if (l >= sizeof(c.weather) || l == 0)
		desc = w[F("main")] | "";
	strlcpy(c.weather, desc, sizeof(c.weather));
	strlcpy(c.icon, w[F("icon")] | "", sizeof(c.icon));

	JsonObject &main = root[F("main")];
	c.temp = main[F("temp")];
	c.feelslike = main[F("temp_min")];	// hmmm
	c.pressure = main[F("pressure")];
	c.humidity = main[F("humidity")];

	JsonObject &wind = root[F("wind")];
	c.wind = ceil(float(wind[F("speed")]) * 3.6);
	c.wind_degrees = wind[F("deg")];

	JsonObject &sys = root["sys"];
	time_t sunrise = (time_t)sys["sunrise"];
	struct tm *sr = gmtime(&sunrise);
	c.sunrise_hour = sr->tm_hour;
	c.sunrise_minute = sr->tm_min;

	time_t sunset = (time_t)sys["sunset"];
	struct tm *ss = gmtime(&sunset);
	c.sunset_hour = ss->tm_hour;
	c.sunset_minute = ss->tm_min;

	strlcpy(c.city, root[F("name")] | "", sizeof(c.city));
	strlcat(c.city, ", ", sizeof(c.city));
	strlcat(c.city, sys[F("country")], sizeof(c.city));
	return true;
}

const unsigned cbytes = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(1) + 2*JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(6) + JSON_OBJECT_SIZE(12) + 956;

bool OpenWeatherMap::fetch_conditions(struct Conditions &conditions) {
	WiFiClient client;
	bool ret = false;

	if (connect_and_get(client, host, true)) {
		DynamicJsonBuffer buffer(cbytes);
		JsonObject &root = buffer.parseObject(client);
		if (ret = root.success()) {
			update_conditions(root, conditions);
			DBG(print(F("Done ")));
			DBG(println(buffer.size()));
		} else {
			ERR(println(F("Failed to parse!")));
			stats.parse_failures++;
		}
	}
	client.stop();
	return ret;
}

static void update_forecasts(JsonObject &root, struct Forecast fs[], int n) {
	int cnt = root[F("cnt")];
	JsonArray &list = root[F("list")];

	for (int i = 0, j = 0; i < n && j < cnt; i++, j += 2) {
		struct Forecast &f = fs[i];

		JsonObject &fc = list[j];
		f.epoch = fc[F("dt")];

		JsonObject &main = fc[F("main")];
		f.temp_high = main[F("temp_max")];
		f.temp_low = main[F("temp_min")];
		f.humidity = main[F("humidity")];

		JsonObject &weather = fc[F("weather")][0];
		strlcpy(f.conditions, weather[F("description")], sizeof(f.conditions));
		strlcpy(f.icon, weather[F("icon")], sizeof(f.icon));

		JsonObject &wind = fc[F("wind")];
		f.wind_degrees = wind[F("deg")];
		f.ave_wind = ceil(float(wind[F("speed")]) * 3.6);
	}
}

const unsigned fbytes = 16*JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(16) + 2*JSON_OBJECT_SIZE(0) + 46*JSON_OBJECT_SIZE(1) + 17*JSON_OBJECT_SIZE(2) + 17*JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + 32*JSON_OBJECT_SIZE(8) + 12603;

bool OpenWeatherMap::fetch_forecasts(struct Forecast forecasts[], int days) {
	WiFiClient client;
	bool ret = false;

	forecast = true;
	if (connect_and_get(client, host, false)) {
		DynamicJsonBuffer buffer(fbytes);
		JsonObject &root = buffer.parseObject(client);
		if (ret = root.success()) {
			update_forecasts(root, forecasts, days);
			DBG(print(F("Done ")));
			DBG(println(buffer.size()));
		} else {
			ERR(println(F("Failed to parse!")));
			stats.parse_failures++;
		}
	}
	forecast = false;
	client.stop();
	return ret;
}
<|endoftext|>


<commit_before>//******************************************************************************
// FILE : function_base.hpp
//
// LAST MODIFIED : 11 November 2004
//
// DESCRIPTION :
// Basic declarations and #defines for functions.
//
// ???DB.  17Jan04
//   _handle is a bit of a misnomer for smart pointers because the thing about
//   handles is that they don't provide operator-> or operator*
//   (Alexandrescu p.161)
//==============================================================================
#if !defined (__FUNCTION_BASE_HPP__)
#define __FUNCTION_BASE_HPP__

#include <stdexcept>

//#define BEFORE_CACHING

//#define EXPORT_IMPLEMENTED
//#define ONE_TEMPLATE_DEFINITION_IMPLEMENTED

#if defined (EXPORT_IMPLEMENTED)
#define EXPORT export
#define ONE_TEMPLATE_DEFINITION_IMPLEMENTED
#else // defined (EXPORT_IMPLEMENTED)
#define EXPORT
#endif // defined (EXPORT_IMPLEMENTED)

const bool Assert_on=true;

template<class Assertion,class Exception>inline void Assert(
	Assertion assertion,Exception exception)
{
	if (Assert_on&&!(assertion))
	{
		std::cerr << exception.what() << std::endl;
		throw exception;
	}
}

#include <string>

typedef std::string * string_handle;
	//???DB.  Replace with smart pointer or return reference?
	//???DB.  At present big probability of memory leak or segmentation fault

typedef unsigned int Function_size_type;

typedef double Scalar;

#include "boost/numeric/ublas/matrix.hpp"
#include "boost/numeric/ublas/vector.hpp"
#include "boost/numeric/ublas/io.hpp"

namespace ublas = boost::numeric::ublas;

// use column_major so that can use lapack=boost::numeric::bindings::lapack
typedef ublas::matrix<Scalar,ublas::column_major> Matrix;
typedef ublas::vector<Scalar> Vector;

#include "boost/intrusive_ptr.hpp"

// intentional ambiguity to prevent use of boost::intrusive_ptr::operator==
//   Use equivalent instead
template<class Value_type_1,class Value_type_2>
bool operator==(boost::intrusive_ptr<Value_type_1> const & first,
	boost::intrusive_ptr<Value_type_2> const & second);
template<class Value_type>
bool operator==(boost::intrusive_ptr<Value_type> const & first,
	Value_type * second);
template<class Value_type>
bool operator==(Value_type * first,
	boost::intrusive_ptr<Value_type> const & second);

// intentional ambiguity to prevent use of boost::intrusive_ptr::operator!=
//   Use !equivalent instead
template<class Value_type_1,class Value_type_2>
bool operator!=(boost::intrusive_ptr<Value_type_1> const & first,
	boost::intrusive_ptr<Value_type_2> const & second);
template<class Value_type>
bool operator!=(boost::intrusive_ptr<Value_type> const & first,
	Value_type * second);
template<class Value_type>
bool operator!=(Value_type * first,
	boost::intrusive_ptr<Value_type> const & second);

template<class Value_type_1,class Value_type_2>
bool equivalent(boost::intrusive_ptr<Value_type_1> const & first,
	boost::intrusive_ptr<Value_type_2> const & second)
{
	Value_type_1 *first_ptr=first.get();
	Value_type_2 *second_ptr=second.get();

	return (((first_ptr==second_ptr))||
		(first_ptr&&second_ptr&&(*first_ptr== *second_ptr)));
}

// forward declaration so that _handle can be used in definitions
class Function;

typedef boost::intrusive_ptr<Function> Function_handle;
void intrusive_ptr_add_ref(Function *);
void intrusive_ptr_release(Function *);

// forward declaration so that _handle can be used in definitions
class Function_variable;

typedef boost::intrusive_ptr<Function_variable> Function_variable_handle;
void intrusive_ptr_add_ref(Function_variable *);
void intrusive_ptr_release(Function_variable *);

#endif /* !defined (__FUNCTION_BASE_HPP__) */
<commit_msg>Was missing an include.<commit_after>//******************************************************************************
// FILE : function_base.hpp
//
// LAST MODIFIED : 11 November 2004
//
// DESCRIPTION :
// Basic declarations and #defines for functions.
//
// ???DB.  17Jan04
//   _handle is a bit of a misnomer for smart pointers because the thing about
//   handles is that they don't provide operator-> or operator*
//   (Alexandrescu p.161)
//==============================================================================
#if !defined (__FUNCTION_BASE_HPP__)
#define __FUNCTION_BASE_HPP__

#include <iostream>
#include <stdexcept>

//#define BEFORE_CACHING

//#define EXPORT_IMPLEMENTED
//#define ONE_TEMPLATE_DEFINITION_IMPLEMENTED

#if defined (EXPORT_IMPLEMENTED)
#define EXPORT export
#define ONE_TEMPLATE_DEFINITION_IMPLEMENTED
#else // defined (EXPORT_IMPLEMENTED)
#define EXPORT
#endif // defined (EXPORT_IMPLEMENTED)

const bool Assert_on=true;

template<class Assertion,class Exception>inline void Assert(
	Assertion assertion,Exception exception)
{
	if (Assert_on&&!(assertion))
	{
		std::cerr << exception.what() << std::endl;
		throw exception;
	}
}

#include <string>

typedef std::string * string_handle;
	//???DB.  Replace with smart pointer or return reference?
	//???DB.  At present big probability of memory leak or segmentation fault

typedef unsigned int Function_size_type;

typedef double Scalar;

#include "boost/numeric/ublas/matrix.hpp"
#include "boost/numeric/ublas/vector.hpp"
#include "boost/numeric/ublas/io.hpp"

namespace ublas = boost::numeric::ublas;

// use column_major so that can use lapack=boost::numeric::bindings::lapack
typedef ublas::matrix<Scalar,ublas::column_major> Matrix;
typedef ublas::vector<Scalar> Vector;

#include "boost/intrusive_ptr.hpp"

// intentional ambiguity to prevent use of boost::intrusive_ptr::operator==
//   Use equivalent instead
template<class Value_type_1,class Value_type_2>
bool operator==(boost::intrusive_ptr<Value_type_1> const & first,
	boost::intrusive_ptr<Value_type_2> const & second);
template<class Value_type>
bool operator==(boost::intrusive_ptr<Value_type> const & first,
	Value_type * second);
template<class Value_type>
bool operator==(Value_type * first,
	boost::intrusive_ptr<Value_type> const & second);

// intentional ambiguity to prevent use of boost::intrusive_ptr::operator!=
//   Use !equivalent instead
template<class Value_type_1,class Value_type_2>
bool operator!=(boost::intrusive_ptr<Value_type_1> const & first,
	boost::intrusive_ptr<Value_type_2> const & second);
template<class Value_type>
bool operator!=(boost::intrusive_ptr<Value_type> const & first,
	Value_type * second);
template<class Value_type>
bool operator!=(Value_type * first,
	boost::intrusive_ptr<Value_type> const & second);

template<class Value_type_1,class Value_type_2>
bool equivalent(boost::intrusive_ptr<Value_type_1> const & first,
	boost::intrusive_ptr<Value_type_2> const & second)
{
	Value_type_1 *first_ptr=first.get();
	Value_type_2 *second_ptr=second.get();

	return (((first_ptr==second_ptr))||
		(first_ptr&&second_ptr&&(*first_ptr== *second_ptr)));
}

// forward declaration so that _handle can be used in definitions
class Function;

typedef boost::intrusive_ptr<Function> Function_handle;
void intrusive_ptr_add_ref(Function *);
void intrusive_ptr_release(Function *);

// forward declaration so that _handle can be used in definitions
class Function_variable;

typedef boost::intrusive_ptr<Function_variable> Function_variable_handle;
void intrusive_ptr_add_ref(Function_variable *);
void intrusive_ptr_release(Function_variable *);

#endif /* !defined (__FUNCTION_BASE_HPP__) */
<|endoftext|>