<commit_before>#include <cassert>

#include "ee/ads/NullInterstitialAd.hpp"
#include "ee/ads/NullRewardedVideo.hpp"
#include "ee/ads/internal/MediationManager.hpp"
#include "ee/core/Logger.hpp"
#include "ee/core/MessageBridge.hpp"
#include "ee/core/Utils.hpp"
#include "ee/ironsource/IronSourceBridge.hpp"
#include "ee/ironsource/internal/IronSourceInterstitialAd.hpp"
#include "ee/ironsource/internal/IronSourceRewardedVideo.hpp"

#include <ee/nlohmann/json.hpp>

namespace ee {
namespace ironsource {
using Self = IronSource;

namespace {
// clang-format off
constexpr auto k__initialize        = "IronSource_initialize";
constexpr auto k__hasRewardedVideo  = "IronSource_hasRewardedVideo";
constexpr auto k__showRewardedVideo = "IronSource_showRewardedVideo";

constexpr auto k__loadInterstitial   = "IronSource_loadInterstitial";
constexpr auto k__hasInterstitial   = "IronSource_hasInterstitial";
constexpr auto k__showInterstitial  = "IronSource_showInterstitial";
constexpr auto k__onRewarded        = "IronSource_onRewarded";
constexpr auto k__onFailed          = "IronSource_onFailed";
constexpr auto k__onOpened          = "IronSource_onOpened";
constexpr auto k__onClosed          = "IronSource_onClosed";

constexpr auto k__onInterstitialFailed         = "IronSource_onInterstitialFailed";
constexpr auto k__onInterstitialOpened          = "IronSource_onInterstitialOpened";
constexpr auto k__onInterstitialClosed          = "IronSource_onInterstitialClosed";
// clang-format on
} // namespace

Self::IronSource()
    : Self(Logger::getSystemLogger()) {}

Self::IronSource(const Logger& logger)
    : bridge_(MessageBridge::getInstance())
    , _closeTimeout(0.0f)
    , logger_(logger) {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    rewarded_ = false;

    bridge_.registerHandler(
        [this](const std::string& message) {
            onRewarded(message);
            return "";
        },
        k__onRewarded);
    bridge_.registerHandler(
        [this](const std::string& message) {
            onFailed();
            return "";
        },
        k__onFailed);
    bridge_.registerHandler(
        [this](const std::string& message) {
            onOpened();
            return "";
        },
        k__onOpened);
    bridge_.registerHandler(
        [this](const std::string& message) {
            onClosed();
            return "";
        },
        k__onClosed);

    bridge_.registerHandler(
        [this](const std::string& message) {
            onInterstitialOpened();
            return "";
        },
        k__onInterstitialOpened);

    bridge_.registerHandler(
        [this](const std::string& message) {
            onInterstitialFailed();
            return "";
        },
        k__onInterstitialFailed);

    bridge_.registerHandler(
        [this](const std::string& message) {
            onInterstitialClosed();
            return "";
        },
        k__onInterstitialClosed);

    handlerLock_ = std::make_unique<core::SpinLock>();
}

Self::~IronSource() {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    bridge_.deregisterHandler(k__onRewarded);
    bridge_.deregisterHandler(k__onFailed);
    bridge_.deregisterHandler(k__onOpened);
    bridge_.deregisterHandler(k__onClosed);

    bridge_.deregisterHandler(k__onInterstitialOpened);
    bridge_.deregisterHandler(k__onInterstitialFailed);
    bridge_.deregisterHandler(k__onInterstitialClosed);
}

void Self::initialize(const std::string& gameId) {
    logger_.debug("%s: gameId = %s", __PRETTY_FUNCTION__, gameId.c_str());
    bridge_.call(k__initialize, gameId);
}

std::shared_ptr<IRewardedVideo>
Self::createRewardedVideo(const std::string& placementId) {
    logger_.debug("%s: placementId = %s", __PRETTY_FUNCTION__,
                  placementId.c_str());
    if (rewardedVideos_.count(placementId) != 0) {
        return std::make_shared<NullRewardedVideo>(logger_);
    }
    auto result = new RewardedVideo(logger_, this, placementId);
    rewardedVideos_[placementId] = result;
    return std::shared_ptr<IRewardedVideo>(result);
}

bool Self::destroyRewardedVideo(const std::string& placementId) {
    logger_.debug("%s: placementId = %s", __PRETTY_FUNCTION__,
                  placementId.c_str());
    if (rewardedVideos_.count(placementId) == 0) {
        return false;
    }
    rewardedVideos_.erase(placementId);
    return true;
}

std::shared_ptr<IInterstitialAd>
Self::createInterstitialAd(const std::string& placementId) {
    logger_.debug("%s: placementId = %s", __PRETTY_FUNCTION__,
                  placementId.c_str());
    if (interstitialAds_.count(placementId) != 0) {
        return std::make_shared<NullInterstitialAd>();
    }
    auto result = new InterstitialAd(logger_, this, placementId);
    interstitialAds_[placementId] = result;
    return std::shared_ptr<IInterstitialAd>(result);
}

bool Self::destroyInterstitialAd(const std::string& placementId) {
    logger_.debug("%s: placementId = %s", __PRETTY_FUNCTION__,
                  placementId.c_str());
    if (interstitialAds_.count(placementId) == 0) {
        return false;
    }
    interstitialAds_.erase(placementId);
    return true;
}

void Self::loadInterstitial() {
    bridge_.call(k__loadInterstitial);
}

bool Self::hasInterstitial() const {
    auto response = bridge_.call(k__hasInterstitial);
    return core::toBool(response);
}

bool Self::showInterstitial(const std::string& placementId) {
    if (not hasInterstitial()) {
        return false;
    }

    bridge_.call(k__showInterstitial, placementId);
    return true;
}

bool Self::hasRewardedVideo() const {
    auto response = bridge_.call(k__hasRewardedVideo);
    return core::toBool(response);
}

bool Self::showRewardedVideo(const std::string& placementId) {
    if (not hasRewardedVideo()) {
        return false;
    }
    rewarded_ = false;
    _shouldDoRewardInGame = false;
    bridge_.call(k__showRewardedVideo, placementId);
    return true;
}

void Self::onRewarded(const std::string& placementId) {
    logger_.debug("%s: placementId = %s", __PRETTY_FUNCTION__,
                  placementId.c_str());
    rewarded_ = true;
    if (_shouldDoRewardInGame) {
        doRewardInGame();
    }
    _shouldDoRewardInGame = true;
}

void Self::onFailed() {
    logger_.debug("%s", __PRETTY_FUNCTION__);

    _shouldDoRewardInGame = true;
    onClosed();
}

void Self::onOpened() {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    rewarded_ = false;
    _didRewardFlag = false;
}

void Self::onClosed() {
    logger_.debug("%s", __PRETTY_FUNCTION__);

    if (_shouldDoRewardInGame) {
        doRewardInGame();
    } else {
        // wait for reward
        // if out of time just callback failed
        ee::core::runFunctionDelay(
            [this] {
                std::lock_guard<core::SpinLock> guard(*handlerLock_);
                rewarded_ = false;
                doRewardInGame();
            },
            _closeTimeout);
    }
    _shouldDoRewardInGame = true;
}

void Self::doRewardInGame() {
    if (_didRewardFlag) {
        return;
    }

    logger_.debug("%s", __PRETTY_FUNCTION__);
    auto&& mediation = ads::MediationManager::getInstance();

    // Other mediation network.
    auto wasInterstitialAd = mediation.setInterstitialAdDone();
    auto wasRewardedVideo = mediation.finishRewardedVideo(rewarded_);

    _didRewardFlag = true;
    assert(wasInterstitialAd || wasRewardedVideo);
}

#pragma mark - For Interstitial

void Self::onInterstitialOpened() {
    logger_.debug("%s", __PRETTY_FUNCTION__);
}

void Self::onInterstitialFailed() {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    onInterstitialClosed();
}

void Self::onInterstitialClosed() {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    //    auto&& mediation = ads::MediationManager::getInstance();
    //
    //    auto successful = mediation.finishInterstitialAd();
    //    assert(successful);
    _shouldDoRewardInGame = true;
    onClosed();
}

#pragma mark - Config

void Self::setCloseTimeout(float timeout) {
    _closeTimeout = timeout;
}
} // namespace ironsource
} // namespace ee
<commit_msg>- fix build ios<commit_after>#include <cassert>

#include "ee/ads/NullInterstitialAd.hpp"
#include "ee/ads/NullRewardedVideo.hpp"
#include "ee/ads/internal/MediationManager.hpp"
#include "ee/core/Logger.hpp"
#include "ee/core/MessageBridge.hpp"
#include "ee/core/Utils.hpp"
#include "ee/core/internal/SpinLock.hpp"
#include "ee/ironsource/IronSourceBridge.hpp"
#include "ee/ironsource/internal/IronSourceInterstitialAd.hpp"
#include "ee/ironsource/internal/IronSourceRewardedVideo.hpp"

#include <ee/nlohmann/json.hpp>

namespace ee {
namespace ironsource {
using Self = IronSource;

namespace {
// clang-format off
constexpr auto k__initialize        = "IronSource_initialize";
constexpr auto k__hasRewardedVideo  = "IronSource_hasRewardedVideo";
constexpr auto k__showRewardedVideo = "IronSource_showRewardedVideo";

constexpr auto k__loadInterstitial   = "IronSource_loadInterstitial";
constexpr auto k__hasInterstitial   = "IronSource_hasInterstitial";
constexpr auto k__showInterstitial  = "IronSource_showInterstitial";
constexpr auto k__onRewarded        = "IronSource_onRewarded";
constexpr auto k__onFailed          = "IronSource_onFailed";
constexpr auto k__onOpened          = "IronSource_onOpened";
constexpr auto k__onClosed          = "IronSource_onClosed";

constexpr auto k__onInterstitialFailed         = "IronSource_onInterstitialFailed";
constexpr auto k__onInterstitialOpened          = "IronSource_onInterstitialOpened";
constexpr auto k__onInterstitialClosed          = "IronSource_onInterstitialClosed";
// clang-format on
} // namespace

Self::IronSource()
    : Self(Logger::getSystemLogger()) {}

Self::IronSource(const Logger& logger)
    : bridge_(MessageBridge::getInstance())
    , _closeTimeout(0.0f)
    , logger_(logger) {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    rewarded_ = false;

    bridge_.registerHandler(
        [this](const std::string& message) {
            onRewarded(message);
            return "";
        },
        k__onRewarded);
    bridge_.registerHandler(
        [this](const std::string& message) {
            onFailed();
            return "";
        },
        k__onFailed);
    bridge_.registerHandler(
        [this](const std::string& message) {
            onOpened();
            return "";
        },
        k__onOpened);
    bridge_.registerHandler(
        [this](const std::string& message) {
            onClosed();
            return "";
        },
        k__onClosed);

    bridge_.registerHandler(
        [this](const std::string& message) {
            onInterstitialOpened();
            return "";
        },
        k__onInterstitialOpened);

    bridge_.registerHandler(
        [this](const std::string& message) {
            onInterstitialFailed();
            return "";
        },
        k__onInterstitialFailed);

    bridge_.registerHandler(
        [this](const std::string& message) {
            onInterstitialClosed();
            return "";
        },
        k__onInterstitialClosed);

    handlerLock_ = std::make_unique<core::SpinLock>();
}

Self::~IronSource() {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    bridge_.deregisterHandler(k__onRewarded);
    bridge_.deregisterHandler(k__onFailed);
    bridge_.deregisterHandler(k__onOpened);
    bridge_.deregisterHandler(k__onClosed);

    bridge_.deregisterHandler(k__onInterstitialOpened);
    bridge_.deregisterHandler(k__onInterstitialFailed);
    bridge_.deregisterHandler(k__onInterstitialClosed);
}

void Self::initialize(const std::string& gameId) {
    logger_.debug("%s: gameId = %s", __PRETTY_FUNCTION__, gameId.c_str());
    bridge_.call(k__initialize, gameId);
}

std::shared_ptr<IRewardedVideo>
Self::createRewardedVideo(const std::string& placementId) {
    logger_.debug("%s: placementId = %s", __PRETTY_FUNCTION__,
                  placementId.c_str());
    if (rewardedVideos_.count(placementId) != 0) {
        return std::make_shared<NullRewardedVideo>(logger_);
    }
    auto result = new RewardedVideo(logger_, this, placementId);
    rewardedVideos_[placementId] = result;
    return std::shared_ptr<IRewardedVideo>(result);
}

bool Self::destroyRewardedVideo(const std::string& placementId) {
    logger_.debug("%s: placementId = %s", __PRETTY_FUNCTION__,
                  placementId.c_str());
    if (rewardedVideos_.count(placementId) == 0) {
        return false;
    }
    rewardedVideos_.erase(placementId);
    return true;
}

std::shared_ptr<IInterstitialAd>
Self::createInterstitialAd(const std::string& placementId) {
    logger_.debug("%s: placementId = %s", __PRETTY_FUNCTION__,
                  placementId.c_str());
    if (interstitialAds_.count(placementId) != 0) {
        return std::make_shared<NullInterstitialAd>();
    }
    auto result = new InterstitialAd(logger_, this, placementId);
    interstitialAds_[placementId] = result;
    return std::shared_ptr<IInterstitialAd>(result);
}

bool Self::destroyInterstitialAd(const std::string& placementId) {
    logger_.debug("%s: placementId = %s", __PRETTY_FUNCTION__,
                  placementId.c_str());
    if (interstitialAds_.count(placementId) == 0) {
        return false;
    }
    interstitialAds_.erase(placementId);
    return true;
}

void Self::loadInterstitial() {
    bridge_.call(k__loadInterstitial);
}

bool Self::hasInterstitial() const {
    auto response = bridge_.call(k__hasInterstitial);
    return core::toBool(response);
}

bool Self::showInterstitial(const std::string& placementId) {
    if (not hasInterstitial()) {
        return false;
    }

    bridge_.call(k__showInterstitial, placementId);
    return true;
}

bool Self::hasRewardedVideo() const {
    auto response = bridge_.call(k__hasRewardedVideo);
    return core::toBool(response);
}

bool Self::showRewardedVideo(const std::string& placementId) {
    if (not hasRewardedVideo()) {
        return false;
    }
    rewarded_ = false;
    _shouldDoRewardInGame = false;
    bridge_.call(k__showRewardedVideo, placementId);
    return true;
}

void Self::onRewarded(const std::string& placementId) {
    logger_.debug("%s: placementId = %s", __PRETTY_FUNCTION__,
                  placementId.c_str());
    rewarded_ = true;
    if (_shouldDoRewardInGame) {
        doRewardInGame();
    }
    _shouldDoRewardInGame = true;
}

void Self::onFailed() {
    logger_.debug("%s", __PRETTY_FUNCTION__);

    _shouldDoRewardInGame = true;
    onClosed();
}

void Self::onOpened() {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    rewarded_ = false;
    _didRewardFlag = false;
}

void Self::onClosed() {
    logger_.debug("%s", __PRETTY_FUNCTION__);

    if (_shouldDoRewardInGame) {
        doRewardInGame();
    } else {
        // wait for reward
        // if out of time just callback failed
        ee::core::runFunctionDelay(
            [this] {
                std::lock_guard<core::SpinLock> guard(*handlerLock_);
                rewarded_ = false;
                doRewardInGame();
            },
            _closeTimeout);
    }
    _shouldDoRewardInGame = true;
}

void Self::doRewardInGame() {
    if (_didRewardFlag) {
        return;
    }

    logger_.debug("%s", __PRETTY_FUNCTION__);
    auto&& mediation = ads::MediationManager::getInstance();

    // Other mediation network.
    auto wasInterstitialAd = mediation.setInterstitialAdDone();
    auto wasRewardedVideo = mediation.finishRewardedVideo(rewarded_);

    _didRewardFlag = true;
    assert(wasInterstitialAd || wasRewardedVideo);
}

#pragma mark - For Interstitial

void Self::onInterstitialOpened() {
    logger_.debug("%s", __PRETTY_FUNCTION__);
}

void Self::onInterstitialFailed() {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    onInterstitialClosed();
}

void Self::onInterstitialClosed() {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    //    auto&& mediation = ads::MediationManager::getInstance();
    //
    //    auto successful = mediation.finishInterstitialAd();
    //    assert(successful);
    _shouldDoRewardInGame = true;
    onClosed();
}

#pragma mark - Config

void Self::setCloseTimeout(float timeout) {
    _closeTimeout = timeout;
}
} // namespace ironsource
} // namespace ee
<|endoftext|>


<commit_before>#include <test/unit/math/test_ad.hpp>
#include <limits>
#include <vector>

TEST(mathMixCore, atan2) {
  auto f = [](const auto& x1, const auto& x2) {
    using stan::math::atan2;
    return atan2(x1, x2);
  };
  double nan = std::numeric_limits<double>::quiet_NaN();
  stan::test::expect_ad(f, nan, 1.0);
  stan::test::expect_ad(f, 1.0, nan);
  stan::test::expect_ad(f, nan, nan);
  stan::test::expect_ad(f, 1.0, 1.0);
  stan::test::expect_ad(f, 1.5, 1.5);
  stan::test::expect_ad(f, 1.2, 3.9);
  stan::test::expect_ad(f, 0.5, 2.3);
}

TEST(mathMixScalFun, atan2) {
  auto f = [](const auto& x1, const auto& x2) {
    using stan::math::atan2;
    return atan2(x1, x2);
  };

  stan::test::expect_common_nonzero_binary(f);

  stan::test::expect_ad(f, 1.0, 1.0);
  stan::test::expect_ad(f, 1.0, 0.5);
  stan::test::expect_ad(f, 1.2, 3.9);
  stan::test::expect_ad(f, 7.5, 1.8);

  Eigen::VectorXd in1(3);
  in1 << 1.0, 1.0, 1.2;
  Eigen::VectorXd in2(3);
  in2 << 1.0, 0.5, 3.9;
  stan::test::expect_ad_vectorized_binary(f, in1, in2);
}

TEST(mathMixScalFun, atan2_varmat) {
  auto f = [](const auto& x1, const auto& x2) {
    using stan::math::atan2;
    return atan2(x1, x2);
  };

  Eigen::VectorXd in1(3);
  in1 << 0.5, 3.4, 5.2;
  Eigen::VectorXd in2(3);
  in2 << 3.3, 0.9, 6.7;
  stan::test::expect_ad_matvar(f, in1, in2);
  stan::test::expect_ad_matvar(f, in1(0), in2);
  stan::test::expect_ad_matvar(f, in1, in2(0));
}
<commit_msg>Update atan2_test.cpp<commit_after>#include <test/unit/math/test_ad.hpp>
#include <limits>
#include <vector>

TEST(mathMixCore, atan2) {
  auto f = [](const auto& x1, const auto& x2) {
    using stan::math::atan2;
    return atan2(x1, x2);
  };
  double nan = std::numeric_limits<double>::quiet_NaN();
  stan::test::expect_ad(f, nan, 1.0);
  stan::test::expect_ad(f, 1.0, nan);
  stan::test::expect_ad(f, nan, nan);
  stan::test::expect_ad(f, 1.0, 1.0);
  stan::test::expect_ad(f, 1.5, 1.5);
  stan::test::expect_ad(f, 1.2, 3.9);
  stan::test::expect_ad(f, 0.5, 2.3);
}

TEST(mathMixScalFun, atan2) {
  auto f = [](const auto& x1, const auto& x2) {
    using stan::math::atan2;
    return atan2(x1, x2);
  };

  // finite differences fails for
  // infinite inputs
  // stan::test::expect_common_nonzero_binary(f);

  stan::test::expect_ad(f, 1.0, 1.0);
  stan::test::expect_ad(f, 1.0, 0.5);
  stan::test::expect_ad(f, 1.2, 3.9);
  stan::test::expect_ad(f, 7.5, 1.8);

  Eigen::VectorXd in1(3);
  in1 << 1.0, 1.0, 1.2;
  Eigen::VectorXd in2(3);
  in2 << 1.0, 0.5, 3.9;
  stan::test::expect_ad_vectorized_binary(f, in1, in2);
}

TEST(mathMixScalFun, atan2_varmat) {
  auto f = [](const auto& x1, const auto& x2) {
    using stan::math::atan2;
    return atan2(x1, x2);
  };

  Eigen::VectorXd in1(3);
  in1 << 0.5, 3.4, 5.2;
  Eigen::VectorXd in2(3);
  in2 << 3.3, 0.9, 6.7;
  stan::test::expect_ad_matvar(f, in1, in2);
  stan::test::expect_ad_matvar(f, in1(0), in2);
  stan::test::expect_ad_matvar(f, in1, in2(0));
}
<|endoftext|>


<commit_before>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

classUI::classUI()
{

}

void classUI::run()
{
    bool runOn = true;
    string choice;
    do
    {
        cout << "Welcome to the Amazing Database: " << endl;
        cout << "-----------------------------------------------------------" << endl;
        cout << "add" << "\t" << "Add a person to the database" << endl;
        cout << "remove" << "\t" << "Remove a person from the database" << endl;
        cout << "view" << "\t" << "View the entire database" << endl;
        cout << "save" << "\t" << "Save the database" << endl;
        cout << "search" << "\t" << "Search the database" << endl;
        cout << "sort" << "\t" << "Sort the database by name/yearofbirth" << endl;
        cout << "exit" << "\t" << "Exit" << endl;
        cin >> choice;
        if (choice != "exit"){
           select(choice);
        }
        else{
            list.saveFile();
            runOn = false;
        }
    }while(runOn == true);
}

void classUI::select(string ch)
{
    if(ch == "add" || ch == "ADD" || ch == "Add" ){
        addPerson();
    }

    else if(ch == "view" || ch == "View" || ch == "VIEW")
    {
    viewAll();
    }
    else if(ch == "sort" || ch == "Sort" || ch == "SORT")
    {
        string sortcho;
        cout << "Enter 'name' or 'year' and then re-enter the 'view' command." << endl;
        cin >> sortcho;

        if(sortcho == "name" || sortcho == "Name" || sortcho == "NAME")
        {
            list.sortNames();
        }
        else if(sortcho == "year" || sortcho == "Year" || sortcho == "YEAR")
        {
            list.sortBirth();
        }
        viewAll();

    }
    else if(ch == "search" || ch == "Search" || ch == "SEARCH"){
        searching();
    }
    else if(ch == "remove" || ch == "Remove" || ch == "REMOVE"){
        remove();
    }
    else if(ch == "save" || ch == "Save" || ch == "SAVE"){
        save();
    }
    else if(ch == "yo" || ch == "Yo" || ch == "yO" || ch == "YO")
    {
        yo();
    }
    else
    {
        cout << "Invalid input" << endl;
    }
}
void classUI::view(int i)
{
    int nameSize  = list.getNameSize(i);
    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl;
    cout << "--------------------------------|-------|-------|-------------" << endl;

    cout << list.getName(i);
    if(nameSize > 0 && nameSize <= 7)
    {
        cout << "\t" << "\t" << "\t" << "\t";
    }
    else if(nameSize > 7 && nameSize <= 15)
    {
        cout << "\t" << "\t" << "\t";
    }
    else if(nameSize > 15 && nameSize <= 23)
    {
        cout << "\t" << "\t";
    }
    else if(nameSize > 23 && nameSize <= 31)
    {
        cout << "\t";
    }

    if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
    {
        cout << "|Male" << "\t";
    }
    else
    {
        cout << "|Female" << "\t";
    }
    cout  << "|" << list.getBirth(i);
    if(list.getDeath(i) == 0)
    {
        cout << "\t" << "|Still kickin'"  << endl;
    }
    else
    {
        cout << "\t" << "|" << list.getDeath(i)  << endl;
    }
    cout << list.getComment(i) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
}

void classUI::searching()
{

    cout << "----------Select any of the following options----------" << endl;
    cout << "What do you want to search for? " << endl;
    cout << "Name -- Searches for a name" << endl;
    cout << "Gender -- Searches for a Gender" << endl;
    cout << "Year -- Searches for a year born" << endl;
    search();
}
void classUI::addPerson()
{
    string name;
    char gender;
    int yearOfBirth = 0;
    int yearOfDeath = 0;
    string comment;

    cout << "Input Name: ";
    cin.ignore();
    std::getline(std::cin,name);
    cout << "Input gender (M/F): ";
    cin >> gender;
    if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
    {
       cout << "Input year of birth: ";
       cin >> yearOfBirth;
       cout << "Input year of death: ";
       cin >> yearOfDeath;
       cout << "Input a comment: ";
       cin >> comment;
    }
    else
    {
        cout << "Invalid gender! Try again." << endl;
        addPerson();
    }
    list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);

}

void classUI::search()
{
        string searchChoice;
        cin >> searchChoice;
        if (searchChoice == "Name" || searchChoice == "name" || searchChoice == "NAME")
        {
                string namesearch;
                cout << "Enter a name you want to search for: ";
                cin >> namesearch;

                for(int i = 0; i < list.getPersonsSize();++i)
                {
                    if(namesearch == list.getName(i))
                    {
                        namesearch =  list.getName(i);
                        view(i);
                    }
                }
                /*if ( eitthvad dot)
                {
                    cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl;
                }*/

        }
        else if (searchChoice == "Gender" || searchChoice == "GENDER" || searchChoice == "gender")
        {
                char gendersearch;

                cout << "Enter a Gender you want to search for: (m/f)";
                cin >> gendersearch;

                for(int i = 0; i < list.getPersonsSize();++i)
                {
                    if(gendersearch == list.getGender(i))
                    {
                        gendersearch = list.getGender(i);
                        view(i);
                        cout << "blabla" << endl;
                    }
                }
                /*
                if (eitthvad dot)
                {
                    cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl;
                }*/

        }
        else if (searchChoice == "year" || searchChoice == "YEAR" || searchChoice == "Year")
        {
                int yearsearch;
                cout << "Enter a Year you want to search for: ";
                cin >> yearsearch;

                for(int i = 0; i < list.getPersonsSize();++i)
                {
                    if(yearsearch == list.getBirth(i))
                    {
                        yearsearch = list.getBirth(i);

                         view(i);
                    }
                }/*
                if (eitthvad dot)
                {
                    cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl;
                }*/
           }
        else
        {
            cout << "Error reading input" << endl;
        }

}

void classUI::remove()
{
    string name;
    cout << "Enter a name of person that you want to remove: ";
    cin >> name;
    if (list.removePerson(name) == true)
    {
        cout << "Person removed!" << endl;
    }
    else
    {
        cout << "Person not found!" << endl;
    }
}
void classUI::save()
{
    list.saveFile();
}
void classUI::viewAll()
{
    for(int i = 0; i < list.getPersonsSize(); i++)
    {
        view(i);
    }
}
void classUI::yo()
{
    cout << endl;
    cout << "`8.`8888.      ,8'     ,o888888o.     " << endl;
    cout << " `8.`8888.    ,8'   . 8888     `88.   " << endl;
    cout << "  `8.`8888.  ,8'   ,8 8888       `8b  " << endl;
    cout << "   `8.`8888.,8'    88 8888        `8b " << endl;
    cout << "    `8.`88888'     88 8888         88 " << endl;
    cout << "     `8. 8888      88 8888         88 " << endl;
    cout << "      `8 8888      88 8888        ,8P " << endl;
    cout << "       8 8888      `8 8888       ,8P  " << endl;
    cout << "       8 8888       ` 8888     ,88'   " << endl;
    cout << "       8 8888          `8888888P'     " << endl;
    cout << endl;
}
<commit_msg>Setti inn error message fyrir search ef að hlutir finnast ekki<commit_after>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

classUI::classUI()
{

}

void classUI::run()
{
    bool runOn = true;
    string choice;
    do
    {
        cout << "Welcome to the Amazing Database: " << endl;
        cout << "-----------------------------------------------------------" << endl;
        cout << "add" << "\t" << "Add a person to the database" << endl;
        cout << "remove" << "\t" << "Remove a person from the database" << endl;
        cout << "view" << "\t" << "View the entire database" << endl;
        cout << "save" << "\t" << "Save the database" << endl;
        cout << "search" << "\t" << "Search the database" << endl;
        cout << "sort" << "\t" << "Sort the database by name/yearofbirth" << endl;
        cout << "exit" << "\t" << "Exit" << endl;
        cin >> choice;
        if (choice != "exit"){
           select(choice);
        }
        else{
            list.saveFile();
            runOn = false;
        }
    }while(runOn == true);
}

void classUI::select(string ch)
{
    if(ch == "add" || ch == "ADD" || ch == "Add" ){
        addPerson();
    }

    else if(ch == "view" || ch == "View" || ch == "VIEW")
    {
    viewAll();
    }
    else if(ch == "sort")
    {
        string sortcho;
        cout << "Enter 'name' or 'year' and then re-enter the 'view' command." << endl;
        cin >> sortcho;

        if(sortcho == "name")
        {
            list.sortNames();
        }
        else if(sortcho == "year")
        {
            list.sortBirth();
        }

    }
    else if(ch == "search" || ch == "Search" || ch == "SEARCH"){
        searching();
    }
    else if(ch == "remove" || ch == "Remove" || ch == "REMOVE"){
        remove();
    }
    else if(ch == "save" || ch == "Save" || ch == "SAVE"){
        save();
    }
    else if(ch == "yo" || ch == "Yo" || ch == "yO" || ch == "YO")
    {
        yo();
    }
    else
    {
        cout << "Invalid input" << endl;
    }
}
void classUI::view(int i)
{
    int nameSize  = list.getNameSize(i);
    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl;
    cout << "--------------------------------|-------|-------|-------------" << endl;

    cout << list.getName(i);
    if(nameSize > 0 && nameSize <= 7)
    {
        cout << "\t" << "\t" << "\t" << "\t";
    }
    else if(nameSize > 7 && nameSize <= 15)
    {
        cout << "\t" << "\t" << "\t";
    }
    else if(nameSize > 15 && nameSize <= 23)
    {
        cout << "\t" << "\t";
    }
    else if(nameSize > 23 && nameSize <= 31)
    {
        cout << "\t";
    }

    if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
    {
        cout << "|Male" << "\t";
    }
    else
    {
        cout << "|Female" << "\t";
    }
    cout  << "|" << list.getBirth(i);
    if(list.getDeath(i) == 0)
    {
        cout << "\t" << "|Still kickin'"  << endl;
    }
    else
    {
        cout << "\t" << "|" << list.getDeath(i)  << endl;
    }
    cout << list.getComment(i) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
}

void classUI::searching()
{

    cout << "----------Select any of the following options----------" << endl;
    cout << "What do you want to search for? " << endl;
    cout << "Name -- Searches for a name" << endl;
    cout << "Gender -- Searches for a Gender" << endl;
    cout << "Year -- Searches for a year born" << endl;
    search();
}
void classUI::addPerson()
{
    string name;
    char gender;
    int yearOfBirth = 0;
    int yearOfDeath = 0;
    string comment;

    cout << "Input Name: ";
    cin.ignore();
    std::getline(std::cin,name);
    cout << "Input gender (M/F): ";
    cin >> gender;
    if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
    {
       cout << "Input year of birth: ";
       cin >> yearOfBirth;
       cout << "Input year of death: ";
       cin >> yearOfDeath;
       cout << "Input a comment: ";
       cin >> comment;
    }
    else
    {
        cout << "Invalid gender! Try again." << endl;
        addPerson();
    }
    list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);

}

void classUI::search()
{
        string searchChoice;
        cin >> searchChoice;
        if (searchChoice == "Name" || searchChoice == "name" || searchChoice == "NAME")
        {
            string namesearch;
            cout << "Enter a name you want to search for: ";
            cin >> namesearch;

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                if(namesearch == list.getName(i))
                {
                    namesearch =  list.getName(i);
                    view(i);
                }
                else if(i+1 == list.getPersonsSize())
                {
                    cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl;
                }
            }
        }
        else if (searchChoice == "Gender" || searchChoice == "GENDER" || searchChoice == "gender")
        {
            char gendersearch;

            cout << "Enter a Gender you want to search for: (m/f)";
            cin >> gendersearch;

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                if(gendersearch == list.getGender(i))
                {
                    gendersearch = list.getGender(i);
                    view(i);
                }
                else if(i+1 == list.getPersonsSize())
                {
                    cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl;
                }
            }
        }
        else if (searchChoice == "year" || searchChoice == "YEAR" || searchChoice == "Year")
        {
                int yearsearch;
                cout << "Enter a Year you want to search for: ";
                cin >> yearsearch;

                for(int i = 0; i < list.getPersonsSize();++i)
                {
                    if(yearsearch == list.getBirth(i))
                    {
                        yearsearch = list.getBirth(i);
                        view(i);
                    }
                    else if(i+1 == list.getPersonsSize())
                    {
                        cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl;
                    }
                }
        }
        else
        {
            cout << "Error reading input" << endl;
        }
}
void classUI::remove()
{
    string name;
    cout << "Enter a name of person that you want to remove: ";
    cin >> name;
    if (list.removePerson(name) == true)
    {
        cout << "Person removed!" << endl;
    }
    else
    {
        cout << "Person not found!" << endl;
    }
}
void classUI::save()
{
    list.saveFile();
}
void classUI::viewAll()
{
    for(int i = 0; i < list.getPersonsSize(); i++)
    {
        view(i);
    }
}
void classUI::yo()
{
    cout << endl;
    cout << "`8.`8888.      ,8'     ,o888888o.     " << endl;
    cout << " `8.`8888.    ,8'   . 8888     `88.   " << endl;
    cout << "  `8.`8888.  ,8'   ,8 8888       `8b  " << endl;
    cout << "   `8.`8888.,8'    88 8888        `8b " << endl;
    cout << "    `8.`88888'     88 8888         88 " << endl;
    cout << "     `8. 8888      88 8888         88 " << endl;
    cout << "      `8 8888      88 8888        ,8P " << endl;
    cout << "       8 8888      `8 8888       ,8P  " << endl;
    cout << "       8 8888       ` 8888     ,88'   " << endl;
    cout << "       8 8888          `8888888P'     " << endl;
    cout << endl;
}
<|endoftext|>


<commit_before>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <time.h>

using namespace std;

ClassUI::ClassUI()
{

}
void ClassUI::run()
{
    cout << "\t" << "Welcome to the Amazing Database! " << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "\t" << "   *** Quote of the day ***" << endl;
    cout << getQuotes() << endl;
    mainMenu();
}
void ClassUI::mainMenu()
{
    string choice;
    do
    {
        cout << "--------------------------------------------------------------" << endl;
        cout << " (1) - " << "\t" << "Add a person to the database." << endl;
        cout << " (2) - " << "\t" << "Remove a person from the database." << endl;
        cout << " (3) - " << "\t" << "View the entire database." << endl;
        cout << " (4) - " << "\t" << "Save the database." << endl;
        cout << " (5) - " << "\t" << "Search the database." << endl;
        cout << " (6) - " << "\t" << "Sort the database." << endl;
        cout << " (7) - " << "\t" << "Exit." << endl;
        cout << "Enter your command (1 - 7): ";
        cin >> choice;
        cout << endl;

        if (choice != "7")
        {
           select(choice);
        }
        else
        {
            list.saveFile();
            runOn = false;
        }
    }while(runOn == true);
}
void ClassUI::select(string ch)
{
    if(ch == "1")
    {
        addPerson();
    }
    else if(ch == "2")
    {
        remove();
    }
    else if(ch == "3")
    {
        viewAll();
    }
    else if(ch == "4")
    {
        save();
    }
    else if(ch == "5")
    {
        searching();
    }
        else if(ch == "6")
    {
        sorting();
    }
    else if(ch == "yo")
    {
        yo();
    }
    else
    {
        cout << "Invalid input. Please enter a number between 1 - 7." << endl;
    }
}
void ClassUI::view(int i)
{
    int nameSize  = list.getNameSize(i);

    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl;
    cout << "--------------------------------|-------|-------|-------------" << endl;
    cout << list.getName(i);

    if(nameSize > 0 && nameSize <= 7)
    {
        cout << "\t" << "\t" << "\t" << "\t";
    }
    else if(nameSize > 7 && nameSize <= 15)
    {
        cout << "\t" << "\t" << "\t";
    }
    else if(nameSize > 15 && nameSize <= 23)
    {
        cout << "\t" << "\t";
    }
    else if(nameSize > 23 && nameSize <= 31)
    {
        cout << "\t";
    }

    if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
    {
        cout << "|Male" << "\t";
    }
    else
    {
        cout << "|Female" << "\t";
    }

    cout  << "|" << list.getBirth(i);

    if(list.getDeath(i) == 0)
    {
        cout << "\t" << "| n/a"  << endl;
    }
    else
    {
        cout << "\t" << "|" << list.getDeath(i)  << endl;
    }
    cout << list.getComment(i) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
}
void ClassUI::searching()
{

    cout << "-------------Select any of the following commands-------------" << endl;
    cout << "What do you want to search for? (1 - 4)" << endl;
    cout << " (1) - Searches for a name." << endl;
    cout << " (2) - Searches for a Gender." << endl;
    cout << " (3) - Searches for a year born." << endl;
    cout << " (4) - Return to main menu" << endl;

    search();
}
void ClassUI::addPerson()
{
    string name;
    string comment;
    char gender;
    char yesOrNo;
    int yearOfBirth = 0;
    int yearOfDeath = 0;

    cout << "Input Name: ";
    cin.ignore();
    std::getline(std::cin,name);
    cout << "Input gender (M/F): ";
    cin >> gender;

    if (gender == 'm')
    {
        gender = 'M';
    }
    else if (gender == 'f')
    {
        gender = 'F';
    }

    if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
    {
       cout << "Input year of birth: ";
       cin >> yearOfBirth;

       cout << "Is the individual deceased? (y/n)";
       cin >> yesOrNo;

       if (yesOrNo == 'Y' || yesOrNo == 'y')
       {
            cout << "Input year of death: ";
            cin >> yearOfDeath;
       }
       cout << "Input a comment about the individual: ";
       cin.ignore();
       std::getline(std::cin,comment);
    }
    else
    {
        cout << "Invalid gender! Try again." << endl;
        addPerson();
    }

    cout << "Are you sure that you want to add this person? (y/n)"; // Þetta er ógeðslegur texti, endilega finnum eitthvað skárra
    string validatePerson;
    cin >> validatePerson;

    if(validatePerson == "y")
    {
        cout << "New person added!" << endl;
        list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);
    }
    else
    {
        cout << "Operation addPerson aborted!" << endl; // Endilega komið með tillögu að breytingu á þessum texta
    }
}
void ClassUI::search()
{
    string searchChoice;
    cout << "Enter your command (1 - 4): ";
    cin >> searchChoice;
    cout << endl;

    if (searchChoice == "1")
    {
        string namesearch;
        cout << "Enter a name you want to search for: ";
        cin.ignore();
        std::getline(std::cin,namesearch);

        for(int i = 0; i < list.getPersonsSize();++i)
        {
            std::size_t found = list.getName(i).find(namesearch);
            if (found!=std::string::npos)
            {
                view(i);
            }
        }

        if(list.nameSearcher(namesearch) == false)
        {
            cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
            searching();
        }
    }
    else if (searchChoice == "2")
    {
        char gendersearch;

        cout << "Enter a gender you want to search for: (M/F)";
        cin >> gendersearch;

        if(gendersearch == 'm')
            {
                 gendersearch = 'M';
            }
        else if (gendersearch == 'f')
            {
                 gendersearch = 'F';
            }

        for(int i = 0; i < list.getPersonsSize();++i)
        {
            if(gendersearch == list.getGender(i))
            {
                gendersearch = list.getGender(i);
                view(i);
            }
        }

        if(list.genderSearcher(gendersearch) == false)
        {
            cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
            searching();
        }
    }
    else if (searchChoice == "3")
    {
            int yearsearch;
            cout << "Enter a year you want to search for: ";
            cin >> yearsearch;

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                if(yearsearch == list.getBirth(i))
                {
                    yearsearch = list.getBirth(i);
                    view(i);
                }
            }

            if(list.yearSearcher(yearsearch) == false)
            {
                cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                searching();
            }
    }
    else if (searchChoice == "4")
    {
        mainMenu();
    }
    else
    {
        cout << "Error reading input. Please enter a number between 1- 3." << endl;
        search();
    }
}
void ClassUI::remove()
{
    string name;
    cout << "Enter the full name of the person that you want to remove: ";
    cin.ignore();
    std::getline(std::cin,name);

    if (list.removePersonFound(name) == true)
    {
        char validateRemove;
        cout << "Person found!" << endl;
        cout << "Are you sure you want to remove this person? (y/n): ";
        cin >> validateRemove;

        if(validateRemove == 'y' || validateRemove == 'Y')
        {
            if(list.removePerson(name) == true)
            {
                cout << "Person removed!" << endl;
            }
            else
            {
                cout << "Person not removed!" << endl;
            }
        }
    }
    else
    {
        cout << "Person not found!" << endl;
    }
}
void ClassUI::save()
{
    list.saveFile();
    cout << "Database saved." << endl;
}
void ClassUI::viewAll()
{
    for(int i = 0; i < list.getPersonsSize(); i++)
    {
        view(i);
    }
}
void ClassUI::yo()
{
    cout << endl;
    cout << "`8.`8888.      ,8'     ,o888888o.     " << endl;
    cout << " `8.`8888.    ,8'   . 8888     `88.   " << endl;
    cout << "  `8.`8888.  ,8'   ,8 8888       `8b  " << endl;
    cout << "   `8.`8888.,8'    88 8888        `8b " << endl;
    cout << "    `8.`88888'     88 8888         88 " << endl;
    cout << "     `8. 8888      88 8888         88 " << endl;
    cout << "      `8 8888      88 8888        ,8P " << endl;
    cout << "       8 8888      `8 8888       ,8P  " << endl;
    cout << "       8 8888       ` 8888     ,88'   " << endl;
    cout << "       8 8888          `8888888P'     " << endl;
    cout << endl;
}
string ClassUI::getQuotes()
{
    string quotes[5] = {"\"A good programmer is someone who always looks both ways before crossing a one-way street.\" (Doug Linder)",
                        "\"Programming is like sex. One mistake and you have to support it for the rest of your life.\" (Michael Sinz)",
                        "\"Walking on water and developing software from a specification are easy if both are frozen.\" (Edward V Berard)",
                        "\"One man's crappy software is another man's full time job.\" (Jessica Gaston)",
                        "\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\" (Waldi Ravens)"
                       };
    int v1 = 0;
    srand (time(NULL));
    v1 = rand() % 5;
    return quotes[v1];
}
void ClassUI::sorting()
{
    string sortcho;
    cout << "Enter a sort command (1 - 3):" << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << " (1) - Sort by alphabetical order" << endl;
    cout << " (2) - Sort by chronological order" << endl;
    cout << " (3) - Return to main menu" << endl;
    cout << "Enter your command (1 - 2): ";
    cin >> sortcho;
    cout << endl;

    if(sortcho == "1")
    {
        list.sortNames();
         viewAll();
    }
    else if(sortcho == "2")
    {
        list.sortBirth();
         viewAll();
    }
    else if(sortcho == "3")
    {
        mainMenu();
    }
}
<commit_msg>lagað cout í addperson<commit_after>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <time.h>

using namespace std;

ClassUI::ClassUI()
{

}
void ClassUI::run()
{
    cout << "\t" << "Welcome to the Amazing Database! " << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "\t" << "   *** Quote of the day ***" << endl;
    cout << getQuotes() << endl;
    mainMenu();
}
void ClassUI::mainMenu()
{
    string choice;
    do
    {
        cout << "--------------------------------------------------------------" << endl;
        cout << " (1) - " << "\t" << "Add a person to the database." << endl;
        cout << " (2) - " << "\t" << "Remove a person from the database." << endl;
        cout << " (3) - " << "\t" << "View the entire database." << endl;
        cout << " (4) - " << "\t" << "Save the database." << endl;
        cout << " (5) - " << "\t" << "Search the database." << endl;
        cout << " (6) - " << "\t" << "Sort the database." << endl;
        cout << " (7) - " << "\t" << "Exit." << endl;
        cout << "Enter your command (1 - 7): ";
        cin >> choice;
        cout << endl;

        if (choice != "7")
        {
           select(choice);
        }
        else
        {
            list.saveFile();
            runOn = false;
        }
    }while(runOn == true);
}
void ClassUI::select(string ch)
{
    if(ch == "1")
    {
        addPerson();
    }
    else if(ch == "2")
    {
        remove();
    }
    else if(ch == "3")
    {
        viewAll();
    }
    else if(ch == "4")
    {
        save();
    }
    else if(ch == "5")
    {
        searching();
    }
        else if(ch == "6")
    {
        sorting();
    }
    else if(ch == "yo")
    {
        yo();
    }
    else
    {
        cout << "Invalid input. Please enter a number between 1 - 7." << endl;
    }
}
void ClassUI::view(int i)
{
    int nameSize  = list.getNameSize(i);

    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl;
    cout << "--------------------------------|-------|-------|-------------" << endl;
    cout << list.getName(i);

    if(nameSize > 0 && nameSize <= 7)
    {
        cout << "\t" << "\t" << "\t" << "\t";
    }
    else if(nameSize > 7 && nameSize <= 15)
    {
        cout << "\t" << "\t" << "\t";
    }
    else if(nameSize > 15 && nameSize <= 23)
    {
        cout << "\t" << "\t";
    }
    else if(nameSize > 23 && nameSize <= 31)
    {
        cout << "\t";
    }

    if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
    {
        cout << "|Male" << "\t";
    }
    else
    {
        cout << "|Female" << "\t";
    }

    cout  << "|" << list.getBirth(i);

    if(list.getDeath(i) == 0)
    {
        cout << "\t" << "| n/a"  << endl;
    }
    else
    {
        cout << "\t" << "|" << list.getDeath(i)  << endl;
    }
    cout << list.getComment(i) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
}
void ClassUI::searching()
{

    cout << "-------------Select any of the following commands-------------" << endl;
    cout << "What do you want to search for? (1 - 4)" << endl;
    cout << " (1) - Searches for a name." << endl;
    cout << " (2) - Searches for a Gender." << endl;
    cout << " (3) - Searches for a year born." << endl;
    cout << " (4) - Return to main menu" << endl;

    search();
}
void ClassUI::addPerson()
{
    string name;
    string comment;
    char gender;
    char yesOrNo;
    int yearOfBirth = 0;
    int yearOfDeath = 0;

    cout << "Input Name: ";
    cin.ignore();
    std::getline(std::cin,name);
    cout << "Input gender (M/F): ";
    cin >> gender;

    if (gender == 'm')
    {
        gender = 'M';
    }
    else if (gender == 'f')
    {
        gender = 'F';
    }

    if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
    {
       cout << "Input year of birth: ";
       cin >> yearOfBirth;

       cout << "Is the individual deceased? (y/n) ";
       cin >> yesOrNo;

       if (yesOrNo == 'Y' || yesOrNo == 'y')
       {
            cout << "Input year of death: ";
            cin >> yearOfDeath;
       }
       cout << "Input a comment about the individual: ";
       cin.ignore();
       std::getline(std::cin,comment);
    }
    else
    {
        cout << "Invalid gender! Try again." << endl;
        addPerson();
    }

    cout << "Are you sure that you want to add this person? (y/n) ";
    string validatePerson;
    cin >> validatePerson;

    if(validatePerson == "y")
    {
        cout << "New person added!" << endl;
        list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);
    }
    else
    {
        cout << "Person not added!" << endl;
    }
}
void ClassUI::search()
{
    string searchChoice;
    cout << "Enter your command (1 - 4): ";
    cin >> searchChoice;
    cout << endl;

    if (searchChoice == "1")
    {
        string namesearch;
        cout << "Enter a name you want to search for: ";
        cin.ignore();
        std::getline(std::cin,namesearch);

        for(int i = 0; i < list.getPersonsSize();++i)
        {
            std::size_t found = list.getName(i).find(namesearch);
            if (found!=std::string::npos)
            {
                view(i);
            }
        }

        if(list.nameSearcher(namesearch) == false)
        {
            cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
            searching();
        }
    }
    else if (searchChoice == "2")
    {
        char gendersearch;

        cout << "Enter a gender you want to search for: (M/F)";
        cin >> gendersearch;

        if(gendersearch == 'm')
            {
                 gendersearch = 'M';
            }
        else if (gendersearch == 'f')
            {
                 gendersearch = 'F';
            }

        for(int i = 0; i < list.getPersonsSize();++i)
        {
            if(gendersearch == list.getGender(i))
            {
                gendersearch = list.getGender(i);
                view(i);
            }
        }

        if(list.genderSearcher(gendersearch) == false)
        {
            cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
            searching();
        }
    }
    else if (searchChoice == "3")
    {
            int yearsearch;
            cout << "Enter a year you want to search for: ";
            cin >> yearsearch;

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                if(yearsearch == list.getBirth(i))
                {
                    yearsearch = list.getBirth(i);
                    view(i);
                }
            }

            if(list.yearSearcher(yearsearch) == false)
            {
                cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                searching();
            }
    }
    else if (searchChoice == "4")
    {
        mainMenu();
    }
    else
    {
        cout << "Error reading input. Please enter a number between 1- 3." << endl;
        search();
    }
}
void ClassUI::remove()
{
    string name;
    cout << "Enter the full name of the person that you want to remove: ";
    cin.ignore();
    std::getline(std::cin,name);

    if (list.removePersonFound(name) == true)
    {
        char validateRemove;
        cout << "Person found!" << endl;
        cout << "Are you sure you want to remove this person? (y/n): ";
        cin >> validateRemove;

        if(validateRemove == 'y' || validateRemove == 'Y')
        {
            if(list.removePerson(name) == true)
            {
                cout << "Person removed!" << endl;
            }
            else
            {
                cout << "Person not removed!" << endl;
            }
        }
    }
    else
    {
        cout << "Person not found!" << endl;
    }
}
void ClassUI::save()
{
    list.saveFile();
    cout << "Database saved." << endl;
}
void ClassUI::viewAll()
{
    for(int i = 0; i < list.getPersonsSize(); i++)
    {
        view(i);
    }
}
void ClassUI::yo()
{
    cout << endl;
    cout << "`8.`8888.      ,8'     ,o888888o.     " << endl;
    cout << " `8.`8888.    ,8'   . 8888     `88.   " << endl;
    cout << "  `8.`8888.  ,8'   ,8 8888       `8b  " << endl;
    cout << "   `8.`8888.,8'    88 8888        `8b " << endl;
    cout << "    `8.`88888'     88 8888         88 " << endl;
    cout << "     `8. 8888      88 8888         88 " << endl;
    cout << "      `8 8888      88 8888        ,8P " << endl;
    cout << "       8 8888      `8 8888       ,8P  " << endl;
    cout << "       8 8888       ` 8888     ,88'   " << endl;
    cout << "       8 8888          `8888888P'     " << endl;
    cout << endl;
}
string ClassUI::getQuotes()
{
    string quotes[5] = {"\"A good programmer is someone who always looks both ways before crossing a one-way street.\" (Doug Linder)",
                        "\"Programming is like sex. One mistake and you have to support it for the rest of your life.\" (Michael Sinz)",
                        "\"Walking on water and developing software from a specification are easy if both are frozen.\" (Edward V Berard)",
                        "\"One man's crappy software is another man's full time job.\" (Jessica Gaston)",
                        "\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\" (Waldi Ravens)"
                       };
    int v1 = 0;
    srand (time(NULL));
    v1 = rand() % 5;
    return quotes[v1];
}
void ClassUI::sorting()
{
    string sortcho;
    cout << "Enter a sort command (1 - 3):" << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << " (1) - Sort by alphabetical order" << endl;
    cout << " (2) - Sort by chronological order" << endl;
    cout << " (3) - Return to main menu" << endl;
    cout << "Enter your command (1 - 2): ";
    cin >> sortcho;
    cout << endl;

    if(sortcho == "1")
    {
        list.sortNames();
         viewAll();
    }
    else if(sortcho == "2")
    {
        list.sortBirth();
         viewAll();
    }
    else if(sortcho == "3")
    {
        mainMenu();
    }
}
<|endoftext|>


<commit_before>/*
    This file is part of Android File Transfer For Linux.
    Copyright (C) 2015-2018  Vladimir Menshakov

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2.1 of the License,
    or (at your option) any later version.

    This library is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this library; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

#include <stdio.h>
#include <stdexcept>

#include <usb/Context.h>

#include <cli/CommandLine.h>
#include <cli/Session.h>

#include <mtp/log.h>
#include <mtp/version.h>

#include <getopt.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
	using namespace mtp;
	bool forceInteractive = false;
	bool showHelp = false;
	bool showPrompt = true;
	bool showVersion = false;
	bool claimInterface = true;
	bool showEvents = false;
	const char *fileInput = nullptr;

	if (!isatty(STDIN_FILENO))
		showPrompt = false;

	static struct option long_options[] =
	{
		{"verbose",			no_argument,		0,	'v' },
		{"interactive",		no_argument,		0,	'i' },
		{"batch",			no_argument,		0,	'b' },
		{"events",			no_argument,		0,	'e' },
		{"help",			no_argument,		0,	'h' },
		{"version",			no_argument,		0,	'V' },
		{"no-claim",		no_argument,		0,	'C' },
		{"input-file",		required_argument,	0,	'f' },
		{0,					0,					0,	 0	}
	};

	while(true)
	{
		int optionIndex = 0; //index of matching option
		int c = getopt_long(argc, argv, "ibehvVCf:", long_options, &optionIndex);
		if (c == -1)
			break;
		switch(c)
		{
		case 'f':
			fileInput = optarg; //falling back to batch processing here
		case 'b':
			showPrompt = false; //no break here, prompt = false, interactive = true
		case 'i':
			forceInteractive = true;
			break;
		case 'v':
			g_debug = true;
			break;
		case 'V':
			showVersion = true;
			break;
		case 'C':
			claimInterface = false;
			break;
		case 'e':
			showEvents = true;
			break;
		case '?':
		case 'h':
		default:
			showHelp = true;
		}
	}
	if (fileInput)
	{
		close(STDIN_FILENO);
		int fd = open(fileInput, O_RDONLY);
		if (fd == -1)
		{
			perror("open");
			exit(1);
		}
		if (fd != STDIN_FILENO)
		{
			fprintf(stderr, "failed to reopen stdin\n");
			exit(1);
		}
	}

	if (showHelp)
	{
		error(
			"usage:\n"
			"-h\t--help\t\tshow this help\n"
			"-v\t--verbose\tshow debug output\n"
			"-i\t--interactive\tforce interactive mode\n"
			"-b\t--batch\t\tbatch command processing\n"
			"-e\t--events\t\tallow event processing\n"
			"-f\t--input-file\tuse file to read input commands\n"
			"-C\t--no-claim\tno usb interface claim\n"
			"-V\t--version\tshow version information"
			);
		exit(0);
	}

	if (showVersion)
	{
		print(GetVersion());
		exit(0);
	}

	auto mtp = Device::FindFirst(claimInterface);
	if (!mtp)
	{
		error("no mtp device found");
		exit(1);
	}

	try
	{
		bool hasCommands = optind >= argc;
		cli::Session session(mtp, showPrompt);
		if (!session.SetFirstStorage())
		{
			error("your device may be locked or does not have any storage available");
			exit(2);
		}
		session.ShowEvents(showEvents);

		if (forceInteractive || (session.IsInteractive() && hasCommands))
		{
			session.InteractiveInput();
		}
		else
		{
			for(int i = optind; i < argc; ++i)
			{
				session.ProcessCommand(argv[i]);
			}
		}

		exit(0);
	}
	catch (const std::exception &ex)
	{ error("error: ", ex.what()); exit(1); }
}
<commit_msg>added ctrl-c handler, interrupting current transaction<commit_after>/*
    This file is part of Android File Transfer For Linux.
    Copyright (C) 2015-2018  Vladimir Menshakov

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2.1 of the License,
    or (at your option) any later version.

    This library is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this library; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

#include <stdio.h>
#include <stdexcept>

#include <usb/Context.h>

#include <cli/CommandLine.h>
#include <cli/Session.h>

#include <mtp/log.h>
#include <mtp/version.h>

#include <atomic>

#include <fcntl.h>
#include <fcntl.h>
#include <getopt.h>
#include <unistd.h>
#include <signal.h>

#include <sys/types.h>
#include <sys/stat.h>

namespace
{
	std::atomic<cli::Session *>		gSession(nullptr);

	static void SigIntHandler(int)
	{
		cli::Session * session = gSession.load();
		try
		{
			if (session)
				session->Cancel();
		}
		catch(const std::exception & ex)
		{
			mtp::debug("cancellation failed: ", ex.what());
			exit(0);
		}
	}
}

int main(int argc, char **argv)
{
	using namespace mtp;
	bool forceInteractive = false;
	bool showHelp = false;
	bool showPrompt = true;
	bool showVersion = false;
	bool claimInterface = true;
	bool showEvents = false;
	const char *fileInput = nullptr;

	if (!isatty(STDIN_FILENO))
		showPrompt = false;

	static struct option long_options[] =
	{
		{"verbose",			no_argument,		0,	'v' },
		{"interactive",		no_argument,		0,	'i' },
		{"batch",			no_argument,		0,	'b' },
		{"events",			no_argument,		0,	'e' },
		{"help",			no_argument,		0,	'h' },
		{"version",			no_argument,		0,	'V' },
		{"no-claim",		no_argument,		0,	'C' },
		{"input-file",		required_argument,	0,	'f' },
		{0,					0,					0,	 0	}
	};

	struct sigaction newHandler = { };
	newHandler.sa_handler = &SigIntHandler;
	newHandler.sa_flags = SA_RESTART;
	if (sigaction(SIGINT, &newHandler, nullptr) != 0)
		perror("sigaction(SIGINT)");

	while(true)
	{
		int optionIndex = 0; //index of matching option
		int c = getopt_long(argc, argv, "ibehvVCf:", long_options, &optionIndex);
		if (c == -1)
			break;
		switch(c)
		{
		case 'f':
			fileInput = optarg; //falling back to batch processing here
		case 'b':
			showPrompt = false; //no break here, prompt = false, interactive = true
		case 'i':
			forceInteractive = true;
			break;
		case 'v':
			g_debug = true;
			break;
		case 'V':
			showVersion = true;
			break;
		case 'C':
			claimInterface = false;
			break;
		case 'e':
			showEvents = true;
			break;
		case '?':
		case 'h':
		default:
			showHelp = true;
		}
	}
	if (fileInput)
	{
		close(STDIN_FILENO);
		int fd = open(fileInput, O_RDONLY);
		if (fd == -1)
		{
			perror("open");
			exit(1);
		}
		if (fd != STDIN_FILENO)
		{
			fprintf(stderr, "failed to reopen stdin\n");
			exit(1);
		}
	}

	if (showHelp)
	{
		error(
			"usage:\n"
			"-h\t--help\t\tshow this help\n"
			"-v\t--verbose\tshow debug output\n"
			"-i\t--interactive\tforce interactive mode\n"
			"-b\t--batch\t\tbatch command processing\n"
			"-e\t--events\t\tallow event processing\n"
			"-f\t--input-file\tuse file to read input commands\n"
			"-C\t--no-claim\tno usb interface claim\n"
			"-V\t--version\tshow version information"
			);
		exit(0);
	}

	if (showVersion)
	{
		print(GetVersion());
		exit(0);
	}

	auto mtp = Device::FindFirst(claimInterface);
	if (!mtp)
	{
		error("no mtp device found");
		exit(1);
	}

	try
	{
		bool hasCommands = optind >= argc;
		cli::Session session(mtp, showPrompt);
		gSession.store(&session);
		if (!session.SetFirstStorage())
		{
			error("your device may be locked or does not have any storage available");
			exit(2);
		}
		session.ShowEvents(showEvents);

		if (forceInteractive || (session.IsInteractive() && hasCommands))
		{
			session.InteractiveInput();
		}
		else
		{
			for(int i = optind; i < argc; ++i)
			{
				session.ProcessCommand(argv[i]);
			}
		}
		gSession.store(nullptr);

		exit(0);
	}
	catch (const std::exception &ex)
	{ error("error: ", ex.what()); exit(1); }
}
<|endoftext|>


<commit_before>#include "cnn/exec.h"

#include "cnn/param-nodes.h"

using namespace std;

namespace cnn {

ExecutionEngine::~ExecutionEngine() {}

void SimpleExecutionEngine::invalidate() {
    last_node_evaluated = 0;
}

const Tensor& SimpleExecutionEngine::forward() {
  const VariableIndex node_max_index = (VariableIndex)cg.nodes.size();
  return forward(node_max_index);
}

const Tensor& SimpleExecutionEngine::forward(VariableIndex i) {
  invalidate();
  return incremental_forward(i);
}

const Tensor& SimpleExecutionEngine::get_value(VariableIndex i) {
    assert(i < cg.nodes.size());
    if (i >= last_node_evaluated) {
        incremental_forward(i);
    }
    return nfxs[i];
}

const Tensor& SimpleExecutionEngine::incremental_forward() {
  const VariableIndex node_max_index = (VariableIndex)cg.nodes.size();
  return incremental_forward(node_max_index);
}

const Tensor& SimpleExecutionEngine::incremental_forward(VariableIndex node_max_index) {
  // free any old memory if this is a new HG
  if (last_node_evaluated == 0) fxs->free();

  assert(node_max_index > 0);
  nfxs.resize(node_max_index);
  if (node_max_index - last_node_evaluated == 0)
    return nfxs.back();

  //vector<string> dummy(5, "x");
  vector<const Tensor*> xs(16);
  for (; last_node_evaluated < node_max_index; ++last_node_evaluated) {
    const Node* node = cg.nodes[last_node_evaluated];
    xs.resize(node->arity());
    unsigned ai = 0;
    for (VariableIndex arg : node->args) {
      xs[ai] = &nfxs[arg];
      ++ai;
    }
    nfxs[last_node_evaluated].d = node->dim;
    nfxs[last_node_evaluated].v = static_cast<float*>(fxs->allocate(node->dim.size() * sizeof(float)));
    if (nfxs[last_node_evaluated].v == nullptr) {
      cerr << "out of memory\n";
      abort();
    }
    void* aux_mem = nullptr;
    size_t aux_size = node->aux_storage_size();
    if (aux_size) {
      aux_mem = fxs->allocate(aux_size);
      if (!aux_mem) {
        cerr << "aux out of memory\n";
        abort();
      }
    }
    node->aux_mem = aux_mem;
    node->forward(xs, nfxs[last_node_evaluated]);
  }
  return nfxs.back();
}

void SimpleExecutionEngine::backward() {
  if (nfxs.back().d.size() != 1) {
    cerr << "backward() called on non-scalar node.\n";
    abort();
  }

  const unsigned num_nodes = cg.nodes.size();
  ndEdfs.resize(num_nodes);
  dEdfs->free();
  for (unsigned i = 0; i < num_nodes; ++i) {
    const auto dim = nfxs[i].d;
    ndEdfs[i].d = dim;
    ndEdfs[i].v = static_cast<float*>(dEdfs->allocate(dim.size() * sizeof(float)));
    assert(ndEdfs[i].v);
  }
  dEdfs->zero_allocated_memory();
  // initialize dE/dE = 1
  ndEdfs.back().v = kSCALAR_ONE;

  // here we find constant paths to avoid doing extra work
  vector<bool> needs_derivative(num_nodes, false);
  for (auto i : cg.parameter_nodes)
    needs_derivative[i] = true;

  for (unsigned ni = 0; ni < num_nodes; ++ni) {
    bool nd = needs_derivative[ni];
    for (auto arg : cg.nodes[ni]->args)
      nd |= needs_derivative[arg];
    needs_derivative[ni] = nd;
  }

  // loop in reverse topological order
  vector<const Tensor*> xs;
  for (int i = num_nodes - 1; i >= 0; --i) {
    const Node* node = cg.nodes[i];
    xs.resize(node->arity());
    unsigned ai = 0;
    for (VariableIndex arg : node->args) {
      xs[ai] = &nfxs[arg];
      ++ai;
    }
    ai = 0;
    for (VariableIndex arg : node->args) {
      if (needs_derivative[arg]) {
        node->backward(xs, nfxs[i], ndEdfs[i], ai, ndEdfs[arg]);
      }
      ++ai;
    }
  }

  // accumulate gradients into parameters
  // this is simpler than you might find in some other frameworks
  // since we assume parameters come into the graph as a "function"
  // that returns the current value of the parameters
  for (VariableIndex i : cg.parameter_nodes)
    static_cast<ParameterNodeBase*>(cg.nodes[i])->accumulate_grad(ndEdfs[i]);
}

} // namespace cnn
<commit_msg>incremental_forward index fix<commit_after>#include "cnn/exec.h"

#include "cnn/param-nodes.h"

using namespace std;

namespace cnn {

ExecutionEngine::~ExecutionEngine() {}

void SimpleExecutionEngine::invalidate() {
    last_node_evaluated = 0;
}

const Tensor& SimpleExecutionEngine::forward() {
  const VariableIndex node_max_index = (VariableIndex)cg.nodes.size();
  return forward(node_max_index);
}

const Tensor& SimpleExecutionEngine::forward(VariableIndex i) {
  invalidate();
  return incremental_forward(i);
}

const Tensor& SimpleExecutionEngine::get_value(VariableIndex i) {
    assert(i < cg.nodes.size());
    if (i >= last_node_evaluated) {
        // node_max_index is used as a sentinel here, so we should forward until (i+1) not i
        incremental_forward( (VariableIndex)((unsigned int)i+1) );
    }
    return nfxs[i];
}

const Tensor& SimpleExecutionEngine::incremental_forward() {
  const VariableIndex node_max_index = (VariableIndex)cg.nodes.size();
  return incremental_forward(node_max_index);
}

const Tensor& SimpleExecutionEngine::incremental_forward(VariableIndex node_max_index) {
  // free any old memory if this is a new HG
  if (last_node_evaluated == 0) fxs->free();

  assert(node_max_index > 0);
  nfxs.resize(node_max_index);
  if (node_max_index - last_node_evaluated == 0)
    return nfxs.back();

  //vector<string> dummy(5, "x");
  vector<const Tensor*> xs(16);
  for (; last_node_evaluated < node_max_index; ++last_node_evaluated) {
    const Node* node = cg.nodes[last_node_evaluated];
    xs.resize(node->arity());
    unsigned ai = 0;
    for (VariableIndex arg : node->args) {
      xs[ai] = &nfxs[arg];
      ++ai;
    }
    nfxs[last_node_evaluated].d = node->dim;
    nfxs[last_node_evaluated].v = static_cast<float*>(fxs->allocate(node->dim.size() * sizeof(float)));
    if (nfxs[last_node_evaluated].v == nullptr) {
      cerr << "out of memory\n";
      abort();
    }
    void* aux_mem = nullptr;
    size_t aux_size = node->aux_storage_size();
    if (aux_size) {
      aux_mem = fxs->allocate(aux_size);
      if (!aux_mem) {
        cerr << "aux out of memory\n";
        abort();
      }
    }
    node->aux_mem = aux_mem;
    node->forward(xs, nfxs[last_node_evaluated]);
  }
  return nfxs.back();
}

void SimpleExecutionEngine::backward() {
  if (nfxs.back().d.size() != 1) {
    cerr << "backward() called on non-scalar node.\n";
    abort();
  }

  const unsigned num_nodes = cg.nodes.size();
  ndEdfs.resize(num_nodes);
  dEdfs->free();
  for (unsigned i = 0; i < num_nodes; ++i) {
    const auto dim = nfxs[i].d;
    ndEdfs[i].d = dim;
    ndEdfs[i].v = static_cast<float*>(dEdfs->allocate(dim.size() * sizeof(float)));
    assert(ndEdfs[i].v);
  }
  dEdfs->zero_allocated_memory();
  // initialize dE/dE = 1
  ndEdfs.back().v = kSCALAR_ONE;

  // here we find constant paths to avoid doing extra work
  vector<bool> needs_derivative(num_nodes, false);
  for (auto i : cg.parameter_nodes)
    needs_derivative[i] = true;

  for (unsigned ni = 0; ni < num_nodes; ++ni) {
    bool nd = needs_derivative[ni];
    for (auto arg : cg.nodes[ni]->args)
      nd |= needs_derivative[arg];
    needs_derivative[ni] = nd;
  }

  // loop in reverse topological order
  vector<const Tensor*> xs;
  for (int i = num_nodes - 1; i >= 0; --i) {
    const Node* node = cg.nodes[i];
    xs.resize(node->arity());
    unsigned ai = 0;
    for (VariableIndex arg : node->args) {
      xs[ai] = &nfxs[arg];
      ++ai;
    }
    ai = 0;
    for (VariableIndex arg : node->args) {
      if (needs_derivative[arg]) {
        node->backward(xs, nfxs[i], ndEdfs[i], ai, ndEdfs[arg]);
      }
      ++ai;
    }
  }

  // accumulate gradients into parameters
  // this is simpler than you might find in some other frameworks
  // since we assume parameters come into the graph as a "function"
  // that returns the current value of the parameters
  for (VariableIndex i : cg.parameter_nodes)
    static_cast<ParameterNodeBase*>(cg.nodes[i])->accumulate_grad(ndEdfs[i]);
}

} // namespace cnn
<|endoftext|>


<commit_before>// Copyright 2014, Xilinx Inc.
// All rights reserved.

#include <getopt.h>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <ctime>
#include <iostream>
#include <vector>
#include <cassert>
#include <fstream>
#include "oclHelper.h"
#include "pgm.h"

const int FAST_THREADS_X = 16;
const int FAST_THREADS_Y = 16;
const int FAST_THREADS_NONMAX_X = 32;
const int FAST_THREADS_NONMAX_Y = 8;

#define DIVUP(A, B) (((A) + (B) - 1) / (B))

#define CL_INT_CHECK(err) do {                                                          \
        if (err != CL_SUCCESS) {                                                        \
            std::cout << "OpenCL error (" << err << ", " << oclErrorCode(err) << ")" << \
            " in file:line " << __FILE__ << ":" << __LINE__ << std::endl;               \
            return -1;                                                                  \
        }                                                                               \
    } while(0)

#define CL_CHECK(fn) do {                                                               \
        cl_int err = fn;                                                                \
        if (err != CL_SUCCESS) {                                                        \
            std::cout << "OpenCL error (" << err << ", " << oclErrorCode(err) << ")" << \
            " in file:line " << __FILE__ << ":" << __LINE__ << std::endl;               \
            return -1;                                                                  \
        }                                                                               \
    } while(0)

class Timer {
    time_t mTimeStart;
    time_t mTimeEnd;
public:
    Timer() {
        mTimeStart = std::time(0);
        mTimeEnd = mTimeStart;
    }
    double stop() {
        mTimeEnd = std::time(0);
        return std::difftime(mTimeEnd, mTimeStart);
    }
    void reset() {
        mTimeStart = time(0);
        mTimeEnd = mTimeStart;
    }
};

typedef std::pair<int, int> Position;

const static struct option long_options[] = {
    {"device",        required_argument, 0, 'd'},
    {"kernel",        required_argument, 0, 'k'},
    {"img_file",      required_argument, 0, 'f'},
    {"iteration",     optional_argument, 0, 'i'},
    {"verbose",       no_argument,       0, 'v'},
    {"help",          no_argument,       0, 'h'},
    {0, 0, 0, 0}
};

static void printHelp()
{
    std::cout << "usage: %s <options>\n";
    std::cout << "  -d <cpu|gpu|acc>\n";
    std::cout << "  -k <kernel_file> \n";
    std::cout << "  -f <img_file>\n";
    std::cout << "  -i <iteration_count>\n";
    std::cout << "  -t <fast_thr>\n";
    std::cout << "  -v\n";
    std::cout << "  -h\n";
}

int runTest(std::string imgFile, std::vector<int> fpgaX, std::vector<int> fpgaY, std::vector<int> fpgaScore)
{
    int extIndex = imgFile.find_last_of(".");
    std::string testFile = imgFile.substr(0, extIndex) + std::string(".test");
    std::ifstream testStream;
    testStream.open(testFile.c_str());

    size_t nsamples = 0;
    testStream >> nsamples;

    if (nsamples != fpgaX.size())
        return 1;

    int* goldX = new int[nsamples];
    int* goldY = new int[nsamples];
    int* goldScore = new int[nsamples];

    for (size_t i = 0; i < nsamples; i++) {
        testStream >> goldX[i] >> goldY[i] >> goldScore[i];
    }

    for (size_t i = 0; i < nsamples; i++) {
        if (fpgaX[i] != goldX[i] || fpgaY[i] != goldY[i] || fpgaScore[i] != goldScore[i])
            return 1;
    }

    delete[] goldX;
    delete[] goldY;
    delete[] goldScore;

    testStream.close();

    return 0;
}

static int runOpenCL(std::string imgFile, std::string kernelFile, cl_device_type deviceType,
                     int iteration, int fast_thr, bool verbose, double delay)
{
    oclHardware hardware = getOclHardware(deviceType);
    if (!hardware.mQueue) {
        return -1;
    }
    std::cout << "verbose: " << verbose << std::endl;

    oclSoftware software;
    std::memset(&software, 0, sizeof(oclSoftware));
    std::strcpy(software.mKernelName, "locate_features");
    std::strcpy(software.mFileName, kernelFile.c_str());

    getOclSoftware(software, hardware);

    int* h_img;
    size_t w, h;
    readPGM(&h_img, &w, &h, imgFile);
    size_t img_el = w*h;

    int wi = (int)w, hi = (int)h;

    cl_int err = 0;

    cl_mem d_img = clCreateBuffer(hardware.mContext, CL_MEM_READ_ONLY, img_el * sizeof(int), NULL, &err);
    CL_INT_CHECK(err);
    cl_mem d_score = clCreateBuffer(hardware.mContext, CL_MEM_READ_WRITE, img_el * sizeof(int), NULL, &err);
    CL_INT_CHECK(err);

    CL_CHECK(clEnqueueWriteBuffer(hardware.mQueue, d_img, CL_TRUE, 0,
                                  img_el * sizeof(int), h_img, 0, 0, 0));

    int arg = 0;

    const unsigned edge = 3;
    const unsigned local_el = (FAST_THREADS_X + edge*2) * (FAST_THREADS_Y + edge*2);
    CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(cl_mem), &d_img));
    CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(int), &wi));
    CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(int), &hi));
    CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(cl_mem), &d_score));
    CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(int), &fast_thr));
    CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(unsigned), &edge));
    CL_CHECK(clSetKernelArg(software.mKernel, arg++, local_el * sizeof(int), NULL));

    size_t localSize[2] = { FAST_THREADS_X, FAST_THREADS_Y };

    unsigned groups_x = DIVUP(w, localSize[0]);
    unsigned groups_y = DIVUP(h, localSize[1]);
    size_t globalSize[2] = { localSize[0] * groups_x, localSize[1] * groups_y };

    if (verbose) {
        std::cout << "Global size = (" << globalSize[0] << "," << globalSize[1] << ",1)" << std::endl;
        std::cout << "Local  size = (" << localSize[0] << "," << localSize[1] << ",1)" << std::endl;
    }

    std::vector<int> h_score_init(w * h, 0);
    int* h_score = new int[img_el];

    std::vector<int> x, y, score;

    Timer timer;
    for(int i = 0; i < iteration; i++)
    {
        // Here we start measurings host time for kernel execution
        CL_CHECK(clEnqueueWriteBuffer(hardware.mQueue, d_score, CL_TRUE, 0,
                                      img_el * sizeof(int), &h_score_init[0], 0, 0, 0));

        CL_CHECK(clEnqueueNDRangeKernel(hardware.mQueue, software.mKernel, 2, 0,
                                        globalSize, localSize, 0, 0, 0));

        CL_CHECK(clFinish(hardware.mQueue));

        CL_CHECK(clEnqueueReadBuffer(hardware.mQueue, d_score, CL_TRUE, 0,
                                     img_el * sizeof(int), h_score, 0, 0, 0));

        if (i == iteration-1) {
            for (size_t j = 0; j < h; j++) {
                for (size_t k = 0; k < w; k++) {
                    size_t idx = j*w + k;
                    int s = h_score[idx];
                    if (s != 0) {
                        x.push_back(k);
                        y.push_back(j);
                        score.push_back(s);

                        if (verbose)
                            std::cout << "(" << k << ", " << j << "): " << s << std::endl;
                    }
                }
            }
        }
    }
    delay = timer.stop();

    int testRes = runTest(imgFile, x, y, score);

    delete[] h_img;
    delete[] h_score;
    clReleaseMemObject(d_img);
    clReleaseMemObject(d_score);

    return testRes;
}

int main(int argc, char** argv)
{
    cl_device_type deviceType = CL_DEVICE_TYPE_ACCELERATOR;;
    int option_index = 0;
    std::string kernelFile("fast.cl");
    std::string imgFile("./data/square.pgm");
    int iteration = 1;
    int fast_thr = 20;
    bool verbose = false;
    // Commandline
    int c;
    while ((c = getopt_long(argc, argv, "d:k:f:i:t:vh", long_options, &option_index)) != -1)
    {
        switch (c)
        {
        case 0:
            if (long_options[option_index].flag != 0)
                break;
        case 'd':
            if (strcmp(optarg, "gpu") == 0)
                deviceType = CL_DEVICE_TYPE_GPU;
            else if (strcmp(optarg, "cpu") == 0)
                deviceType = CL_DEVICE_TYPE_CPU;
            else if (strcmp(optarg, "soft") == 0)
                deviceType = CL_DEVICE_TYPE_DEFAULT;
            else if (strcmp(optarg, "acc") != 0) {
                std::cout << "Incorrect platform specified\n";
                printHelp();
                return -1;
            }
            break;
        case 'k':
            kernelFile = optarg;
            break;
        case 'f':
            imgFile = optarg;
            break;
        case 'i':
            iteration = atoi(optarg);
            break;
        case 't':
            fast_thr = atoi(optarg);
            break;
        case 'h':
            printHelp();
            return 0;
        case 'v':
            verbose = true;
            break;
        default:
            printHelp();
            return 1;
        }
    }

    double delay = 0;
    if ((deviceType != CL_DEVICE_TYPE_DEFAULT) && runOpenCL(imgFile, kernelFile, deviceType,
                                                            iteration, fast_thr, verbose, delay)) {
        std::cout << "FAILED TEST\n";
        return 1;
    }
    //runOpenCL(imgFile, kernelFile, deviceType, iteration, fast_thr, verbose, delay);

    std::cout << "OpenCL total time: " << delay << " sec\n";
    std::cout << "OpenCL average time per iteration: " << delay/iteration << " sec\n";
    std::cout << "PASSED TEST\n";
    return 0;
}
<commit_msg>Moved OpenCL helper macros to oclHelper.h<commit_after>// Copyright 2014, Xilinx Inc.
// All rights reserved.

#include <getopt.h>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <ctime>
#include <iostream>
#include <vector>
#include <cassert>
#include <fstream>
#include "oclHelper.h"
#include "pgm.h"

const int FAST_THREADS_X = 16;
const int FAST_THREADS_Y = 16;
const int FAST_THREADS_NONMAX_X = 32;
const int FAST_THREADS_NONMAX_Y = 8;

class Timer {
    time_t mTimeStart;
    time_t mTimeEnd;
public:
    Timer() {
        mTimeStart = std::time(0);
        mTimeEnd = mTimeStart;
    }
    double stop() {
        mTimeEnd = std::time(0);
        return std::difftime(mTimeEnd, mTimeStart);
    }
    void reset() {
        mTimeStart = time(0);
        mTimeEnd = mTimeStart;
    }
};

typedef std::pair<int, int> Position;

const static struct option long_options[] = {
    {"device",        required_argument, 0, 'd'},
    {"kernel",        required_argument, 0, 'k'},
    {"img_file",      required_argument, 0, 'f'},
    {"iteration",     optional_argument, 0, 'i'},
    {"verbose",       no_argument,       0, 'v'},
    {"help",          no_argument,       0, 'h'},
    {0, 0, 0, 0}
};

static void printHelp()
{
    std::cout << "usage: %s <options>\n";
    std::cout << "  -d <cpu|gpu|acc>\n";
    std::cout << "  -k <kernel_file> \n";
    std::cout << "  -f <img_file>\n";
    std::cout << "  -i <iteration_count>\n";
    std::cout << "  -t <fast_thr>\n";
    std::cout << "  -v\n";
    std::cout << "  -h\n";
}

int runTest(std::string imgFile, std::vector<int> fpgaX, std::vector<int> fpgaY, std::vector<int> fpgaScore)
{
    int extIndex = imgFile.find_last_of(".");
    std::string testFile = imgFile.substr(0, extIndex) + std::string(".test");
    std::ifstream testStream;
    testStream.open(testFile.c_str());

    size_t nsamples = 0;
    testStream >> nsamples;

    if (nsamples != fpgaX.size())
        return 1;

    int* goldX = new int[nsamples];
    int* goldY = new int[nsamples];
    int* goldScore = new int[nsamples];

    for (size_t i = 0; i < nsamples; i++) {
        testStream >> goldX[i] >> goldY[i] >> goldScore[i];
    }

    for (size_t i = 0; i < nsamples; i++) {
        if (fpgaX[i] != goldX[i] || fpgaY[i] != goldY[i] || fpgaScore[i] != goldScore[i])
            return 1;
    }

    delete[] goldX;
    delete[] goldY;
    delete[] goldScore;

    testStream.close();

    return 0;
}

static int runOpenCL(std::string imgFile, std::string kernelFile, cl_device_type deviceType,
                     int iteration, int fast_thr, bool verbose, double delay)
{
    oclHardware hardware = getOclHardware(deviceType);
    if (!hardware.mQueue) {
        return -1;
    }
    std::cout << "verbose: " << verbose << std::endl;

    oclSoftware software;
    std::memset(&software, 0, sizeof(oclSoftware));
    std::strcpy(software.mKernelName, "locate_features");
    std::strcpy(software.mFileName, kernelFile.c_str());

    getOclSoftware(software, hardware);

    int* h_img;
    size_t w, h;
    readPGM(&h_img, &w, &h, imgFile);
    size_t img_el = w*h;

    int wi = (int)w, hi = (int)h;

    cl_int err = 0;

    cl_mem d_img = clCreateBuffer(hardware.mContext, CL_MEM_READ_ONLY, img_el * sizeof(int), NULL, &err);
    CL_INT_CHECK(err);
    cl_mem d_score = clCreateBuffer(hardware.mContext, CL_MEM_READ_WRITE, img_el * sizeof(int), NULL, &err);
    CL_INT_CHECK(err);

    CL_CHECK(clEnqueueWriteBuffer(hardware.mQueue, d_img, CL_TRUE, 0,
                                  img_el * sizeof(int), h_img, 0, 0, 0));

    int arg = 0;

    const unsigned edge = 3;
    const unsigned local_el = (FAST_THREADS_X + edge*2) * (FAST_THREADS_Y + edge*2);
    CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(cl_mem), &d_img));
    CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(int), &wi));
    CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(int), &hi));
    CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(cl_mem), &d_score));
    CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(int), &fast_thr));
    CL_CHECK(clSetKernelArg(software.mKernel, arg++, sizeof(unsigned), &edge));
    CL_CHECK(clSetKernelArg(software.mKernel, arg++, local_el * sizeof(int), NULL));

    size_t localSize[2] = { FAST_THREADS_X, FAST_THREADS_Y };

    unsigned groups_x = DIVUP(w, localSize[0]);
    unsigned groups_y = DIVUP(h, localSize[1]);
    size_t globalSize[2] = { localSize[0] * groups_x, localSize[1] * groups_y };

    if (verbose) {
        std::cout << "Global size = (" << globalSize[0] << "," << globalSize[1] << ",1)" << std::endl;
        std::cout << "Local  size = (" << localSize[0] << "," << localSize[1] << ",1)" << std::endl;
    }

    std::vector<int> h_score_init(w * h, 0);
    int* h_score = new int[img_el];

    std::vector<int> x, y, score;

    Timer timer;
    for(int i = 0; i < iteration; i++)
    {
        // Here we start measurings host time for kernel execution
        CL_CHECK(clEnqueueWriteBuffer(hardware.mQueue, d_score, CL_TRUE, 0,
                                      img_el * sizeof(int), &h_score_init[0], 0, 0, 0));

        CL_CHECK(clEnqueueNDRangeKernel(hardware.mQueue, software.mKernel, 2, 0,
                                        globalSize, localSize, 0, 0, 0));

        CL_CHECK(clFinish(hardware.mQueue));

        CL_CHECK(clEnqueueReadBuffer(hardware.mQueue, d_score, CL_TRUE, 0,
                                     img_el * sizeof(int), h_score, 0, 0, 0));

        if (i == iteration-1) {
            for (size_t j = 0; j < h; j++) {
                for (size_t k = 0; k < w; k++) {
                    size_t idx = j*w + k;
                    int s = h_score[idx];
                    if (s != 0) {
                        x.push_back(k);
                        y.push_back(j);
                        score.push_back(s);

                        if (verbose)
                            std::cout << "(" << k << ", " << j << "): " << s << std::endl;
                    }
                }
            }
        }
    }
    delay = timer.stop();

    int testRes = runTest(imgFile, x, y, score);

    delete[] h_img;
    delete[] h_score;
    clReleaseMemObject(d_img);
    clReleaseMemObject(d_score);

    return testRes;
}

int main(int argc, char** argv)
{
    cl_device_type deviceType = CL_DEVICE_TYPE_ACCELERATOR;;
    int option_index = 0;
    std::string kernelFile("fast.cl");
    std::string imgFile("./data/square.pgm");
    int iteration = 1;
    int fast_thr = 20;
    bool verbose = false;
    // Commandline
    int c;
    while ((c = getopt_long(argc, argv, "d:k:f:i:t:vh", long_options, &option_index)) != -1)
    {
        switch (c)
        {
        case 0:
            if (long_options[option_index].flag != 0)
                break;
        case 'd':
            if (strcmp(optarg, "gpu") == 0)
                deviceType = CL_DEVICE_TYPE_GPU;
            else if (strcmp(optarg, "cpu") == 0)
                deviceType = CL_DEVICE_TYPE_CPU;
            else if (strcmp(optarg, "soft") == 0)
                deviceType = CL_DEVICE_TYPE_DEFAULT;
            else if (strcmp(optarg, "acc") != 0) {
                std::cout << "Incorrect platform specified\n";
                printHelp();
                return -1;
            }
            break;
        case 'k':
            kernelFile = optarg;
            break;
        case 'f':
            imgFile = optarg;
            break;
        case 'i':
            iteration = atoi(optarg);
            break;
        case 't':
            fast_thr = atoi(optarg);
            break;
        case 'h':
            printHelp();
            return 0;
        case 'v':
            verbose = true;
            break;
        default:
            printHelp();
            return 1;
        }
    }

    double delay = 0;
    if ((deviceType != CL_DEVICE_TYPE_DEFAULT) && runOpenCL(imgFile, kernelFile, deviceType,
                                                            iteration, fast_thr, verbose, delay)) {
        std::cout << "FAILED TEST\n";
        return 1;
    }
    //runOpenCL(imgFile, kernelFile, deviceType, iteration, fast_thr, verbose, delay);

    std::cout << "OpenCL total time: " << delay << " sec\n";
    std::cout << "OpenCL average time per iteration: " << delay/iteration << " sec\n";
    std::cout << "PASSED TEST\n";
    return 0;
}
<|endoftext|>