text:
//  (C) Copyright Johan Ditmar, Karel Hruda, Paul O'Neill & Luke Stedman 2009.
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).

#include <protean/detail/data_table_column.hpp>

#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/format.hpp>

namespace protean { namespace detail {

    /* Column setup implementation */
    /*******************************/
    template <variant_base::enum_type_t E>
    data_table& data_table::add_column(const std::string& name)
    {
        if (!m_columns.empty() && !get_column(0).empty())
            boost::throw_exception(variant_error("Cannot add a column since values have been inserted"));

        if (m_columns.size() >= DATA_TABLE_MAX_COLUMNS)
            boost::throw_exception(variant_error("Reached maximum column capacity"));

        for ( const auto& column : m_columns )
            if (column.name() == name)
                boost::throw_exception(variant_error("Column name already in use"));

        m_columns.push_back(new data_table_column<E>(name, m_capacity));

        return *this;
    }

    /* Push-back implementation */
    /****************************/
    template <typename Tuple>
    data_table& data_table::push_back(const Tuple& value)
    {
        size_t tuple_length = boost::tuples::length<Tuple>::value;
        if (tuple_length != m_columns.size())
            boost::throw_exception(variant_error(boost::str(
                boost::format("Cannot insert value with %s elements into series with %s columns")
                % tuple_length
                % m_columns.size()
            )));

        push_back_impl<0>(value);
        return *this;
    }

    template <size_t N, typename HT, typename TT>
    void data_table::push_back_impl(const boost::tuples::cons<HT, TT>& tuple)
    {
        get_column(N).push_back(tuple.get_head());
        push_back_impl<N+1>(tuple.get_tail());
    }

    template <size_t N, typename TT>
    void data_table::push_back_impl(const boost::tuples::cons<std::string, TT>& tuple)
    {
        get_column(N).push_back( detail::string(tuple.get_head().c_str(), tuple.get_head().size()) );
        push_back_impl<N+1>(tuple.get_tail());
    }

    template <size_t N>
    void data_table::push_back_impl(const boost::tuples::null_type&)
    {}

    /* Typed iterators implementation */
    /**********************************/
    #define COLUMN_BEGIN_ITERATOR(z, n, t) \
        get_column(n).begin<t ## n>()

    #define COLUMN_END_ITERATOR(z, n, t) \
        get_column(n).end<t ## n>()

    #define BEGIN_ITERATOR_DEF(z, n, t)                                                                     \
        template <BOOST_PP_ENUM_PARAMS(BOOST_PP_ADD(n, 1), variant_base::enum_type_t t)>                    \
        data_table_iterator<BOOST_PP_ENUM_PARAMS(BOOST_PP_ADD(n, 1), t)> data_table::begin()                \
        {                                                                                \
            return data_table_iterator<BOOST_PP_ENUM_PARAMS(BOOST_PP_ADD(n, 1), t)>(                        \
                make_row( BOOST_PP_ENUM(BOOST_PP_ADD(n, 1), COLUMN_BEGIN_ITERATOR, t) )                     \
            );                                                                                \
        }

    #define END_ITERATOR_DEF(z, n, t)                                                                       \
        template <BOOST_PP_ENUM_PARAMS(BOOST_PP_ADD(n, 1), variant_base::enum_type_t t)>                    \
        data_table_iterator<BOOST_PP_ENUM_PARAMS(BOOST_PP_ADD(n, 1), t)> data_table::end()                  \
        {                                                                                \
            return data_table_iterator<BOOST_PP_ENUM_PARAMS(BOOST_PP_ADD(n, 1), t)>(                        \
                make_row( BOOST_PP_ENUM(BOOST_PP_ADD(n, 1), COLUMN_END_ITERATOR, t) )                       \
            );                                                                                \
        }

    #define BEGIN_CONST_ITERATOR_DEF(z, n, t)                                                               \
        template <BOOST_PP_ENUM_PARAMS(BOOST_PP_ADD(n, 1), variant_base::enum_type_t t)>                    \
        data_table_const_iterator<BOOST_PP_ENUM_PARAMS(BOOST_PP_ADD(n, 1), t)> data_table::begin() const    \
        {                                                                                \
            return data_table_const_iterator<BOOST_PP_ENUM_PARAMS(BOOST_PP_ADD(n, 1), t)>(                  \
                make_row( BOOST_PP_ENUM(BOOST_PP_ADD(n, 1), COLUMN_BEGIN_ITERATOR, t) )                     \
            );                                                                                \
        }

    #define END_CONST_ITERATOR_DEF(z, n, t)                                                                 \
        template <BOOST_PP_ENUM_PARAMS(BOOST_PP_ADD(n, 1), variant_base::enum_type_t t)>                    \
        data_table_const_iterator<BOOST_PP_ENUM_PARAMS(BOOST_PP_ADD(n, 1), t)> data_table::end() const      \
        {                                                                                \
            return data_table_const_iterator<BOOST_PP_ENUM_PARAMS(BOOST_PP_ADD(n, 1), t)>(                  \
                make_row( BOOST_PP_ENUM(BOOST_PP_ADD(n, 1), COLUMN_END_ITERATOR, t) )                       \
            );                                                                                \
        }

    // data_table_iterator<T0, ..., Tn> begin() { ... }
    BOOST_PP_REPEAT(DATA_TABLE_MAX_COLUMNS, BEGIN_ITERATOR_DEF, DATA_TABLE_COLUMN_TYPE_PREFIX)
    // data_table_iterator<T0, ..., Tn> end() { ... }
    BOOST_PP_REPEAT(DATA_TABLE_MAX_COLUMNS, END_ITERATOR_DEF, DATA_TABLE_COLUMN_TYPE_PREFIX)
    // data_table_const_iterator<T0, ..., Tn> begin() const { ... }
    BOOST_PP_REPEAT(DATA_TABLE_MAX_COLUMNS, BEGIN_CONST_ITERATOR_DEF, DATA_TABLE_COLUMN_TYPE_PREFIX)
    // data_table_const_iterator<T0, ..., Tn> end() const { ... }
    BOOST_PP_REPEAT(DATA_TABLE_MAX_COLUMNS, END_CONST_ITERATOR_DEF, DATA_TABLE_COLUMN_TYPE_PREFIX)

}} // namespace protean::detail

ext: ipp

max_stars_repo_name: llawall/protean

max_issues_repo_name: llawall/protean

max_forks_repo_name: llawall/protean


text:
/*
 * @CopyRight:
 * FISCO-BCOS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FISCO-BCOS 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with FISCO-BCOS.  If not, see <http://www.gnu.org/licenses/>
 * (c) 2016-2018 fisco-dev contributors.
 */
/**
 * @brief : unitest for DAG(Directed Acyclic Graph) basic implement
 * @author: jimmyshi
 * @date: 2019-1-9
 */

#include <libblockverifier/DAG.h>
#include <test/tools/libutils/TestOutputHelper.h>
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <set>

using namespace std;
using namespace dev;
using namespace dev::blockverifier;

namespace dev
{
namespace test
{
BOOST_FIXTURE_TEST_SUITE(DAGTest, TestOutputHelperFixture)

bool have(set<ID>& _set, ID _id)
{
    return _set.find(_id) != _set.end();
}

void consumeAndPush(DAG& _dag, ID _id, set<ID>& _topSet)
{
    ID top = _dag.consume(_id);
    if (top != INVALID_ID)
        _topSet.insert(top);
}

BOOST_AUTO_TEST_CASE(DAGPopConsumeTest)
{
    DAG dag;
    dag.init(9);
    dag.addEdge(0, 1);
    dag.addEdge(1, 2);
    dag.addEdge(4, 5);
    dag.addEdge(2, 4);
    dag.addEdge(3, 4);
    dag.addEdge(0, 3);
    dag.addEdge(6, 7);
    // single 8 vertex

    // BOOST_CHECK(dag.isQueueEmpty());

    dag.generate();
    // BOOST_CHECK(!dag.isQueueEmpty());

    set<ID> topSet;
    for (int i = 0; i < 9; i++)
    {
        auto id = dag.waitPop(false);
        std::cout << "pop " << id << std::endl;
        if (id == INVALID_ID)
        {
            break;
        }
        topSet.insert(id);
    }
    BOOST_CHECK_EQUAL(topSet.size(), 3);
    BOOST_CHECK(have(topSet, 0));
    BOOST_CHECK(have(topSet, 6));
    BOOST_CHECK(have(topSet, 8));
    topSet.clear();
    consumeAndPush(dag, 0, topSet);
    std::cout << "consume " << 0 << std::endl;
    consumeAndPush(dag, 6, topSet);
    std::cout << "consume " << 6 << std::endl;
    consumeAndPush(dag, 8, topSet);
    std::cout << "consume " << 8 << std::endl;

    for (int i = 0; i < 9; i++)
    {
        auto id = dag.waitPop(false);
        std::cout << "pop " << id << std::endl;
        if (id == INVALID_ID)
        {
            break;
        }
        topSet.insert(id);
    }
    BOOST_CHECK_EQUAL(topSet.size(), 3);
    BOOST_CHECK(have(topSet, 1));
    BOOST_CHECK(have(topSet, 3));
    BOOST_CHECK(have(topSet, 7));
    topSet.clear();
    consumeAndPush(dag, 1, topSet);
    std::cout << "consume " << 1 << std::endl;
    consumeAndPush(dag, 3, topSet);
    std::cout << "consume " << 3 << std::endl;
    consumeAndPush(dag, 7, topSet);
    std::cout << "consume " << 7 << std::endl;

    for (int i = 0; i < 9; i++)
    {
        auto id = dag.waitPop(false);
        std::cout << "pop " << id << std::endl;
        if (id == INVALID_ID)
        {
            break;
        }
        topSet.insert(id);
    }
    BOOST_CHECK_EQUAL(topSet.size(), 1);
    BOOST_CHECK(have(topSet, 2));
    topSet.clear();
    consumeAndPush(dag, 2, topSet);
    std::cout << "consume " << 2 << std::endl;

    for (int i = 0; i < 9; i++)
    {
        auto id = dag.waitPop(false);
        std::cout << "pop " << id << std::endl;
        if (id == INVALID_ID)
        {
            break;
        }
        topSet.insert(id);
    }
    BOOST_CHECK_EQUAL(topSet.size(), 1);
    BOOST_CHECK(have(topSet, 4));
    topSet.clear();
    consumeAndPush(dag, 4, topSet);
    std::cout << "consume " << 4 << std::endl;

    for (int i = 0; i < 9; i++)
    {
        auto id = dag.waitPop(false);
        std::cout << "pop " << id << std::endl;
        if (id == INVALID_ID)
        {
            break;
        }
        topSet.insert(id);
    }
    BOOST_CHECK_EQUAL(topSet.size(), 1);
    BOOST_CHECK(have(topSet, 5));
    topSet.clear();
    consumeAndPush(dag, 5, topSet);
    std::cout << "consume " << 5 << std::endl;

    for (int i = 0; i < 9; i++)
    {
        auto id = dag.waitPop(false);
        std::cout << "pop " << id << std::endl;
        if (id == INVALID_ID)
        {
            break;
        }
        topSet.insert(id);
    }
    BOOST_CHECK_EQUAL(topSet.size(), 0);
}

BOOST_AUTO_TEST_SUITE_END()
}  // namespace test
}  // namespace dev

ext: cpp

max_stars_repo_name: imtypist/FISCO-BCOS

max_issues_repo_name: imtypist/FISCO-BCOS

max_forks_repo_name: imtypist/FISCO-BCOS


text:
//---------------------------------------------------------------------------//
//!
//! \file   Utility_OneDDistribution.hpp
//! \author Alex Robinson
//! \brief  One-dimensional distribution class declaration
//!
//---------------------------------------------------------------------------//

#ifndef UTILITY_ONE_D_DISTRIBUTION_HPP
#define UTILITY_ONE_D_DISTRIBUTION_HPP

// Std Lib Includes
#include <limits>
#include <stdexcept>
#include <iostream>

// Boost Includes
#include <boost/units/quantity.hpp>
#include <boost/mpl/and.hpp>
#include <boost/utility/enable_if.hpp>

// FRENSIE Includes
#include "Utility_OneDDistributionType.hpp"
#include "Utility_ComparePolicy.hpp"
#include "Utility_UnitTraits.hpp"
#include "Utility_QuantityTraits.hpp"
#include "Utility_ExceptionTestMacros.hpp"

/*! \defgroup one_d_distributions One-Dimensional Distributions
 */

namespace Utility{

/*! The unit-aware one-dimensional distribution
 * \details When the IndependentUnit type and/or the DependentUnit type
 * resolves to void, the IndepQuantity and/or the DepQuantity type reduces to
 * double respectively.
 * \ingroup one_d_distributions
 */
template<typename IndependentUnit, typename DependentUnit = void>
class UnitAwareOneDDistribution
{

protected:

  //! The independent unit traits typedef
  typedef UnitTraits<IndependentUnit> IndepUnitTraits;

  //! The inverse independent unit traits typedef
  typedef UnitTraits<typename UnitTraits<IndependentUnit>::InverseUnit> InverseIndepUnitTraits;

  //! The dependent unit traits typedef
  typedef UnitTraits<DependentUnit> DepUnitTraits;

  //! The distribution normalization unit traits typedef
  typedef UnitTraits<typename UnitTraits<typename UnitTraits<DependentUnit>::InverseUnit>::template GetMultipliedUnitType<typename UnitTraits<IndependentUnit>::InverseUnit>::type> DistNormUnitTraits;

  //! The distribution normalization quantity type
  typedef typename DistNormUnitTraits::template GetQuantityType<double>::type DistNormQuantity;

public:

  //! The independent unit type
  typedef IndependentUnit IndepUnit;

  //! The dependent unit type
  typedef DependentUnit DepUnit;

  //! The independent quantity type
  typedef typename IndepUnitTraits::template GetQuantityType<double>::type IndepQuantity;

  //! The inverse independent quantity type
  typedef typename InverseIndepUnitTraits::template GetQuantityType<double>::type InverseIndepQuantity;

  //! The dependent quantity type
  typedef typename DepUnitTraits::template GetQuantityType<double>::type DepQuantity;

  //! Constructor
  UnitAwareOneDDistribution()
  { /* ... */ }

  //! Destructor
  virtual ~UnitAwareOneDDistribution()
  { /* ... */ }

  //! Evaluate the distribution
  virtual DepQuantity evaluate( const IndepQuantity indep_var_value ) const = 0;

  //! Evaluate the PDF
  virtual InverseIndepQuantity evaluatePDF( const IndepQuantity indep_var_value ) const = 0;

  //! Return a random sample from the distribution
  virtual IndepQuantity sample() const = 0;

  //! Return a random sample and record the number of trials
  virtual IndepQuantity sampleAndRecordTrials( unsigned& trials ) const = 0;

  //! Return the upper bound of the distribution independent variable
  virtual IndepQuantity getUpperBoundOfIndepVar() const = 0;

  //! Return the lower bound of the distribution independent variable
  virtual IndepQuantity getLowerBoundOfIndepVar() const = 0;

  //! Return the distribution type
  virtual OneDDistributionType getDistributionType() const = 0;

  //! Test if the distribution is tabular
  virtual bool isTabular() const;

  //! Test if the distribution is continuous
  virtual bool isContinuous() const = 0;

  //! Test if the distribution has the same bounds
  bool hasSameBounds( const UnitAwareOneDDistribution<IndependentUnit,DependentUnit>& distribution ) const;
};

// Test if the distribution is tabular
template<typename IndependentUnit, typename DependentUnit>
inline bool UnitAwareOneDDistribution<IndependentUnit,DependentUnit>::isTabular() const
{
  return false;
}

// Test if the distribution has the same bounds
template<typename IndependentUnit, typename DependentUnit>
inline bool UnitAwareOneDDistribution<IndependentUnit,DependentUnit>::hasSameBounds(
	const UnitAwareOneDDistribution<IndependentUnit,DependentUnit>& distribution ) const
{
  return
    Policy::relError( getRawQuantity( this->getUpperBoundOfIndepVar() ),
		      getRawQuantity( distribution.getUpperBoundOfIndepVar() ))
    < 1e-9 &&
    Policy::relError( getRawQuantity( this->getLowerBoundOfIndepVar() ),
		      getRawQuantity( distribution.getLowerBoundOfIndepVar() ))
    < 1e-9;
}

/*! The one-dimensional distribution (unit-agnostic)
 * \ingroup one_d_distributions
 */
typedef UnitAwareOneDDistribution<void,void> OneDDistribution;

//! The invalid distribution string name error
class InvalidDistributionStringName : public std::logic_error
{

public:

  InvalidDistributionStringName( const std::string& what_arg )
    : std::logic_error( what_arg )
  { /* ... */ }
};

/*! The invalid distribution string representation error
 * \ingroup one_d_distributions
 */
class InvalidDistributionStringRepresentation : public std::logic_error
{

public:

  InvalidDistributionStringRepresentation( const std::string& what_arg )
    : std::logic_error( what_arg )
  { /* ... */ }
};

/*! Macro for restricting distribution units to a certain dimension
 *
 * \details Certain distributions only make sense when defined on a certain
 * dimension (e.g. energy). This macro will prevent improper use of a
 * distribution by preventing the distribution template instance from
 * compiling when the template parameter has the incorrect dimension. Void
 * will also be allowed (needed for creating unit-agnostic distribution). If
 * the compiler shows "__unit_has_invalid_dimension_if_visible__" then you
 * know that an attempt to use a unit with a restricted dimension was made,
 * which should help remedy the error faster (given that boost::units
 * template errors can be intimidating!). This macro can only be used
 * once - using it multiple times in the same header will prevent your
 * distribution from working with any dimension! It is safe to place it
 * anywhere in the distribution class declaration.
 * \ingroup one_d_distributions
 */
#define RESTRICT_UNIT_TO_BOOST_DIMENSION( Unit, Dim )\
typedef typename boost::enable_if<boost::mpl::or_<typename boost::is_same<typename UnitTraits<Unit>::Dimension,boost::units::Dim>::type,typename boost::is_same<typename UnitTraits<Unit>::Dimension,void>::type> >::type __unit_has_invalid_dimension_if_visible__

/*! Macro for excluding a unit from a certain dimension
 *
 * \details Certain distributions do not make sense when defined on a
 * certain dimension. This macro will prevent improper use of a distribution
 * by preventing the distribution template instance from compiling when
 * the template parameter has the incorrect dimension. If the compiler shows
 * "__unit_has_invalid_dimension_if_visible__" then you know that an attempt
 * to use a unit with a restricted dimension was made, which should help remedy
 * the error faster (given that boost::units template errors can be
 * intimidating!). This macro can be used as many times as desired in a
 * distribution header file, but only once per dimension (obviously). It is
 * safe to place it anywhere in the distribution class declaration.
 * \ingroup one_d_distributions
 */
#define RESTRICT_UNIT_FROM_BOOST_DIMENSION( Unit, Dim )\
typedef typename boost::disable_if<typename boost::is_same<typename UnitTraits<Unit>::Dimension,boost::units::Dim>::type>,Unit>::type __unit_has_invalid_ ## Dim ## _if_visible__

} // end Utility namespace

#endif // end UTILITY_ONE_D_DISTRIBUTION_HPP

//---------------------------------------------------------------------------//
// end Utility_OneDDistribution.hpp
//---------------------------------------------------------------------------//

ext: hpp


text:
#include "main.h"
#include "boinc.h"
#include "util.h"

#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include "diagnosticsdialog.h"
#include "ui_diagnosticsdialog.h"
#include "neuralnet/researcher.h"
#include "upgrade.h"

#include <numeric>
#include <fstream>

DiagnosticsDialog::DiagnosticsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DiagnosticsDialog)
{
    ui->setupUi(this);
}

DiagnosticsDialog::~DiagnosticsDialog()
{
    delete ui;
}

unsigned int DiagnosticsDialog::GetNumberOfTestsPending()
{
    LOCK(cs_diagnostictests);

    unsigned int pending_count = 0;

    for (const auto& entry : test_status_map)
    {
        if (entry.second == pending) pending_count++;
    }

    return pending_count;
}

DiagnosticsDialog::DiagnosticTestStatus DiagnosticsDialog::GetTestStatus(std::string test_name)
{
    LOCK(cs_diagnostictests);

    auto entry = test_status_map.find(test_name);

    if (entry != test_status_map.end())
    {
        return entry->second;
    }
    else
    {
        return unknown;
    }
}

unsigned int DiagnosticsDialog::UpdateTestStatus(std::string test_name, DiagnosticTestStatus test_status)
{
    LOCK(cs_diagnostictests);

    test_status_map[test_name] = test_status;

    return test_status_map.size();
}

void DiagnosticsDialog::ResetOverallDiagnosticResult(unsigned int& number_of_tests_in)
{
    LOCK(cs_diagnostictests);

    number_of_tests = number_of_tests_in;

    test_status_map.clear();

    diagnostic_result_status = pending;

    diagnostic_result = NA;
}

void DiagnosticsDialog::UpdateOverallDiagnosticResult(DiagnosticResult diagnostic_result_in)
{
    LOCK(cs_diagnostictests);

    // Set diagnostic_result_status to completed. This is under lock, so no one can snoop.
    diagnostic_result_status = completed;

    // If the total number of registered tests is less than the initialized number, then
    // the overall status is pending by default.
    if (test_status_map.size() < number_of_tests)
    {
        diagnostic_result_status = pending;
    }

    diagnostic_result = (DiagnosticResult) std::max<int>(diagnostic_result_in,  diagnostic_result);

    // If diagnostic_result_status is still set to completed, then at least all tests
    // are registered. Walk through the map of tests one by one and check the status.
    // The first one encountered that is pending means the overall status is pending.
    if (diagnostic_result_status == completed)
    {
        for (const auto& entry : test_status_map)
        {
            if (entry.second == pending)
            {
                diagnostic_result_status = pending;
                break;
            }
        }
    }
}

// Lock should be taken on cs_diagnostictests before calling this function.
DiagnosticsDialog::DiagnosticResult DiagnosticsDialog::GetOverallDiagnosticResult()
{
    return diagnostic_result;
}

// Lock should be taken on cs_diagnostictests before calling this function.
DiagnosticsDialog::DiagnosticTestStatus DiagnosticsDialog::GetOverallDiagnosticStatus()
{
    return diagnostic_result_status;
}

void DiagnosticsDialog::DisplayOverallDiagnosticResult()
{
    LOCK(cs_diagnostictests);

    if (GetOverallDiagnosticStatus() == pending)
    {
        ui->overallResultResultLabel->setText(tr("Testing..."));
        ui->overallResultResultLabel->setStyleSheet("");
    }
    else
    {
        // Overall status must be completed, so display overall result
        switch (GetOverallDiagnosticResult())
        {
        case NA:
            ui->overallResultResultLabel->clear();
            ui->overallResultResultLabel->setStyleSheet("");
            break;

        case passed:
            ui->overallResultResultLabel->setText(tr("Passed"));
            ui->overallResultResultLabel->setStyleSheet("color:white;background-color:green");
            break;

        case warning:
            ui->overallResultResultLabel->setText(tr("Warning"));
            ui->overallResultResultLabel->setStyleSheet("color:black;background-color:yellow");
            break;

        case failed:
            ui->overallResultResultLabel->setText(tr("Failed"));
            ui->overallResultResultLabel->setStyleSheet("color:white;background-color:red");
        }
    }

    this->repaint();
}

bool DiagnosticsDialog::VerifyBoincPath()
{
    boost::filesystem::path boincPath = (boost::filesystem::path) GetBoincDataDir();

    if (boincPath.empty())
        boincPath = (boost::filesystem::path) GetArgument("boincdatadir", "");

    boincPath = boincPath / "client_state.xml";

    return boost::filesystem::exists(boincPath) ? true : false;
}

bool DiagnosticsDialog::VerifyIsCPIDValid()
{
    boost::filesystem::path clientStatePath = GetBoincDataDir();

    if (!clientStatePath.empty())
        clientStatePath = clientStatePath / "client_state.xml";

    else
        clientStatePath = (boost::filesystem::path) GetArgument("boincdatadir", "") / "client_state.xml";

    if (clientStatePath.empty())
        return false;

    fsbridge::ifstream clientStateStream;
    std::string clientState;

    clientStateStream.open(clientStatePath);
    clientState.assign((std::istreambuf_iterator<char>(clientStateStream)), std::istreambuf_iterator<char>());
    clientStateStream.close();

    size_t pos = 0;
    std::string cpid;

    if ((pos = clientState.find("<external_cpid>")) != std::string::npos)
    {
        cpid = clientState.substr(pos + 15, clientState.length());
        pos = cpid.find("</external_cpid>");
        cpid.erase(pos, cpid.length());
    }

    return (NN::Researcher::Get()->Id().ToString() == cpid) ? true : false;
}

bool DiagnosticsDialog::VerifyCPIDIsInNeuralNetwork()
{
    return NN::Researcher::Get()->Eligible();
}

bool DiagnosticsDialog::VerifyWalletIsSynced()
{
    int64_t nwalletAge = PreviousBlockAge();

    return (nwalletAge < (60 * 60)) ? true : false;
}

bool DiagnosticsDialog::VerifyCPIDHasRAC()
{
    double racValue = 0;

    boost::filesystem::path clientStatePath = (boost::filesystem::path) GetBoincDataDir();

    if (!clientStatePath.empty())
        clientStatePath = clientStatePath / "client_state.xml";

    else
        clientStatePath = (boost::filesystem::path) GetArgument("boincdatadir", "") / "client_state.xml";

    if (clientStatePath.empty())
        return false;

    fsbridge::ifstream clientStateStream;
    std::string clientState;
    std::vector<std::string> racStrings;

    clientStateStream.open(clientStatePath.string());
    clientState.assign((std::istreambuf_iterator<char>(clientStateStream)), std::istreambuf_iterator<char>());
    clientStateStream.close();

    if (clientState.length() > 0)
    {
        size_t pos = 0;
        std::string delim = "</user_expavg_credit>";
        std::string line;

        while ((pos = clientState.find(delim)) != std::string::npos)
        {
            line = clientState.substr(0, pos);
            clientState.erase(0, pos + delim.length());
            pos = line.find("<user_expavg_credit>");
            racStrings.push_back(line.substr(pos + 20, line.length()));
        }

        for (auto const& racString : racStrings)
        {
            try
            {
                racValue += std::stod(racString);
            }

            catch (std::exception& ex)
            {
                continue;
            }
        }
    }

    return (racValue >= 1) ? true : false;
}

double DiagnosticsDialog::VerifyETTSReasonable()
{
    // We are going to compute the ETTS with ignore_staking_status set to true
    // and also use a 960 block diff as the input, which smooths out short
    // term fluctuations. The standard 1-1/e confidence (mean) is used.

    double diff = GetAverageDifficulty(960);

    double result = GetEstimatedTimetoStake(true, diff);

    return result;
}

int DiagnosticsDialog::VerifyCountSeedNodes()
{
    LOCK(cs_vNodes);

    int count = 0;

    for (auto const& vnodes : vNodes)
        if (!vnodes->fInbound)
            count++;

    return count;
}

int DiagnosticsDialog::VerifyCountConnections()
{
    LOCK(cs_vNodes);

    return (int)vNodes.size();
}

void DiagnosticsDialog::on_testButton_clicked()
{
    // Check to see if there is already a test run in progress, and if so return.
    // We do not want overlapping test runs.

    if (GetNumberOfTestsPending())
    {
        LogPrintf("INFO: DiagnosticsDialog::on_testButton_clicked: Tests still in progress from a prior run: %u", GetNumberOfTestsPending());
        this->repaint();
        return;
    }

    // This needs to be updated if there are more tests added.
    unsigned int number_of_tests = 11;

    ResetOverallDiagnosticResult(number_of_tests);
    DisplayOverallDiagnosticResult();

    // Tests that are N/A if in investor mode.
    if (NN::Researcher::ConfiguredForInvestorMode())
    {
        // N/A tests for investor mode
        ui->boincPathResultLabel->setText(tr("N/A"));
        ui->boincPathResultLabel->setStyleSheet("color:black;background-color:grey");
        UpdateTestStatus("boincPath", completed);

        ui->verifyCPIDValidResultLabel->setText(tr("N/A"));
        ui->verifyCPIDValidResultLabel->setStyleSheet("color:black;background-color:grey");
        UpdateTestStatus("verifyCPIDValid", completed);

        ui->verifyCPIDHasRACResultLabel->setText(tr("N/A"));
        ui->verifyCPIDHasRACResultLabel->setStyleSheet("color:black;background-color:grey");
        UpdateTestStatus("verifyCPIDHasRAC", completed);

        ui->verifyCPIDIsInNNResultLabel->setText(tr("N/A"));
        ui->verifyCPIDIsInNNResultLabel->setStyleSheet("color:black;background-color:grey");
        UpdateTestStatus("verifyCPIDIsInNN", completed);

        ui->checkETTSResultLabel->setText(tr("N/A"));
        ui->checkETTSResultLabel->setStyleSheet("color:black;background-color:grey");
        UpdateTestStatus("checkETTS", completed);

    }
    else
    {
        //BOINC path
        ui->boincPathResultLabel->setStyleSheet("");
        ui->boincPathResultLabel->setText(tr("Testing..."));
        UpdateTestStatus("boincPath", pending);
        this->repaint();

        if (VerifyBoincPath())
        {
            ui->boincPathResultLabel->setText(tr("Passed"));
            ui->boincPathResultLabel->setStyleSheet("color:white;background-color:green");
            UpdateTestStatus("boincPath", completed);
            UpdateOverallDiagnosticResult(passed);
        }
        else
        {
            ui->boincPathResultLabel->setText(tr("Failed"));
            ui->boincPathResultLabel->setStyleSheet("color:white;background-color:red");
            UpdateTestStatus("boincPath", completed);
            UpdateOverallDiagnosticResult(failed);
        }

        //CPID valid
        ui->verifyCPIDValidResultLabel->setStyleSheet("");
        ui->verifyCPIDValidResultLabel->setText(tr("Testing..."));
        UpdateTestStatus("verifyCPIDValid", pending);
        this->repaint();

        if (VerifyIsCPIDValid())
        {
            ui->verifyCPIDValidResultLabel->setText(tr("Passed"));
            ui->verifyCPIDValidResultLabel->setStyleSheet("color:white;background-color:green");
            UpdateTestStatus("verifyCPIDValid", completed);
            UpdateOverallDiagnosticResult(passed);
        }
        else
        {
            ui->verifyCPIDValidResultLabel->setText(tr("Failed: BOINC CPID does not match CPID"));
            ui->verifyCPIDValidResultLabel->setStyleSheet("color:white;background-color:red");
            UpdateTestStatus("verifyCPIDValid", completed);
            UpdateOverallDiagnosticResult(failed);
        }

        //CPID has rac
        ui->verifyCPIDHasRACResultLabel->setStyleSheet("");
        ui->verifyCPIDHasRACResultLabel->setText(tr("Testing..."));
        UpdateTestStatus("verifyCPIDHasRAC", pending);
        this->repaint();

        if (VerifyCPIDHasRAC())
        {
            ui->verifyCPIDHasRACResultLabel->setText(tr("Passed"));
            ui->verifyCPIDHasRACResultLabel->setStyleSheet("color:white;background-color:green");
            UpdateTestStatus("verifyCPIDHasRAC", completed);
            UpdateOverallDiagnosticResult(passed);

        }
        else
        {
            ui->verifyCPIDHasRACResultLabel->setText(tr("Failed"));
            ui->verifyCPIDHasRACResultLabel->setStyleSheet("color:white;background-color:red");
            UpdateTestStatus("verifyCPIDHasRAC", completed);
            UpdateOverallDiagnosticResult(failed);
        }

        //cpid is in nn
        ui->verifyCPIDIsInNNResultLabel->setStyleSheet("");
        ui->verifyCPIDIsInNNResultLabel->setText(tr("Testing..."));
        UpdateTestStatus("verifyCPIDIsInNN", pending);
        this->repaint();

        if (VerifyCPIDIsInNeuralNetwork())
        {
            ui->verifyCPIDIsInNNResultLabel->setText(tr("Passed"));
            ui->verifyCPIDIsInNNResultLabel->setStyleSheet("color:white;background-color:green");
            UpdateTestStatus("verifyCPIDIsInNN", completed);
            UpdateOverallDiagnosticResult(passed);
        }
        else
        {
            ui->verifyCPIDIsInNNResultLabel->setText(tr("Failed"));
            ui->verifyCPIDIsInNNResultLabel->setStyleSheet("color:white;background-color:red");
            UpdateTestStatus("verifyCPIDIsInNN", completed);
            UpdateOverallDiagnosticResult(failed);
        }

        // verify reasonable ETTS
        // This is only checked if wallet is a researcher wallet because the purpose is to
        // alert the owner that his stake time is too long and therefore there is a chance
        // of research rewards loss between stakes due to the 180 day limit.
        ui->checkETTSResultLabel->setStyleSheet("");
        ui->checkETTSResultLabel->setText(tr("Testing..."));
        UpdateTestStatus("checkETTS", pending);

        double ETTS = VerifyETTSReasonable() / (24.0 * 60.0 * 60.0);

        std::string rounded_ETTS;

        //round appropriately for display.
        if (ETTS >= 100)
        {
            rounded_ETTS = RoundToString(ETTS, 0);
        }
        else if (ETTS >= 10)
        {
            rounded_ETTS = RoundToString(ETTS, 1);
        }
        else
        {
            rounded_ETTS = RoundToString(ETTS, 2);
        }

        // ETTS of zero actually means no coins, i.e. infinite.
        if (ETTS == 0.0)
        {
            ui->checkETTSResultLabel->setText(tr("Failed: ETTS is infinite. No coins to stake."));
            ui->checkETTSResultLabel->setStyleSheet("color:white;background-color:red");
            UpdateTestStatus("checkETTS", completed);
            UpdateOverallDiagnosticResult(failed);
        }
        else if (ETTS > 90.0)
        {
            ui->checkETTSResultLabel->setText(tr("Failed: ETTS = %1 > 90 days")
                                              .arg(QString(rounded_ETTS.c_str())));
            ui->checkETTSResultLabel->setStyleSheet("color:white;background-color:red");
            UpdateTestStatus("checkETTS", completed);
            UpdateOverallDiagnosticResult(failed);
        }
        else if (ETTS > 45.0 && ETTS <= 90.0)
        {
            ui->checkETTSResultLabel->setText(tr("Warning: 45 days < ETTS = %1 <= 90 days")
                                              .arg(QString(rounded_ETTS.c_str())));
            ui->checkETTSResultLabel->setStyleSheet("color:black;background-color:yellow");
            UpdateTestStatus("checkETTS", completed);
            UpdateOverallDiagnosticResult(warning);
        }
        else
        {
            ui->checkETTSResultLabel->setText(tr("Passed: ETTS = %1 <= 45 days")
                                              .arg(QString(rounded_ETTS.c_str())));
            ui->checkETTSResultLabel->setStyleSheet("color:white;background-color:green");
            UpdateTestStatus("checkETTS", completed);
            UpdateOverallDiagnosticResult(passed);
        }
    }

    // Tests that are common to both investor and researcher mode.
    // wallet synced
    ui->verifyWalletIsSyncedResultLabel->setStyleSheet("");
    ui->verifyWalletIsSyncedResultLabel->setText(tr("Testing..."));
    UpdateTestStatus("verifyWalletIsSynced", pending);
    this->repaint();

    if (VerifyWalletIsSynced())
    {
        ui->verifyWalletIsSyncedResultLabel->setText(tr("Passed"));
        ui->verifyWalletIsSyncedResultLabel->setStyleSheet("color:white;background-color:green");
        UpdateTestStatus("verifyWalletIsSynced", completed);
        UpdateOverallDiagnosticResult(passed);
    }

    else
    {
        ui->verifyWalletIsSyncedResultLabel->setText(tr("Failed"));
        ui->verifyWalletIsSyncedResultLabel->setStyleSheet("color:white;background-color:red");
        UpdateTestStatus("verifyWalletIsSynced", completed);
        UpdateOverallDiagnosticResult(failed);
    }

    // clock
    ui->verifyClockResultLabel->setStyleSheet("");
    ui->verifyClockResultLabel->setText(tr("Testing..."));
    UpdateTestStatus("verifyClockResult", pending);
    this->repaint();

    VerifyClock();

    // seed nodes
    ui->verifySeedNodesResultLabel->setStyleSheet("");
    ui->verifySeedNodesResultLabel->setText(tr("Testing..."));
    UpdateTestStatus("verifySeedNodes", pending);
    this->repaint();

    unsigned int seed_node_connections = VerifyCountSeedNodes();

    if (seed_node_connections >= 1 && seed_node_connections < 3)
    {
        ui->verifySeedNodesResultLabel->setText(tr("Warning: Count = %1 (Pass = 3+)").arg(QString::number(seed_node_connections)));
        ui->verifySeedNodesResultLabel->setStyleSheet("color:black;background-color:yellow");
        UpdateTestStatus("verifySeedNodes", completed);
        UpdateOverallDiagnosticResult(warning);
    }
    else if(seed_node_connections >= 3)
    {
        ui->verifySeedNodesResultLabel->setText(tr("Passed: Count = %1").arg(QString::number(seed_node_connections)));
        ui->verifySeedNodesResultLabel->setStyleSheet("color:white;background-color:green");
        UpdateTestStatus("verifySeedNodes", completed);
        UpdateOverallDiagnosticResult(passed);
    }
    else
    {
        ui->verifySeedNodesResultLabel->setText(tr("Failed: Count = %1").arg(QString::number(seed_node_connections)));
        ui->verifySeedNodesResultLabel->setStyleSheet("color:white;background-color:red");
        UpdateTestStatus("verifySeedNodes", completed);
        UpdateOverallDiagnosticResult(failed);
    }

    // connection count
    ui->verifyConnectionsResultLabel->setStyleSheet("");
    ui->verifyConnectionsResultLabel->setText(tr("Testing..."));
    UpdateTestStatus("verifyConnections", pending);
    this->repaint();

    unsigned int connections = VerifyCountConnections();

    if (connections <= 7 && connections >= 1)
    {
        ui->verifyConnectionsResultLabel->setText(tr("Warning: Count = %1 (Pass = 8+)").arg(QString::number(connections)));
        ui->verifyConnectionsResultLabel->setStyleSheet("color:black;background-color:yellow");
        UpdateTestStatus("verifyConnections", completed);
        UpdateOverallDiagnosticResult(warning);
    }
    else if (connections >= 8)
    {
        ui->verifyConnectionsResultLabel->setText(tr("Passed: Count = %1").arg(QString::number(connections)));
        ui->verifyConnectionsResultLabel->setStyleSheet("color:white;background-color:green");
        UpdateTestStatus("verifyConnections", completed);
        UpdateOverallDiagnosticResult(passed);
    }
    else
    {
        ui->verifyConnectionsResultLabel->setText(tr("Failed: Count = %1").arg(QString::number(connections)));
        ui->verifyConnectionsResultLabel->setStyleSheet("color:white;background-color:red");
        UpdateTestStatus("verifyConnections", completed);
        UpdateOverallDiagnosticResult(failed);
    }

    // tcp port
    ui->verifyTCPPortResultLabel->setStyleSheet("");
    ui->verifyTCPPortResultLabel->setText(tr("Testing..."));
    UpdateTestStatus("verifyTCPPort", pending);
    this->repaint();

    VerifyTCPPort();

    // client version
    ui->checkClientVersionResultLabel->setStyleSheet("");
    ui->checkClientVersionResultLabel->setText(tr("Testing..."));
    UpdateTestStatus("checkClientVersion", pending);

    std::string client_message;

    if (g_UpdateChecker->CheckForLatestUpdate(false, client_message))
    {
        ui->checkClientVersionResultLabel->setText(tr("Warning: New Client version available:\n %1").arg(QString(client_message.c_str())));
        ui->checkClientVersionResultLabel->setStyleSheet("color:black;background-color:yellow;height:2em");
        UpdateTestStatus("checkClientVersion", completed);
        UpdateOverallDiagnosticResult(warning);
    }
    else
    {
        ui->checkClientVersionResultLabel->setText(tr("Passed"));
        ui->checkClientVersionResultLabel->setStyleSheet("color:white;background-color:green");
        UpdateTestStatus("checkClientVersion", completed);
        UpdateOverallDiagnosticResult(passed);
    }

    DisplayOverallDiagnosticResult();
}

void DiagnosticsDialog::VerifyClock()
{
    QTimer *timerVerifyClock = new QTimer();

    // Set up a timeout clock of 10 seconds as a fail-safe.
    connect(timerVerifyClock, SIGNAL(timeout()), this, SLOT(clkFinished()));
    timerVerifyClock->start(10 * 1000);

    QHostInfo NTPHost = QHostInfo::fromName("pool.ntp.org");
    udpSocket = new QUdpSocket(this);

    connect(udpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(clkStateChanged(QAbstractSocket::SocketState)));
    connect(udpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(clkSocketError()));

    udpSocket->connectToHost(QHostAddress(NTPHost.addresses().first()), 123, QIODevice::ReadWrite);
}

void DiagnosticsDialog::clkStateChanged(QAbstractSocket::SocketState state)
{
    if (state == QAbstractSocket::ConnectedState)
    {
        connect(udpSocket, SIGNAL(readyRead()), this, SLOT(clkFinished()));

        char NTPMessage[48] = {0x1b, 0, 0, 0 ,0, 0, 0, 0, 0};

        udpSocket->write(NTPMessage, sizeof(NTPMessage));
    }

    return;
}

void DiagnosticsDialog::clkSocketError()
{
    udpSocket->close();

    // Call clkFinished to handle.
    clkFinished();

    return;
}

void DiagnosticsDialog::clkFinished()
{
    if (udpSocket->waitForReadyRead(10 * 1000))
    {
        int64_t start_time = GetAdjustedTime();

        // Only allow this loop to run for 5 seconds maximum.
        while (udpSocket->hasPendingDatagrams() && GetAdjustedTime() - start_time <= 5)
        {
            QByteArray BufferSocket = udpSocket->readAll();

            if (BufferSocket.size() == 48)
            {
                int nNTPCount = 40;
                unsigned long DateTimeIn = uchar(BufferSocket.at(nNTPCount)) + (uchar(BufferSocket.at(nNTPCount + 1)) << 8) + (uchar(BufferSocket.at(nNTPCount + 2)) << 16) + (uchar(BufferSocket.at(nNTPCount + 3)) << 24);
                long tmit = ntohl((time_t)DateTimeIn);
                tmit -= 2208988800U;

                udpSocket->close();

                boost::posix_time::ptime localTime = boost::posix_time::microsec_clock::universal_time();
                boost::posix_time::ptime networkTime = boost::posix_time::from_time_t(tmit);
                boost::posix_time::time_duration timeDiff = networkTime - localTime;

                if (timeDiff.minutes() < 3)
                {
                    ui->verifyClockResultLabel->setText(tr("Passed"));
                    ui->verifyClockResultLabel->setStyleSheet("color:white;background-color:green");
                    UpdateTestStatus("verifyClockResult", completed);

                    // We need this here because there is no return call (callback) to the on_testButton_clicked function
                    UpdateOverallDiagnosticResult(passed);
                }
                else
                {
                    ui->verifyClockResultLabel->setText(tr("Failed: Sync local time with network"));
                    ui->verifyClockResultLabel->setStyleSheet("color:white;background-color:red");
                    UpdateTestStatus("verifyClockResult", completed);

                    // We need this here because there is no return call (callback) to the on_testButton_clicked function
                    UpdateOverallDiagnosticResult(failed);
                }

                // We need this here because there is no return call (callback) to the on_testButton_clicked function
                DisplayOverallDiagnosticResult();

                return;
            }
        }
    }
    else // The other state here is a socket or other indeterminate error such as a timeout (coming from clkSocketError).
    {
        // This is needed to "cancel" the timeout timer. Essentially if the test was marked completed via the normal exits
        // above, then when the timer calls clkFinished again, it will hit this conditional and be a no-op.
        if (GetTestStatus("verifyClockResult") != completed)
        {
            ui->verifyClockResultLabel->setText(tr("Warning: Cannot connect to NTP server"));
            ui->verifyClockResultLabel->setStyleSheet("color:black;background-color:yellow");
            UpdateTestStatus("verifyClockResult", completed);

            // We need this here because there is no return call (callback) to the on_testButton_clicked function
            UpdateOverallDiagnosticResult(warning);

            DisplayOverallDiagnosticResult();
        }

        return;
    }
}

void DiagnosticsDialog::VerifyTCPPort()
{
    tcpSocket = new QTcpSocket(this);

    connect(tcpSocket, SIGNAL(connected()), this, SLOT(TCPFinished()));
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(TCPFailed(QAbstractSocket::SocketError)));

    tcpSocket->connectToHost("portquiz.net", GetListenPort());
}

void DiagnosticsDialog::TCPFinished()
{
    tcpSocket->close();
    ui->verifyTCPPortResultLabel->setText(tr("Passed"));
    ui->verifyTCPPortResultLabel->setStyleSheet("color:white;background-color:green");

    // We need this here because there is no return call (callback) to the on_testButton_clicked function
    UpdateTestStatus("verifyTCPPort", completed);
    UpdateOverallDiagnosticResult(passed);

    DisplayOverallDiagnosticResult();

    return;
}

void DiagnosticsDialog::TCPFailed(QAbstractSocket::SocketError socket)
{
    ui->verifyTCPPortResultLabel->setText(tr("Warning: Port 32749 may be blocked by your firewall"));
    ui->verifyTCPPortResultLabel->setStyleSheet("color:black;background-color:yellow");

    // We need this here because there is no return call (callback) to the on_testButton_clicked function
    UpdateTestStatus("verifyTCPPort", completed);
    UpdateOverallDiagnosticResult(failed);

    DisplayOverallDiagnosticResult();

    return;
}

max_stars_repo_name: theMarix/Gridcoin-Research

max_issues_repo_name: theMarix/Gridcoin-Research

max_forks_repo_name: theMarix/Gridcoin-Research


text:
#ifndef TMC_UNIT_TESTS
#define BOOST_TEST_MODULE lib_test_sample_creator
#endif
#include <boost/test/included/unit_test.hpp>

#include "sample_creator.h"

BOOST_AUTO_TEST_SUITE( sample_creator )

BOOST_AUTO_TEST_CASE( from_stream ) {
    std::string names_buffer("| this is comment\n"
                             "target_feature.| one more comment\n"
                             "\n"
                             "   feature1: continuous.   \n"
                             "feature2: continuous.   | third comment\n"
                             "feature3: ignore.\n"
                             "feature4: continuous.\n"
                             "target_feature: v1, v2.\n"
                             "case weight: continuous.\n"
                             "feature5: continuous.\n"
                             "\n"
                             "  | one more comment here\n"
                             "\n");
    BOOST_TEST_MESSAGE("Creating sample from names buffer:\n"
                               << "#######################################################\n"
                               << names_buffer
                               << "#######################################################");
    std::stringstream ss_names((std::stringstream(names_buffer)));
    std::shared_ptr<FeatureNames> pFN = std::make_shared<FeatureNames>(ss_names);

    std::string data_buffer("11,22,34,44,v2,1,77\n"
                            "12,22,34,44,v1,2,77\n"
                            "14,22,34,44,v2,3,77\n"
                            "11,22,34,44,v1,4,77\n"
                            "11,23,34,44,v2,5,77\n"
                            "11,23,34,44,v2,6,77\n"
                            "11,23,34,44,v2,7,77\n"
    );
    BOOST_TEST_MESSAGE("Pushing data from buffer:\n"
                               << "#######################################################\n"
                               << data_buffer
                               << "#######################################################");
    std::stringstream ss_buffer((std::stringstream(data_buffer)));

    SampleCreator sample_creator;
    sample_creator.set_feature_names(pFN);
    std::shared_ptr<Sample> pSample = sample_creator.from_stream(ss_buffer);
    BOOST_TEST_MESSAGE("Resulting sample: " << *pSample);
    BOOST_CHECK_EQUAL(pSample->dim(), 4);
    BOOST_CHECK_EQUAL(pSample->size(), 4);
    BOOST_CHECK((*pSample)[0]->get_data() == std::vector<double>({11,22,44,77}) );
    BOOST_CHECK((*pSample)[1]->get_data() == std::vector<double>({12,22,44,77}) );
    BOOST_CHECK((*pSample)[2]->get_data() == std::vector<double>({14,22,44,77}) );
    BOOST_CHECK((*pSample)[3]->get_data() == std::vector<double>({11,23,44,77}) );
    BOOST_CHECK_EQUAL((*pSample)[0]->get_weight_negatives(), 4);
    BOOST_CHECK_EQUAL((*pSample)[0]->get_weight_positives(), 1);
    BOOST_CHECK_EQUAL((*pSample)[1]->get_weight_negatives(), 2);
    BOOST_CHECK_EQUAL((*pSample)[1]->get_weight_positives(), 0);
    BOOST_CHECK_EQUAL((*pSample)[2]->get_weight_negatives(), 0);
    BOOST_CHECK_EQUAL((*pSample)[2]->get_weight_positives(), 3);
    BOOST_CHECK_EQUAL((*pSample)[3]->get_weight_negatives(), 0);
    BOOST_CHECK_EQUAL((*pSample)[3]->get_weight_positives(), 18);
}

BOOST_AUTO_TEST_CASE( from_file ) {
    const std::string names_file("data/tmc_paper_9/tmc_paper.names");
    const std::string data_file("data/tmc_paper_9/tmc_paper.data");

    std::shared_ptr<FeatureNames> pFN = std::make_shared<FeatureNames>(names_file);

    SampleCreator sample_creator;
    sample_creator.set_feature_names(pFN);
    BOOST_TEST_MESSAGE("Creating sample from file: " << data_file);
    std::shared_ptr<Sample> pSample = sample_creator.from_file(data_file);

    BOOST_TEST_MESSAGE("Resulting sample: " << *pSample);
    BOOST_CHECK_EQUAL(pSample->dim(), 2);
    BOOST_CHECK_EQUAL(pSample->size(), 4);
}

BOOST_AUTO_TEST_CASE( neg_pos_count ) {
    std::string names_buffer("| this is comment\n"
                             "target_feature.| one more comment\n"
                             "\n"
                             "   feature1: continuous.   \n"
                             "feature2: continuous.   | third comment\n"
                             "feature3: ignore.\n"
                             "feature4: continuous.\n"
                             "target_feature: v1, v2.\n"
                             "case weight: continuous.\n"
                             "feature5: continuous.\n"
                             "\n"
                             "  | one more comment here\n"
                             "\n");
    BOOST_TEST_MESSAGE("Creating sample from names buffer:\n"
                               << "#######################################################\n"
                               << names_buffer
                               << "#######################################################");
    std::stringstream ss_names((std::stringstream(names_buffer)));
    std::shared_ptr<FeatureNames> pFN = std::make_shared<FeatureNames>(ss_names);

    std::string data_buffer("11,22,34,44,v2,1,77\n"
                            "12,22,34,44,v1,2,77\n"
                            "14,22,34,44,v2,3,77\n"
                            "11,22,34,44,v1,4,77\n"
                            "11,23,34,44,v2,5,77\n"
                            "11,23,34,44,v2,6,77\n"
                            "11,23,34,44,v2,7,77\n"
    );
    BOOST_TEST_MESSAGE("Pushing data from buffer:\n"
                               << "#######################################################\n"
                               << data_buffer
                               << "#######################################################");
    std::stringstream ss_buffer((std::stringstream(data_buffer)));

    SampleCreator sample_creator1;
    sample_creator1.set_feature_names(pFN);
    std::shared_ptr<Sample> pSample = sample_creator1.from_stream(ss_buffer);
    BOOST_TEST_MESSAGE("Resulting sample: " << *pSample);
 }

BOOST_AUTO_TEST_CASE( comparison_and_merge ) {
    std::string names_buffer("| this is comment\n"
                             "target_feature.| one more comment\n"
                             "\n"
                             "   feature1: continuous.   \n"
                             "feature2: continuous.   | third comment\n"
                             "feature3: ignore.\n"
                             "feature4: continuous.\n"
                             "target_feature: v1, v2.\n"
                             "case weight: continuous.\n"
                             "feature5: continuous.\n"
                             "\n"
                             "  | one more comment here\n"
                             "\n");
    std::stringstream ss_names((std::stringstream(names_buffer)));
    std::shared_ptr<FeatureNames> pFN = std::make_shared<FeatureNames>(ss_names);

    std::string data_buffer1("11,22,34,44,v2,1,77\n"
                            "12,22,34,44,v1,2,77\n"
                            "14,22,34,44,v2,3,77\n"
                            );
    std::string data_buffer2("14,22,34,44,v2,3,77\n"
                             "11,22,34,43,v1,4,77\n"
                             );
    std::string data_buffer3("14,22,34,45,v2,3,77\n"
                             "11,22,34,45,v1,4,77\n"
                             "11,23,34,44,v2,5,77\n"
                             );
    std::string data_buffer4("15,22,34,45,v2,3,77\n"
                             "12,23,34,45,v1,4,77\n"
                             "13,23,4,44,v2,5,77\n"
                             );

    std::stringstream ss_buffer1((std::stringstream(data_buffer1)));
    std::stringstream ss_buffer2((std::stringstream(data_buffer2)));
    std::stringstream ss_buffer3((std::stringstream(data_buffer3)));
    std::stringstream ss_buffer4((std::stringstream(data_buffer4)));

    SampleCreator sample_creator;
    sample_creator.set_feature_names(pFN);

    std::shared_ptr<Sample> pSample1 = sample_creator.from_stream(ss_buffer1);
    std::shared_ptr<Sample> pSample2 = sample_creator.from_stream(ss_buffer2);
    std::shared_ptr<Sample> pSample3 = sample_creator.from_stream(ss_buffer3);
    std::shared_ptr<Sample> pSample4 = sample_creator.from_stream(ss_buffer4);
    BOOST_TEST_MESSAGE("Sample1: " << *pSample1);
    BOOST_TEST_MESSAGE("Sample2: " << *pSample2);
    BOOST_TEST_MESSAGE("Sample3: " << *pSample3);
    BOOST_TEST_MESSAGE("Sample4: " << *pSample4);

    BOOST_CHECK_EQUAL(pSample2->has_no_intersection_with(*pSample1), false);
    BOOST_CHECK_EQUAL(pSample1->has_no_intersection_with(*pSample2), false);
    BOOST_CHECK_EQUAL(pSample3->has_no_intersection_with(*pSample1), true);
    BOOST_CHECK_EQUAL(pSample1->has_no_intersection_with(*pSample3), true);
    BOOST_CHECK_GE( *pSample4, *pSample3 );
    BOOST_CHECK_LE( *pSample3, *pSample4 );
    BOOST_CHECK( !(*pSample4 <= *pSample3) );
    BOOST_CHECK( !(*pSample3 >= *pSample4) );
    BOOST_CHECK( !(*pSample1 <= *pSample2) );
    BOOST_CHECK( !(*pSample1 >= *pSample2) );
    BOOST_CHECK( !(*pSample2 <= *pSample1) );
    BOOST_CHECK( !(*pSample2 >= *pSample1) );

    std::shared_ptr<Sample> pSample12 = sample_creator.merge(pSample1, pSample2);
    BOOST_TEST_MESSAGE("Merged Sample12: " << *pSample12);
    BOOST_CHECK_EQUAL(pSample12->size(), 4);
}

BOOST_AUTO_TEST_CASE( split ) {
    std::string names_buffer("| this is comment\n"
                             "target_feature.| one more comment\n"
                             "\n"
                             "   feature1: continuous.   \n"
                             "feature2: continuous.   | third comment\n"
                             "feature3: ignore.\n"
                             "feature4: ignore.\n"
                             "target_feature: v1, v2.\n"
                             "case weight: continuous.\n"
                             "feature5: ignore.\n"
                             "\n"
                             "  | one more comment here\n"
                             "\n");
    std::stringstream ss_names((std::stringstream(names_buffer)));
    std::shared_ptr<FeatureNames> pFN = std::make_shared<FeatureNames>(ss_names);
    std::string data_buffer1("1,8,34,44,v2,1,77\n"
                             "2,2,34,44,v1,2,77\n"
                             "2,5,34,44,v2,3,77\n"
                             "3,7,34,44,v2,1,77\n"
                             "3,9,34,44,v1,2,77\n"
                             "4,1,34,44,v2,3,77\n"
                             "4,5,34,44,v2,1,77\n"
                             "5,8,34,44,v1,2,77\n"
                             "6,0,34,44,v2,3,77\n"
                             "7,1,34,44,v2,3,77\n"
                             "7,5,34,44,v2,3,77\n"
                             "8,2,34,44,v2,3,77\n"
                             );
    std::stringstream ss_buffer1((std::stringstream(data_buffer1)));

    SampleCreator sample_creator1;
    sample_creator1.set_feature_names(pFN);

    std::shared_ptr<Sample> pSample1 = sample_creator1.from_stream(ss_buffer1);
    BOOST_TEST_MESSAGE("Sample1: " << *pSample1);

    std::shared_ptr<Sample> pLower;
    std::shared_ptr<Sample> pUpper;

    boost::dynamic_bitset<> db(pSample1->size());
    db[3] = db[4] = db[7] = true;

    SampleCreator sample_creator2;
    std::tie(pLower,pUpper) = sample_creator2.split_sample(pSample1, db);
    BOOST_TEST_MESSAGE("Lower subsample: " << *pLower);
    BOOST_TEST_MESSAGE("Upper subsample: " << *pUpper);

    BOOST_CHECK(pSample1->dim() == pLower->dim());
    BOOST_CHECK_EQUAL(pUpper->size(),3);
    BOOST_CHECK_EQUAL(pUpper->size() + pLower->size(), pSample1->size());
    BOOST_CHECK_EQUAL(pUpper->get_neg_pos_counts().first + pLower->get_neg_pos_counts().first , pSample1->get_neg_pos_counts().first );
    BOOST_CHECK_EQUAL(pUpper->get_neg_pos_counts().second  + pLower->get_neg_pos_counts().second, pSample1->get_neg_pos_counts().second);

    BOOST_CHECK(pLower->contains((*pSample1)[0]));
    BOOST_CHECK(pLower->contains((*pSample1)[1]));
    BOOST_CHECK(pLower->contains((*pSample1)[5]));
    BOOST_CHECK(pLower->contains((*pSample1)[6]));

    BOOST_CHECK(pUpper->contains((*pSample1)[4]));
    BOOST_CHECK(pUpper->contains((*pSample1)[7]));
    BOOST_CHECK(pUpper->contains((*pSample1)[3]));

    BOOST_CHECK_GE(*pUpper, *pLower);
    BOOST_CHECK_LE(*pLower, *pUpper);
    BOOST_CHECK(!(*pUpper <= *pLower));
    BOOST_CHECK(!(*pLower >= *pUpper));
    BOOST_CHECK(pLower->has_no_intersection_with(*pUpper));
    BOOST_CHECK(pUpper->has_no_intersection_with(*pLower));
}

BOOST_AUTO_TEST_SUITE_END()

ext: cc

max_stars_repo_name: tmcombi/tmcombi

max_issues_repo_name: tmcombi/tmcombi

max_forks_repo_name: tmcombi/tmcombi


text:
////////////////////////////////////////////////////////////////////////////////////////////////////
// grammar.hpp
// Contains all Proto's grammar-building facilities.
//
//  Copyright 2012 Eric Niebler. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_PROTO_V5_GRAMMAR_HPP_INCLUDED
#define BOOST_PROTO_V5_GRAMMAR_HPP_INCLUDED

#include <boost/proto/v5/grammar/basic_grammar.hpp>
#include <boost/proto/v5/grammar/and.hpp>
#include <boost/proto/v5/grammar/case.hpp>
#include <boost/proto/v5/grammar/expr.hpp>
#include <boost/proto/v5/grammar/if.hpp>
#include <boost/proto/v5/grammar/match.hpp>
#include <boost/proto/v5/grammar/not.hpp>
#include <boost/proto/v5/grammar/or.hpp>
#include <boost/proto/v5/grammar/placeholders.hpp>
#include <boost/proto/v5/grammar/switch.hpp>

#endif


text:
/*=============================================================================
    Copyright (c) 2007 Tobias Schwinger

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/

#if !defined(BOOST_FUSION_REPETITIVE_VIEW_BEGIN_IMPL_HPP_INCLUDED)
#define BOOST_FUSION_REPETITIVE_VIEW_BEGIN_IMPL_HPP_INCLUDED

#include <boost/fusion/sequence/intrinsic/begin.hpp>
#include <boost/fusion/support/config.hpp>
#include <boost/fusion/view/repetitive_view/repetitive_view_fwd.hpp>

namespace boost {
namespace fusion {
struct repetitive_view_tag;

template <typename Sequence, typename Pos> struct repetitive_view_iterator;

namespace extension {
template <typename Tag> struct begin_impl;

template <> struct begin_impl<repetitive_view_tag> {
  template <typename View> struct apply {
    typedef typename View::sequence_type sequence_type;

    typedef repetitive_view_iterator<
        sequence_type, typename result_of::begin<sequence_type>::type>
        type;

    BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static type call(View const &v) {
      return type(v.seq);
    }
  };
};

} // namespace extension

} // namespace fusion
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
/*
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 *
 * (C) Copyright 2013 Andrey Semashev
 */
/*!
 * \file   exceptions/overflow_error.hpp
 *
 * \brief  This header defines the \c overflow_error exception.
 */

#ifndef BOOST_SYNC_EXCEPTIONS_OVERFLOW_ERROR_HPP_INCLUDED_
#define BOOST_SYNC_EXCEPTIONS_OVERFLOW_ERROR_HPP_INCLUDED_

#include <string>
#include <boost/sync/detail/config.hpp>
#include <boost/sync/detail/system_error.hpp>
#include <boost/sync/exceptions/runtime_exception.hpp>
#include <boost/sync/detail/header.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

namespace boost {

namespace sync {

class BOOST_SYMBOL_VISIBLE overflow_error :
    public runtime_exception
{
public:
    explicit overflow_error(int sys_err = static_cast< int >(sync::detail::system_ns::errc::value_too_large)) : runtime_exception(sys_err, "boost::sync::overflow_error")
    {
    }

    overflow_error(int sys_err, const char* what) : runtime_exception(sys_err, what)
    {
    }

    overflow_error(int sys_err, std::string const& what) : runtime_exception(sys_err, what)
    {
    }

    ~overflow_error() BOOST_NOEXCEPT_OR_NOTHROW
    {
    }
};

} // namespace sync

} // namespace boost

#include <boost/sync/detail/footer.hpp>

#endif // BOOST_SYNC_EXCEPTIONS_OVERFLOW_ERROR_HPP_INCLUDED_

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
// Copyright 2020 Hannah Rittich
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef ALLIUM_LA_EIGEN_SPARSE_MATRIX_HPP
#define ALLIUM_LA_EIGEN_SPARSE_MATRIX_HPP

#include "sparse_matrix.hpp"
#include "eigen_vector.hpp"
#include "linear_operator.hpp"
#include <allium/util/except.hpp>
#include <Eigen/Sparse>

namespace allium {
  /** @cond INTERNAL */
  template <typename N>
  class triplet_iterator final {
    public:
      typedef typename std::vector<MatrixEntry<N>>::iterator base_iterator;

      typedef typename base_iterator::difference_type difference_type;
      typedef Eigen::Triplet<N> value_type;
      typedef const Eigen::Triplet<N> *pointer;
      typedef const Eigen::Triplet<N> &reference;
      typedef std::forward_iterator_tag iterator_category;

      explicit triplet_iterator(base_iterator base) : base(base) {};

      bool operator!= (const triplet_iterator& other) const {
        return base != other.base;
      }

      reference operator* () {
        current = Eigen::Triplet<N>(base->row(),
                                    base->col(),
                                    base->value());
        return current;
      }

      pointer operator-> () {
        return &(**this);
      }

      triplet_iterator& operator++ () {
        ++base;
        return *this;
      }
    private:
      base_iterator base;
      Eigen::Triplet<N> current;
  };
  /** @endcond */

  /**
    @brief A sparse matrix implementation based on Eigen.
   */
  template <typename N>
  class EigenSparseMatrixStorage final
      : public SparseMatrixStorage<EigenVectorStorage<N>>
		{
    public:
      using Vector = EigenVectorStorage<N>;
      using DefaultVector = EigenVectorStorage<N>;
      using SparseMatrixStorage<Vector>::Number;
      using SparseMatrixStorage<Vector>::Real;
      using SparseMatrixStorage<Vector>::row_spec;
      using SparseMatrixStorage<Vector>::col_spec;

      EigenSparseMatrixStorage(VectorSpec rows, VectorSpec cols)
        : SparseMatrixStorage<Vector>(rows, cols),
          m_mat(rows.global_size(), cols.global_size()) {}

      void set_entries(LocalCooMatrix<N> lmat) override {
        auto entries = std::move(lmat).entries();

        m_mat.setFromTriplets(
          triplet_iterator<N>(entries.begin()),
          triplet_iterator<N>(entries.end()));
      };

      LocalCooMatrix<N> get_entries() override {
        LocalCooMatrix<N> lmat;

        for (long k=0; k < m_mat.outerSize(); ++k) {
          for (typename Eigen::SparseMatrix<N>::InnerIterator it(m_mat,k); it; ++it)
          {
            lmat.add(it.row(), it.col(), it.value());
          }
        }

        return lmat;
      }

      void apply(EigenVectorStorage<N>& result, const EigenVectorStorage<N>& arg) {
        result.native() = m_mat * arg.native();
      }

    private:
      Eigen::SparseMatrix<N> m_mat;
  };
}

#endif

max_stars_repo_name: hrittich/allium