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

#include <qt/clientmodel.h>

#include <qt/bantablemodel.h>
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
#include <qt/peertablemodel.h>

#include <chain.h>
#include <chainparams.h>
#include <checkpoints.h>
#include <clientversion.h>
#include <validation.h>
#include <net.h>
#include <txmempool.h>
#include <ui_interface.h>
#include <util.h>
#include <warnings.h>

#include <stdint.h>

#include <QDebug>
#include <QTimer>

class CBlockIndex;

static int64_t nLastHeaderTipUpdateNotification = 0;
static int64_t nLastBlockTipUpdateNotification = 0;

ClientModel::ClientModel(OptionsModel *_optionsModel, QObject *parent) :
    QObject(parent),
    optionsModel(_optionsModel),
    peerTableModel(0),
    banTableModel(0),
    pollTimer(0)
{
    cachedBestHeaderHeight = -1;
    cachedBestHeaderTime = -1;
    peerTableModel = new PeerTableModel(this);
    banTableModel = new BanTableModel(this);
    pollTimer = new QTimer(this);
    connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));
    pollTimer->start(MODEL_UPDATE_DELAY);

    versionOutDated = false;

    subscribeToCoreSignals();
}

ClientModel::~ClientModel()
{
    unsubscribeFromCoreSignals();
}

int ClientModel::getNumConnections(unsigned int flags) const
{
    CConnman::NumConnections connections = CConnman::CONNECTIONS_NONE;

    if(flags == CONNECTIONS_IN)
        connections = CConnman::CONNECTIONS_IN;
    else if (flags == CONNECTIONS_OUT)
        connections = CConnman::CONNECTIONS_OUT;
    else if (flags == CONNECTIONS_ALL)
        connections = CConnman::CONNECTIONS_ALL;

    if(g_connman)
         return g_connman->GetNodeCount(connections);
    return 0;
}

int ClientModel::getNumBlocks() const
{
    LOCK(cs_main);
    return chainActive.Height();
}

int ClientModel::getHeaderTipHeight() const
{
    if (cachedBestHeaderHeight == -1) {
        // make sure we initially populate the cache via a cs_main lock
        // otherwise we need to wait for a tip update
        LOCK(cs_main);
        if (pindexBestHeader) {
            cachedBestHeaderHeight = pindexBestHeader->nHeight;
            cachedBestHeaderTime = pindexBestHeader->GetBlockTime();
        }
    }
    return cachedBestHeaderHeight;
}

int64_t ClientModel::getHeaderTipTime() const
{
    if (cachedBestHeaderTime == -1) {
        LOCK(cs_main);
        if (pindexBestHeader) {
            cachedBestHeaderHeight = pindexBestHeader->nHeight;
            cachedBestHeaderTime = pindexBestHeader->GetBlockTime();
        }
    }
    return cachedBestHeaderTime;
}

quint64 ClientModel::getTotalBytesRecv() const
{
    if(!g_connman)
        return 0;
    return g_connman->GetTotalBytesRecv();
}

quint64 ClientModel::getTotalBytesSent() const
{
    if(!g_connman)
        return 0;
    return g_connman->GetTotalBytesSent();
}

QDateTime ClientModel::getLastBlockDate() const
{
    LOCK(cs_main);

    if (chainActive.Tip())
        return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime());

    return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network
}

long ClientModel::getMempoolSize() const
{
    return mempool.size();
}

size_t ClientModel::getMempoolDynamicUsage() const
{
    return mempool.DynamicMemoryUsage();
}

double ClientModel::getVerificationProgress(const CBlockIndex *tipIn) const
{
    CBlockIndex *tip = const_cast<CBlockIndex *>(tipIn);
    if (!tip)
    {
        LOCK(cs_main);
        tip = chainActive.Tip();
    }
    return GuessVerificationProgress(Params().TxData(), tip);
}

void ClientModel::updateTimer()
{
    // no locking required at this point
    // the following calls will acquire the required lock
    Q_EMIT mempoolSizeChanged(getMempoolSize(), getMempoolDynamicUsage());
    Q_EMIT bytesChanged(getTotalBytesRecv(), getTotalBytesSent());

}

void ClientModel::updateNumConnections(int numConnections)
{
    Q_EMIT numConnectionsChanged(numConnections);
}

void ClientModel::updateNetworkActive(bool networkActive)
{
    Q_EMIT networkActiveChanged(networkActive);
}

void ClientModel::updateAlert()
{
    Q_EMIT alertsChanged(getStatusBarWarnings());
}

bool ClientModel::inInitialBlockDownload() const
{
    return IsInitialBlockDownload();
}

void ClientModel::updateBlockchainStatus(int status)
{
    Q_EMIT BlockchainStatusChanged(status);
}

enum BlockSource ClientModel::getBlockSource() const
{
    if (fReindex)
        return BLOCK_SOURCE_REINDEX;
    else if (fImporting)
        return BLOCK_SOURCE_DISK;
    else if (getNumConnections() > 0)
        return BLOCK_SOURCE_NETWORK;

    return BLOCK_SOURCE_NONE;
}

void ClientModel::setNetworkActive(bool active)
{
    if (g_connman) {
         g_connman->SetNetworkActive(active);
    }
}

bool ClientModel::getNetworkActive() const
{
    if (g_connman) {
        return g_connman->GetNetworkActive();
    }
    return false;
}

QString ClientModel::getStatusBarWarnings() const
{
    return QString::fromStdString(GetWarnings("gui"));
}

OptionsModel *ClientModel::getOptionsModel()
{
    return optionsModel;
}

PeerTableModel *ClientModel::getPeerTableModel()
{
    return peerTableModel;
}

BanTableModel *ClientModel::getBanTableModel()
{
    return banTableModel;
}

QString ClientModel::formatFullVersion() const
{
    return QString::fromStdString(FormatFullVersion());
}

QString ClientModel::formatSubVersion() const
{
    return QString::fromStdString(strSubVersion);
}

bool ClientModel::isReleaseVersion() const
{
    return CLIENT_VERSION_IS_RELEASE;
}

QString ClientModel::formatClientStartupTime() const
{
    return QDateTime::fromTime_t(GetStartupTime()).toString();
}

QString ClientModel::dataDir() const
{
    return GUIUtil::boostPathToQString(GetDataDir());
}

void ClientModel::updateBanlist()
{
    banTableModel->refresh();
}

// Handlers for core signals
static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress)
{
    // emits signal "showProgress"
    QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection,
                              Q_ARG(QString, QString::fromStdString(title)),
                              Q_ARG(int, nProgress));
}

static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
{
    // Too noisy: qDebug() << "NotifyNumConnectionsChanged: " + QString::number(newNumConnections);
    QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
                              Q_ARG(int, newNumConnections));
}

static void NotifyNetworkActiveChanged(ClientModel *clientmodel, bool networkActive)
{
    QMetaObject::invokeMethod(clientmodel, "updateNetworkActive", Qt::QueuedConnection,
                              Q_ARG(bool, networkActive));
}

static void NotifyAlertChanged(ClientModel *clientmodel)
{
    qDebug() << "NotifyAlertChanged";
    QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection);
}

static void NotifyBlockchainStatusChanged(ClientModel *clientmodel, int newStatus)
{
    qDebug() << "NotifyBlockchainStatusChanged: " + QString::number(newStatus);
    QMetaObject::invokeMethod(clientmodel, "updateBlockchainStatus", Qt::QueuedConnection,
                              Q_ARG(int, newStatus));
}

static void BannedListChanged(ClientModel *clientmodel)
{
    qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__);
    QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection);
}

static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex, bool fHeader)
{
    // lock free async UI updates in case we have a new block tip
    // during initial sync, only update the UI if the last update
    // was > 250ms (MODEL_UPDATE_DELAY) ago
    int64_t now = 0;
    if (initialSync)
        now = GetTimeMillis();

    int64_t& nLastUpdateNotification = fHeader ? nLastHeaderTipUpdateNotification : nLastBlockTipUpdateNotification;

    if (fHeader) {
        // cache best headers time and height to reduce future cs_main locks
        clientmodel->cachedBestHeaderHeight = pIndex->nHeight;
        clientmodel->cachedBestHeaderTime = pIndex->GetBlockTime();
    }
    // if we are in-sync, update the UI regardless of last update time
    if (!initialSync || now - nLastUpdateNotification > MODEL_UPDATE_DELAY) {
        //pass an async signal to the UI thread
        QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection,
                                  Q_ARG(int, pIndex->nHeight),
                                  Q_ARG(QDateTime, QDateTime::fromTime_t(pIndex->GetBlockTime())),
                                  Q_ARG(double, clientmodel->getVerificationProgress(pIndex)),
                                  Q_ARG(bool, fHeader));
        nLastUpdateNotification = now;
    }
}

bool ClientModel::isNewVersionAvailable()
{
    //Connect to default tor node
    QNetworkProxy proxy;
    proxy.setType(QNetworkProxy::Socks5Proxy);
    proxy.setHostName("127.0.0.1");
    proxy.setPort(9081);

    QUrl url("https://deeponion.org/latestversion.txt");
    qInfo() << url.toString();
    QNetworkRequest request(url);
    QNetworkAccessManager nam;
    nam.setProxy(proxy);
    QNetworkReply * reply = nam.get(request);
    QTimer timer;
    timer.setSingleShot(true);
    timer.start(5000);

    while(timer.isActive()){
        qApp->processEvents();
        if(reply->isFinished()){
            timer.stop();

        //    QMessageBox Msgbox;
        //        Msgbox.setText(reply->readAll());
        //        Msgbox.exec();

            QByteArray response_data = reply->readAll();
            int ver = QString(response_data).toInt();
            if(ver == 0)
            {
                versionStatus = " - not available - ";
                reply->close();
                return false; //Empty response
            }
            if(isNewVersion(ver))
            {
                versionStatus = "outdated</>";
                versionOutDated = true;
            }
            else
            {
                versionStatus = "up to date</>";
                versionOutDated = false;
            }
            reply->close();
            return true;
        }
    }
    //Timeout
    versionStatus = " - not available - ";
    reply->close();
    return false;
}

bool ClientModel::isNewVersion(int ver)
{
   if(ver > CLIENT_VERSION)
       return true;
   else
      return true;// return false;
}

QString ClientModel::VersionStatus()
{
    return versionStatus;
}

bool ClientModel::VersionOutDated()
{
    return versionOutDated;
}

void ClientModel::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
    uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyNetworkActiveChanged.connect(boost::bind(NotifyNetworkActiveChanged, this, _1));
    uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this));
    uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this));
    uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2, false));
    uiInterface.NotifyHeaderTip.connect(boost::bind(BlockTipChanged, this, _1, _2, true));
    uiInterface.NotifyBlockchainStatusChanged.connect(boost::bind(NotifyBlockchainStatusChanged, this, _1));
}

void ClientModel::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
    uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyNetworkActiveChanged.disconnect(boost::bind(NotifyNetworkActiveChanged, this, _1));
    uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this));
    uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this));
    uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, false));
    uiInterface.NotifyHeaderTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, true));
    uiInterface.NotifyBlockchainStatusChanged.disconnect(boost::bind(NotifyBlockchainStatusChanged, this, _1));
}
<commit_msg>remove debugging config<commit_after>// Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <qt/clientmodel.h>

#include <qt/bantablemodel.h>
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
#include <qt/peertablemodel.h>

#include <chain.h>
#include <chainparams.h>
#include <checkpoints.h>
#include <clientversion.h>
#include <validation.h>
#include <net.h>
#include <txmempool.h>
#include <ui_interface.h>
#include <util.h>
#include <warnings.h>

#include <stdint.h>

#include <QDebug>
#include <QTimer>

class CBlockIndex;

static int64_t nLastHeaderTipUpdateNotification = 0;
static int64_t nLastBlockTipUpdateNotification = 0;

ClientModel::ClientModel(OptionsModel *_optionsModel, QObject *parent) :
    QObject(parent),
    optionsModel(_optionsModel),
    peerTableModel(0),
    banTableModel(0),
    pollTimer(0)
{
    cachedBestHeaderHeight = -1;
    cachedBestHeaderTime = -1;
    peerTableModel = new PeerTableModel(this);
    banTableModel = new BanTableModel(this);
    pollTimer = new QTimer(this);
    connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));
    pollTimer->start(MODEL_UPDATE_DELAY);

    versionOutDated = false;

    subscribeToCoreSignals();
}

ClientModel::~ClientModel()
{
    unsubscribeFromCoreSignals();
}

int ClientModel::getNumConnections(unsigned int flags) const
{
    CConnman::NumConnections connections = CConnman::CONNECTIONS_NONE;

    if(flags == CONNECTIONS_IN)
        connections = CConnman::CONNECTIONS_IN;
    else if (flags == CONNECTIONS_OUT)
        connections = CConnman::CONNECTIONS_OUT;
    else if (flags == CONNECTIONS_ALL)
        connections = CConnman::CONNECTIONS_ALL;

    if(g_connman)
         return g_connman->GetNodeCount(connections);
    return 0;
}

int ClientModel::getNumBlocks() const
{
    LOCK(cs_main);
    return chainActive.Height();
}

int ClientModel::getHeaderTipHeight() const
{
    if (cachedBestHeaderHeight == -1) {
        // make sure we initially populate the cache via a cs_main lock
        // otherwise we need to wait for a tip update
        LOCK(cs_main);
        if (pindexBestHeader) {
            cachedBestHeaderHeight = pindexBestHeader->nHeight;
            cachedBestHeaderTime = pindexBestHeader->GetBlockTime();
        }
    }
    return cachedBestHeaderHeight;
}

int64_t ClientModel::getHeaderTipTime() const
{
    if (cachedBestHeaderTime == -1) {
        LOCK(cs_main);
        if (pindexBestHeader) {
            cachedBestHeaderHeight = pindexBestHeader->nHeight;
            cachedBestHeaderTime = pindexBestHeader->GetBlockTime();
        }
    }
    return cachedBestHeaderTime;
}

quint64 ClientModel::getTotalBytesRecv() const
{
    if(!g_connman)
        return 0;
    return g_connman->GetTotalBytesRecv();
}

quint64 ClientModel::getTotalBytesSent() const
{
    if(!g_connman)
        return 0;
    return g_connman->GetTotalBytesSent();
}

QDateTime ClientModel::getLastBlockDate() const
{
    LOCK(cs_main);

    if (chainActive.Tip())
        return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime());

    return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network
}

long ClientModel::getMempoolSize() const
{
    return mempool.size();
}

size_t ClientModel::getMempoolDynamicUsage() const
{
    return mempool.DynamicMemoryUsage();
}

double ClientModel::getVerificationProgress(const CBlockIndex *tipIn) const
{
    CBlockIndex *tip = const_cast<CBlockIndex *>(tipIn);
    if (!tip)
    {
        LOCK(cs_main);
        tip = chainActive.Tip();
    }
    return GuessVerificationProgress(Params().TxData(), tip);
}

void ClientModel::updateTimer()
{
    // no locking required at this point
    // the following calls will acquire the required lock
    Q_EMIT mempoolSizeChanged(getMempoolSize(), getMempoolDynamicUsage());
    Q_EMIT bytesChanged(getTotalBytesRecv(), getTotalBytesSent());

}

void ClientModel::updateNumConnections(int numConnections)
{
    Q_EMIT numConnectionsChanged(numConnections);
}

void ClientModel::updateNetworkActive(bool networkActive)
{
    Q_EMIT networkActiveChanged(networkActive);
}

void ClientModel::updateAlert()
{
    Q_EMIT alertsChanged(getStatusBarWarnings());
}

bool ClientModel::inInitialBlockDownload() const
{
    return IsInitialBlockDownload();
}

void ClientModel::updateBlockchainStatus(int status)
{
    Q_EMIT BlockchainStatusChanged(status);
}

enum BlockSource ClientModel::getBlockSource() const
{
    if (fReindex)
        return BLOCK_SOURCE_REINDEX;
    else if (fImporting)
        return BLOCK_SOURCE_DISK;
    else if (getNumConnections() > 0)
        return BLOCK_SOURCE_NETWORK;

    return BLOCK_SOURCE_NONE;
}

void ClientModel::setNetworkActive(bool active)
{
    if (g_connman) {
         g_connman->SetNetworkActive(active);
    }
}

bool ClientModel::getNetworkActive() const
{
    if (g_connman) {
        return g_connman->GetNetworkActive();
    }
    return false;
}

QString ClientModel::getStatusBarWarnings() const
{
    return QString::fromStdString(GetWarnings("gui"));
}

OptionsModel *ClientModel::getOptionsModel()
{
    return optionsModel;
}

PeerTableModel *ClientModel::getPeerTableModel()
{
    return peerTableModel;
}

BanTableModel *ClientModel::getBanTableModel()
{
    return banTableModel;
}

QString ClientModel::formatFullVersion() const
{
    return QString::fromStdString(FormatFullVersion());
}

QString ClientModel::formatSubVersion() const
{
    return QString::fromStdString(strSubVersion);
}

bool ClientModel::isReleaseVersion() const
{
    return CLIENT_VERSION_IS_RELEASE;
}

QString ClientModel::formatClientStartupTime() const
{
    return QDateTime::fromTime_t(GetStartupTime()).toString();
}

QString ClientModel::dataDir() const
{
    return GUIUtil::boostPathToQString(GetDataDir());
}

void ClientModel::updateBanlist()
{
    banTableModel->refresh();
}

// Handlers for core signals
static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress)
{
    // emits signal "showProgress"
    QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection,
                              Q_ARG(QString, QString::fromStdString(title)),
                              Q_ARG(int, nProgress));
}

static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
{
    // Too noisy: qDebug() << "NotifyNumConnectionsChanged: " + QString::number(newNumConnections);
    QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
                              Q_ARG(int, newNumConnections));
}

static void NotifyNetworkActiveChanged(ClientModel *clientmodel, bool networkActive)
{
    QMetaObject::invokeMethod(clientmodel, "updateNetworkActive", Qt::QueuedConnection,
                              Q_ARG(bool, networkActive));
}

static void NotifyAlertChanged(ClientModel *clientmodel)
{
    qDebug() << "NotifyAlertChanged";
    QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection);
}

static void NotifyBlockchainStatusChanged(ClientModel *clientmodel, int newStatus)
{
    qDebug() << "NotifyBlockchainStatusChanged: " + QString::number(newStatus);
    QMetaObject::invokeMethod(clientmodel, "updateBlockchainStatus", Qt::QueuedConnection,
                              Q_ARG(int, newStatus));
}

static void BannedListChanged(ClientModel *clientmodel)
{
    qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__);
    QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection);
}

static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex, bool fHeader)
{
    // lock free async UI updates in case we have a new block tip
    // during initial sync, only update the UI if the last update
    // was > 250ms (MODEL_UPDATE_DELAY) ago
    int64_t now = 0;
    if (initialSync)
        now = GetTimeMillis();

    int64_t& nLastUpdateNotification = fHeader ? nLastHeaderTipUpdateNotification : nLastBlockTipUpdateNotification;

    if (fHeader) {
        // cache best headers time and height to reduce future cs_main locks
        clientmodel->cachedBestHeaderHeight = pIndex->nHeight;
        clientmodel->cachedBestHeaderTime = pIndex->GetBlockTime();
    }
    // if we are in-sync, update the UI regardless of last update time
    if (!initialSync || now - nLastUpdateNotification > MODEL_UPDATE_DELAY) {
        //pass an async signal to the UI thread
        QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection,
                                  Q_ARG(int, pIndex->nHeight),
                                  Q_ARG(QDateTime, QDateTime::fromTime_t(pIndex->GetBlockTime())),
                                  Q_ARG(double, clientmodel->getVerificationProgress(pIndex)),
                                  Q_ARG(bool, fHeader));
        nLastUpdateNotification = now;
    }
}

bool ClientModel::isNewVersionAvailable()
{
    //Connect to default tor node
    QNetworkProxy proxy;
    proxy.setType(QNetworkProxy::Socks5Proxy);
    proxy.setHostName("127.0.0.1");
    proxy.setPort(9081);

    QUrl url("https://deeponion.org/latestversion.txt");
    qInfo() << url.toString();
    QNetworkRequest request(url);
    QNetworkAccessManager nam;
    nam.setProxy(proxy);
    QNetworkReply * reply = nam.get(request);
    QTimer timer;
    timer.setSingleShot(true);
    timer.start(5000);

    while(timer.isActive()){
        qApp->processEvents();
        if(reply->isFinished()){
            timer.stop();

        //    QMessageBox Msgbox;
        //        Msgbox.setText(reply->readAll());
        //        Msgbox.exec();

            QByteArray response_data = reply->readAll();
            int ver = QString(response_data).toInt();
            if(ver == 0)
            {
                versionStatus = " - not available - ";
                reply->close();
                return false; //Empty response
            }
            if(isNewVersion(ver))
            {
                versionStatus = "outdated</>";
                versionOutDated = true;
            }
            else
            {
                versionStatus = "up to date</>";
                versionOutDated = false;
            }
            reply->close();
            return true;
        }
    }
    //Timeout
    versionStatus = " - not available - ";
    reply->close();
    return false;
}

bool ClientModel::isNewVersion(int ver)
{
   if(ver > CLIENT_VERSION)
       return true;
   else
       return false;
}

QString ClientModel::VersionStatus()
{
    return versionStatus;
}

bool ClientModel::VersionOutDated()
{
    return versionOutDated;
}

void ClientModel::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
    uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyNetworkActiveChanged.connect(boost::bind(NotifyNetworkActiveChanged, this, _1));
    uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this));
    uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this));
    uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2, false));
    uiInterface.NotifyHeaderTip.connect(boost::bind(BlockTipChanged, this, _1, _2, true));
    uiInterface.NotifyBlockchainStatusChanged.connect(boost::bind(NotifyBlockchainStatusChanged, this, _1));
}

void ClientModel::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
    uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyNetworkActiveChanged.disconnect(boost::bind(NotifyNetworkActiveChanged, this, _1));
    uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this));
    uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this));
    uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, false));
    uiInterface.NotifyHeaderTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, true));
    uiInterface.NotifyBlockchainStatusChanged.disconnect(boost::bind(NotifyBlockchainStatusChanged, this, _1));
}
<|endoftext|>


<commit_before>/*
  db2.cc

  DB2 OCI Interface to Qore DBI layer

  Qore Programming Language

  Copyright 2009 Qore Technologies, sro

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "../config.h"
#include <qore/Qore.h>

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <strings.h>
#include <assert.h>
#include <unistd.h>

#include <sqlcli1.h>
#include <sqlutil.h>
#include <sqlenv.h>

#include <memory>
#include <string>

static QoreStringNode *db2_module_init();
static void db2_module_ns_init(QoreNamespace *rns, QoreNamespace *qns);
static void db2_module_delete();

DLLEXPORT char qore_module_name[] = "db2";
DLLEXPORT char qore_module_version[] = PACKAGE_VERSION;
DLLEXPORT char qore_module_description[] = "DB2 database driver";
DLLEXPORT char qore_module_author[] = "Qore Technologies, sro";
DLLEXPORT char qore_module_url[] = "http://www.qoretechnologies.com";
DLLEXPORT int qore_module_api_major = QORE_MODULE_API_MAJOR;
DLLEXPORT int qore_module_api_minor = QORE_MODULE_API_MINOR;
DLLEXPORT qore_module_init_t qore_module_init = db2_module_init;
DLLEXPORT qore_module_ns_init_t qore_module_ns_init = db2_module_ns_init;
DLLEXPORT qore_module_delete_t qore_module_delete = db2_module_delete;
DLLEXPORT qore_license_t qore_module_license = QL_LGPL;

// capabilities of this driver
#define DBI_DB2_CAPS (DBI_CAP_TRANSACTION_MANAGEMENT | DBI_CAP_STORED_PROCEDURES | DBI_CAP_CHARSET_SUPPORT | DBI_CAP_LOB_SUPPORT | DBI_CAP_BIND_BY_VALUE | DBI_CAP_BIND_BY_PLACEHOLDER)

DBIDriver *DBID_DB2 = 0;

static QoreString QoreDB2ClientName;
static QoreString this_hostname;
static const char *this_user = 0;

class QoreDB2Handle {
};

class QoreDB2 {
private:
   SQLHANDLE henv, hdbc;

   // add diagnostic info to exception description string
   DLLLOCAL static void addDiagnostics(SQLSMALLINT htype, SQLHANDLE hndl, QoreStringNode *desc) {
      SQLCHAR message[SQL_MAX_MESSAGE_LENGTH + 1];
      SQLCHAR sqlstate[SQL_SQLSTATE_SIZE + 1];
      SQLINTEGER sqlcode;
      SQLSMALLINT length, i = 1;

      // get multiple field settings of diagnostic record
      while (SQLGetDiagRec(htype, hndl, i, sqlstate, &sqlcode, message, SQL_MAX_MESSAGE_LENGTH + 1, &length) == SQL_SUCCESS) {
	 if (i > 1)
	    desc->concat("; ");
	 desc->sprintf("SQLSTATE: %s, native error code: %d: %s", sqlstate, sqlcode, message);
	 i++;
      }
      if (i == 1)
	 desc->concat("no diagnostic information available");
   }

public:
   DLLLOCAL QoreDB2(const std::string &dbname, const std::string &user, const std::string &pass, ExceptionSink *xsink) : henv(0), hdbc(0) {
      SQLRETURN rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
      if (rc != SQL_SUCCESS) {
	 xsink->raiseException("DBI:DB2:OPEN-ERROR", "error allocating environment handle: SQLAllocHandle() returned %d", rc);
	 return;
      }

      //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_ODBC_VERSION)\n");
      // set environment attributes
      rc = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0);
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_ODBC_VERSION)", xsink))
	 return;

      //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_INFO_APPLNAME)\n");
      rc = SQLSetEnvAttr(henv, SQL_ATTR_INFO_APPLNAME, (void *)QoreDB2ClientName.getBuffer(), 0);
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_INFO_APPLNAME)", xsink))
	 return;

      //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_INFO_WRKSTNNAME)\n");
      rc = SQLSetEnvAttr(henv, SQL_ATTR_INFO_WRKSTNNAME, (void *)this_hostname.getBuffer(), 0);
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_INFO_WRKSTNNAME)", xsink))
	 return;

      //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_INFO_USERID)\n");
      rc = SQLSetEnvAttr(henv, SQL_ATTR_INFO_USERID, (void *)this_user, 0);
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_INFO_USERID)", xsink))
	 return;

      //printd(5, "QoreDB2::QoreDB2() calling SQLAllocHandle(SQL_HANDLE_DBC)\n");
      rc = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLAllocHandle(SQL_HANDLE_DBC)", xsink))
	 return;

      // set connection attributes
      //printd(5, "QoreDB2::QoreDB2() calling SQLSetConnectAttr(SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF)\n");
      rc = SQLSetConnectAttr(hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_OFF, SQL_NTS);
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetConnectAttr(SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF)", xsink))
	 return;

      //printd(5, "QoreDB2::QoreDB2() calling SQLConnect()\n");
      rc = SQLConnect(hdbc, (SQLCHAR *)dbname.c_str(), dbname.size(), (SQLCHAR *)user.c_str(), user.size(), (SQLCHAR *)pass.c_str(), pass.size());
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLConnect()", xsink))
	 return;
   }

   DLLLOCAL ~QoreDB2() {
      if (hdbc) {
	 // TODO: check return value?
	 SQLDisconnect(hdbc);
	 SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
      }

      if (henv) {
	 SQLFreeHandle(SQL_HANDLE_ENV, henv);
      }
   }

   DLLLOCAL int commit(ExceptionSink *xsink) {
      SQLRETURN rc = SQLEndTran(SQL_HANDLE_DBC, hdbc, SQL_COMMIT);
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "SQLEndTran(SQL_COMMIT)", xsink))
	 return -1;
      return 0;
   }

   DLLLOCAL int rollback(ExceptionSink *xsink) {
      SQLRETURN rc = SQLEndTran(SQL_HANDLE_DBC, hdbc, SQL_ROLLBACK);
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "SQLEndTran(SQL_ROLLBACK)", xsink))
	 return -1;
      return 0;
   }

   DLLLOCAL static int checkError(SQLSMALLINT htype, SQLHANDLE hndl, SQLRETURN rc, const char *info, ExceptionSink *xsink) {
      switch (rc) {
	 case SQL_SUCCESS:
	    return 0;

	 case SQL_INVALID_HANDLE:
	    assert(false);
	    return -1;

	 case SQL_ERROR: {
	    QoreStringNode *desc = new QoreStringNode();
	    desc->sprintf("error %d in %s: ", rc, info);
	    addDiagnostics(htype, hndl, desc);
	    xsink->raiseException("DBI:DB2:ERROR", desc);
	    return -1;
	 }

	 case SQL_SUCCESS_WITH_INFO:
	 case SQL_STILL_EXECUTING:
	 case SQL_NEED_DATA:
	 case SQL_NO_DATA_FOUND:
	    return 0;
      }

      QoreStringNode *desc = new QoreStringNode();
      desc->sprintf("unknown error  %d returned in %s: ", rc, info);
      addDiagnostics(htype, hndl, desc);
      xsink->raiseException("DBI:DB2:ERROR", desc);
      return -1;
   }
};

static AbstractQoreNode *db2_exec(Datasource *ds, const QoreString *qstr, const QoreListNode *args, ExceptionSink *xsink) {
   return 0;
}

static AbstractQoreNode *db2_select(Datasource *ds, const QoreString *qstr, const QoreListNode *args, ExceptionSink *xsink) {
   return 0;
}

static AbstractQoreNode *db2_select_rows(Datasource *ds, const QoreString *qstr, const QoreListNode *args, ExceptionSink *xsink) {
   return 0;
}

static int db2_commit(Datasource *ds, ExceptionSink *xsink) {
   return reinterpret_cast<QoreDB2 *>(ds->getPrivateData())->commit(xsink);
}

static int db2_rollback(Datasource *ds, ExceptionSink *xsink) {
   return reinterpret_cast<QoreDB2 *>(ds->getPrivateData())->rollback(xsink);
}

static int db2_open(Datasource *ds, ExceptionSink *xsink) {
   if (!ds->getDBName()) {
      xsink->raiseException("DATASOURCE-MISSING-DBNAME", "missing dbname in datasource connection");
      return -1;
   }

   std::auto_ptr<QoreDB2> db2(new QoreDB2(ds->getDBNameStr(), ds->getUsernameStr(), ds->getPasswordStr(), xsink));
   if (*xsink)
      return -1;

   ds->setPrivateData((void *)db2.release());
   return 0;
}

static int db2_close(Datasource *ds) {
   QORE_TRACE("db2_close()");

   QoreDB2 *d_db2 = (QoreDB2 *)ds->getPrivateData();
   delete d_db2;

   ds->setPrivateData(0);
   return 0;
}

static AbstractQoreNode *db2_get_server_version(Datasource *ds, ExceptionSink *xsink) {
   // get private data structure for connection
   //QoreDB2 *db2 = (QoreDB2 *)ds->getPrivateData();

   return 0;
}

static AbstractQoreNode *db2_get_client_version(const Datasource *ds, ExceptionSink *xsink) {
   return 0;
}

#ifndef HOSTNAMEBUFSIZE
#define HOSTNAMEBUFSIZE 512
#endif

static QoreStringNode *db2_module_init() {
   QORE_TRACE("db2_module_init()");

   QoreDB2ClientName.sprintf("Qore DB2 driver v%s on Qore v%s %s %s", PACKAGE_VERSION, qore_version_string, qore_target_arch, qore_target_os);

   // DB2 API global initialization
   // turn off thread locking in the DB2 API - all locking will be provided by qore
   SQLRETURN rc = SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_PROCESSCTL, (void *)SQL_PROCESSCTL_NOTHREAD, 0);
   if (rc != SQL_SUCCESS) {
      QoreStringNode *err = new QoreStringNode("error initializing DB2 API: SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_PROCESSCTL, (void *)SQL_PROCESSCTL_NOTHREAD, 0) returned %d", rc);
      return err;
   }

   // get username
   this_user = getlogin();
   if (!this_user)
      this_user = "<unknown user>";

   // get hostname
   char buf[HOSTNAMEBUFSIZE + 1];
   this_hostname.set(!gethostname(buf, HOSTNAMEBUFSIZE) ? buf : "<unknown>");

   // register driver with DBI subsystem
   qore_dbi_method_list methods;
   methods.add(QDBI_METHOD_OPEN, db2_open);
   methods.add(QDBI_METHOD_CLOSE, db2_close);
   methods.add(QDBI_METHOD_SELECT, db2_select);
   methods.add(QDBI_METHOD_SELECT_ROWS, db2_select_rows);
   methods.add(QDBI_METHOD_EXEC, db2_exec);
   methods.add(QDBI_METHOD_COMMIT, db2_commit);
   methods.add(QDBI_METHOD_ROLLBACK, db2_rollback);
   methods.add(QDBI_METHOD_GET_SERVER_VERSION, db2_get_server_version);
   methods.add(QDBI_METHOD_GET_CLIENT_VERSION, db2_get_client_version);

   DBID_DB2 = DBI.registerDriver("db2", methods, DBI_DB2_CAPS);

   return 0;
}

static void db2_module_ns_init(QoreNamespace *rns, QoreNamespace *qns) {
   QORE_TRACE("db2_module_ns_init()");
   // nothing to do at the moment
}

static void db2_module_delete() {
   QORE_TRACE("db2_module_delete()");
}
<commit_msg>initial support for executing queries<commit_after>/*
  db2.cc

  DB2 OCI Interface to Qore DBI layer

  Qore Programming Language

  Copyright 2009 Qore Technologies, sro

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "../config.h"
#include <qore/Qore.h>

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <strings.h>
#include <assert.h>
#include <unistd.h>

#include <sqlcli1.h>
#include <sqlutil.h>
#include <sqlenv.h>

#include <memory>
#include <string>

static QoreStringNode *db2_module_init();
static void db2_module_ns_init(QoreNamespace *rns, QoreNamespace *qns);
static void db2_module_delete();

DLLEXPORT char qore_module_name[] = "db2";
DLLEXPORT char qore_module_version[] = PACKAGE_VERSION;
DLLEXPORT char qore_module_description[] = "DB2 database driver";
DLLEXPORT char qore_module_author[] = "Qore Technologies, sro";
DLLEXPORT char qore_module_url[] = "http://www.qoretechnologies.com";
DLLEXPORT int qore_module_api_major = QORE_MODULE_API_MAJOR;
DLLEXPORT int qore_module_api_minor = QORE_MODULE_API_MINOR;
DLLEXPORT qore_module_init_t qore_module_init = db2_module_init;
DLLEXPORT qore_module_ns_init_t qore_module_ns_init = db2_module_ns_init;
DLLEXPORT qore_module_delete_t qore_module_delete = db2_module_delete;
DLLEXPORT qore_license_t qore_module_license = QL_LGPL;

// capabilities of this driver
#define DBI_DB2_CAPS (DBI_CAP_TRANSACTION_MANAGEMENT | DBI_CAP_STORED_PROCEDURES | DBI_CAP_CHARSET_SUPPORT | DBI_CAP_LOB_SUPPORT | DBI_CAP_BIND_BY_VALUE | DBI_CAP_BIND_BY_PLACEHOLDER)

DBIDriver *DBID_DB2 = 0;

static QoreString QoreDB2ClientName;
static QoreString this_hostname;
static const char *this_user = 0;

#define QORE_DB2_MAX_COL_NAME_LEN 128

//class QoreDB2Handle {};

class QoreDB2 {
private:
   SQLHANDLE henv, hdbc;

   // add diagnostic info to exception description string
   DLLLOCAL static void addDiagnostics(SQLSMALLINT htype, SQLHANDLE hndl, QoreStringNode *desc) {
      SQLCHAR message[SQL_MAX_MESSAGE_LENGTH + 1];
      SQLCHAR sqlstate[SQL_SQLSTATE_SIZE + 1];
      SQLINTEGER sqlcode;
      SQLSMALLINT length, i = 1;

      // get multiple field settings of diagnostic record
      while (SQLGetDiagRec(htype, hndl, i, sqlstate, &sqlcode, message, SQL_MAX_MESSAGE_LENGTH + 1, &length) == SQL_SUCCESS) {
	 if (i > 1)
	    desc->concat("; ");
	 desc->sprintf("SQLSTATE: %s, native error code: %d: %s", sqlstate, sqlcode, message);
	 i++;
      }
      if (i == 1)
	 desc->concat("no diagnostic information available");
   }

public:
   DLLLOCAL QoreDB2(const std::string &dbname, const std::string &user, const std::string &pass, ExceptionSink *xsink) : henv(0), hdbc(0) {
      SQLRETURN rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
      if (rc != SQL_SUCCESS) {
	 xsink->raiseException("DBI:DB2:OPEN-ERROR", "error allocating environment handle: SQLAllocHandle() returned %d", rc);
	 return;
      }

      //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_ODBC_VERSION)\n");
      // set environment attributes
      rc = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0);
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_ODBC_VERSION)", xsink))
	 return;

      //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_INFO_APPLNAME)\n");
      rc = SQLSetEnvAttr(henv, SQL_ATTR_INFO_APPLNAME, (void *)QoreDB2ClientName.getBuffer(), 0);
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_INFO_APPLNAME)", xsink))
	 return;

      //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_INFO_WRKSTNNAME)\n");
      rc = SQLSetEnvAttr(henv, SQL_ATTR_INFO_WRKSTNNAME, (void *)this_hostname.getBuffer(), 0);
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_INFO_WRKSTNNAME)", xsink))
	 return;

      //printd(5, "QoreDB2::QoreDB2() calling SQLSetEnvAttr(SQL_ATTR_INFO_USERID)\n");
      rc = SQLSetEnvAttr(henv, SQL_ATTR_INFO_USERID, (void *)this_user, 0);
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetEnvAttr(SQL_ATTR_INFO_USERID)", xsink))
	 return;

      //printd(5, "QoreDB2::QoreDB2() calling SQLAllocHandle(SQL_HANDLE_DBC)\n");
      rc = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLAllocHandle(SQL_HANDLE_DBC)", xsink))
	 return;

      // set connection attributes
      //printd(5, "QoreDB2::QoreDB2() calling SQLSetConnectAttr(SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF)\n");
      rc = SQLSetConnectAttr(hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_OFF, SQL_NTS);
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLSetConnectAttr(SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF)", xsink))
	 return;

      //printd(5, "QoreDB2::QoreDB2() calling SQLConnect()\n");
      rc = SQLConnect(hdbc, (SQLCHAR *)dbname.c_str(), dbname.size(), (SQLCHAR *)user.c_str(), user.size(), (SQLCHAR *)pass.c_str(), pass.size());
      if (QoreDB2::checkError(SQL_HANDLE_ENV, henv, rc, "open: SQLConnect()", xsink))
	 return;
   }

   DLLLOCAL ~QoreDB2() {
      if (hdbc) {
	 // TODO: check return value?
	 SQLDisconnect(hdbc);
	 SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
      }

      if (henv) {
	 SQLFreeHandle(SQL_HANDLE_ENV, henv);
      }
   }

   DLLLOCAL int commit(ExceptionSink *xsink) {
      SQLRETURN rc = SQLEndTran(SQL_HANDLE_DBC, hdbc, SQL_COMMIT);
      if (QoreDB2::checkError(SQL_HANDLE_DBC, hdbc, rc, "SQLEndTran(SQL_COMMIT)", xsink))
	 return -1;
      return 0;
   }

   DLLLOCAL int rollback(ExceptionSink *xsink) {
      SQLRETURN rc = SQLEndTran(SQL_HANDLE_DBC, hdbc, SQL_ROLLBACK);
      if (QoreDB2::checkError(SQL_HANDLE_DBC, hdbc, rc, "SQLEndTran(SQL_ROLLBACK)", xsink))
	 return -1;
      return 0;
   }

   DLLLOCAL AbstractQoreNode *select(const QoreString &sql, const QoreListNode *args, ExceptionSink *xsink) {
      SQLHANDLE hstmt;
      SQLRETURN rc = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
      if (QoreDB2::checkError(SQL_HANDLE_DBC, henv, rc, "select: SQLAllocHandle(SQL_HANDLE_STMT)", xsink))
	 return 0;

      // free handle on block exit
      ON_BLOCK_EXIT(SQLFreeHandle, SQL_HANDLE_STMT, hstmt);

      // prepare the statement
      rc = SQLPrepare(hstmt, (SQLCHAR*)sql.getBuffer(), SQL_NTS);
      if (QoreDB2::checkError(SQL_HANDLE_STMT, hstmt, rc, "select: SQLPrepare()", xsink))
	 return 0;

      rc = SQLExecute(hstmt);
      if (QoreDB2::checkError(SQL_HANDLE_STMT, hstmt, rc, "select: SQLExecute()", xsink))
	 return 0;

      SQLSMALLINT cols;
      rc = SQLNumResultCols(hstmt, &cols);
      if (QoreDB2::checkError(SQL_HANDLE_STMT, hstmt, rc, "select: SQLNumResultCols()", xsink))
	 return 0;

      printd(0, "QoreDB2::select() query returned %d columns\n", (int)cols);

      for (int i = 0; i < cols; ++i) {
	 SQLSMALLINT colNameLen;
	 SQLSMALLINT colType;
	 SQLUINTEGER colSize;
	 SQLSMALLINT colScale;
	 char cname[QORE_DB2_MAX_COL_NAME_LEN + 1];

	 rc = SQLDescribeCol(hstmt, (SQLSMALLINT)(i + 1), (SQLCHAR*)cname, sizeof(cname), &colNameLen, &colType, &colSize, &colScale, 0);
	 if (QoreDB2::checkError(SQL_HANDLE_STMT, hstmt, rc, "select: SQLDescribeCol()", xsink))
	    return 0;

	 printd(0, "column %d/%d: %s: type=%d size=%d scale=%d\n", i, cols, cname, colType, colSize, colScale);
      }

      return 0;
   }

   DLLLOCAL AbstractQoreNode *exec(const QoreString &sql, const QoreListNode *args, ExceptionSink *xsink) {
      return 0;
   }

   DLLLOCAL AbstractQoreNode *select_rows(const QoreString &sql, const QoreListNode *args, ExceptionSink *xsink) {
      return 0;
   }

   DLLLOCAL static int checkError(SQLSMALLINT htype, SQLHANDLE hndl, SQLRETURN rc, const char *info, ExceptionSink *xsink) {
      switch (rc) {
	 case SQL_SUCCESS:
	    return 0;

	 case SQL_INVALID_HANDLE:
	    assert(false);
	    return -1;

	 case SQL_ERROR: {
	    QoreStringNode *desc = new QoreStringNode();
	    desc->sprintf("error %d in %s: ", rc, info);
	    addDiagnostics(htype, hndl, desc);
	    xsink->raiseException("DBI:DB2:ERROR", desc);
	    return -1;
	 }

	 case SQL_SUCCESS_WITH_INFO:
	 case SQL_STILL_EXECUTING:
	 case SQL_NEED_DATA:
	 case SQL_NO_DATA_FOUND:
	    return 0;
      }

      QoreStringNode *desc = new QoreStringNode();
      desc->sprintf("unknown error  %d returned in %s: ", rc, info);
      addDiagnostics(htype, hndl, desc);
      xsink->raiseException("DBI:DB2:ERROR", desc);
      return -1;
   }
};

static AbstractQoreNode *db2_exec(Datasource *ds, const QoreString *qstr, const QoreListNode *args, ExceptionSink *xsink) {
   return reinterpret_cast<QoreDB2 *>(ds->getPrivateData())->exec(*qstr, args, xsink);
}

static AbstractQoreNode *db2_select(Datasource *ds, const QoreString *qstr, const QoreListNode *args, ExceptionSink *xsink) {
   return reinterpret_cast<QoreDB2 *>(ds->getPrivateData())->select(*qstr, args, xsink);
}

static AbstractQoreNode *db2_select_rows(Datasource *ds, const QoreString *qstr, const QoreListNode *args, ExceptionSink *xsink) {
   return reinterpret_cast<QoreDB2 *>(ds->getPrivateData())->select_rows(*qstr, args, xsink);
}

static int db2_commit(Datasource *ds, ExceptionSink *xsink) {
   return reinterpret_cast<QoreDB2 *>(ds->getPrivateData())->commit(xsink);
}

static int db2_rollback(Datasource *ds, ExceptionSink *xsink) {
   return reinterpret_cast<QoreDB2 *>(ds->getPrivateData())->rollback(xsink);
}

static int db2_open(Datasource *ds, ExceptionSink *xsink) {
   if (!ds->getDBName()) {
      xsink->raiseException("DATASOURCE-MISSING-DBNAME", "missing dbname in datasource connection");
      return -1;
   }

   std::auto_ptr<QoreDB2> db2(new QoreDB2(ds->getDBNameStr(), ds->getUsernameStr(), ds->getPasswordStr(), xsink));
   if (*xsink)
      return -1;

   ds->setPrivateData((void *)db2.release());
   return 0;
}

static int db2_close(Datasource *ds) {
   QORE_TRACE("db2_close()");

   QoreDB2 *d_db2 = (QoreDB2 *)ds->getPrivateData();
   delete d_db2;

   ds->setPrivateData(0);
   return 0;
}

static AbstractQoreNode *db2_get_server_version(Datasource *ds, ExceptionSink *xsink) {
   // get private data structure for connection
   //QoreDB2 *db2 = (QoreDB2 *)ds->getPrivateData();

   return 0;
}

static AbstractQoreNode *db2_get_client_version(const Datasource *ds, ExceptionSink *xsink) {
   return 0;
}

#ifndef HOSTNAMEBUFSIZE
#define HOSTNAMEBUFSIZE 512
#endif

static QoreStringNode *db2_module_init() {
   QORE_TRACE("db2_module_init()");

   QoreDB2ClientName.sprintf("Qore DB2 driver v%s on Qore v%s %s %s", PACKAGE_VERSION, qore_version_string, qore_target_arch, qore_target_os);

   // DB2 API global initialization
   // turn off thread locking in the DB2 API - all locking will be provided by qore
   SQLRETURN rc = SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_PROCESSCTL, (void *)SQL_PROCESSCTL_NOTHREAD, 0);
   if (rc != SQL_SUCCESS) {
      QoreStringNode *err = new QoreStringNode("error initializing DB2 API: SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_PROCESSCTL, (void *)SQL_PROCESSCTL_NOTHREAD, 0) returned %d", rc);
      return err;
   }

   // get username
   this_user = getlogin();
   if (!this_user)
      this_user = "<unknown user>";

   // get hostname
   char buf[HOSTNAMEBUFSIZE + 1];
   this_hostname.set(!gethostname(buf, HOSTNAMEBUFSIZE) ? buf : "<unknown>");

   // register driver with DBI subsystem
   qore_dbi_method_list methods;
   methods.add(QDBI_METHOD_OPEN, db2_open);
   methods.add(QDBI_METHOD_CLOSE, db2_close);
   methods.add(QDBI_METHOD_SELECT, db2_select);
   methods.add(QDBI_METHOD_SELECT_ROWS, db2_select_rows);
   methods.add(QDBI_METHOD_EXEC, db2_exec);
   methods.add(QDBI_METHOD_COMMIT, db2_commit);
   methods.add(QDBI_METHOD_ROLLBACK, db2_rollback);
   methods.add(QDBI_METHOD_GET_SERVER_VERSION, db2_get_server_version);
   methods.add(QDBI_METHOD_GET_CLIENT_VERSION, db2_get_client_version);

   DBID_DB2 = DBI.registerDriver("db2", methods, DBI_DB2_CAPS);

   return 0;
}

static void db2_module_ns_init(QoreNamespace *rns, QoreNamespace *qns) {
   QORE_TRACE("db2_module_ns_init()");
   // nothing to do at the moment
}

static void db2_module_delete() {
   QORE_TRACE("db2_module_delete()");
}
<|endoftext|>


<commit_before>#include <iostream>

#include "common/state/ray_config.h"
#include "ray/raylet/raylet.h"
#include "ray/status.h"

#ifndef RAYLET_TEST
int main(int argc, char *argv[]) {
  RAY_CHECK(argc == 9);

  const std::string raylet_socket_name = std::string(argv[1]);
  const std::string store_socket_name = std::string(argv[2]);
  const std::string node_ip_address = std::string(argv[3]);
  const std::string redis_address = std::string(argv[4]);
  int redis_port = std::stoi(argv[5]);
  int num_initial_workers = std::stoi(argv[6]);
  const std::string worker_command = std::string(argv[7]);
  const std::string static_resource_list = std::string(argv[8]);

  // Configuration for the node manager.
  ray::raylet::NodeManagerConfig node_manager_config;
  std::unordered_map<std::string, double> static_resource_conf;
  // Parse the resource list.
  std::istringstream resource_string(static_resource_list);
  std::string resource_name;
  std::string resource_quantity;

  while (std::getline(resource_string, resource_name, ',')) {
    RAY_CHECK(std::getline(resource_string, resource_quantity, ','));
    // TODO(rkn): The line below could throw an exception. What should we do about this?
    static_resource_conf[resource_name] = std::stod(resource_quantity);
  }
  node_manager_config.resource_config =
      ray::raylet::ResourceSet(std::move(static_resource_conf));
  RAY_LOG(INFO) << "Starting raylet with static resource configuration: "
                << node_manager_config.resource_config.ToString();
  node_manager_config.num_initial_workers = num_initial_workers;
  node_manager_config.num_workers_per_process =
      RayConfig::instance().num_workers_per_process();
  // Use a default worker that can execute empty tasks with dependencies.

  std::stringstream worker_command_stream(worker_command);
  std::string token;
  while (getline(worker_command_stream, token, ' ')) {
    node_manager_config.worker_command.push_back(token);
  }

  node_manager_config.heartbeat_period_ms =
      RayConfig::instance().heartbeat_timeout_milliseconds();
  node_manager_config.max_lineage_size = RayConfig::instance().max_lineage_size();

  // Configuration for the object manager.
  ray::ObjectManagerConfig object_manager_config;
  object_manager_config.store_socket_name = store_socket_name;
  object_manager_config.pull_timeout_ms =
      RayConfig::instance().object_manager_pull_timeout_ms();
  object_manager_config.push_timeout_ms =
      RayConfig::instance().object_manager_push_timeout_ms();

  int num_cpus = static_cast<int>(static_resource_conf["CPU"]);
  object_manager_config.max_sends = std::max(1, num_cpus / 4);
  object_manager_config.max_receives = std::max(1, num_cpus / 4);
  object_manager_config.object_chunk_size =
      RayConfig::instance().object_manager_default_chunk_size();

  RAY_LOG(INFO) << "Starting object manager with configuration: \n"
                   "max_sends = "
                << object_manager_config.max_sends << "\n"
                                                      "max_receives = "
                << object_manager_config.max_receives << "\n"
                                                         "object_chunk_size = "
                << object_manager_config.object_chunk_size;

  //  initialize mock gcs & object directory
  auto gcs_client = std::make_shared<ray::gcs::AsyncGcsClient>();
  RAY_LOG(INFO) << "Initializing GCS client "
                << gcs_client->client_table().GetLocalClientId();

  // Initialize the node manager.
  boost::asio::io_service main_service;

  ray::raylet::Raylet server(main_service, raylet_socket_name, node_ip_address,
                             redis_address, redis_port, node_manager_config,
                             object_manager_config, gcs_client);

  // Destroy the Raylet on a SIGTERM. The pointer to main_service is
  // guaranteed to be valid since this function will run the event loop
  // instead of returning immediately.
  auto handler = [&main_service](const boost::system::error_code &error,
                                 int signal_number) { main_service.stop(); };
  boost::asio::signal_set signals(main_service, SIGTERM);
  signals.async_wait(handler);

  main_service.run();
}
#endif
<commit_msg>[xray] Silence some object manager logging (#2437)<commit_after>#include <iostream>

#include "common/state/ray_config.h"
#include "ray/raylet/raylet.h"
#include "ray/status.h"

#ifndef RAYLET_TEST
int main(int argc, char *argv[]) {
  RAY_CHECK(argc == 9);

  const std::string raylet_socket_name = std::string(argv[1]);
  const std::string store_socket_name = std::string(argv[2]);
  const std::string node_ip_address = std::string(argv[3]);
  const std::string redis_address = std::string(argv[4]);
  int redis_port = std::stoi(argv[5]);
  int num_initial_workers = std::stoi(argv[6]);
  const std::string worker_command = std::string(argv[7]);
  const std::string static_resource_list = std::string(argv[8]);

  // Configuration for the node manager.
  ray::raylet::NodeManagerConfig node_manager_config;
  std::unordered_map<std::string, double> static_resource_conf;
  // Parse the resource list.
  std::istringstream resource_string(static_resource_list);
  std::string resource_name;
  std::string resource_quantity;

  while (std::getline(resource_string, resource_name, ',')) {
    RAY_CHECK(std::getline(resource_string, resource_quantity, ','));
    // TODO(rkn): The line below could throw an exception. What should we do about this?
    static_resource_conf[resource_name] = std::stod(resource_quantity);
  }
  node_manager_config.resource_config =
      ray::raylet::ResourceSet(std::move(static_resource_conf));
  RAY_LOG(DEBUG) << "Starting raylet with static resource configuration: "
                 << node_manager_config.resource_config.ToString();
  node_manager_config.num_initial_workers = num_initial_workers;
  node_manager_config.num_workers_per_process =
      RayConfig::instance().num_workers_per_process();
  // Use a default worker that can execute empty tasks with dependencies.

  std::stringstream worker_command_stream(worker_command);
  std::string token;
  while (getline(worker_command_stream, token, ' ')) {
    node_manager_config.worker_command.push_back(token);
  }

  node_manager_config.heartbeat_period_ms =
      RayConfig::instance().heartbeat_timeout_milliseconds();
  node_manager_config.max_lineage_size = RayConfig::instance().max_lineage_size();

  // Configuration for the object manager.
  ray::ObjectManagerConfig object_manager_config;
  object_manager_config.store_socket_name = store_socket_name;
  object_manager_config.pull_timeout_ms =
      RayConfig::instance().object_manager_pull_timeout_ms();
  object_manager_config.push_timeout_ms =
      RayConfig::instance().object_manager_push_timeout_ms();

  int num_cpus = static_cast<int>(static_resource_conf["CPU"]);
  object_manager_config.max_sends = std::max(1, num_cpus / 4);
  object_manager_config.max_receives = std::max(1, num_cpus / 4);
  object_manager_config.object_chunk_size =
      RayConfig::instance().object_manager_default_chunk_size();

  RAY_LOG(DEBUG) << "Starting object manager with configuration: \n"
                 << "max_sends = " << object_manager_config.max_sends << "\n"
                 << "max_receives = " << object_manager_config.max_receives << "\n"
                 << "object_chunk_size = " << object_manager_config.object_chunk_size;

  //  initialize mock gcs & object directory
  auto gcs_client = std::make_shared<ray::gcs::AsyncGcsClient>();
  RAY_LOG(DEBUG) << "Initializing GCS client "
                 << gcs_client->client_table().GetLocalClientId();

  // Initialize the node manager.
  boost::asio::io_service main_service;

  ray::raylet::Raylet server(main_service, raylet_socket_name, node_ip_address,
                             redis_address, redis_port, node_manager_config,
                             object_manager_config, gcs_client);

  // Destroy the Raylet on a SIGTERM. The pointer to main_service is
  // guaranteed to be valid since this function will run the event loop
  // instead of returning immediately.
  auto handler = [&main_service](const boost::system::error_code &error,
                                 int signal_number) { main_service.stop(); };
  boost::asio::signal_set signals(main_service, SIGTERM);
  signals.async_wait(handler);

  main_service.run();
}
#endif
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright 2011-2013 The University of North Carolina at Chapel Hill
 *  All rights reserved.
 *
 *  Licensed under the MADAI Software License. You may obtain a copy of
 *  this license at
 *
 *         https://madai-public.cs.unc.edu/software/license/
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "Paths.h"

namespace madai {

#ifdef WIN32
const char Paths::SEPARATOR = '\\';
#else
const char Paths::SEPARATOR = '/';
#endif

const std::string Paths::DEFAULT_MODEL_OUTPUT_DIRECTORY( "model_output" );

const std::string Paths::DEFAULT_EXPERIMENTAL_RESULTS_DIRECTORY( "experimental_results" );

const std::string Paths::TRACE_DIRECTORY( "trace" );

const std::string Paths::OBSERVABLE_NAMES_FILE( "observable_names.dat" );

const std::string Paths::PARAMETERS_FILE( "parameters.dat" );

const std::string Paths::RESULTS_FILE( "results.dat" );

const std::string Paths::RUNTIME_PARAMETER_FILE( "stat_params.dat" );

const std::string Paths::EMULATOR_STATE_FILE( "emulator_state.dat" );

const std::string Paths::PCA_DECOMPOSITION_FILE( "pca_decomposition.dat" );

const std::string Paths::PARAMETER_PRIORS_FILE( "parameter_priors.dat" );

} // end namespace madai
<commit_msg>Renamed stat_params.dat => settings.dat<commit_after>/*=========================================================================
 *
 *  Copyright 2011-2013 The University of North Carolina at Chapel Hill
 *  All rights reserved.
 *
 *  Licensed under the MADAI Software License. You may obtain a copy of
 *  this license at
 *
 *         https://madai-public.cs.unc.edu/software/license/
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "Paths.h"

namespace madai {

#ifdef WIN32
const char Paths::SEPARATOR = '\\';
#else
const char Paths::SEPARATOR = '/';
#endif

const std::string Paths::DEFAULT_MODEL_OUTPUT_DIRECTORY( "model_output" );

const std::string Paths::DEFAULT_EXPERIMENTAL_RESULTS_DIRECTORY( "experimental_results" );

const std::string Paths::TRACE_DIRECTORY( "trace" );

const std::string Paths::OBSERVABLE_NAMES_FILE( "observable_names.dat" );

const std::string Paths::PARAMETERS_FILE( "parameters.dat" );

const std::string Paths::RESULTS_FILE( "results.dat" );

const std::string Paths::RUNTIME_PARAMETER_FILE( "settings.dat" );

const std::string Paths::EMULATOR_STATE_FILE( "emulator_state.dat" );

const std::string Paths::PCA_DECOMPOSITION_FILE( "pca_decomposition.dat" );

const std::string Paths::PARAMETER_PRIORS_FILE( "parameter_priors.dat" );

} // end namespace madai
<|endoftext|>


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

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

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

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

=========================================================================*/
#include "PtLoad.hh"
#include "vtkMath.hh"
#include "FTensors.hh"

// Description:
// Construct with ModelBounds=(-1,1,-1,1,-1,1), SampleDimensions=(50,50,50),
// and LoadValue = 1.
vtkPointLoad::vtkPointLoad()
{
 this->LoadValue = 1.0;

  this->ModelBounds[0] = -1.0;
  this->ModelBounds[1] = 1.0;
  this->ModelBounds[2] = -1.0;
  this->ModelBounds[3] = 1.0;
  this->ModelBounds[4] = -1.0;
  this->ModelBounds[5] = 1.0;

  this->SampleDimensions[0] = 50;
  this->SampleDimensions[1] = 50;
  this->SampleDimensions[2] = 50;
}

// Description:
// Specify the dimensions of the volume. A stress tensor will be computed for
// each point in the volume.
void vtkPointLoad::SetSampleDimensions(int i, int j, int k)
{
  int dim[3];

  dim[0] = i;
  dim[1] = j;
  dim[2] = k;

  this->SetSampleDimensions(dim);
}

// Description:
// Specify the dimensions of the volume. A stress tensor will be computed for
// each point in the volume.
void vtkPointLoad::SetSampleDimensions(int dim[3])
{
  vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")");

  if ( dim[0] != this->SampleDimensions[0] || dim[1] != SampleDimensions[1] ||
  dim[2] != SampleDimensions[2] )
    {
    for ( int i=0; i<3; i++)
      this->SampleDimensions[i] = (dim[i] > 0 ? dim[i] : 1);
    this->Modified();
    }
}

// Description:
// Specify the region in space over which the tensors are computed. The point
// load is assumed to be applied at top center of the volume.
void vtkPointLoad::SetModelBounds(float xmin, float xmax, float ymin, float ymax, float zmin, float zmax)
{
  if (this->ModelBounds[0] != xmin || this->ModelBounds[1] != xmax ||
  this->ModelBounds[2] != ymin || this->ModelBounds[3] != ymax ||
  this->ModelBounds[4] != zmin || this->ModelBounds[5] != zmax )
    {
    this->Modified();
    this->ModelBounds[0] = xmin;
    this->ModelBounds[1] = xmax;
    this->ModelBounds[2] = ymin;
    this->ModelBounds[3] = ymax;
    this->ModelBounds[4] = zmin;
    this->ModelBounds[5] = zmax;
    }
}

// Description:
// Specify the region in space over which the tensors are computed. The point
// load is assumed to be applied at top center of the volume.
void vtkPointLoad::SetModelBounds(float *bounds)
{
  vtkPointLoad::SetModelBounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]);
}

void vtkPointLoad::Execute()
{
  int ptId, i;
  vtkFloatTensors *newTensors;
  vtkTensor tensor;
  int numPts;
  vtkMath math;

  vtkDebugMacro(<< "Computing point load stress tensors");
//
// Initialize self; create output objects
//
  this->Initialize();

  numPts = this->SampleDimensions[0] * this->SampleDimensions[1]
           * this->SampleDimensions[2];
  newTensors = new vtkFloatTensors(numPts);

  // Compute origin and aspect ratio
  this->SetDimensions(this->GetSampleDimensions());
  for (i=0; i < 3; i++)
    {
    this->Origin[i] = this->ModelBounds[2*i];
    this->AspectRatio[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i])
                           / (this->SampleDimensions[i] - 1);
    }
//
// Traverse all points evaluating implicit function at each point
//
  for (ptId=0; ptId < numPts; ptId++ )
    {
    }
//
// Update self
//
  this->PointData.SetTensors(newTensors);
}

void vtkPointLoad::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkStructuredPointsSource::PrintSelf(os,indent);

  os << indent << "Load Value: " << this->LoadValue << "\n";
  os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", "
               << this->SampleDimensions[1] << ", "
               << this->SampleDimensions[2] << ")\n";
  os << indent << "ModelBounds: \n";
  os << indent << "  Xmin,Xmax: (" << this->ModelBounds[0] << ", " << this->ModelBounds[1] << ")\n";
  os << indent << "  Ymin,Ymax: (" << this->ModelBounds[2] << ", " << this->ModelBounds[3] << ")\n";
  os << indent << "  Zmin,Zmax: (" << this->ModelBounds[4] << ", " << this->ModelBounds[5] << ")\n";
}
<commit_msg>ENH: IMplementation.<commit_after>/*=========================================================================

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

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

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

=========================================================================*/
#include "PtLoad.hh"
#include "vtkMath.hh"
#include "FTensors.hh"

// Description:
// Construct with ModelBounds=(-1,1,-1,1,-1,1), SampleDimensions=(50,50,50),
// and LoadValue = 1.
vtkPointLoad::vtkPointLoad()
{
 this->LoadValue = 1.0;

  this->ModelBounds[0] = -1.0;
  this->ModelBounds[1] = 1.0;
  this->ModelBounds[2] = -1.0;
  this->ModelBounds[3] = 1.0;
  this->ModelBounds[4] = -1.0;
  this->ModelBounds[5] = 1.0;

  this->SampleDimensions[0] = 50;
  this->SampleDimensions[1] = 50;
  this->SampleDimensions[2] = 50;
}

// Description:
// Specify the dimensions of the volume. A stress tensor will be computed for
// each point in the volume.
void vtkPointLoad::SetSampleDimensions(int i, int j, int k)
{
  int dim[3];

  dim[0] = i;
  dim[1] = j;
  dim[2] = k;

  this->SetSampleDimensions(dim);
}

// Description:
// Specify the dimensions of the volume. A stress tensor will be computed for
// each point in the volume.
void vtkPointLoad::SetSampleDimensions(int dim[3])
{
  vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")");

  if ( dim[0] != this->SampleDimensions[0] || dim[1] != SampleDimensions[1] ||
  dim[2] != SampleDimensions[2] )
    {
    for ( int i=0; i<3; i++)
      this->SampleDimensions[i] = (dim[i] > 0 ? dim[i] : 1);
    this->Modified();
    }
}

// Description:
// Specify the region in space over which the tensors are computed. The point
// load is assumed to be applied at top center of the volume.
void vtkPointLoad::SetModelBounds(float xmin, float xmax, float ymin, float ymax, float zmin, float zmax)
{
  if (this->ModelBounds[0] != xmin || this->ModelBounds[1] != xmax ||
  this->ModelBounds[2] != ymin || this->ModelBounds[3] != ymax ||
  this->ModelBounds[4] != zmin || this->ModelBounds[5] != zmax )
    {
    this->Modified();
    this->ModelBounds[0] = xmin;
    this->ModelBounds[1] = xmax;
    this->ModelBounds[2] = ymin;
    this->ModelBounds[3] = ymax;
    this->ModelBounds[4] = zmin;
    this->ModelBounds[5] = zmax;
    }
}

// Description:
// Specify the region in space over which the tensors are computed. The point
// load is assumed to be applied at top center of the volume.
void vtkPointLoad::SetModelBounds(float *bounds)
{
  vtkPointLoad::SetModelBounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]);
}

void vtkPointLoad::Execute()
{
  int ptId, i, j, k;
  vtkFloatTensors *newTensors;
  vtkTensor tensor;
  int numPts;
  vtkMath math;
  float P, pi, twoPi, xP[3], rho, rho2, rho3, rho5, nu;
  float x, x2, y, y2, z, z2, z3, rhoPlusz2, zPlus2rho, txy, txz, tyz;

  vtkDebugMacro(<< "Computing point load stress tensors");
//
// Initialize self; create output objects
//
  this->Initialize();

  numPts = this->SampleDimensions[0] * this->SampleDimensions[1]
           * this->SampleDimensions[2];
  newTensors = new vtkFloatTensors(numPts);

  // Compute origin and aspect ratio
  this->SetDimensions(this->GetSampleDimensions());
  for (i=0; i < 3; i++)
    {
    this->Origin[i] = this->ModelBounds[2*i];
    this->AspectRatio[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i])
                           / (this->SampleDimensions[i] - 1);
    }
//
// Compute the location of the load
//
  xP[0] = (this->ModelBounds[0] + this->ModelBounds[1]) / 2.0; //in center
  xP[1] = (this->ModelBounds[2] + this->ModelBounds[3]) / 2.0;
  xP[2] = this->ModelBounds[5]; // at top of box
//
// Traverse all points evaluating implicit function at each point
//
  twoPi = 2.0*math.Pi();
  P = -this->LoadValue;

  for (k=0; k<this->Dimensions[2]; k++)
    {
    z = this->Origin[2] + k*this->AspectRatio[2];
    for (j=0; j<this->Dimensions[1]; j++)
      {
      y = this->Origin[1] + k*this->AspectRatio[1];
      for (i=0; i<this->Dimensions[0]; i++)
        {
        x = this->Origin[0] + k*this->AspectRatio[0];
        rho = sqrt((x-xP[0])*(x-xP[0]) + (y-xP[1])*(y-xP[1]) +
                   (z-xP[2])*(z-xP[2]));
        rho2 = rho*rho;
        rho3 = rho2*rho;
        rho5 = rho2*rho3;
        nu = (1.0 - 2.0*this->PoissonsRatio);
        x2 = x*x;
        y2 = y*y;
        rhoPlusz2 = (rho + z) * (rho + z);
        zPlus2rho = (2.0*rho + z);

        // normal stresses
        tensor.SetComponent(0,0, P/(twoPi*rho2) * (3.0*z*x2/rho3 -
                     nu*(z/rho - rho/(rho+z) + x2*(zPlus2rho)/(rho*rhoPlusz2))));
        tensor.SetComponent(1,1, P/(twoPi*rho2) * (3.0*z*y2/rho3 -
                     nu*(z/rho - rho/(rho+z) + y2*(zPlus2rho)/(rho*rhoPlusz2))));
        tensor.SetComponent(2,2, 3.0*P*z3/(twoPi*rho5));

        //shear stresses
        txy = P/(twoPi*rho2) * (3.0*x*y*z/rho3 -
                                nu*x*y*(zPlus2rho)/(rho*rhoPlusz2));

        tensor.SetComponent(0,1,txy);
        tensor.SetComponent(1,0,txy);

        txz = 3.0*P*x*z2/(twoPi*rho5);
        tensor.SetComponent(0,2,txz);
        tensor.SetComponent(2,0,txz);

        tyz = 3.0*P*y*z2/(twoPi*rho5);
        tensor.SetComponent(1,2,tyz);
        tensor.SetComponent(2,1,tyz);

        newTensors->InsertNextTensor(tensor);
        }
      }
    }
//
// Update self
//
  this->PointData.SetTensors(newTensors);
}

void vtkPointLoad::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkStructuredPointsSource::PrintSelf(os,indent);

  os << indent << "Load Value: " << this->LoadValue << "\n";
  os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", "
               << this->SampleDimensions[1] << ", "
               << this->SampleDimensions[2] << ")\n";
  os << indent << "ModelBounds: \n";
  os << indent << "  Xmin,Xmax: (" << this->ModelBounds[0] << ", " << this->ModelBounds[1] << ")\n";
  os << indent << "  Ymin,Ymax: (" << this->ModelBounds[2] << ", " << this->ModelBounds[3] << ")\n";
  os << indent << "  Zmin,Zmax: (" << this->ModelBounds[4] << ", " << this->ModelBounds[5] << ")\n";
  os << indent << "Poisson's Ratio: " << this->PoissonsRatio << "\n";

}

<|endoftext|>


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

// include ---------------------------------------------------------------

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif

#ifdef _SVX_OPTPATH_CXX
#ifndef _HEADBAR_HXX //autogen
#include <svtools/headbar.hxx>
#endif
#else
class HeaderBar;
#endif
#ifndef SVX_CONTROLL_FUCUS_HELPER_HXX
#include "ControlFocusHelper.hxx"
#endif

// forward ---------------------------------------------------------------

class SvTabListBox;
namespace svx
{
    class OptHeaderTabListBox;
}
struct OptPath_Impl;

// define ----------------------------------------------------------------

#define SfxPathTabPage SvxPathTabPage

// class SvxPathTabPage --------------------------------------------------

class SvxPathTabPage : public SfxTabPage
{
private:
    FixedText           aTypeText;
    FixedText           aPathText;
    SvxControlFocusHelper aPathCtrl;
    PushButton          aStandardBtn;
    PushButton          aPathBtn;
    FixedLine           aStdBox;

    HeaderBar*                  pHeaderBar;
    ::svx::OptHeaderTabListBox* pPathBox;
    OptPath_Impl*               pImpl;

#ifdef _SVX_OPTPATH_CXX
    DECL_LINK( PathHdl_Impl, PushButton * );
    DECL_LINK( StandardHdl_Impl, PushButton * );

    DECL_LINK( PathSelect_Impl, OptHeaderTabListBox * );
    DECL_LINK( HeaderSelect_Impl, HeaderBar * );
    DECL_LINK( HeaderEndDrag_Impl, HeaderBar * );
#endif

public:
    SvxPathTabPage( Window* pParent, const SfxItemSet& rSet );
    ~SvxPathTabPage();

    static SfxTabPage*  Create( Window* pParent, const SfxItemSet& rSet );
    static USHORT*      GetRanges();

    virtual BOOL        FillItemSet( SfxItemSet& rSet );
    virtual void        Reset( const SfxItemSet& rSet );
    virtual void        FillUserData();
};

#endif

<commit_msg>INTEGRATION: CWS pathoptions01 (1.5.444); FILE MERGED 2006/07/07 04:51:00 pb 1.5.444.1: fix: #i67100# add Get/SetPathList()<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: optpath.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-07-13 12:01:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SVX_OPTPATH_HXX
#define _SVX_OPTPATH_HXX

// include ---------------------------------------------------------------

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif

#ifdef _SVX_OPTPATH_CXX
#ifndef _HEADBAR_HXX //autogen
#include <svtools/headbar.hxx>
#endif
#else
class HeaderBar;
#endif
#ifndef SVX_CONTROLL_FUCUS_HELPER_HXX
#include "ControlFocusHelper.hxx"
#endif

// forward ---------------------------------------------------------------

class SvTabListBox;
namespace svx
{
    class OptHeaderTabListBox;
}
struct OptPath_Impl;

// define ----------------------------------------------------------------

#define SfxPathTabPage SvxPathTabPage

// class SvxPathTabPage --------------------------------------------------

class SvxPathTabPage : public SfxTabPage
{
private:
    FixedText           aTypeText;
    FixedText           aPathText;
    SvxControlFocusHelper aPathCtrl;
    PushButton          aStandardBtn;
    PushButton          aPathBtn;
    FixedLine           aStdBox;

    HeaderBar*                  pHeaderBar;
    ::svx::OptHeaderTabListBox* pPathBox;
    OptPath_Impl*               pImpl;

#ifdef _SVX_OPTPATH_CXX
    DECL_LINK( PathHdl_Impl, PushButton * );
    DECL_LINK( StandardHdl_Impl, PushButton * );

    DECL_LINK( PathSelect_Impl, OptHeaderTabListBox * );
    DECL_LINK( HeaderSelect_Impl, HeaderBar * );
    DECL_LINK( HeaderEndDrag_Impl, HeaderBar * );

    void        GetPathList( USHORT _nPathHandle,
                             String& _rInternalPath, String& _rUserPath, String& _rWritablePath );
    void        SetPathList( USHORT _nPathHandle,
                             const String& _rUserPath, const String& _rWritablePath );
#endif

public:
    SvxPathTabPage( Window* pParent, const SfxItemSet& rSet );
    ~SvxPathTabPage();

    static SfxTabPage*  Create( Window* pParent, const SfxItemSet& rSet );
    static USHORT*      GetRanges();

    virtual BOOL        FillItemSet( SfxItemSet& rSet );
    virtual void        Reset( const SfxItemSet& rSet );
    virtual void        FillUserData();
};

#endif

<|endoftext|>


<commit_before>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;
    MTL M;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);
	// Read Secretfile
    // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF
    Gals Secret;
    printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.Secretfile.c_str());
    Secret=read_Secretfile(F.Secretfile,F);

    std::vector<int> count;
    count=count_galaxies(Secret);
    printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
    for(int i=0;i<8;i++){printf (" type %d number  %d  \n",i, count[i]);}
    //read the three input files
    MTL Targ=read_MTLfile(F.Targfile,F,0,0);
    MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
    MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
    //combine the three input files

    M=Targ;

    printf(" M size %d \n",M.size());
    M.insert(M.end(),SStars.begin(),SStars.end());
    printf(" M size %d \n",M.size());
    M.insert(M.end(),SkyF.begin(),SkyF.end());
    printf(" M size %d \n",M.size());
    F.Ngal=M.size();
    assign_priority_class(M);

    //establish priority classes
    std::vector <int> count_class(M.priority_list.size(),0);
    for(int i;i<M.size();++i){
        if(!M[i].SS&&!M[i].SF){
        count_class[M[i].priority_class]+=1;
        }
    }

    for(int i;i<M.priority_list.size();++i){
        printf("  class  %d  number  %d\n",i,count_class[i]);
    }

    //diagnostic
    int count_ss=0;
    int count_sf=0;
    for(int g=0;g<M.size();++g){
        if(M[g].SS) count_ss++;
        if(M[g].SF) count_sf++;
    }
    printf("  number SS = %d  number SF = %d\n",count_ss,count_sf);

    PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1;
    F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
	pp.get_neighbors(F); pp.compute_fibsofsp(F);

    //P is original list of plates
	Plates P = read_plate_centers(F);

    printf(" future plates %d\n",P.size());
    F.Nplate=P.size();
	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

	// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
	F.cb = create_cb(); // cb=central body
	F.fh = create_fh(); // fh=fiber holder

	//// Collect available galaxies <-> tilefibers --------------------
	// HTM Tree of galaxies
	const double MinTreeSize = 0.01;
	init_time_at(time,"# Start building HTM tree",t);
	htmTree<struct target> T(M,MinTreeSize);
	print_time(time,"# ... took :");//T.stats();

	// For plates/fibers, collect available galaxies; done in parallel
    collect_galaxies_for_all(M,T,P,pp,F);

	// For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
	collect_available_tilefibers(M,P,F);

	//results_on_inputs("doc/figs/",G,P,F,true);

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
    Assignment A(M,F);

	print_time(t,"# Start assignment at : ");

	// Make a plan ----------------------------------------------------
    // Plans whole survey without sky fibers, standard stars
    // assumes maximum number of observations needed for QSOs, LRGs

    simple_assign(M,P,pp,F,A);

    //check to see if any SS or SF are assigned
    int SS_count=0;
    int SF_count=0;
    std::vector <int> class_count(3,0);
    for( int j=0;j<F.Nplate;++j){
        for (int k=0;k<F.Nfiber;++k){
            if(A.TF[j][k]!=-1){
                if(M[A.TF[j][k]].SS)SS_count++;
                if(M[A.TF[j][k]].SF)SF_count++;
                class_count[M[A.TF[j][k]].priority_class]++;
            }
        }
    }
    printf("after simple assign,  SS assigned %d  SF assigned %d\n",SS_count,SF_count);
    printf(" class 0 %d  class 1 %d  class 2 %d\n", class_count[0],class_count[1],class_count[2]);

    //check to see if there are tiles with no galaxies
    //need to keep mapping of old tile list to new tile list
    for (int j=0;j<F.Nplate ;++j){
        bool not_done=true;
        for(int k=0;k<F.Nfiber && not_done;++k){
            if(A.TF[j][k]!=-1){
                A.suborder.push_back(j);
                not_done=false;

            }
        }
    }
    F.NUsedplate=A.suborder.size();
    printf(" Plates after screening %d \n",F.NUsedplate);

    //diagnostic
    /*
    for (int j=0;j<F.NUsedplate;++j){
        int js=A.suborder[j];
        printf("  js = %d  available SF for fibers\n",js);
        for (int k=0;k<10;++k){
            printf(" %d ",P[js].SF_av_gal_fiber[k*500].size());
        }
        printf("\n  petals");
        for (int q=0;q<F.Npetal;++q){
            printf(" %d",P[js].SF_av_gal[q].size());
        }
        printf("\n");
    }
    */

    //if(F.diagnose)diagnostic(M,G,F,A);

    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs

	// Smooth out distribution of free fibers, and increase the number of assignments

	for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly
	for (int i=0; i<1; i++) {
        improve(M,P,pp,F,A);
		redistribute_tf(M,P,pp,F,A);
	}

	print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
    //try assigning SF and SS before real time assignment
    for (int j=0;j<F.NUsedplate;++j){

        int js=A.suborder[j];
        //printf(" before assign_sf_ss js= %d\n",js);
        A.next_plate=js;
        assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile
        //printf("before assign_unused js= %d \n",js);
        assign_unused(js,M,P,pp,F,A);
    }
    if(F.diagnose)diagnostic(M,Secret,F,A);
    init_time_at(time,"# Begin real time assignment",t);

	//Execute plan, updating targets at intervals
    std::vector <int> update_intervals=F.pass_intervals;
    update_intervals.push_back(F.NUsedplate);
    for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate
        printf(" before pass = %d  at %d  tiles\n",i,update_intervals[i]);
        //display_results("doc/figs/",G,P,pp,F,A,true);
        //plan whole survey from this point out
        A.next_plate=F.pass_intervals[i];
        for (int jj=F.pass_intervals[i]; jj<F.NUsedplate; jj++) {
            int j = A.suborder[jj];
            //printf("  next plate is %d \n",j);
            assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF
            assign_unused(j,M,P,pp,F,A);
            //A.next_plate++;
        }
        //update target information for interval i
        //A.next_plate=F.pass_intervals[i];
        for (int jj=update_intervals[i]; jj<update_intervals[i+1]; jj++) {
            //int j = A.suborder[A.next_plate];
            //int js=A.suborder[jj];
            // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
            if (0<=jj-F.Analysis) update_plan_from_one_obs(jj,Secret,M,P,pp,F,A,F.Nplate-1); else printf("\n");
            //A.next_plate++;
        }

        //if(A.next_plate<F.Nplate){
        redistribute_tf(M,P,pp,F,A);
        redistribute_tf(M,P,pp,F,A);
        improve(M,P,pp,F,A);
        redistribute_tf(M,P,pp,F,A);
        //}

        if(F.diagnose)diagnostic(M,Secret,F,A);
    }

	// Results -------------------------------------------------------
    if (F.PrintAscii) for (int j=0; j<F.NUsedplate; j++){
        write_FAtile_ascii(A.suborder[j],F.outDir,M,P,pp,F,A);
    }

    if (F.PrintFits) for (int j=0; j<F.NUsedplate; j++){
        fa_write(A.suborder[j],F.outDir,M,P,pp,F,A); // Write output
    }

	display_results("doc/figs/",Secret,M,P,pp,F,A,true);
	if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane

	print_time(t,"# Finished !... in");

	return(0);

}
<commit_msg>print check of SS SF<commit_after>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;
    MTL M;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);
	// Read Secretfile
    // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF
    Gals Secret;
    printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.Secretfile.c_str());
    Secret=read_Secretfile(F.Secretfile,F);

    std::vector<int> count;
    count=count_galaxies(Secret);
    printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
    for(int i=0;i<8;i++){printf (" type %d number  %d  \n",i, count[i]);}
    //read the three input files
    MTL Targ=read_MTLfile(F.Targfile,F,0,0);
    MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
    MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
    //combine the three input files

    M=Targ;

    printf(" M size %d \n",M.size());
    M.insert(M.end(),SStars.begin(),SStars.end());
    printf(" M size %d \n",M.size());
    M.insert(M.end(),SkyF.begin(),SkyF.end());
    printf(" M size %d \n",M.size());
    F.Ngal=M.size();
    assign_priority_class(M);

    //establish priority classes
    std::vector <int> count_class(M.priority_list.size(),0);
    for(int i;i<M.size();++i){
        if(!M[i].SS&&!M[i].SF){
        count_class[M[i].priority_class]+=1;
        }
    }

    for(int i;i<M.priority_list.size();++i){
        printf("  class  %d  number  %d\n",i,count_class[i]);
    }

    //diagnostic
    int count_ss=0;
    int count_sf=0;
    for(int g=0;g<M.size();++g){
        if(M[g].SS) count_ss++;
        if(M[g].SF) count_sf++;
    }
    printf("  number SS = %d  number SF = %d\n",count_ss,count_sf);

    PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1;
    F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
	pp.get_neighbors(F); pp.compute_fibsofsp(F);

    //P is original list of plates
	Plates P = read_plate_centers(F);

    printf(" future plates %d\n",P.size());
    F.Nplate=P.size();
	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

	// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
	F.cb = create_cb(); // cb=central body
	F.fh = create_fh(); // fh=fiber holder

	//// Collect available galaxies <-> tilefibers --------------------
	// HTM Tree of galaxies
	const double MinTreeSize = 0.01;
	init_time_at(time,"# Start building HTM tree",t);
	htmTree<struct target> T(M,MinTreeSize);
	print_time(time,"# ... took :");//T.stats();

	// For plates/fibers, collect available galaxies; done in parallel
    collect_galaxies_for_all(M,T,P,pp,F);

	// For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
	collect_available_tilefibers(M,P,F);

	//results_on_inputs("doc/figs/",G,P,F,true);

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
    Assignment A(M,F);

	print_time(t,"# Start assignment at : ");

	// Make a plan ----------------------------------------------------
    // Plans whole survey without sky fibers, standard stars
    // assumes maximum number of observations needed for QSOs, LRGs

    simple_assign(M,P,pp,F,A);

    //check to see if any SS or SF are assigned
    int SS_count=0;
    int SF_count=0;
    std::vector <int> class_count(3,0);
    for( int j=0;j<F.Nplate;++j){
        for (int k=0;k<F.Nfiber;++k){
            if(A.TF[j][k]!=-1){
                if(M[A.TF[j][k]].SS)SS_count++;
                if(M[A.TF[j][k]].SF)SF_count++;
                class_count[M[A.TF[j][k]].priority_class]++;
            }
        }
    }
    printf("after simple assign,  SS assigned %d  SF assigned %d\n",SS_count,SF_count);
    printf(" class 0 %d  class 1 %d  class 2 %d\n", class_count[0],class_count[1],class_count[2]);

    //check to see if there are tiles with no galaxies
    //need to keep mapping of old tile list to new tile list
    for (int j=0;j<F.Nplate ;++j){
        bool not_done=true;
        for(int k=0;k<F.Nfiber && not_done;++k){
            if(A.TF[j][k]!=-1){
                A.suborder.push_back(j);
                not_done=false;

            }
        }
    }
    F.NUsedplate=A.suborder.size();
    printf(" Plates after screening %d \n",F.NUsedplate);

    //diagnostic
    /*
    for (int j=0;j<F.NUsedplate;++j){
        int js=A.suborder[j];
        printf("  js = %d  available SF for fibers\n",js);
        for (int k=0;k<10;++k){
            printf(" %d ",P[js].SF_av_gal_fiber[k*500].size());
        }
        printf("\n  petals");
        for (int q=0;q<F.Npetal;++q){
            printf(" %d",P[js].SF_av_gal[q].size());
        }
        printf("\n");
    }
    */

    //if(F.diagnose)diagnostic(M,G,F,A);

    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs

	// Smooth out distribution of free fibers, and increase the number of assignments

	for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly
	for (int i=0; i<1; i++) {
        improve(M,P,pp,F,A);
		redistribute_tf(M,P,pp,F,A);
	}

	print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
    //try assigning SF and SS before real time assignment
    for (int j=0;j<F.NUsedplate;++j){

        int js=A.suborder[j];
        //printf(" before assign_sf_ss js= %d\n",js);
        A.next_plate=js;
        assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile
        //printf("before assign_unused js= %d \n",js);
        assign_unused(js,M,P,pp,F,A);
    }
    if(F.diagnose)diagnostic(M,Secret,F,A);
    init_time_at(time,"# Begin real time assignment",t);

	//Execute plan, updating targets at intervals
    std::vector <int> update_intervals=F.pass_intervals;
    update_intervals.push_back(F.NUsedplate);
    for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate
        printf(" before pass = %d  at %d  tiles\n",i,update_intervals[i]);
        //display_results("doc/figs/",G,P,pp,F,A,true);
        //plan whole survey from this point out
        A.next_plate=F.pass_intervals[i];
        for (int jj=F.pass_intervals[i]; jj<F.NUsedplate; jj++) {
            int j = A.suborder[jj];
            //printf("  next plate is %d \n",j);
            assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF
            assign_unused(j,M,P,pp,F,A);
            //A.next_plate++;
        }
        //update target information for interval i
        //A.next_plate=F.pass_intervals[i];
        for (int jj=update_intervals[i]; jj<update_intervals[i+1]; jj++) {
            //int j = A.suborder[A.next_plate];
            //int js=A.suborder[jj];
            // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
            if (0<=jj-F.Analysis) update_plan_from_one_obs(jj,Secret,M,P,pp,F,A,F.Nplate-1); else printf("\n");
            //A.next_plate++;
        }

        //if(A.next_plate<F.Nplate){
        redistribute_tf(M,P,pp,F,A);
        redistribute_tf(M,P,pp,F,A);
        improve(M,P,pp,F,A);
        redistribute_tf(M,P,pp,F,A);
        //}

        if(F.diagnose)diagnostic(M,Secret,F,A);
    }
    // check on SS and SF

    for(int js=0;js<F.NUsedplate;++js){
        printf("\n js = %d\n",js);
        for (int p=0;p<F.Npetal;++p){
            int count_SS=0;
            int count_SF=0;
            for (int k=0;k<F.Nfbp;++k){
                int kk=pp.fibers_of_sp[p][k];
                int g=A.TF[js][kk];
                if(g!=-1 && M[g].SS)count_SS++;
                if(g!=-1 && M[g].SF)count_SF++;

            }
            printf("  %d  %d   ",count_SS,count_SF);
        }
        printf("\n");
    }

	// Results -------------------------------------------------------
    if (F.PrintAscii) for (int j=0; j<F.NUsedplate; j++){
        write_FAtile_ascii(A.suborder[j],F.outDir,M,P,pp,F,A);
    }

    if (F.PrintFits) for (int j=0; j<F.NUsedplate; j++){
        fa_write(A.suborder[j],F.outDir,M,P,pp,F,A); // Write output
    }

	display_results("doc/figs/",Secret,M,P,pp,F,A,true);
	if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane

	print_time(t,"# Finished !... in");

	return(0);

}
<|endoftext|>