<commit_before>//      Command.cpp
//

#include <vector>
#include <string>
#include "CommandAbstract.h"
#include "CommandFactory.h"
#include "Command.h"

CommandAbstract* CommandFactory::create(Player* &player, std::vector <std::string> commandFull)
{
    std::string cmd = commandFull[0];
    commandFull.erase(commandFull.begin());

    CommandAbstract* command;

    if (cmd.compare("talk") == 0) {
        if (!player->isConnected() || !player->connect()) {
            throw "A player must be connected to launch the command talk";
        }
        command = new CommandTalk();
    }
    else {
        return NULL;
    }

    command->setArgs(commandFull);
    command->setPlayer(player);
    return command;
}
<commit_msg>include removed<commit_after>//      Command.cpp
//

#include <vector>
#include <string>
#include "CommandFactory.h"
#include "Command.h"

CommandAbstract* CommandFactory::create(Player* &player, std::vector <std::string> commandFull)
{
    std::string cmd = commandFull[0];
    commandFull.erase(commandFull.begin());

    CommandAbstract* command;

    if (cmd.compare("talk") == 0) {
        if (!player->isConnected() || !player->connect()) {
            throw "A player must be connected to launch the command talk";
        }
        command = new CommandTalk();
    }
    else {
        return NULL;
    }

    command->setArgs(commandFull);
    command->setPlayer(player);
    return command;
}
<|endoftext|>


<commit_before>#include "TestUtils/ResponseUtils.h"
#include "gtest/gtest.h"

#include <Managers/GameAgent.h>
#include <Managers/GameInterface.h>
#include <Tasks/BasicTasks/Combat.h>
#include <Tasks/BasicTasks/Draw.h>
#include <Tasks/BasicTasks/PlayCard.h>

#include <future>

using namespace Hearthstonepp;

TEST(BasicCard, EX1_066)
{
    GameAgent agent(
        Player(new Account("Player 1", ""), new Deck("", CardClass::WARRIOR)),
        Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE)));

    TaskAgent& taskAgent = agent.GetTaskAgent();
    TestUtils::AutoResponder response(agent);

    Player& player1 = agent.GetPlayer1();
    Player& player2 = agent.GetPlayer2();

    player1.totalMana = player1.existMana = 10;
    player2.totalMana = player2.existMana = 10;

    agent.RunTask(BasicTasks::DrawCardTask(
                      Cards::GetInstance()->FindCardByName("Fiery War Axe")),
                  player1, player2);
    EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(1));
    EXPECT_EQ(agent.GetPlayer1().hand[0]->card->name, "Fiery War Axe");

    agent.RunTask(BasicTasks::DrawCardTask(Cards::GetInstance()->FindCardByName(
                      "Acidic Swamp Ooze")),
                  player2, player1);
    EXPECT_EQ(agent.GetPlayer2().hand.size(), static_cast<size_t>(1));
    EXPECT_EQ(agent.GetPlayer2().hand[0]->card->name, "Acidic Swamp Ooze");

    // Create response for GameAgent to run PlayCardTask
    auto respPlayCard1 = response.PlayCard(0);
    MetaData result =
        agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player1, player2);
    EXPECT_EQ(result, MetaData::PLAY_WEAPON_SUCCESS);
    EXPECT_NE(agent.GetPlayer1().hero->weapon, nullptr);

    TaskMeta reqPlayCard1 = respPlayCard1.get();
    EXPECT_EQ(reqPlayCard1.id, +TaskID::REQUIRE);
    auto require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(reqPlayCard1);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_CARD);

    // Create multiple response for PlayCardTask And PlayMinionTask
    auto respAutoMinion = response.AutoMinion(0, 0);
    result =
        agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player2, player1);
    EXPECT_EQ(result, MetaData::PLAY_MINION_SUCCESS);
    EXPECT_EQ(agent.GetPlayer1().hero->weapon, nullptr);

    auto[respPlayCard2, respPlayMinion] = respAutoMinion.get();
    require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayCard2);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_CARD);

    require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayMinion);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_POSITION);
}

TEST(BasicCard, CS2_041)
{
    GameAgent agent(
        Player(new Account("Player 1", ""), new Deck("", CardClass::SHAMAN)),
        Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE)));

    TaskAgent& taskAgent = agent.GetTaskAgent();
    TestUtils::AutoResponder response(agent);

    Player& player1 = agent.GetPlayer1();
    Player& player2 = agent.GetPlayer2();

    player1.totalMana = agent.GetPlayer1().existMana = 10;
    player2.totalMana = agent.GetPlayer2().existMana = 10;

    agent.RunTask(BasicTasks::DrawCardTask(Cards::GetInstance()->FindCardByName(
                      "Acidic Swamp Ooze")),
                  player1, player2);
    EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(1));
    EXPECT_EQ(agent.GetPlayer1().hand[0]->card->name, "Acidic Swamp Ooze");

    agent.RunTask(BasicTasks::DrawCardTask(Cards::GetInstance()->FindCardByName(
                      "Ancestral Healing")),
                  player1, player2);
    EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(2));
    EXPECT_EQ(agent.GetPlayer1().hand[1]->card->name, "Ancestral Healing");

    agent.RunTask(BasicTasks::DrawCardTask(
                      Cards::GetInstance()->FindCardByName("Stonetusk Boar")),
                  player2, player1);
    EXPECT_EQ(agent.GetPlayer2().hand.size(), static_cast<size_t>(1));
    EXPECT_EQ(agent.GetPlayer2().hand[0]->card->name, "Stonetusk Boar");

    // Create multiple response for PlayCardTask And PlayMinionTask
    auto respAutoMinion = response.AutoMinion(0, 0);
    MetaData result =
        agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player1, player2);
    EXPECT_EQ(result, MetaData::PLAY_MINION_SUCCESS);
    EXPECT_EQ(agent.GetPlayer1().field[0]->card->name, "Acidic Swamp Ooze");

    auto[respPlayCard1, respPlayMinion1] = respAutoMinion.get();
    auto require =
        TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayCard1);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_CARD);

    require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayMinion1);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_POSITION);

    // Create multiple response for PlayCardTask And PlayMinionTask
    respAutoMinion = response.AutoMinion(0, 0);
    result =
        agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player2, player1);
    EXPECT_EQ(result, MetaData::PLAY_MINION_SUCCESS);
    EXPECT_EQ(agent.GetPlayer2().field[0]->card->name, "Stonetusk Boar");

    auto[respPlayCard2, respPlayMinion2] = respAutoMinion.get();
    require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayCard2);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_CARD);

    require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayMinion2);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_POSITION);

    auto respAutoTarget = response.Target(1, 1);
    result = agent.RunTask(BasicTasks::CombatTask(taskAgent), player2, player1);
    EXPECT_EQ(result, MetaData::COMBAT_SUCCESS);
    EXPECT_EQ(agent.GetPlayer1().field[0]->health, 1);
    EXPECT_EQ(agent.GetPlayer2().field[0], nullptr);

    // Create multiple response for PlayCardTask And PlaySpellTask
    //auto respAutoSpell = response.AutoSpell(0, 0);
    //result =
    //    agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player1, player2);
    //EXPECT_EQ(result, MetaData::PLAY_SPELL_SUCCESS);

    //auto[respPlayCard3, respPlaySpell] = respAutoSpell.get();
    //require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayCard3);
    //EXPECT_EQ(TaskID::_from_integral(require->required()),
    //          +TaskID::SELECT_CARD);

    //require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlaySpell);
    //EXPECT_EQ(TaskID::_from_integral(require->required()),
    //          +TaskID::SELECT_POSITION);

    //
    //    agent.Process(agent.GetPlayer1(), BasicTask::PlayCardTask(0, 0));
    //    auto minion =
    //    dynamic_cast<Character*>(agent.GetPlayer1().field.at(0));
    //    minion->health -= 1;
    //    EXPECT_EQ(minion->health, 1u);
    //
    //    agent.Process(agent.GetPlayer1(),
    //                  BasicTask::PlayCardTask(0, -1, TargetType::MY_FIELD,
    //                  1));
    //    EXPECT_EQ(static_cast<bool>(minion->gameTags[GameTag::TAUNT]), true);
    //    EXPECT_EQ(minion->health, 2);
}
<commit_msg>[ci skip] Add test code for CS2_041<commit_after>#include "TestUtils/ResponseUtils.h"
#include "gtest/gtest.h"

#include <Managers/GameAgent.h>
#include <Managers/GameInterface.h>
#include <Tasks/BasicTasks/Combat.h>
#include <Tasks/BasicTasks/Draw.h>
#include <Tasks/BasicTasks/PlayCard.h>

#include <future>

using namespace Hearthstonepp;

TEST(BasicCard, EX1_066)
{
    GameAgent agent(
        Player(new Account("Player 1", ""), new Deck("", CardClass::WARRIOR)),
        Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE)));

    TaskAgent& taskAgent = agent.GetTaskAgent();
    TestUtils::AutoResponder response(agent);

    Player& player1 = agent.GetPlayer1();
    Player& player2 = agent.GetPlayer2();

    player1.totalMana = player1.existMana = 10;
    player2.totalMana = player2.existMana = 10;

    agent.RunTask(BasicTasks::DrawCardTask(
                      Cards::GetInstance()->FindCardByName("Fiery War Axe")),
                  player1, player2);
    EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(1));
    EXPECT_EQ(agent.GetPlayer1().hand[0]->card->name, "Fiery War Axe");

    agent.RunTask(BasicTasks::DrawCardTask(Cards::GetInstance()->FindCardByName(
                      "Acidic Swamp Ooze")),
                  player2, player1);
    EXPECT_EQ(agent.GetPlayer2().hand.size(), static_cast<size_t>(1));
    EXPECT_EQ(agent.GetPlayer2().hand[0]->card->name, "Acidic Swamp Ooze");

    // Create response for GameAgent to run PlayCardTask
    auto respPlayCard1 = response.PlayCard(0);
    MetaData result =
        agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player1, player2);
    EXPECT_EQ(result, MetaData::PLAY_WEAPON_SUCCESS);
    EXPECT_NE(agent.GetPlayer1().hero->weapon, nullptr);

    TaskMeta reqPlayCard1 = respPlayCard1.get();
    EXPECT_EQ(reqPlayCard1.id, +TaskID::REQUIRE);
    auto require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(reqPlayCard1);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_CARD);

    // Create multiple response for PlayCardTask And PlayMinionTask
    auto respAutoMinion = response.AutoMinion(0, 0);
    result =
        agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player2, player1);
    EXPECT_EQ(result, MetaData::PLAY_MINION_SUCCESS);
    EXPECT_EQ(agent.GetPlayer1().hero->weapon, nullptr);

    auto[respPlayCard2, respPlayMinion] = respAutoMinion.get();
    require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayCard2);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_CARD);

    require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayMinion);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_POSITION);
}

TEST(BasicCard, CS2_041)
{
    GameAgent agent(
        Player(new Account("Player 1", ""), new Deck("", CardClass::SHAMAN)),
        Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE)));

    TaskAgent& taskAgent = agent.GetTaskAgent();
    TestUtils::AutoResponder response(agent);

    Player& player1 = agent.GetPlayer1();
    Player& player2 = agent.GetPlayer2();

    player1.totalMana = agent.GetPlayer1().existMana = 10;
    player2.totalMana = agent.GetPlayer2().existMana = 10;

    agent.RunTask(BasicTasks::DrawCardTask(Cards::GetInstance()->FindCardByName(
                      "Acidic Swamp Ooze")),
                  player1, player2);
    EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(1));
    EXPECT_EQ(agent.GetPlayer1().hand[0]->card->name, "Acidic Swamp Ooze");

    agent.RunTask(BasicTasks::DrawCardTask(Cards::GetInstance()->FindCardByName(
                      "Ancestral Healing")),
                  player1, player2);
    EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(2));
    EXPECT_EQ(agent.GetPlayer1().hand[1]->card->name, "Ancestral Healing");

    agent.RunTask(BasicTasks::DrawCardTask(
                      Cards::GetInstance()->FindCardByName("Stonetusk Boar")),
                  player2, player1);
    EXPECT_EQ(agent.GetPlayer2().hand.size(), static_cast<size_t>(1));
    EXPECT_EQ(agent.GetPlayer2().hand[0]->card->name, "Stonetusk Boar");

    // Create multiple response for PlayCardTask And PlayMinionTask
    auto respAutoMinion = response.AutoMinion(0, 0);
    MetaData result =
        agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player1, player2);
    EXPECT_EQ(result, MetaData::PLAY_MINION_SUCCESS);
    EXPECT_EQ(agent.GetPlayer1().field[0]->card->name, "Acidic Swamp Ooze");

    auto[respPlayCard1, respPlayMinion1] = respAutoMinion.get();
    auto require =
        TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayCard1);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_CARD);

    require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayMinion1);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_POSITION);

    // Create multiple response for PlayCardTask And PlayMinionTask
    respAutoMinion = response.AutoMinion(0, 0);
    result =
        agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player2, player1);
    EXPECT_EQ(result, MetaData::PLAY_MINION_SUCCESS);
    EXPECT_EQ(agent.GetPlayer2().field[0]->card->name, "Stonetusk Boar");

    auto[respPlayCard2, respPlayMinion2] = respAutoMinion.get();
    require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayCard2);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_CARD);

    require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayMinion2);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_POSITION);

    auto respAutoTarget = response.Target(1, 1);
    result = agent.RunTask(BasicTasks::CombatTask(taskAgent), player2, player1);
    EXPECT_EQ(result, MetaData::COMBAT_SUCCESS);
    EXPECT_EQ(agent.GetPlayer1().field[0]->health, 1);
    EXPECT_EQ(agent.GetPlayer2().field[0], nullptr);

    // Create multiple response for PlayCardTask And PlaySpellTask
    auto respAutoSpell = response.AutoSpell(0, TargetType::MY_FIELD, 0);
    result =
        agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player1, player2);
    EXPECT_EQ(result, MetaData::PLAY_SPELL_SUCCESS);

    auto[respPlayCard3, respPlaySpell] = respAutoSpell.get();
    require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayCard3);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_CARD);

    require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlaySpell);
    EXPECT_EQ(TaskID::_from_integral(require->required()),
              +TaskID::SELECT_TARGET);

    EXPECT_EQ(agent.GetPlayer1().field[0]->health, 2);
    EXPECT_EQ(agent.GetPlayer1().field[0]->gameTags[GameTag::TAUNT], 1);
}
<|endoftext|>


<commit_before>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * DataManReader.cpp
 *
 *  Created on: Feb 21, 2017
 *      Author: Jason Wang
 */

#include "DataManReader.tcc"
#include "adios2/helper/adiosString.h"

namespace adios2
{
namespace core
{
namespace engine
{

DataManReader::DataManReader(IO &io, const std::string &name,
                             const Mode openMode, helper::Comm comm)
: Engine("DataManReader", io, name, openMode, std::move(comm)),
  m_Serializer(m_Comm, helper::IsRowMajor(io.m_HostLanguage)),
  m_RequesterThreadActive(true), m_SubscriberThreadActive(true),
  m_FinalStep(std::numeric_limits<size_t>::max())
{
    m_MpiRank = m_Comm.Rank();
    m_MpiSize = m_Comm.Size();
    helper::GetParameter(m_IO.m_Parameters, "IPAddress", m_IPAddress);
    helper::GetParameter(m_IO.m_Parameters, "Port", m_Port);
    helper::GetParameter(m_IO.m_Parameters, "Timeout", m_Timeout);
    helper::GetParameter(m_IO.m_Parameters, "Verbose", m_Verbosity);
    helper::GetParameter(m_IO.m_Parameters, "Threading", m_Threading);
    helper::GetParameter(m_IO.m_Parameters, "Monitor", m_MonitorActive);
    helper::GetParameter(m_IO.m_Parameters, "MaxStepBufferSize",
                         m_ReceiverBufferSize);

    if (m_IPAddress.empty())
    {
        throw(std::invalid_argument(
            "IP address not specified in wide area staging"));
    }

    std::string requesterAddress =
        "tcp://" + m_IPAddress + ":" + std::to_string(m_Port);
    std::string subscriberAddress =
        "tcp://" + m_IPAddress + ":" + std::to_string(m_Port + 1);
    m_Requester.OpenRequester(requesterAddress, m_Timeout,
                              m_ReceiverBufferSize);

    auto timeBeforeRequest = std::chrono::system_clock::now();
    auto reply = m_Requester.Request("Handshake", 9);
    auto timeAfterRequest = std::chrono::system_clock::now();
    auto roundLatency = std::chrono::duration_cast<std::chrono::milliseconds>(
                            timeAfterRequest - timeBeforeRequest)
                            .count();

    auto startTime = std::chrono::system_clock::now();

    while (reply == nullptr or reply->empty())
    {
        reply = m_Requester.Request("Handshake", 9);
        auto nowTime = std::chrono::system_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::seconds>(
            nowTime - startTime);
        roundLatency = duration.count() * 1000;
        if (duration.count() > m_Timeout)
        {
            m_InitFailed = true;
            return;
        }
    }

    nlohmann::json message = nlohmann::json::parse(reply->data());
    m_TransportMode = message["Transport"];

    if (m_MonitorActive)
    {
        m_Monitor.SetClockError(roundLatency, message["TimeStamp"]);
        m_Monitor.AddTransport(m_TransportMode);
        if (m_Threading)
        {
            m_Monitor.SetReaderThreading();
        }
        bool writerThreading = message["Threading"];
        if (writerThreading)
        {
            m_Monitor.SetWriterThreading();
        }
        auto it = message.find("FloatAccuracy");
        if (it != message.end() && !it->get<std::string>().empty())
        {
            m_Monitor.SetRequiredAccuracy(it->get<std::string>());
        }
    }

    if (m_TransportMode == "fast")
    {
        m_Subscriber.OpenSubscriber(subscriberAddress, m_ReceiverBufferSize);
        m_SubscriberThread = std::thread(&DataManReader::SubscribeThread, this);
    }
    else if (m_TransportMode == "reliable")
    {
    }
    else
    {
        throw(std::invalid_argument("unknown transport mode"));
    }

    m_Requester.Request("Ready", 5);

    if (m_TransportMode == "reliable")
    {
        m_RequesterThread = std::thread(&DataManReader::RequestThread, this);
    }
}

DataManReader::~DataManReader()
{
    if (not m_IsClosed)
    {
        DoClose();
    }

    if (m_Verbosity >= 5)
    {
        std::cout << "DataManReader::~DataManReader() Rank " << m_MpiRank
                  << ", Step " << m_CurrentStep << std::endl;
    }
}

StepStatus DataManReader::BeginStep(StepMode stepMode,
                                    const float timeoutSeconds)
{
    if (m_Verbosity >= 5)
    {
        std::cout << "DataManReader::BeginStep() begin, Rank " << m_MpiRank
                  << ", Step " << m_CurrentStep << std::endl;
    }

    float timeout = timeoutSeconds;

    if (timeout <= 0)
    {
        timeout = m_Timeout;
    }

    if (m_InitFailed)
    {
        if (m_Verbosity >= 5)
        {
            std::cout << "DataManReader::BeginStep(), Rank " << m_MpiRank
                      << " returned EndOfStream due "
                         "to initialization failure"
                      << std::endl;
        }
        return StepStatus::EndOfStream;
    }

    if (m_CurrentStep >= m_FinalStep and m_CurrentStep >= 0)
    {
        if (m_Verbosity >= 5)
        {
            std::cout << "DataManReader::BeginStep() Rank " << m_MpiRank
                      << " returned EndOfStream, "
                         "final step is "
                      << m_FinalStep << std::endl;
        }
        return StepStatus::EndOfStream;
    }

    m_CurrentStepMetadata =
        m_Serializer.GetEarliestLatestStep(m_CurrentStep, 1, timeout, false);

    if (m_CurrentStepMetadata == nullptr)
    {
        if (m_Verbosity >= 5)
        {
            std::cout << "DataManReader::BeginStep() Rank " << m_MpiRank
                      << " returned EndOfStream due "
                         "to timeout"
                      << std::endl;
        }
        return StepStatus::EndOfStream;
    }

    m_Serializer.GetAttributes(m_IO);

    for (const auto &i : *m_CurrentStepMetadata)
    {
        if (i.step == m_CurrentStep)
        {
            if (i.type == DataType::None)
            {
                throw("unknown data type");
            }
#define declare_type(T)                                                        \
    else if (i.type == helper::GetDataType<T>())                               \
    {                                                                          \
        CheckIOVariable<T>(i.name, i.shape, i.start, i.count);                 \
    }
            ADIOS2_FOREACH_STDTYPE_1ARG(declare_type)
#undef declare_type
            else { throw("unknown data type"); }
        }
    }

    if (m_Verbosity >= 5)
    {
        std::cout << "DataManReader::BeginStep() end, Rank " << m_MpiRank
                  << ", Step " << m_CurrentStep << std::endl;
    }

    if (m_MonitorActive)
    {
        m_Monitor.BeginStep(m_CurrentStep);
    }

    return StepStatus::OK;
}

size_t DataManReader::CurrentStep() const { return m_CurrentStep; }

void DataManReader::PerformGets() {}

void DataManReader::EndStep()
{
    m_Serializer.Erase(m_CurrentStep, true);
    m_CurrentStepMetadata = nullptr;

    if (m_MonitorActive)
    {
        auto comMap = m_Serializer.GetOperatorMap();
        for (const auto &i : comMap)
        {
            std::string method, accuracy;
            auto it = i.second.find("accuracy");
            if (it != i.second.end())
            {
                accuracy = it->second;
            }
            it = i.second.find("method");
            if (it != i.second.end())
            {
                method = it->second;
            }
            m_Monitor.AddCompression(method, accuracy);
        }
        m_Monitor.EndStep(m_CurrentStep);
    }
}

void DataManReader::Flush(const int transportIndex) {}

// PRIVATE

void DataManReader::RequestThread()
{
    while (m_RequesterThreadActive)
    {
        std::string request = "Step";
        auto buffer = m_Requester.Request(request.data(), request.size());
        if (buffer != nullptr && buffer->size() > 0)
        {
            if (buffer->size() < 64)
            {
                try
                {
                    auto jmsg = nlohmann::json::parse(buffer->data());
                    m_FinalStep = jmsg["FinalStep"].get<size_t>();
                    return;
                }
                catch (...)
                {
                }
            }
            m_Serializer.PutPack(buffer, m_Threading);
            if (m_MonitorActive)
            {
                size_t combiningSteps = m_Serializer.GetCombiningSteps();
                if (combiningSteps < 20)
                {
                    m_Monitor.SetAverageSteps(40);
                }
                else
                {
                    m_Monitor.SetAverageSteps(combiningSteps * 2);
                }
                auto timeStamps = m_Serializer.GetTimeStamps();
                for (const auto &timeStamp : timeStamps)
                {
                    m_Monitor.AddLatencyMilliseconds(timeStamp);
                }
            }
        }
    }
}

void DataManReader::SubscribeThread()
{
    while (m_SubscriberThreadActive)
    {
        auto buffer = m_Subscriber.Receive();
        if (buffer != nullptr && buffer->size() > 0)
        {
            if (buffer->size() < 64)
            {
                try
                {
                    auto jmsg = nlohmann::json::parse(buffer->data());
                    m_FinalStep = jmsg["FinalStep"].get<size_t>();
                    continue;
                }
                catch (...)
                {
                }
            }
            m_Serializer.PutPack(buffer, m_Threading);
            if (m_MonitorActive)
            {
                size_t combiningSteps = m_Serializer.GetCombiningSteps();
                if (combiningSteps < 20)
                {
                    m_Monitor.SetAverageSteps(40);
                }
                else
                {
                    m_Monitor.SetAverageSteps(combiningSteps * 2);
                }
                auto timeStamps = m_Serializer.GetTimeStamps();
                for (const auto &timeStamp : timeStamps)
                {
                    m_Monitor.AddLatencyMilliseconds(timeStamp);
                }
            }
        }
    }
}

#define declare_type(T)                                                        \
    void DataManReader::DoGetSync(Variable<T> &variable, T *data)              \
    {                                                                          \
        GetSyncCommon(variable, data);                                         \
    }                                                                          \
    void DataManReader::DoGetDeferred(Variable<T> &variable, T *data)          \
    {                                                                          \
        GetDeferredCommon(variable, data);                                     \
    }                                                                          \
    std::map<size_t, std::vector<typename Variable<T>::Info>>                  \
    DataManReader::DoAllStepsBlocksInfo(const Variable<T> &variable) const     \
    {                                                                          \
        return AllStepsBlocksInfoCommon(variable);                             \
    }                                                                          \
    std::vector<typename Variable<T>::Info> DataManReader::DoBlocksInfo(       \
        const Variable<T> &variable, const size_t step) const                  \
    {                                                                          \
        return BlocksInfoCommon(variable, step);                               \
    }
ADIOS2_FOREACH_STDTYPE_1ARG(declare_type)
#undef declare_type

void DataManReader::DoClose(const int transportIndex)
{
    m_SubscriberThreadActive = false;
    m_RequesterThreadActive = false;
    if (m_SubscriberThread.joinable())
    {
        m_SubscriberThread.join();
    }
    if (m_RequesterThread.joinable())
    {
        m_RequesterThread.join();
    }
    m_IsClosed = true;
    if (m_MonitorActive)
    {
        m_Monitor.OutputJson(m_Name);
    }
}

} // end namespace engine
} // end namespace core
} // end namespace adios2
<commit_msg>added combining steps to dataman monitor<commit_after>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * DataManReader.cpp
 *
 *  Created on: Feb 21, 2017
 *      Author: Jason Wang
 */

#include "DataManReader.tcc"
#include "adios2/helper/adiosString.h"

namespace adios2
{
namespace core
{
namespace engine
{

DataManReader::DataManReader(IO &io, const std::string &name,
                             const Mode openMode, helper::Comm comm)
: Engine("DataManReader", io, name, openMode, std::move(comm)),
  m_Serializer(m_Comm, helper::IsRowMajor(io.m_HostLanguage)),
  m_RequesterThreadActive(true), m_SubscriberThreadActive(true),
  m_FinalStep(std::numeric_limits<size_t>::max())
{
    m_MpiRank = m_Comm.Rank();
    m_MpiSize = m_Comm.Size();
    helper::GetParameter(m_IO.m_Parameters, "IPAddress", m_IPAddress);
    helper::GetParameter(m_IO.m_Parameters, "Port", m_Port);
    helper::GetParameter(m_IO.m_Parameters, "Timeout", m_Timeout);
    helper::GetParameter(m_IO.m_Parameters, "Verbose", m_Verbosity);
    helper::GetParameter(m_IO.m_Parameters, "Threading", m_Threading);
    helper::GetParameter(m_IO.m_Parameters, "Monitor", m_MonitorActive);
    helper::GetParameter(m_IO.m_Parameters, "MaxStepBufferSize",
                         m_ReceiverBufferSize);

    if (m_IPAddress.empty())
    {
        throw(std::invalid_argument(
            "IP address not specified in wide area staging"));
    }

    std::string requesterAddress =
        "tcp://" + m_IPAddress + ":" + std::to_string(m_Port);
    std::string subscriberAddress =
        "tcp://" + m_IPAddress + ":" + std::to_string(m_Port + 1);
    m_Requester.OpenRequester(requesterAddress, m_Timeout,
                              m_ReceiverBufferSize);

    auto timeBeforeRequest = std::chrono::system_clock::now();
    auto reply = m_Requester.Request("Handshake", 9);
    auto timeAfterRequest = std::chrono::system_clock::now();
    auto roundLatency = std::chrono::duration_cast<std::chrono::milliseconds>(
                            timeAfterRequest - timeBeforeRequest)
                            .count();

    auto startTime = std::chrono::system_clock::now();

    while (reply == nullptr or reply->empty())
    {
        reply = m_Requester.Request("Handshake", 9);
        auto nowTime = std::chrono::system_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::seconds>(
            nowTime - startTime);
        roundLatency = duration.count() * 1000;
        if (duration.count() > m_Timeout)
        {
            m_InitFailed = true;
            return;
        }
    }

    nlohmann::json message = nlohmann::json::parse(reply->data());
    m_TransportMode = message["Transport"];

    if (m_MonitorActive)
    {
        m_Monitor.SetClockError(roundLatency, message["TimeStamp"]);
        m_Monitor.AddTransport(m_TransportMode);
        if (m_Threading)
        {
            m_Monitor.SetReaderThreading();
        }
        bool writerThreading = message["Threading"];
        if (writerThreading)
        {
            m_Monitor.SetWriterThreading();
        }
        auto it = message.find("FloatAccuracy");
        if (it != message.end() && !it->get<std::string>().empty())
        {
            m_Monitor.SetRequiredAccuracy(it->get<std::string>());
        }
    }

    if (m_TransportMode == "fast")
    {
        m_Subscriber.OpenSubscriber(subscriberAddress, m_ReceiverBufferSize);
        m_SubscriberThread = std::thread(&DataManReader::SubscribeThread, this);
    }
    else if (m_TransportMode == "reliable")
    {
    }
    else
    {
        throw(std::invalid_argument("unknown transport mode"));
    }

    m_Requester.Request("Ready", 5);

    if (m_TransportMode == "reliable")
    {
        m_RequesterThread = std::thread(&DataManReader::RequestThread, this);
    }
}

DataManReader::~DataManReader()
{
    if (not m_IsClosed)
    {
        DoClose();
    }

    if (m_Verbosity >= 5)
    {
        std::cout << "DataManReader::~DataManReader() Rank " << m_MpiRank
                  << ", Step " << m_CurrentStep << std::endl;
    }
}

StepStatus DataManReader::BeginStep(StepMode stepMode,
                                    const float timeoutSeconds)
{
    if (m_Verbosity >= 5)
    {
        std::cout << "DataManReader::BeginStep() begin, Rank " << m_MpiRank
                  << ", Step " << m_CurrentStep << std::endl;
    }

    float timeout = timeoutSeconds;

    if (timeout <= 0)
    {
        timeout = m_Timeout;
    }

    if (m_InitFailed)
    {
        if (m_Verbosity >= 5)
        {
            std::cout << "DataManReader::BeginStep(), Rank " << m_MpiRank
                      << " returned EndOfStream due "
                         "to initialization failure"
                      << std::endl;
        }
        return StepStatus::EndOfStream;
    }

    if (m_CurrentStep >= m_FinalStep and m_CurrentStep >= 0)
    {
        if (m_Verbosity >= 5)
        {
            std::cout << "DataManReader::BeginStep() Rank " << m_MpiRank
                      << " returned EndOfStream, "
                         "final step is "
                      << m_FinalStep << std::endl;
        }
        return StepStatus::EndOfStream;
    }

    m_CurrentStepMetadata =
        m_Serializer.GetEarliestLatestStep(m_CurrentStep, 1, timeout, false);

    if (m_CurrentStepMetadata == nullptr)
    {
        if (m_Verbosity >= 5)
        {
            std::cout << "DataManReader::BeginStep() Rank " << m_MpiRank
                      << " returned EndOfStream due "
                         "to timeout"
                      << std::endl;
        }
        return StepStatus::EndOfStream;
    }

    m_Serializer.GetAttributes(m_IO);

    for (const auto &i : *m_CurrentStepMetadata)
    {
        if (i.step == m_CurrentStep)
        {
            if (i.type == DataType::None)
            {
                throw("unknown data type");
            }
#define declare_type(T)                                                        \
    else if (i.type == helper::GetDataType<T>())                               \
    {                                                                          \
        CheckIOVariable<T>(i.name, i.shape, i.start, i.count);                 \
    }
            ADIOS2_FOREACH_STDTYPE_1ARG(declare_type)
#undef declare_type
            else { throw("unknown data type"); }
        }
    }

    if (m_Verbosity >= 5)
    {
        std::cout << "DataManReader::BeginStep() end, Rank " << m_MpiRank
                  << ", Step " << m_CurrentStep << std::endl;
    }

    if (m_MonitorActive)
    {
        m_Monitor.BeginStep(m_CurrentStep);
    }

    return StepStatus::OK;
}

size_t DataManReader::CurrentStep() const { return m_CurrentStep; }

void DataManReader::PerformGets() {}

void DataManReader::EndStep()
{
    m_Serializer.Erase(m_CurrentStep, true);
    m_CurrentStepMetadata = nullptr;

    if (m_MonitorActive)
    {
        auto comMap = m_Serializer.GetOperatorMap();
        for (const auto &i : comMap)
        {
            std::string method, accuracy;
            auto it = i.second.find("accuracy");
            if (it != i.second.end())
            {
                accuracy = it->second;
            }
            it = i.second.find("method");
            if (it != i.second.end())
            {
                method = it->second;
            }
            m_Monitor.AddCompression(method, accuracy);
        }
        m_Monitor.EndStep(m_CurrentStep);
    }
}

void DataManReader::Flush(const int transportIndex) {}

// PRIVATE

void DataManReader::RequestThread()
{
    while (m_RequesterThreadActive)
    {
        std::string request = "Step";
        auto buffer = m_Requester.Request(request.data(), request.size());
        if (buffer != nullptr && buffer->size() > 0)
        {
            if (buffer->size() < 64)
            {
                try
                {
                    auto jmsg = nlohmann::json::parse(buffer->data());
                    m_FinalStep = jmsg["FinalStep"].get<size_t>();
                    return;
                }
                catch (...)
                {
                }
            }
            m_Serializer.PutPack(buffer, m_Threading);
            if (m_MonitorActive)
            {
                size_t combiningSteps = m_Serializer.GetCombiningSteps();
                m_Monitor.SetCombiningSteps(combiningSteps);
                if (combiningSteps < 20)
                {
                    m_Monitor.SetAverageSteps(40);
                }
                else
                {
                    m_Monitor.SetAverageSteps(combiningSteps * 2);
                }
                auto timeStamps = m_Serializer.GetTimeStamps();
                for (const auto &timeStamp : timeStamps)
                {
                    m_Monitor.AddLatencyMilliseconds(timeStamp);
                }
            }
        }
    }
}

void DataManReader::SubscribeThread()
{
    while (m_SubscriberThreadActive)
    {
        auto buffer = m_Subscriber.Receive();
        if (buffer != nullptr && buffer->size() > 0)
        {
            if (buffer->size() < 64)
            {
                try
                {
                    auto jmsg = nlohmann::json::parse(buffer->data());
                    m_FinalStep = jmsg["FinalStep"].get<size_t>();
                    continue;
                }
                catch (...)
                {
                }
            }
            m_Serializer.PutPack(buffer, m_Threading);
            if (m_MonitorActive)
            {
                size_t combiningSteps = m_Serializer.GetCombiningSteps();
                if (combiningSteps < 20)
                {
                    m_Monitor.SetAverageSteps(40);
                }
                else
                {
                    m_Monitor.SetAverageSteps(combiningSteps * 2);
                }
                auto timeStamps = m_Serializer.GetTimeStamps();
                for (const auto &timeStamp : timeStamps)
                {
                    m_Monitor.AddLatencyMilliseconds(timeStamp);
                }
            }
        }
    }
}

#define declare_type(T)                                                        \
    void DataManReader::DoGetSync(Variable<T> &variable, T *data)              \
    {                                                                          \
        GetSyncCommon(variable, data);                                         \
    }                                                                          \
    void DataManReader::DoGetDeferred(Variable<T> &variable, T *data)          \
    {                                                                          \
        GetDeferredCommon(variable, data);                                     \
    }                                                                          \
    std::map<size_t, std::vector<typename Variable<T>::Info>>                  \
    DataManReader::DoAllStepsBlocksInfo(const Variable<T> &variable) const     \
    {                                                                          \
        return AllStepsBlocksInfoCommon(variable);                             \
    }                                                                          \
    std::vector<typename Variable<T>::Info> DataManReader::DoBlocksInfo(       \
        const Variable<T> &variable, const size_t step) const                  \
    {                                                                          \
        return BlocksInfoCommon(variable, step);                               \
    }
ADIOS2_FOREACH_STDTYPE_1ARG(declare_type)
#undef declare_type

void DataManReader::DoClose(const int transportIndex)
{
    m_SubscriberThreadActive = false;
    m_RequesterThreadActive = false;
    if (m_SubscriberThread.joinable())
    {
        m_SubscriberThread.join();
    }
    if (m_RequesterThread.joinable())
    {
        m_RequesterThread.join();
    }
    m_IsClosed = true;
    if (m_MonitorActive)
    {
        m_Monitor.OutputJson(m_Name);
    }
}

} // end namespace engine
} // end namespace core
} // end namespace adios2
<|endoftext|>


<commit_before>// @(#)root/rootx:$Name:  $:$Id: rootx.cxx,v 1.17 2005/06/01 14:07:58 rdm Exp $
// Author: Fons Rademakers   19/02/98

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// Rootx                                                                //
//                                                                      //
// Rootx is a small front-end program that starts the main ROOT module. //
// This program is called "root" in the $ROOTSYS/bin directory and the  //
// real ROOT executable is now called "root.exe" (formerly "root").     //
// Rootx puts up a splash screen giving some info about the current     //
// version of ROOT and, more importanly, it sets up the required        //
// LD_LIBRARY_PATH, SHLIB_PATH and LIBPATH environment variables        //
// (depending on the platform).                                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#ifdef HAVE_CONFIG
#include "config.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <errno.h>

#include <netdb.h>
#include <sys/socket.h>

#if defined(__sgi) || defined(__sun)
#define HAVE_UTMPX_H
#define UTMP_NO_ADDR
#endif
#if (defined(__alpha) && !defined(__linux)) || defined(_AIX) || \
    defined(__FreeBSD__) || defined(__Lynx__) || defined(__APPLE__) || \
    defined(__OpenBSD__)
#define UTMP_NO_ADDR
#endif

#ifdef __sun
#   ifndef _REENTRANT
#      if __SUNPRO_CC > 0x420
#         define GLOBAL_ERRNO
#      endif
#   endif
#endif

#ifndef __VMS
# ifdef HAVE_UTMPX_H
# include <utmpx.h>
# define STRUCT_UTMP struct utmpx
# else
# if defined(__linux) && defined(__powerpc) && (__GNUC__ == 2) && (__GNUC_MINOR__ < 90)
   extern "C" {
# endif
# include <utmp.h>
# define STRUCT_UTMP struct utmp
# endif
#endif

#if !defined(UTMP_FILE) && defined(_PATH_UTMP)      // 4.4BSD
#define UTMP_FILE _PATH_UTMP
#endif
#if defined(UTMPX_FILE)                             // Solaris, SysVr4
#undef  UTMP_FILE
#define UTMP_FILE UTMPX_FILE
#endif
#ifndef UTMP_FILE
#define UTMP_FILE "/etc/utmp"
#endif

#if defined(__CYGWIN__) && defined(__GNUC__)
#define ROOTBINARY "root_exe.exe"
#else
#define ROOTBINARY "root.exe"
#endif

extern void PopupLogo(bool);
extern void WaitLogo();
extern void PopdownLogo();
extern void CloseDisplay();

static STRUCT_UTMP *gUtmpContents;
static bool gNoLogo = false;

static int GetErrno()
{
#ifdef GLOBAL_ERRNO
   return ::errno;
#else
   return errno;
#endif
}

static void ResetErrno()
{
#ifdef GLOBAL_ERRNO
   ::errno = 0;
#else
   errno = 0;
#endif
}

static int ReadUtmp()
{
   FILE  *utmp;
   struct stat file_stats;
   size_t n_read, size;

   gUtmpContents = 0;

   utmp = fopen(UTMP_FILE, "r");
   if (!utmp)
      return 0;

   fstat(fileno(utmp), &file_stats);
   size = file_stats.st_size;
   if (size <= 0) {
      fclose(utmp);
      return 0;
   }

   gUtmpContents = (STRUCT_UTMP *) malloc(size);
   if (!gUtmpContents) return 0;

   n_read = fread(gUtmpContents, 1, size, utmp);
   if (ferror(utmp) || fclose(utmp) == EOF || n_read < size) {
      free(gUtmpContents);
      gUtmpContents = 0;
      return 0;
   }

   return size / sizeof(STRUCT_UTMP);
}

static STRUCT_UTMP *SearchEntry(int n, const char *tty)
{
   STRUCT_UTMP *ue = gUtmpContents;

   while (n--) {
      if (ue->ut_name[0] && !strncmp(tty, ue->ut_line, sizeof(ue->ut_line)))
         return ue;
      ue++;
   }
   return 0;
}

static void SetDisplay()
{
   // Set DISPLAY environment variable.

   if (!getenv("DISPLAY")) {
      char *tty = ttyname(0);  // device user is logged in on
      if (tty) {
         tty += 5;             // remove "/dev/"
         STRUCT_UTMP *utmp_entry = SearchEntry(ReadUtmp(), tty);
         if (utmp_entry) {
            static char display[64];
            if (utmp_entry->ut_host[0]) {
               if (strchr(utmp_entry->ut_host, ':')) {
                  sprintf(display, "DISPLAY=%s", utmp_entry->ut_host);
                  fprintf(stderr, "*** DISPLAY not set, setting it to %s\n",
                          utmp_entry->ut_host);
               } else {
                  sprintf(display, "DISPLAY=%s:0.0", utmp_entry->ut_host);
                  fprintf(stderr, "*** DISPLAY not set, setting it to %s:0.0\n",
                          utmp_entry->ut_host);
               }
               putenv((char *)display);
#ifndef UTMP_NO_ADDR
            } else if (utmp_entry->ut_addr) {
               struct hostent *he;
               if ((he = gethostbyaddr((const char*)&utmp_entry->ut_addr,
                                       sizeof(utmp_entry->ut_addr), AF_INET))) {
                  sprintf(display, "DISPLAY=%s:0.0", he->h_name);
                  fprintf(stderr, "*** DISPLAY not set, setting it to %s:0.0\n",
                          he->h_name);
                  putenv((char *)display);
               }
#endif
            }
         }
         free(gUtmpContents);
      }
   }
}

static void SetLibraryPath()
{
#ifndef ROOTLIBDIR
   // Set library path for the different platforms.

   char *msg;

#  if defined(__linux) || defined(__alpha) || defined(__sgi) || \
      defined(__sun) || defined(__FreeBSD__) || defined(__APPLE__) || \
      defined(__OpenBSD__)
   if (getenv("LD_LIBRARY_PATH")) {
      msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("LD_LIBRARY_PATH"))+100];
      sprintf(msg, "LD_LIBRARY_PATH=%s/lib:%s", getenv("ROOTSYS"),
                                                getenv("LD_LIBRARY_PATH"));
   } else {
      msg = new char [strlen(getenv("ROOTSYS"))+100];
#  if defined(__sun)
      sprintf(msg, "LD_LIBRARY_PATH=%s/lib:/usr/dt/lib", getenv("ROOTSYS"));
#  else
      sprintf(msg, "LD_LIBRARY_PATH=%s/lib", getenv("ROOTSYS"));
#  endif
   }
#  elif defined(__hpux)  || defined(_HIUX_SOURCE)
   if (getenv("SHLIB_PATH")) {
      msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("SHLIB_PATH"))+100];
      sprintf(msg, "SHLIB_PATH=%s/lib:%s", getenv("ROOTSYS"),
                                           getenv("SHLIB_PATH"));
   } else {
      msg = new char [strlen(getenv("ROOTSYS"))+100];
      sprintf(msg, "SHLIB_PATH=%s/lib", getenv("ROOTSYS"));
   }
#  elif defined(_AIX)
   if (getenv("LIBPATH")) {
      msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("LIBPATH"))+100];
      sprintf(msg, "LIBPATH=%s/lib:%s", getenv("ROOTSYS"),
                                        getenv("LIBPATH"));
   } else {
      msg = new char [strlen(getenv("ROOTSYS"))+100];
      sprintf(msg, "LIBPATH=%s/lib:/lib:/usr/lib", getenv("ROOTSYS"));
   }
#  endif
   putenv(msg);
#endif
}

extern "C" {
   static void SigUsr1(int);
}

static void SigUsr1(int)
{
   // When we get SIGUSR1 from child (i.e. ROOT) then pop down logo.

   if (!gNoLogo)
      PopdownLogo();
}

static void WaitChild(int childpid)
{
   // Wait till child (i.e. ROOT) is finished.

   int status;

   do {
      while (waitpid(childpid, &status, WUNTRACED) < 0) {
         if (GetErrno() != EINTR)
            break;
         ResetErrno();
      }

      if (WIFEXITED(status))
         exit(WEXITSTATUS(status));

      if (WIFSIGNALED(status))
         exit(WTERMSIG(status));

      if (WIFSTOPPED(status)) {         // child got ctlr-Z
         raise(SIGTSTP);                // stop also parent
         kill(childpid, SIGCONT);       // if parent wakes up, wake up child
      }
   } while (WIFSTOPPED(status));

   exit(0);
}

static void PrintUsage(char *pname)
{
   // This is a copy of the text in TApplication::GetOptions().

   fprintf(stderr, "Usage: %s [-l] [-b] [-n] [-q] [dir] [file1.C ... fileN.C]\n", pname);
   fprintf(stderr, "Options:\n");
   fprintf(stderr, "  -b : run in batch mode without graphics\n");
   fprintf(stderr, "  -n : do not execute logon and logoff macros as specified in .rootrc\n");
   fprintf(stderr, "  -q : exit after processing command line macro files\n");
   fprintf(stderr, "  -l : do not show splash screen\n");
   fprintf(stderr, " dir : if dir is a valid directory cd to it before executing\n");
   fprintf(stderr, "\n");
   fprintf(stderr, "  -?      : print usage\n");
   fprintf(stderr, "  -h      : print usage\n");
   fprintf(stderr, "  --help  : print usage\n");
   fprintf(stderr, "  -config : print ./configure options\n");
   fprintf(stderr, "\n");
}

int main(int argc, char **argv)
{
   const int kMAXARGS = 256;
   char *argvv[kMAXARGS];
   char  arg0[2048];

#ifndef ROOTPREFIX
   if (!getenv("ROOTSYS")) {
      fprintf(stderr, "%s: ROOTSYS not set. Set it before trying to run %s.\n",
              argv[0], argv[0]);
      return 1;
   }
#endif

   // In batch mode don't show splash screen, idem for no logo mode,
   // in about mode show always splash screen
   bool batch = false, about = false;
   int i;
   for (i = 1; i < argc; i++) {
      if (!strcmp(argv[i], "-?") || !strncmp(argv[i], "-h", 2) ||
          !strncmp(argv[i], "--help", 6)) {
         PrintUsage(argv[0]);
         return 1;
      }
      if (!strcmp(argv[i], "-b"))      batch   = true;
      if (!strcmp(argv[i], "-l"))      gNoLogo = true;
      if (!strcmp(argv[i], "-a"))      about   = true;
      if (!strcmp(argv[i], "-config")) gNoLogo = true;
   }
   if (batch)
      gNoLogo = true;
   if (about) {
      batch   = false;
      gNoLogo = false;
   }

   if (!batch) {
      SetDisplay();
      if (!getenv("DISPLAY")) {
         fprintf(stderr, "%s: can't figure out DISPLAY, set it manually\n", argv[0]);
         return 1;
      }
      if (about) {
         PopupLogo(true);
         WaitLogo();
         return 0;
      } else if (!gNoLogo)
         PopupLogo(false);
   }

   // Ignore SIGINT and SIGQUIT. Install handler for SIGUSR1.

   struct sigaction ignore, handle, saveintr, savequit, saveusr1;

#if defined(__sun) && !defined(__i386) && !defined(__SVR4)
   ignore.sa_handler = (void (*)())SIG_IGN;
#elif defined(__sun) && defined(__SVR4)
   ignore.sa_handler = (void (*)(int))SIG_IGN;
#else
   ignore.sa_handler = SIG_IGN;
#endif
   sigemptyset(&ignore.sa_mask);
   ignore.sa_flags = 0;
   handle = ignore;
#if defined(__sun) && !defined(__i386) && !defined(__SVR4)
   handle.sa_handler = (void (*)())SigUsr1;
#elif defined(__sun) && defined(__SVR4)
   handle.sa_handler = SigUsr1;
#elif (defined(__sgi) && !defined(__KCC)) || defined(__Lynx__)
#   if defined(IRIX64) || (__GNUG__>=3)
   handle.sa_handler = SigUsr1;
#   else
   handle.sa_handler = (void (*)(...))SigUsr1;
#   endif
#else
   handle.sa_handler = SigUsr1;
#endif
   sigaction(SIGINT,  &ignore, &saveintr);
   sigaction(SIGQUIT, &ignore, &savequit);
   sigaction(SIGUSR1, &handle, &saveusr1);

   // Create child...

   int childpid;
   if ((childpid = fork()) < 0) {
      fprintf(stderr, "%s: error forking child\n", argv[0]);
      return 1;
   } else if (childpid > 0) {
      if (!gNoLogo)
         WaitLogo();
      WaitChild(childpid);
   }

   // Continue with child...

   // Restore original signal actions
   sigaction(SIGINT,  &saveintr, 0);
   sigaction(SIGQUIT, &savequit, 0);
   sigaction(SIGUSR1, &saveusr1, 0);

   // Close X display connection
   CloseDisplay();

   // Child is going to overlay itself with the actual ROOT module...

   // Build argv vector
#ifdef ROOTBINDIR
   sprintf(arg0, "%s/%s", ROOTBINDIR, ROOTBINARY);
#else
   sprintf(arg0, "%s/bin/%s", getenv("ROOTSYS"), ROOTBINARY);
#endif
   argvv[0] = arg0;
   argvv[1] = (char *) "-splash";

   int iargc = argc;
   if (iargc > kMAXARGS-2) iargc = kMAXARGS-2;
   for (i = 1; i < iargc; i++)
      argvv[1+i] = argv[i];
   argvv[1+i] = 0;

   // Make sure library path is set
   SetLibraryPath();

   // Execute actual ROOT module
   execv(arg0, argvv);

   // Exec failed
#ifndef ROOTBINDIR
   fprintf(stderr,
           "%s: can't start ROOT -- check that %s/bin/%s exists!\n",
           argv[0], getenv("ROOTSYS"), ROOTBINARY);
#else
   fprintf(stderr, "%s: can't start ROOT -- check that %s/%s exists!\n",
           argv[0], ROOTBINDIR, ROOTBINARY);
#endif

   return 1;
}

<commit_msg>Preset DYLD_LIBRARY_PATH for MacOS X.<commit_after>// @(#)root/rootx:$Name:  $:$Id: rootx.cxx,v 1.18 2005/09/04 09:13:27 brun Exp $
// Author: Fons Rademakers   19/02/98

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// Rootx                                                                //
//                                                                      //
// Rootx is a small front-end program that starts the main ROOT module. //
// This program is called "root" in the $ROOTSYS/bin directory and the  //
// real ROOT executable is now called "root.exe" (formerly "root").     //
// Rootx puts up a splash screen giving some info about the current     //
// version of ROOT and, more importanly, it sets up the required        //
// LD_LIBRARY_PATH, SHLIB_PATH and LIBPATH environment variables        //
// (depending on the platform).                                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#ifdef HAVE_CONFIG
#include "config.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <errno.h>

#include <netdb.h>
#include <sys/socket.h>

#if defined(__sgi) || defined(__sun)
#define HAVE_UTMPX_H
#define UTMP_NO_ADDR
#endif
#if (defined(__alpha) && !defined(__linux)) || defined(_AIX) || \
    defined(__FreeBSD__) || defined(__Lynx__) || defined(__APPLE__) || \
    defined(__OpenBSD__)
#define UTMP_NO_ADDR
#endif

#ifdef __sun
#   ifndef _REENTRANT
#      if __SUNPRO_CC > 0x420
#         define GLOBAL_ERRNO
#      endif
#   endif
#endif

#ifndef __VMS
# ifdef HAVE_UTMPX_H
# include <utmpx.h>
# define STRUCT_UTMP struct utmpx
# else
# if defined(__linux) && defined(__powerpc) && (__GNUC__ == 2) && (__GNUC_MINOR__ < 90)
   extern "C" {
# endif
# include <utmp.h>
# define STRUCT_UTMP struct utmp
# endif
#endif

#if !defined(UTMP_FILE) && defined(_PATH_UTMP)      // 4.4BSD
#define UTMP_FILE _PATH_UTMP
#endif
#if defined(UTMPX_FILE)                             // Solaris, SysVr4
#undef  UTMP_FILE
#define UTMP_FILE UTMPX_FILE
#endif
#ifndef UTMP_FILE
#define UTMP_FILE "/etc/utmp"
#endif

#if defined(__CYGWIN__) && defined(__GNUC__)
#define ROOTBINARY "root_exe.exe"
#else
#define ROOTBINARY "root.exe"
#endif

extern void PopupLogo(bool);
extern void WaitLogo();
extern void PopdownLogo();
extern void CloseDisplay();

static STRUCT_UTMP *gUtmpContents;
static bool gNoLogo = false;

static int GetErrno()
{
#ifdef GLOBAL_ERRNO
   return ::errno;
#else
   return errno;
#endif
}

static void ResetErrno()
{
#ifdef GLOBAL_ERRNO
   ::errno = 0;
#else
   errno = 0;
#endif
}

static int ReadUtmp()
{
   FILE  *utmp;
   struct stat file_stats;
   size_t n_read, size;

   gUtmpContents = 0;

   utmp = fopen(UTMP_FILE, "r");
   if (!utmp)
      return 0;

   fstat(fileno(utmp), &file_stats);
   size = file_stats.st_size;
   if (size <= 0) {
      fclose(utmp);
      return 0;
   }

   gUtmpContents = (STRUCT_UTMP *) malloc(size);
   if (!gUtmpContents) return 0;

   n_read = fread(gUtmpContents, 1, size, utmp);
   if (ferror(utmp) || fclose(utmp) == EOF || n_read < size) {
      free(gUtmpContents);
      gUtmpContents = 0;
      return 0;
   }

   return size / sizeof(STRUCT_UTMP);
}

static STRUCT_UTMP *SearchEntry(int n, const char *tty)
{
   STRUCT_UTMP *ue = gUtmpContents;

   while (n--) {
      if (ue->ut_name[0] && !strncmp(tty, ue->ut_line, sizeof(ue->ut_line)))
         return ue;
      ue++;
   }
   return 0;
}

static void SetDisplay()
{
   // Set DISPLAY environment variable.

   if (!getenv("DISPLAY")) {
      char *tty = ttyname(0);  // device user is logged in on
      if (tty) {
         tty += 5;             // remove "/dev/"
         STRUCT_UTMP *utmp_entry = SearchEntry(ReadUtmp(), tty);
         if (utmp_entry) {
            static char display[64];
            if (utmp_entry->ut_host[0]) {
               if (strchr(utmp_entry->ut_host, ':')) {
                  sprintf(display, "DISPLAY=%s", utmp_entry->ut_host);
                  fprintf(stderr, "*** DISPLAY not set, setting it to %s\n",
                          utmp_entry->ut_host);
               } else {
                  sprintf(display, "DISPLAY=%s:0.0", utmp_entry->ut_host);
                  fprintf(stderr, "*** DISPLAY not set, setting it to %s:0.0\n",
                          utmp_entry->ut_host);
               }
               putenv((char *)display);
#ifndef UTMP_NO_ADDR
            } else if (utmp_entry->ut_addr) {
               struct hostent *he;
               if ((he = gethostbyaddr((const char*)&utmp_entry->ut_addr,
                                       sizeof(utmp_entry->ut_addr), AF_INET))) {
                  sprintf(display, "DISPLAY=%s:0.0", he->h_name);
                  fprintf(stderr, "*** DISPLAY not set, setting it to %s:0.0\n",
                          he->h_name);
                  putenv((char *)display);
               }
#endif
            }
         }
         free(gUtmpContents);
      }
   }
}

static void SetLibraryPath()
{
#ifndef ROOTLIBDIR
   // Set library path for the different platforms.

   char *msg;

#  if defined(__hpux)  || defined(_HIUX_SOURCE)
   if (getenv("SHLIB_PATH")) {
      msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("SHLIB_PATH"))+100];
      sprintf(msg, "SHLIB_PATH=%s/lib:%s", getenv("ROOTSYS"),
                                           getenv("SHLIB_PATH"));
   } else {
      msg = new char [strlen(getenv("ROOTSYS"))+100];
      sprintf(msg, "SHLIB_PATH=%s/lib", getenv("ROOTSYS"));
   }
#  elif defined(_AIX)
   if (getenv("LIBPATH")) {
      msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("LIBPATH"))+100];
      sprintf(msg, "LIBPATH=%s/lib:%s", getenv("ROOTSYS"),
                                        getenv("LIBPATH"));
   } else {
      msg = new char [strlen(getenv("ROOTSYS"))+100];
      sprintf(msg, "LIBPATH=%s/lib:/lib:/usr/lib", getenv("ROOTSYS"));
   }
#  elif defined(__APPLE__)
   if (getenv("DYLD_LIBRARY_PATH")) {
      msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("DYLD_LIBRARY_PATH"))+100];
      sprintf(msg, "DYLD_LIBRARY_PATH=%s/lib:%s", getenv("ROOTSYS"),
                                                  getenv("DYLD_LIBRARY_PATH"));
   } else {
      msg = new char [strlen(getenv("ROOTSYS"))+100];
      sprintf(msg, "DYLD_LIBRARY_PATH=%s/lib", getenv("ROOTSYS"));
   }
#  else
   if (getenv("LD_LIBRARY_PATH")) {
      msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("LD_LIBRARY_PATH"))+100];
      sprintf(msg, "LD_LIBRARY_PATH=%s/lib:%s", getenv("ROOTSYS"),
                                                getenv("LD_LIBRARY_PATH"));
   } else {
      msg = new char [strlen(getenv("ROOTSYS"))+100];
#  if defined(__sun)
      sprintf(msg, "LD_LIBRARY_PATH=%s/lib:/usr/dt/lib", getenv("ROOTSYS"));
#  else
      sprintf(msg, "LD_LIBRARY_PATH=%s/lib", getenv("ROOTSYS"));
#  endif
   }
#  endif
   putenv(msg);
#endif
}

extern "C" {
   static void SigUsr1(int);
}

static void SigUsr1(int)
{
   // When we get SIGUSR1 from child (i.e. ROOT) then pop down logo.

   if (!gNoLogo)
      PopdownLogo();
}

static void WaitChild(int childpid)
{
   // Wait till child (i.e. ROOT) is finished.

   int status;

   do {
      while (waitpid(childpid, &status, WUNTRACED) < 0) {
         if (GetErrno() != EINTR)
            break;
         ResetErrno();
      }

      if (WIFEXITED(status))
         exit(WEXITSTATUS(status));

      if (WIFSIGNALED(status))
         exit(WTERMSIG(status));

      if (WIFSTOPPED(status)) {         // child got ctlr-Z
         raise(SIGTSTP);                // stop also parent
         kill(childpid, SIGCONT);       // if parent wakes up, wake up child
      }
   } while (WIFSTOPPED(status));

   exit(0);
}

static void PrintUsage(char *pname)
{
   // This is a copy of the text in TApplication::GetOptions().

   fprintf(stderr, "Usage: %s [-l] [-b] [-n] [-q] [dir] [file1.C ... fileN.C]\n", pname);
   fprintf(stderr, "Options:\n");
   fprintf(stderr, "  -b : run in batch mode without graphics\n");
   fprintf(stderr, "  -n : do not execute logon and logoff macros as specified in .rootrc\n");
   fprintf(stderr, "  -q : exit after processing command line macro files\n");
   fprintf(stderr, "  -l : do not show splash screen\n");
   fprintf(stderr, " dir : if dir is a valid directory cd to it before executing\n");
   fprintf(stderr, "\n");
   fprintf(stderr, "  -?      : print usage\n");
   fprintf(stderr, "  -h      : print usage\n");
   fprintf(stderr, "  --help  : print usage\n");
   fprintf(stderr, "  -config : print ./configure options\n");
   fprintf(stderr, "\n");
}

int main(int argc, char **argv)
{
   const int kMAXARGS = 256;
   char *argvv[kMAXARGS];
   char  arg0[2048];

#ifndef ROOTPREFIX
   if (!getenv("ROOTSYS")) {
      fprintf(stderr, "%s: ROOTSYS not set. Set it before trying to run %s.\n",
              argv[0], argv[0]);
      return 1;
   }
#endif

   // In batch mode don't show splash screen, idem for no logo mode,
   // in about mode show always splash screen
   bool batch = false, about = false;
   int i;
   for (i = 1; i < argc; i++) {
      if (!strcmp(argv[i], "-?") || !strncmp(argv[i], "-h", 2) ||
          !strncmp(argv[i], "--help", 6)) {
         PrintUsage(argv[0]);
         return 1;
      }
      if (!strcmp(argv[i], "-b"))      batch   = true;
      if (!strcmp(argv[i], "-l"))      gNoLogo = true;
      if (!strcmp(argv[i], "-a"))      about   = true;
      if (!strcmp(argv[i], "-config")) gNoLogo = true;
   }
   if (batch)
      gNoLogo = true;
   if (about) {
      batch   = false;
      gNoLogo = false;
   }

   if (!batch) {
      SetDisplay();
      if (!getenv("DISPLAY")) {
         fprintf(stderr, "%s: can't figure out DISPLAY, set it manually\n", argv[0]);
         return 1;
      }
      if (about) {
         PopupLogo(true);
         WaitLogo();
         return 0;
      } else if (!gNoLogo)
         PopupLogo(false);
   }

   // Ignore SIGINT and SIGQUIT. Install handler for SIGUSR1.

   struct sigaction ignore, handle, saveintr, savequit, saveusr1;

#if defined(__sun) && !defined(__i386) && !defined(__SVR4)
   ignore.sa_handler = (void (*)())SIG_IGN;
#elif defined(__sun) && defined(__SVR4)
   ignore.sa_handler = (void (*)(int))SIG_IGN;
#else
   ignore.sa_handler = SIG_IGN;
#endif
   sigemptyset(&ignore.sa_mask);
   ignore.sa_flags = 0;
   handle = ignore;
#if defined(__sun) && !defined(__i386) && !defined(__SVR4)
   handle.sa_handler = (void (*)())SigUsr1;
#elif defined(__sun) && defined(__SVR4)
   handle.sa_handler = SigUsr1;
#elif (defined(__sgi) && !defined(__KCC)) || defined(__Lynx__)
#   if defined(IRIX64) || (__GNUG__>=3)
   handle.sa_handler = SigUsr1;
#   else
   handle.sa_handler = (void (*)(...))SigUsr1;
#   endif
#else
   handle.sa_handler = SigUsr1;
#endif
   sigaction(SIGINT,  &ignore, &saveintr);
   sigaction(SIGQUIT, &ignore, &savequit);
   sigaction(SIGUSR1, &handle, &saveusr1);

   // Create child...

   int childpid;
   if ((childpid = fork()) < 0) {
      fprintf(stderr, "%s: error forking child\n", argv[0]);
      return 1;
   } else if (childpid > 0) {
      if (!gNoLogo)
         WaitLogo();
      WaitChild(childpid);
   }

   // Continue with child...

   // Restore original signal actions
   sigaction(SIGINT,  &saveintr, 0);
   sigaction(SIGQUIT, &savequit, 0);
   sigaction(SIGUSR1, &saveusr1, 0);

   // Close X display connection
   CloseDisplay();

   // Child is going to overlay itself with the actual ROOT module...

   // Build argv vector
#ifdef ROOTBINDIR
   sprintf(arg0, "%s/%s", ROOTBINDIR, ROOTBINARY);
#else
   sprintf(arg0, "%s/bin/%s", getenv("ROOTSYS"), ROOTBINARY);
#endif
   argvv[0] = arg0;
   argvv[1] = (char *) "-splash";

   int iargc = argc;
   if (iargc > kMAXARGS-2) iargc = kMAXARGS-2;
   for (i = 1; i < iargc; i++)
      argvv[1+i] = argv[i];
   argvv[1+i] = 0;

   // Make sure library path is set
   SetLibraryPath();

   // Execute actual ROOT module
   execv(arg0, argvv);

   // Exec failed
#ifndef ROOTBINDIR
   fprintf(stderr,
           "%s: can't start ROOT -- check that %s/bin/%s exists!\n",
           argv[0], getenv("ROOTSYS"), ROOTBINARY);
#else
   fprintf(stderr, "%s: can't start ROOT -- check that %s/%s exists!\n",
           argv[0], ROOTBINDIR, ROOTBINARY);
#endif

   return 1;
}

<|endoftext|>


<commit_before><commit_msg>Implementing hal functions<commit_after>#include "ros/ros.h"
#include "hal/DigitalOutput.h"
#include "hal/DigitalInput.h"
#include "hal/AnalogInput.h"
#include "hal/PWM.h"

bool pwmHandler(PWM::Request &request, PWM::Response &response){
  //The response here is empty
  ROS_INFO("PWM Request: %i @ pin %i", request.value, request.pin);
}

int main(int argc, char **argv){
  ros::init(argc, argv, "hal");
  ros::NodeHandler handler;

  ros::Rate loopTimer(15);
  while(ros::ok()){
    loopTimer.sleep();
  }
}
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not 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 bpied warranties, including, but not limited to, the bpied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/

namespace cv { namespace gpu {

    struct BrdReflect101
    {
        BrdReflect101(int len) : last(len - 1) {}

        __device__ int idx_low(int i) const
        {
            return abs(i);
        }

        __device__ int idx_high(int i) const
        {
            return last - abs(i - last);
        }

        __device__ int idx(int i) const
        {
            return i <= last ? idx_low(i) : idx_high(i);
        }

        bool is_range_safe(int mini, int maxi) const
        {
            return -last <= mini && maxi <= 2 * last;
        }

        int last;
    };

    template <typename T>
    struct BrdRowReflect101: BrdReflect101
    {
        BrdRowReflect101(int len) : BrdReflect101(len) {}

        __device__ float at_low(int i, const T* data) const
        {
            return data[idx_low(i)];
        }

        __device__ float at_high(int i, const T* data) const
        {
            return data[idx_high(i)];
        }
    };

    template <typename T>
    struct BrdColReflect101: BrdReflect101
    {
        BrdColReflect101(int len, int step) : BrdReflect101(len), step(step) {}

        __device__ float at_low(int i, const T* data) const
        {
            return data[idx_low(i) * step];
        }

        __device__ float at_high(int i, const T* data) const
        {
            return data[idx_high(i) * step];
        }

        int step;
    };

}}<commit_msg>updated BrdReflect101 in gpu module<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not 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 bpied warranties, including, but not limited to, the bpied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/

namespace cv { namespace gpu {

    struct BrdReflect101
    {
        BrdReflect101(int len) : last(len - 1) {}

        __device__ int idx_low(int i) const
        {
            return abs(i);
        }

        __device__ int idx_high(int i) const
        {
            return last - abs(last - i);
        }

        __device__ int idx(int i) const
        {
            return abs(idx_high(i));
        }

        bool is_range_safe(int mini, int maxi) const
        {
            return -last <= mini && maxi <= 2 * last;
        }

        int last;
    };

    template <typename T>
    struct BrdRowReflect101: BrdReflect101
    {
        BrdRowReflect101(int len) : BrdReflect101(len) {}

        __device__ float at_low(int i, const T* data) const
        {
            return data[idx_low(i)];
        }

        __device__ float at_high(int i, const T* data) const
        {
            return data[idx_high(i)];
        }
    };

    template <typename T>
    struct BrdColReflect101: BrdReflect101
    {
        BrdColReflect101(int len, int step) : BrdReflect101(len), step(step) {}

        __device__ float at_low(int i, const T* data) const
        {
            return data[idx_low(i) * step];
        }

        __device__ float at_high(int i, const T* data) const
        {
            return data[idx_high(i) * step];
        }

        int step;
    };

    struct BrdReplicate
    {
        BrdReplicate(int len) : last(len - 1) {}

        __device__ int idx_low(int i) const
        {
            return max(i, 0);
        }

        __device__ int idx_high(int i) const
        {
            return min(i, last);
        }

        __device__ int idx(int i) const
        {
            return min(max(i, last), 0);
        }

        bool is_range_safe(int mini, int maxi) const
        {
            return true;
        }

        int last;
    };

    template <typename T>
    struct BrdRowReplicate: BrdReplicate
    {
        BrdRowReplicate(int len) : BrdReplicate(len) {}

        __device__ float at_low(int i, const T* data) const
        {
            return data[idx_low(i)];
        }

        __device__ float at_high(int i, const T* data) const
        {
            return data[idx_high(i)];
        }
    };

    template <typename T>
    struct BrdColReplicate: BrdReplicate
    {
        BrdColReplicate(int len, int step) : BrdReplicate(len), step(step) {}

        __device__ float at_low(int i, const T* data) const
        {
            return data[idx_low(i) * step];
        }

        __device__ float at_high(int i, const T* data) const
        {
            return data[idx_high(i) * step];
        }

        int step;
    };

}}<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2016-2021 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. 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.
 *
 * 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 <modules/plottinggl/plottingglmodule.h>
#include <modules/plotting/plottingmodule.h>

#include <inviwo/core/common/inviwoapplication.h>
#include <modules/opengl/shader/shadermanager.h>

#include <modules/plottinggl/processors/axisrenderprocessor.h>
#include <modules/plottinggl/processors/colorscalelegend.h>
#include <modules/plottinggl/processors/imageplotprocessor.h>
#include <modules/plottinggl/processors/parallelcoordinates/parallelcoordinates.h>
#include <modules/plottinggl/processors/scatterplotmatrixprocessor.h>
#include <modules/plottinggl/processors/scatterplotprocessor.h>
#include <modules/plottinggl/processors/volumeaxis.h>
#include <modules/plottinggl/processors/persistencediagramplotprocessor.h>
#include <modules/plottinggl/processors/parallelcoordinates/pcpaxissettings.h>

#include <modules/plottinggl/datavisualizer/pcpdataframevisualizer.h>
#include <modules/plottinggl/datavisualizer/scatterplotdataframevisualizer.h>

namespace inviwo {

PlottingGLModule::PlottingGLModule(InviwoApplication* app) : InviwoModule(app, "PlottingGL") {

    ShaderManager::getPtr()->addShaderSearchPath(getPath(ModulePath::GLSL));

    registerProcessor<plot::AxisRenderProcessor>();
    registerProcessor<plot::ColorScaleLegend>();
    registerProcessor<plot::ImagePlotProcessor>();
    registerProcessor<plot::ParallelCoordinates>();
    registerProcessor<plot::PersistenceDiagramPlotProcessor>();
    registerProcessor<plot::ScatterPlotMatrixProcessor>();
    registerProcessor<plot::ScatterPlotProcessor>();
    registerProcessor<plot::VolumeAxis>();

    registerProperty<plot::ScatterPlotGL::Properties>();
    registerProperty<plot::PCPAxisSettings>();

    registerDataVisualizer(std::make_unique<PCPDataFrameVisualizer>(app));
    registerDataVisualizer(std::make_unique<ScatterPlotDataFrameVisualizer>(app));
}

int PlottingGLModule::getVersion() const { return 2; }

std::unique_ptr<VersionConverter> PlottingGLModule::getConverter(int version) const {
    return std::make_unique<Converter>(version);
}

PlottingGLModule::Converter::Converter(int version) : version_(version) {}

bool PlottingGLModule::Converter::convert(TxElement* root) {
    bool res = false;
    switch (version_) {
        case 0: {
            TraversingVersionConverter conv{[&](TxElement* node) -> bool {
                std::string key;
                node->GetValue(&key);
                if (key != "Processor") return true;
                const auto type = node->GetAttributeOrDefault("type", "");
                if (type != "org.inviwo.ParallelCoordinates") return true;

                auto props = xml::getElement(node, "Properties");
                if (auto tf = xml::getElement(node,
                                              "Properties/Property&identifier=colors/Properties/"
                                              "Property&identifier=tf")) {
                    props->InsertEndChild(*tf);
                }

                if (auto color = xml::getElement(node,
                                                 "Properties/Property&identifier=colors/Properties/"
                                                 "Property&identifier=selectedColorAxis")) {
                    props->InsertEndChild(*color);
                }

                return true;
            }};

            res |= conv.convert(root);
            [[fallthrough]];
        }
        case 1: {
            TraversingVersionConverter conv{[&](TxElement* node) -> bool {
                std::string key;
                node->GetValue(&key);
                if (key != "Processor") return true;
                const auto type = node->GetAttributeOrDefault("type", "");
                if (type != "org.inviwo.ParallelCoordinates") return true;

                auto props = xml::getElement(node, "Properties");
                TxElement compNode{"Property"};
                compNode.SetAttribute("type", "org.inviwo.DataFrameColormapProperty");
                compNode.SetAttribute("identifier", "colormap");

                TxElement propNode{"Properties"};
                // Move old TF and selected color into new DataFrameColormapProperty
                if (auto tf = xml::getElement(props, "Property&identifier=tf")) {
                    propNode.InsertEndChild(*tf);
                }

                if (auto color = xml::getElement(props, "Property&identifier=selectedColorAxis")) {
                    propNode.InsertEndChild(*color);
                }

                // Override colormap so that the old one is used
                TxElement boolNode{"Property"};
                boolNode.SetAttribute("type", "org.inviwo.BoolProperty");
                boolNode.SetAttribute("identifier", "overrideColormap");

                TxElement valNode{"value"};
                valNode.SetAttribute("content", "1");

                boolNode.InsertEndChild(valNode);
                propNode.InsertEndChild(boolNode);
                compNode.InsertEndChild(propNode);
                props->InsertEndChild(compNode);

                return true;
            }};
            res |= conv.convert(root);

            return res;
        }

        default:
            return false;  // No changes
    }
}

}  // namespace inviwo
<commit_msg>PlottingGL: scatter plot version conversion<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2016-2021 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. 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.
 *
 * 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 <modules/plottinggl/plottingglmodule.h>
#include <modules/plotting/plottingmodule.h>

#include <inviwo/core/common/inviwoapplication.h>
#include <modules/opengl/shader/shadermanager.h>

#include <modules/plottinggl/processors/axisrenderprocessor.h>
#include <modules/plottinggl/processors/colorscalelegend.h>
#include <modules/plottinggl/processors/imageplotprocessor.h>
#include <modules/plottinggl/processors/parallelcoordinates/parallelcoordinates.h>
#include <modules/plottinggl/processors/scatterplotmatrixprocessor.h>
#include <modules/plottinggl/processors/scatterplotprocessor.h>
#include <modules/plottinggl/processors/volumeaxis.h>
#include <modules/plottinggl/processors/persistencediagramplotprocessor.h>
#include <modules/plottinggl/processors/parallelcoordinates/pcpaxissettings.h>

#include <modules/plottinggl/datavisualizer/pcpdataframevisualizer.h>
#include <modules/plottinggl/datavisualizer/scatterplotdataframevisualizer.h>

namespace inviwo {

PlottingGLModule::PlottingGLModule(InviwoApplication* app) : InviwoModule(app, "PlottingGL") {

    ShaderManager::getPtr()->addShaderSearchPath(getPath(ModulePath::GLSL));

    registerProcessor<plot::AxisRenderProcessor>();
    registerProcessor<plot::ColorScaleLegend>();
    registerProcessor<plot::ImagePlotProcessor>();
    registerProcessor<plot::ParallelCoordinates>();
    registerProcessor<plot::PersistenceDiagramPlotProcessor>();
    registerProcessor<plot::ScatterPlotMatrixProcessor>();
    registerProcessor<plot::ScatterPlotProcessor>();
    registerProcessor<plot::VolumeAxis>();

    registerProperty<plot::ScatterPlotGL::Properties>();
    registerProperty<plot::PCPAxisSettings>();

    registerDataVisualizer(std::make_unique<PCPDataFrameVisualizer>(app));
    registerDataVisualizer(std::make_unique<ScatterPlotDataFrameVisualizer>(app));
}

int PlottingGLModule::getVersion() const { return 3; }

std::unique_ptr<VersionConverter> PlottingGLModule::getConverter(int version) const {
    return std::make_unique<Converter>(version);
}

PlottingGLModule::Converter::Converter(int version) : version_(version) {}

bool PlottingGLModule::Converter::convert(TxElement* root) {
    bool res = false;
    switch (version_) {
        case 0: {
            TraversingVersionConverter conv{[&](TxElement* node) -> bool {
                std::string key;
                node->GetValue(&key);
                if (key != "Processor") return true;
                const auto type = node->GetAttributeOrDefault("type", "");
                if (type != "org.inviwo.ParallelCoordinates") return true;

                auto props = xml::getElement(node, "Properties");
                if (auto tf = xml::getElement(node,
                                              "Properties/Property&identifier=colors/Properties/"
                                              "Property&identifier=tf")) {
                    props->InsertEndChild(*tf);
                    res = true;
                }

                if (auto color = xml::getElement(node,
                                                 "Properties/Property&identifier=colors/Properties/"
                                                 "Property&identifier=selectedColorAxis")) {
                    props->InsertEndChild(*color);
                    res = true;
                }

                return true;
            }};

            conv.convert(root);
            [[fallthrough]];
        }
        case 1: {
            TraversingVersionConverter conv{[&](TxElement* node) -> bool {
                std::string key;
                node->GetValue(&key);
                if (key != "Processor") return true;
                const auto type = node->GetAttributeOrDefault("type", "");
                if (type != "org.inviwo.ParallelCoordinates") return true;

                auto props = xml::getElement(node, "Properties");
                TxElement compNode{"Property"};
                compNode.SetAttribute("type", "org.inviwo.DataFrameColormapProperty");
                compNode.SetAttribute("identifier", "colormap");

                TxElement propNode{"Properties"};
                // Move old TF and selected color into new DataFrameColormapProperty
                if (auto tf = xml::getElement(props, "Property&identifier=tf")) {
                    propNode.InsertEndChild(*tf);
                }

                if (auto color = xml::getElement(props, "Property&identifier=selectedColorAxis")) {
                    propNode.InsertEndChild(*color);
                }

                // Override colormap so that the old one is used
                TxElement boolNode{"Property"};
                boolNode.SetAttribute("type", "org.inviwo.BoolProperty");
                boolNode.SetAttribute("identifier", "overrideColormap");

                TxElement valNode{"value"};
                valNode.SetAttribute("content", "1");

                boolNode.InsertEndChild(valNode);
                propNode.InsertEndChild(boolNode);
                compNode.InsertEndChild(propNode);
                props->InsertEndChild(compNode);

                res = true;

                return true;
            }};
            conv.convert(root);
            [[fallthrough]];
        }
        case 2: {
            TraversingVersionConverter conv{[&](TxElement* node) -> bool {
                std::string key;
                node->GetValue(&key);
                if (key != "Processor") return true;
                const auto type = node->GetAttributeOrDefault("type", "");
                if ((type != "org.inviwo.ScatterPlotProcessor") &&
                    (type != "org.inviwo.ScatterPlotMatrixProcessor")) {
                    return true;
                }

                std::string_view identifier = (type == "org.inviwo.ScatterPlotProcessor")
                                                  ? "scatterplot"
                                                  : "scatterPlotproperties";

                if (auto plot = xml::getElement(
                        node,
                        fmt::format("Properties/Property&identifier={}/Properties", identifier))) {
                    // Rename color property
                    if (auto color = xml::getElement(plot, "Property&identifier=color")) {
                        color->SetAttribute("identifier", "defaultColor");
                    }

                    // Move hovering bool property to checked state of a BoolComposite
                    {
                        TxElement compNode{"Property"};
                        compNode.SetAttribute("type", "org.inviwo.BoolCompositeProperty");
                        compNode.SetAttribute("identifier", "showHighlighted");

                        TxElement propNode{"Properties"};
                        if (auto hovered = xml::getElement(plot, "Property&identifier=hovering")) {
                            hovered->SetAttribute("identifier", "checked");
                            hovered->SetAttribute("displayName", "");
                            propNode.InsertEndChild(*hovered);
                        }
                        // Change type of hover color to vec3, move to composite
                        if (auto highlightColor =
                                xml::getElement(plot, "Property&identifier=hoverColor")) {
                            highlightColor->SetAttribute("type", "org.inviwo.FloatVec3Property");
                            highlightColor->SetAttribute("identifier", "highlightColor");

                            propNode.InsertEndChild(*highlightColor);

                            if (auto value = xml::getElement(highlightColor, "value")) {
                                auto str = value->GetAttributeOrDefault("w", "1.0");

                                TxElement alphaNode{"Property"};
                                alphaNode.SetAttribute("type", "org.inviwo.FloatProperty");
                                alphaNode.SetAttribute("identifier", "highlightAlpha");
                                TxElement valueNode("value");
                                valueNode.SetAttribute("content", str);

                                alphaNode.InsertEndChild(valueNode);
                                propNode.InsertEndChild(alphaNode);
                            }
                        }
                        compNode.InsertEndChild(propNode);
                        plot->InsertEndChild(compNode);
                    }

                    // Change type of selection color to vec3, move to composite
                    {
                        TxElement compNode{"Property"};
                        compNode.SetAttribute("type", "org.inviwo.BoolCompositeProperty");
                        compNode.SetAttribute("identifier", "showSelected");

                        TxElement propNode{"Properties"};
                        if (auto highlightColor =
                                xml::getElement(plot, "Property&identifier=selectionColor")) {
                            highlightColor->SetAttribute("type", "org.inviwo.FloatVec3Property");
                            highlightColor->SetAttribute("identifier", "highlightColor");

                            propNode.InsertEndChild(*highlightColor);

                            if (auto value = xml::getElement(highlightColor, "value")) {
                                auto str = value->GetAttributeOrDefault("w", "1.0");

                                TxElement alphaNode{"Property"};
                                alphaNode.SetAttribute("type", "org.inviwo.FloatProperty");
                                alphaNode.SetAttribute("identifier", "selectionAlpha");
                                TxElement valueNode("value");
                                valueNode.SetAttribute("content", str);

                                alphaNode.InsertEndChild(valueNode);
                                propNode.InsertEndChild(alphaNode);
                            }
                        }
                        compNode.InsertEndChild(propNode);
                        plot->InsertEndChild(compNode);
                    }
                    res = true;
                }
                return true;
            }};
            conv.convert(root);
            return res;
        }

        default:
            return false;  // No changes
    }
}

}  // namespace inviwo
<|endoftext|>