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

#include "sync.h"

#include "util.h"
#include "utilstrencodings.h"

#include <stdio.h>

#include <boost/foreach.hpp>
#include <boost/thread.hpp>

#ifdef DEBUG_LOCKCONTENTION
void PrintLockContention(const char* pszName, const char* pszFile, int nLine)
{
    LogPrintf("LOCKCONTENTION: %s\n", pszName);
    LogPrintf("Locker: %s:%d\n", pszFile, nLine);
}
#endif /* DEBUG_LOCKCONTENTION */

#ifdef DEBUG_LOCKORDER
//
// Early deadlock detection.
// Problem being solved:
//    Thread 1 locks  A, then B, then C
//    Thread 2 locks  D, then C, then A
//     --> may result in deadlock between the two threads, depending on when they run.
// Solution implemented here:
// Keep track of pairs of locks: (A before B), (A before C), etc.
// Complain if any thread tries to lock in a different order.
//

struct CLockLocation {
    CLockLocation(const char* pszName, const char* pszFile, int nLine, bool fTryIn)
    {
        mutexName = pszName;
        sourceFile = pszFile;
        sourceLine = nLine;
        fTry = fTryIn;
    }

    std::string ToString() const
    {
        return mutexName + "  " + sourceFile + ":" + itostr(sourceLine) + (fTry ? " (TRY)" : "");
    }

    std::string MutexName() const { return mutexName; }

    bool fTry;
private:
    std::string mutexName;
    std::string sourceFile;
    int sourceLine;
};

typedef std::vector<std::pair<void*, CLockLocation> > LockStack;
typedef std::map<std::pair<void*, void*>, LockStack> LockOrders;
typedef std::set<std::pair<void*, void*> > InvLockOrders;

struct LockData {
    // Very ugly hack: as the global constructs and destructors run single
    // threaded, we use this boolean to know whether LockData still exists,
    // as DeleteLock can get called by global CCriticalSection destructors
    // after LockData disappears.
    bool available;
    LockData() : available(true) {}
    ~LockData() { available = false; }

    LockOrders lockorders;
    InvLockOrders invlockorders;
    boost::mutex dd_mutex;
} static lockdata;

boost::thread_specific_ptr<LockStack> lockstack;

static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
{
    LogPrintf("POTENTIAL DEADLOCK DETECTED\n");
    LogPrintf("Previous lock order was:\n");
    BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, s2) {
        if (i.first == mismatch.first) {
            LogPrintf(" (1)");
        }
        if (i.first == mismatch.second) {
            LogPrintf(" (2)");
        }
        LogPrintf(" %s\n", i.second.ToString());
    }
    LogPrintf("Current lock order is:\n");
    BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, s1) {
        if (i.first == mismatch.first) {
            LogPrintf(" (1)");
        }
        if (i.first == mismatch.second) {
            LogPrintf(" (2)");
        }
        LogPrintf(" %s\n", i.second.ToString());
    }
    assert(false);
}

static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
{
    if (lockstack.get() == NULL)
        lockstack.reset(new LockStack);

    boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex);

    (*lockstack).push_back(std::make_pair(c, locklocation));

    if (!fTry) {
        BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, (*lockstack)) {
            if (i.first == c)
                break;

            std::pair<void*, void*> p1 = std::make_pair(i.first, c);
            if (lockdata.lockorders.count(p1))
                continue;
            lockdata.lockorders[p1] = (*lockstack);

            std::pair<void*, void*> p2 = std::make_pair(c, i.first);
            lockdata.invlockorders.insert(p2);
            if (lockdata.lockorders.count(p2))
                potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]);
        }
    }
}

static void pop_lock()
{
    (*lockstack).pop_back();
}

void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
{
    push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry), fTry);
}

void LeaveCritical()
{
    pop_lock();
}

std::string LocksHeld()
{
    std::string result;
    BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, *lockstack)
        result += i.second.ToString() + std::string("\n");
    return result;
}

void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)
{
    BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, *lockstack)
        if (i.first == cs)
            return;
    fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str());
    abort();
}

void DeleteLock(void* cs)
{
    if (!lockdata.available) {
        // We're already shutting down.
        return;
    }
    boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex);
    std::pair<void*, void*> item = std::make_pair(cs, (void*)0);
    LockOrders::iterator it = lockdata.lockorders.lower_bound(item);
    while (it != lockdata.lockorders.end() && it->first.first == cs) {
        std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first);
        lockdata.invlockorders.erase(invitem);
        lockdata.lockorders.erase(it++);
    }
    InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item);
    while (invit != lockdata.invlockorders.end() && invit->first == cs) {
        std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first);
        lockdata.lockorders.erase(invinvitem);
        lockdata.invlockorders.erase(invit++);
    }
}

#endif /* DEBUG_LOCKORDER */
<commit_msg>Further-enforce lockordering by enforcing directly after TRY_LOCKs<commit_after>// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "sync.h"

#include "util.h"
#include "utilstrencodings.h"

#include <stdio.h>

#include <boost/foreach.hpp>
#include <boost/thread.hpp>

#ifdef DEBUG_LOCKCONTENTION
void PrintLockContention(const char* pszName, const char* pszFile, int nLine)
{
    LogPrintf("LOCKCONTENTION: %s\n", pszName);
    LogPrintf("Locker: %s:%d\n", pszFile, nLine);
}
#endif /* DEBUG_LOCKCONTENTION */

#ifdef DEBUG_LOCKORDER
//
// Early deadlock detection.
// Problem being solved:
//    Thread 1 locks  A, then B, then C
//    Thread 2 locks  D, then C, then A
//     --> may result in deadlock between the two threads, depending on when they run.
// Solution implemented here:
// Keep track of pairs of locks: (A before B), (A before C), etc.
// Complain if any thread tries to lock in a different order.
//

struct CLockLocation {
    CLockLocation(const char* pszName, const char* pszFile, int nLine, bool fTryIn)
    {
        mutexName = pszName;
        sourceFile = pszFile;
        sourceLine = nLine;
        fTry = fTryIn;
    }

    std::string ToString() const
    {
        return mutexName + "  " + sourceFile + ":" + itostr(sourceLine) + (fTry ? " (TRY)" : "");
    }

    std::string MutexName() const { return mutexName; }

    bool fTry;
private:
    std::string mutexName;
    std::string sourceFile;
    int sourceLine;
};

typedef std::vector<std::pair<void*, CLockLocation> > LockStack;
typedef std::map<std::pair<void*, void*>, LockStack> LockOrders;
typedef std::set<std::pair<void*, void*> > InvLockOrders;

struct LockData {
    // Very ugly hack: as the global constructs and destructors run single
    // threaded, we use this boolean to know whether LockData still exists,
    // as DeleteLock can get called by global CCriticalSection destructors
    // after LockData disappears.
    bool available;
    LockData() : available(true) {}
    ~LockData() { available = false; }

    LockOrders lockorders;
    InvLockOrders invlockorders;
    boost::mutex dd_mutex;
} static lockdata;

boost::thread_specific_ptr<LockStack> lockstack;

static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
{
    LogPrintf("POTENTIAL DEADLOCK DETECTED\n");
    LogPrintf("Previous lock order was:\n");
    BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, s2) {
        if (i.first == mismatch.first) {
            LogPrintf(" (1)");
        }
        if (i.first == mismatch.second) {
            LogPrintf(" (2)");
        }
        LogPrintf(" %s\n", i.second.ToString());
    }
    LogPrintf("Current lock order is:\n");
    BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, s1) {
        if (i.first == mismatch.first) {
            LogPrintf(" (1)");
        }
        if (i.first == mismatch.second) {
            LogPrintf(" (2)");
        }
        LogPrintf(" %s\n", i.second.ToString());
    }
    assert(false);
}

static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
{
    if (lockstack.get() == NULL)
        lockstack.reset(new LockStack);

    boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex);

    (*lockstack).push_back(std::make_pair(c, locklocation));

    BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, (*lockstack)) {
        if (i.first == c)
            break;

        std::pair<void*, void*> p1 = std::make_pair(i.first, c);
        if (lockdata.lockorders.count(p1))
            continue;
        lockdata.lockorders[p1] = (*lockstack);

        std::pair<void*, void*> p2 = std::make_pair(c, i.first);
        lockdata.invlockorders.insert(p2);
        if (lockdata.lockorders.count(p2))
            potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]);
    }
}

static void pop_lock()
{
    (*lockstack).pop_back();
}

void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
{
    push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry), fTry);
}

void LeaveCritical()
{
    pop_lock();
}

std::string LocksHeld()
{
    std::string result;
    BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, *lockstack)
        result += i.second.ToString() + std::string("\n");
    return result;
}

void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)
{
    BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, *lockstack)
        if (i.first == cs)
            return;
    fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str());
    abort();
}

void DeleteLock(void* cs)
{
    if (!lockdata.available) {
        // We're already shutting down.
        return;
    }
    boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex);
    std::pair<void*, void*> item = std::make_pair(cs, (void*)0);
    LockOrders::iterator it = lockdata.lockorders.lower_bound(item);
    while (it != lockdata.lockorders.end() && it->first.first == cs) {
        std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first);
        lockdata.invlockorders.erase(invitem);
        lockdata.lockorders.erase(it++);
    }
    InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item);
    while (invit != lockdata.invlockorders.end() && invit->first == cs) {
        std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first);
        lockdata.lockorders.erase(invinvitem);
        lockdata.invlockorders.erase(invit++);
    }
}

#endif /* DEBUG_LOCKORDER */
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 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 "txdb.h"
#include "main.h"

using namespace std;

void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
    if (coins.IsPruned())
        batch.Erase(make_pair('c', hash));
    else
        batch.Write(make_pair('c', hash), coins);
}

void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
    batch.Write('B', hash);
}

CCoinsViewDB::CCoinsViewDB(bool fMemory) : db(GetDataDir() / "coins", fMemory) {
}

bool CCoinsViewDB::GetCoins(uint256 txid, CCoins &coins) {
    return db.Read(make_pair('c', txid), coins);
}

bool CCoinsViewDB::SetCoins(uint256 txid, const CCoins &coins) {
    CLevelDBBatch batch;
    BatchWriteCoins(batch, txid, coins);
    return db.WriteBatch(batch);
}

bool CCoinsViewDB::HaveCoins(uint256 txid) {
    return db.Exists(make_pair('c', txid));
}

CBlockIndex *CCoinsViewDB::GetBestBlock() {
    uint256 hashBestChain;
    if (!db.Read('B', hashBestChain))
        return NULL;
    std::map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(hashBestChain);
    if (it == mapBlockIndex.end())
        return NULL;
    return it->second;
}

bool CCoinsViewDB::SetBestBlock(CBlockIndex *pindex) {
    CLevelDBBatch batch;
    BatchWriteHashBestChain(batch, pindex->GetBlockHash());
    return db.WriteBatch(batch);
}

bool CCoinsViewDB::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
    printf("Committing %u changed transactions to coin database...\n", (unsigned int)mapCoins.size());

    CLevelDBBatch batch;
    for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
        BatchWriteCoins(batch, it->first, it->second);
    BatchWriteHashBestChain(batch, pindex->GetBlockHash());

    return db.WriteBatch(batch);
}

CBlockTreeDB::CBlockTreeDB(bool fMemory) : CLevelDB(GetDataDir() / "blktree", fMemory) {
}

bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
{
    return Write(make_pair('b', blockindex.GetBlockHash()), blockindex);
}

bool CBlockTreeDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
{
    return Read('I', bnBestInvalidWork);
}

bool CBlockTreeDB::WriteBestInvalidWork(const CBigNum& bnBestInvalidWork)
{
    return Write('I', bnBestInvalidWork);
}

bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) {
    return Write(make_pair('f', nFile), info);
}

bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
    return Read(make_pair('f', nFile), info);
}

bool CBlockTreeDB::WriteLastBlockFile(int nFile) {
    return Write('l', nFile);
}

bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
    return Read('l', nFile);
}

bool CCoinsViewDB::GetStats(CCoinsStats &stats) {
    leveldb::Iterator *pcursor = db.NewIterator();
    pcursor->SeekToFirst();

    while (pcursor->Valid()) {
        try {
            leveldb::Slice slKey = pcursor->key();
            CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
            char chType;
            ssKey >> chType;
            if (chType == 'c' && !fRequestShutdown) {
                leveldb::Slice slValue = pcursor->value();
                CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
                CCoins coins;
                ssValue >> coins;
                uint256 txhash;
                ssKey >> txhash;

                stats.nTransactions++;
                BOOST_FOREACH(const CTxOut &out, coins.vout) {
                    if (!out.IsNull())
                        stats.nTransactionOutputs++;
                }
                stats.nSerializedSize += 32 + slValue.size();
            }
            pcursor->Next();
        } catch (std::exception &e) {
            return error("%s() : deserialize error", __PRETTY_FUNCTION__);
        }
    }
    delete pcursor;
    stats.nHeight = GetBestBlock()->nHeight;
    return true;
}

bool CBlockTreeDB::LoadBlockIndexGuts()
{
    leveldb::Iterator *pcursor = NewIterator();

    CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
    ssKeySet << make_pair('b', uint256(0));
    pcursor->Seek(ssKeySet.str());

    // Load mapBlockIndex
    while (pcursor->Valid()) {
        try {
            leveldb::Slice slKey = pcursor->key();
            CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
            char chType;
            ssKey >> chType;
            if (chType == 'b' && !fRequestShutdown) {
                leveldb::Slice slValue = pcursor->value();
                CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
                CDiskBlockIndex diskindex;
                ssValue >> diskindex;

                // Construct block index object
                CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
                pindexNew->pprev          = InsertBlockIndex(diskindex.hashPrev);
                pindexNew->nHeight        = diskindex.nHeight;
                pindexNew->nFile          = diskindex.nFile;
                pindexNew->nDataPos       = diskindex.nDataPos;
                pindexNew->nUndoPos       = diskindex.nUndoPos;
                pindexNew->nVersion       = diskindex.nVersion;
                pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
                pindexNew->nTime          = diskindex.nTime;
                pindexNew->nBits          = diskindex.nBits;
                pindexNew->nNonce         = diskindex.nNonce;
                pindexNew->nStatus        = diskindex.nStatus;
                pindexNew->nTx            = diskindex.nTx;

                // Watch for genesis block
                if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
                    pindexGenesisBlock = pindexNew;

                if (!pindexNew->CheckIndex())
                    return error("LoadBlockIndex() : CheckIndex failed: %s", pindexNew->ToString().c_str());

                pcursor->Next();
            } else {
                break; // if shutdown requested or finished loading block index
            }
        } catch (std::exception &e) {
            return error("%s() : deserialize error", __PRETTY_FUNCTION__);
        }
    }
    delete pcursor;

    return true;
}
<commit_msg>Bugfix: don't crash by trying to write unchanged best block<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 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 "txdb.h"
#include "main.h"

using namespace std;

void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
    if (coins.IsPruned())
        batch.Erase(make_pair('c', hash));
    else
        batch.Write(make_pair('c', hash), coins);
}

void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
    batch.Write('B', hash);
}

CCoinsViewDB::CCoinsViewDB(bool fMemory) : db(GetDataDir() / "coins", fMemory) {
}

bool CCoinsViewDB::GetCoins(uint256 txid, CCoins &coins) {
    return db.Read(make_pair('c', txid), coins);
}

bool CCoinsViewDB::SetCoins(uint256 txid, const CCoins &coins) {
    CLevelDBBatch batch;
    BatchWriteCoins(batch, txid, coins);
    return db.WriteBatch(batch);
}

bool CCoinsViewDB::HaveCoins(uint256 txid) {
    return db.Exists(make_pair('c', txid));
}

CBlockIndex *CCoinsViewDB::GetBestBlock() {
    uint256 hashBestChain;
    if (!db.Read('B', hashBestChain))
        return NULL;
    std::map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(hashBestChain);
    if (it == mapBlockIndex.end())
        return NULL;
    return it->second;
}

bool CCoinsViewDB::SetBestBlock(CBlockIndex *pindex) {
    CLevelDBBatch batch;
    BatchWriteHashBestChain(batch, pindex->GetBlockHash());
    return db.WriteBatch(batch);
}

bool CCoinsViewDB::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
    printf("Committing %u changed transactions to coin database...\n", (unsigned int)mapCoins.size());

    CLevelDBBatch batch;
    for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
        BatchWriteCoins(batch, it->first, it->second);
    if (pindex)
        BatchWriteHashBestChain(batch, pindex->GetBlockHash());

    return db.WriteBatch(batch);
}

CBlockTreeDB::CBlockTreeDB(bool fMemory) : CLevelDB(GetDataDir() / "blktree", fMemory) {
}

bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
{
    return Write(make_pair('b', blockindex.GetBlockHash()), blockindex);
}

bool CBlockTreeDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
{
    return Read('I', bnBestInvalidWork);
}

bool CBlockTreeDB::WriteBestInvalidWork(const CBigNum& bnBestInvalidWork)
{
    return Write('I', bnBestInvalidWork);
}

bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) {
    return Write(make_pair('f', nFile), info);
}

bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
    return Read(make_pair('f', nFile), info);
}

bool CBlockTreeDB::WriteLastBlockFile(int nFile) {
    return Write('l', nFile);
}

bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
    return Read('l', nFile);
}

bool CCoinsViewDB::GetStats(CCoinsStats &stats) {
    leveldb::Iterator *pcursor = db.NewIterator();
    pcursor->SeekToFirst();

    while (pcursor->Valid()) {
        try {
            leveldb::Slice slKey = pcursor->key();
            CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
            char chType;
            ssKey >> chType;
            if (chType == 'c' && !fRequestShutdown) {
                leveldb::Slice slValue = pcursor->value();
                CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
                CCoins coins;
                ssValue >> coins;
                uint256 txhash;
                ssKey >> txhash;

                stats.nTransactions++;
                BOOST_FOREACH(const CTxOut &out, coins.vout) {
                    if (!out.IsNull())
                        stats.nTransactionOutputs++;
                }
                stats.nSerializedSize += 32 + slValue.size();
            }
            pcursor->Next();
        } catch (std::exception &e) {
            return error("%s() : deserialize error", __PRETTY_FUNCTION__);
        }
    }
    delete pcursor;
    stats.nHeight = GetBestBlock()->nHeight;
    return true;
}

bool CBlockTreeDB::LoadBlockIndexGuts()
{
    leveldb::Iterator *pcursor = NewIterator();

    CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
    ssKeySet << make_pair('b', uint256(0));
    pcursor->Seek(ssKeySet.str());

    // Load mapBlockIndex
    while (pcursor->Valid()) {
        try {
            leveldb::Slice slKey = pcursor->key();
            CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
            char chType;
            ssKey >> chType;
            if (chType == 'b' && !fRequestShutdown) {
                leveldb::Slice slValue = pcursor->value();
                CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
                CDiskBlockIndex diskindex;
                ssValue >> diskindex;

                // Construct block index object
                CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
                pindexNew->pprev          = InsertBlockIndex(diskindex.hashPrev);
                pindexNew->nHeight        = diskindex.nHeight;
                pindexNew->nFile          = diskindex.nFile;
                pindexNew->nDataPos       = diskindex.nDataPos;
                pindexNew->nUndoPos       = diskindex.nUndoPos;
                pindexNew->nVersion       = diskindex.nVersion;
                pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
                pindexNew->nTime          = diskindex.nTime;
                pindexNew->nBits          = diskindex.nBits;
                pindexNew->nNonce         = diskindex.nNonce;
                pindexNew->nStatus        = diskindex.nStatus;
                pindexNew->nTx            = diskindex.nTx;

                // Watch for genesis block
                if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
                    pindexGenesisBlock = pindexNew;

                if (!pindexNew->CheckIndex())
                    return error("LoadBlockIndex() : CheckIndex failed: %s", pindexNew->ToString().c_str());

                pcursor->Next();
            } else {
                break; // if shutdown requested or finished loading block index
            }
        } catch (std::exception &e) {
            return error("%s() : deserialize error", __PRETTY_FUNCTION__);
        }
    }
    delete pcursor;

    return true;
}
<|endoftext|>


<commit_before>#include <cmath>
#include <cstdarg>
#include <assert.h>

#include "opencv2/opencv.hpp"
using namespace cv;

#include "structures.hpp"
#include "util.hpp"

void showImage(const char* title, const Mat& img)
{
	std::cout << "\nShowing image: \"" << title << "\"." << std::endl;
	namedWindow(title, CV_WINDOW_NORMAL);
	imshow(title, img);
}

void showImageAndWait(const char* title, const Mat& img)
{
	showImage(title, img);
	std::cout << "Press any key to continue..." << std::endl;
	waitKey(0);
}

Point3f backproject3D(const float x,const float y, float depth, const Mat m_cameraMatrix)
{
	Mat new_point = depth * (Mat_<float>(1,3) << x,y,1) * m_cameraMatrix.inv().t();
	return Point3f(new_point);
}

/**
 * Custom logger, instantiate with namespace string to prefix messages with.
 * For example:
 *     Logger _log("Load Images");
 */
Logger::Logger(const char* _namespace)
	: name_space(_namespace), start(ch::system_clock::now())
{}

void Logger::operator() (const char* format, ...)
{
	va_list args;
	va_start(args, format);

	printf("%s>\t", name_space);
	vprintf(format, args);
	printf("\n");

	va_end(args);
}

void Logger::tok()
{
	const clock_t    end = ch::system_clock::now();
	ch::milliseconds dur = ch::duration_cast<ch::milliseconds>(end - start);
	(*this)("Done in %.2fs.", (float)dur.count() / 1e3);
}

/*
 * convert rotation matrix to quaternion
*/
Vec4f R2Quaternion(Mat& R)
{
	assert(R.rows == 3 && R.cols == 3);
	// typedef typename DataType<float>::work_type _wTp;
	if (R.type() != CV_32F) R.convertTo(R, CV_32F);;
	float q0,q1,q2,q3;
	float r00 = R.at<float>(0,0);
	float r01 = R.at<float>(0,1);
	float r02 = R.at<float>(0,2);
	float r10 = R.at<float>(1,0);
	float r11 = R.at<float>(1,1);
	float r12 = R.at<float>(1,2);
	float r20 = R.at<float>(2,0);
	float r21 = R.at<float>(2,1);
	float r22 = R.at<float>(2,2);

	float trace = r00 + r11 + r22;
	if( trace > 0 ){
		float s = 0.5 / sqrt(trace+ 1.0);
    	q0 = 0.25 / s;
    	q1 = ( r21 - r12 ) * s;
    	q2 = ( r02 - r20 ) * s;
    	q3 = ( r10 - r01 ) * s;
	} else {
    	if ( r00 > r11 && r00 > r22 )
    	{
      	float s = 2.0 * sqrt( 1.0 + r00 - r11 - r22);
      	q0 = (r21 - r12 ) / s;
      	q1 = 0.25 * s;
      	q2 = (r01 + r10 ) / s;
      	q3 = (r02 + r20 ) / s;
    	} else if (r11 > r22) {
	    float s = 2.0 * sqrt( 1.0 + r11 - r00 - r22);
	    q0 = (r02 - r20 ) / s;
	    q1 = (r01 + r10 ) / s;
	    q2 = 0.25 * s;
	    q3 = (r12 + r21 ) / s;
    	} else {
      	float s = 2.0 * sqrt( 1.0 + r22 - r00 - r11 );
      	q0 = (r10 - r01 ) / s;
	    q1 = (r02 + r20 ) / s;
	    q2 = (r12 + r21 ) / s;
	    q3 = 0.25 * s;
    	}
	}
	Vec4f q = normalize(Vec<float,4>::Vec(q0, q1, q2, q3));
	return q;
}

Mat quat2R(Vec4f& q){

    float sqw = q[0]*q[0];
    float sqx = q[1]*q[1];
    float sqy = q[2]*q[2];
    float sqz = q[3]*q[3];

    // invs (inverse square length) is only required if quaternion is not already normalised
    float invs = 1 / (sqx + sqy + sqz + sqw);
    float m00 = ( sqx - sqy - sqz + sqw)*invs ; // since sqw + sqx + sqy + sqz =1/invs*invs
    float m11 = (-sqx + sqy - sqz + sqw)*invs ;
    float m22 = (-sqx - sqy + sqz + sqw)*invs ;

    float tmp1 = q[1]*q[2];
    float tmp2 = q[3]*q[0];
    float m10 = 2.0 * (tmp1 + tmp2)*invs ;
    float m01 = 2.0 * (tmp1 - tmp2)*invs ;

    tmp1 = q[1]*q[3];
    tmp2 = q[2]*q[0];
    float m20 = 2.0 * (tmp1 - tmp2)*invs ;
    float m02 = 2.0 * (tmp1 + tmp2)*invs ;
    tmp1 = q[2]*q[3];
    tmp2 = q[1]*q[0];
    float m21 = 2.0 * (tmp1 + tmp2)*invs ;
    float m12 = 2.0 * (tmp1 - tmp2)*invs ;
    Mat R = (Mat_<float>(3,3) << m00, m01, m02, m10, m11, m12, m20, m21, m22);
    return R;
}

bool checkCoherentRotation(cv::Mat& R) {

	if(fabs(determinant(R))-1.0 > 1e-05) return false;
	return true;
}

bool checkCoherentQ(Vec4f& q0, Vec4f& q1)
{
	Vec4f absdelta,reldelta;
	absdiff(q0,q1,absdelta);
	divide(absdelta,q1,reldelta);
	if (reldelta[0]>0.05 ||reldelta[1]>0.05 ||reldelta[2]>0.05 ||reldelta[3]>0.05)
		return false;
	return true;
}

<commit_msg>Fix Vec4f constructor in util<commit_after>#include <cmath>
#include <cstdarg>
#include <assert.h>

#include "opencv2/opencv.hpp"
using namespace cv;

#include "structures.hpp"
#include "util.hpp"

void showImage(const char* title, const Mat& img)
{
	std::cout << "\nShowing image: \"" << title << "\"." << std::endl;
	namedWindow(title, CV_WINDOW_NORMAL);
	imshow(title, img);
}

void showImageAndWait(const char* title, const Mat& img)
{
	showImage(title, img);
	std::cout << "Press any key to continue..." << std::endl;
	waitKey(0);
}

Point3f backproject3D(const float x,const float y, float depth, const Mat m_cameraMatrix)
{
	Mat new_point = depth * (Mat_<float>(1,3) << x,y,1) * m_cameraMatrix.inv().t();
	return Point3f(new_point);
}

/**
 * Custom logger, instantiate with namespace string to prefix messages with.
 * For example:
 *     Logger _log("Load Images");
 */
Logger::Logger(const char* _namespace)
	: name_space(_namespace), start(ch::system_clock::now())
{}

void Logger::operator() (const char* format, ...)
{
	va_list args;
	va_start(args, format);

	printf("%s>\t", name_space);
	vprintf(format, args);
	printf("\n");

	va_end(args);
}

void Logger::tok()
{
	const clock_t    end = ch::system_clock::now();
	ch::milliseconds dur = ch::duration_cast<ch::milliseconds>(end - start);
	(*this)("Done in %.2fs.", (float)dur.count() / 1e3);
}

/*
 * convert rotation matrix to quaternion
*/
Vec4f R2Quaternion(Mat& R)
{
	assert(R.rows == 3 && R.cols == 3);
	// typedef typename DataType<float>::work_type _wTp;
	if (R.type() != CV_32F) R.convertTo(R, CV_32F);;
	float q0,q1,q2,q3;
	float r00 = R.at<float>(0,0);
	float r01 = R.at<float>(0,1);
	float r02 = R.at<float>(0,2);
	float r10 = R.at<float>(1,0);
	float r11 = R.at<float>(1,1);
	float r12 = R.at<float>(1,2);
	float r20 = R.at<float>(2,0);
	float r21 = R.at<float>(2,1);
	float r22 = R.at<float>(2,2);

	float trace = r00 + r11 + r22;
	if( trace > 0 ){
		float s = 0.5 / sqrt(trace+ 1.0);
    	q0 = 0.25 / s;
    	q1 = ( r21 - r12 ) * s;
    	q2 = ( r02 - r20 ) * s;
    	q3 = ( r10 - r01 ) * s;
	} else {
    	if ( r00 > r11 && r00 > r22 )
    	{
      	float s = 2.0 * sqrt( 1.0 + r00 - r11 - r22);
      	q0 = (r21 - r12 ) / s;
      	q1 = 0.25 * s;
      	q2 = (r01 + r10 ) / s;
      	q3 = (r02 + r20 ) / s;
    	} else if (r11 > r22) {
	    float s = 2.0 * sqrt( 1.0 + r11 - r00 - r22);
	    q0 = (r02 - r20 ) / s;
	    q1 = (r01 + r10 ) / s;
	    q2 = 0.25 * s;
	    q3 = (r12 + r21 ) / s;
    	} else {
      	float s = 2.0 * sqrt( 1.0 + r22 - r00 - r11 );
      	q0 = (r10 - r01 ) / s;
	    q1 = (r02 + r20 ) / s;
	    q2 = (r12 + r21 ) / s;
	    q3 = 0.25 * s;
    	}
	}
	Vec4f q = normalize(Vec4f(q0, q1, q2, q3));
	return q;
}

Mat quat2R(Vec4f& q){

    float sqw = q[0]*q[0];
    float sqx = q[1]*q[1];
    float sqy = q[2]*q[2];
    float sqz = q[3]*q[3];

    // invs (inverse square length) is only required if quaternion is not already normalised
    float invs = 1 / (sqx + sqy + sqz + sqw);
    float m00 = ( sqx - sqy - sqz + sqw)*invs ; // since sqw + sqx + sqy + sqz =1/invs*invs
    float m11 = (-sqx + sqy - sqz + sqw)*invs ;
    float m22 = (-sqx - sqy + sqz + sqw)*invs ;

    float tmp1 = q[1]*q[2];
    float tmp2 = q[3]*q[0];
    float m10 = 2.0 * (tmp1 + tmp2)*invs ;
    float m01 = 2.0 * (tmp1 - tmp2)*invs ;

    tmp1 = q[1]*q[3];
    tmp2 = q[2]*q[0];
    float m20 = 2.0 * (tmp1 - tmp2)*invs ;
    float m02 = 2.0 * (tmp1 + tmp2)*invs ;
    tmp1 = q[2]*q[3];
    tmp2 = q[1]*q[0];
    float m21 = 2.0 * (tmp1 + tmp2)*invs ;
    float m12 = 2.0 * (tmp1 - tmp2)*invs ;
    Mat R = (Mat_<float>(3,3) << m00, m01, m02, m10, m11, m12, m20, m21, m22);
    return R;
}

bool checkCoherentRotation(cv::Mat& R) {

	if(fabs(determinant(R))-1.0 > 1e-05) return false;
	return true;
}

bool checkCoherentQ(Vec4f& q0, Vec4f& q1)
{
	Vec4f absdelta,reldelta;
	absdiff(q0,q1,absdelta);
	divide(absdelta,q1,reldelta);
	if (reldelta[0]>0.05 ||reldelta[1]>0.05 ||reldelta[2]>0.05 ||reldelta[3]>0.05)
		return false;
	return true;
}

<|endoftext|>


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

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

  Copyright (c) Insight Software 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.

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

#include "itkImageRegistrationMethod.h"
#include "itkAffineTransform.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkGradientDescentOptimizer.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkCommandIterationUpdate.h"

#include "itkImageRegistrationMethodImageSource.h"

/**
 *  This program tests one instantiation of the itk::ImageRegistrationMethod class
 *
 *
 */

template<class DataType>
bool DoRegistration ()
{

  bool pass = true;

  const unsigned int dimension = 2;

  // Fixed Image Type
  typedef itk::Image<DataType,dimension>               FixedImageType;

  // Moving Image Type
  typedef itk::Image<DataType,dimension>               MovingImageType;

  // Size Type
  typedef typename MovingImageType::SizeType                 SizeType;

  // Transform Type
  typedef itk::AffineTransform< double, dimension > TransformType;
  typedef typename TransformType::ParametersType             ParametersType;

  typedef typename FixedImageType::PixelType     FixedImagePixelType;
  typedef typename MovingImageType::PixelType    MovingImagePixelType;

  // ImageSource
  typedef itk::testhelper::ImageRegistrationMethodImageSource<
                                  FixedImagePixelType,
                                  MovingImagePixelType,
                                  dimension >         ImageSourceType;
  // Transform Type
  typedef itk::AffineTransform< double, dimension > TransformType;
  typedef typename TransformType::ParametersType             ParametersType;

  // Optimizer Type
  typedef itk::GradientDescentOptimizer                  OptimizerType;

  // Metric Type
  typedef itk::MeanSquaresImageToImageMetric<
                                    FixedImageType,
                                    MovingImageType >    MetricType;

  // Interpolation technique
  typedef itk:: LinearInterpolateImageFunction<
                                    MovingImageType,
                                    double >             InterpolatorType;

  // Registration Method
  typedef itk::ImageRegistrationMethod<
                                    FixedImageType,
                                    MovingImageType >    RegistrationType;

  typedef itk::CommandIterationUpdate<
                                  OptimizerType >    CommandIterationType;

  typename MetricType::Pointer         metric        = MetricType::New();
  typename TransformType::Pointer      transform     = TransformType::New();
  typename OptimizerType::Pointer      optimizer     = OptimizerType::New();
  typename TransformType::Pointer      trasform      = TransformType::New();
  typename InterpolatorType::Pointer   interpolator  = InterpolatorType::New();
  typename RegistrationType::Pointer   registration  = RegistrationType::New();

  typename ImageSourceType::Pointer    imageSource   = ImageSourceType::New();

  SizeType size;
  size[0] = 100;
  size[1] = 100;

  imageSource->GenerateImages( size );

  typename FixedImageType::ConstPointer     fixedImage    = imageSource->GetFixedImage();
  typename MovingImageType::ConstPointer    movingImage   = imageSource->GetMovingImage();

  //
  // Connect all the components required for Registratio
  //
  registration->SetMetric(        metric        );
  registration->SetOptimizer(     optimizer     );
  registration->SetTransform(     transform     );
  registration->SetFixedImage(    fixedImage    );
  registration->SetMovingImage(   movingImage   );
  registration->SetInterpolator(  interpolator  );

  // Select the Region of Interest over which the Metric will be computed
  // Registration time will be proportional to the number of pixels in this region.
  metric->SetFixedImageRegion( fixedImage->GetBufferedRegion() );

  // Instantiate an Observer to report the progress of the Optimization
  CommandIterationType::Pointer iterationCommand = CommandIterationType::New();
  iterationCommand->SetOptimizer(  optimizer.GetPointer() );

  // Scale the translation components of the Transform in the Optimizer
  OptimizerType::ScalesType scales( transform->GetNumberOfParameters() );
  scales.Fill( 1.0 );

  unsigned long   numberOfIterations =  100;
  double          translationScale   = 1e-6;
  double          learningRate       = 1e-8;

  for( unsigned int i=0; i<dimension; i++)
    {
    scales[ i + dimension * dimension ] = translationScale;
    }

  optimizer->SetScales( scales );
  optimizer->SetLearningRate( learningRate );
  optimizer->SetNumberOfIterations( numberOfIterations );
  optimizer->MinimizeOn();

  // Start from an Identity transform (in a normal case, the user
  // can probably provide a better guess than the identity...
  transform->SetIdentity();
  registration->SetInitialTransformParameters( transform->GetParameters() );

  // Initialize the internal connections of the registration method.
  // This can potentially throw an exception
  try
    {
    registration->Update();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cerr << e << std::endl;
    pass = false;
    }

  ParametersType actualParameters = imageSource->GetActualParameters();
  ParametersType finalParameters  = registration->GetLastTransformParameters();

  const unsigned int numbeOfParameters = actualParameters.Size();

  // We know that for the Affine transform the Translation parameters are at
  // the end of the list of parameters.
  const unsigned int offsetOrder = finalParameters.Size()-actualParameters.Size();

  const double tolerance = 1.0;  // equivalent to 1 pixel.

  for(unsigned int i=0; i<numbeOfParameters; i++)
    {
    // the parameters are negated in order to get the inverse transformation.
    // this only works for comparing translation parameters....
    std::cout << finalParameters[i+offsetOrder] << " == " << -actualParameters[i] << std::endl;
    if( fabs ( finalParameters[i+offsetOrder] - (-actualParameters[i]) ) > tolerance )
      {
      std::cout << "Tolerance exceeded at component " << i << std::endl;
      pass = false;
      }
    }

  return pass;

}
int itkImageRegistrationMethodTest_16(int itkNotUsed(argc), char*[] itkNotUsed(argv) )
{
  bool result_uc, result_c, result_us, result_s,
    result_ui, result_i, result_ul, result_l,
    result_f, result_d;
  result_uc = DoRegistration<unsigned char>();
  result_c  = DoRegistration<char>();
  result_us = DoRegistration<unsigned short>();
  result_s  = DoRegistration<short>();
  result_ui = DoRegistration<unsigned int>();
  result_i = DoRegistration<int>();
  result_ul = DoRegistration<unsigned long>();
  result_l  = DoRegistration<long>();
  result_f  = DoRegistration<float>();
#ifndef __BORLANDC__
  result_d  = DoRegistration<double>();
#else
  result_d = true;
#endif

  std::cout << "<unsigned char>:  " << result_uc << std::endl;
  std::cout << "<char>:           " << result_c  << std::endl;
  std::cout << "<unsigned short>: " << result_us << std::endl;
  std::cout << "<short>:          " << result_s  << std::endl;
  std::cout << "<unsigned int>:   " << result_ui << std::endl;
  std::cout << "<int>:            " << result_i  << std::endl;
  std::cout << "<unsigned long>:  " << result_ul << std::endl;
  std::cout << "<long>:           " << result_l  << std::endl;
  std::cout << "<float>:          " << result_f  << std::endl;
  std::cout << "<double>:         " << result_d  << std::endl;

  return EXIT_SUCCESS;
}

<commit_msg>COMP: ITK_LEAN_AND_MEAN to avoid overflow in Microsoft compiler.<commit_after>/*=========================================================================

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

  Copyright (c) Insight Software 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.

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

#ifdef _MSC_VER
#define ITK_LEAN_AND_MEAN
#endif

#include "itkImageRegistrationMethod.h"
#include "itkAffineTransform.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkGradientDescentOptimizer.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkCommandIterationUpdate.h"

#include "itkImageRegistrationMethodImageSource.h"

/**
 *  This program tests one instantiation of the itk::ImageRegistrationMethod class
 *
 *
 */

template<class DataType>
bool DoRegistration ()
{

  bool pass = true;

  const unsigned int dimension = 2;

  // Fixed Image Type
  typedef itk::Image<DataType,dimension>               FixedImageType;

  // Moving Image Type
  typedef itk::Image<DataType,dimension>               MovingImageType;

  // Size Type
  typedef typename MovingImageType::SizeType                 SizeType;

  // Transform Type
  typedef itk::AffineTransform< double, dimension > TransformType;
  typedef typename TransformType::ParametersType             ParametersType;

  typedef typename FixedImageType::PixelType     FixedImagePixelType;
  typedef typename MovingImageType::PixelType    MovingImagePixelType;

  // ImageSource
  typedef itk::testhelper::ImageRegistrationMethodImageSource<
                                  FixedImagePixelType,
                                  MovingImagePixelType,
                                  dimension >         ImageSourceType;
  // Transform Type
  typedef itk::AffineTransform< double, dimension > TransformType;
  typedef typename TransformType::ParametersType             ParametersType;

  // Optimizer Type
  typedef itk::GradientDescentOptimizer                  OptimizerType;

  // Metric Type
  typedef itk::MeanSquaresImageToImageMetric<
                                    FixedImageType,
                                    MovingImageType >    MetricType;

  // Interpolation technique
  typedef itk:: LinearInterpolateImageFunction<
                                    MovingImageType,
                                    double >             InterpolatorType;

  // Registration Method
  typedef itk::ImageRegistrationMethod<
                                    FixedImageType,
                                    MovingImageType >    RegistrationType;

  typedef itk::CommandIterationUpdate<
                                  OptimizerType >    CommandIterationType;

  typename MetricType::Pointer         metric        = MetricType::New();
  typename TransformType::Pointer      transform     = TransformType::New();
  typename OptimizerType::Pointer      optimizer     = OptimizerType::New();
  typename TransformType::Pointer      trasform      = TransformType::New();
  typename InterpolatorType::Pointer   interpolator  = InterpolatorType::New();
  typename RegistrationType::Pointer   registration  = RegistrationType::New();

  typename ImageSourceType::Pointer    imageSource   = ImageSourceType::New();

  SizeType size;
  size[0] = 100;
  size[1] = 100;

  imageSource->GenerateImages( size );

  typename FixedImageType::ConstPointer     fixedImage    = imageSource->GetFixedImage();
  typename MovingImageType::ConstPointer    movingImage   = imageSource->GetMovingImage();

  //
  // Connect all the components required for Registratio
  //
  registration->SetMetric(        metric        );
  registration->SetOptimizer(     optimizer     );
  registration->SetTransform(     transform     );
  registration->SetFixedImage(    fixedImage    );
  registration->SetMovingImage(   movingImage   );
  registration->SetInterpolator(  interpolator  );

  // Select the Region of Interest over which the Metric will be computed
  // Registration time will be proportional to the number of pixels in this region.
  metric->SetFixedImageRegion( fixedImage->GetBufferedRegion() );

  // Instantiate an Observer to report the progress of the Optimization
  CommandIterationType::Pointer iterationCommand = CommandIterationType::New();
  iterationCommand->SetOptimizer(  optimizer.GetPointer() );

  // Scale the translation components of the Transform in the Optimizer
  OptimizerType::ScalesType scales( transform->GetNumberOfParameters() );
  scales.Fill( 1.0 );

  unsigned long   numberOfIterations =  100;
  double          translationScale   = 1e-6;
  double          learningRate       = 1e-8;

  for( unsigned int i=0; i<dimension; i++)
    {
    scales[ i + dimension * dimension ] = translationScale;
    }

  optimizer->SetScales( scales );
  optimizer->SetLearningRate( learningRate );
  optimizer->SetNumberOfIterations( numberOfIterations );
  optimizer->MinimizeOn();

  // Start from an Identity transform (in a normal case, the user
  // can probably provide a better guess than the identity...
  transform->SetIdentity();
  registration->SetInitialTransformParameters( transform->GetParameters() );

  // Initialize the internal connections of the registration method.
  // This can potentially throw an exception
  try
    {
    registration->Update();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cerr << e << std::endl;
    pass = false;
    }

  ParametersType actualParameters = imageSource->GetActualParameters();
  ParametersType finalParameters  = registration->GetLastTransformParameters();

  const unsigned int numbeOfParameters = actualParameters.Size();

  // We know that for the Affine transform the Translation parameters are at
  // the end of the list of parameters.
  const unsigned int offsetOrder = finalParameters.Size()-actualParameters.Size();

  const double tolerance = 1.0;  // equivalent to 1 pixel.

  for(unsigned int i=0; i<numbeOfParameters; i++)
    {
    // the parameters are negated in order to get the inverse transformation.
    // this only works for comparing translation parameters....
    std::cout << finalParameters[i+offsetOrder] << " == " << -actualParameters[i] << std::endl;
    if( fabs ( finalParameters[i+offsetOrder] - (-actualParameters[i]) ) > tolerance )
      {
      std::cout << "Tolerance exceeded at component " << i << std::endl;
      pass = false;
      }
    }

  return pass;

}
int itkImageRegistrationMethodTest_16(int itkNotUsed(argc), char*[] itkNotUsed(argv) )
{
  bool result_uc, result_c, result_us, result_s,
    result_ui, result_i, result_ul, result_l,
    result_f, result_d;
  result_uc = DoRegistration<unsigned char>();
  result_c  = DoRegistration<char>();
  result_us = DoRegistration<unsigned short>();
  result_s  = DoRegistration<short>();
  result_ui = DoRegistration<unsigned int>();
  result_i = DoRegistration<int>();
  result_ul = DoRegistration<unsigned long>();
  result_l  = DoRegistration<long>();
  result_f  = DoRegistration<float>();
#ifndef __BORLANDC__
  result_d  = DoRegistration<double>();
#else
  result_d = true;
#endif

  std::cout << "<unsigned char>:  " << result_uc << std::endl;
  std::cout << "<char>:           " << result_c  << std::endl;
  std::cout << "<unsigned short>: " << result_us << std::endl;
  std::cout << "<short>:          " << result_s  << std::endl;
  std::cout << "<unsigned int>:   " << result_ui << std::endl;
  std::cout << "<int>:            " << result_i  << std::endl;
  std::cout << "<unsigned long>:  " << result_ul << std::endl;
  std::cout << "<long>:           " << result_l  << std::endl;
  std::cout << "<float>:          " << result_f  << std::endl;
  std::cout << "<double>:         " << result_d  << std::endl;

  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#include "Game.hpp"

Game::Game(options o) : players(o.players), this_player_go(o.this_player_go) {
  // Generate board and start playing
  rapidjson::Document d = get_config_from_file(o.board_config);
  string board_name(d["board_name"].GetString());
  int width = d["board_width"].GetInt();
  int height = d["board_height"].GetInt();
  rapidjson::Value& mods(d["modifiers"]);
  rapidjson::Value& scores(d["scores"]);
  this->b = new Board(board_name, width, height, mods, scores);

  // Get other details (for later implementation)
  if (d.HasMember("tiles") &&
      d["tiles"].HasMember("each") &&
      d["tiles"].HasMember("total")) {
    this->tiles_each = d["tiles"]["each"].GetInt();
    this->tiles_left = d["tiles"]["total"].GetInt();
  } else {
    this->tiles_each = 7;
    this->tiles_left = 100;
  }

  assert(o.players > 0 && o.this_player_go > 0 && o.this_player_go <= o.players);

  cout << "Players:\t" << this->players << endl;
  cout << "Your Go:\t" << this->this_player_go << endl;
  cout << endl;
  cout << "Board:\t" << endl;
  this->b->print_board();

  int go = 0;
  while (!this->is_end()) {
    int player_turn = go % o.players;
    if (player_turn == o.this_player_go - 1) {
      cout << "Your go!" << endl;
      this->player_go();
    } else {
      cout << "Opponent's go:\tPlayer" << (player_turn + 1) << endl;
      this->opponent_go();
      this->b->print_board();
    }
    go++;
  }
}

rapidjson::Document get_config_from_file(string& config) {
  ifstream config_file(config);

  // get length of file:
  config_file.seekg (0, config_file.end);
  int length = config_file.tellg();
  config_file.seekg (0, config_file.beg);
  char* config_file_raw = new char[length];

  config_file.read(config_file_raw, length);

  rapidjson::Document d;
  d.Parse(config_file_raw);

  return d;
}

bool Game::is_end(void) {
  return this->tiles_left == 0;
}

void Game::opponent_go(void) {
  while (true) {
    string input;

    // For putting on the Board
    string word;
    int x, y;
    Direction d;

    while (true) {
      string word_regex("[A-Za-z]{0,");
      word_regex.append(to_string(this->tiles_each));
      word_regex.append("}");
      regex validator(word_regex);

      // Get the word
      cout << "Please enter the word (if you type more than 1 word, the second will be ignored):\t";
      cin >> noskipws >> input;
      cin.clear();
      cin.ignore(INT_MAX, '\n');

      if (input.compare("") == 0) {
        cout << "The opponent passed!" << endl;
        return;
      }

      if (regex_match(input, validator) && valid_word_for_game(input)) {
        word = input;
        break;
      }

      cout << "The word you entered was invalid. Please try again." << endl;
    }

    while (true) {
      regex y_("^[A-Za-z]$");

      // Get the position
      cout << "Please enter the position on the board (e.g. 1 A):\t";
      cin >> input;
      try {
        x = stoi(input);
        if (x <= 0 || x > this->b->get_width()) {
          throw invalid_argument("");
        }
        x -= 1; // Convert from user to program
      } catch (invalid_argument e) {
        cout << "The value " << input << " is not in the range {1,"
             << this->b->get_width() << "}."<< endl;
        continue;
      }

      cin >> input;
      if (!regex_match(input, y_)) {
        continue;
      }
      y = (int) toupper(input[0]) - 'A';

      cin.clear();
      cin.ignore(INT_MAX, '\n');

      if (valid_position_for_game(x, y)) {
        break;
      }
    }

    while (true) {
      // Get the word
      cout << "Please enter the direction (NORTH|EAST|SOUTH|WEST):\t";
      cin >> input;
      cin.clear();
      cin.ignore(INT_MAX, '\n');

      for (auto& c : input) {
        c = toupper(c);
      }

      if (input.compare("NORTH") == 0) {
        d = NORTH; break;
      } else if (input.compare("EAST") == 0) {
        d = EAST; break;
      } else if (input.compare("SOUTH") == 0) {
        d = SOUTH; break;
      } else if (input.compare("WEST") == 0) {
        d = WEST; break;
      }

      cout << "Incorrect direction. Please try again!" << endl;
    }

    if (can_put_word_on_board(word, x, y, d)) {
      this->b->set_word(word, x, y, d);
      break;
    }

    cout << "Incorrect parameters specified. Please try again!" << endl;
  }
}

void Game::player_go(void) {
  while (true) {
    string input_; // Dummy variable
    vector<char > input;

    // For putting on the Board
    int tiles_available = 0;
    // string word;
    // int x, y;
    // Direction d;

    // Get the number of tiles
    while (true) {
      cout << "How many tiles do you have left? (Between 0 and " << this->tiles_each << ")\t";
      cin >> input_;
      try {
        tiles_available = stoi(input_);
        if (tiles_available > 0 && tiles_available <= this->tiles_each) {
          break;
        }
      } catch (invalid_argument e) {
        continue;
      }
    }

    // Get the tiles from the user
    while (true) {
      string word_regex("[A-Za-z]{0,");
      word_regex.append(to_string(this->tiles_each));
      word_regex.append("}");
      regex validator(word_regex);

      // Get the word
      cout << "Please enter the tiles you have left, separated by a space:\t";
      char c;
      for (int i = 0; i < tiles_available; i++) {
        cin >> c;
        input.push_back(toupper(c));
      }
      cin.clear();
      cin.ignore(INT_MAX, '\n');

      for (auto it = input.begin(); it != input.end(); it++) {
        cout << *it << " ";
      }
      cout << endl;
    }
  }
}

bool Game::valid_word_for_game(string& input) {
  return true;
}

bool Game::valid_position_for_game(int& x, int& y) {
  return true;
}

bool Game::can_put_word_on_board(string& word, int& w, int& h, Direction& d) {
  return true;
}
<commit_msg>Clean up<commit_after>#include "Game.hpp"

Game::Game(options o) : players(o.players), this_player_go(o.this_player_go) {
  // Generate board and start playing
  rapidjson::Document d = get_config_from_file(o.board_config);
  string board_name(d["board_name"].GetString());
  int width = d["board_width"].GetInt();
  int height = d["board_height"].GetInt();
  rapidjson::Value& mods(d["modifiers"]);
  rapidjson::Value& scores(d["scores"]);
  this->b = new Board(board_name, width, height, mods, scores);

  // Get other details (for later implementation)
  if (d.HasMember("tiles") &&
      d["tiles"].HasMember("each") &&
      d["tiles"].HasMember("total")) {
    this->tiles_each = d["tiles"]["each"].GetInt();
    this->tiles_left = d["tiles"]["total"].GetInt();
  } else {
    this->tiles_each = 7;
    this->tiles_left = 100;
  }

  assert(o.players > 0 && o.this_player_go > 0 && o.this_player_go <= o.players);

  cout << "Players:\t" << this->players << endl;
  cout << "Your Go:\t" << this->this_player_go << endl;
  cout << endl;
  cout << "Board:\t" << endl;
  this->b->print_board();

  int go = 0;
  while (!this->is_end()) {
    int player_turn = go % o.players;
    if (player_turn == o.this_player_go - 1) {
      cout << "Your go!" << endl;
      this->player_go();
    } else {
      cout << "Opponent's go:\tPlayer" << (player_turn + 1) << endl;
      this->opponent_go();
      this->b->print_board();
    }
    go++;
  }
}

rapidjson::Document get_config_from_file(string& config) {
  ifstream config_file(config);

  // get length of file:
  config_file.seekg (0, config_file.end);
  int length = config_file.tellg();
  config_file.seekg (0, config_file.beg);
  char* config_file_raw = new char[length];

  config_file.read(config_file_raw, length);

  rapidjson::Document d;
  d.Parse(config_file_raw);

  return d;
}

bool Game::is_end(void) {
  return this->tiles_left == 0;
}

void Game::opponent_go(void) {
  while (true) {
    string input;

    // For putting on the Board
    string word;
    int x, y;
    Direction d;

    while (true) {
      string word_regex("[A-Za-z]{0,");
      word_regex.append(to_string(this->tiles_each));
      word_regex.append("}");
      regex validator(word_regex);

      // Get the word
      cout << "Please enter the word (if you type more than 1 word, the second will be ignored):\t";
      cin >> noskipws >> input;
      cin.clear();
      cin.ignore(INT_MAX, '\n');

      if (input.compare("") == 0) {
        cout << "The opponent passed!" << endl;
        return;
      }

      if (regex_match(input, validator) && valid_word_for_game(input)) {
        word = input;
        break;
      }

      cout << "The word you entered was invalid. Please try again." << endl;
    }

    while (true) {
      regex y_("^[A-Za-z]$");

      // Get the position
      cout << "Please enter the position on the board (e.g. 1 A):\t";
      cin >> input;
      try {
        x = stoi(input);
        if (x <= 0 || x > this->b->get_width()) {
          throw invalid_argument("");
        }
        x -= 1; // Convert from user to program
      } catch (invalid_argument e) {
        cout << "The value " << input << " is not in the range {1,"
             << this->b->get_width() << "}."<< endl;
        continue;
      }

      cin >> input;
      if (!regex_match(input, y_)) {
        continue;
      }
      y = (int) toupper(input[0]) - 'A';

      cin.clear();
      cin.ignore(INT_MAX, '\n');

      if (valid_position_for_game(x, y)) {
        break;
      }
    }

    while (true) {
      // Get the word
      cout << "Please enter the direction (NORTH|EAST|SOUTH|WEST):\t";
      cin >> input;
      cin.clear();
      cin.ignore(INT_MAX, '\n');

      for (auto& c : input) {
        c = toupper(c);
      }

      if (input.compare("NORTH") == 0) {
        d = NORTH; break;
      } else if (input.compare("EAST") == 0) {
        d = EAST; break;
      } else if (input.compare("SOUTH") == 0) {
        d = SOUTH; break;
      } else if (input.compare("WEST") == 0) {
        d = WEST; break;
      }

      cout << "Incorrect direction. Please try again!" << endl;
    }

    if (can_put_word_on_board(word, x, y, d)) {
      this->b->set_word(word, x, y, d);
      break;
    }

    cout << "Incorrect parameters specified. Please try again!" << endl;
  }
}

void Game::player_go(void) {
  while (true) {
    string input_; // Dummy variable
    vector<char > input;

    // For putting on the Board
    int tiles_available = 0;
    // string word;
    // int x, y;
    // Direction d;

    // Get the number of tiles
    while (true) {
      cout << "How many tiles do you have left? (Between 0 and " << this->tiles_each << ")\t";
      cin >> input_;
      try {
        tiles_available = stoi(input_);
        if (tiles_available > 0 && tiles_available <= this->tiles_each) {
          break;
        }
      } catch (invalid_argument e) {
        continue;
      }
    }

    // Get the tiles from the user
    while (true) {
      string word_regex("[A-Za-z]{0,");
      word_regex.append(to_string(this->tiles_each));
      word_regex.append("}");
      regex validator(word_regex);

      // Get the word
      cout << "Please enter the tiles you have left, separated by a space:\t";
      char c;
      for (int i = 0; i < tiles_available; i++) {
        cin >> c;
        input.push_back(toupper(c));
      }
      cin.clear();
      cin.ignore(INT_MAX, '\n');
    }
  }
}

bool Game::valid_word_for_game(string& input) {
  return true;
}

bool Game::valid_position_for_game(int& x, int& y) {
  return true;
}

bool Game::can_put_word_on_board(string& word, int& w, int& h, Direction& d) {
  return true;
}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

#pragma once
#ifndef NET_TCP_COMMON_HPP
#define NET_TCP_COMMON_HPP

#include <net/ip4/addr.hpp>
#include <net/packet.hpp>

namespace net {
  namespace tcp {

    // Constants
    // default size of TCP window - how much data can be "in flight" (unacknowledged)
    static constexpr uint16_t default_window_size = 0xffff;
    // maximum size of a TCP segment - later set based on MTU or peer
    static constexpr uint16_t default_mss = 536;
    // the maximum amount of half-open connections per port (listener)
    static constexpr size_t max_syn_backlog = 64;

    using Address = ip4::Addr;

    /** A port */
    using port_t = uint16_t;

    /** A Sequence number (SYN/ACK) (32 bits) */
    using seq_t = uint32_t;

    /** A shared buffer pointer */
    using buffer_t = std::shared_ptr<uint8_t>;

    /**
     * @brief Creates a shared buffer with a given length
     *
     * @param length buffer length
     * @return a newly created buffer_t
     */
    static buffer_t new_shared_buffer(uint64_t length)
    { return buffer_t(new uint8_t[length], std::default_delete<uint8_t[]>()); }

    class Packet;
    using Packet_ptr = std::unique_ptr<Packet>;

    class Connection;
    using Connection_ptr = std::shared_ptr<Connection>;

  } // < namespace tcp
} // < namespace net

#endif // < NET_TCP_COMMON_HPP
<commit_msg>tcp: Removed static keyword for non-class helper function<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

#pragma once
#ifndef NET_TCP_COMMON_HPP
#define NET_TCP_COMMON_HPP

#include <net/ip4/addr.hpp>
#include <net/packet.hpp>

namespace net {
  namespace tcp {

    // Constants
    // default size of TCP window - how much data can be "in flight" (unacknowledged)
    static constexpr uint16_t default_window_size = 0xffff;
    // maximum size of a TCP segment - later set based on MTU or peer
    static constexpr uint16_t default_mss = 536;
    // the maximum amount of half-open connections per port (listener)
    static constexpr size_t max_syn_backlog = 64;

    using Address = ip4::Addr;

    /** A port */
    using port_t = uint16_t;

    /** A Sequence number (SYN/ACK) (32 bits) */
    using seq_t = uint32_t;

    /** A shared buffer pointer */
    using buffer_t = std::shared_ptr<uint8_t>;

    /**
     * @brief Creates a shared buffer with a given length
     *
     * @param length buffer length
     * @return a newly created buffer_t
     */
    inline buffer_t new_shared_buffer(uint64_t length)
    { return buffer_t(new uint8_t[length], std::default_delete<uint8_t[]>()); }

    class Packet;
    using Packet_ptr = std::unique_ptr<Packet>;

    class Connection;
    using Connection_ptr = std::shared_ptr<Connection>;

  } // < namespace tcp
} // < namespace net

#endif // < NET_TCP_COMMON_HPP
<|endoftext|>


<commit_before>#include <iostream>     /* cin, cout */
#include <stdio.h>      /* printf */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <vector>       /* vector */

using namespace std;

// Variable declarations
int next_move = 2; // "X" = 2; "O" = 5;
int next_player = 1; // -1 = human, 1 = AI, 0 = no move;
int board[9] = {0,0,0,0,0,0,0,0,0};
const int board_size = 3;
bool game_running = true;
const int X = 2;
const int O = 5;

// Function declarations
bool makeMove(int node, int brd[], int player);
int checkLine(int line, int brd[]);
void showBoard(const int brd[]);
char gridChar(int i);
void drawBoard(int brd[]);
int switchPlayer(int player);
int checkScore(int brd[], int player);
bool boardFull(int brd[]);
int gameScore(int brd[], int player);
int randomMove(int brd[], int player);
int betterMove(int brd[], int player);
int forkMove(int brd[], int player);
void humanMove(int brd[], int player);
//int minimax(int brd[], int player);
//int aiMove(int brd[], int player);

int main () {
    while(game_running){
        drawBoard(board);

        if (next_move==X) {cout<<"Next move: X"<<endl;}
        else if (next_move == O){cout<<"Next move: O"<<endl;}

        int node = 0;

        if (next_player == -1){
            humanMove(board, next_move);
        }

        else if (next_player == 1){
            node = betterMove(board,next_move);
            //node = aiMove(board, next_move);
            //node = randomMove(board,next_move);
            makeMove(node, board, next_move);
        }

        int score = gameScore(board, next_move);
        next_player = -next_player;

        if (score!=-1){
            game_running = false;
            drawBoard(board);
            cout<<"GAME OVER!"<<endl;
            }
        next_move = switchPlayer(next_move);
        cout<<"----------------------------------------"<<endl;
    }
}

int lines[8][3] = {
    {0,1,2}, {3,4,5},{6,7,8}, // rows
    {0,3,6}, {1,4,7},{2,5,8}, // columns
    {0,4,8}, {2,4,6}          // diagonals
};

bool makeMove(int node, int brd[], int player) {
    bool good_move = false;

    if (brd[node]==0){
        brd[node]=player;
        good_move=true;
    }
    else {
        cout<<"Invallid move!"<<endl;
    }

    return good_move;
}

int checkLine(int line, int brd[]) {
    int sum = 0;

    for (int i=0; i<board_size; i++) {
        sum = sum+brd[lines[line][i]];
    }

    return sum;
}

void showBoard(const int brd[]){
    for (int m=0; m<board_size; m++){
        for (int n=0; n<board_size; n++) {
            char p = '-';
            if (brd[m*board_size+n]==2) {
                p = 'X';
            }

            else if (brd[m*board_size+n]==5) {
                p = 'O';
            }

            cout<<p<<' ';
        }
        cout<<endl;
    }
}

char gridChar(int i) {
    switch(i) {
        case 2:
            return 'X';
        case 5:
            return 'O';
        default:
            return ' ';
    }
}

void drawBoard(int brd[]) {
    printf("\n");
    printf(" %c | %c | %c\n",gridChar(brd[0]),gridChar(brd[1]),gridChar(brd[2]));
    printf("---+---+---\n");
    printf(" %c | %c | %c\n",gridChar(brd[3]),gridChar(brd[4]),gridChar(brd[5]));
    printf("---+---+---\n");
    printf(" %c | %c | %c\n",gridChar(brd[6]),gridChar(brd[7]),gridChar(brd[8]));
    printf("\n");
}

int switchPlayer(int player){
    int mv = 0;
    if (player == 2) {
        mv=5;
    }
    else mv = 2;
    return mv;
}

int checkScore(int brd[], int player) {
    int score = -1;

    for (int i = 0; i<8; i++){
        if(checkLine(i, brd)== (3 * player)){
            score = 100;
        }

        else if(checkLine(i, brd)== (3 * switchPlayer(player))){
            score = -100;
        }

        else if (boardFull(brd)){
            score = 0;
        }
    }
    return score;
}

bool boardFull(int brd[]){
    bool full = true;
    for (int m=0; m < (board_size * board_size); m++){
        if (brd[m]==0) {
            full = false;
            }
        }
    return full;
}

int gameScore(int brd[], int player){
    int game_score = -1;

    for (int i=0; i<8; i++){
        int score = checkLine(i, brd);
        if (score == (player * 3)){
            game_score = 10;
        }

        else if (score == (switchPlayer(player)*3)){
            game_score = -10;
        }
    }

    if (game_score==-1 && boardFull(brd)){
        game_score = 0;
    }

    return game_score;
};

int randomMove(int brd[], int player){
    vector<int> freeNodes;
    srand (time(NULL));
    for (int i=0; i<9; i++){
        if (brd[i]==0){
            freeNodes.push_back(i);
        }
    }
    int r = freeNodes.size();
    int n = rand() % r;
    int m = freeNodes[n];
    return m;
}

int betterMove(int brd[], int player){
     int mv = -1;

     //first move
     int sum = 0;
     int corners[4] = {0,2,6,8};

     for (int n = 0; n<8; n++) {
        sum = sum + brd[n];
     }

     //if the board is empty, take a corner
     if (sum == 0){
        srand (time(NULL));
        int n = rand() % 4;
        mv = corners[n];
        return mv;
     }

     else if (sum == X || sum == O){
        if (brd[4]==0){
            mv = 4;
            return mv;
        }

        else {
            srand (time(NULL));
            int n = rand() % 4;
            mv = corners[n];
            return mv;
        }
     }

     //win move
     for (int n = 0; n<8; n++){
        int s = checkLine(n, brd);
        if (s == (2 * player)){
            cout<<"I can win!"<<endl;
            for (int k=0; k<3; k++){
                if (board[lines[n][k]] == 0){
                    mv = lines[n][k];
                    cout<<"Best Move: "<<mv<<endl;
                    return mv;
                }
            }
        }
     }

     //block move
     for (int n = 0; n<8; n++){
        int s = checkLine(n, brd);
        if (s == (2 * switchPlayer(player))){
            cout<<"I have to block!"<<endl;
            for (int k=0; k<3; k++){
                if (board[lines[n][k]] == 0){
                    mv = lines[n][k];
                    cout<<"Best Move: "<<mv<<endl;
                    return mv;
                }
            }
        }
     }

     //fork move
     if(forkMove(brd,player)>-1){
        mv = forkMove(brd, player);
        cout<<"Best Move: "<<mv<<endl;
        return mv;
     }

     //random move
     if (mv==-1){
        cout<<"Playing random!"<<endl;
        mv = randomMove(brd, player);
     }
     cout<<"Best Move: "<<mv<<endl;
     return mv;
}

int forkMove(int brd[], int player){
    int fork_move = -1;
    for (int i = 0; i<9; i++){
        int l = 0;
        if (brd[i]==0){
            makeMove(i, brd, player);
            for (int m = 0; m<8; m++){
                if (checkLine(m, brd)== (2 * player)){
                    l = l+1;
                }
            }
            if (l>1){
               fork_move = i;
               cout<<"I can fork!"<<endl;
            }
            brd[i]=0;
            return fork_move;
        }
    }
    return fork_move;
}

void humanMove(int brd[], int player){
    bool done = false;

    while (done == false){
        cout<<"Your turn! Select an empty square."<<endl;
        int box;
        cin>>box;
        done = makeMove(box, brd, player);
    }
}

/*
int aiMove(int brd[], int player){
    int best_move = -1;
    int score = -9000;

    for (int m=0; m<9; m++){
        if (brd[m]==0){
            brd[m] = player;
            int temp_score = minimax(brd, player);
            brd[m] = 0; //reset board

            if (temp_score > score){
                score = temp_score;
                best_move = m;
                cout<<best_move<<"|"<<score;
            }
        }
    }

    cout<<"AI best move:"<<best_move<<endl;
    return best_move;
}

int minimax(int brd[], int player){
    int score = -9000;
    int temp_score = checkScore(brd, player);

    if (temp_score != -1){
        score = temp_score;
    }

    for (int m=0; m<9; m++){
        if (brd[m]==0){
            brd[m] = player;
        }
    }

    else {
        for (int n=0; n<9; n++){
            if (brd[n]==0){
                brd[n]= player;
                int other_player = switchPlayer(player);
                int sc = - minimax(brd, other_player);

                if (sc > score){
                    score = sc;
                }
                brd[n]=0;
            }
        }
    }
    return score;
}
*/
<commit_msg>Clean-up<commit_after>#include <iostream>     /* cin, cout */
#include <stdio.h>      /* printf */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <vector>       /* vector */

using namespace std;

// Variable declarations
int next_move = 2; // "X" = 2; "O" = 5;
int next_player = 1; // -1 = human, 1 = AI, 0 = no move;
int board[9] = {0,0,0,0,0,0,0,0,0};
const int board_size = 3;
bool game_running = true;
const int X = 2;
const int O = 5;

// Function declarations
bool makeMove(int node, int brd[], int player);
int checkLine(int line, int brd[]);
void showBoard(const int brd[]);
char gridChar(int i);
void drawBoard(int brd[]);
int switchPlayer(int player);
int checkScore(int brd[], int player);
bool boardFull(int brd[]);
int gameScore(int brd[], int player);
int randomMove(int brd[], int player);
int betterMove(int brd[], int player);
int forkMove(int brd[], int player);
void humanMove(int brd[], int player);

int main () {
    while(game_running){
        drawBoard(board);

        if (next_move==X) {cout<<"Next move: X"<<endl;}
        else if (next_move == O){cout<<"Next move: O"<<endl;}

        int node = 0;

        if (next_player == -1){
            humanMove(board, next_move);
        }

        else if (next_player == 1){
            node = betterMove(board,next_move);
            //node = aiMove(board, next_move);
            //node = randomMove(board,next_move);
            makeMove(node, board, next_move);
        }

        int score = gameScore(board, next_move);
        next_player = -next_player;

        if (score!=-1){
            game_running = false;
            drawBoard(board);
            cout<<"GAME OVER!"<<endl;
            }
        next_move = switchPlayer(next_move);
        cout<<"----------------------------------------"<<endl;
    }
}

int lines[8][3] = {
    {0,1,2}, {3,4,5},{6,7,8}, // rows
    {0,3,6}, {1,4,7},{2,5,8}, // columns
    {0,4,8}, {2,4,6}          // diagonals
};

bool makeMove(int node, int brd[], int player) {
    bool good_move = false;

    if (brd[node]==0){
        brd[node]=player;
        good_move=true;
    }
    else {
        cout<<"Invallid move!"<<endl;
    }

    return good_move;
}

int checkLine(int line, int brd[]) {
    int sum = 0;

    for (int i=0; i<board_size; i++) {
        sum = sum+brd[lines[line][i]];
    }

    return sum;
}

void showBoard(const int brd[]){
    for (int m=0; m<board_size; m++){
        for (int n=0; n<board_size; n++) {
            char p = '-';
            if (brd[m*board_size+n]==2) {
                p = 'X';
            }

            else if (brd[m*board_size+n]==5) {
                p = 'O';
            }

            cout<<p<<' ';
        }
        cout<<endl;
    }
}

char gridChar(int i) {
    switch(i) {
        case 2:
            return 'X';
        case 5:
            return 'O';
        default:
            return ' ';
    }
}

void drawBoard(int brd[]) {
    printf("\n");
    printf(" %c | %c | %c\n",gridChar(brd[0]),gridChar(brd[1]),gridChar(brd[2]));
    printf("---+---+---\n");
    printf(" %c | %c | %c\n",gridChar(brd[3]),gridChar(brd[4]),gridChar(brd[5]));
    printf("---+---+---\n");
    printf(" %c | %c | %c\n",gridChar(brd[6]),gridChar(brd[7]),gridChar(brd[8]));
    printf("\n");
}

int switchPlayer(int player){
    int mv = 0;
    if (player == 2) {
        mv=5;
    }
    else mv = 2;
    return mv;
}

int checkScore(int brd[], int player) {
    int score = -1;

    for (int i = 0; i<8; i++){
        if(checkLine(i, brd)== (3 * player)){
            score = 100;
        }

        else if(checkLine(i, brd)== (3 * switchPlayer(player))){
            score = -100;
        }

        else if (boardFull(brd)){
            score = 0;
        }
    }
    return score;
}

bool boardFull(int brd[]){
    bool full = true;
    for (int m=0; m < (board_size * board_size); m++){
        if (brd[m]==0) {
            full = false;
            }
        }
    return full;
}

int gameScore(int brd[], int player){
    int game_score = -1;

    for (int i=0; i<8; i++){
        int score = checkLine(i, brd);
        if (score == (player * 3)){
            game_score = 10;
        }

        else if (score == (switchPlayer(player)*3)){
            game_score = -10;
        }
    }

    if (game_score==-1 && boardFull(brd)){
        game_score = 0;
    }

    return game_score;
};

int randomMove(int brd[], int player){
    vector<int> freeNodes;
    srand (time(NULL));
    for (int i=0; i<9; i++){
        if (brd[i]==0){
            freeNodes.push_back(i);
        }
    }
    int r = freeNodes.size();
    int n = rand() % r;
    int m = freeNodes[n];
    return m;
}

int betterMove(int brd[], int player){
     int mv = -1;

     //first move
     int sum = 0;
     int corners[4] = {0,2,6,8};

     for (int n = 0; n<8; n++) {
        sum = sum + brd[n];
     }

     //if the board is empty, take a corner
     if (sum == 0){
        srand (time(NULL));
        int n = rand() % 4;
        mv = corners[n];
        return mv;
     }

     else if (sum == X || sum == O){
        if (brd[4]==0){
            mv = 4;
            return mv;
        }

        else {
            srand (time(NULL));
            int n = rand() % 4;
            mv = corners[n];
            return mv;
        }
     }

     //win move
     for (int n = 0; n<8; n++){
        int s = checkLine(n, brd);
        if (s == (2 * player)){
            cout<<"I can win!"<<endl;
            for (int k=0; k<3; k++){
                if (board[lines[n][k]] == 0){
                    mv = lines[n][k];
                    cout<<"Best Move: "<<mv<<endl;
                    return mv;
                }
            }
        }
     }

     //block move
     for (int n = 0; n<8; n++){
        int s = checkLine(n, brd);
        if (s == (2 * switchPlayer(player))){
            cout<<"I have to block!"<<endl;
            for (int k=0; k<3; k++){
                if (board[lines[n][k]] == 0){
                    mv = lines[n][k];
                    cout<<"Best Move: "<<mv<<endl;
                    return mv;
                }
            }
        }
     }

     //fork move
     if(forkMove(brd,player)>-1){
        mv = forkMove(brd, player);
        cout<<"Best Move: "<<mv<<endl;
        return mv;
     }

     //random move
     if (mv==-1){
        cout<<"Playing random!"<<endl;
        mv = randomMove(brd, player);
     }
     cout<<"Best Move: "<<mv<<endl;
     return mv;
}

int forkMove(int brd[], int player){
    int fork_move = -1;
    for (int i = 0; i<9; i++){
        int l = 0;
        if (brd[i]==0){
            makeMove(i, brd, player);
            for (int m = 0; m<8; m++){
                if (checkLine(m, brd)== (2 * player)){
                    l = l+1;
                }
            }
            if (l>1){
               fork_move = i;
               cout<<"I can fork!"<<endl;
            }
            brd[i]=0;
            return fork_move;
        }
    }
    return fork_move;
}

void humanMove(int brd[], int player){
    bool done = false;

    while (done == false){
        cout<<"Your turn! Select an empty square."<<endl;
        int box;
        cin>>box;
        done = makeMove(box, brd, player);
    }
}<|endoftext|>


<commit_before>#include <iostream>
#include <limits>

//psi: PolyStatic Interpreter
//"psi" -> interactive interpreter
//"psi liquify file.ps[liquid,solid]" -> interactive interpreter starting with environment from file.psliquid or file.pssolid
//"psi solidify file.psliquid" -> compile file.psliquid into file.pssolid
//"psi melt file.pssolid" -> extract interface information from file.pssolid to file.psgas

int main(int nargs, char const *const *args)
{
	for(unsigned i = 0; i < nargs; ++i)
	{
		std::cout << args[i] << std::endl;
	}

	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
<commit_msg>More planning<commit_after>#include <iostream>
#include <limits>
#include <string>
#include <vector>
#include <algorithm>

//psi: PolyStatic Interpreter
//"psi" -> interactive interpreter
//"psi liquify file.ps[liquid,solid]..." -> interactive interpreter starting with environment from file.psliquid or file.pssolid (*.ps*id)
//"psi solidify file.psliquid..." -> compile file.psliquid into file.pssolid
//"psi melt file.pssolid..." -> extract interface information from file.pssolid to file.psgas

void Liquify(std::vector<std::string> const &files = std::vector<std::string>());
void Solidify(std::vector<std::string> const &files);
void Melt(std::vector<std::string> const &files);

int main(int nargs, char const *const *args_)
{
//	auto &WaitForEnter = []{ std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); };
	if(nargs < 1) return -1;
	std::vector<std::string> args;
	std::for_each(args_+1, args_+nargs, [&args](char const *s)
	{
		args.push_back(s);
	});

	if(args.size() == 0)
	{
		Liquify();
	}
	else
	{
		std::string command = args[0];
		args.pop_front();
		std::transform(command.begin(), command.end(), command.begin(), ::tolower);
		if(command == "liquify")
		{
			Liquify(args);
		}
		else if(command == "solidify")
		{
			Solidify(args);
		}
		else if(command == "melt")
		{
			Melt(args);
		}
		else
		{
			std::cout << '"' << command << "\" is not a command" << std::endl;
		}
	}
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <log4cplus/configurator.h>
#include <log4cplus/loggingmacros.h>
#include "Brain.h"
#include "CurlHelpers.h"
#include "MHEHardDevContainer.h"
#include "MHEDatabase.h"
#include "MHEHardware.h"
#include "MHEWeb.h"

static log4cplus::Logger logger;

int main(int ac, char **av)
{
    boost::program_options::options_description desc("ConfigFile");
	boost::program_options::variables_map vm;
	std::string gcmAppId;
	int webPort, brainRefresh;

	log4cplus::PropertyConfigurator::doConfigure("log4cplus.properties");
	logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("Main"));
	desc.add_options()
		("WebServer.port", boost::program_options::value<int>(&webPort)->default_value(8080))
		("Brain.refresh", boost::program_options::value<int>(&brainRefresh)->default_value(300))
		("Notify.gcmAppId", boost::program_options::value<std::string>(&gcmAppId))
	    ;
    std::ifstream settings_file("config.ini", std::ifstream::in);
	boost::program_options::store(boost::program_options::parse_config_file(settings_file, desc, true), vm);
	settings_file.close();
	boost::program_options::notify(vm);
	curlInit();
	LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("Application starting..."));
	LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - WebServer.port=" << webPort));
	LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - Brain.refresh=" << brainRefresh));
	LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - Notify.gcmAppId=" << gcmAppId));

    MHEDatabase *db = new MHEDatabase();

    if (logger.isEnabledFor(log4cplus::DEBUG_LOG_LEVEL))
    {
        std::vector<DBCondition> conds = db->getConditions();
        BOOST_FOREACH(DBCondition cond, conds)
        {
            LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)cond));
        }
        std::vector<DBGraph> graphs = db->getGraphs();
        BOOST_FOREACH(DBGraph graph, graphs)
        {
            LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)graph));
        }
        std::vector<DBRoom> rooms = db->getRooms();
        BOOST_FOREACH(DBRoom room, rooms)
        {
            LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)room));
        }
        std::vector<DBRoomGraphCond> roomGraphConds = db->getRoomGraphCondByActiveDaysAndCalendar();
        BOOST_FOREACH(DBRoomGraphCond rgc, roomGraphConds)
        {
            LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)rgc));
        }
    }

    MHEMobileNotify *notify = (gcmAppId.size() == 0 ? NULL : new MHEMobileNotify(gcmAppId, db));
    MHEHardDevContainer *hardDev = new MHEHardDevContainer(*db);
    MHEWeb *ws = new MHEWeb(webPort, db, hardDev, notify);
    Brain b(db, hardDev, brainRefresh, notify);
    b.start();

    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("Application stopping..."));
    delete ws;
    if (notify != NULL)
        delete notify;
    delete hardDev;
    delete db;
    curlDestroy();
}
<commit_msg>Clean code.<commit_after>#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <log4cplus/configurator.h>
#include <log4cplus/loggingmacros.h>
#include "Brain.h"
#include "CurlHelpers.h"
#include "MHEHardDevContainer.h"
#include "MHEDatabase.h"
#include "MHEHardware.h"
#include "MHEWeb.h"

int main(int ac, char **av)
{
    boost::program_options::options_description desc("ConfigFile");
	boost::program_options::variables_map vm;
	log4cplus::Logger logger;
	std::string gcmAppId;
	int webPort, brainRefresh;

	log4cplus::PropertyConfigurator::doConfigure("log4cplus.properties");
	logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("Main"));
	desc.add_options()
		("WebServer.port", boost::program_options::value<int>(&webPort)->default_value(8080))
		("Brain.refresh", boost::program_options::value<int>(&brainRefresh)->default_value(300))
		("Notify.gcmAppId", boost::program_options::value<std::string>(&gcmAppId))
	    ;
    std::ifstream settings_file("config.ini", std::ifstream::in);
	boost::program_options::store(boost::program_options::parse_config_file(settings_file, desc, true), vm);
	settings_file.close();
	boost::program_options::notify(vm);
	curlInit();
	LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("Application starting..."));
	LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - WebServer.port=" << webPort));
	LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - Brain.refresh=" << brainRefresh));
	LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - Notify.gcmAppId=" << gcmAppId));

    MHEDatabase *db = new MHEDatabase();

    if (logger.isEnabledFor(log4cplus::DEBUG_LOG_LEVEL))
    {
        std::vector<DBCondition> conds = db->getConditions();
        BOOST_FOREACH(DBCondition cond, conds)
        {
            LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)cond));
        }
        std::vector<DBGraph> graphs = db->getGraphs();
        BOOST_FOREACH(DBGraph graph, graphs)
        {
            LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)graph));
        }
        std::vector<DBRoom> rooms = db->getRooms();
        BOOST_FOREACH(DBRoom room, rooms)
        {
            LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)room));
        }
        std::vector<DBRoomGraphCond> roomGraphConds = db->getRoomGraphCondByActiveDaysAndCalendar();
        BOOST_FOREACH(DBRoomGraphCond rgc, roomGraphConds)
        {
            LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)rgc));
        }
    }

    MHEMobileNotify *notify = (gcmAppId.size() == 0 ? NULL : new MHEMobileNotify(gcmAppId, db));
    MHEHardDevContainer *hardDev = new MHEHardDevContainer(*db);
    MHEWeb *ws = new MHEWeb(webPort, db, hardDev, notify);
    Brain b(db, hardDev, brainRefresh, notify);
    b.start();

    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("Application stopping..."));
    delete ws;
    if (notify != NULL)
        delete notify;
    delete hardDev;
    delete db;
    curlDestroy();
    return 0;
}
<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE Sort
#include <boost/thread.hpp>
#include <boost/test/unit_test.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/reductor.hpp>
#include "context_setup.hpp"

BOOST_AUTO_TEST_CASE(threads)
{
    const size_t n = 1024 * 1024;

    auto run = [n](vex::backend::command_queue queue, cl_long *s) {
        std::vector<vex::backend::command_queue> q(1, queue);
        vex::vector<int> x(q, n);
        x = 1;
        vex::Reductor<cl_long, vex::SUM> sum(q);
        *s = sum(x);
    };

    std::vector< boost::thread > threads;
    std::vector< cl_long       > results(ctx.size(), 0);

    for(unsigned d = 0; d < ctx.size(); ++d) {
        threads.push_back( boost::thread(run, ctx.queue(d), &results[d]) );
    }

    cl_long sum = 0;
    for(unsigned d = 0; d < ctx.size(); ++d) {
        threads[d].join();
        sum += results[d];
    }

    BOOST_CHECK_EQUAL(sum, n * ctx.size());
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Avoid copying boost::thread<commit_after>#define BOOST_TEST_MODULE Sort
#include <boost/thread.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/reductor.hpp>
#include "context_setup.hpp"

BOOST_AUTO_TEST_CASE(threads)
{
    const size_t n = 1024 * 1024;

    auto run = [n](vex::backend::command_queue queue, cl_long *s) {
        std::vector<vex::backend::command_queue> q(1, queue);
        vex::vector<int> x(q, n);
        x = 1;
        vex::Reductor<cl_long, vex::SUM> sum(q);
        *s = sum(x);
    };

    boost::ptr_vector< boost::thread > threads;
    std::vector< cl_long       > results(ctx.size(), 0);

    for(unsigned d = 0; d < ctx.size(); ++d) {
        threads.push_back( new boost::thread(run, ctx.queue(d), &results[d]) );
    }

    cl_long sum = 0;
    for(unsigned d = 0; d < ctx.size(); ++d) {
        threads[d].join();
        sum += results[d];
    }

    BOOST_CHECK_EQUAL(sum, n * ctx.size());
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>

#include <util/PlatformUtils.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

#include <DOMSupport/DOMSupportDefault.hpp>

#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathSupportDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>

#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
#include <XSLT/XSLTResultTarget.hpp>

#include <XercesParserLiaison/XercesParserLiaison.hpp>

#include <XercesPlatformSupport/TextFileOutputStream.hpp>
#include <XercesPlatformSupport/XercesDOMPrintWriter.hpp>

int
main(
			int				argc,
			const char*		/* argv */[])
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::cerr;
	using std::endl;
	using std::ofstream;
#endif

	if (argc != 1)
	{
		cerr << "Usage: SimpleTransform"
			 << endl
			 << endl;
	}
	else
	{
		try
		{
			// Call the static initializers...
			XMLPlatformUtils::Initialize();
			XSLTEngineImpl::Initialize();

			// Create the support objects that are necessary for running the processor...
			DOMSupportDefault				theDOMSupport;
			XercesParserLiaison				theParserLiaison(theDOMSupport);
			XPathSupportDefault				theXPathSupport(theDOMSupport);
			XSLTProcessorEnvSupportDefault	theXSLTProcessorEnvSupport;
			XObjectFactoryDefault			theXObjectFactory;
			XPathFactoryDefault				theXPathFactory;

			// Create a processor...
			XSLTEngineImpl	theProcessor(
					theParserLiaison,
					theXPathSupport,
					theXSLTProcessorEnvSupport,
					theXObjectFactory,
					theXPathFactory);

			// Connect the processor to the support object...
			theXSLTProcessorEnvSupport.setProcessor(&theProcessor);

			// Create a stylesheet construction context, and a stylesheet
			// execution context...
			StylesheetConstructionContextDefault	theConstructionContext(
						theProcessor,
						theXSLTProcessorEnvSupport,
						theXPathFactory);

			StylesheetExecutionContextDefault		theExecutionContext(
						theProcessor,
						theXSLTProcessorEnvSupport,
						theXPathSupport,
						theXObjectFactory);

			// Our input files...The assumption is that the executable will be run
			// from same directory as the input files.
			const XalanDOMString		theXMLFileName("foo.xml");
			const XalanDOMString		theXSLFileName("foo.xsl");

			// Our input sources...
			XSLTInputSource		theInputSource(c_wstr(theXMLFileName));
			XSLTInputSource		theStylesheetSource(c_wstr(theXSLFileName));

			// Our output target...
			TextFileOutputStream	theOutputStream("foo.out");
			XercesDOMPrintWriter	theResultWriter(theOutputStream);
			XSLTResultTarget		theResultTarget(&theResultWriter);

			theProcessor.process(
						theInputSource,
						theStylesheetSource,
						theResultTarget,
						theConstructionContext,
						theExecutionContext);

			// Call the static terminators...
			XMLPlatformUtils::Terminate();
			XSLTEngineImpl::Terminate();
		}
		catch(...)
		{
			cerr << "Exception caught!!!"
				 << endl
				 << endl;
		}
	}

	return 0;
}
<commit_msg>Made some minor changes to support UNIX platforms.<commit_after>// Base header file.  Must be first.
#include <Include/PlatformDefinitions.hpp>

#include <iostream>
#include <fstream>

#include <util/PlatformUtils.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

#include <DOMSupport/DOMSupportDefault.hpp>

#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathSupportDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>

#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
#include <XSLT/XSLTResultTarget.hpp>

#include <XercesParserLiaison/XercesParserLiaison.hpp>

#include <XercesPlatformSupport/TextFileOutputStream.hpp>
#include <XercesPlatformSupport/XercesDOMPrintWriter.hpp>

int
main(
			int				argc,
			const char*		/* argv */[])
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::cerr;
	using std::endl;
	using std::ofstream;
#endif

	if (argc != 1)
	{
		cerr << "Usage: SimpleTransform"
			 << endl
			 << endl;
	}
	else
	{
		try
		{
			// Call the static initializers...
			XMLPlatformUtils::Initialize();
			XSLTEngineImpl::Initialize();

			// Create the support objects that are necessary for running the processor...
			DOMSupportDefault				theDOMSupport;
			XercesParserLiaison				theParserLiaison(theDOMSupport);
			XPathSupportDefault				theXPathSupport(theDOMSupport);
			XSLTProcessorEnvSupportDefault	theXSLTProcessorEnvSupport;
			XObjectFactoryDefault			theXObjectFactory;
			XPathFactoryDefault				theXPathFactory;

			// Create a processor...
			XSLTEngineImpl	theProcessor(
					theParserLiaison,
					theXPathSupport,
					theXSLTProcessorEnvSupport,
					theXObjectFactory,
					theXPathFactory);

			// Connect the processor to the support object...
			theXSLTProcessorEnvSupport.setProcessor(&theProcessor);

			// Create a stylesheet construction context, and a stylesheet
			// execution context...
			StylesheetConstructionContextDefault	theConstructionContext(
						theProcessor,
						theXSLTProcessorEnvSupport,
						theXPathFactory);

			StylesheetExecutionContextDefault		theExecutionContext(
						theProcessor,
						theXSLTProcessorEnvSupport,
						theXPathSupport,
						theXObjectFactory);

			// Our input files...The assumption is that the executable will be run
			// from same directory as the input files.
			const XalanDOMString		theXMLFileName("foo.xml");
			const XalanDOMString		theXSLFileName("foo.xsl");

			// Our input sources...
			XSLTInputSource		theInputSource(c_wstr(theXMLFileName));
			XSLTInputSource		theStylesheetSource(c_wstr(theXSLFileName));

			// Our output target...
			TextFileOutputStream	theOutputStream("foo.out");
			XercesDOMPrintWriter	theResultWriter(theOutputStream);
			XSLTResultTarget		theResultTarget(&theResultWriter);

			theProcessor.process(
						theInputSource,
						theStylesheetSource,
						theResultTarget,
						theConstructionContext,
						theExecutionContext);

			// Call the static terminators...
			XMLPlatformUtils::Terminate();
			XSLTEngineImpl::Terminate();
		}
		catch(...)
		{
			cerr << "Exception caught!!!"
				 << endl
				 << endl;
		}
	}

	return 0;
}
<|endoftext|>