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

#include "main.h"
#include "masternode-budget.h"
#include "messagesigner.h"
#include "net.h"
#include "spork.h"
#include "sporkdb.h"
#include <iostream>

#define MAKE_SPORK_DEF(name, defaultValue) CSporkDef(name, defaultValue, #name)

std::vector<CSporkDef> sporkDefs = {
    MAKE_SPORK_DEF(SPORK_2_SWIFTTX,                         0),             // ON
    MAKE_SPORK_DEF(SPORK_3_SWIFTTX_BLOCK_FILTERING,         0),             // ON
    MAKE_SPORK_DEF(SPORK_5_MAX_VALUE,                       1000),          // 1000 PIV
    MAKE_SPORK_DEF(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT,  4070908800ULL), // OFF
    MAKE_SPORK_DEF(SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT,   4070908800ULL), // OFF
    MAKE_SPORK_DEF(SPORK_10_MASTERNODE_PAY_UPDATED_NODES,   0),             // OFF
    MAKE_SPORK_DEF(SPORK_13_ENABLE_SUPERBLOCKS,             4070908800ULL), // OFF
    MAKE_SPORK_DEF(SPORK_14_NEW_PROTOCOL_ENFORCEMENT,       4070908800ULL), // OFF
    MAKE_SPORK_DEF(SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2,     4070908800ULL), // OFF
    MAKE_SPORK_DEF(SPORK_16_ZEROCOIN_MAINTENANCE_MODE,      4070908800ULL), // OFF
    MAKE_SPORK_DEF(SPORK_17_COLDSTAKING_ENFORCEMENT,        4070908800ULL), // OFF
    MAKE_SPORK_DEF(SPORK_18_ZEROCOIN_PUBLICSPEND_V4,        4070908800ULL), // OFF
};

CSporkManager sporkManager;
std::map<uint256, CSporkMessage> mapSporks;

CSporkManager::CSporkManager()
{
    for (auto& sporkDef : sporkDefs) {
        sporkDefsById.emplace(sporkDef.sporkId, &sporkDef);
        sporkDefsByName.emplace(sporkDef.name, &sporkDef);
    }
}

void CSporkManager::Clear()
{
    strMasterPrivKey = "";
    mapSporksActive.clear();
}

// PIVX: on startup load spork values from previous session if they exist in the sporkDB
void CSporkManager::LoadSporksFromDB()
{
    for (const auto& sporkDef : sporkDefs) {
        // attempt to read spork from sporkDB
        CSporkMessage spork;
        if (!pSporkDB->ReadSpork(sporkDef.sporkId, spork)) {
            LogPrintf("%s : no previous value for %s found in database\n", __func__, sporkDef.name);
            continue;
        }

        // add spork to memory
        mapSporks[spork.GetHash()] = spork;
        mapSporksActive[spork.nSporkID] = spork;
        std::time_t result = spork.nValue;
        // If SPORK Value is greater than 1,000,000 assume it's actually a Date and then convert to a more readable format
        std::string sporkName = sporkManager.GetSporkNameByID(spork.nSporkID);
        if (spork.nValue > 1000000) {
            char* res = std::ctime(&result);
            LogPrintf("%s : loaded spork %s with value %d : %s\n", __func__, sporkName.c_str(), spork.nValue,
                      ((res) ? res : "no time") );
        } else {
            LogPrintf("%s : loaded spork %s with value %d\n", __func__,
                      sporkName, spork.nValue);
        }
    }
}

void CSporkManager::ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
    if (fLiteMode || chainActive.Tip() == nullptr) return; // disable all obfuscation/masternode related functionality

    if (strCommand == "spork") {

        CSporkMessage spork;
        vRecv >> spork;

        // Ignore spork messages about unknown/deleted sporks
        std::string strSpork = sporkManager.GetSporkNameByID(spork.nSporkID);
        if (strSpork == "Unknown") return;

        // Do not accept sporks signed way too far into the future
        if (spork.nTimeSigned > GetAdjustedTime() + 2 * 60 * 60) {
            LOCK(cs_main);
            LogPrintf("%s : ERROR: too far into the future\n", __func__);
            Misbehaving(pfrom->GetId(), 100);
            return;
        }

        // reject old signatures 600 blocks after hard-fork
        if (spork.nMessVersion != MessageVersion::MESS_VER_HASH) {
            int nHeight;
            {
                LOCK(cs_main);
                nHeight = chainActive.Height();
            }
            if (Params().NewSigsActive(nHeight - 600)) {
                LogPrintf("%s : nMessVersion=%d not accepted anymore at block %d", __func__, spork.nMessVersion, nHeight);
                return;
            }
        }

        uint256 hash = spork.GetHash();
        {
            LOCK(cs);
            if (mapSporksActive.count(spork.nSporkID)) {
                // spork is active
                if (mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned) {
                    // spork in memory has been signed more recently
                    if (fDebug) LogPrintf("%s : seen %s block %d \n", __func__, hash.ToString(), chainActive.Tip()->nHeight);
                    return;
                } else {
                    // update active spork
                    if (fDebug) LogPrintf("%s : got updated spork %s block %d \n", __func__, hash.ToString(), chainActive.Tip()->nHeight);
                }
            } else {
                // spork is not active
                if (fDebug) LogPrintf("%s : got new spork %s block %d \n", __func__, hash.ToString(), chainActive.Tip()->nHeight);
            }
        }

        LogPrintf("%s : new %s ID %d Time %d bestHeight %d\n", __func__, hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Tip()->nHeight);

        const bool fRequireNew = spork.nTimeSigned >= Params().NewSporkStart();
        bool fValidSig = spork.CheckSignature();
        if (!fValidSig && !fRequireNew) {
            // See if window is open that allows for old spork key to sign messages
            if (GetAdjustedTime() < Params().RejectOldSporkKey()) {
                CPubKey pubkeyold = spork.GetPublicKeyOld();
                fValidSig = spork.CheckSignature(pubkeyold);
            }
        }

        if (!fValidSig) {
            LOCK(cs_main);
            LogPrintf("%s : Invalid Signature\n", __func__);
            Misbehaving(pfrom->GetId(), 100);
            return;
        }

        {
            LOCK(cs);
            mapSporks[hash] = spork;
            mapSporksActive[spork.nSporkID] = spork;
        }
        spork.Relay();

        // PIVX: add to spork database.
        pSporkDB->WriteSpork(spork.nSporkID, spork);
    }
    if (strCommand == "getsporks") {
        LOCK(cs);
        std::map<SporkId, CSporkMessage>::iterator it = mapSporksActive.begin();

        while (it != mapSporksActive.end()) {
            pfrom->PushMessage("spork", it->second);
            it++;
        }
    }
}

bool CSporkManager::UpdateSpork(SporkId nSporkID, int64_t nValue)
{
    bool fNewSigs = false;
    {
        LOCK(cs_main);
        fNewSigs = chainActive.NewSigsActive();
    }

    CSporkMessage spork = CSporkMessage(nSporkID, nValue, GetTime());

    if(spork.Sign(strMasterPrivKey, fNewSigs)){
        spork.Relay();
        LOCK(cs);
        mapSporks[spork.GetHash()] = spork;
        mapSporksActive[nSporkID] = spork;
        return true;
    }

    return false;
}

// grab the spork value, and see if it's off
bool CSporkManager::IsSporkActive(SporkId nSporkID)
{
    return GetSporkValue(nSporkID) < GetAdjustedTime();
}

// grab the value of the spork on the network, or the default
int64_t CSporkManager::GetSporkValue(SporkId nSporkID)
{
    LOCK(cs);

    if (mapSporksActive.count(nSporkID)) {
        return mapSporksActive[nSporkID].nValue;

    } else {
        auto it = sporkDefsById.find(nSporkID);
        if (it != sporkDefsById.end()) {
            return it->second->defaultValue;
        } else {
            LogPrintf("%s : Unknown Spork %d\n", __func__, nSporkID);
        }
    }

    return -1;
}

SporkId CSporkManager::GetSporkIDByName(std::string strName)
{
    auto it = sporkDefsByName.find(strName);
    if (it == sporkDefsByName.end()) {
        LogPrintf("%s : Unknown Spork name '%s'\n", __func__, strName);
        return SPORK_INVALID;
    }
    return it->second->sporkId;
}

std::string CSporkManager::GetSporkNameByID(SporkId nSporkID)
{
    auto it = sporkDefsById.find(nSporkID);
    if (it == sporkDefsById.end()) {
        LogPrint("%s : Unknown Spork ID %d\n", __func__, nSporkID);
        return "Unknown";
    }
    return it->second->name;
}

bool CSporkManager::SetPrivKey(std::string strPrivKey)
{
    CSporkMessage spork;

    spork.Sign(strPrivKey, true);

    const bool fRequireNew = GetTime() >= Params().NewSporkStart();
    bool fValidSig = spork.CheckSignature();
    if (!fValidSig && !fRequireNew) {
        // See if window is open that allows for old spork key to sign messages
        if (GetAdjustedTime() < Params().RejectOldSporkKey()) {
            CPubKey pubkeyold = spork.GetPublicKeyOld();
            fValidSig = spork.CheckSignature(pubkeyold);
        }
    }
    if (fValidSig) {
        LOCK(cs);
        // Test signing successful, proceed
        LogPrintf("%s : Successfully initialized as spork signer\n", __func__);
        strMasterPrivKey = strPrivKey;
        return true;
    }

    return false;
}

std::string CSporkManager::ToString() const
{
    LOCK(cs);
    return strprintf("Sporks: %llu", mapSporksActive.size());
}

uint256 CSporkMessage::GetSignatureHash() const
{
    CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
    ss << nMessVersion;
    ss << nSporkID;
    ss << nValue;
    ss << nTimeSigned;
    return ss.GetHash();
}

std::string CSporkMessage::GetStrMessage() const
{
    return std::to_string(nSporkID) +
            std::to_string(nValue) +
            std::to_string(nTimeSigned);
}

const CPubKey CSporkMessage::GetPublicKey(std::string& strErrorRet) const
{
    return CPubKey(ParseHex(Params().SporkPubKey()));
}

const CPubKey CSporkMessage::GetPublicKeyOld() const
{
    return CPubKey(ParseHex(Params().SporkPubKeyOld()));
}

void CSporkMessage::Relay()
{
    CInv inv(MSG_SPORK, GetHash());
    RelayInv(inv);
}

<commit_msg>[Spork] Guard chainActive.Tip() and chainActive.Height() methods call.<commit_after>// Copyright (c) 2014-2016 The Dash developers
// Copyright (c) 2016-2018 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "main.h"
#include "masternode-budget.h"
#include "messagesigner.h"
#include "net.h"
#include "spork.h"
#include "sporkdb.h"
#include <iostream>

#define MAKE_SPORK_DEF(name, defaultValue) CSporkDef(name, defaultValue, #name)

std::vector<CSporkDef> sporkDefs = {
    MAKE_SPORK_DEF(SPORK_2_SWIFTTX,                         0),             // ON
    MAKE_SPORK_DEF(SPORK_3_SWIFTTX_BLOCK_FILTERING,         0),             // ON
    MAKE_SPORK_DEF(SPORK_5_MAX_VALUE,                       1000),          // 1000 PIV
    MAKE_SPORK_DEF(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT,  4070908800ULL), // OFF
    MAKE_SPORK_DEF(SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT,   4070908800ULL), // OFF
    MAKE_SPORK_DEF(SPORK_10_MASTERNODE_PAY_UPDATED_NODES,   0),             // OFF
    MAKE_SPORK_DEF(SPORK_13_ENABLE_SUPERBLOCKS,             4070908800ULL), // OFF
    MAKE_SPORK_DEF(SPORK_14_NEW_PROTOCOL_ENFORCEMENT,       4070908800ULL), // OFF
    MAKE_SPORK_DEF(SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2,     4070908800ULL), // OFF
    MAKE_SPORK_DEF(SPORK_16_ZEROCOIN_MAINTENANCE_MODE,      4070908800ULL), // OFF
    MAKE_SPORK_DEF(SPORK_17_COLDSTAKING_ENFORCEMENT,        4070908800ULL), // OFF
    MAKE_SPORK_DEF(SPORK_18_ZEROCOIN_PUBLICSPEND_V4,        4070908800ULL), // OFF
};

CSporkManager sporkManager;
std::map<uint256, CSporkMessage> mapSporks;

CSporkManager::CSporkManager()
{
    for (auto& sporkDef : sporkDefs) {
        sporkDefsById.emplace(sporkDef.sporkId, &sporkDef);
        sporkDefsByName.emplace(sporkDef.name, &sporkDef);
    }
}

void CSporkManager::Clear()
{
    strMasterPrivKey = "";
    mapSporksActive.clear();
}

// PIVX: on startup load spork values from previous session if they exist in the sporkDB
void CSporkManager::LoadSporksFromDB()
{
    for (const auto& sporkDef : sporkDefs) {
        // attempt to read spork from sporkDB
        CSporkMessage spork;
        if (!pSporkDB->ReadSpork(sporkDef.sporkId, spork)) {
            LogPrintf("%s : no previous value for %s found in database\n", __func__, sporkDef.name);
            continue;
        }

        // add spork to memory
        mapSporks[spork.GetHash()] = spork;
        mapSporksActive[spork.nSporkID] = spork;
        std::time_t result = spork.nValue;
        // If SPORK Value is greater than 1,000,000 assume it's actually a Date and then convert to a more readable format
        std::string sporkName = sporkManager.GetSporkNameByID(spork.nSporkID);
        if (spork.nValue > 1000000) {
            char* res = std::ctime(&result);
            LogPrintf("%s : loaded spork %s with value %d : %s\n", __func__, sporkName.c_str(), spork.nValue,
                      ((res) ? res : "no time") );
        } else {
            LogPrintf("%s : loaded spork %s with value %d\n", __func__,
                      sporkName, spork.nValue);
        }
    }
}

void CSporkManager::ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
    if (fLiteMode) return; // disable all obfuscation/masternode related functionality

    int nChainHeight = 0;
    {
        LOCK(cs_main);
        if (chainActive.Tip() == nullptr)
            return;
        nChainHeight = chainActive.Height();
    }

    if (strCommand == "spork") {

        CSporkMessage spork;
        vRecv >> spork;

        // Ignore spork messages about unknown/deleted sporks
        std::string strSpork = sporkManager.GetSporkNameByID(spork.nSporkID);
        if (strSpork == "Unknown") return;

        // Do not accept sporks signed way too far into the future
        if (spork.nTimeSigned > GetAdjustedTime() + 2 * 60 * 60) {
            LOCK(cs_main);
            LogPrintf("%s : ERROR: too far into the future\n", __func__);
            Misbehaving(pfrom->GetId(), 100);
            return;
        }

        // reject old signatures 600 blocks after hard-fork
        if (spork.nMessVersion != MessageVersion::MESS_VER_HASH) {
            if (Params().NewSigsActive(nChainHeight - 600)) {
                LogPrintf("%s : nMessVersion=%d not accepted anymore at block %d\n", __func__, spork.nMessVersion, nChainHeight);
                return;
            }
        }

        uint256 hash = spork.GetHash();
        {
            LOCK(cs);
            if (mapSporksActive.count(spork.nSporkID)) {
                // spork is active
                if (mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned) {
                    // spork in memory has been signed more recently
                    if (fDebug) LogPrintf("%s : seen %s block %d \n", __func__, hash.ToString(), nChainHeight);
                    return;
                } else {
                    // update active spork
                    if (fDebug) LogPrintf("%s : got updated spork %s block %d \n", __func__, hash.ToString(), nChainHeight);
                }
            } else {
                // spork is not active
                if (fDebug) LogPrintf("%s : got new spork %s block %d \n", __func__, hash.ToString(), nChainHeight);
            }
        }

        LogPrintf("%s : new %s ID %d Time %d bestHeight %d\n", __func__, hash.ToString(), spork.nSporkID, spork.nValue, nChainHeight);

        const bool fRequireNew = spork.nTimeSigned >= Params().NewSporkStart();
        bool fValidSig = spork.CheckSignature();
        if (!fValidSig && !fRequireNew) {
            // See if window is open that allows for old spork key to sign messages
            if (GetAdjustedTime() < Params().RejectOldSporkKey()) {
                CPubKey pubkeyold = spork.GetPublicKeyOld();
                fValidSig = spork.CheckSignature(pubkeyold);
            }
        }

        if (!fValidSig) {
            LOCK(cs_main);
            LogPrintf("%s : Invalid Signature\n", __func__);
            Misbehaving(pfrom->GetId(), 100);
            return;
        }

        {
            LOCK(cs);
            mapSporks[hash] = spork;
            mapSporksActive[spork.nSporkID] = spork;
        }
        spork.Relay();

        // PIVX: add to spork database.
        pSporkDB->WriteSpork(spork.nSporkID, spork);
    }
    if (strCommand == "getsporks") {
        LOCK(cs);
        std::map<SporkId, CSporkMessage>::iterator it = mapSporksActive.begin();

        while (it != mapSporksActive.end()) {
            pfrom->PushMessage("spork", it->second);
            it++;
        }
    }
}

bool CSporkManager::UpdateSpork(SporkId nSporkID, int64_t nValue)
{
    bool fNewSigs = false;
    {
        LOCK(cs_main);
        fNewSigs = chainActive.NewSigsActive();
    }

    CSporkMessage spork = CSporkMessage(nSporkID, nValue, GetTime());

    if(spork.Sign(strMasterPrivKey, fNewSigs)){
        spork.Relay();
        LOCK(cs);
        mapSporks[spork.GetHash()] = spork;
        mapSporksActive[nSporkID] = spork;
        return true;
    }

    return false;
}

// grab the spork value, and see if it's off
bool CSporkManager::IsSporkActive(SporkId nSporkID)
{
    return GetSporkValue(nSporkID) < GetAdjustedTime();
}

// grab the value of the spork on the network, or the default
int64_t CSporkManager::GetSporkValue(SporkId nSporkID)
{
    LOCK(cs);

    if (mapSporksActive.count(nSporkID)) {
        return mapSporksActive[nSporkID].nValue;

    } else {
        auto it = sporkDefsById.find(nSporkID);
        if (it != sporkDefsById.end()) {
            return it->second->defaultValue;
        } else {
            LogPrintf("%s : Unknown Spork %d\n", __func__, nSporkID);
        }
    }

    return -1;
}

SporkId CSporkManager::GetSporkIDByName(std::string strName)
{
    auto it = sporkDefsByName.find(strName);
    if (it == sporkDefsByName.end()) {
        LogPrintf("%s : Unknown Spork name '%s'\n", __func__, strName);
        return SPORK_INVALID;
    }
    return it->second->sporkId;
}

std::string CSporkManager::GetSporkNameByID(SporkId nSporkID)
{
    auto it = sporkDefsById.find(nSporkID);
    if (it == sporkDefsById.end()) {
        LogPrint("%s : Unknown Spork ID %d\n", __func__, nSporkID);
        return "Unknown";
    }
    return it->second->name;
}

bool CSporkManager::SetPrivKey(std::string strPrivKey)
{
    CSporkMessage spork;

    spork.Sign(strPrivKey, true);

    const bool fRequireNew = GetTime() >= Params().NewSporkStart();
    bool fValidSig = spork.CheckSignature();
    if (!fValidSig && !fRequireNew) {
        // See if window is open that allows for old spork key to sign messages
        if (GetAdjustedTime() < Params().RejectOldSporkKey()) {
            CPubKey pubkeyold = spork.GetPublicKeyOld();
            fValidSig = spork.CheckSignature(pubkeyold);
        }
    }
    if (fValidSig) {
        LOCK(cs);
        // Test signing successful, proceed
        LogPrintf("%s : Successfully initialized as spork signer\n", __func__);
        strMasterPrivKey = strPrivKey;
        return true;
    }

    return false;
}

std::string CSporkManager::ToString() const
{
    LOCK(cs);
    return strprintf("Sporks: %llu", mapSporksActive.size());
}

uint256 CSporkMessage::GetSignatureHash() const
{
    CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
    ss << nMessVersion;
    ss << nSporkID;
    ss << nValue;
    ss << nTimeSigned;
    return ss.GetHash();
}

std::string CSporkMessage::GetStrMessage() const
{
    return std::to_string(nSporkID) +
            std::to_string(nValue) +
            std::to_string(nTimeSigned);
}

const CPubKey CSporkMessage::GetPublicKey(std::string& strErrorRet) const
{
    return CPubKey(ParseHex(Params().SporkPubKey()));
}

const CPubKey CSporkMessage::GetPublicKeyOld() const
{
    return CPubKey(ParseHex(Params().SporkPubKeyOld()));
}

void CSporkMessage::Relay()
{
    CInv inv(MSG_SPORK, GetHash());
    RelayInv(inv);
}

<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 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.

#include <os>
#include <vga>
#include <cassert>
#include <net/inet4>
#include <hw/ps2.hpp>

#include "snake.hpp"

ConsoleVGA vga;

void begin_snake()
{
  hw::KBM::init();
  static Snake snake(vga);

  hw::KBM::set_virtualkey_handler(
  [] (int key) {

    if (key == hw::KBM::VK_RIGHT) {
      snake.set_dir(Snake::RIGHT);
    }
    if (key == hw::KBM::VK_LEFT) {
      snake.set_dir(Snake::LEFT);
    }
    if (key == hw::KBM::VK_UP) {
      snake.set_dir(Snake::UP);
    }
    if (key == hw::KBM::VK_DOWN) {
      snake.set_dir(Snake::DOWN);
    }
    if (key == hw::KBM::VK_SPACE) {
      if (snake.is_gameover())
        snake.reset();
    }

  });
}

void Service::start()
{
  // redirect stdout to vga screen
  // ... even though we aren't really using it after the game starts

  OS::set_rsprint(
  [] (const char* data, size_t len)
  {
    vga.write(data, len);
  });

  // we have to start snake later to avoid late text output
  hw::PIT::on_timeout(0.25, [] { begin_snake(); });

  // Stack with network interface (eth0) driven by VirtioNet
  // DNS address defaults to 8.8.8.8
  auto inet = net::new_ipv4_stack<>(0.15, [](bool timeout) {
    if (timeout) {
      printf("%s\n", "DHCP negotiation timed out\n");
    } else {
      printf("%s\n", "DHCP negotiation completed successfully\n");
    }
  });

  // Static IP configuration, until we (possibly) get DHCP
  inet->network_config({ 10,0,0,42 },      // IP
                       { 255,255,255,0 },  // Netmask
                       { 10,0,0,1 },       // Gateway
                       { 8,8,8,8 });       // DNS

  printf("*** TEST SERVICE STARTED ***\n");
}
<commit_msg>Refactored function begin_snake<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 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.

#include <os>
#include <vga>
#include <cassert>
#include <net/inet4>
#include <hw/ps2.hpp>

#include "snake.hpp"

ConsoleVGA vga;

void begin_snake()
{
  static Snake snake {vga};

  hw::KBM::init();
  hw::KBM::set_virtualkey_handler(
  [] (int key) {
    if (key == hw::KBM::VK_RIGHT) {
      snake.set_dir(Snake::RIGHT);
    } else if (key == hw::KBM::VK_LEFT) {
      snake.set_dir(Snake::LEFT);
    } else if (key == hw::KBM::VK_UP) {
      snake.set_dir(Snake::UP);
    } else if (key == hw::KBM::VK_DOWN) {
      snake.set_dir(Snake::DOWN);
    } else if (key == hw::KBM::VK_SPACE and snake.is_gameover()) {
      snake.reset();
    }
  });
}

void Service::start()
{
  // redirect stdout to vga screen
  // ... even though we aren't really using it after the game starts

  OS::set_rsprint(
  [] (const char* data, size_t len)
  {
    vga.write(data, len);
  });

  // we have to start snake later to avoid late text output
  hw::PIT::on_timeout(0.25, [] { begin_snake(); });

  // Stack with network interface (eth0) driven by VirtioNet
  // DNS address defaults to 8.8.8.8
  auto inet = net::new_ipv4_stack<>(0.15, [](bool timeout) {
    if (timeout) {
      printf("%s\n", "DHCP negotiation timed out\n");
    } else {
      printf("%s\n", "DHCP negotiation completed successfully\n");
    }
  });

  // Static IP configuration, until we (possibly) get DHCP
  inet->network_config({ 10,0,0,42 },      // IP
                       { 255,255,255,0 },  // Netmask
                       { 10,0,0,1 },       // Gateway
                       { 8,8,8,8 });       // DNS

  printf("*** TEST SERVICE STARTED ***\n");
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013-2016 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
 *
 * This file is part of vanillacoin.
 *
 * vanillacoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include <coin/address_manager.hpp>
#include <coin/configuration.hpp>
#include <coin/constants.hpp>
#include <coin/logger.hpp>
#include <coin/protocol.hpp>
#include <coin/stack.hpp>
#include <coin/stack_impl.hpp>

using namespace coin;

stack::stack()
    : stack_impl_(0)
{
    // ...
}

void stack::start(const std::map<std::string, std::string> & args)
{
    if (stack_impl_)
    {
        throw std::runtime_error("Stack is already allocated");
    }
    else
    {
        /**
         * Allocate the stack implementation.
         */
        stack_impl_ = new stack_impl(*this);

        /**
         * Set the arguments.
         */
        stack_impl_->get_configuration().set_args(args);

        /**
         * Use different bootstrap endpoints for test networks.
         */
        if (constants::test_net == true)
        {
            /**
             * Add any test network nodes here.
             */
        }
        else
        {
            stack_impl_->get_configuration().bootstrap_nodes().push_back(
                std::make_pair("23.254.243.105", 32809)
            );
            stack_impl_->get_configuration().bootstrap_nodes().push_back(
                std::make_pair("23.254.243.106", 40006)
            );
            stack_impl_->get_configuration().bootstrap_nodes().push_back(
                std::make_pair("23.254.243.107", 40008)
            );
            stack_impl_->get_configuration().bootstrap_nodes().push_back(
                std::make_pair("23.254.243.108", 60912)
            );
            stack_impl_->get_configuration().bootstrap_nodes().push_back(
                std::make_pair("23.254.243.167", 32997)
            );
            stack_impl_->get_configuration().bootstrap_nodes().push_back(
                std::make_pair("23.254.243.168", 34749)
            );
        }

        /**
         * Start the stack implementation.
         */
        stack_impl_->start();
    }
}

void stack::stop()
{
    if (stack_impl_)
    {
        /**
         * Stop the stack implementation.
         */
        stack_impl_->stop();

        /**
         * Deallocate the stack implementation.
         */
        delete stack_impl_, stack_impl_ = 0;
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }
}

void stack::send_coins(
    const std::int64_t & amount, const std::string & destination,
    const std::map<std::string, std::string> & wallet_values
    )
{
    if (stack_impl_)
    {
        stack_impl_->send_coins(amount, destination, wallet_values);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }
}

void stack::start_mining(
    const std::map<std::string, std::string> & mining_values
    )
{
    if (stack_impl_)
    {
        stack_impl_->start_mining(mining_values);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }
}

void stack::stop_mining(
    const std::map<std::string, std::string> & mining_values
    )
{
    if (stack_impl_)
    {
        stack_impl_->stop_mining(mining_values);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }
}

void stack::broadcast_alert(const std::map<std::string, std::string> & pairs)
{
    if (stack_impl_)
    {
        stack_impl_->broadcast_alert(pairs);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }
}

void stack::wallet_encrypt(const std::string & passphrase)
{
    if (stack_impl_)
    {
        stack_impl_->wallet_encrypt(passphrase);
    }
}

void stack::wallet_lock()
{
    if (stack_impl_)
    {
        stack_impl_->wallet_lock();
    }
}

void stack::wallet_unlock(const std::string & passphrase)
{
    if (stack_impl_)
    {
        stack_impl_->wallet_unlock(passphrase);
    }
}

void stack::wallet_change_passphrase(
    const std::string & passphrase_old, const std::string & password_new
    )
{
    if (stack_impl_)
    {
        stack_impl_->wallet_change_passphrase(passphrase_old, password_new);
    }
}

bool stack::wallet_is_crypted(const std::uint32_t & wallet_id)
{
    if (stack_impl_)
    {
        return stack_impl_->wallet_is_crypted(wallet_id);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }

    return false;
}

bool stack::wallet_is_locked(const std::uint32_t & wallet_id)
{
    if (stack_impl_)
    {
        return stack_impl_->wallet_is_locked(wallet_id);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }

    return false;
}

void stack::wallet_zerotime_lock(const std::string & tx_id)
{
    if (stack_impl_)
    {
        stack_impl_->wallet_zerotime_lock(tx_id);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }
}

void stack::on_error(const std::map<std::string, std::string> & pairs)
{
    log_error("Stack got error, pairs = " << pairs.size() << ".");
}

void stack::rpc_send(const std::string & command_line)
{
    if (stack_impl_)
    {
        stack_impl_->rpc_send(command_line);
    }
}

void stack::set_configuration_wallet_transaction_history_maximum(
    const std::time_t & val
    )
{
    if (stack_impl_)
    {
        stack_impl_->set_configuration_wallet_transaction_history_maximum(val);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }
}

const std::time_t
    stack::configuration_wallet_transaction_history_maximum() const
{
    if (stack_impl_)
    {
        return stack_impl_->configuration_wallet_transaction_history_maximum();
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }

    return 0;
}

void stack::on_status(const std::map<std::string, std::string> & pairs)
{
    log_none("Stack got info, pairs = " << pairs.size() << ".");
}

void stack::on_alert(const std::map<std::string, std::string> & pairs)
{
    log_none("Stack got alert, pairs = " << pairs.size() << ".");
}

<commit_msg>update static bootstrap endpoints (again)<commit_after>/*
 * Copyright (c) 2013-2016 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
 *
 * This file is part of vanillacoin.
 *
 * vanillacoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include <coin/address_manager.hpp>
#include <coin/configuration.hpp>
#include <coin/constants.hpp>
#include <coin/logger.hpp>
#include <coin/protocol.hpp>
#include <coin/stack.hpp>
#include <coin/stack_impl.hpp>

using namespace coin;

stack::stack()
    : stack_impl_(0)
{
    // ...
}

void stack::start(const std::map<std::string, std::string> & args)
{
    if (stack_impl_)
    {
        throw std::runtime_error("Stack is already allocated");
    }
    else
    {
        /**
         * Allocate the stack implementation.
         */
        stack_impl_ = new stack_impl(*this);

        /**
         * Set the arguments.
         */
        stack_impl_->get_configuration().set_args(args);

        /**
         * Use different bootstrap endpoints for test networks.
         */
        if (constants::test_net == true)
        {
            /**
             * Add any test network nodes here.
             */
        }
        else
        {
            stack_impl_->get_configuration().bootstrap_nodes().push_back(
                std::make_pair("23.254.243.105", 32809)
            );
            stack_impl_->get_configuration().bootstrap_nodes().push_back(
                std::make_pair("23.254.243.106", 40006)
            );
            stack_impl_->get_configuration().bootstrap_nodes().push_back(
                std::make_pair("23.254.243.107", 40008)
            );
            stack_impl_->get_configuration().bootstrap_nodes().push_back(
                std::make_pair("23.254.243.108", 60912)
            );
            stack_impl_->get_configuration().bootstrap_nodes().push_back(
                std::make_pair("23.254.243.115", 53389)
            );
            stack_impl_->get_configuration().bootstrap_nodes().push_back(
                std::make_pair("23.254.243.12", 38548)
            );
        }

        /**
         * Start the stack implementation.
         */
        stack_impl_->start();
    }
}

void stack::stop()
{
    if (stack_impl_)
    {
        /**
         * Stop the stack implementation.
         */
        stack_impl_->stop();

        /**
         * Deallocate the stack implementation.
         */
        delete stack_impl_, stack_impl_ = 0;
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }
}

void stack::send_coins(
    const std::int64_t & amount, const std::string & destination,
    const std::map<std::string, std::string> & wallet_values
    )
{
    if (stack_impl_)
    {
        stack_impl_->send_coins(amount, destination, wallet_values);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }
}

void stack::start_mining(
    const std::map<std::string, std::string> & mining_values
    )
{
    if (stack_impl_)
    {
        stack_impl_->start_mining(mining_values);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }
}

void stack::stop_mining(
    const std::map<std::string, std::string> & mining_values
    )
{
    if (stack_impl_)
    {
        stack_impl_->stop_mining(mining_values);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }
}

void stack::broadcast_alert(const std::map<std::string, std::string> & pairs)
{
    if (stack_impl_)
    {
        stack_impl_->broadcast_alert(pairs);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }
}

void stack::wallet_encrypt(const std::string & passphrase)
{
    if (stack_impl_)
    {
        stack_impl_->wallet_encrypt(passphrase);
    }
}

void stack::wallet_lock()
{
    if (stack_impl_)
    {
        stack_impl_->wallet_lock();
    }
}

void stack::wallet_unlock(const std::string & passphrase)
{
    if (stack_impl_)
    {
        stack_impl_->wallet_unlock(passphrase);
    }
}

void stack::wallet_change_passphrase(
    const std::string & passphrase_old, const std::string & password_new
    )
{
    if (stack_impl_)
    {
        stack_impl_->wallet_change_passphrase(passphrase_old, password_new);
    }
}

bool stack::wallet_is_crypted(const std::uint32_t & wallet_id)
{
    if (stack_impl_)
    {
        return stack_impl_->wallet_is_crypted(wallet_id);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }

    return false;
}

bool stack::wallet_is_locked(const std::uint32_t & wallet_id)
{
    if (stack_impl_)
    {
        return stack_impl_->wallet_is_locked(wallet_id);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }

    return false;
}

void stack::wallet_zerotime_lock(const std::string & tx_id)
{
    if (stack_impl_)
    {
        stack_impl_->wallet_zerotime_lock(tx_id);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }
}

void stack::on_error(const std::map<std::string, std::string> & pairs)
{
    log_error("Stack got error, pairs = " << pairs.size() << ".");
}

void stack::rpc_send(const std::string & command_line)
{
    if (stack_impl_)
    {
        stack_impl_->rpc_send(command_line);
    }
}

void stack::set_configuration_wallet_transaction_history_maximum(
    const std::time_t & val
    )
{
    if (stack_impl_)
    {
        stack_impl_->set_configuration_wallet_transaction_history_maximum(val);
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }
}

const std::time_t
    stack::configuration_wallet_transaction_history_maximum() const
{
    if (stack_impl_)
    {
        return stack_impl_->configuration_wallet_transaction_history_maximum();
    }
    else
    {
        throw std::runtime_error("Stack is not allocated");
    }

    return 0;
}

void stack::on_status(const std::map<std::string, std::string> & pairs)
{
    log_none("Stack got info, pairs = " << pairs.size() << ".");
}

void stack::on_alert(const std::map<std::string, std::string> & pairs)
{
    log_none("Stack got alert, pairs = " << pairs.size() << ".");
}

<|endoftext|>


<commit_before>// Copyright 2011-2012 Google
// 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.

#include "base/hash.h"
#include "base/map-util.h"
#include "base/stl_util.h"
#include "base/random.h"
#include "constraint_solver/constraint_solveri.h"
#include "constraint_solver/constraint_solver.h"
#include "util/string_array.h"

DEFINE_int32(vars, 3, "Number of variables");
DEFINE_int32(values, 5, "Number of values");
DEFINE_int32(slack, 1, "Slack in cardinalities");
DEFINE_int32(seed, 1, "Random seed");
DEFINE_int32(offset, 0, "Min value of variables");

namespace operations_research {
extern Constraint* MakeGcc(Solver* const solver,
                           const std::vector<IntVar*>& vars,
                           int64 first_domain_value,
                           const std::vector<int>& min_occurrences,
                           const std::vector<int>& max_occurrences);

extern Constraint* MakeSoftGcc(Solver* const solver,
                               const std::vector<IntVar*>& vars,
                               int64 min_value,
                               const std::vector<int>& card_mins,
                               const std::vector<int>& card_max,
                               IntVar* const violation_var);

static const char* kConstraintName[] = { "Distribute", "Gcc", "SoftGcc" };

int64 TestGcc(int num_vars,
              int num_values,
              int slack,
              int seed,
              int type,
              int offset) {
  ACMRandom rgen(seed); // defines a random generator

  std::vector<int> card_min(num_values, 0);
  std::vector<int> card_max(num_values, 0);
  for (int i = 0; i< num_vars - slack; ++i) {
    const int index = rgen.Uniform(num_values);
    card_min[index]++;
    card_max[index]++;
  }
  for (int i = 0; i < 2 * slack; ++i) {
    card_max[rgen.Uniform(num_values)]++;
  }

  LOG(INFO) << kConstraintName[type] << " constraint";
  // LOG(INFO) << "  - num variables = " << num_vars;
  // LOG(INFO) << "  - num values = " << num_values;
  // LOG(INFO) << "  - slack = " << slack;
  // LOG(INFO) << "  - seed = " << seed;
  // LOG(INFO) << "  - min_cards = [" << IntVectorToString(card_min, " ") << "]";
  // LOG(INFO) << "  - max_cards = [" << IntVectorToString(card_max, " ") << "]";

  Solver solver("TestGcc");
  std::vector<IntVar*> vars;
  solver.MakeIntVarArray(num_vars, offset, offset + num_values - 1, "v", &vars);
  switch (type) {
    case 0:
      solver.AddConstraint(solver.MakeDistribute(vars, card_min, card_max));
      break;
    case 1:
      solver.AddConstraint(MakeGcc(&solver, vars, 0, card_min, card_max));
      break;
    case 2:
      solver.AddConstraint(MakeSoftGcc(&solver,
                                       vars,
                                       0,
                                       card_min,
                                       card_max,
                                       solver.MakeIntConst(0)));
      break;
    default:
      LOG(FATAL) << "Constraint type not recognized";
  }
  DecisionBuilder* const db = solver.MakePhase(vars,
                                               Solver::CHOOSE_FIRST_UNBOUND,
                                               Solver::ASSIGN_MIN_VALUE);

  LOG(INFO) << "Start search";
  CycleTimer t;
  t.Start();
  solver.NewSearch(db);
  int counter = 0;
  while(solver.NextSolution()) {
    counter++;
  }
  solver.EndSearch();
  t.Stop();

  LOG(INFO) << "test time : " << t.GetInUsec() << " micro seconds";
  LOG(INFO) << "Found " << counter << " solutions";
  return counter;
}
}  // namespace operations_research

int main(int argc, char** argv) {
  google::ParseCommandLineFlags(&argc, &argv, true);
  const int dis = operations_research::TestGcc(FLAGS_vars,
                                               FLAGS_values,
                                               FLAGS_slack,
                                               FLAGS_seed,
                                               0,
                                               FLAGS_offset);
  const int gcc = operations_research::TestGcc(FLAGS_vars,
                                               FLAGS_values,
                                               FLAGS_slack,
                                               FLAGS_seed,
                                               1,
                                               FLAGS_offset);
  const int soft = operations_research::TestGcc(FLAGS_vars,
                                                FLAGS_values,
                                                FLAGS_slack,
                                                FLAGS_seed,
                                                2, FLAGS_offset);
  if (gcc != dis && gcc != soft && dis == soft) {
    LOG(INFO) << "Problem with vars = " << FLAGS_vars
              << ", and values = " << FLAGS_values
              << ", seed = " << FLAGS_seed
              << ", slack = " << FLAGS_slack;
  }
  return 0;
}
<commit_msg>fix gcc_test<commit_after>// Copyright 2011-2012 Google
// 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.

#include "base/hash.h"
#include "base/map-util.h"
#include "base/stl_util.h"
#include "base/random.h"
#include "constraint_solver/constraint_solveri.h"
#include "constraint_solver/constraint_solver.h"
#include "util/string_array.h"

DEFINE_int32(vars, 3, "Number of variables");
DEFINE_int32(values, 5, "Number of values");
DEFINE_int32(slack, 1, "Slack in cardinalities");
DEFINE_int32(seed, 1, "Random seed");
DEFINE_int32(offset, 0, "Min value of variables");

namespace operations_research {
extern Constraint* MakeGcc(Solver* const solver,
                           const std::vector<IntVar*>& vars,
                           int64 first_domain_value,
                           const std::vector<int>& min_occurrences,
                           const std::vector<int>& max_occurrences);

extern Constraint* MakeSoftGcc(Solver* const solver,
                               const std::vector<IntVar*>& vars,
                               int64 min_value,
                               const std::vector<int>& card_mins,
                               const std::vector<int>& card_max,
                               IntVar* const violation_var);

static const char* kConstraintName[] = { "Distribute", "Gcc", "SoftGcc" };

int64 TestGcc(int num_vars,
              int num_values,
              int slack,
              int seed,
              int type,
              int offset) {
  ACMRandom rgen(seed); // defines a random generator

  std::vector<int> card_min(num_values, 0);
  std::vector<int> card_max(num_values, 0);
  std::vector<int> values(num_values);
  for (int i = 0; i< num_vars - slack; ++i) {
    const int index = rgen.Uniform(num_values);
    card_min[index]++;
    card_max[index]++;
  }
  for (int i = 0; i < num_values; ++i) {
    values[i] = offset + i;
  }
  for (int i = 0; i < 2 * slack; ++i) {
    card_max[rgen.Uniform(num_values)]++;
  }

  LOG(INFO) << kConstraintName[type] << " constraint";
  // LOG(INFO) << "  - num variables = " << num_vars;
  // LOG(INFO) << "  - num values = " << num_values;
  // LOG(INFO) << "  - slack = " << slack;
  // LOG(INFO) << "  - seed = " << seed;
  // LOG(INFO) << "  - min_cards = [" << IntVectorToString(card_min, " ") << "]";
  // LOG(INFO) << "  - max_cards = [" << IntVectorToString(card_max, " ") << "]";

  Solver solver("TestGcc");
  std::vector<IntVar*> vars;
  solver.MakeIntVarArray(num_vars, offset, offset + num_values - 1, "v", &vars);
  switch (type) {
    case 0:
      solver.AddConstraint(
          solver.MakeDistribute(vars, values, card_min, card_max));
      break;
    case 1:
      solver.AddConstraint(MakeGcc(&solver, vars, offset, card_min, card_max));
      break;
    case 2:
      solver.AddConstraint(MakeSoftGcc(&solver,
                                       vars,
                                       offset,
                                       card_min,
                                       card_max,
                                       solver.MakeIntConst(0)));
      break;
    default:
      LOG(FATAL) << "Constraint type not recognized";
  }
  DecisionBuilder* const db = solver.MakePhase(vars,
                                               Solver::CHOOSE_FIRST_UNBOUND,
                                               Solver::ASSIGN_MIN_VALUE);

  LOG(INFO) << "Start search";
  CycleTimer t;
  t.Start();
  solver.NewSearch(db);
  int counter = 0;
  while(solver.NextSolution()) {
    counter++;
  }
  solver.EndSearch();
  t.Stop();

  LOG(INFO) << "test time : " << t.GetInUsec() << " micro seconds";
  LOG(INFO) << "Found " << counter << " solutions";
  return counter;
}
}  // namespace operations_research

int main(int argc, char** argv) {
  google::ParseCommandLineFlags(&argc, &argv, true);
  const int dis = operations_research::TestGcc(FLAGS_vars,
                                               FLAGS_values,
                                               FLAGS_slack,
                                               FLAGS_seed,
                                               0,
                                               FLAGS_offset);
  const int gcc = operations_research::TestGcc(FLAGS_vars,
                                               FLAGS_values,
                                               FLAGS_slack,
                                               FLAGS_seed,
                                               1,
                                               FLAGS_offset);
  const int soft = operations_research::TestGcc(FLAGS_vars,
                                                FLAGS_values,
                                                FLAGS_slack,
                                                FLAGS_seed,
                                                2, FLAGS_offset);
  if (gcc != dis && gcc != soft && dis == soft) {
    LOG(INFO) << "Problem with vars = " << FLAGS_vars
              << ", and values = " << FLAGS_values
              << ", seed = " << FLAGS_seed
              << ", slack = " << FLAGS_slack;
  }
  return 0;
}
<|endoftext|>


<commit_before>#include "store.h"

#include <QtGui/QGuiApplication>

Store::Store(QQuickItem* parent):QQuickItem(parent)
{
    _loaded = false;

    //_autoLoad = true;
    //_autoSave = true;

    _name = "";

    QString sub;

    if(QGuiApplication::organizationName() != "")
        sub += QGuiApplication::organizationName() + QDir::separator();
    if(QGuiApplication::organizationDomain() != "")
        sub += QGuiApplication::organizationDomain() + QDir::separator();
    if(QGuiApplication::applicationName() != "")
        sub += QGuiApplication::applicationName() + QDir::separator();
    #ifdef QAK_STORE_VERSION_PATH
    if(QGuiApplication::applicationVersion() != "")
        sub += QGuiApplication::applicationVersion() + QDir::separator() ;
    #endif
    if(sub == "") {
         qWarning() << "Store warning: Couldn't resolve" << sub << "for storing values. Using generic directory: \"Qak\"";
         sub = "Qak";
    }

    while(sub.endsWith( QDir::separator() )) sub.chop(1);

    _store_path = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)+QDir::separator()+sub;

    _ensureStorePath();
    #ifdef QT_DEBUG
    qDebug() << "Store using" << _store_path;
    #endif

    //qDebug() << "Setting objectName";
    //this->setObjectName(QString("Store"));

    QQuickItem *qi = new QQuickItem();

    // Run through all the properties
    // This is done to get a list of the QuickItems normal attributes which we don't want to save
    _blacklist.append("name");
    //_blacklist.append("autoLoad");
    //_blacklist.append("autoSave");
    _blacklist.append("isLoaded");
    const QMetaObject *metaobject = qi->metaObject();
    int count = metaobject->propertyCount();
    for (int i=0; i<count; ++i) {
        QMetaProperty metaproperty = metaobject->property(i);
        const char *name = metaproperty.name();
        _blacklist.append(name);
    }
    delete qi;
    qi = 0;
}
/*
Store::~Store()
{
    if( _autoSave ) {
        #ifdef QT_DEBUG
        qDebug() << "Store auto saving";
        #endif
        save();
    }
}
*/

QString Store::name()
{
    return _name;
}
/*
bool Store::autoLoad()
{
    return _autoLoad;
}

bool Store::autoSave()
{
    return _autoSave;
}
*/

bool Store::isLoaded()
{
    return _loaded;
}

void Store::setName(const QString &n)
{
    if (n != _name) {
        _name = n;
        emit nameChanged();
        /*
        if( _autoLoad ) {
            #ifdef QT_DEBUG
            qDebug() << "Store auto loading" << _name;
            #endif
            load();
        }
        */
    }
}
/*
void Store::setAutoLoad(const bool &v)
{
    if (v != _autoLoad) {
        _autoLoad = v;
        emit autoLoadChanged();
    }
}

void Store::setAutoSave(const bool &v)
{
    if (v != _autoSave) {
        _autoSave = v;
        emit autoSaveChanged();
    }
}
*/
void Store::save()
{
    if(_name == "")
    {
        qCritical() << "Store error: Property \"name\" not set";
        emit error("Store error: Property \"name\" not set");
        return;
    }

    _ensureStorePath();

    QString path = _store_path + QDir::separator() + _name;
    QJsonDocument json = QJsonDocument();
    QJsonObject rootItem = QJsonObject();

    emit saving();
    // Run through all the properties
    const QMetaObject *metaobject = this->metaObject();
    int count = metaobject->propertyCount();
    for (int i=0; i<count; ++i) {
        QMetaProperty metaproperty = metaobject->property(i);
        const char *name = metaproperty.name();

        bool blacklisted = false;
        for (int i = 0; i < _blacklist.size(); ++i) {
            //qDebug() << _quick_item_names.at(i).toLocal8Bit().constData();
            if(_blacklist.at(i).toLocal8Bit().constData() == QString(name))
                blacklisted = true;
        }

        if(!blacklisted) {
            QVariant value = this->property(name);

            #ifdef QT_DEBUG
            qDebug() << "Store" << _name << "property" << name << "stored" << value.typeName() << ":" << value;
            #endif

            QJsonValue jValue;
            jValue = jValue.fromVariant(value);
            rootItem.insert(name,jValue);
        }
    }
    json.setObject(rootItem);
    QByteArray bJson = json.toJson(QJsonDocument::Indented);
    QFile file(path);
    if(file.open(QIODevice::WriteOnly))
        file.write(bJson);
    else
        qWarning() << "Store" << _name << "warning: Couldn't save to" << path;
    file.close();

    //qDebug() << "Store saved" << bJson << "in" << path;
    emit saved();
}

void Store::load()
{
    if(_name == "")
    {
        qCritical() << "Store error: Property \"name\" not set";
        emit error("Store error: Property \"name\" not set");
        return;
    }

    QString path = _store_path + QDir::separator() + _name;

    QString bJson;
    QFile file;
    file.setFileName(path);
    if(file.exists())
    {
        file.open(QIODevice::ReadOnly | QIODevice::Text);
        bJson = file.readAll();
        file.close();
    }
    else
    {
        #ifdef QT_DEBUG
        qWarning() << "Store" << _name << "warning: Couldn't load" << path;
        #endif
        emit error("Could not load store from: \""+path+"\"");
        //_loaded = true;
        //emit isLoadedChanged();
        //emit loaded();
        return;
    }

    QJsonDocument json = QJsonDocument::fromJson(bJson.toUtf8());
    QJsonObject rootItem = json.object();

    // Run through all the properties
    const QMetaObject *metaobject = this->metaObject();
    int count = metaobject->propertyCount();
    for (int i=0; i<count; ++i) {
        QMetaProperty metaproperty = metaobject->property(i);
        const char *name = metaproperty.name();
        //QVariant value = this->property(name);
        bool blacklisted = false;
        for (int i = 0; i < _blacklist.size(); ++i) {
            //qDebug() << _quick_item_names.at(i).toLocal8Bit().constData();
            if(_blacklist.at(i).toLocal8Bit().constData() == QString(name))
                blacklisted = true;
        }

        if(!blacklisted) {
            QJsonValue value = rootItem.value(QString(name));

            if(value != QJsonValue::Undefined)
            {
                this->setProperty(name,value.toVariant());
                #ifdef QT_DEBUG
                qDebug() << "Store" << _name << "property" << name << "loaded" << value;
                #endif

            }
            else
                qWarning() << "Store" << _name << "warning: Property" << name << "not found";
        }
    }

    //qDebug() << "Store loaded" << bJson << "from" << path;
    _loaded = true;
    emit isLoadedChanged();
    emit loaded();
}

void Store::clear()
{
    if(_name == "")
    {
        qCritical() << "Store error: Property \"name\" not set";
        emit error("Property \"name\" not set");
        return;
    }

    QString path = _store_path + QDir::separator() + _name;
    bool result = QFile::remove(path);

    if(!result)
        emit error("Failed removing store directory "+path);
    #ifdef QT_DEBUG
    else
        qDebug() << "Store clear" << path << result;
    #endif

    emit cleared();
}

void Store::clear(const QString &name)
{
    if(name == "")
    {
        qCritical() << "Store error: Argument \"name\" not set";
        emit error("Argument \"name\" not set");
        return;
    }

    QString path = _store_path + QDir::separator() + name;
    bool result = QFile::remove(path);

    if(!result)
        emit error("Failed removing store directory "+path);
    #ifdef QT_DEBUG
    else
        qDebug() << "Store" << name << "clear" << path << result;
    #endif

    emit cleared();
}

void Store::clearAll()
{
    QDir dir(_store_path);
    if (dir.exists()) {
        dir.removeRecursively();

        #ifdef QT_DEBUG
        qDebug() << "Store clearAll" << _store_path;
        #endif

        emit cleared();
    }
}

void Store::_ensureStorePath()
{
    // TODO fix silent fail?
    // This function is used in object constructor where _name is not yet set
    if(_name == "")
        return;

    QDir dir(_store_path);
    if (!dir.exists()) {
        if(!dir.mkpath("."))
            emit error("Failed creating store directory "+_store_path);
        #ifdef QT_DEBUG
        else
            qDebug() << "Store created directory" << _store_path;
        #endif
    }

}
<commit_msg>Minor debug output fixes<commit_after>#include "store.h"

#include <QtGui/QGuiApplication>

Store::Store(QQuickItem* parent):QQuickItem(parent)
{
    _loaded = false;

    //_autoLoad = true;
    //_autoSave = true;

    _name = "";

    QString sub;

    if(QGuiApplication::organizationName() != "")
        sub += QGuiApplication::organizationName() + QDir::separator();
    if(QGuiApplication::organizationDomain() != "")
        sub += QGuiApplication::organizationDomain() + QDir::separator();
    if(QGuiApplication::applicationName() != "")
        sub += QGuiApplication::applicationName() + QDir::separator();
    #ifdef QAK_STORE_VERSION_PATH
    if(QGuiApplication::applicationVersion() != "")
        sub += QGuiApplication::applicationVersion() + QDir::separator() ;
    #endif
    if(sub == "") {
         qWarning() << "Store warning: Couldn't resolve" << sub << "for storing values. Using generic directory: \"Qak\"";
         sub = "Qak";
    }

    while(sub.endsWith( QDir::separator() )) sub.chop(1);

    _store_path = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)+QDir::separator()+sub;

    _ensureStorePath();
    #ifdef QT_DEBUG
    qDebug() << "Store using" << _store_path;
    #endif

    //qDebug() << "Setting objectName";
    //this->setObjectName(QString("Store"));

    QQuickItem *qi = new QQuickItem();

    // Run through all the properties
    // This is done to get a list of the QuickItems normal attributes which we don't want to save
    _blacklist.append("name");
    //_blacklist.append("autoLoad");
    //_blacklist.append("autoSave");
    _blacklist.append("isLoaded");
    const QMetaObject *metaobject = qi->metaObject();
    int count = metaobject->propertyCount();
    for (int i=0; i<count; ++i) {
        QMetaProperty metaproperty = metaobject->property(i);
        const char *name = metaproperty.name();
        _blacklist.append(name);
    }
    delete qi;
    qi = 0;
}
/*
Store::~Store()
{
    if( _autoSave ) {
        #ifdef QT_DEBUG
        qDebug() << "Store auto saving";
        #endif
        save();
    }
}
*/

QString Store::name()
{
    return _name;
}
/*
bool Store::autoLoad()
{
    return _autoLoad;
}

bool Store::autoSave()
{
    return _autoSave;
}
*/

bool Store::isLoaded()
{
    return _loaded;
}

void Store::setName(const QString &n)
{
    if (n != _name) {
        _name = n;
        emit nameChanged();
        /*
        if( _autoLoad ) {
            #ifdef QT_DEBUG
            qDebug() << "Store auto loading" << _name;
            #endif
            load();
        }
        */
    }
}
/*
void Store::setAutoLoad(const bool &v)
{
    if (v != _autoLoad) {
        _autoLoad = v;
        emit autoLoadChanged();
    }
}

void Store::setAutoSave(const bool &v)
{
    if (v != _autoSave) {
        _autoSave = v;
        emit autoSaveChanged();
    }
}
*/
void Store::save()
{
    if(_name == "")
    {
        qCritical() << "Store error: Property \"name\" not set";
        emit error("Store error: Property \"name\" not set");
        return;
    }

    _ensureStorePath();

    QString path = _store_path + QDir::separator() + _name;
    QJsonDocument json = QJsonDocument();
    QJsonObject rootItem = QJsonObject();

    emit saving();
    // Run through all the properties
    const QMetaObject *metaobject = this->metaObject();
    int count = metaobject->propertyCount();
    for (int i=0; i<count; ++i) {
        QMetaProperty metaproperty = metaobject->property(i);
        const char *name = metaproperty.name();

        bool blacklisted = false;
        for (int i = 0; i < _blacklist.size(); ++i) {
            //qDebug() << _quick_item_names.at(i).toLocal8Bit().constData();
            if(_blacklist.at(i).toLocal8Bit().constData() == QString(name))
                blacklisted = true;
        }

        if(!blacklisted) {
            QVariant value = this->property(name);

            #ifdef QT_DEBUG
            qDebug() << "Store" << _name << "property" << name << "stored" << value;
            #endif

            QJsonValue jValue;
            jValue = jValue.fromVariant(value);
            rootItem.insert(name,jValue);
        }
    }
    json.setObject(rootItem);
    QByteArray bJson = json.toJson(QJsonDocument::Indented);
    QFile file(path);
    if(file.open(QIODevice::WriteOnly))
        file.write(bJson);
    else
        qWarning() << "Store" << _name << "warning: Couldn't save to" << path;
    file.close();

    //qDebug() << "Store saved" << bJson << "in" << path;
    emit saved();
}

void Store::load()
{
    if(_name == "")
    {
        qCritical() << "Store error: Property \"name\" not set";
        emit error("Store error: Property \"name\" not set");
        return;
    }

    QString path = _store_path + QDir::separator() + _name;

    QString bJson;
    QFile file;
    file.setFileName(path);
    if(file.exists())
    {
        file.open(QIODevice::ReadOnly | QIODevice::Text);
        bJson = file.readAll();
        file.close();
    }
    else
    {
        #ifdef QT_DEBUG
        qWarning() << "Store" << _name << "warning: Couldn't load" << path;
        #endif
        emit error("Could not load store from: \""+path+"\"");
        //_loaded = true;
        //emit isLoadedChanged();
        //emit loaded();
        return;
    }

    QJsonDocument json = QJsonDocument::fromJson(bJson.toUtf8());
    QJsonObject rootItem = json.object();

    // Run through all the properties
    const QMetaObject *metaobject = this->metaObject();
    int count = metaobject->propertyCount();
    for (int i=0; i<count; ++i) {
        QMetaProperty metaproperty = metaobject->property(i);
        const char *name = metaproperty.name();
        //QVariant value = this->property(name);
        bool blacklisted = false;
        for (int i = 0; i < _blacklist.size(); ++i) {
            //qDebug() << _quick_item_names.at(i).toLocal8Bit().constData();
            if(_blacklist.at(i).toLocal8Bit().constData() == QString(name))
                blacklisted = true;
        }

        if(!blacklisted) {
            QJsonValue value = rootItem.value(QString(name));

            if(value != QJsonValue::Undefined)
            {
                this->setProperty(name,value.toVariant());
                #ifdef QT_DEBUG
                qDebug() << "Store" << _name << "property" << name << "loaded" << value;
                #endif

            }
            else
                qWarning() << "Store" << _name << "warning: Property" << name << "not found";
        }
    }

    //qDebug() << "Store loaded" << bJson << "from" << path;
    _loaded = true;
    emit isLoadedChanged();
    emit loaded();
}

void Store::clear()
{
    if(_name == "")
    {
        qCritical() << "Store error: Property \"name\" not set";
        emit error("Property \"name\" not set");
        return;
    }

    QString path = _store_path + QDir::separator() + _name;
    bool result = QFile::remove(path);

    if(!result)
        emit error("Failed removing store directory "+path);
    #ifdef QT_DEBUG
    else
        qDebug() << "Store clear" << path << result;
    #endif

    emit cleared();
}

void Store::clear(const QString &name)
{
    if(name == "")
    {
        qCritical() << "Store error: Argument \"name\" not set";
        emit error("Argument \"name\" not set");
        return;
    }

    QString path = _store_path + QDir::separator() + name;
    bool result = QFile::remove(path);

    if(!result)
        emit error("Failed removing store directory "+path);
    #ifdef QT_DEBUG
    else
        qDebug() << "Store" << name << "clear" << path << result;
    #endif

    emit cleared();
}

void Store::clearAll()
{
    QDir dir(_store_path);
    if (dir.exists()) {
        dir.removeRecursively();

        #ifdef QT_DEBUG
        qDebug() << "Store clearAll" << _store_path;
        #endif

        emit cleared();
    }
}

void Store::_ensureStorePath()
{
    // TODO fix silent fail?
    // This function is used in object constructor where _name is not yet set
    if(_name == "")
        return;

    QDir dir(_store_path);
    if (!dir.exists()) {
        if(!dir.mkpath("."))
            emit error("Failed creating store directory "+_store_path);
        #ifdef QT_DEBUG
        else
            qDebug() << "Store created directory" << _store_path;
        #endif
    }

}
<|endoftext|>


<commit_before>// Copyright (c) 2019 Franka Emika GmbH
// Use of this source code is governed by the Apache-2.0 license, see LICENSE
#include <iostream>
#include <thread>

#include <franka/exception.h>
#include <franka/vacuum_gripper.h>

/**
 * @example vacuum_object.cpp
 * An example showing how to control FRANKA's vacuum gripper.
 */

int main(int argc, char** argv) {
  if (argc != 2) {
    std::cerr << "Usage: ./vacuum_object <vacuum-gripper-hostname>" << std::endl;
    return -1;
  }

  try {
    franka::VacuumGripper vacuum_gripper(argv[1]);

    // Print a vacuum gripper state.
    franka::VacuumGripperState vacuum_gripper_state = vacuum_gripper.readOnce();
    std::cout << "Initial vacuum gripper state: " << vacuum_gripper_state << std::endl;

    // Vacuum the object.
    if (!vacuum_gripper.vacuum(100, std::chrono::milliseconds(1000))) {
      std::cout << "Failed to vacuum the object." << std::endl;
      return -1;
    }

    vacuum_gripper_state = vacuum_gripper.readOnce();
    std::cout << "Vacuum gripper state after applying vacuum: " << vacuum_gripper_state
              << std::endl;

    // Wait 3s and check afterwards, if the object is still grasped.
    std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(3000));

    vacuum_gripper_state = vacuum_gripper.readOnce();
    if (!vacuum_gripper_state.in_control_range) {
      std::cout << "Object lost." << std::endl;
      return -1;
    }

    std::cout << "Vacuumed object, will release it now." << std::endl;
    vacuum_gripper.dropOff(std::chrono::milliseconds(1000));
  } catch (franka::Exception const& e) {
    std::cout << e.what() << std::endl;
    return -1;
  }

  return 0;
}
<commit_msg>Improve vacuum object example.<commit_after>// Copyright (c) 2019 Franka Emika GmbH
// Use of this source code is governed by the Apache-2.0 license, see LICENSE
#include <iostream>
#include <thread>

#include <franka/exception.h>
#include <franka/vacuum_gripper.h>

/**
 * @example vacuum_object.cpp
 * An example showing how to control FRANKA's vacuum gripper.
 */

int main(int argc, char** argv) {
  if (argc != 2) {
    std::cerr << "Usage: ./vacuum_object <vacuum-gripper-hostname>" << std::endl;
    return -1;
  }

  franka::VacuumGripper vacuum_gripper(argv[1]);
  try {
    // Print a vacuum gripper state.
    franka::VacuumGripperState vacuum_gripper_state = vacuum_gripper.readOnce();
    std::cout << "Initial vacuum gripper state: " << vacuum_gripper_state << std::endl;

    // Vacuum the object.
    if (!vacuum_gripper.vacuum(100, std::chrono::milliseconds(1000))) {
      std::cout << "Failed to vacuum the object." << std::endl;
      return -1;
    }

    vacuum_gripper_state = vacuum_gripper.readOnce();
    std::cout << "Vacuum gripper state after applying vacuum: " << vacuum_gripper_state
              << std::endl;

    // Wait 3s and check afterwards, if the object is still grasped.
    std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(3000));

    vacuum_gripper_state = vacuum_gripper.readOnce();
    if (!vacuum_gripper_state.in_control_range) {
      std::cout << "Object lost." << std::endl;
      return -1;
    }

    std::cout << "Vacuumed object, will release it now." << std::endl;
    vacuum_gripper.dropOff(std::chrono::milliseconds(1000));
  } catch (franka::Exception const& e) {
    vacuum_gripper.stop();
    std::cout << e.what() << std::endl;
    return -1;
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cctype>
#include <chrono>
#include <list>
#include <string.h>

#include "core/Halite.hpp"

bool quiet_output = false, ignore_timeout = false; //Need to be passed to the game.
Halite * my_game; //Is a pointer to avoid problems with assignment, dynamic memory, and default constructors.

Networking promptNetworking();
void promptDimensions(unsigned short & w, unsigned short & h);

int main(int argc, char* args[]) {
	srand(time(NULL)); //For all non-seeded randomness.

	bool watch_game = false, override_names = false; //Extra parameters.

	//Paramters to start up a game.
	bool passed_dimensions = false, passed_seed = false, passed_bot_names = false;
	unsigned short mapWidth, mapHeight;
	unsigned int seed = (std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count() % 4294967295); //Using microseconds to prevent same maps from coming up due to multiple worker servers.
	Networking networking;
	std::vector<std::string> * names = NULL;

	std::list<std::string> sArgs;
	for(int a = 1; a < argc; a++) sArgs.push_back(args[a]);

	for(auto a = sArgs.begin(); a != sArgs.end();) {
		if(*a == "-d") {
			passed_dimensions = true;
			a = sArgs.erase(a);
			try {
				if(a == sArgs.end()) throw 0;
				mapWidth = std::stoll(*a);
				a = sArgs.erase(a);
				if(a == sArgs.end()) throw 0;
				mapHeight = std::stoll(*a);
				a = sArgs.erase(a);
			}
			catch(...) {
				std::cout << "The dimension parameters were either not present or invalid despite the flag having been given." << std::endl;
				return EXIT_FAILURE;
			}
		}
		else if(*a == "-w") {
			watch_game = true;
			a = sArgs.erase(a);
		}
		else if(*a == "-q") {
			quiet_output = true;
			a = sArgs.erase(a);
		}
		else if(*a == "-o") {
			override_names = true;
			a = sArgs.erase(a);
		}
		else if(*a == "-s") {
			passed_seed = true;
			a = sArgs.erase(a);
			try {
				if(a == sArgs.end()) throw 0;
				seed = std::stoll(*a);
				a = sArgs.erase(a);
			}
			catch(...) {
				std::cout << "The seed parameter was either not present or invalid despite the flag having been given." << std::endl;
				return EXIT_FAILURE;
			}
		}
		else if(*a == "-t") {
			ignore_timeout = true;
			a = sArgs.erase(a);
		}
		else a++;
	}

	if(!passed_dimensions) {
		promptDimensions(mapWidth, mapHeight);
	}

	if(override_names) {
		if(sArgs.size() < 4 || sArgs.size() % 2 != 0) {
			std::cout << "Invalid player parameters from args. Prompting instead (override disabled):" << std::endl;
			networking = promptNetworking();
		}
		try {
			names = new std::vector<std::string>();
			while(!sArgs.empty()) {
				networking.startAndConnectBot(sArgs.front());
				sArgs.pop_front();
				names->push_back(sArgs.front());
				sArgs.pop_front();
			}
		}
		catch(...) {
			std::cout << "Invalid player parameters from args. Prompting instead (override disabled):" << std::endl;
			networking = promptNetworking();
		}
	}
	else {
		if(sArgs.size() < 2) {
			std::cout << "Invalid player parameters from args. Prompting instead:" << std::endl;
			networking = promptNetworking();
		}
		try {
			while(!sArgs.empty()) {
				std::cout << sArgs.front() << std::endl;
				networking.startAndConnectBot(sArgs.front());
				sArgs.pop_front();
			}
		}
		catch(...) {
			std::cout << "Invalid player parameters from args. Prompting instead:" << std::endl;
			networking = promptNetworking();
		}
	}

	//Create game. Null parameters will be ignored.
	my_game = new Halite(mapWidth, mapHeight, seed, networking, names);

	std::string filename = "Replays/" + std::to_string(seed) + '-' + std::to_string(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock().now().time_since_epoch()).count()) + ".hlt";

	GameStatistics stats = my_game->runGame();

	try{
		my_game->output(filename);
	}
	catch(std::runtime_error & e) {
		filename = filename.substr(8);
		if(!quiet_output) {
			std::cout << "Map seed is " << seed << std::endl << "Opening a file at " << filename << std::endl;
		}
		my_game->output(filename);
	}

	std::string victoryOut;
	if(quiet_output) {
		std::cout << filename << ' ' << seed << std::endl << stats;
	}
	else {
		for(unsigned int a = 0; a < stats.player_statistics.size(); a++) std::cout << "Player #" << stats.player_statistics[a].tag << ", " << my_game->getName(stats.player_statistics[a].tag) << ", came in rank #" << stats.player_statistics[a].rank << "!\n";
	}

	delete my_game;

	if(watch_game) {
#ifdef _WIN32
		std::string command = ".\\visualizer " + filename;
#else
		std::string command = "./visualizer " + filename;
#endif
		system(command.c_str());
	}

	return 0;
}

Networking promptNetworking() {
	Networking n;
	std::string in;
	bool done = false;
	for(int np = 0; !done; np++) {
		//If less than 2, bypass this step: Ask if the user like to add another AI
		if (np >= 2) {
			std::cout << "Would you like to add another player? Please enter Yes or No: ";
			while (true) {
				std::getline(std::cin, in);
				std::transform(in.begin(), in.end(), in.begin(), ::tolower);
				if (in == "n" || in == "no" || in == "nope" || in == "y" || in == "yes" || in == "yep") break;
				std::cout << "That isn't a valid input. Please enter Yes or No: ";
			}
			if (in == "n" || in == "no" || in == "nope") break;
		}

		while (true) {
			std::string startCommand;
			std::cout << "What is the start command for this bot: ";
			std::getline(std::cin, startCommand);

			try{
				n.startAndConnectBot(startCommand);
				break;
			}
			catch (int e) {
				std::cout << "There was a problem with that start command. Please enter another one.\n";
			}
		}

		std::cout << "Connected to player #" << int(np + 1) << std::endl;
	}
	return n;
}

void promptDimensions(unsigned short & w, unsigned short & h) {
	std::string in;
	std::cout << "Please enter the width of the map: ";
	std::getline(std::cin, in);
	while(true) {
		try{
			w = std::stoi(in);
			break;
		}
		catch(std::exception e) {
			std::cout << "That isn't a valid input. Please enter a positive integer width of the map: ";
			std::getline(std::cin, in);
		}
	}
	std::cout << "Please enter the height of the map: ";
	std::getline(std::cin, in);
	while(true) {
		try{
			h = std::stoi(in);
			break;
		}
		catch(std::exception e) {
			std::cout << "That isn't a valid input. Please enter a positive integer height of the map: ";
			std::getline(std::cin, in);
		}
	}
}<commit_msg>Changed args to argv for consistency<commit_after>#include <iostream>
#include <cctype>
#include <chrono>
#include <list>
#include <string.h>

#include "core/Halite.hpp"

bool quiet_output = false, ignore_timeout = false; //Need to be passed to the game.
Halite * my_game; //Is a pointer to avoid problems with assignment, dynamic memory, and default constructors.

Networking promptNetworking();
void promptDimensions(unsigned short & w, unsigned short & h);

int main(int argc, char ** argv) {
	srand(time(NULL)); //For all non-seeded randomness.

	bool watch_game = false, override_names = false; //Extra parameters.

	//Paramters to start up a game.
	bool passed_dimensions = false, passed_seed = false, passed_bot_names = false;
	unsigned short mapWidth, mapHeight;
	unsigned int seed = (std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count() % 4294967295); //Using microseconds to prevent same maps from coming up due to multiple worker servers.
	Networking networking;
	std::vector<std::string> * names = NULL;

	std::list<std::string> sArgs;
	for(int a = 1; a < argc; a++) sArgs.push_back(argv[a]);

	for(auto a = sArgs.begin(); a != sArgs.end();) {
		if(*a == "-d") {
			passed_dimensions = true;
			a = sArgs.erase(a);
			try {
				if(a == sArgs.end()) throw 0;
				mapWidth = std::stoll(*a);
				a = sArgs.erase(a);
				if(a == sArgs.end()) throw 0;
				mapHeight = std::stoll(*a);
				a = sArgs.erase(a);
			}
			catch(...) {
				std::cout << "The dimension parameters were either not present or invalid despite the flag having been given." << std::endl;
				return EXIT_FAILURE;
			}
		}
		else if(*a == "-w") {
			watch_game = true;
			a = sArgs.erase(a);
		}
		else if(*a == "-q") {
			quiet_output = true;
			a = sArgs.erase(a);
		}
		else if(*a == "-o") {
			override_names = true;
			a = sArgs.erase(a);
		}
		else if(*a == "-s") {
			passed_seed = true;
			a = sArgs.erase(a);
			try {
				if(a == sArgs.end()) throw 0;
				seed = std::stoll(*a);
				a = sArgs.erase(a);
			}
			catch(...) {
				std::cout << "The seed parameter was either not present or invalid despite the flag having been given." << std::endl;
				return EXIT_FAILURE;
			}
		}
		else if(*a == "-t") {
			ignore_timeout = true;
			a = sArgs.erase(a);
		}
		else a++;
	}

	if(!passed_dimensions) {
		promptDimensions(mapWidth, mapHeight);
	}

	if(override_names) {
		if(sArgs.size() < 4 || sArgs.size() % 2 != 0) {
			std::cout << "Invalid player parameters from argv. Prompting instead (override disabled):" << std::endl;
			networking = promptNetworking();
		}
		try {
			names = new std::vector<std::string>();
			while(!sArgs.empty()) {
				networking.startAndConnectBot(sArgs.front());
				sArgs.pop_front();
				names->push_back(sArgs.front());
				sArgs.pop_front();
			}
		}
		catch(...) {
			std::cout << "Invalid player parameters from argv. Prompting instead (override disabled):" << std::endl;
			networking = promptNetworking();
		}
	}
	else {
		if(sArgs.size() < 2) {
			std::cout << "Invalid player parameters from argv. Prompting instead:" << std::endl;
			networking = promptNetworking();
		}
		try {
			while(!sArgs.empty()) {
				std::cout << sArgs.front() << std::endl;
				networking.startAndConnectBot(sArgs.front());
				sArgs.pop_front();
			}
		}
		catch(...) {
			std::cout << "Invalid player parameters from argv. Prompting instead:" << std::endl;
			networking = promptNetworking();
		}
	}

	//Create game. Null parameters will be ignored.
	my_game = new Halite(mapWidth, mapHeight, seed, networking, names);

	std::string filename = "Replays/" + std::to_string(seed) + '-' + std::to_string(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock().now().time_since_epoch()).count()) + ".hlt";

	GameStatistics stats = my_game->runGame();

	try{
		my_game->output(filename);
	}
	catch(std::runtime_error & e) {
		filename = filename.substr(8);
		if(!quiet_output) {
			std::cout << "Map seed is " << seed << std::endl << "Opening a file at " << filename << std::endl;
		}
		my_game->output(filename);
	}

	std::string victoryOut;
	if(quiet_output) {
		std::cout << filename << ' ' << seed << std::endl << stats;
	}
	else {
		for(unsigned int a = 0; a < stats.player_statistics.size(); a++) std::cout << "Player #" << stats.player_statistics[a].tag << ", " << my_game->getName(stats.player_statistics[a].tag) << ", came in rank #" << stats.player_statistics[a].rank << "!\n";
	}

	delete my_game;

	if(watch_game) {
#ifdef _WIN32
		std::string command = ".\\visualizer " + filename;
#else
		std::string command = "./visualizer " + filename;
#endif
		system(command.c_str());
	}

	return 0;
}

Networking promptNetworking() {
	Networking n;
	std::string in;
	bool done = false;
	for(int np = 0; !done; np++) {
		//If less than 2, bypass this step: Ask if the user like to add another AI
		if (np >= 2) {
			std::cout << "Would you like to add another player? Please enter Yes or No: ";
			while (true) {
				std::getline(std::cin, in);
				std::transform(in.begin(), in.end(), in.begin(), ::tolower);
				if (in == "n" || in == "no" || in == "nope" || in == "y" || in == "yes" || in == "yep") break;
				std::cout << "That isn't a valid input. Please enter Yes or No: ";
			}
			if (in == "n" || in == "no" || in == "nope") break;
		}

		while (true) {
			std::string startCommand;
			std::cout << "What is the start command for this bot: ";
			std::getline(std::cin, startCommand);

			try{
				n.startAndConnectBot(startCommand);
				break;
			}
			catch (int e) {
				std::cout << "There was a problem with that start command. Please enter another one.\n";
			}
		}

		std::cout << "Connected to player #" << int(np + 1) << std::endl;
	}
	return n;
}

void promptDimensions(unsigned short & w, unsigned short & h) {
	std::string in;
	std::cout << "Please enter the width of the map: ";
	std::getline(std::cin, in);
	while(true) {
		try{
			w = std::stoi(in);
			break;
		}
		catch(std::exception e) {
			std::cout << "That isn't a valid input. Please enter a positive integer width of the map: ";
			std::getline(std::cin, in);
		}
	}
	std::cout << "Please enter the height of the map: ";
	std::getline(std::cin, in);
	while(true) {
		try{
			h = std::stoi(in);
			break;
		}
		catch(std::exception e) {
			std::cout << "That isn't a valid input. Please enter a positive integer height of the map: ";
			std::getline(std::cin, in);
		}
	}
}<|endoftext|>


<commit_before>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <iostream>
#include <boost/config.hpp>
#include <fcntl.h>
#include <stdio.h>

int test_main();

extern bool tests_failure;

#include "libtorrent/assert.hpp"
#include <signal.h>

void sig_handler(int sig)
{
	char stack_text[10000];
	print_backtrace(stack_text, sizeof(stack_text), 30);
	char const* sig_name = 0;
	switch (sig)
	{
#define SIG(x) case x: sig_name = #x; break
		SIG(SIGSEGV);
		SIG(SIGBUS);
		SIG(SIGILL);
		SIG(SIGABRT);
		SIG(SIGFPE);
		SIG(SIGSYS);
#undef SIG
	};
	fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text);
	exit(138);
}

int main()
{
#ifdef O_NONBLOCK
	// on darwin, stdout is set to non-blocking mode by default
	// which sometimes causes tests to fail with EAGAIN just
	// by printing logs
	int flags = fcntl(fileno(stdout), F_GETFL, 0);
	fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK);
	flags = fcntl(fileno(stderr), F_GETFL, 0);
	fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK);
#endif

	signal(SIGSEGV, &sig_handler);
	signal(SIGBUS, &sig_handler);
	signal(SIGILL, &sig_handler);
	signal(SIGABRT, &sig_handler);
	signal(SIGFPE, &sig_handler);
	signal(SIGSYS, &sig_handler);

#ifndef BOOST_NO_EXCEPTIONS
	try
	{
#endif
		test_main();
#ifndef BOOST_NO_EXCEPTIONS
	}
	catch (std::exception const& e)
	{
		std::cerr << "Terminated with exception: \"" << e.what() << "\"\n";
		tests_failure = true;
	}
	catch (...)
	{
		std::cerr << "Terminated with unknown exception\n";
		tests_failure = true;
	}
#endif
	fflush(stdout);
	fflush(stderr);
	return tests_failure ? 1 : 0;
}

<commit_msg>fix windows unit test build<commit_after>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <iostream>
#include <boost/config.hpp>
#include <fcntl.h>
#include <stdio.h>

int test_main();

extern bool tests_failure;

#include "libtorrent/assert.hpp"
#include <signal.h>

void sig_handler(int sig)
{
	char stack_text[10000];
	print_backtrace(stack_text, sizeof(stack_text), 30);
	char const* sig_name = 0;
	switch (sig)
	{
#define SIG(x) case x: sig_name = #x; break
		SIG(SIGSEGV);
#ifdef SIGBUS
		SIG(SIGBUS);
#endif
		SIG(SIGILL);
		SIG(SIGABRT);
		SIG(SIGFPE);
#ifdef SIGSYS
		SIG(SIGSYS);
#endif
#undef SIG
	};
	fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text);
	exit(138);
}

int main()
{
#ifdef O_NONBLOCK
	// on darwin, stdout is set to non-blocking mode by default
	// which sometimes causes tests to fail with EAGAIN just
	// by printing logs
	int flags = fcntl(fileno(stdout), F_GETFL, 0);
	fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK);
	flags = fcntl(fileno(stderr), F_GETFL, 0);
	fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK);
#endif

	signal(SIGSEGV, &sig_handler);
#ifdef SIGBUS
	signal(SIGBUS, &sig_handler);
#endif
	signal(SIGILL, &sig_handler);
	signal(SIGABRT, &sig_handler);
	signal(SIGFPE, &sig_handler);
#ifdef SIGSYS
	signal(SIGSYS, &sig_handler);
#endif

#ifndef BOOST_NO_EXCEPTIONS
	try
	{
#endif
		test_main();
#ifndef BOOST_NO_EXCEPTIONS
	}
	catch (std::exception const& e)
	{
		std::cerr << "Terminated with exception: \"" << e.what() << "\"\n";
		tests_failure = true;
	}
	catch (...)
	{
		std::cerr << "Terminated with unknown exception\n";
		tests_failure = true;
	}
#endif
	fflush(stdout);
	fflush(stderr);
	return tests_failure ? 1 : 0;
}

<|endoftext|>