<commit_before>#include <metaSMT/support/disable_warnings.hpp>
#include <boost/python.hpp>
#include <metaSMT/support/enable_warnings.hpp>

#include "solvers.hpp"

#include <metaSMT/API/SymbolTable.hpp>

using namespace boost::python;

template<typename T>
solver make_solver()
{
  return solver( boost::shared_ptr<T>( new T() ) );
}

template<typename T>
struct evaluate_expression_visitor : public boost::static_visitor<typename T::result_type>
{
  typedef typename T::result_type result_type;

  explicit evaluate_expression_visitor( T& _solver ) : _solver( _solver ) {}

  typename T::result_type operator()( bool expr ) const
  {
    if ( expr )
    {
      return metaSMT::evaluate( _solver, metaSMT::logic::True );
    }
    else
    {
      return metaSMT::evaluate( _solver, metaSMT::logic::False );
    }
  }

  typename T::result_type operator()( const metaSMT::logic::QF_BV::QF_BV<boost::proto::terminal<metaSMT::logic::QF_BV::tag::bit0_tag>::type>& ) const
  {
    return metaSMT::evaluate( _solver, metaSMT::logic::QF_BV::bit0 );
  }

  typename T::result_type operator()( const metaSMT::logic::QF_BV::QF_BV<boost::proto::terminal<metaSMT::logic::QF_BV::tag::bit1_tag>::type>& ) const
  {
    return metaSMT::evaluate( _solver, metaSMT::logic::QF_BV::bit1 );
  }

  typename T::result_type operator()( const metaSMT::logic::predicate& pred ) const
  {
    return metaSMT::evaluate( _solver, pred );
  }

  typename T::result_type operator()( const metaSMT::logic::QF_BV::bitvector& bv ) const
  {
    return metaSMT::evaluate( _solver, bv );
  }

  typename T::result_type operator()( const bvuint_expression& expr ) const
  {
    return metaSMT::evaluate( _solver, metaSMT::logic::QF_BV::bvuint( expr.value, expr.width ) );
  }

  typename T::result_type operator()( const bvsint_expression& expr ) const
  {
    return metaSMT::evaluate( _solver, metaSMT::logic::QF_BV::bvsint( expr.value, expr.width ) );
  }

  template<typename Tag>
  typename T::result_type operator()( const bvstr_expression<Tag>& expr ) const
  {
    return metaSMT::evaluate( _solver, proto::make_expr<Tag>( boost::cref( expr.value ) ) );
  }

  template<typename LogicTag, typename Tag>
  typename T::result_type operator()( const unary_expression<LogicTag, Tag>& expr ) const
  {
    return metaSMT::evaluate( _solver, proto::make_expr<Tag>( boost::cref( boost::apply_visitor( *this, expr.expr ) ) ) );
  }

  template<typename LogicTag, typename Tag>
  typename T::result_type operator()( const binary_expression<LogicTag, Tag>& expr ) const
  {
    return metaSMT::evaluate( _solver, proto::make_expr<Tag>( boost::cref( boost::apply_visitor( *this, expr.left ) ), boost::cref( boost::apply_visitor( *this, expr.right ) ) ) );
  }

  template<typename LogicTag, typename Tag>
  typename T::result_type operator()( const ternary_expression<LogicTag, Tag>& expr ) const
  {
    return metaSMT::evaluate( _solver, proto::make_expr<Tag>( boost::cref( boost::apply_visitor( *this, expr.expr1 ) ), boost::cref( boost::apply_visitor( *this, expr.expr2 ) ), boost::cref( boost::apply_visitor( *this, expr.expr3 ) ) ) );
  }

  template<typename Tag>
  typename T::result_type operator()( const extend_expression<Tag>& expr ) const
  {
    return metaSMT::evaluate( _solver, proto::make_expr<Tag>( boost::cref( expr.by ), boost::cref( boost::apply_visitor( *this, expr.expr ) ) ) );
  }

  template<typename Tag>
  typename T::result_type operator()( const extract_expression<Tag>& expr ) const
  {
    return metaSMT::evaluate( _solver, proto::make_expr<Tag>( boost::cref( expr.from ), boost::cref( expr.width ), boost::cref( boost::apply_visitor( *this, expr.expr ) ) ) );
  }

private:
  T& _solver;
};

struct assertion_visitor : public boost::static_visitor<>
{
  explicit assertion_visitor( const logic_expression& expr ) : expr( expr ) {}

  template<typename T>
  void operator()( const boost::shared_ptr<T>& s ) const
  {
    metaSMT::assertion( *s, boost::apply_visitor( evaluate_expression_visitor<T>( *s ), expr ) );
  }

private:
  const logic_expression& expr;
};

void py_assertion( const solver& ctx, const logic_expression& expr )
{
  boost::apply_visitor( assertion_visitor( expr ), ctx );
}

struct solve_visitor : public boost::static_visitor<bool>
{
  template<typename T>
  bool operator()( const T& s ) const
  {
    return metaSMT::solve( *s );
  }
};

bool py_solve( const solver& ctx )
{
  return boost::apply_visitor( solve_visitor(), ctx );
}

struct read_value_visitor : public boost::static_visitor<bool>
{
  explicit read_value_visitor( const metaSMT::logic::predicate& pred ) : pred( pred ) {}

  template<typename T>
  bool operator()( const T& s ) const
  {
    return metaSMT::read_value( *s, pred );
  }

private:
  const metaSMT::logic::predicate& pred;
};

bool py_read_value( const solver& ctx, const metaSMT::logic::predicate& pred )
{
  return boost::apply_visitor( read_value_visitor( pred ), ctx );
}

struct read_bv_value_visitor : public boost::static_visitor<unsigned>
{
  explicit read_bv_value_visitor( const metaSMT::logic::QF_BV::bitvector& bv ) : bv( bv ) {}

  template<typename T>
  unsigned operator()( const T& s ) const
  {
    return metaSMT::read_value( *s, bv );
  }

private:
  const metaSMT::logic::QF_BV::bitvector& bv;
};

unsigned py_read_bv_value( const solver& ctx, const metaSMT::logic::QF_BV::bitvector& bv )
{
  return boost::apply_visitor( read_bv_value_visitor( bv ), ctx );
}

// Symbol Table
class smt2_symbol_table
{
public:
  typedef std::map<unsigned, std::string> map;

  std::string operator()( unsigned id )
  {
    map::const_iterator it = _map.find( id );
    if ( it == _map.end() )
    {
      return boost::str( boost::format( "var_%d" ) % id );
    }
    else
    {
      return it->second;
    }
  }

  void insert1( metaSMT::logic::predicate p, const std::string& name )
  {
    _map.insert( std::make_pair( boost::proto::value( p ).id, name ) );
  }

  void insert2( metaSMT::logic::QF_BV::bitvector b, const std::string& name )
  {
    _map.insert( std::make_pair( boost::proto::value( b ).id, name ) );
  }

private:
  map _map;
};

struct set_symbol_table_visitor : public boost::static_visitor<unsigned>
{
  explicit set_symbol_table_visitor( smt2_symbol_table& table ) : table( table ) {}

  unsigned operator()( boost::shared_ptr<smt2_solver>& s ) const
  {
    metaSMT::set_symbol_table( *s, table );
  }

  template<typename T>
  unsigned operator()( T& s ) const
  {
    // do nothing
  }

private:
  smt2_symbol_table& table;
};

void py_set_symbol_table( solver& ctx, smt2_symbol_table& table )
{
  boost::apply_visitor( set_symbol_table_visitor( table ), ctx );
}

void export_solvers()
{
  class_<solver>( "solver" )
    .def( "py_assertion", &py_assertion )
    .def( "solve", &py_solve )
    .def( "read_value", &py_read_value )
    .def( "read_value", &py_read_bv_value )
    .def( "__getitem__", &py_read_value )
    .def( "__getitem__", &py_read_bv_value )
    .def( "set_symbol_table", &py_set_symbol_table )
    ;
#if ENABLE_SOLVER_SWORD
  def( "sword_solver", &make_solver<sword_solver> );
#endif
#if ENABLE_SOLVER_BOOLECTOR
  def( "boolector_solver", &make_solver<boolector_solver> );
#endif
#if ENABLE_SOLVER_Z3
  def( "z3_solver", &make_solver<z3_solver> );
#endif
#if ENABLE_SOLVER_CUDD
  def( "cudd_solver", &make_solver<cudd_solver> );
#endif
#if ENABLE_SOLVER_MINISAT
  def( "minisat_solver", &make_solver<minisat_solver> );
#if ENABLE_SOLVER_AIGER
  def( "minisat_aiger_solver", &make_solver<minisat_aiger_solver> );
#endif
#endif
#if ENABLE_SOLVER_PICOSAT
  def( "picosat_solver", &make_solver<picosat_solver> );
#endif
#if ENABLE_SOLVER_GLUCOSER
  def( "glucoser_executable_solver", &make_solver<glucoser_executable_solver> );
#endif
#if ENABLE_SOLVER_MINISAT_EXECUTABLE
  def( "minisat_executable_solver", &make_solver<minisat_executable_solver> );
#endif
#if ENABLE_SOLVER_PICOSAT_EXECUTABLE
  def( "picosat_executable_solver", &make_solver<picosat_executable_solver> );
#endif
#if ENABLE_SOLVER_PLINGELING_EXECUTABLE
  def( "plingeling_executable_solver", &make_solver<plingeling_executable_solver> );
#endif
#if ENABLE_SOLVER_PRECOSAT_EXECUTABLE
  def( "precosat_executable_solver", &make_solver<precosat_executable_solver> );
#endif
#if ENABLE_SOLVER_SMT2
  def( "smt2_solver", &make_solver<smt2_solver> );
#endif

#if ENABLE_SOLVER_CONSTRAINT
  def( "constraint_solver", &make_solver<constraint_solver> );
#endif

  class_<smt2_symbol_table>( "smt2_symbol_table" )
    .def( "insert", &smt2_symbol_table::insert1 )
    .def( "insert", &smt2_symbol_table::insert2 )
    ;
}
<commit_msg>fixed warning in python bindings<commit_after>#include <metaSMT/support/disable_warnings.hpp>
#include <boost/python.hpp>
#include <metaSMT/support/enable_warnings.hpp>

#include "solvers.hpp"

#include <metaSMT/API/SymbolTable.hpp>

using namespace boost::python;

template<typename T>
solver make_solver()
{
  return solver( boost::shared_ptr<T>( new T() ) );
}

template<typename T>
struct evaluate_expression_visitor : public boost::static_visitor<typename T::result_type>
{
  typedef typename T::result_type result_type;

  explicit evaluate_expression_visitor( T& _solver ) : _solver( _solver ) {}

  typename T::result_type operator()( bool expr ) const
  {
    if ( expr )
    {
      return metaSMT::evaluate( _solver, metaSMT::logic::True );
    }
    else
    {
      return metaSMT::evaluate( _solver, metaSMT::logic::False );
    }
  }

  typename T::result_type operator()( const metaSMT::logic::QF_BV::QF_BV<boost::proto::terminal<metaSMT::logic::QF_BV::tag::bit0_tag>::type>& ) const
  {
    return metaSMT::evaluate( _solver, metaSMT::logic::QF_BV::bit0 );
  }

  typename T::result_type operator()( const metaSMT::logic::QF_BV::QF_BV<boost::proto::terminal<metaSMT::logic::QF_BV::tag::bit1_tag>::type>& ) const
  {
    return metaSMT::evaluate( _solver, metaSMT::logic::QF_BV::bit1 );
  }

  typename T::result_type operator()( const metaSMT::logic::predicate& pred ) const
  {
    return metaSMT::evaluate( _solver, pred );
  }

  typename T::result_type operator()( const metaSMT::logic::QF_BV::bitvector& bv ) const
  {
    return metaSMT::evaluate( _solver, bv );
  }

  typename T::result_type operator()( const bvuint_expression& expr ) const
  {
    return metaSMT::evaluate( _solver, metaSMT::logic::QF_BV::bvuint( expr.value, expr.width ) );
  }

  typename T::result_type operator()( const bvsint_expression& expr ) const
  {
    return metaSMT::evaluate( _solver, metaSMT::logic::QF_BV::bvsint( expr.value, expr.width ) );
  }

  template<typename Tag>
  typename T::result_type operator()( const bvstr_expression<Tag>& expr ) const
  {
    return metaSMT::evaluate( _solver, proto::make_expr<Tag>( boost::cref( expr.value ) ) );
  }

  template<typename LogicTag, typename Tag>
  typename T::result_type operator()( const unary_expression<LogicTag, Tag>& expr ) const
  {
    return metaSMT::evaluate( _solver, proto::make_expr<Tag>( boost::cref( boost::apply_visitor( *this, expr.expr ) ) ) );
  }

  template<typename LogicTag, typename Tag>
  typename T::result_type operator()( const binary_expression<LogicTag, Tag>& expr ) const
  {
    return metaSMT::evaluate( _solver, proto::make_expr<Tag>( boost::cref( boost::apply_visitor( *this, expr.left ) ), boost::cref( boost::apply_visitor( *this, expr.right ) ) ) );
  }

  template<typename LogicTag, typename Tag>
  typename T::result_type operator()( const ternary_expression<LogicTag, Tag>& expr ) const
  {
    return metaSMT::evaluate( _solver, proto::make_expr<Tag>( boost::cref( boost::apply_visitor( *this, expr.expr1 ) ), boost::cref( boost::apply_visitor( *this, expr.expr2 ) ), boost::cref( boost::apply_visitor( *this, expr.expr3 ) ) ) );
  }

  template<typename Tag>
  typename T::result_type operator()( const extend_expression<Tag>& expr ) const
  {
    return metaSMT::evaluate( _solver, proto::make_expr<Tag>( boost::cref( expr.by ), boost::cref( boost::apply_visitor( *this, expr.expr ) ) ) );
  }

  template<typename Tag>
  typename T::result_type operator()( const extract_expression<Tag>& expr ) const
  {
    return metaSMT::evaluate( _solver, proto::make_expr<Tag>( boost::cref( expr.from ), boost::cref( expr.width ), boost::cref( boost::apply_visitor( *this, expr.expr ) ) ) );
  }

private:
  T& _solver;
};

struct assertion_visitor : public boost::static_visitor<>
{
  explicit assertion_visitor( const logic_expression& expr ) : expr( expr ) {}

  template<typename T>
  void operator()( const boost::shared_ptr<T>& s ) const
  {
    metaSMT::assertion( *s, boost::apply_visitor( evaluate_expression_visitor<T>( *s ), expr ) );
  }

private:
  const logic_expression& expr;
};

void py_assertion( const solver& ctx, const logic_expression& expr )
{
  boost::apply_visitor( assertion_visitor( expr ), ctx );
}

struct solve_visitor : public boost::static_visitor<bool>
{
  template<typename T>
  bool operator()( const T& s ) const
  {
    return metaSMT::solve( *s );
  }
};

bool py_solve( const solver& ctx )
{
  return boost::apply_visitor( solve_visitor(), ctx );
}

struct read_value_visitor : public boost::static_visitor<bool>
{
  explicit read_value_visitor( const metaSMT::logic::predicate& pred ) : pred( pred ) {}

  template<typename T>
  bool operator()( const T& s ) const
  {
    return metaSMT::read_value( *s, pred );
  }

private:
  const metaSMT::logic::predicate& pred;
};

bool py_read_value( const solver& ctx, const metaSMT::logic::predicate& pred )
{
  return boost::apply_visitor( read_value_visitor( pred ), ctx );
}

struct read_bv_value_visitor : public boost::static_visitor<unsigned>
{
  explicit read_bv_value_visitor( const metaSMT::logic::QF_BV::bitvector& bv ) : bv( bv ) {}

  template<typename T>
  unsigned operator()( const T& s ) const
  {
    return metaSMT::read_value( *s, bv );
  }

private:
  const metaSMT::logic::QF_BV::bitvector& bv;
};

unsigned py_read_bv_value( const solver& ctx, const metaSMT::logic::QF_BV::bitvector& bv )
{
  return boost::apply_visitor( read_bv_value_visitor( bv ), ctx );
}

// Symbol Table
class smt2_symbol_table
{
public:
  typedef std::map<unsigned, std::string> map;

  std::string operator()( unsigned id )
  {
    map::const_iterator it = _map.find( id );
    if ( it == _map.end() )
    {
      return boost::str( boost::format( "var_%d" ) % id );
    }
    else
    {
      return it->second;
    }
  }

  void insert1( metaSMT::logic::predicate p, const std::string& name )
  {
    _map.insert( std::make_pair( boost::proto::value( p ).id, name ) );
  }

  void insert2( metaSMT::logic::QF_BV::bitvector b, const std::string& name )
  {
    _map.insert( std::make_pair( boost::proto::value( b ).id, name ) );
  }

private:
  map _map;
};

struct set_symbol_table_visitor : public boost::static_visitor<void>
{
  explicit set_symbol_table_visitor( smt2_symbol_table& table ) : table( table ) {}

  void operator()( boost::shared_ptr<smt2_solver>& s ) const
  {
    metaSMT::set_symbol_table( *s, table );
  }

  template<typename T>
  void operator()( T& s ) const
  {
    // do nothing
  }

private:
  smt2_symbol_table& table;
};

void py_set_symbol_table( solver& ctx, smt2_symbol_table& table )
{
  boost::apply_visitor( set_symbol_table_visitor( table ), ctx );
}

void export_solvers()
{
  class_<solver>( "solver" )
    .def( "py_assertion", &py_assertion )
    .def( "solve", &py_solve )
    .def( "read_value", &py_read_value )
    .def( "read_value", &py_read_bv_value )
    .def( "__getitem__", &py_read_value )
    .def( "__getitem__", &py_read_bv_value )
    .def( "set_symbol_table", &py_set_symbol_table )
    ;
#if ENABLE_SOLVER_SWORD
  def( "sword_solver", &make_solver<sword_solver> );
#endif
#if ENABLE_SOLVER_BOOLECTOR
  def( "boolector_solver", &make_solver<boolector_solver> );
#endif
#if ENABLE_SOLVER_Z3
  def( "z3_solver", &make_solver<z3_solver> );
#endif
#if ENABLE_SOLVER_CUDD
  def( "cudd_solver", &make_solver<cudd_solver> );
#endif
#if ENABLE_SOLVER_MINISAT
  def( "minisat_solver", &make_solver<minisat_solver> );
#if ENABLE_SOLVER_AIGER
  def( "minisat_aiger_solver", &make_solver<minisat_aiger_solver> );
#endif
#endif
#if ENABLE_SOLVER_PICOSAT
  def( "picosat_solver", &make_solver<picosat_solver> );
#endif
#if ENABLE_SOLVER_GLUCOSER
  def( "glucoser_executable_solver", &make_solver<glucoser_executable_solver> );
#endif
#if ENABLE_SOLVER_MINISAT_EXECUTABLE
  def( "minisat_executable_solver", &make_solver<minisat_executable_solver> );
#endif
#if ENABLE_SOLVER_PICOSAT_EXECUTABLE
  def( "picosat_executable_solver", &make_solver<picosat_executable_solver> );
#endif
#if ENABLE_SOLVER_PLINGELING_EXECUTABLE
  def( "plingeling_executable_solver", &make_solver<plingeling_executable_solver> );
#endif
#if ENABLE_SOLVER_PRECOSAT_EXECUTABLE
  def( "precosat_executable_solver", &make_solver<precosat_executable_solver> );
#endif
#if ENABLE_SOLVER_SMT2
  def( "smt2_solver", &make_solver<smt2_solver> );
#endif

#if ENABLE_SOLVER_CONSTRAINT
  def( "constraint_solver", &make_solver<constraint_solver> );
#endif

  class_<smt2_symbol_table>( "smt2_symbol_table" )
    .def( "insert", &smt2_symbol_table::insert1 )
    .def( "insert", &smt2_symbol_table::insert2 )
    ;
}
<|endoftext|>


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

#include "orderhistorydialog.h"
#include "ui_orderhistorydialog.h"

#include "guiutil.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "wallet.h"
#include "base58.h"
#include "ui_interface.h"

#include <boost/filesystem.hpp>

#include "leveldb/db.h"
#include "leveldb/write_batch.h"

// potentially overzealous includes here
#include "base58.h"
#include "rpcserver.h"
#include "init.h"
#include "util.h"
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
#include "leveldb/db.h"
#include "leveldb/write_batch.h"
// end potentially overzealous includes

using namespace json_spirit;
#include "mastercore.h"
using namespace mastercore;

// potentially overzealous using here
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace leveldb;
// end potentially overzealous using

#include "mastercore_dex.h"
#include "mastercore_tx.h"
#include "mastercore_sp.h"
#include "mastercore_parse_string.h"

#include <QDateTime>
#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>

OrderHistoryDialog::OrderHistoryDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::orderHistoryDialog),
    model(0)
{
    ui->setupUi(this);
    this->model = model;

    // setup
    ui->orderHistoryTable->setColumnCount(7);
    ui->orderHistoryTable->setHorizontalHeaderItem(0, new QTableWidgetItem(" "));
    ui->orderHistoryTable->setHorizontalHeaderItem(1, new QTableWidgetItem("Date"));
    ui->orderHistoryTable->setHorizontalHeaderItem(2, new QTableWidgetItem("Status"));
    ui->orderHistoryTable->setHorizontalHeaderItem(3, new QTableWidgetItem("Trade Details"));
    ui->orderHistoryTable->setHorizontalHeaderItem(4, new QTableWidgetItem("Sold"));
    ui->orderHistoryTable->setHorizontalHeaderItem(5, new QTableWidgetItem("Received"));
    ui->orderHistoryTable->verticalHeader()->setVisible(false);
//    ui->txHistoryTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
//    ui->txHistoryTable->setShowGrid(false);
    ui->orderHistoryTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->orderHistoryTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->orderHistoryTable->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->orderHistoryTable->horizontalHeader()->setResizeMode(3, QHeaderView::Stretch);
    ui->orderHistoryTable->setColumnWidth(0, 23);
    ui->orderHistoryTable->setColumnWidth(1, 150);
    ui->orderHistoryTable->setColumnWidth(2, 110);
    ui->orderHistoryTable->setColumnWidth(4, 180);
    ui->orderHistoryTable->setColumnWidth(5, 180);
    ui->orderHistoryTable->setColumnWidth(6, 0);

    CWallet *wallet = pwalletMain;
    string sAddress = "";
    string addressParam = "";
    bool addressFilter;

    addressFilter = false;
    int64_t nCount = 10;
    int64_t nFrom = 0;
    int64_t nStartBlock = 0;
    int64_t nEndBlock = 999999;

    Array response; //prep an array to hold our output
    int rowcount = 0;

    // rewrite to use original listtransactions methodology from core
    LOCK(wallet->cs_wallet);
    std::list<CAccountingEntry> acentries;
    CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, "*");

    // iterate backwards
    for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
    {
        CWalletTx *const pwtx = (*it).second.first;
        if (pwtx != 0)
        {
            uint256 hash = pwtx->GetHash();
            CTransaction wtx;
            uint256 blockHash = 0;
            if (!GetTransaction(hash, wtx, blockHash, true)) continue;
            // get the time of the tx
            int64_t nTime = pwtx->GetTxTime();
            // get the height of the transaction and check it's within the chosen parameters
            blockHash = pwtx->hashBlock;
            if ((0 == blockHash) || (NULL == mapBlockIndex[blockHash])) continue;
            CBlockIndex* pBlockIndex = mapBlockIndex[blockHash];
            if (NULL == pBlockIndex) continue;
            int blockHeight = pBlockIndex->nHeight;
            if ((blockHeight < nStartBlock) || (blockHeight > nEndBlock)) continue; // ignore it if not within our range
            // check if the transaction exists in txlist, and if so is it correct type (21)
            if (p_txlistdb->exists(hash))
            {
                // get type from levelDB
                string strValue;
                if (!p_txlistdb->getTX(hash, strValue)) continue;
                std::vector<std::string> vstr;
                boost::split(vstr, strValue, boost::is_any_of(":"), token_compress_on);
                if (4 <= vstr.size())
                {
                    // if tx21, get the details for the list
                    if(21 == atoi(vstr[2]))
                    {
                        string statusText;
                        unsigned int propertyIdForSale = 0;
                        unsigned int propertyIdDesired = 0;
                        uint64_t amountForSale = 0;
                        uint64_t amountDesired = 0;
                        string address;
                        bool divisibleForSale;
                        bool divisibleDesired;
                        bool valid;
                        Array tradeArray;
                        uint64_t totalBought = 0;
                        uint64_t totalSold = 0;
                        bool orderOpen = false;

                        CMPMetaDEx temp_metadexoffer;
                        CMPTransaction mp_obj;
                        int parseRC = parseTransaction(true, wtx, blockHeight, 0, &mp_obj);
                        if (0 <= parseRC) //negative RC means no MP content/badly encoded TX, we shouldn't see this if TX in levelDB but check for sanity
                        {
                            if (0<=mp_obj.step1())
                            {
                                //MPTxType = mp_obj.getTypeString();
                                //MPTxTypeInt = mp_obj.getType();
                                address = mp_obj.getSender();
                                //if (!filterAddress.empty()) if ((senderAddress != filterAddress) && (refAddress != filterAddress)) return -1; // return negative rc if filtering & no match

                                int tmpblock=0;
                                uint32_t tmptype=0;
                                uint64_t amountNew=0;
                                valid=getValidMPTX(hash, &tmpblock, &tmptype, &amountNew);

                                if (0 == mp_obj.step2_Value())
                                {
                                    propertyIdForSale = mp_obj.getProperty();
                                    amountForSale = mp_obj.getAmount();
                                    divisibleForSale = isPropertyDivisible(propertyIdForSale);
                                    if (0 <= mp_obj.interpretPacket(NULL,&temp_metadexoffer))
                                    {
                                        propertyIdDesired = temp_metadexoffer.getDesProperty();
                                        divisibleDesired = isPropertyDivisible(propertyIdDesired);
                                        amountDesired = temp_metadexoffer.getAmountDesired();
                                        //mdex_action = temp_metadexoffer.getAction();
                                        t_tradelistdb->getMatchingTrades(hash, propertyIdForSale, &tradeArray, &totalSold, &totalBought);

                                        // status - is order cancelled/closed-filled/open/open-partialfilled?
                                        // is the sell offer still open - need more efficient way to do this
                                        for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it)
                                        {
                                            if (my_it->first == propertyIdForSale) //at minimum only go deeper if it's the right property id
                                            {
                                                md_PricesMap & prices = my_it->second;
                                                for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it)
                                                {
                                                    md_Set & indexes = (it->second);
                                                    for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it)
                                                    {
                                                        CMPMetaDEx obj = *it;
                                                        if( obj.getHash().GetHex() == hash.GetHex() ) orderOpen = true;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        // work out status
                        bool partialFilled = false;
                        bool filled = false;
                        if(totalSold>0) partialFilled = true;
                        if(totalSold>=amountForSale) filled = true;
                        statusText = "UNKNOWN";
                        if((!orderOpen) && (!partialFilled)) statusText = "CANCELLED";
                        if((!orderOpen) && (partialFilled)) statusText = "PART CANCEL";
                        if((!orderOpen) && (filled)) statusText = "FILLED";
                        if((orderOpen) && (!partialFilled)) statusText = "OPEN";
                        if((orderOpen) && (partialFilled)) statusText = "PART FILLED";

                        // add to list
                        string displayText = "Sell ";
                        string displayIn = "+";
                        string displayOut = "-";
                        string displayInToken;
                        string displayOutToken;

                        if(divisibleForSale) { displayText += FormatDivisibleShortMP(amountForSale); } else { displayText += FormatIndivisibleMP(amountForSale); }
                        if(propertyIdForSale < 3)
                        {
                            if(propertyIdForSale == 1) { displayText += " MSC for "; displayOutToken = " MSC"; }
                            if(propertyIdForSale == 2) { displayText += " TMSC for "; displayOutToken = " TMSC"; }
                        }
                        else
                        {
                            string s = to_string(propertyIdForSale);
                            displayText += " SPT#" + s + " for ";
                            displayOutToken = " SPT#" + s;
                        }
                        if(divisibleDesired) { displayText += FormatDivisibleShortMP(amountDesired); } else { displayText += FormatIndivisibleMP(amountDesired); }
                        if(propertyIdDesired < 3)
                        {
                            if(propertyIdDesired == 1) { displayText += " MSC"; displayInToken = " MSC"; }
                            if(propertyIdDesired == 2) { displayText += " TMSC"; displayInToken = " TMSC"; }
                        }
                        else
                        {
                            string s = to_string(propertyIdDesired);
                            displayText += " SPT#" + s;
                            displayInToken = " SPT#" + s;
                        }
                        if(divisibleDesired) { displayIn += FormatDivisibleShortMP(totalBought); } else { displayIn += FormatIndivisibleMP(totalBought); }
                        if(divisibleForSale) { displayOut += FormatDivisibleShortMP(totalSold); } else { displayOut += FormatIndivisibleMP(totalSold); }
                        if(totalBought == 0) displayIn = "0";
                        if(totalSold == 0) displayOut = "0";
                        displayIn += displayInToken;
                        displayOut += displayOutToken;
                        QDateTime txTime;
                        txTime.setTime_t(nTime);
                        QString txTimeStr = txTime.toString(Qt::SystemLocaleShortDate);

                        //icon
                        QIcon ic = QIcon(":/icons/transaction_0");
                        // add to order history
                        ui->orderHistoryTable->setRowCount(rowcount+1);
                        QTableWidgetItem *dateCell = new QTableWidgetItem(txTimeStr);
                        QTableWidgetItem *statusCell = new QTableWidgetItem(QString::fromStdString(statusText));
                        QTableWidgetItem *infoCell = new QTableWidgetItem(QString::fromStdString(displayText));
                        QTableWidgetItem *amountOutCell = new QTableWidgetItem(QString::fromStdString(displayOut));
                        QTableWidgetItem *amountInCell = new QTableWidgetItem(QString::fromStdString(displayIn));
                        QTableWidgetItem *iconCell = new QTableWidgetItem;
                        QTableWidgetItem *txidCell = new QTableWidgetItem(QString::fromStdString(hash.GetHex()));
                        iconCell->setIcon(ic);
                        //addressCell->setTextAlignment(Qt::AlignLeft + Qt::AlignVCenter);
                        //addressCell->setForeground(QColor("#707070"));
                        amountOutCell->setTextAlignment(Qt::AlignRight + Qt::AlignVCenter);
                        amountOutCell->setForeground(QColor("#EE0000"));
                        amountInCell->setTextAlignment(Qt::AlignRight + Qt::AlignVCenter);
                        amountInCell->setForeground(QColor("#00AA00"));
                        if (rowcount % 2)
                        {
                            dateCell->setBackground(QColor("#F0F0F0"));
                            statusCell->setBackground(QColor("#F0F0F0"));
                            infoCell->setBackground(QColor("#F0F0F0"));
                            amountOutCell->setBackground(QColor("#F0F0F0"));
                            amountInCell->setBackground(QColor("#F0F0F0"));
                            iconCell->setBackground(QColor("#F0F0F0"));
                            txidCell->setBackground(QColor("#F0F0F0"));
                        }
                        if((!orderOpen) && (filled)) //make filled orders background
                        {
                            dateCell->setForeground(QColor("#707070"));
                            statusCell->setForeground(QColor("#707070"));
                            infoCell->setForeground(QColor("#707070"));
                            amountOutCell->setForeground(QColor("#993333"));
                            amountInCell->setForeground(QColor("#33CC66"));
                        }
                        ui->orderHistoryTable->setItem(rowcount, 0, iconCell);
                        ui->orderHistoryTable->setItem(rowcount, 1, dateCell);
                        ui->orderHistoryTable->setItem(rowcount, 2, statusCell);
                        ui->orderHistoryTable->setItem(rowcount, 3, infoCell);
                        ui->orderHistoryTable->setItem(rowcount, 4, amountOutCell);
                        ui->orderHistoryTable->setItem(rowcount, 5, amountInCell);
                        ui->orderHistoryTable->setItem(rowcount, 6, txidCell);
                        rowcount += 1;

/*
                        qItem->setData(Qt::UserRole + 1, QString::fromStdString(displayText));
                        qItem->setData(Qt::UserRole + 2, QString::fromStdString(displayIn));
                        qItem->setData(Qt::UserRole + 3, QString::fromStdString(displayOut));
                        qItem->setData(Qt::UserRole + 4, QString::fromStdString(statusText));
                        qItem->setData(Qt::UserRole + 5, QString::fromStdString(address));
                        qItem->setData(Qt::UserRole + 6, txTimeStr);
                        ui->orderHistoryLW->addItem(qItem);
*/
                    }
                }
            }
            // don't burn time doing more work than we need to
//            if ((int)response.size() >= (nCount+nFrom)) break;
        }
    }
    // sort array here and cut on nFrom and nCount
//    if (nFrom > (int)response.size())
//        nFrom = response.size();
//    if ((nFrom + nCount) > (int)response.size())
//        nCount = response.size() - nFrom;
//    Array::iterator first = response.begin();
//    std::advance(first, nFrom);
//    Array::iterator last = response.begin();
//    std::advance(last, nFrom+nCount);

//    if (last != response.end()) response.erase(last, response.end());
//    if (first != response.begin()) response.erase(response.begin(), first);

//    std::reverse(response.begin(), response.end()); // return oldest to newest?
 //   return response;   // return response array for JSON serialization

}

void OrderHistoryDialog::setModel(WalletModel *model)
{
    this->model = model;
    //connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(OrderRefresh()));
}

<commit_msg>Fix icons and decolor unmatched trades<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "orderhistorydialog.h"
#include "ui_orderhistorydialog.h"

#include "guiutil.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "wallet.h"
#include "base58.h"
#include "ui_interface.h"

#include <boost/filesystem.hpp>

#include "leveldb/db.h"
#include "leveldb/write_batch.h"

// potentially overzealous includes here
#include "base58.h"
#include "rpcserver.h"
#include "init.h"
#include "util.h"
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
#include "leveldb/db.h"
#include "leveldb/write_batch.h"
// end potentially overzealous includes

using namespace json_spirit;
#include "mastercore.h"
using namespace mastercore;

// potentially overzealous using here
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace leveldb;
// end potentially overzealous using

#include "mastercore_dex.h"
#include "mastercore_tx.h"
#include "mastercore_sp.h"
#include "mastercore_parse_string.h"

#include <QDateTime>
#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>

OrderHistoryDialog::OrderHistoryDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::orderHistoryDialog),
    model(0)
{
    ui->setupUi(this);
    this->model = model;

    // setup
    ui->orderHistoryTable->setColumnCount(7);
    ui->orderHistoryTable->setHorizontalHeaderItem(0, new QTableWidgetItem(" "));
    ui->orderHistoryTable->setHorizontalHeaderItem(1, new QTableWidgetItem("Date"));
    ui->orderHistoryTable->setHorizontalHeaderItem(2, new QTableWidgetItem("Status"));
    ui->orderHistoryTable->setHorizontalHeaderItem(3, new QTableWidgetItem("Trade Details"));
    ui->orderHistoryTable->setHorizontalHeaderItem(4, new QTableWidgetItem("Sold"));
    ui->orderHistoryTable->setHorizontalHeaderItem(5, new QTableWidgetItem("Received"));
    ui->orderHistoryTable->verticalHeader()->setVisible(false);
//    ui->txHistoryTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
//    ui->txHistoryTable->setShowGrid(false);
    ui->orderHistoryTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->orderHistoryTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->orderHistoryTable->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->orderHistoryTable->horizontalHeader()->setResizeMode(3, QHeaderView::Stretch);
    ui->orderHistoryTable->setColumnWidth(0, 23);
    ui->orderHistoryTable->setColumnWidth(1, 150);
    ui->orderHistoryTable->setColumnWidth(2, 110);
    ui->orderHistoryTable->setColumnWidth(4, 180);
    ui->orderHistoryTable->setColumnWidth(5, 180);
    ui->orderHistoryTable->setColumnWidth(6, 0);

    CWallet *wallet = pwalletMain;
    string sAddress = "";
    string addressParam = "";
    bool addressFilter;

    addressFilter = false;
    int64_t nCount = 10;
    int64_t nFrom = 0;
    int64_t nStartBlock = 0;
    int64_t nEndBlock = 999999;

    Array response; //prep an array to hold our output
    int rowcount = 0;

    // rewrite to use original listtransactions methodology from core
    LOCK(wallet->cs_wallet);
    std::list<CAccountingEntry> acentries;
    CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, "*");

    // iterate backwards
    for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
    {
        CWalletTx *const pwtx = (*it).second.first;
        if (pwtx != 0)
        {
            uint256 hash = pwtx->GetHash();
            CTransaction wtx;
            uint256 blockHash = 0;
            if (!GetTransaction(hash, wtx, blockHash, true)) continue;
            // get the time of the tx
            int64_t nTime = pwtx->GetTxTime();
            // get the height of the transaction and check it's within the chosen parameters
            blockHash = pwtx->hashBlock;
            if ((0 == blockHash) || (NULL == mapBlockIndex[blockHash])) continue;
            CBlockIndex* pBlockIndex = mapBlockIndex[blockHash];
            if (NULL == pBlockIndex) continue;
            int blockHeight = pBlockIndex->nHeight;
            if ((blockHeight < nStartBlock) || (blockHeight > nEndBlock)) continue; // ignore it if not within our range
            // check if the transaction exists in txlist, and if so is it correct type (21)
            if (p_txlistdb->exists(hash))
            {
                // get type from levelDB
                string strValue;
                if (!p_txlistdb->getTX(hash, strValue)) continue;
                std::vector<std::string> vstr;
                boost::split(vstr, strValue, boost::is_any_of(":"), token_compress_on);
                if (4 <= vstr.size())
                {
                    // if tx21, get the details for the list
                    if(21 == atoi(vstr[2]))
                    {
                        string statusText;
                        unsigned int propertyIdForSale = 0;
                        unsigned int propertyIdDesired = 0;
                        uint64_t amountForSale = 0;
                        uint64_t amountDesired = 0;
                        string address;
                        bool divisibleForSale;
                        bool divisibleDesired;
                        bool valid;
                        Array tradeArray;
                        uint64_t totalBought = 0;
                        uint64_t totalSold = 0;
                        bool orderOpen = false;

                        CMPMetaDEx temp_metadexoffer;
                        CMPTransaction mp_obj;
                        int parseRC = parseTransaction(true, wtx, blockHeight, 0, &mp_obj);
                        if (0 <= parseRC) //negative RC means no MP content/badly encoded TX, we shouldn't see this if TX in levelDB but check for sanity
                        {
                            if (0<=mp_obj.step1())
                            {
                                //MPTxType = mp_obj.getTypeString();
                                //MPTxTypeInt = mp_obj.getType();
                                address = mp_obj.getSender();
                                //if (!filterAddress.empty()) if ((senderAddress != filterAddress) && (refAddress != filterAddress)) return -1; // return negative rc if filtering & no match

                                int tmpblock=0;
                                uint32_t tmptype=0;
                                uint64_t amountNew=0;
                                valid=getValidMPTX(hash, &tmpblock, &tmptype, &amountNew);

                                if (0 == mp_obj.step2_Value())
                                {
                                    propertyIdForSale = mp_obj.getProperty();
                                    amountForSale = mp_obj.getAmount();
                                    divisibleForSale = isPropertyDivisible(propertyIdForSale);
                                    if (0 <= mp_obj.interpretPacket(NULL,&temp_metadexoffer))
                                    {
                                        propertyIdDesired = temp_metadexoffer.getDesProperty();
                                        divisibleDesired = isPropertyDivisible(propertyIdDesired);
                                        amountDesired = temp_metadexoffer.getAmountDesired();
                                        //mdex_action = temp_metadexoffer.getAction();
                                        t_tradelistdb->getMatchingTrades(hash, propertyIdForSale, &tradeArray, &totalSold, &totalBought);

                                        // status - is order cancelled/closed-filled/open/open-partialfilled?
                                        // is the sell offer still open - need more efficient way to do this
                                        for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it)
                                        {
                                            if (my_it->first == propertyIdForSale) //at minimum only go deeper if it's the right property id
                                            {
                                                md_PricesMap & prices = my_it->second;
                                                for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it)
                                                {
                                                    md_Set & indexes = (it->second);
                                                    for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it)
                                                    {
                                                        CMPMetaDEx obj = *it;
                                                        if( obj.getHash().GetHex() == hash.GetHex() ) orderOpen = true;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        // work out status
                        bool partialFilled = false;
                        bool filled = false;
                        if(totalSold>0) partialFilled = true;
                        if(totalSold>=amountForSale) filled = true;
                        statusText = "UNKNOWN";
                        if((!orderOpen) && (!partialFilled)) statusText = "CANCELLED";
                        if((!orderOpen) && (partialFilled)) statusText = "PART CANCEL";
                        if((!orderOpen) && (filled)) statusText = "FILLED";
                        if((orderOpen) && (!partialFilled)) statusText = "OPEN";
                        if((orderOpen) && (partialFilled)) statusText = "PART FILLED";

                        // add to list
                        string displayText = "Sell ";
                        string displayIn = "+";
                        string displayOut = "-";
                        string displayInToken;
                        string displayOutToken;

                        if(divisibleForSale) { displayText += FormatDivisibleShortMP(amountForSale); } else { displayText += FormatIndivisibleMP(amountForSale); }
                        if(propertyIdForSale < 3)
                        {
                            if(propertyIdForSale == 1) { displayText += " MSC for "; displayOutToken = " MSC"; }
                            if(propertyIdForSale == 2) { displayText += " TMSC for "; displayOutToken = " TMSC"; }
                        }
                        else
                        {
                            string s = to_string(propertyIdForSale);
                            displayText += " SPT#" + s + " for ";
                            displayOutToken = " SPT#" + s;
                        }
                        if(divisibleDesired) { displayText += FormatDivisibleShortMP(amountDesired); } else { displayText += FormatIndivisibleMP(amountDesired); }
                        if(propertyIdDesired < 3)
                        {
                            if(propertyIdDesired == 1) { displayText += " MSC"; displayInToken = " MSC"; }
                            if(propertyIdDesired == 2) { displayText += " TMSC"; displayInToken = " TMSC"; }
                        }
                        else
                        {
                            string s = to_string(propertyIdDesired);
                            displayText += " SPT#" + s;
                            displayInToken = " SPT#" + s;
                        }
                        if(divisibleDesired) { displayIn += FormatDivisibleShortMP(totalBought); } else { displayIn += FormatIndivisibleMP(totalBought); }
                        if(divisibleForSale) { displayOut += FormatDivisibleShortMP(totalSold); } else { displayOut += FormatIndivisibleMP(totalSold); }
                        if(totalBought == 0) displayIn = "0";
                        if(totalSold == 0) displayOut = "0";
                        displayIn += displayInToken;
                        displayOut += displayOutToken;
                        QDateTime txTime;
                        txTime.setTime_t(nTime);
                        QString txTimeStr = txTime.toString(Qt::SystemLocaleShortDate);

                        //icon
                        QIcon ic = QIcon(":/icons/transaction_0");
                        if(statusText == "CANCELLED") ic =QIcon(":/icons/meta_cancelled");
                        if(statusText == "PART CANCEL") ic = QIcon(":/icons/meta_partialclosed");
                        if(statusText == "FILLED") ic = QIcon(":/icons/meta_filled");
                        if(statusText == "OPEN") ic = QIcon(":/icons/meta_open");
                        if(statusText == "PART FILLED") ic = QIcon(":/icons/meta_partial");

                        // add to order history
                        ui->orderHistoryTable->setRowCount(rowcount+1);
                        QTableWidgetItem *dateCell = new QTableWidgetItem(txTimeStr);
                        QTableWidgetItem *statusCell = new QTableWidgetItem(QString::fromStdString(statusText));
                        QTableWidgetItem *infoCell = new QTableWidgetItem(QString::fromStdString(displayText));
                        QTableWidgetItem *amountOutCell = new QTableWidgetItem(QString::fromStdString(displayOut));
                        QTableWidgetItem *amountInCell = new QTableWidgetItem(QString::fromStdString(displayIn));
                        QTableWidgetItem *iconCell = new QTableWidgetItem;
                        QTableWidgetItem *txidCell = new QTableWidgetItem(QString::fromStdString(hash.GetHex()));
                        iconCell->setIcon(ic);
                        //addressCell->setTextAlignment(Qt::AlignLeft + Qt::AlignVCenter);
                        //addressCell->setForeground(QColor("#707070"));
                        amountOutCell->setTextAlignment(Qt::AlignRight + Qt::AlignVCenter);
                        amountOutCell->setForeground(QColor("#EE0000"));
                        amountInCell->setTextAlignment(Qt::AlignRight + Qt::AlignVCenter);
                        amountInCell->setForeground(QColor("#00AA00"));
                        if (rowcount % 2)
                        {
                            dateCell->setBackground(QColor("#F0F0F0"));
                            statusCell->setBackground(QColor("#F0F0F0"));
                            infoCell->setBackground(QColor("#F0F0F0"));
                            amountOutCell->setBackground(QColor("#F0F0F0"));
                            amountInCell->setBackground(QColor("#F0F0F0"));
                            iconCell->setBackground(QColor("#F0F0F0"));
                            txidCell->setBackground(QColor("#F0F0F0"));
                        }
                        if((!orderOpen) && (filled)) //make filled orders background
                        {
                            dateCell->setForeground(QColor("#707070"));
                            statusCell->setForeground(QColor("#707070"));
                            infoCell->setForeground(QColor("#707070"));
                            amountOutCell->setForeground(QColor("#993333"));
                            amountInCell->setForeground(QColor("#006600"));
                        }
                        if(displayIn.substr(0,2) == "0 ") amountInCell->setForeground(QColor("#000000"));
                        if(displayOut.substr(0,2) == "0 ") amountOutCell->setForeground(QColor("#000000"));

                        ui->orderHistoryTable->setItem(rowcount, 0, iconCell);
                        ui->orderHistoryTable->setItem(rowcount, 1, dateCell);
                        ui->orderHistoryTable->setItem(rowcount, 2, statusCell);
                        ui->orderHistoryTable->setItem(rowcount, 3, infoCell);
                        ui->orderHistoryTable->setItem(rowcount, 4, amountOutCell);
                        ui->orderHistoryTable->setItem(rowcount, 5, amountInCell);
                        ui->orderHistoryTable->setItem(rowcount, 6, txidCell);
                        rowcount += 1;

/*
                        qItem->setData(Qt::UserRole + 1, QString::fromStdString(displayText));
                        qItem->setData(Qt::UserRole + 2, QString::fromStdString(displayIn));
                        qItem->setData(Qt::UserRole + 3, QString::fromStdString(displayOut));
                        qItem->setData(Qt::UserRole + 4, QString::fromStdString(statusText));
                        qItem->setData(Qt::UserRole + 5, QString::fromStdString(address));
                        qItem->setData(Qt::UserRole + 6, txTimeStr);
                        ui->orderHistoryLW->addItem(qItem);
*/
                    }
                }
            }
            // don't burn time doing more work than we need to
//            if ((int)response.size() >= (nCount+nFrom)) break;
        }
    }
    // sort array here and cut on nFrom and nCount
//    if (nFrom > (int)response.size())
//        nFrom = response.size();
//    if ((nFrom + nCount) > (int)response.size())
//        nCount = response.size() - nFrom;
//    Array::iterator first = response.begin();
//    std::advance(first, nFrom);
//    Array::iterator last = response.begin();
//    std::advance(last, nFrom+nCount);

//    if (last != response.end()) response.erase(last, response.end());
//    if (first != response.begin()) response.erase(response.begin(), first);

//    std::reverse(response.begin(), response.end()); // return oldest to newest?
 //   return response;   // return response array for JSON serialization

}

void OrderHistoryDialog::setModel(WalletModel *model)
{
    this->model = model;
    //connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(OrderRefresh()));
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: OGLTrans_TransitionImpl.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2007-11-09 10:17:11 $
 *
 *  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 2007 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 INCLUDED_SLIDESHOW_TRANSITION_HXX_
#define INCLUDED_SLIDESHOW_TRANSITION_HXX_

#include <basegfx/vector/b2dvector.hxx>
#include <basegfx/vector/b3dvector.hxx>

#include <vector>

class Primitive;
class Operation;

/** OpenGL 3D Transition class. It implicitly is constructed from XOGLTransition

    This class is capable of making itself into many difference transitions. It holds Primitives and Operations on those primitives.
*/
class OGLTransitionImpl
{
public:
    OGLTransitionImpl() :
        maLeavingSlidePrimitives(),
        maEnteringSlidePrimitives()
    {}

    ~OGLTransitionImpl();

    void display( double nTime, ::sal_Int32 glLeavingSlideTex, ::sal_Int32 glEnteringSlideTex , double SlideWidthScale, double SlideHeightScale);
    void makeOutsideCubeFaceToLeft();
    void makeInsideCubeFaceToLeft();
    void makeNByMTileFlip( ::sal_uInt16 n, ::sal_uInt16 m );
    void makeRevolvingCircles( ::sal_uInt16 nCircles , ::sal_uInt16 nPointsOnCircles );
    void makeHelix( ::sal_uInt16 nRows );

private:
    /** clears all the primitives and operations
    */
    void clear();

    /** All the primitives that use the leaving slide texture
    */
    std::vector<Primitive> maLeavingSlidePrimitives;

    /** All the primitives that use the leaving slide texture
    */
    std::vector<Primitive> maEnteringSlidePrimitives;

    /** All the operations that should be applied to both leaving and entering slide primitives. These operations will be called in the order they were pushed back in. In OpenGL this effectively uses the operations in the opposite order they were pushed back.
    */
    std::vector<Operation*> OverallOperations;
};

/** This class is a list of Triangles that will share Operations, and could possibly share
*/
class Primitive
{
public:
    Primitive() {}
    explicit Primitive(const Primitive& rvalue);
    ~Primitive();

    void display(double nTime, double SlideWidthScale, double SlideHeightScale);
    const Primitive& operator=(const Primitive& rvalue);

    /** PushBack a vertex,normal, and tex coord. Each SlideLocation is where on the slide is mapped to this location ( from (0,0) to (1,1)  ). This will make sure the correct aspect ratio is used, and helps to make slides begin and end at the correct position. (0,0) is the top left of the slide, and (1,1) is the bottom right.

    @param SlideLocation0
    Location of first Vertex on slide

    @param SlideLocation1
    Location of second Vertex on slide

    @param SlideLocation2
    Location of third Vertex on slide

    */
    void pushTriangle(const basegfx::B2DVector& SlideLocation0,const basegfx::B2DVector& SlideLocation1,const basegfx::B2DVector& SlideLocation2);

    /** clear all the vertices, normals, tex coordinates, and normals
    */
    void clearTriangles();

    /** guards against directly changing the vertices

        @return
        the list of vertices
    */
    const std::vector<basegfx::B3DVector>& getVertices() const {return Vertices;}

    /** guards against directly changing the vertices
    */
    const std::vector<basegfx::B3DVector>& getNormals() const {return Normals;}

    /** guards against directly changing the vertices

        @return
        the list of Texture Coordinates

    */
    const std::vector<basegfx::B2DVector>& getTexCoords() const {return TexCoords;}

    /** list of Operations to be performed on this primitive.These operations will be called in the order they were pushed back in. In OpenGL this effectively uses the operations in the opposite order they were pushed back.

        @return
        the list of Operations

    */
    std::vector<Operation*> Operations;

private:
    /** list of vertices
    */
    std::vector<basegfx::B3DVector> Vertices;

    /** list of Normals
    */
    std::vector<basegfx::B3DVector> Normals;

    /** list of Texture Coordinates
    */
    std::vector<basegfx::B2DVector> TexCoords;
};

/** This class is to be derived to make any operation (tranform) you may need in order to construct your transitions
*/
class Operation
{
public:
    Operation(){}
    virtual ~Operation(){}

    /** Should this operation be interpolated . If TRUE, the transform will smoothly move from making no difference from t = 0.0 to nT0 to being completely transformed from t = nT1 to 1. If FALSE, the transform will be inneffectual from t = 0 to nT0, and completely transformed from t = nT0 to 1.
    */
    bool bInterpolate;

    /** time to begin the transformation
    */
    double nT0;

    /** time to finish the transformation
    */
    double nT1;
public:
    /** this is the function that is called to give the Operation to OpenGL.

        @param t
        time from t = 0 to t = 1

        @param SlideWidthScale
        width of slide divided by width of window

        @param SlideHeightScale
        height of slide divided by height of window

    */
    virtual void interpolate(double t,double SlideWidthScale,double SlideHeightScale) = 0;

    /** return a copy of this operation
    */
    virtual Operation* clone() = 0;
};

/** this class is a generic CounterClockWise(CCW) rotation with an axis angle
*/
class SRotate: public Operation
{
public:
    void interpolate(double t,double SlideWidthScale,double SlideHeightScale);
    virtual SRotate* clone();

    /** Constructor

        @param Axis
        axis to rotate about

        @param Origin
        position that rotation axis runs through

        @param Angle
        angle in radians of CCW rotation

        @param bInter
        see Operation

        @param T0
        transformation starting time

        @param T1
        transformation ending time

    */
    SRotate(const basegfx::B3DVector& Axis,const basegfx::B3DVector& Origin,double Angle,bool bInter, double T0, double T1);
    ~SRotate(){}
private:
    /** axis to rotate CCW about
    */
    basegfx::B3DVector axis;

    /** position that rotation axis runs through
    */
    basegfx::B3DVector origin;

    /** angle in radians of CCW rotation
    */
    double angle;
};

/** scaling transformation
*/
class SScale: public Operation
{
public:
    void interpolate(double t,double SlideWidthScale,double SlideHeightScale);
    SScale* clone();

    /** Constructor

        @param Scale
        amount to scale by

        @param Origin
        position that rotation axis runs through

        @param bInter
        see Operation

        @param T0
        transformation starting time

        @param T1
        transformation ending time

    */
    SScale(const basegfx::B3DVector& Scale, const basegfx::B3DVector& Origin,bool bInter, double T0, double T1);
    ~SScale(){}
private:
    basegfx::B3DVector scale;
    basegfx::B3DVector origin;
};

/** translation transformation
*/
class STranslate: public Operation
{
public:
    void interpolate(double t,double SlideWidthScale,double SlideHeightScale);
    STranslate* clone();

    /** Constructor

        @param Vector
        vector to translate

        @param bInter
        see Operation

        @param T0
        transformation starting time

        @param T1
        transformation ending time

    */
    STranslate(const basegfx::B3DVector& Vector,bool bInter, double T0, double T1);
    ~STranslate(){}
private:
    /** vector to translate by
    */
    basegfx::B3DVector vector;
};

/** Same as SRotate, except the depth is scaled by the width of the slide divided by the width of the window.
*/
class RotateAndScaleDepthByWidth: public Operation
{
public:
    void interpolate(double t,double SlideWidthScale,double SlideHeightScale);
    RotateAndScaleDepthByWidth* clone();

    RotateAndScaleDepthByWidth(const basegfx::B3DVector& Axis,const basegfx::B3DVector& Origin,double Angle,bool bInter, double T0, double T1);
    ~RotateAndScaleDepthByWidth(){}
private:
    basegfx::B3DVector axis;
    basegfx::B3DVector origin;
    double angle;
};

#endif // INCLUDED_SLIDESHOW_TRANSITION_HXX_

<commit_msg>INTEGRATION: CWS transogl02 (1.2.4); FILE MERGED 2008/01/15 10:07:34 fridrich_strba 1.2.4.3: making copy constructor explicit makes the class unsuitable for use with stl-ish containers, thorsten dixit 2008/01/14 20:43:28 fridrich_strba 1.2.4.2: pushPrimitive should take a const reference, thorsten dixit 2007/12/10 19:03:53 radekdoulik 1.2.4.1: implemented 5 new transitions, fixed flicker problems<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: OGLTrans_TransitionImpl.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2008-01-29 08:35:14 $
 *
 *  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 2007 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 INCLUDED_OGLTRANS_TRANSITIONIMPL_HXX_
#define INCLUDED_OGLTRANS_TRANSITIONIMPL_HXX_

#include <basegfx/vector/b2dvector.hxx>
#include <basegfx/vector/b3dvector.hxx>

#include <vector>
#include <GL/gl.h>

class Primitive;
class Operation;
class SceneObject;

/** OpenGL 3D Transition class. It implicitly is constructed from XOGLTransition

    This class is capable of making itself into many difference transitions. It holds Primitives and Operations on those primitives.
*/
class OGLTransitionImpl
{
public:
    OGLTransitionImpl() :
        maLeavingSlidePrimitives(),
        maEnteringSlidePrimitives(),
        maSceneObjects()
    {}

    ~OGLTransitionImpl();

    void prepare();
    void display( double nTime, ::sal_Int32 glLeavingSlideTex, ::sal_Int32 glEnteringSlideTex, double SlideWidth, double SlideHeight, double DispWidth, double DispHeight);
    void finish();

    void makeOutsideCubeFaceToLeft();
    void makeInsideCubeFaceToLeft();
    void makeNByMTileFlip( ::sal_uInt16 n, ::sal_uInt16 m );
    void makeRevolvingCircles( ::sal_uInt16 nCircles , ::sal_uInt16 nPointsOnCircles );
    void makeHelix( ::sal_uInt16 nRows );
    void makeFallLeaving();
    void makeTurnAround();
    void makeTurnDown();
    void makeIris();
    void makeRochade();

private:
    /** clears all the primitives and operations
    */
    void clear();

    /** All the primitives that use the leaving slide texture
    */
    std::vector<Primitive> maLeavingSlidePrimitives;

    /** All the primitives that use the leaving slide texture
    */
    std::vector<Primitive> maEnteringSlidePrimitives;

    /** All the surrounding scene objects
    */
    std::vector<SceneObject*> maSceneObjects;

    /** All the operations that should be applied to both leaving and entering slide primitives. These operations will be called in the order they were pushed back in. In OpenGL this effectively uses the operations in the opposite order they were pushed back.
    */
    std::vector<Operation*> OverallOperations;
};

class SceneObject
{
public:
    SceneObject();

    virtual void prepare() {};
    virtual void display(double nTime, double SlideWidth, double SlideHeight, double DispWidth, double DispHeight);
    virtual void finish() {};

    void pushPrimitive (const Primitive &p);

protected:
    /** All the surrounding scene primitives
    */
    std::vector<Primitive> maPrimitives;
};

class Iris : public SceneObject
{
public:
    Iris ();

    virtual void prepare();
    virtual void display(double nTime, double SlideWidth, double SlideHeight, double DispWidth, double DispHeight);
    virtual void finish();

private:

    GLuint maTexture;
};

/** This class is a list of Triangles that will share Operations, and could possibly share
*/
class Primitive
{
public:
    Primitive() {}
    // making copy constructor explicit makes the class un-suitable for use with stl containers
    Primitive(const Primitive& rvalue);
    ~Primitive();

    void display(double nTime, double SlideWidthScale, double SlideHeightScale);
    const Primitive& operator=(const Primitive& rvalue);

    /** PushBack a vertex,normal, and tex coord. Each SlideLocation is where on the slide is mapped to this location ( from (0,0) to (1,1)  ). This will make sure the correct aspect ratio is used, and helps to make slides begin and end at the correct position. (0,0) is the top left of the slide, and (1,1) is the bottom right.

    @param SlideLocation0
    Location of first Vertex on slide

    @param SlideLocation1
    Location of second Vertex on slide

    @param SlideLocation2
    Location of third Vertex on slide

    */
    void pushTriangle(const basegfx::B2DVector& SlideLocation0,const basegfx::B2DVector& SlideLocation1,const basegfx::B2DVector& SlideLocation2);

    /** clear all the vertices, normals, tex coordinates, and normals
    */
    void clearTriangles();

    /** guards against directly changing the vertices

        @return
        the list of vertices
    */
    const std::vector<basegfx::B3DVector>& getVertices() const {return Vertices;}

    /** guards against directly changing the vertices
    */
    const std::vector<basegfx::B3DVector>& getNormals() const {return Normals;}

    /** guards against directly changing the vertices

        @return
        the list of Texture Coordinates

    */
    const std::vector<basegfx::B2DVector>& getTexCoords() const {return TexCoords;}

    /** list of Operations to be performed on this primitive.These operations will be called in the order they were pushed back in. In OpenGL this effectively uses the operations in the opposite order they were pushed back.

        @return
        the list of Operations

    */
    std::vector<Operation*> Operations;

private:
    /** list of vertices
    */
    std::vector<basegfx::B3DVector> Vertices;

    /** list of Normals
    */
    std::vector<basegfx::B3DVector> Normals;

    /** list of Texture Coordinates
    */
    std::vector<basegfx::B2DVector> TexCoords;
};

/** This class is to be derived to make any operation (tranform) you may need in order to construct your transitions
*/
class Operation
{
public:
    Operation(){}
    virtual ~Operation(){}

    /** Should this operation be interpolated . If TRUE, the transform will smoothly move from making no difference from t = 0.0 to nT0 to being completely transformed from t = nT1 to 1. If FALSE, the transform will be inneffectual from t = 0 to nT0, and completely transformed from t = nT0 to 1.
    */
    bool bInterpolate;

    /** time to begin the transformation
    */
    double nT0;

    /** time to finish the transformation
    */
    double nT1;
public:
    /** this is the function that is called to give the Operation to OpenGL.

        @param t
        time from t = 0 to t = 1

        @param SlideWidthScale
        width of slide divided by width of window

        @param SlideHeightScale
        height of slide divided by height of window

    */
    virtual void interpolate(double t,double SlideWidthScale,double SlideHeightScale) = 0;

    /** return a copy of this operation
    */
    virtual Operation* clone() = 0;
};

/** this class is a generic CounterClockWise(CCW) rotation with an axis angle
*/
class SRotate: public Operation
{
public:
    void interpolate(double t,double SlideWidthScale,double SlideHeightScale);
    virtual SRotate* clone();

    /** Constructor

        @param Axis
        axis to rotate about

        @param Origin
        position that rotation axis runs through

        @param Angle
        angle in radians of CCW rotation

        @param bInter
        see Operation

        @param T0
        transformation starting time

        @param T1
        transformation ending time

    */
    SRotate(const basegfx::B3DVector& Axis,const basegfx::B3DVector& Origin,double Angle,bool bInter, double T0, double T1);
    ~SRotate(){}
private:
    /** axis to rotate CCW about
    */
    basegfx::B3DVector axis;

    /** position that rotation axis runs through
    */
    basegfx::B3DVector origin;

    /** angle in radians of CCW rotation
    */
    double angle;
};

/** scaling transformation
*/
class SScale: public Operation
{
public:
    void interpolate(double t,double SlideWidthScale,double SlideHeightScale);
    SScale* clone();

    /** Constructor

        @param Scale
        amount to scale by

        @param Origin
        position that rotation axis runs through

        @param bInter
        see Operation

        @param T0
        transformation starting time

        @param T1
        transformation ending time

    */
    SScale(const basegfx::B3DVector& Scale, const basegfx::B3DVector& Origin,bool bInter, double T0, double T1);
    ~SScale(){}
private:
    basegfx::B3DVector scale;
    basegfx::B3DVector origin;
};

/** translation transformation
*/
class STranslate: public Operation
{
public:
    void interpolate(double t,double SlideWidthScale,double SlideHeightScale);
    STranslate* clone();

    /** Constructor

        @param Vector
        vector to translate

        @param bInter
        see Operation

        @param T0
        transformation starting time

        @param T1
        transformation ending time

    */
    STranslate(const basegfx::B3DVector& Vector,bool bInter, double T0, double T1);
    ~STranslate(){}
private:
    /** vector to translate by
    */
    basegfx::B3DVector vector;
};

/** translation transformation
*/
class SEllipseTranslate: public Operation
{
public:
    void interpolate(double t,double SlideWidthScale,double SlideHeightScale);
    SEllipseTranslate* clone();

    /** Constructor

        @param Vector
        vector to translate

        @param bInter
        see Operation

        @param T0
        transformation starting time

        @param T1
        transformation ending time

    */
    SEllipseTranslate(double dWidth, double dHeight, double dStartPosition, double dEndPosition, bool bInter, double T0, double T1);
    ~SEllipseTranslate(){}
private:
    /** width and length of the ellipse
     */
    double width, height;

    /** start and end position on the ellipse <0,1>
     */
    double startPosition;
    double endPosition;
};

/** Same as SRotate, except the depth is scaled by the width of the slide divided by the width of the window.
*/
class RotateAndScaleDepthByWidth: public Operation
{
public:
    void interpolate(double t,double SlideWidthScale,double SlideHeightScale);
    RotateAndScaleDepthByWidth* clone();

    RotateAndScaleDepthByWidth(const basegfx::B3DVector& Axis,const basegfx::B3DVector& Origin,double Angle,bool bInter, double T0, double T1);
    ~RotateAndScaleDepthByWidth(){}
private:
    basegfx::B3DVector axis;
    basegfx::B3DVector origin;
    double angle;
};

#endif // INCLUDED_SLIDESHOW_TRANSITION_HXX_

<|endoftext|>


<commit_before>#include "async.h"
#include "dbfe.h"
#include "merkle_misc.h"
#include "merkle_hash.h"

#define MODE_ENV 1
#define MODE_OLD 2

int
main (int argc, char *argv[])
{
  if (argc != 3)
    fatal << "usage: dbdump <-e|-o> <dbfile>\n";

  int mode = MODE_ENV;
  if (strcmp(argv[1], "-o") == 0)
    mode = MODE_OLD;

  int r;
  DB *db = NULL;
  DB_ENV* dbe = NULL;
  char cpath[MAXPATHLEN];

  if (mode == MODE_ENV) {

    r = db_env_create (&dbe, 0);
    assert (!r);
    r = chdir (argv[2]);
    if (r == -1) fatal << "couldn't chdir to " << argv[2] << "\n";

    getcwd (cpath, MAXPATHLEN);
    warn << "opening db in: " << cpath << "\n";
    r = dbe->set_data_dir (dbe, cpath);
    assert (!r);
    r = dbe->set_lg_dir (dbe, cpath);
    assert (!r);
    r = dbe->set_tmp_dir (dbe, cpath);
    assert (!r);

    dbe->set_errfile (dbe, stdout);
    r = dbe->open (dbe, NULL,
		   DB_JOINENV,
		   //		   DB_CREATE| DB_INIT_MPOOL | DB_INIT_LOCK |
		   // DB_INIT_LOG | DB_INIT_TXN | DB_RECOVER | DB_JOINENV,
		   0);
    assert (!r);

  }

  r = db_create(&db, dbe, 0);
  assert (r==0);

  if (mode == MODE_OLD) {
#if ((DB_VERSION_MAJOR < 4) || ((DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR < 1)))
    r = db->open(db, (const char *)argv[2], NULL, DB_BTREE, DB_RDONLY, 0664);
#else
    r = db->open(db, NULL, (const char *)argv[2], NULL,
		 DB_BTREE, DB_RDONLY, 0664);
#endif

} else {
#if ((DB_VERSION_MAJOR < 4) || ((DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR < 1)))
  r = db->open(db, "db", NULL, DB_BTREE, DB_RDONLY, 0664);
#else
  r = db->open(db, NULL, "db", NULL, DB_BTREE, DB_RDONLY, 0664);
#endif

}

  assert (r == 0);

  DBC *cursor;
  r = db->cursor(db, NULL, &cursor, 0);
  assert (r==0);

  DBT key, data;
  unsigned totalsz = 0;
  unsigned keys = 0;

  for (int i = 0; ; i++) {
    bzero (&key, sizeof (key));
    bzero (&data, sizeof (data));
    //data.flags = DB_DBT_PARTIAL;
    int err = cursor->c_get(cursor, &key, &data,
			    ((i==0) ? DB_FIRST : DB_NEXT));
    if (err == DB_NOTFOUND) {
      warn << "EOF.\n";
      break;
    } else if (err) {
      fatal << "err: " << err << " " << strerror (err) << "\n";
    }
    warn << "key[" << i << "] " << hexdump (key.data, key.size) << "\n";
    ptr<dbrec> kr = New refcounted<dbrec> (key.data, key.size);

    warn << "key[" << i << "] " << to_merkle_hash (kr) << "\n";

    bzero (&data, sizeof (data));
    err = db->get (db, NULL, &key, &data, 0);
    if (err)
      warn << "lookup err: " << err << " " << strerror (err) << "\n";

    keys++;
    totalsz += data.size;

    err_flush ();
  }

  db->close (db, 0);
  dbe->close (dbe, 0);
  warn << "total keys: " << keys << "\n";
  warn << "total bytes: " << totalsz << "\n";
}

<commit_msg>send dbdump output to stdout and don't print merkle hashes for easier parsing<commit_after>#include "async.h"
#include "dbfe.h"
#include "merkle_misc.h"
#include "merkle_hash.h"

#define MODE_ENV 1
#define MODE_OLD 2

int
main (int argc, char *argv[])
{
  if (argc != 3)
    fatal << "usage: dbdump <-e|-o> <dbfile>\n";

  int mode = MODE_ENV;
  if (strcmp(argv[1], "-o") == 0)
    mode = MODE_OLD;

  int r;
  DB *db = NULL;
  DB_ENV* dbe = NULL;
  char cpath[MAXPATHLEN];

  errfd = 1;

  if (mode == MODE_ENV) {

    r = db_env_create (&dbe, 0);
    assert (!r);
    r = chdir (argv[2]);
    if (r == -1) fatal << "couldn't chdir to " << argv[2] << "\n";

    getcwd (cpath, MAXPATHLEN);
    warn << "opening db in: " << cpath << "\n";
    r = dbe->set_data_dir (dbe, cpath);
    assert (!r);
    r = dbe->set_lg_dir (dbe, cpath);
    assert (!r);
    r = dbe->set_tmp_dir (dbe, cpath);
    assert (!r);

    dbe->set_errfile (dbe, stdout);
    r = dbe->open (dbe, NULL,
		   DB_JOINENV,
		   //		   DB_CREATE| DB_INIT_MPOOL | DB_INIT_LOCK |
		   // DB_INIT_LOG | DB_INIT_TXN | DB_RECOVER | DB_JOINENV,
		   0);
    assert (!r);

  }

  r = db_create(&db, dbe, 0);
  assert (r==0);

  if (mode == MODE_OLD) {
#if ((DB_VERSION_MAJOR < 4) || ((DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR < 1)))
    r = db->open(db, (const char *)argv[2], NULL, DB_BTREE, DB_RDONLY, 0664);
#else
    r = db->open(db, NULL, (const char *)argv[2], NULL,
		 DB_BTREE, DB_RDONLY, 0664);
#endif

} else {
#if ((DB_VERSION_MAJOR < 4) || ((DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR < 1)))
  r = db->open(db, "db", NULL, DB_BTREE, DB_RDONLY, 0664);
#else
  r = db->open(db, NULL, "db", NULL, DB_BTREE, DB_RDONLY, 0664);
#endif

}

  assert (r == 0);

  DBC *cursor;
  r = db->cursor(db, NULL, &cursor, 0);
  assert (r==0);

  DBT key, data;
  unsigned totalsz = 0;
  unsigned keys = 0;

  for (int i = 0; ; i++) {
    bzero (&key, sizeof (key));
    bzero (&data, sizeof (data));
    //data.flags = DB_DBT_PARTIAL;
    int err = cursor->c_get(cursor, &key, &data,
			    ((i==0) ? DB_FIRST : DB_NEXT));
    if (err == DB_NOTFOUND) {
      warn << "EOF.\n";
      break;
    } else if (err) {
      fatal << "err: " << err << " " << strerror (err) << "\n";
    }
    warn << "key[" << i << "] " << hexdump (key.data, key.size) << "\n";
    //   ptr<dbrec> kr = New refcounted<dbrec> (key.data, key.size);

    //warn << "key[" << i << "] " << to_merkle_hash (kr) << "\n";

    bzero (&data, sizeof (data));
    err = db->get (db, NULL, &key, &data, 0);
    if (err)
      warn << "lookup err: " << err << " " << strerror (err) << "\n";

    keys++;
    totalsz += data.size;

    err_flush ();
  }

  db->close (db, 0);
  dbe->close (dbe, 0);
  warn << "total keys: " << keys << "\n";
  warn << "total bytes: " << totalsz << "\n";
}

<|endoftext|>