<commit_before>#include "NodeGraphicsObject.hpp"

#include <iostream>
#include <cstdlib>

#include <QtWidgets/QtWidgets>
#include <QtWidgets/QGraphicsEffect>

#include "ConnectionGraphicsObject.hpp"
#include "ConnectionState.hpp"

#include "FlowScene.hpp"
#include "NodePainter.hpp"

#include "Node.hpp"
#include "NodeDataModel.hpp"
#include "NodeConnectionInteraction.hpp"

#include "StyleCollection.hpp"

using QtNodes::NodeGraphicsObject;
using QtNodes::Node;
using QtNodes::FlowScene;

NodeGraphicsObject::
NodeGraphicsObject(FlowScene &scene,
                   Node& node)
  : _scene(scene)
  , _node(node)
  , _proxyWidget(nullptr)
{
  _scene.addItem(this);

  setFlag(QGraphicsItem::ItemDoesntPropagateOpacityToChildren, true);
  setFlag(QGraphicsItem::ItemIsMovable, true);
  setFlag(QGraphicsItem::ItemIsFocusable, true);
  setFlag(QGraphicsItem::ItemIsSelectable, true);
  setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true);

  setCacheMode( QGraphicsItem::DeviceCoordinateCache );

  auto const &nodeStyle = StyleCollection::nodeStyle();

  {
    auto effect = new QGraphicsDropShadowEffect;
    effect->setOffset(4, 4);
    effect->setBlurRadius(20);
    effect->setColor(nodeStyle.ShadowColor);

    setGraphicsEffect(effect);
  }

  setOpacity(nodeStyle.Opacity);

  setAcceptHoverEvents(true);

  embedQWidget();

  // connect to the move signals to emit the move signals in FlowScene
  auto onMoveSlot = [this] {
    _scene.nodeMoved(_node, pos());
  };
  connect(this, &QGraphicsObject::xChanged, this, onMoveSlot);
  connect(this, &QGraphicsObject::yChanged, this, onMoveSlot);
}

NodeGraphicsObject::
~NodeGraphicsObject()
{
  _scene.removeItem(this);
}

Node&
NodeGraphicsObject::
node()
{
  return _node;
}

void
NodeGraphicsObject::
embedQWidget()
{
  NodeGeometry & geom = _node.nodeGeometry();

  if (auto w = _node.nodeDataModel()->embeddedWidget())
  {
    _proxyWidget = new QGraphicsProxyWidget(this);

    _proxyWidget->setWidget(w);

    _proxyWidget->setPreferredWidth(5);

    geom.recalculateSize();

    _proxyWidget->setPos(geom.widgetPosition());

    update();

    _proxyWidget->setOpacity(1.0);
    _proxyWidget->setFlag(QGraphicsItem::ItemIgnoresParentOpacity);
  }
}

QRectF
NodeGraphicsObject::
boundingRect() const
{
  return _node.nodeGeometry().boundingRect();
}

void
NodeGraphicsObject::
setGeometryChanged()
{
  prepareGeometryChange();
}

void
NodeGraphicsObject::
moveConnections() const
{

  NodeState const & nodeState = _node.nodeState();

  auto moveConnections =
    [&](PortType portType)
    {
      auto const & connectionEntries =
        nodeState.getEntries(portType);

      for (auto const & connections : connectionEntries)
      {
        for (auto & con : connections)
          con.second->getConnectionGraphicsObject().move();
      }
    };

  moveConnections(PortType::In);

  moveConnections(PortType::Out);
}

void
NodeGraphicsObject::
paint(QPainter * painter,
      QStyleOptionGraphicsItem const* option,
      QWidget* )
{
  painter->setClipRect(option->exposedRect);

  NodePainter::paint(painter, _node, _scene);
}

QVariant
NodeGraphicsObject::
itemChange(GraphicsItemChange change, const QVariant &value)
{
  if (change == ItemPositionChange && scene())
  {
    moveConnections();
  }

  return QGraphicsItem::itemChange(change, value);
}

void
NodeGraphicsObject::
mousePressEvent(QGraphicsSceneMouseEvent * event)
{
  // deselect all other items after this one is selected
  if (!isSelected() &&
      !(event->modifiers() & Qt::ControlModifier))
  {
    _scene.clearSelection();
  }

  auto clickPort =
    [&](PortType portToCheck)
    {
      NodeGeometry & nodeGeometry = _node.nodeGeometry();

      // TODO do not pass sceneTransform
      int portIndex = nodeGeometry.checkHitScenePoint(portToCheck,
                                                      event->scenePos(),
                                                      sceneTransform());

      if (portIndex != INVALID)
      {
        NodeState const & nodeState = _node.nodeState();

        std::unordered_map<QUuid, Connection*> connections =
          nodeState.connections(portToCheck, portIndex);

        // start dragging existing connection
        if (!connections.empty() && portToCheck == PortType::In)
        {
          auto con = connections.begin()->second;

          NodeConnectionInteraction interaction(_node, *con, _scene);

          interaction.disconnect(portToCheck);
        }
        else // initialize new Connection
        {
          const auto outPolicy = _node.nodeDataModel()->portOutConnectionPolicy(portIndex);
          if (!connections.empty() &&
              portToCheck == PortType::Out &&
              outPolicy == NodeDataModel::ConnectionPolicy::One)
          {
            _scene.deleteConnection( *connections.begin()->second );
          }

          // todo add to FlowScene
          auto connection = _scene.createConnection(portToCheck,
                                                    _node,
                                                    portIndex);

          _node.nodeState().setConnection(portToCheck,
                                          portIndex,
                                          *connection);

          connection->getConnectionGraphicsObject().grabMouse();
        }
      }
    };

  clickPort(PortType::In);
  clickPort(PortType::Out);

  auto pos     = event->pos();
  auto & geom  = _node.nodeGeometry();
  auto & state = _node.nodeState();

  if (geom.resizeRect().contains(QPoint(pos.x(),
                                        pos.y())))
  {
    state.setResizing(true);
  }
}

void
NodeGraphicsObject::
mouseMoveEvent(QGraphicsSceneMouseEvent * event)
{
  auto & geom  = _node.nodeGeometry();
  auto & state = _node.nodeState();

  if (state.resizing())
  {
    auto diff = event->pos() - event->lastPos();

    if (auto w = _node.nodeDataModel()->embeddedWidget())
    {
      prepareGeometryChange();

      auto oldSize = w->size();

      oldSize += QSize(diff.x(), diff.y());

      w->setFixedSize(oldSize);

      _proxyWidget->setMinimumSize(oldSize);
      _proxyWidget->setMaximumSize(oldSize);
      _proxyWidget->setPos(geom.widgetPosition());

      geom.recalculateSize();
      update();

      moveConnections();

      event->accept();
    }
  }
  else
  {
    QGraphicsObject::mouseMoveEvent(event);

    if (event->lastPos() != event->pos())
      moveConnections();

    event->ignore();
  }

  QRectF r = scene()->sceneRect();

  r = r.united(mapToScene(boundingRect()).boundingRect());

  scene()->setSceneRect(r);
}

void
NodeGraphicsObject::
mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
  auto & state = _node.nodeState();

  state.setResizing(false);

  QGraphicsObject::mouseReleaseEvent(event);

  // position connections precisely after fast node move
  moveConnections();
}

void
NodeGraphicsObject::
hoverEnterEvent(QGraphicsSceneHoverEvent * event)
{
  _node.nodeGeometry().setHovered(true);
  update();
  _scene.nodeHovered(node(), event->screenPos());
  event->accept();
}

void
NodeGraphicsObject::
hoverLeaveEvent(QGraphicsSceneHoverEvent * event)
{
  _node.nodeGeometry().setHovered(false);
  update();
  _scene.nodeHoverLeft(node());
  event->accept();
}

void
NodeGraphicsObject::
hoverMoveEvent(QGraphicsSceneHoverEvent * event)
{
  auto pos    = event->pos();
  auto & geom = _node.nodeGeometry();

  if (geom.resizeRect().contains(QPoint(pos.x(),
                                        pos.y())))
  {
    setCursor(QCursor(Qt::SizeFDiagCursor));
  }
  else
  {
    setCursor(QCursor());
  }

  event->accept();
}

void
NodeGraphicsObject::
mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event)
{
  QGraphicsItem::mouseDoubleClickEvent(event);

  _scene.nodeDoubleClicked(node());
}
<commit_msg>Fix Z level problem with overlapped proxy widgets (#82)<commit_after>#include "NodeGraphicsObject.hpp"

#include <iostream>
#include <cstdlib>

#include <QtWidgets/QtWidgets>
#include <QtWidgets/QGraphicsEffect>

#include "ConnectionGraphicsObject.hpp"
#include "ConnectionState.hpp"

#include "FlowScene.hpp"
#include "NodePainter.hpp"

#include "Node.hpp"
#include "NodeDataModel.hpp"
#include "NodeConnectionInteraction.hpp"

#include "StyleCollection.hpp"

using QtNodes::NodeGraphicsObject;
using QtNodes::Node;
using QtNodes::FlowScene;

NodeGraphicsObject::
NodeGraphicsObject(FlowScene &scene,
                   Node& node)
  : _scene(scene)
  , _node(node)
  , _proxyWidget(nullptr)
{
  _scene.addItem(this);

  setFlag(QGraphicsItem::ItemDoesntPropagateOpacityToChildren, true);
  setFlag(QGraphicsItem::ItemIsMovable, true);
  setFlag(QGraphicsItem::ItemIsFocusable, true);
  setFlag(QGraphicsItem::ItemIsSelectable, true);
  setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true);

  setCacheMode( QGraphicsItem::DeviceCoordinateCache );

  auto const &nodeStyle = StyleCollection::nodeStyle();

  {
    auto effect = new QGraphicsDropShadowEffect;
    effect->setOffset(4, 4);
    effect->setBlurRadius(20);
    effect->setColor(nodeStyle.ShadowColor);

    setGraphicsEffect(effect);
  }

  setOpacity(nodeStyle.Opacity);

  setAcceptHoverEvents(true);

  setZValue(0);

  embedQWidget();

  // connect to the move signals to emit the move signals in FlowScene
  auto onMoveSlot = [this] {
    _scene.nodeMoved(_node, pos());
  };
  connect(this, &QGraphicsObject::xChanged, this, onMoveSlot);
  connect(this, &QGraphicsObject::yChanged, this, onMoveSlot);
}

NodeGraphicsObject::
~NodeGraphicsObject()
{
  _scene.removeItem(this);
}

Node&
NodeGraphicsObject::
node()
{
  return _node;
}

void
NodeGraphicsObject::
embedQWidget()
{
  NodeGeometry & geom = _node.nodeGeometry();

  if (auto w = _node.nodeDataModel()->embeddedWidget())
  {
    _proxyWidget = new QGraphicsProxyWidget(this);

    _proxyWidget->setWidget(w);

    _proxyWidget->setPreferredWidth(5);

    geom.recalculateSize();

    _proxyWidget->setPos(geom.widgetPosition());

    update();

    _proxyWidget->setOpacity(1.0);
    _proxyWidget->setFlag(QGraphicsItem::ItemIgnoresParentOpacity);
  }
}

QRectF
NodeGraphicsObject::
boundingRect() const
{
  return _node.nodeGeometry().boundingRect();
}

void
NodeGraphicsObject::
setGeometryChanged()
{
  prepareGeometryChange();
}

void
NodeGraphicsObject::
moveConnections() const
{

  NodeState const & nodeState = _node.nodeState();

  auto moveConnections =
    [&](PortType portType)
    {
      auto const & connectionEntries =
        nodeState.getEntries(portType);

      for (auto const & connections : connectionEntries)
      {
        for (auto & con : connections)
          con.second->getConnectionGraphicsObject().move();
      }
    };

  moveConnections(PortType::In);

  moveConnections(PortType::Out);
}

void
NodeGraphicsObject::
paint(QPainter * painter,
      QStyleOptionGraphicsItem const* option,
      QWidget* )
{
  painter->setClipRect(option->exposedRect);

  NodePainter::paint(painter, _node, _scene);
}

QVariant
NodeGraphicsObject::
itemChange(GraphicsItemChange change, const QVariant &value)
{
  if (change == ItemPositionChange && scene())
  {
    moveConnections();
  }

  return QGraphicsItem::itemChange(change, value);
}

void
NodeGraphicsObject::
mousePressEvent(QGraphicsSceneMouseEvent * event)
{
  // deselect all other items after this one is selected
  if (!isSelected() &&
      !(event->modifiers() & Qt::ControlModifier))
  {
    _scene.clearSelection();
  }

  auto clickPort =
    [&](PortType portToCheck)
    {
      NodeGeometry & nodeGeometry = _node.nodeGeometry();

      // TODO do not pass sceneTransform
      int portIndex = nodeGeometry.checkHitScenePoint(portToCheck,
                                                      event->scenePos(),
                                                      sceneTransform());

      if (portIndex != INVALID)
      {
        NodeState const & nodeState = _node.nodeState();

        std::unordered_map<QUuid, Connection*> connections =
          nodeState.connections(portToCheck, portIndex);

        // start dragging existing connection
        if (!connections.empty() && portToCheck == PortType::In)
        {
          auto con = connections.begin()->second;

          NodeConnectionInteraction interaction(_node, *con, _scene);

          interaction.disconnect(portToCheck);
        }
        else // initialize new Connection
        {
          const auto outPolicy = _node.nodeDataModel()->portOutConnectionPolicy(portIndex);
          if (!connections.empty() &&
              portToCheck == PortType::Out &&
              outPolicy == NodeDataModel::ConnectionPolicy::One)
          {
            _scene.deleteConnection( *connections.begin()->second );
          }

          // todo add to FlowScene
          auto connection = _scene.createConnection(portToCheck,
                                                    _node,
                                                    portIndex);

          _node.nodeState().setConnection(portToCheck,
                                          portIndex,
                                          *connection);

          connection->getConnectionGraphicsObject().grabMouse();
        }
      }
    };

  clickPort(PortType::In);
  clickPort(PortType::Out);

  auto pos     = event->pos();
  auto & geom  = _node.nodeGeometry();
  auto & state = _node.nodeState();

  if (geom.resizeRect().contains(QPoint(pos.x(),
                                        pos.y())))
  {
    state.setResizing(true);
  }
}

void
NodeGraphicsObject::
mouseMoveEvent(QGraphicsSceneMouseEvent * event)
{
  auto & geom  = _node.nodeGeometry();
  auto & state = _node.nodeState();

  if (state.resizing())
  {
    auto diff = event->pos() - event->lastPos();

    if (auto w = _node.nodeDataModel()->embeddedWidget())
    {
      prepareGeometryChange();

      auto oldSize = w->size();

      oldSize += QSize(diff.x(), diff.y());

      w->setFixedSize(oldSize);

      _proxyWidget->setMinimumSize(oldSize);
      _proxyWidget->setMaximumSize(oldSize);
      _proxyWidget->setPos(geom.widgetPosition());

      geom.recalculateSize();
      update();

      moveConnections();

      event->accept();
    }
  }
  else
  {
    QGraphicsObject::mouseMoveEvent(event);

    if (event->lastPos() != event->pos())
      moveConnections();

    event->ignore();
  }

  QRectF r = scene()->sceneRect();

  r = r.united(mapToScene(boundingRect()).boundingRect());

  scene()->setSceneRect(r);
}

void
NodeGraphicsObject::
mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
  auto & state = _node.nodeState();

  state.setResizing(false);

  QGraphicsObject::mouseReleaseEvent(event);

  // position connections precisely after fast node move
  moveConnections();
}

void
NodeGraphicsObject::
hoverEnterEvent(QGraphicsSceneHoverEvent * event)
{
  // bring all the colliding nodes to background
  QList<QGraphicsItem *> overlapItems = collidingItems();

  for (QGraphicsItem *item : overlapItems)
  {
    if (item->zValue() > 0.0)
    {
      item->setZValue(0.0);
    }
  }
  // bring this node forward
  setZValue(1.0);

  _node.nodeGeometry().setHovered(true);
  update();
  _scene.nodeHovered(node(), event->screenPos());
  event->accept();
}

void
NodeGraphicsObject::
hoverLeaveEvent(QGraphicsSceneHoverEvent * event)
{
  _node.nodeGeometry().setHovered(false);
  update();
  _scene.nodeHoverLeft(node());
  event->accept();
}

void
NodeGraphicsObject::
hoverMoveEvent(QGraphicsSceneHoverEvent * event)
{
  auto pos    = event->pos();
  auto & geom = _node.nodeGeometry();

  if (geom.resizeRect().contains(QPoint(pos.x(),
                                        pos.y())))
  {
    setCursor(QCursor(Qt::SizeFDiagCursor));
  }
  else
  {
    setCursor(QCursor());
  }

  event->accept();
}

void
NodeGraphicsObject::
mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event)
{
  QGraphicsItem::mouseDoubleClickEvent(event);

  _scene.nodeDoubleClicked(node());
}
<|endoftext|>


<commit_before><commit_msg>sfx2: remove commented consts<commit_after><|endoftext|>


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

#include "transactionrecord.h"

#include "consensus/consensus.h"
#include "dstencode.h"
#include "main.h"
#include "timedata.h"

#include <stdint.h>

#include <boost/foreach.hpp>

/* Return positive answer if transaction should be shown in list.
 */
bool TransactionRecord::showTransaction(const CWalletTx &wtx)
{
    if (wtx.IsCoinBase())
    {
        // Ensures we show generated coins / mined transactions at depth 1
        if (!wtx.IsInMainChain())
        {
            return false;
        }
    }
    return true;
}

/*
 * Decompose CWallet transaction to model transaction records.
 */
QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)
{
    QList<TransactionRecord> parts;
    int64_t nTime = wtx.GetTxTime();
    CAmount nCredit = wtx.GetCredit(ISMINE_ALL);
    CAmount nDebit = wtx.GetDebit(ISMINE_ALL);
    CAmount nNet = nCredit - nDebit;
    uint256 hash = wtx.GetHash();
    std::map<std::string, std::string> mapValue = wtx.mapValue;

    if (nNet > 0 || wtx.IsCoinBase())
    {
        //
        // Credit
        //
        std::string labelPublic = "";
        BOOST_FOREACH (const CTxOut &txout, wtx.vout)
        {
            isminetype mine = wallet->IsMine(txout);
            if (mine)
            {
                TransactionRecord sub(hash, nTime);
                CTxDestination address;
                sub.idx = parts.size(); // sequence number
                sub.credit = txout.nValue;
                sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;

                // the public label refers to the following utxo
                if (labelPublic == "")
                {
                    labelPublic = getLabelPublic(txout.scriptPubKey);
                    if (labelPublic != "")
                        continue;
                }

                if (wtx.IsCoinBase())
                {
                    // Generated
                    sub.type = TransactionRecord::Generated;
                }
                else if (ExtractDestination(txout.scriptPubKey, address) && wallet->IsMine(address))
                {
                    // Received by Bitcoin Address
                    sub.type = TransactionRecord::RecvWithAddress;
                    if (labelPublic == "")
                        sub.addresses.push_back(std::make_pair(EncodeDestination(address), txout.scriptPubKey));
                    else
                        sub.addresses.push_back(
                            std::make_pair("<" + labelPublic + "> " + EncodeDestination(address), txout.scriptPubKey));
                }
                else
                {
                    // Received by IP connection (deprecated features), or a multisignature or other non-simple
                    // transaction
                    sub.type = TransactionRecord::RecvFromOther;
                    sub.addresses.push_back(std::make_pair(mapValue["from"], txout.scriptPubKey));
                }

                parts.append(sub);
            }

            labelPublic = "";
        }
    }
    else
    {
        bool involvesWatchAddress = false;
        isminetype fAllToMe = ISMINE_SPENDABLE;
        BOOST_FOREACH (const CTxOut &txout, wtx.vout)
        {
            isminetype mine = wallet->IsMine(txout);
            if (mine & ISMINE_WATCH_ONLY)
                involvesWatchAddress = true;
            if (fAllToMe > mine)
                fAllToMe = mine;
        }

        // load all tx addresses for user display/filter
        AddressList listAllAddresses;
        CTxDestination address;
        BOOST_FOREACH (const CTxOut &txout, wtx.vout)
        {
            if (!fAllToMe && wallet->IsMine(txout))
            {
                continue; // skip change if some tx went to somewhere else
            }
            // get public label if it exists
            std::string labelPublic = getLabelPublic(txout.scriptPubKey);
            if (labelPublic != "")
                // use public label before address
                listAllAddresses.push_back(std::make_pair("<" + labelPublic + ">", txout.scriptPubKey));
            else if (ExtractDestination(txout.scriptPubKey, address))
                // a standard address
                listAllAddresses.push_back(std::make_pair(EncodeDestination(address), txout.scriptPubKey));

            else
                // add the unknown scriptPubKey as n/a - TODO could also skip these if there is no need to
                // display/filter??
                listAllAddresses.push_back(std::make_pair("n/a", txout.scriptPubKey));
        }

        isminetype fAllFromMe = ISMINE_SPENDABLE;
        BOOST_FOREACH (const CTxIn &txin, wtx.vin)
        {
            isminetype mine = wallet->IsMine(txin);
            if (mine & ISMINE_WATCH_ONLY)
                involvesWatchAddress = true;
            if (fAllFromMe > mine)
                fAllFromMe = mine;
        }

        if (fAllFromMe && fAllToMe)
        {
            // Payment to self
            CAmount nChange = wtx.GetChange();
            parts.append(TransactionRecord(
                hash, nTime, TransactionRecord::SendToSelf, listAllAddresses, -(nDebit - nChange), nCredit - nChange));

            // maybe pass to TransactionRecord as constructor argument
            parts.last().involvesWatchAddress = involvesWatchAddress;
        }
        else if (fAllFromMe)
        {
            //
            // Debit
            //
            CAmount nTxFee = nDebit - wtx.GetValueOut();

            for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)
            {
                const CTxOut &txout = wtx.vout[nOut];

                if (wallet->IsMine(txout))
                {
                    // Ignore parts sent to self, as this is usually the change
                    // from a transaction sent back to our own address.
                    continue;
                }

                TransactionRecord sub(hash, nTime);
                sub.idx = parts.size();
                sub.involvesWatchAddress = involvesWatchAddress;

                CTxDestination address;
                std::string labelPublic = getLabelPublic(txout.scriptPubKey);
                if (labelPublic != "")
                    continue;
                else if (ExtractDestination(txout.scriptPubKey, address))
                {
                    // Sent to Bitcoin Address
                    sub.type = TransactionRecord::SendToAddress;
                    // sub.addresses.push_back(std::make_pair(EncodeDestination(address), txout.scriptPubKey));
                }
                else
                {
                    // Sent to IP, or other non-address transaction like OP_EVAL
                    sub.type = TransactionRecord::SendToOther;
                    // sub.addresses.push_back(std::make_pair(mapValue["to"], txout.scriptPubKey));
                }

                sub.addresses = listAllAddresses;

                CAmount nValue = txout.nValue;
                /* Add fee to first output */
                if (nTxFee > 0)
                {
                    nValue += nTxFee;
                    nTxFee = 0;
                }
                sub.debit = -nValue;

                parts.append(sub);
            }
        }
        else
        {
            //
            // Mixed debit transaction, can't break down payees
            //
            parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, listAllAddresses, nNet, 0));
            parts.last().involvesWatchAddress = involvesWatchAddress;
        }
    }

    return parts;
}

void TransactionRecord::updateStatus(const CWalletTx &wtx)
{
    AssertLockHeld(cs_main);
    // Determine transaction status

    // Find the block the tx is in
    CBlockIndex *pindex = NULL;
    BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);
    if (mi != mapBlockIndex.end())
        pindex = (*mi).second;

    // Sort order, unrecorded transactions sort to the top
    status.sortKey = strprintf("%010d-%01d-%010u-%03d", (pindex ? pindex->nHeight : std::numeric_limits<int>::max()),
        (wtx.IsCoinBase() ? 1 : 0), wtx.nTimeReceived, idx);
    status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);
    status.depth = wtx.GetDepthInMainChain();
    status.cur_num_blocks = chainActive.Height();

    if (!CheckFinalTx(wtx))
    {
        if (wtx.nLockTime < LOCKTIME_THRESHOLD)
        {
            status.status = TransactionStatus::OpenUntilBlock;
            status.open_for = wtx.nLockTime - chainActive.Height();
        }
        else
        {
            status.status = TransactionStatus::OpenUntilDate;
            status.open_for = wtx.nLockTime;
        }
    }
    // For generated transactions, determine maturity
    else if (type == TransactionRecord::Generated)
    {
        if (wtx.GetBlocksToMaturity() > 0)
        {
            status.status = TransactionStatus::Immature;

            if (wtx.IsInMainChain())
            {
                status.matures_in = wtx.GetBlocksToMaturity();

                // Check if the block was requested by anyone
                if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
                    status.status = TransactionStatus::MaturesWarning;
            }
            else
            {
                status.status = TransactionStatus::NotAccepted;
            }
        }
        else
        {
            status.status = TransactionStatus::Confirmed;
        }
    }
    else
    {
        if (status.depth < 0)
        {
            status.status = TransactionStatus::Conflicted;
        }
        else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
        {
            status.status = TransactionStatus::Offline;
        }
        else if (status.depth == 0)
        {
            status.status = TransactionStatus::Unconfirmed;
        }
        else if (status.depth < RecommendedNumConfirmations)
        {
            status.status = TransactionStatus::Confirming;
        }
        else
        {
            status.status = TransactionStatus::Confirmed;
        }
    }
}

bool TransactionRecord::statusUpdateNeeded()
{
    AssertLockHeld(cs_main);
    return status.cur_num_blocks != chainActive.Height();
}

QString TransactionRecord::getTxID() const { return QString::fromStdString(hash.ToString()); }
int TransactionRecord::getOutputIndex() const { return idx; }
<commit_msg>Revert Transacation description back to previous behavior (fixes #838) (#892)<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "transactionrecord.h"

#include "consensus/consensus.h"
#include "dstencode.h"
#include "main.h"
#include "timedata.h"

#include <stdint.h>

#include <boost/foreach.hpp>

/* Return positive answer if transaction should be shown in list.
 */
bool TransactionRecord::showTransaction(const CWalletTx &wtx)
{
    if (wtx.IsCoinBase())
    {
        // Ensures we show generated coins / mined transactions at depth 1
        if (!wtx.IsInMainChain())
        {
            return false;
        }
    }
    return true;
}

/*
 * Decompose CWallet transaction to model transaction records.
 */
QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)
{
    QList<TransactionRecord> parts;
    int64_t nTime = wtx.GetTxTime();
    CAmount nCredit = wtx.GetCredit(ISMINE_ALL);
    CAmount nDebit = wtx.GetDebit(ISMINE_ALL);
    CAmount nNet = nCredit - nDebit;
    uint256 hash = wtx.GetHash();
    std::map<std::string, std::string> mapValue = wtx.mapValue;

    if (nNet > 0 || wtx.IsCoinBase())
    {
        //
        // Credit
        //
        std::string labelPublic = "";
        BOOST_FOREACH (const CTxOut &txout, wtx.vout)
        {
            isminetype mine = wallet->IsMine(txout);
            if (mine)
            {
                TransactionRecord sub(hash, nTime);
                CTxDestination address;
                sub.idx = parts.size(); // sequence number
                sub.credit = txout.nValue;
                sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;

                // the public label refers to the following utxo
                if (labelPublic == "")
                {
                    labelPublic = getLabelPublic(txout.scriptPubKey);
                    if (labelPublic != "")
                        continue;
                }

                if (wtx.IsCoinBase())
                {
                    // Generated
                    sub.type = TransactionRecord::Generated;
                }
                else if (ExtractDestination(txout.scriptPubKey, address) && wallet->IsMine(address))
                {
                    // Received by Bitcoin Address
                    sub.type = TransactionRecord::RecvWithAddress;
                    if (labelPublic == "")
                        sub.addresses.push_back(std::make_pair(EncodeDestination(address), txout.scriptPubKey));
                    else
                        sub.addresses.push_back(
                            std::make_pair("<" + labelPublic + "> " + EncodeDestination(address), txout.scriptPubKey));
                }
                else
                {
                    // Received by IP connection (deprecated features), or a multisignature or other non-simple
                    // transaction
                    sub.type = TransactionRecord::RecvFromOther;
                    sub.addresses.push_back(std::make_pair(mapValue["from"], txout.scriptPubKey));
                }

                parts.append(sub);
            }

            labelPublic = "";
        }
    }
    else
    {
        bool involvesWatchAddress = false;
        isminetype fAllToMe = ISMINE_SPENDABLE;
        BOOST_FOREACH (const CTxOut &txout, wtx.vout)
        {
            isminetype mine = wallet->IsMine(txout);
            if (mine & ISMINE_WATCH_ONLY)
                involvesWatchAddress = true;
            if (fAllToMe > mine)
                fAllToMe = mine;
        }

        // load all tx addresses for user display/filter
        AddressList listAllAddresses;

        isminetype fAllFromMe = ISMINE_SPENDABLE;
        BOOST_FOREACH (const CTxIn &txin, wtx.vin)
        {
            isminetype mine = wallet->IsMine(txin);
            if (mine & ISMINE_WATCH_ONLY)
                involvesWatchAddress = true;
            if (fAllFromMe > mine)
                fAllFromMe = mine;
        }

        if (fAllFromMe && fAllToMe)
        {
            // Payment to self
            CAmount nChange = wtx.GetChange();
            parts.append(TransactionRecord(
                hash, nTime, TransactionRecord::SendToSelf, listAllAddresses, -(nDebit - nChange), nCredit - nChange));

            // maybe pass to TransactionRecord as constructor argument
            parts.last().involvesWatchAddress = involvesWatchAddress;
        }
        else if (fAllFromMe)
        {
            //
            // Debit
            //
            CAmount nTxFee = nDebit - wtx.GetValueOut();

            for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)
            {
                const CTxOut &txout = wtx.vout[nOut];

                if (wallet->IsMine(txout))
                {
                    // Ignore parts sent to self, as this is usually the change
                    // from a transaction sent back to our own address.
                    continue;
                }

                TransactionRecord sub(hash, nTime);
                sub.idx = parts.size();
                sub.involvesWatchAddress = involvesWatchAddress;

                CTxDestination address;
                std::string labelPublic = getLabelPublic(txout.scriptPubKey);
                if (labelPublic != "")
                    continue;
                else if (ExtractDestination(txout.scriptPubKey, address))
                {
                    // Sent to Bitcoin Address
                    sub.type = TransactionRecord::SendToAddress;
                    sub.addresses.push_back(std::make_pair(EncodeDestination(address), txout.scriptPubKey));
                }
                else
                {
                    // Sent to IP, or other non-address transaction like OP_EVAL
                    sub.type = TransactionRecord::SendToOther;
                    sub.addresses.push_back(std::make_pair(mapValue["to"], txout.scriptPubKey));
                }

                CAmount nValue = txout.nValue;
                /* Add fee to first output */
                if (nTxFee > 0)
                {
                    nValue += nTxFee;
                    nTxFee = 0;
                }
                sub.debit = -nValue;

                parts.append(sub);
            }
        }
        else
        {
            //
            // Mixed debit transaction, can't break down payees
            //
            parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, listAllAddresses, nNet, 0));
            parts.last().involvesWatchAddress = involvesWatchAddress;
        }
    }

    return parts;
}

void TransactionRecord::updateStatus(const CWalletTx &wtx)
{
    AssertLockHeld(cs_main);
    // Determine transaction status

    // Find the block the tx is in
    CBlockIndex *pindex = NULL;
    BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);
    if (mi != mapBlockIndex.end())
        pindex = (*mi).second;

    // Sort order, unrecorded transactions sort to the top
    status.sortKey = strprintf("%010d-%01d-%010u-%03d", (pindex ? pindex->nHeight : std::numeric_limits<int>::max()),
        (wtx.IsCoinBase() ? 1 : 0), wtx.nTimeReceived, idx);
    status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);
    status.depth = wtx.GetDepthInMainChain();
    status.cur_num_blocks = chainActive.Height();

    if (!CheckFinalTx(wtx))
    {
        if (wtx.nLockTime < LOCKTIME_THRESHOLD)
        {
            status.status = TransactionStatus::OpenUntilBlock;
            status.open_for = wtx.nLockTime - chainActive.Height();
        }
        else
        {
            status.status = TransactionStatus::OpenUntilDate;
            status.open_for = wtx.nLockTime;
        }
    }
    // For generated transactions, determine maturity
    else if (type == TransactionRecord::Generated)
    {
        if (wtx.GetBlocksToMaturity() > 0)
        {
            status.status = TransactionStatus::Immature;

            if (wtx.IsInMainChain())
            {
                status.matures_in = wtx.GetBlocksToMaturity();

                // Check if the block was requested by anyone
                if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
                    status.status = TransactionStatus::MaturesWarning;
            }
            else
            {
                status.status = TransactionStatus::NotAccepted;
            }
        }
        else
        {
            status.status = TransactionStatus::Confirmed;
        }
    }
    else
    {
        if (status.depth < 0)
        {
            status.status = TransactionStatus::Conflicted;
        }
        else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
        {
            status.status = TransactionStatus::Offline;
        }
        else if (status.depth == 0)
        {
            status.status = TransactionStatus::Unconfirmed;
        }
        else if (status.depth < RecommendedNumConfirmations)
        {
            status.status = TransactionStatus::Confirming;
        }
        else
        {
            status.status = TransactionStatus::Confirmed;
        }
    }
}

bool TransactionRecord::statusUpdateNeeded()
{
    AssertLockHeld(cs_main);
    return status.cur_num_blocks != chainActive.Height();
}

QString TransactionRecord::getTxID() const { return QString::fromStdString(hash.ToString()); }
int TransactionRecord::getOutputIndex() const { return idx; }
<|endoftext|>


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

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>
#include "itkTestMain.h"

void RegisterTests()
{
#ifdef TubeTK_USE_VTK
  REGISTER_TEST( itkAnisotropicDiffusiveRegistrationExecution );
  REGISTER_TEST( itkAnisotropicDiffusiveRegistrationImageRegistrationTest );
  REGISTER_TEST( itkAnisotropicDiffusiveRegistrationRegularizationTest );
#endif
  REGISTER_TEST( itkImageToTubeRigidRegistrationTest );
  REGISTER_TEST( itkTubeToTubeTransformFilterTest );
}

<commit_msg>BUG: Merge conflict resolved<commit_after>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>
#include "itkTestMain.h"

void RegisterTests()
{
#ifdef TubeTK_USE_VTK
  REGISTER_TEST( itkAnisotropicDiffusiveRegistrationImageRegistrationTest );
  REGISTER_TEST( itkAnisotropicDiffusiveRegistrationRegularizationTest );
#endif
  REGISTER_TEST( itkImageToTubeRigidRegistrationTest );
  REGISTER_TEST( itkTubeToTubeTransformFilterTest );
}

<|endoftext|>


<commit_before>
#include "otbWrapperOutputProcessXMLParameter.h"

#include "otbWrapperChoiceParameter.h"
#include "otbWrapperListViewParameter.h"
#include "otbWrapperDirectoryParameter.h"
#include "otbWrapperEmptyParameter.h"
#include "otbWrapperInputFilenameParameter.h"
#include "otbWrapperInputFilenameListParameter.h"
#include "otbWrapperOutputFilenameParameter.h"
#include "otbWrapperInputVectorDataParameter.h"
#include "otbWrapperInputVectorDataListParameter.h"
#include "otbWrapperNumericalParameter.h"
#include "otbWrapperOutputVectorDataParameter.h"
#include "otbWrapperRadiusParameter.h"
#include "otbWrapperStringParameter.h"
#include "otbWrapperStringListParameter.h"
#include "otbWrapperInputImageParameter.h"
#include "otbWrapperInputImageListParameter.h"
#include "otbWrapperComplexInputImageParameter.h"
#include "otbWrapperOutputImageParameter.h"
#include "otbWrapperComplexOutputImageParameter.h"
#include "otbWrapperRAMParameter.h"
#include "itksys/SystemTools.hxx"

namespace otb
{
namespace Wrapper
{
OutputProcessXMLParameter::OutputProcessXMLParameter()
{
  this->SetKey("outxml");
  this->SetName("Save otb application to xml file");
  this->SetDescription("Save otb application to xml file");
  this->SetMandatory(false);
  this->SetActive(false);
  this->SetRole(Role_Output);
}

OutputProcessXMLParameter::~OutputProcessXMLParameter()
{

}

std::string
OutputProcessXMLParameter::pixelTypeToString(ImagePixelType pixType)
{
  std::string type;

  switch( pixType )
    {
    case ImagePixelType_uint8:
    {
    type = "uint8";
    break;
    }
    case ImagePixelType_int16:
    {
    type = "int16";
    break;
    }
    case ImagePixelType_int32:
    {
    type = "int32";
    break;
    }
    case ImagePixelType_float:
    {
    type = "float";
    break;
    }
    case ImagePixelType_double:
    {
    type = "double";
    break;
    }
    }
  return type;
}

TiXmlElement* OutputProcessXMLParameter::AddChildNodeTo(TiXmlElement *parent, std::string name, std::string value)
{
  TiXmlElement * n_Node = new TiXmlElement( name.c_str() );
  parent->LinkEndChild( n_Node );
  if(!value.empty())
    {
      TiXmlText * nv_NodeValue = new TiXmlText( value.c_str() );
      n_Node->LinkEndChild( nv_NodeValue );
    }
  return n_Node;
}

void
OutputProcessXMLParameter::Write(Application::Pointer app)
{
  // Check if the filename is not empty
  if(m_FileName.empty())
    itkExceptionMacro("The XML output FileName is empty, please set the filename via the method SetFileName");

  // Check that the right extension is given : expected .xml */
  if (itksys::SystemTools::GetFilenameLastExtension(m_FileName) != ".xml")
    {
    itkExceptionMacro(<<itksys::SystemTools::GetFilenameLastExtension(m_FileName)
                      <<" is a wrong Extension FileName : Expected .xml");
    }

  // start creating XML file
  TiXmlDocument doc;

  TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
  doc.LinkEndChild( decl );

  TiXmlElement * n_OTB = new TiXmlElement( "OTB");
  doc.LinkEndChild( n_OTB );

  std::string version = OTB_VERSION_STRING;

  AddChildNodeTo(n_OTB, "version", version);

  TiXmlElement *n_App;
  n_App = AddChildNodeTo(n_OTB, "application");
  AddChildNodeTo(n_App, "name", app->GetName());
  AddChildNodeTo(n_App, "descr", app->GetDescription());

  TiXmlElement *n_AppDoc;
  n_AppDoc = AddChildNodeTo(n_App, "doc");
  AddChildNodeTo(n_AppDoc, "name", app->GetDocName());
  AddChildNodeTo(n_AppDoc, "longdescr", app->GetDocLongDescription());
  AddChildNodeTo(n_AppDoc, "authors", app->GetDocAuthors());
  AddChildNodeTo(n_AppDoc, "limitations", app->GetDocLimitations());
  AddChildNodeTo(n_AppDoc, "seealso", app->GetDocSeeAlso());

  TiXmlElement *n_DocTags;
  n_DocTags = AddChildNodeTo(n_AppDoc, "tags");
  std::vector<std::string> docTagList = app->GetDocTags();
  std::vector<std::string>::iterator tagIt;
  for(tagIt = docTagList.begin(); tagIt!= docTagList.end(); ++tagIt)
    {
      std::string tag = *tagIt;
      AddChildNodeTo(n_DocTags, "tag", tag);
    }
  ParameterGroup::Pointer paramGroup = app->GetParameterList();

  std::vector<std::string> paramList = paramGroup->GetParametersKeys(true);

  // Iterate through parameters
  for (std::vector<std::string>::const_iterator it = paramList.begin(); it!= paramList.end(); ++it)
    {
      std::string key = *it;
      Parameter *param = paramGroup->GetParameterByKey(key);
      std::string paramName = param->GetName();
      ParameterType type = app->GetParameterType(key);
      std::string typeAsString = paramGroup->GetParameterTypeAsString(type);

      // if param is a Group, dont do anything, ParamGroup dont have values
      if (type != ParameterType_Group)
      {
       bool paramExists = app->HasUserValue(key) && app->IsParameterEnabled(key);
       if ( key == "outxml" )
         {
           paramExists = false;
         }
       if (type == ParameterType_Empty && app->HasUserValue(key))
         {
           paramExists = true;
         }
       // if parameter doesn't have any value then skip it
       if (paramExists)
        {
         std::vector<std::string> values;
         std::string value;
         bool hasValueList = false;
         std::string pixelTypeAsString;
         if (type == ParameterType_OutputImage)
          {
           OutputImageParameter *imgParam = dynamic_cast<OutputImageParameter *>(param);
           value = imgParam->GetFileName();
           ImagePixelType pixType = imgParam->GetPixelType();
           pixelTypeAsString = pixelTypeToString(pixType); //FIXME save this
         }
         else if( type == ParameterType_InputImageList || type == ParameterType_InputFilenameList ||
                  type == ParameterType_InputVectorDataList || type == ParameterType_StringList )
           {
           values = app->GetParameterStringList(key);
           hasValueList = true;
           }
         else if (type == ParameterType_Int || type == ParameterType_Radius || type == ParameterType_RAM )
           {
           value = app->GetParameterAsString(key);
           }
         else if(type == ParameterType_Float)
           {
           std::ostringstream oss;
           oss << std::setprecision(10);
           oss << app->GetParameterFloat( key );
           value = oss.str();
           }
         else if ( type == ParameterType_String || type == ParameterType_InputFilename ||
                   type == ParameterType_Directory || type == ParameterType_InputImage ||
                   type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData ||
                   type == ParameterType_Choice || type == ParameterType_ListView ||
                   type == ParameterType_OutputVectorData || type == ParameterType_OutputFilename)
           {
           value = app->GetParameterString(key);
           }
         else if(key == "rand")
           {
           std::ostringstream strm;
           strm << app->GetParameterInt("rand");
           value = strm.str();
           }
         else if (typeAsString == "Empty")
           {
           EmptyParameter* eParam = dynamic_cast<EmptyParameter *> (param);
           value = "false";
           if( eParam->GetActive() )
             {
             value = "true";
             }
           }

         //get only file name
    /*
      if(type == ParameterType_InputFilename || type == ParameterType_InputImage ||
      type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData ||
      type == ParameterType_OutputVectorData || type == ParameterType_OutputFilename)
           {
           unsigned found = value.find_last_of("/\\");
           //std::cerr << " path: " << value.substr(0,found) << '\n';
           value = value.substr(found+1);
           }
           else
           if(type == ParameterType_InputImageList || type == ParameterType_InputFilenameList ||
           type == ParameterType_InputVectorDataList)
           {
           std::vector<std::string>::iterator strIt;
           for(strIt = values.begin(); strIt != values.end(); ++strIt)
                    {
                    std::string val = *strIt;
                    unsigned found = val.find_last_of("/\\");
                    *strIt = val.substr(found+1);
                    }
                    }
  */
         //parameter node in xml
         TiXmlElement * n_Parameter = new TiXmlElement("parameter");

         const char * mandatory = "false";

         if( param->GetMandatory() )
           mandatory = "true";

         n_Parameter->SetAttribute("mandatory", mandatory);

         //setting parameter key as child node in parameter
         AddChildNodeTo(n_Parameter, "key", key);
         AddChildNodeTo(n_Parameter, "type", typeAsString);
         AddChildNodeTo(n_Parameter, "name", paramName);

         if(type == ParameterType_OutputImage || type == ParameterType_ComplexOutputImage)
           {
           AddChildNodeTo(n_Parameter, "pixtype", pixelTypeAsString);
           }
         if(!hasValueList)
           {
             AddChildNodeTo(n_Parameter, "value", value);
           }
         else
           {
             TiXmlElement *n_Values = AddChildNodeTo(n_Parameter, "values");
             std::vector<std::string>::iterator strIt;
             for(strIt = values.begin(); strIt != values.end(); ++strIt)
              {
                AddChildNodeTo(n_Values, "value",*strIt);
              }
           }
         n_App->LinkEndChild(n_Parameter);
       }
      }
    }

  // Finally, write xml contents to file
  doc.SaveFile( m_FileName.c_str() );

}

} //end namespace wrapper

} //end namespace otb
<commit_msg>WRG: added default case for switch in pixelTypeToString<commit_after>
#include "otbWrapperOutputProcessXMLParameter.h"

#include "otbWrapperChoiceParameter.h"
#include "otbWrapperListViewParameter.h"
#include "otbWrapperDirectoryParameter.h"
#include "otbWrapperEmptyParameter.h"
#include "otbWrapperInputFilenameParameter.h"
#include "otbWrapperInputFilenameListParameter.h"
#include "otbWrapperOutputFilenameParameter.h"
#include "otbWrapperInputVectorDataParameter.h"
#include "otbWrapperInputVectorDataListParameter.h"
#include "otbWrapperNumericalParameter.h"
#include "otbWrapperOutputVectorDataParameter.h"
#include "otbWrapperRadiusParameter.h"
#include "otbWrapperStringParameter.h"
#include "otbWrapperStringListParameter.h"
#include "otbWrapperInputImageParameter.h"
#include "otbWrapperInputImageListParameter.h"
#include "otbWrapperComplexInputImageParameter.h"
#include "otbWrapperOutputImageParameter.h"
#include "otbWrapperComplexOutputImageParameter.h"
#include "otbWrapperRAMParameter.h"
#include "itksys/SystemTools.hxx"

namespace otb
{
namespace Wrapper
{
OutputProcessXMLParameter::OutputProcessXMLParameter()
{
  this->SetKey("outxml");
  this->SetName("Save otb application to xml file");
  this->SetDescription("Save otb application to xml file");
  this->SetMandatory(false);
  this->SetActive(false);
  this->SetRole(Role_Output);
}

OutputProcessXMLParameter::~OutputProcessXMLParameter()
{

}

std::string
OutputProcessXMLParameter::pixelTypeToString(ImagePixelType pixType)
{
  std::string type;

  switch( pixType )
    {
    case ImagePixelType_uint8:
    {
    type = "uint8";
    break;
    }
    case ImagePixelType_int16:
    {
    type = "int16";
    break;
    }
    case ImagePixelType_int32:
    {
    type = "int32";
    break;
    }
    case ImagePixelType_float:
    {
    type = "float";
    break;
    }
    case ImagePixelType_double:
    {
    type = "double";
    break;
    }
    default:
    {
    type = "float";
    break;
    }
    }
  return type;
}

TiXmlElement* OutputProcessXMLParameter::AddChildNodeTo(TiXmlElement *parent, std::string name, std::string value)
{
  TiXmlElement * n_Node = new TiXmlElement( name.c_str() );
  parent->LinkEndChild( n_Node );
  if(!value.empty())
    {
      TiXmlText * nv_NodeValue = new TiXmlText( value.c_str() );
      n_Node->LinkEndChild( nv_NodeValue );
    }
  return n_Node;
}

void
OutputProcessXMLParameter::Write(Application::Pointer app)
{
  // Check if the filename is not empty
  if(m_FileName.empty())
    itkExceptionMacro("The XML output FileName is empty, please set the filename via the method SetFileName");

  // Check that the right extension is given : expected .xml */
  if (itksys::SystemTools::GetFilenameLastExtension(m_FileName) != ".xml")
    {
    itkExceptionMacro(<<itksys::SystemTools::GetFilenameLastExtension(m_FileName)
                      <<" is a wrong Extension FileName : Expected .xml");
    }

  // start creating XML file
  TiXmlDocument doc;

  TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
  doc.LinkEndChild( decl );

  TiXmlElement * n_OTB = new TiXmlElement( "OTB");
  doc.LinkEndChild( n_OTB );

  std::string version = OTB_VERSION_STRING;

  AddChildNodeTo(n_OTB, "version", version);

  TiXmlElement *n_App;
  n_App = AddChildNodeTo(n_OTB, "application");
  AddChildNodeTo(n_App, "name", app->GetName());
  AddChildNodeTo(n_App, "descr", app->GetDescription());

  TiXmlElement *n_AppDoc;
  n_AppDoc = AddChildNodeTo(n_App, "doc");
  AddChildNodeTo(n_AppDoc, "name", app->GetDocName());
  AddChildNodeTo(n_AppDoc, "longdescr", app->GetDocLongDescription());
  AddChildNodeTo(n_AppDoc, "authors", app->GetDocAuthors());
  AddChildNodeTo(n_AppDoc, "limitations", app->GetDocLimitations());
  AddChildNodeTo(n_AppDoc, "seealso", app->GetDocSeeAlso());

  TiXmlElement *n_DocTags;
  n_DocTags = AddChildNodeTo(n_AppDoc, "tags");
  std::vector<std::string> docTagList = app->GetDocTags();
  std::vector<std::string>::iterator tagIt;
  for(tagIt = docTagList.begin(); tagIt!= docTagList.end(); ++tagIt)
    {
      std::string tag = *tagIt;
      AddChildNodeTo(n_DocTags, "tag", tag);
    }
  ParameterGroup::Pointer paramGroup = app->GetParameterList();

  std::vector<std::string> paramList = paramGroup->GetParametersKeys(true);

  // Iterate through parameters
  for (std::vector<std::string>::const_iterator it = paramList.begin(); it!= paramList.end(); ++it)
    {
      std::string key = *it;
      Parameter *param = paramGroup->GetParameterByKey(key);
      std::string paramName = param->GetName();
      ParameterType type = app->GetParameterType(key);
      std::string typeAsString = paramGroup->GetParameterTypeAsString(type);

      // if param is a Group, dont do anything, ParamGroup dont have values
      if (type != ParameterType_Group)
      {
       bool paramExists = app->HasUserValue(key) && app->IsParameterEnabled(key);
       if ( type == ParameterType_OutputProcessXML )
         {
           paramExists = false;
         }
       if (type == ParameterType_Empty && app->HasUserValue(key))
         {
           paramExists = true;
         }
        if(type  == ParameterType_RAM)
        {
          paramExists = true;
        }
       // if parameter doesn't have any value then skip it
       if (paramExists)
        {
         std::vector<std::string> values;
         std::string value;
         bool hasValueList = false;
         std::string pixelTypeAsString;
         if (type == ParameterType_OutputImage)
          {
           OutputImageParameter *imgParam = dynamic_cast<OutputImageParameter *>(param);
           value = imgParam->GetFileName();
           ImagePixelType pixType = imgParam->GetPixelType();
           pixelTypeAsString = pixelTypeToString(pixType);
         }
         else if( type == ParameterType_InputImageList || type == ParameterType_InputFilenameList ||
                  type == ParameterType_InputVectorDataList || type == ParameterType_StringList )
           {
           values = app->GetParameterStringList(key);
           hasValueList = true;
           }
         else if (type == ParameterType_Int || type == ParameterType_Radius || type == ParameterType_RAM )
           {
           value = app->GetParameterAsString(key);
           }
         else if(type == ParameterType_Float)
           {
           std::ostringstream oss;
           oss << std::setprecision(10);
           oss << app->GetParameterFloat( key );
           value = oss.str();
           }
         else if ( type == ParameterType_String || type == ParameterType_InputFilename ||
                   type == ParameterType_Directory || type == ParameterType_InputImage ||
                   type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData ||
                   type == ParameterType_Choice || type == ParameterType_ListView ||
                   type == ParameterType_OutputVectorData || type == ParameterType_OutputFilename)
           {
           value = app->GetParameterString(key);
           }
         else if(key == "rand")
           {
           std::ostringstream strm;
           strm << app->GetParameterInt("rand");
           value = strm.str();
           }
         else if (typeAsString == "Empty")
           {
           EmptyParameter* eParam = dynamic_cast<EmptyParameter *> (param);
           value = "false";
           if( eParam->GetActive() )
             {
             value = "true";
             }
           }

         //get only file name
    /*
      if(type == ParameterType_InputFilename || type == ParameterType_InputImage ||
      type == ParameterType_ComplexInputImage || type == ParameterType_InputVectorData ||
      type == ParameterType_OutputVectorData || type == ParameterType_OutputFilename)
           {
           unsigned found = value.find_last_of("/\\");
           //std::cerr << " path: " << value.substr(0,found) << '\n';
           value = value.substr(found+1);
           }
           else
           if(type == ParameterType_InputImageList || type == ParameterType_InputFilenameList ||
           type == ParameterType_InputVectorDataList)
           {
           std::vector<std::string>::iterator strIt;
           for(strIt = values.begin(); strIt != values.end(); ++strIt)
                    {
                    std::string val = *strIt;
                    unsigned found = val.find_last_of("/\\");
                    *strIt = val.substr(found+1);
                    }
                    }
  */
         //parameter node in xml
         TiXmlElement * n_Parameter = new TiXmlElement("parameter");

         const char * mandatory = "false";

         if( param->GetMandatory() )
           mandatory = "true";

         n_Parameter->SetAttribute("mandatory", mandatory);

         //setting parameter key as child node in parameter
         AddChildNodeTo(n_Parameter, "key", key);
         AddChildNodeTo(n_Parameter, "type", typeAsString);
         AddChildNodeTo(n_Parameter, "name", paramName);

         if(type == ParameterType_OutputImage || type == ParameterType_ComplexOutputImage)
           {
           AddChildNodeTo(n_Parameter, "pixtype", pixelTypeAsString);
           }
         if(!hasValueList)
           {
             AddChildNodeTo(n_Parameter, "value", value);
           }
         else
           {
             TiXmlElement *n_Values = AddChildNodeTo(n_Parameter, "values");
             std::vector<std::string>::iterator strIt;
             for(strIt = values.begin(); strIt != values.end(); ++strIt)
              {
                AddChildNodeTo(n_Values, "value",*strIt);
              }
           }
         n_App->LinkEndChild(n_Parameter);
       }
      }
    }

  // Finally, write xml contents to file
  doc.SaveFile( m_FileName.c_str() );

}

} //end namespace wrapper

} //end namespace otb
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkFEMLoadImplementationGravMembraneC02D.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif

#include "itkFEMElementMembraneC02D.h"
#include "itkFEMLoadGrav.h"
#include "vnl/vnl_math.h"

namespace itk {
namespace fem {

vnl_vector<Element::Float>
GravityLoad(const vnl_vector<Element::Float>& f, MembraneC02D::ConstPointer element)
{
  typedef Element::Float Float;

  vnl_vector<Float> GL(8), shapeF(4);
  vnl_matrix<Float> J(2,2);
  Float gxcom, gycom, detJ;

  // Talk to Aljaz about that
  // Material properties !!!
  Float dense = 1;

  /** Defines gaussian integration points */
  Float pt = 1.0 / sqrt(3.0);
  Float GPoints[][2] = {{-pt, -pt}, {pt, -pt}, {pt, pt}, {-pt, pt}};

  /** Declares auxiliary variables */
  Float x[2];
  int p;

  /** Initialize load vector */
  GL.fill(0.0);

  /** Computes constants
    * theta should be in radians
    */
  gxcom = dense * f[0];
  gycom = dense * f[1];

  /** Carry out numerical integration */
  for (int i=0; i<4; i++) {

    /** Gets integration point */
    x[0] = GPoints[i][0];
    x[1] = GPoints[i][1];

    /** Computes the shape function derivatives at integration point */
    shapeF = element->ComputeShapeFunctionsAt(x);

    /** Computes the Jacobian matrix and its determinant
      * at the i-th integration point
      */
    J = element->ComputeJacobianMatrixAt(x);
    detJ = element->JacobianMatrixDeterminant(J);

    /** Calculates loads and associate with element nodal points */
    for (int j=0; j<4; j++) {
      p = j<<1;

      GL[  p] += gxcom * shapeF[j] * detJ;
      GL[p+1] += gycom * shapeF[j] * detJ;
    }
  }

  return GL;
}

/**
 * Return the force vector for MembraneC02D element
 */
Element::LoadVectorType
LoadGravImplementationMembraneC02D
(MembraneC02D::ConstPointer element, Element::LoadElementPointer load)
{

  typedef Element::Float Float;
  LoadGrav::Pointer l0=dynamic_cast<LoadGrav*>(&*load);
  if ( !l0 ) throw;
  // for gravity loads
  vnl_vector<Float> pt(4,0.0), f(2,0.0);
  // Computes point at which gravity load acts on
  // and also gives the current displacement
  pt[0] = (element->m_node[0]->X + element->m_node[1]->X + element->m_node[2]->X + element->m_node[3]->X)/4;
  pt[1] = (element->m_node[0]->Y + element->m_node[1]->Y + element->m_node[2]->Y + element->m_node[3]->Y)/4;
/*  pt[2] = ( Node::solution[element->GetDegreeOfFreedom(0)] +
            Node::solution[element->GetDegreeOfFreedom(1)] +
            Node::solution[element->GetDegreeOfFreedom(2)] +
            Node::solution[element->GetDegreeOfFreedom(3)] ) / 4;
  pt[3] = ( Node::solution[element->GetDegreeOfFreedom(0)] +
            Node::solution[element->GetDegreeOfFreedom(1)] +
            Node::solution[element->GetDegreeOfFreedom(2)] +
            Node::solution[element->GetDegreeOfFreedom(3)] ) / 4;
*/
  f=l0->Fg(pt);

  return GravityLoad(f , element);

}

}} // end namespace itk::fem
<commit_msg>added the use of solution vector<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkFEMLoadImplementationGravMembraneC02D.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif

#include "itkFEMElementMembraneC02D.h"
#include "itkFEMLoadGrav.h"
#include "vnl/vnl_math.h"

namespace itk {
namespace fem {

vnl_vector<Element::Float>
GravityLoad(const vnl_vector<Element::Float>& f, MembraneC02D::ConstPointer element)
{
  typedef Element::Float Float;

  vnl_vector<Float> GL(8), shapeF(4);
  vnl_matrix<Float> J(2,2);
  Float gxcom, gycom, detJ;

  // Talk to Aljaz about that
  // Material properties !!!
  Float dense = 1;

  /** Defines gaussian integration points */
  Float pt = 1.0 / sqrt(3.0);
  Float GPoints[][2] = {{-pt, -pt}, {pt, -pt}, {pt, pt}, {-pt, pt}};

  /** Declares auxiliary variables */
  Float x[2];
  int p;

  /** Initialize load vector */
  GL.fill(0.0);

  /** Computes constants
    * theta should be in radians
    */
  gxcom = dense * f[0];
  gycom = dense * f[1];

  /** Carry out numerical integration */
  for (int i=0; i<4; i++) {

    /** Gets integration point */
    x[0] = GPoints[i][0];
    x[1] = GPoints[i][1];

    /** Computes the shape function derivatives at integration point */
    shapeF = element->ComputeShapeFunctionsAt(x);

    /** Computes the Jacobian matrix and its determinant
      * at the i-th integration point
      */
    J = element->ComputeJacobianMatrixAt(x);
    detJ = element->JacobianMatrixDeterminant(J);

    /** Calculates loads and associate with element nodal points */
    for (int j=0; j<4; j++) {
      p = j<<1;

      GL[  p] += gxcom * shapeF[j] * detJ;
      GL[p+1] += gycom * shapeF[j] * detJ;
    }
  }

  return GL;
}

/**
 * Return the force vector for MembraneC02D element
 */
Element::LoadVectorType
LoadGravImplementationMembraneC02D
(MembraneC02D::ConstPointer element, Element::LoadElementPointer load)
{

  typedef Element::Float Float;
  LoadGrav::Pointer l0=dynamic_cast<LoadGrav*>(&*load);
  if ( !l0 ) throw;
  // for gravity loads
  vnl_vector<Float> pt(4,0.0), f(2,0.0);
  Solution::ConstPointer   S=l0->GetSolution();
  // Computes point at which gravity load acts on
  // and also gives the current displacement
  pt[0] = (element->m_node[0]->X + element->m_node[1]->X + element->m_node[2]->X + element->m_node[3]->X)/4;
  pt[1] = (element->m_node[0]->Y + element->m_node[1]->Y + element->m_node[2]->Y + element->m_node[3]->Y)/4;
  pt[2] = ( S->GetSolutionValue(element->GetDegreeOfFreedom(0)) +
            S->GetSolutionValue(element->GetDegreeOfFreedom(2)) +
            S->GetSolutionValue(element->GetDegreeOfFreedom(4)) +
            S->GetSolutionValue(element->GetDegreeOfFreedom(6)) ) / 4;
 pt[3] = ( S->GetSolutionValue(element->GetDegreeOfFreedom(1)) +
            S->GetSolutionValue(element->GetDegreeOfFreedom(3)) +
            S->GetSolutionValue(element->GetDegreeOfFreedom(5)) +
            S->GetSolutionValue(element->GetDegreeOfFreedom(7)) ) / 4;
/* */
  f=l0->Fg(pt);

  return GravityLoad(f , element);

}

}} // end namespace itk::fem
<|endoftext|>


<commit_before>/* The MIT License

   Copyright (c) 2013 Adrian Tan <atks@umich.edu>

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.
*/

#include "view.h"

namespace
{

class Igor : Program
{
    public:

    ///////////
    //options//
    ///////////
    std::string input_vcf_file;
    std::string output_vcf_file;
    std::vector<GenomeInterval> intervals;
    std::vector<std::string> samples;
    std::string filter;
    std::string variant;
    uint32_t sort_window_size;
    bool print_header;
    bool print_sites_only;
    bool print;
    int32_t no_subset_samples;

    ///////
    //i/o//
    ///////
    BCFOrderedReader *odr;
    BCFOrderedWriter *odw;

    /////////
    //stats//
    /////////
    uint32_t no_variants;
    uint32_t no_samples;

    Igor(int argc, char **argv)
    {
        version = "0.5";

        //////////////////////////
        //options initialization//
        //////////////////////////
        try
        {
            std::string desc = "Views a VCF or BCF or VCF.GZ file.";

            TCLAP::CmdLine cmd(desc, ' ', version);
            VTOutput my;
            cmd.setOutput(&my);
            TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals []", false, "", "str", cmd);
            TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "file", cmd);
            TCLAP::SwitchArg arg_print("p", "p", "print options and summary []", cmd, false);
            TCLAP::SwitchArg arg_print_header("h", "h", "print header, this option is honored only for STDOUT [false]", cmd, false);
            TCLAP::SwitchArg arg_print_sites_only("s", "s", "print site information only without genotypes [false]", cmd, false);
            TCLAP::ValueArg<uint32_t> arg_sort_window_size("w", "w", "local sorting window size [0]", false, 0, "int", cmd);
            //TCLAP::ValueArg<std::string> arg_sample_list("s", "s", "file containing list of sample []", false, "", "file", cmd);
            //TCLAP::ValueArg<std::string> arg_filter("f", "f", "filter expression []", false, "", "exp", cmd);
            //TCLAP::ValueArg<std::string> arg_variant("v", "v", "variant type []", false, "", "exp", cmd);
            TCLAP::ValueArg<std::string> arg_output_vcf_file("o", "o", "output VCF/VCF.GZ/BCF file [-]", false, "-", "str", cmd);
            TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd);

            cmd.parse(argc, argv);

            input_vcf_file = arg_input_vcf_file.getValue();
            output_vcf_file = arg_output_vcf_file.getValue();
            parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue());
            //read_sample_list(samples, arg_sample_list.getValue());
            print_header = arg_print_header.getValue();
            no_subset_samples = arg_print_sites_only.getValue() ? 0 : -1;
            print = arg_print.getValue();
            sort_window_size = arg_sort_window_size.getValue();
        }
        catch (TCLAP::ArgException &e)
        {
            std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n";
            abort();
        }
    };

    void initialize()
    {
        //////////////////////
        //i/o initialization//
        //////////////////////
        odr = new BCFOrderedReader(input_vcf_file, intervals);
        odw = new BCFOrderedWriter(output_vcf_file, sort_window_size);
        if (no_subset_samples==-1)
        {
            odw->link_hdr(odr->hdr);
        }
        //perform subsetting
        else if (no_subset_samples==0)
        {
            odw->set_hdr(odr->hdr);
            bcf_hdr_subset(odw->hdr, 0, 0, 0);
        }

        if (print_header || output_vcf_file != "-") odw->write_hdr();

        ////////////////////////
        //stats initialization//
        ////////////////////////
        no_variants = 0;
        no_samples = 0;
    }

    void view()
    {
        bcf1_t *v = odw->get_bcf1_from_pool();

        while (odr->read(v))
        {
            if (no_subset_samples==0)
            {
                bcf_subset(odw->hdr, v, 0, 0);
                //maybe add some additional ahoc fixing for BCF files that do not have a complete header.

            }
            odw->write(v);
            v = odw->get_bcf1_from_pool();
            ++no_variants;
        }

        odr->close();
        odw->close();
    };

    void print_options()
    {
        if (!print) return;

        std::clog << "view v" << version << "\n\n";

        std::clog << "options:     input VCF file              " << input_vcf_file << "\n";
        std::clog << "         [o] output VCF file             " << output_vcf_file << "\n";
        std::clog << "         [w] sort window size            " << sort_window_size << "\n";
        std::clog << "         [h] print header                " << (print_header ? "yes" : "no") << "\n";
        std::clog << "         [s] print site information only " << (print_sites_only ? "yes" : "no") << "\n";
        std::clog << "         [p] print options and stats     " << (print ? "yes" : "no") << "\n";
        print_int_op("         [i] intervals                   ", intervals);
        std::clog << "\n";
    }

    void print_stats()
    {
        if (!print) return;

        std::clog << "\n";
        std::clog << "stats: no. variants  : " << no_variants << "\n";
        std::clog << "       no. samples   : " << no_samples << "\n";
        std::clog << "\n";
    };

    ~Igor() {};

    private:
};

}

bool view(int argc, char ** argv)
{
    Igor igor(argc, argv);
    igor.print_options();
    igor.initialize();
    igor.view();
    igor.print_stats();
    return igor.print;
};
<commit_msg>fixed bug for header  output<commit_after>/* The MIT License

   Copyright (c) 2013 Adrian Tan <atks@umich.edu>

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.
*/

#include "view.h"

namespace
{

class Igor : Program
{
    public:

    ///////////
    //options//
    ///////////
    std::string input_vcf_file;
    std::string output_vcf_file;
    std::vector<GenomeInterval> intervals;
    std::vector<std::string> samples;
    std::string filter;
    std::string variant;
    uint32_t sort_window_size;
    bool print_header;
    bool print_sites_only;
    bool print;
    int32_t no_subset_samples;

    ///////
    //i/o//
    ///////
    BCFOrderedReader *odr;
    BCFOrderedWriter *odw;

    /////////
    //stats//
    /////////
    uint32_t no_variants;
    uint32_t no_samples;

    Igor(int argc, char **argv)
    {
        version = "0.5";

        //////////////////////////
        //options initialization//
        //////////////////////////
        try
        {
            std::string desc = "Views a VCF or BCF or VCF.GZ file.";

            TCLAP::CmdLine cmd(desc, ' ', version);
            VTOutput my;
            cmd.setOutput(&my);
            TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals []", false, "", "str", cmd);
            TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "file", cmd);
            TCLAP::SwitchArg arg_print("p", "p", "print options and summary []", cmd, false);
            TCLAP::SwitchArg arg_print_header("h", "h", "print header, this option is honored only for STDOUT [false]", cmd, false);
            TCLAP::SwitchArg arg_print_sites_only("s", "s", "print site information only without genotypes [false]", cmd, false);
            TCLAP::ValueArg<uint32_t> arg_sort_window_size("w", "w", "local sorting window size [0]", false, 0, "int", cmd);
            //TCLAP::ValueArg<std::string> arg_sample_list("s", "s", "file containing list of sample []", false, "", "file", cmd);
            //TCLAP::ValueArg<std::string> arg_filter("f", "f", "filter expression []", false, "", "exp", cmd);
            //TCLAP::ValueArg<std::string> arg_variant("v", "v", "variant type []", false, "", "exp", cmd);
            TCLAP::ValueArg<std::string> arg_output_vcf_file("o", "o", "output VCF/VCF.GZ/BCF file [-]", false, "-", "str", cmd);
            TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd);

            cmd.parse(argc, argv);

            input_vcf_file = arg_input_vcf_file.getValue();
            output_vcf_file = arg_output_vcf_file.getValue();
            parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue());
            //read_sample_list(samples, arg_sample_list.getValue());
            print_header = arg_print_header.getValue();
            no_subset_samples = arg_print_sites_only.getValue() ? 0 : -1;
            print = arg_print.getValue();
            sort_window_size = arg_sort_window_size.getValue();
        }
        catch (TCLAP::ArgException &e)
        {
            std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n";
            abort();
        }
    };

    void initialize()
    {
        //////////////////////
        //i/o initialization//
        //////////////////////
        odr = new BCFOrderedReader(input_vcf_file, intervals);
        odw = new BCFOrderedWriter(output_vcf_file, sort_window_size);
        if (no_subset_samples==-1)
        {
            odw->link_hdr(odr->hdr);
        }
        //perform subsetting
        else if (no_subset_samples==0)
        {
            odw->link_hdr(bcf_hdr_subset(odr->hdr, 0, 0, 0));
        }

        if (print_header || output_vcf_file != "-") odw->write_hdr();

        ////////////////////////
        //stats initialization//
        ////////////////////////
        no_variants = 0;
        no_samples = 0;
    }

    void view()
    {
        bcf1_t *v = odw->get_bcf1_from_pool();

        while (odr->read(v))
        {
            if (no_subset_samples==0)
            {
                bcf_subset(odw->hdr, v, 0, 0);
                //maybe add some additional ahoc fixing for BCF files that do not have a complete header.

            }
            odw->write(v);
            v = odw->get_bcf1_from_pool();
            ++no_variants;
        }

        odr->close();
        odw->close();
    };

    void print_options()
    {
        if (!print) return;

        std::clog << "view v" << version << "\n\n";

        std::clog << "options:     input VCF file              " << input_vcf_file << "\n";
        std::clog << "         [o] output VCF file             " << output_vcf_file << "\n";
        std::clog << "         [w] sort window size            " << sort_window_size << "\n";
        std::clog << "         [h] print header                " << (print_header ? "yes" : "no") << "\n";
        std::clog << "         [s] print site information only " << (print_sites_only ? "yes" : "no") << "\n";
        std::clog << "         [p] print options and stats     " << (print ? "yes" : "no") << "\n";
        print_int_op("         [i] intervals                   ", intervals);
        std::clog << "\n";
    }

    void print_stats()
    {
        if (!print) return;

        std::clog << "\n";
        std::clog << "stats: no. variants  : " << no_variants << "\n";
        std::clog << "       no. samples   : " << no_samples << "\n";
        std::clog << "\n";
    };

    ~Igor() {};

    private:
};

}

bool view(int argc, char ** argv)
{
    Igor igor(argc, argv);
    igor.print_options();
    igor.initialize();
    igor.view();
    igor.print_stats();
    return igor.print;
};
<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_FUN_FROM_VAR_VALUE_HPP
#define STAN_MATH_REV_FUN_FROM_VAR_VALUE_HPP

#include <stan/math/rev/core.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/rev/core/arena_matrix.hpp>
#include <stan/math/rev/core/reverse_pass_callback.hpp>

namespace stan {
namespace math {

/**
 * Converts `var_value` into an Eigen Matrix. Adjoint is propagated back to
 * argument in the reverse pass.
 *
 * @tparam T type of the input
 * @param a matrix to convert
 */
template <typename T, require_var_matrix_t<T>* = nullptr>
Eigen::Matrix<var, T::RowsAtCompileTime, T::ColsAtCompileTime> from_var_value(
    const T& a) {
  arena_matrix<Eigen::Matrix<var, T::RowsAtCompileTime, T::ColsAtCompileTime>>
      res(a.val());
  reverse_pass_callback([res, a]() mutable { a.vi_->adj_ += res.adj(); });
  return res;
}

/**
 * This is a no-op for Eigen containers of vars or scalars or prim types.
 *
 * @tparam T type of the input
 * @param a matrix to convert
 */
template <
    typename T,
    require_any_t<
        conjunction<is_eigen<T>, is_var<scalar_type_t<T>>>,
        std::is_same<std::decay_t<T>, var>,
        bool_constant<!std::is_same<scalar_type_t<T>, var>::value>>* = nullptr>
T from_var_value(T&& a) {
  return std::forward<T>(a);
}

/**
 * Convert the elements of the `std::vector` input to `var_value` types
 * if possible
 *
 * @tparam T type of elemnts of the input vector
 * @param a std::vector of elements to convert
 */
template <typename T>
auto from_var_value(const std::vector<T>& a) {
  std::vector<decltype(from_var_value(std::declval<T>()))> out;
  out.reserve(a.size());
  for (size_t i = 0; i < a.size(); ++i) {
    out.emplace_back(from_var_value(a[i]));
  }
  return out;
}

}  // namespace math
}  // namespace stan

#endif
<commit_msg>Update stan/math/rev/fun/from_var_value.hpp<commit_after>#ifndef STAN_MATH_REV_FUN_FROM_VAR_VALUE_HPP
#define STAN_MATH_REV_FUN_FROM_VAR_VALUE_HPP

#include <stan/math/rev/core.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/rev/core/arena_matrix.hpp>
#include <stan/math/rev/core/reverse_pass_callback.hpp>

namespace stan {
namespace math {

/**
 * Converts `var_value` into an Eigen Matrix. Adjoint is propagated back to
 * argument in the reverse pass.
 *
 * @tparam T type of the input
 * @param a matrix to convert
 */
template <typename T, require_var_matrix_t<T>* = nullptr>
Eigen::Matrix<var, T::RowsAtCompileTime, T::ColsAtCompileTime> from_var_value(
    const T& a) {
  arena_matrix<Eigen::Matrix<var, T::RowsAtCompileTime, T::ColsAtCompileTime>>
      res(a.val());
  reverse_pass_callback([res, a]() mutable { a.vi_->adj_ += res.adj(); });
  return res;
}

/**
 * This is a no-op for Eigen containers of vars, scalars or prim types.
 *
 * @tparam T type of the input
 * @param a matrix to convert
 */
template <
    typename T,
    require_any_t<
        conjunction<is_eigen<T>, is_var<scalar_type_t<T>>>,
        std::is_same<std::decay_t<T>, var>,
        bool_constant<!std::is_same<scalar_type_t<T>, var>::value>>* = nullptr>
T from_var_value(T&& a) {
  return std::forward<T>(a);
}

/**
 * Convert the elements of the `std::vector` input to `var_value` types
 * if possible
 *
 * @tparam T type of elemnts of the input vector
 * @param a std::vector of elements to convert
 */
template <typename T>
auto from_var_value(const std::vector<T>& a) {
  std::vector<decltype(from_var_value(std::declval<T>()))> out;
  out.reserve(a.size());
  for (size_t i = 0; i < a.size(); ++i) {
    out.emplace_back(from_var_value(a[i]));
  }
  return out;
}

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


<commit_before>#include <cstdint>
#include <cstring>
#include <string.h>

#include "Register.hpp"

using namespace std;

Register::Register()
: len(0) {

}

uint64_t Register::getInteger(){
    uint64_t v = *reinterpret_cast<uint64_t*>(this->data);
    return v;
}

void Register::setInteger(uint64_t value){
    this->data = (char*) malloc(sizeof(uint64_t) + sizeof(char));
    memcpy(this->data, &value, sizeof(value));
    this->data[sizeof(uint64_t)] = '\0';
    len = sizeof(uint64_t);
}

string Register::getString(){
    return string(this->data);
}

void Register::setString(const string& value){
    this->data = (char*) malloc(value.length() * sizeof(char) + sizeof(char));
    memcpy(this->data, value.c_str(), value.length() * sizeof(char));
    this->data[value.length()] = '\0';
    len = value.length() * sizeof(char);
}

uint64_t Register::hash(){
    return this->hashfun(string(this->data));
}

bool Register::operator==(Register &that) {
    return strcmp(this->data, that.getString().c_str());
}

bool Register::operator==(Register *that) {
    return strcmp(this->data, that->getString().c_str());
}

Register::~Register(){
    free(this->data);
}
<commit_msg>Register.hash<commit_after>#include <cstdint>
#include <cstring>
#include <string.h>

#include "Register.hpp"

using namespace std;

Register::Register()
: len(0) {

}

uint64_t Register::getInteger(){
    uint64_t v = *reinterpret_cast<uint64_t*>(this->data);
    return v;
}

void Register::setInteger(uint64_t value){
    if (this->len == 0) {
        this->data = (char*) malloc(sizeof(uint64_t) + sizeof(char));
    } else {
        this->data = (char*) realloc(sizeof(uint64_t) + sizeof(char));
    }
    memcpy(this->data, &value, sizeof(value));
    this->data[sizeof(uint64_t)] = '\0';
    len = sizeof(uint64_t);
}

string Register::getString(){
    return string(this->data);
}

void Register::setString(const string& value){
    if (this->len == 0) {
        this->data = (char*) malloc(value.length() * sizeof(char) + sizeof(char));
    } else {
        this->data = (char*) realloc(value.length() * sizeof(char) + sizeof(char));
    }
    memcpy(this->data, value.c_str(), value.length() * sizeof(char));
    this->data[value.length()] = '\0';
    len = value.length() * sizeof(char);
}

uint64_t Register::hash(){
    return this->hashfun(string(this->data));
}

bool Register::operator==(Register &that) {
    return strcmp(this->data, that.getString().c_str());
}

bool Register::operator==(Register *that) {
    return strcmp(this->data, that->getString().c_str());
}

Register::~Register(){
    free(this->data);
}
<|endoftext|>