<commit_before>#ifndef MJOLNIR_PERIODIC_GRID_CELL_LIST
#define MJOLNIR_PERIODIC_GRID_CELL_LIST
#include <mjolnir/core/System.hpp>
#include <mjolnir/core/NeighborList.hpp>
#include <mjolnir/core/ExclusionList.hpp>
#include <mjolnir/util/range.hpp>
#include <mjolnir/util/logger.hpp>
#include <iostream>
#include <vector>
#include <cmath>
#include <cassert>

namespace mjolnir
{

// XXX: almost same as UnlimitedGridCellList.
// the difference between UnlimitedGridCellList is only the number of cells.
// PeriodicGridCellList can optimize the number of cells using boundary size.
template<typename traitsT, typename parameterT>
class PeriodicGridCellList
{
  public:
    using traits_type         = traitsT;
    using system_type         = System<traits_type>;
    using real_type           = typename traits_type::real_type;
    using coordinate_type     = typename traits_type::coordinate_type;
    using exclusion_list_type = ExclusionList;
    using parameter_type      = parameterT;
    using neighbor_list_type  = NeighborList<parameter_type>;
    using neighbor_type       = typename neighbor_list_type::neighbor_type;
    using range_type          = typename neighbor_list_type::range_type;

    constexpr static real_type mesh_epsilon = 1e-6;

    using particle_cell_idx_pair    = std::pair<std::size_t, std::size_t>;
    using cell_index_container_type = std::vector<particle_cell_idx_pair>;
    using cell_index_const_iterator = typename cell_index_container_type::const_iterator;
    using adjacent_cell_idx         = std::array<std::size_t, 27>;
    using cell_type                 = std::pair<range<cell_index_const_iterator>, adjacent_cell_idx>;
    using cell_list_type            = std::vector<cell_type>;

  public:

    PeriodicGridCellList()
        : cutoff_(0), margin_(1), current_margin_(-1),
          r_x_(-1), r_y_(-1), r_z_(-1), dim_x_(0), dim_y_(0), dim_z_(0)
    {}
    ~PeriodicGridCellList() = default;
    PeriodicGridCellList(PeriodicGridCellList const&) = default;
    PeriodicGridCellList(PeriodicGridCellList &&)     = default;
    PeriodicGridCellList& operator=(PeriodicGridCellList const&) = default;
    PeriodicGridCellList& operator=(PeriodicGridCellList &&)     = default;

    explicit PeriodicGridCellList(const real_type margin)
        : cutoff_(0), margin_(margin), current_margin_(-1),
          r_x_(-1), r_y_(-1), r_z_(-1), dim_x_(0), dim_y_(0), dim_z_(0)
    {}

    bool valid() const noexcept
    {
        return current_margin_ >= 0.0;
    }

    template<typename PotentialT>
    void initialize(const system_type& sys, const PotentialT& pot);

    template<typename PotentialT>
    void reconstruct(const system_type& sys, const PotentialT& pot)
    {
        this->initialize(sys, pot); // do the same thing as `initialize`
        return;
    }

    template<typename PotentialT>
    void make  (const system_type& sys, const PotentialT& pot);

    template<typename PotentialT>
    void update(const real_type, const system_type&, const PotentialT&);

    real_type cutoff() const {return this->cutoff_;}
    real_type margin() const {return this->margin_;}

    range_type partners(std::size_t i) const noexcept {return neighbors_[i];}

  private:

    std::size_t calc_index(const coordinate_type& pos) const noexcept
    {
        const auto ofs = pos - this->lower_bound_;
        return this->calc_index(std::floor(math::X(ofs) * this->r_x_),
                                std::floor(math::Y(ofs) * this->r_y_),
                                std::floor(math::Z(ofs) * this->r_z_));
    }

    std::size_t calc_index(const std::size_t i, const std::size_t j,
                           const std::size_t k) const noexcept
    {
        return i + this->dim_x_ * j + this->dim_x_ * this->dim_y_ * k;
    }

    void set_cutoff(const real_type c) noexcept
    {
        this->cutoff_ = c;
        this->r_x_ = 1 / (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);
        this->r_y_ = 1 / (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);
        this->r_z_ = 1 / (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);
        return;
    }
    void set_margin(const real_type m) noexcept
    {
        this->margin_ = m;
        this->r_x_ = 1.0 / (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);
        this->r_y_ = 1.0 / (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);
        this->r_z_ = 1.0 / (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);
        return;
    }

  private:

    real_type   cutoff_;
    real_type   margin_;
    real_type   current_margin_;
    real_type   r_x_;
    real_type   r_y_;
    real_type   r_z_;
    std::size_t dim_x_;
    std::size_t dim_y_;
    std::size_t dim_z_;

    coordinate_type     lower_bound_;
    neighbor_list_type  neighbors_;
    exclusion_list_type exclusion_;
    cell_list_type      cell_list_;
    cell_index_container_type index_by_cell_;
    // index_by_cell_ has {particle idx, cell idx} and sorted by cell idx
    // first term of cell list contains first and last idx of index_by_cell
};

template<typename traitsT, typename parameterT>
template<typename PotentialT>
void PeriodicGridCellList<traitsT, parameterT>::update(
        const real_type dmargin, const system_type& sys, const PotentialT& pot)
{
    this->current_margin_ -= dmargin;
    if(this->current_margin_ < 0.)
    {
        this->make(sys, pot);
    }
    return ;
}

template<typename traitsT, typename parameterT>
template<typename PotentialT>
void PeriodicGridCellList<traitsT, parameterT>::make(
        const system_type& sys, const PotentialT& pot)
{
    MJOLNIR_GET_DEFAULT_LOGGER_DEBUG();
    MJOLNIR_LOG_FUNCTION_DEBUG();

    neighbors_.clear();
    index_by_cell_.resize(sys.size());

    for(std::size_t i=0; i<sys.size(); ++i)
    {
        index_by_cell_[i] = std::make_pair(i, calc_index(sys[i].position));
    }

    std::sort(this->index_by_cell_.begin(), this->index_by_cell_.end(),
        [](const std::pair<std::size_t, std::size_t>& lhs,
           const std::pair<std::size_t, std::size_t>& rhs) noexcept -> bool
        {
            return lhs.second < rhs.second;
        });

    { // assign first and last iterator for each cells
        auto iter = index_by_cell_.cbegin();
        for(std::size_t i=0; i<cell_list_.size(); ++i)
        {
            if(iter == index_by_cell_.cend() || i != iter->second)
            {
                cell_list_[i].first = make_range(iter, iter);
                continue;
            }
            const auto first = iter;
            while(iter != index_by_cell_.cend() && i == iter->second)
            {
                ++iter;
            }
            cell_list_[i].first = make_range(first, iter);
        }
    }

    MJOLNIR_LOG_DEBUG("cell list is updated");

    const real_type r_c  = cutoff_ * (1. + margin_);
    const real_type r_c2 = r_c * r_c;
    for(std::size_t i=0; i<sys.size(); ++i)
    {
        const auto& ri = sys[i].position;
        const auto& cell = cell_list_[calc_index(ri)];

        MJOLNIR_LOG_DEBUG("particle position", sys[i].position);
        MJOLNIR_LOG_DEBUG("making verlet list for index", i);
        MJOLNIR_LOG_DEBUG("except list for ", i, "-th value");

        std::vector<neighbor_type> partner;
        for(std::size_t cidx : cell.second) // for all adjacent cells...
        {
            for(auto pici : cell_list_[cidx].first)
            {
                const auto j = pici.first;
                MJOLNIR_LOG_DEBUG("looking particle", j);
                if(j <= i || this->exclusion_.is_excluded(i, j))
                {
                    continue;
                }

                if(math::length_sq(sys.adjust_direction(sys[j].position - ri)) < r_c2)
                {
                    MJOLNIR_LOG_DEBUG("add index", j, "to verlet list", i);
                    partner.emplace_back(j, pot.prepair_params(i, j));
                }
            }
        }
        // make the result consistent with NaivePairCalculation...
        std::sort(partner.begin(), partner.end());
        this->neighbors_.add_list_for(i, partner.begin(), partner.end());
    }

    this->current_margin_ = cutoff_ * margin_;
    return ;
}

template<typename traitsT, typename parameterT>
template<typename PotentialT>
void PeriodicGridCellList<traitsT, parameterT>::initialize(
        const system_type& sys, const PotentialT& pot)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_LOG_FUNCTION();

    const real_type max_cutoff = pot.max_cutoff_length();
    this->set_cutoff(max_cutoff);
    this->exclusion_.make(sys, pot);

    MJOLNIR_LOG_INFO(pot.name(), " cutoff = ", max_cutoff);

    this->lower_bound_ = sys.boundary().lower_bound();
    const auto system_size = sys.boundary().width();

    this->dim_x_ = std::max<std::size_t>(3, std::floor(math::X(system_size) * r_x_));
    this->dim_y_ = std::max<std::size_t>(3, std::floor(math::Y(system_size) * r_y_));
    this->dim_z_ = std::max<std::size_t>(3, std::floor(math::Z(system_size) * r_z_));

    MJOLNIR_LOG_INFO("dimension = ", dim_x_, 'x', dim_y_, 'x', dim_z_);

    if(dim_x_ == 3 || dim_y_ == 3 || dim_z_ == 3)
    {
        MJOLNIR_LOG_WARN("system size is too small (",
                dim_x_, 'x', dim_y_, 'x', dim_z_,
                "). This might cause a problem. Please check the cutoff ratio"
                " and the box size!");
    }

    // it may expand cell a bit (to fit system range)
    this->r_x_ = 1.0 / (math::X(system_size) / this->dim_x_);
    this->r_y_ = 1.0 / (math::Y(system_size) / this->dim_y_);
    this->r_z_ = 1.0 / (math::Z(system_size) / this->dim_z_);

    MJOLNIR_LOG_DEBUG("reciplocal width of cells in x coordinate = ", r_x_);
    MJOLNIR_LOG_DEBUG("reciplocal width of cells in y coordinate = ", r_y_);
    MJOLNIR_LOG_DEBUG("reciplocal width of cells in z coordinate = ", r_z_);

    this->cell_list_.resize(dim_x_ * dim_y_ * dim_z_);

    for(int x = 0; x < dim_x_; ++x)
    {
    for(int y = 0; y < dim_y_; ++y)
    {
    for(int z = 0; z < dim_z_; ++z)
    {
        auto& cell = this->cell_list_[calc_index(x, y, z)];

        const std::size_t x_prev = (x ==        0) ? dim_x_-1 : x-1;
        const std::size_t x_next = (x == dim_x_-1) ?        0 : x+1;
        const std::size_t y_prev = (y ==        0) ? dim_y_-1 : y-1;
        const std::size_t y_next = (y == dim_y_-1) ?        0 : y+1;
        const std::size_t z_prev = (z ==        0) ? dim_z_-1 : z-1;
        const std::size_t z_next = (z == dim_z_-1) ?        0 : z+1;

        cell.second[ 0] = calc_index(x_prev, y_prev, z_prev);
        cell.second[ 1] = calc_index(x,      y_prev, z_prev);
        cell.second[ 2] = calc_index(x_next, y_prev, z_prev);
        cell.second[ 3] = calc_index(x_prev, y,      z_prev);
        cell.second[ 4] = calc_index(x,      y,      z_prev);
        cell.second[ 5] = calc_index(x_next, y,      z_prev);
        cell.second[ 6] = calc_index(x_prev, y_next, z_prev);
        cell.second[ 7] = calc_index(x,      y_next, z_prev);
        cell.second[ 8] = calc_index(x_next, y_next, z_prev);

        cell.second[ 9] = calc_index(x_prev, y_prev, z);
        cell.second[10] = calc_index(x,      y_prev, z);
        cell.second[11] = calc_index(x_next, y_prev, z);
        cell.second[12] = calc_index(x_prev, y,      z);
        cell.second[13] = calc_index(x,      y,      z);
        cell.second[14] = calc_index(x_next, y,      z);
        cell.second[15] = calc_index(x_prev, y_next, z);
        cell.second[16] = calc_index(x,      y_next, z);
        cell.second[17] = calc_index(x_next, y_next, z);

        cell.second[18] = calc_index(x_prev, y_prev, z_next);
        cell.second[19] = calc_index(x,      y_prev, z_next);
        cell.second[20] = calc_index(x_next, y_prev, z_next);
        cell.second[21] = calc_index(x_prev, y,      z_next);
        cell.second[22] = calc_index(x,      y,      z_next);
        cell.second[23] = calc_index(x_next, y,      z_next);
        cell.second[24] = calc_index(x_prev, y_next, z_next);
        cell.second[25] = calc_index(x,      y_next, z_next);
        cell.second[26] = calc_index(x_next, y_next, z_next);

        auto uniq = std::unique(cell.second.begin(), cell.second.end());
        assert(uniq == cell.second.end());
        for(auto i : cell.second)
        {
            assert(0 <= i && i <= cell_list_.size());
        }
    }
    }
    }
    this->make(sys, pot);
    return;
}

} // mjolnir
#endif /* MJOLNIR_PERIODIC_GRID_CELL_LIST */
<commit_msg>refactor: remove cmp between int and uint<commit_after>#ifndef MJOLNIR_PERIODIC_GRID_CELL_LIST
#define MJOLNIR_PERIODIC_GRID_CELL_LIST
#include <mjolnir/core/System.hpp>
#include <mjolnir/core/NeighborList.hpp>
#include <mjolnir/core/ExclusionList.hpp>
#include <mjolnir/util/range.hpp>
#include <mjolnir/util/logger.hpp>
#include <iostream>
#include <vector>
#include <cmath>
#include <cassert>

namespace mjolnir
{

// XXX: almost same as UnlimitedGridCellList.
// the difference between UnlimitedGridCellList is only the number of cells.
// PeriodicGridCellList can optimize the number of cells using boundary size.
template<typename traitsT, typename parameterT>
class PeriodicGridCellList
{
  public:
    using traits_type         = traitsT;
    using system_type         = System<traits_type>;
    using real_type           = typename traits_type::real_type;
    using coordinate_type     = typename traits_type::coordinate_type;
    using exclusion_list_type = ExclusionList;
    using parameter_type      = parameterT;
    using neighbor_list_type  = NeighborList<parameter_type>;
    using neighbor_type       = typename neighbor_list_type::neighbor_type;
    using range_type          = typename neighbor_list_type::range_type;

    constexpr static real_type mesh_epsilon = 1e-6;

    using particle_cell_idx_pair    = std::pair<std::size_t, std::size_t>;
    using cell_index_container_type = std::vector<particle_cell_idx_pair>;
    using cell_index_const_iterator = typename cell_index_container_type::const_iterator;
    using adjacent_cell_idx         = std::array<std::size_t, 27>;
    using cell_type                 = std::pair<range<cell_index_const_iterator>, adjacent_cell_idx>;
    using cell_list_type            = std::vector<cell_type>;

  public:

    PeriodicGridCellList()
        : cutoff_(0), margin_(1), current_margin_(-1),
          r_x_(-1), r_y_(-1), r_z_(-1), dim_x_(0), dim_y_(0), dim_z_(0)
    {}
    ~PeriodicGridCellList() = default;
    PeriodicGridCellList(PeriodicGridCellList const&) = default;
    PeriodicGridCellList(PeriodicGridCellList &&)     = default;
    PeriodicGridCellList& operator=(PeriodicGridCellList const&) = default;
    PeriodicGridCellList& operator=(PeriodicGridCellList &&)     = default;

    explicit PeriodicGridCellList(const real_type margin)
        : cutoff_(0), margin_(margin), current_margin_(-1),
          r_x_(-1), r_y_(-1), r_z_(-1), dim_x_(0), dim_y_(0), dim_z_(0)
    {}

    bool valid() const noexcept
    {
        return current_margin_ >= 0.0;
    }

    template<typename PotentialT>
    void initialize(const system_type& sys, const PotentialT& pot);

    template<typename PotentialT>
    void reconstruct(const system_type& sys, const PotentialT& pot)
    {
        this->initialize(sys, pot); // do the same thing as `initialize`
        return;
    }

    template<typename PotentialT>
    void make  (const system_type& sys, const PotentialT& pot);

    template<typename PotentialT>
    void update(const real_type, const system_type&, const PotentialT&);

    real_type cutoff() const {return this->cutoff_;}
    real_type margin() const {return this->margin_;}

    range_type partners(std::size_t i) const noexcept {return neighbors_[i];}

  private:

    std::size_t calc_index(const coordinate_type& pos) const noexcept
    {
        const auto ofs = pos - this->lower_bound_;
        return this->calc_index(std::floor(math::X(ofs) * this->r_x_),
                                std::floor(math::Y(ofs) * this->r_y_),
                                std::floor(math::Z(ofs) * this->r_z_));
    }

    std::size_t calc_index(const std::size_t i, const std::size_t j,
                           const std::size_t k) const noexcept
    {
        return i + this->dim_x_ * j + this->dim_x_ * this->dim_y_ * k;
    }

    void set_cutoff(const real_type c) noexcept
    {
        this->cutoff_ = c;
        this->r_x_ = 1 / (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);
        this->r_y_ = 1 / (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);
        this->r_z_ = 1 / (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);
        return;
    }
    void set_margin(const real_type m) noexcept
    {
        this->margin_ = m;
        this->r_x_ = 1.0 / (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);
        this->r_y_ = 1.0 / (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);
        this->r_z_ = 1.0 / (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);
        return;
    }

  private:

    real_type   cutoff_;
    real_type   margin_;
    real_type   current_margin_;
    real_type   r_x_;
    real_type   r_y_;
    real_type   r_z_;
    std::size_t dim_x_;
    std::size_t dim_y_;
    std::size_t dim_z_;

    coordinate_type     lower_bound_;
    neighbor_list_type  neighbors_;
    exclusion_list_type exclusion_;
    cell_list_type      cell_list_;
    cell_index_container_type index_by_cell_;
    // index_by_cell_ has {particle idx, cell idx} and sorted by cell idx
    // first term of cell list contains first and last idx of index_by_cell
};

template<typename traitsT, typename parameterT>
template<typename PotentialT>
void PeriodicGridCellList<traitsT, parameterT>::update(
        const real_type dmargin, const system_type& sys, const PotentialT& pot)
{
    this->current_margin_ -= dmargin;
    if(this->current_margin_ < 0.)
    {
        this->make(sys, pot);
    }
    return ;
}

template<typename traitsT, typename parameterT>
template<typename PotentialT>
void PeriodicGridCellList<traitsT, parameterT>::make(
        const system_type& sys, const PotentialT& pot)
{
    MJOLNIR_GET_DEFAULT_LOGGER_DEBUG();
    MJOLNIR_LOG_FUNCTION_DEBUG();

    neighbors_.clear();
    index_by_cell_.resize(sys.size());

    for(std::size_t i=0; i<sys.size(); ++i)
    {
        index_by_cell_[i] = std::make_pair(i, calc_index(sys[i].position));
    }

    std::sort(this->index_by_cell_.begin(), this->index_by_cell_.end(),
        [](const std::pair<std::size_t, std::size_t>& lhs,
           const std::pair<std::size_t, std::size_t>& rhs) noexcept -> bool
        {
            return lhs.second < rhs.second;
        });

    { // assign first and last iterator for each cells
        auto iter = index_by_cell_.cbegin();
        for(std::size_t i=0; i<cell_list_.size(); ++i)
        {
            if(iter == index_by_cell_.cend() || i != iter->second)
            {
                cell_list_[i].first = make_range(iter, iter);
                continue;
            }
            const auto first = iter;
            while(iter != index_by_cell_.cend() && i == iter->second)
            {
                ++iter;
            }
            cell_list_[i].first = make_range(first, iter);
        }
    }

    MJOLNIR_LOG_DEBUG("cell list is updated");

    const real_type r_c  = cutoff_ * (1. + margin_);
    const real_type r_c2 = r_c * r_c;
    for(std::size_t i=0; i<sys.size(); ++i)
    {
        const auto& ri = sys[i].position;
        const auto& cell = cell_list_[calc_index(ri)];

        MJOLNIR_LOG_DEBUG("particle position", sys[i].position);
        MJOLNIR_LOG_DEBUG("making verlet list for index", i);
        MJOLNIR_LOG_DEBUG("except list for ", i, "-th value");

        std::vector<neighbor_type> partner;
        for(std::size_t cidx : cell.second) // for all adjacent cells...
        {
            for(auto pici : cell_list_[cidx].first)
            {
                const auto j = pici.first;
                MJOLNIR_LOG_DEBUG("looking particle", j);
                if(j <= i || this->exclusion_.is_excluded(i, j))
                {
                    continue;
                }

                if(math::length_sq(sys.adjust_direction(sys[j].position - ri)) < r_c2)
                {
                    MJOLNIR_LOG_DEBUG("add index", j, "to verlet list", i);
                    partner.emplace_back(j, pot.prepair_params(i, j));
                }
            }
        }
        // make the result consistent with NaivePairCalculation...
        std::sort(partner.begin(), partner.end());
        this->neighbors_.add_list_for(i, partner.begin(), partner.end());
    }

    this->current_margin_ = cutoff_ * margin_;
    return ;
}

template<typename traitsT, typename parameterT>
template<typename PotentialT>
void PeriodicGridCellList<traitsT, parameterT>::initialize(
        const system_type& sys, const PotentialT& pot)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_LOG_FUNCTION();

    const real_type max_cutoff = pot.max_cutoff_length();
    this->set_cutoff(max_cutoff);
    this->exclusion_.make(sys, pot);

    MJOLNIR_LOG_INFO(pot.name(), " cutoff = ", max_cutoff);

    this->lower_bound_ = sys.boundary().lower_bound();
    const auto system_size = sys.boundary().width();

    this->dim_x_ = std::max<std::size_t>(3, std::floor(math::X(system_size) * r_x_));
    this->dim_y_ = std::max<std::size_t>(3, std::floor(math::Y(system_size) * r_y_));
    this->dim_z_ = std::max<std::size_t>(3, std::floor(math::Z(system_size) * r_z_));

    MJOLNIR_LOG_INFO("dimension = ", dim_x_, 'x', dim_y_, 'x', dim_z_);

    if(dim_x_ == 3 || dim_y_ == 3 || dim_z_ == 3)
    {
        MJOLNIR_LOG_WARN("system size is too small (",
                dim_x_, 'x', dim_y_, 'x', dim_z_,
                "). This might cause a problem. Please check the cutoff ratio"
                " and the box size!");
    }

    // it may expand cell a bit (to fit system range)
    this->r_x_ = 1.0 / (math::X(system_size) / this->dim_x_);
    this->r_y_ = 1.0 / (math::Y(system_size) / this->dim_y_);
    this->r_z_ = 1.0 / (math::Z(system_size) / this->dim_z_);

    MJOLNIR_LOG_DEBUG("reciplocal width of cells in x coordinate = ", r_x_);
    MJOLNIR_LOG_DEBUG("reciplocal width of cells in y coordinate = ", r_y_);
    MJOLNIR_LOG_DEBUG("reciplocal width of cells in z coordinate = ", r_z_);

    this->cell_list_.resize(dim_x_ * dim_y_ * dim_z_);

    const int dimx = dim_x_;
    const int dimy = dim_y_;
    const int dimz = dim_x_;

    for(int x = 0; x < dimx; ++x)
    {
    for(int y = 0; y < dimy; ++y)
    {
    for(int z = 0; z < dimz; ++z)
    {
        auto& cell = this->cell_list_[calc_index(x, y, z)];

        const std::size_t x_prev = (x ==        0) ? dimx - 1 : x - 1;
        const std::size_t x_next = (x == dimx - 1) ?        0 : x + 1;
        const std::size_t y_prev = (y ==        0) ? dimy - 1 : y - 1;
        const std::size_t y_next = (y == dimy - 1) ?        0 : y + 1;
        const std::size_t z_prev = (z ==        0) ? dimz - 1 : z - 1;
        const std::size_t z_next = (z == dimz - 1) ?        0 : z + 1;

        cell.second[ 0] = calc_index(x_prev, y_prev, z_prev);
        cell.second[ 1] = calc_index(x,      y_prev, z_prev);
        cell.second[ 2] = calc_index(x_next, y_prev, z_prev);
        cell.second[ 3] = calc_index(x_prev, y,      z_prev);
        cell.second[ 4] = calc_index(x,      y,      z_prev);
        cell.second[ 5] = calc_index(x_next, y,      z_prev);
        cell.second[ 6] = calc_index(x_prev, y_next, z_prev);
        cell.second[ 7] = calc_index(x,      y_next, z_prev);
        cell.second[ 8] = calc_index(x_next, y_next, z_prev);

        cell.second[ 9] = calc_index(x_prev, y_prev, z);
        cell.second[10] = calc_index(x,      y_prev, z);
        cell.second[11] = calc_index(x_next, y_prev, z);
        cell.second[12] = calc_index(x_prev, y,      z);
        cell.second[13] = calc_index(x,      y,      z);
        cell.second[14] = calc_index(x_next, y,      z);
        cell.second[15] = calc_index(x_prev, y_next, z);
        cell.second[16] = calc_index(x,      y_next, z);
        cell.second[17] = calc_index(x_next, y_next, z);

        cell.second[18] = calc_index(x_prev, y_prev, z_next);
        cell.second[19] = calc_index(x,      y_prev, z_next);
        cell.second[20] = calc_index(x_next, y_prev, z_next);
        cell.second[21] = calc_index(x_prev, y,      z_next);
        cell.second[22] = calc_index(x,      y,      z_next);
        cell.second[23] = calc_index(x_next, y,      z_next);
        cell.second[24] = calc_index(x_prev, y_next, z_next);
        cell.second[25] = calc_index(x,      y_next, z_next);
        cell.second[26] = calc_index(x_next, y_next, z_next);

        auto uniq = std::unique(cell.second.begin(), cell.second.end());
        assert(uniq == cell.second.end());
        for(auto i : cell.second)
        {
            assert(0 <= i && i <= cell_list_.size());
        }
    }
    }
    }
    this->make(sys, pot);
    return;
}

} // mjolnir
#endif /* MJOLNIR_PERIODIC_GRID_CELL_LIST */
<|endoftext|>


<commit_before>#pragma once

#include "tcppBridgeFunc.hpp"
#include "../../ast/mgd/mgdObj.hpp"

namespace wrd {

    /// bridge object only can shares 'shared' sub nodes.
    template <typename T>
    class tcppBridge : public obj {
        WRD(CLASS(tcppBridge, obj))
        template <typename Ret, typename T1, typename...Args>
        friend class tcppBridgeFunc;

    private:
        tcppBridge(T* real) : _real(real) {
            _subs.bind(new nchain());
        }

    public:
        static me* def() {
            // TODO: need to handle ctor with argument.
            return new me(new T());
        }

        const std::string& getName() const override {
            static const std::string& inner = ttype<T>::get().getName();
            return inner;
        }

        using super::getCtors;
        funcs& getCtors() override {
            // TODO: pass real constructor of given type T.
            static funcs inner;
            return inner;
        }

        template <typename Ret, typename... Args>
        me* func(const std::string& name, Ret(T::*fptr)(Args...)) {
            subs().add(new tcppBridgeFunc<Ret, T, Args...>(name, fptr));
            return this;
        }

        const obj& getOrigin() const override {
            // if an object doesn't have owned sub nodes it means that all instances of that classes
            // are same and origin simulteneously.
            return *this;
        }

    private:
        T* _real;
    };
}
<commit_msg>wrd: doc: commenting todolist for bridge object<commit_after>#pragma once

#include "tcppBridgeFunc.hpp"
#include "../../ast/mgd/mgdObj.hpp"

namespace wrd {

    /// bridge object only can shares 'shared' sub nodes.
    template <typename T>
    class tcppBridge : public obj {
		// TODO: how to impement 'as()' on bridge obj:
		//	each tcppBridge obj has its unique type object. when it got called 'getType()'
		//	it returns its type object.
		//
		//	however, type object is dynamically belongs to this bridge object, when user
		//	tries to get ttype<T>, it's not derived from wtype so it won't have any 'as()'
		//	func. user can't operate conversion in this way.
        WRD(CLASS(tcppBridge, obj))
        template <typename Ret, typename T1, typename...Args>
        friend class tcppBridgeFunc;

    private:
        tcppBridge(T* real) : _real(real) {
            _subs.bind(new nchain());
        }

    public:
        static me* def() {
            // TODO: need to handle ctor with argument.
            return new me(new T());
        }

        const std::string& getName() const override {
            static const std::string& inner = ttype<T>::get().getName();
            return inner;
        }

        using super::getCtors;
        funcs& getCtors() override {
            // TODO: pass real constructor of given type T.
            static funcs inner;
            return inner;
        }

        template <typename Ret, typename... Args>
        me* func(const std::string& name, Ret(T::*fptr)(Args...)) {
            subs().add(new tcppBridgeFunc<Ret, T, Args...>(name, fptr));
            return this;
        }

        const obj& getOrigin() const override {
            // if an object doesn't have owned sub nodes it means that all instances of that classes
            // are same and origin simulteneously.
            return *this;
        }

    private:
        T* _real;
    };
}
<|endoftext|>


<commit_before>#pragma once
/*
**  Copyright (C) 2014 Aldebaran Robotics
**  See COPYING for the license
*/
#include <boost/container/flat_map.hpp>
#include <boost/thread/mutex.hpp>
#include <qi/future.hpp>
#include <qi/trackable.hpp>

namespace qi
{
  /** Cancel a group of unfinished registered futures on destruction.
   *  Guarantees that the registered set of futures will be canceled
   *  whatever the reason of the destruction of the group.
   *  @remark All public member functions are thread-safe unless specified.
   *
   *  @includename{qi/futuregroup.hpp}
   */
  class ScopedFutureGroup
    : boost::noncopyable
    , public qi::Trackable<ScopedFutureGroup>
  {
  public:
    /** Destructor, cancel all unfinished futures registered.
     */
    ~ScopedFutureGroup()
    {
      destroy();
      cancelAll();
    }

    /** Register a future to be canceled if not finished when this object is destroyed,
     *  or if cancelAll() is called.
     *  Futures finishing before cancelation will be automatically unregistered.
     *  Non-cancelable futures will be ignored.
     *  @param future Future to register.
     */
    template< class T >
    void add(Future<T> future)
    {
      boost::mutex::scoped_lock lock(_mutex);
      _futureCancelList.insert(std::make_pair(future.uniqueId(), qi::bind<void()>(&Future<T>::cancel, future)));

      // The 2 following lines are necessary because of a compiler bug in VS2010 which is fixed in VS2015 and beyond
      using MemFuncType = void (ScopedFutureGroup::*)(Future<T>);
      MemFuncType onFutureFinishedCallback = &ScopedFutureGroup::onFutureFinished<T>;
      future.template thenR<void>(onFutureFinishedCallback, this, _1);
    }

    /** Cancel all registered futures and unregister them.
     */
    void cancelAll()
    {
      FutureCancelList cancelList;
      {
        boost::mutex::scoped_lock lock(_mutex);
        swap(cancelList, _futureCancelList);
      }
      for (FutureCancelList::iterator it = cancelList.begin(), itEnd = cancelList.end();
           it != itEnd; ++it)
      {
        try
        {
          it->second();
        }
        catch (std::exception& ex)
        {
          qiLogWarning("qi.scopedfuturegroup") << "Failed to cancel scoped future: " << ex.what();
        }
        catch (...)
        {
          qiLogWarning("qi.scopedfuturegroup") << "Failed to cancel scoped future: unknown error.";
        }

      }
    }

    /** @return True if there is no future registered, false otherwise. */
    bool empty() const
    {
      boost::mutex::scoped_lock lock(_mutex);
      return _futureCancelList.empty();
    }

    /** @return Count of registered futures. */
    size_t size() const
    {
      boost::mutex::scoped_lock lock(_mutex);
      return _futureCancelList.size();
    }

  private:
    mutable boost::mutex _mutex;
    using FutureCancelList = boost::container::flat_map< FutureUniqueId, boost::function<void()>>;
    FutureCancelList _futureCancelList;

    template<class T>
    void onFutureFinished(Future<T> future)
    {
      boost::mutex::scoped_lock lock(_mutex);
      _futureCancelList.erase(future.uniqueId());
    }
  };
}
<commit_msg>Remove thenR and bind deprecated usage<commit_after>#pragma once
/*
**  Copyright (C) 2014 Aldebaran Robotics
**  See COPYING for the license
*/
#include <boost/container/flat_map.hpp>
#include <boost/thread/mutex.hpp>
#include <qi/future.hpp>
#include <qi/trackable.hpp>

namespace qi
{
  /** Cancel a group of unfinished registered futures on destruction.
   *  Guarantees that the registered set of futures will be canceled
   *  whatever the reason of the destruction of the group.
   *  @remark All public member functions are thread-safe unless specified.
   *
   *  @includename{qi/futuregroup.hpp}
   */
  class ScopedFutureGroup
    : boost::noncopyable
    , public qi::Trackable<ScopedFutureGroup>
  {
  public:
    /** Destructor, cancel all unfinished futures registered.
     */
    ~ScopedFutureGroup()
    {
      destroy();
      cancelAll();
    }

    /** Register a future to be canceled if not finished when this object is destroyed,
     *  or if cancelAll() is called.
     *  Futures finishing before cancelation will be automatically unregistered.
     *  Non-cancelable futures will be ignored.
     *  @param future Future to register.
     */
    template< class T >
    void add(Future<T> future)
    {
      boost::mutex::scoped_lock lock(_mutex);
      _futureCancelList.emplace(future.uniqueId(), [future]() mutable { future.cancel(); });

      // The 2 following lines are necessary because of a compiler bug in VS2010 which is fixed in VS2015 and beyond
      future.then([&](Future<T> f){ onFutureFinished(f); });
    }

    /** Cancel all registered futures and unregister them.
     */
    void cancelAll()
    {
      FutureCancelList cancelList;
      {
        boost::mutex::scoped_lock lock(_mutex);
        swap(cancelList, _futureCancelList);
      }
      for (FutureCancelList::iterator it = cancelList.begin(), itEnd = cancelList.end();
           it != itEnd; ++it)
      {
        try
        {
          it->second();
        }
        catch (std::exception& ex)
        {
          qiLogWarning("qi.scopedfuturegroup") << "Failed to cancel scoped future: " << ex.what();
        }
        catch (...)
        {
          qiLogWarning("qi.scopedfuturegroup") << "Failed to cancel scoped future: unknown error.";
        }

      }
    }

    /** @return True if there is no future registered, false otherwise. */
    bool empty() const
    {
      boost::mutex::scoped_lock lock(_mutex);
      return _futureCancelList.empty();
    }

    /** @return Count of registered futures. */
    size_t size() const
    {
      boost::mutex::scoped_lock lock(_mutex);
      return _futureCancelList.size();
    }

  private:
    mutable boost::mutex _mutex;
    using FutureCancelList = boost::container::flat_map< FutureUniqueId, boost::function<void()>>;
    FutureCancelList _futureCancelList;

    template<class T>
    void onFutureFinished(Future<T> future)
    {
      boost::mutex::scoped_lock lock(_mutex);
      _futureCancelList.erase(future.uniqueId());
    }
  };
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: XMLLineNumberingImportContext.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-13 07:55:19 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_XMLLINENUMBERINGIMPORTCONTEXT_HXX_
#define _XMLOFF_XMLLINENUMBERINGIMPORTCONTEXT_HXX_

#ifndef _XMLOFF_XMLSTYLE_HXX
#include "xmlstyle.hxx"
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

namespace com { namespace sun { namespace star {
    namespace xml { namespace sax { class XAttributeList; } }
} } }

enum LineNumberingToken
{
    XML_TOK_LINENUMBERING_STYLE_NAME,
    XML_TOK_LINENUMBERING_NUMBER_LINES,
    XML_TOK_LINENUMBERING_COUNT_EMPTY_LINES,
    XML_TOK_LINENUMBERING_COUNT_IN_TEXT_BOXES,
    XML_TOK_LINENUMBERING_RESTART_NUMBERING,
    XML_TOK_LINENUMBERING_OFFSET,
    XML_TOK_LINENUMBERING_NUM_FORMAT,
    XML_TOK_LINENUMBERING_NUM_LETTER_SYNC,
    XML_TOK_LINENUMBERING_NUMBER_POSITION,
    XML_TOK_LINENUMBERING_INCREMENT
//  XML_TOK_LINENUMBERING_LINENUMBERING_CONFIGURATION,
//  XML_TOK_LINENUMBERING_INCREMENT,
//  XML_TOK_LINENUMBERING_LINENUMBERING_SEPARATOR,
};

/** import <text:linenumbering-configuration> elements */
class XMLLineNumberingImportContext : public SvXMLStyleContext
{
    const ::rtl::OUString sCharStyleName;
    const ::rtl::OUString sCountEmptyLines;
    const ::rtl::OUString sCountLinesInFrames;
    const ::rtl::OUString sDistance;
    const ::rtl::OUString sInterval;
    const ::rtl::OUString sSeparatorText;
    const ::rtl::OUString sNumberPosition;
    const ::rtl::OUString sNumberingType;
    const ::rtl::OUString sIsOn;
    const ::rtl::OUString sRestartAtEachPage;
    const ::rtl::OUString sSeparatorInterval;

    ::rtl::OUString sStyleName;
    ::rtl::OUString sNumFormat;
    ::rtl::OUString sNumLetterSync;
    ::rtl::OUString sSeparator;
    sal_Int32 nOffset;
    sal_Int16 nNumberPosition;
    sal_Int16 nIncrement;
    sal_Int16 nSeparatorIncrement;
    sal_Bool bNumberLines;
    sal_Bool bCountEmptyLines;
    sal_Bool bCountInFloatingFrames;
    sal_Bool bRestartNumbering;

public:

    TYPEINFO();

    XMLLineNumberingImportContext(
        SvXMLImport& rImport,
        sal_uInt16 nPrfx,
        const ::rtl::OUString& rLocalName,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList);

    ~XMLLineNumberingImportContext();

    // to be used by child context: set separator info
    void SetSeparatorText(const ::rtl::OUString& sText);
    void SetSeparatorIncrement(sal_Int16 nIncr);

protected:

    virtual void StartElement(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList);

    void ProcessAttribute(
        enum LineNumberingToken eToken,
        ::rtl::OUString sValue);

    virtual void CreateAndInsert(sal_Bool bOverwrite);

    virtual SvXMLImportContext *CreateChildContext(
        sal_uInt16 nPrefix,
        const ::rtl::OUString& rLocalName,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList );

    void ProcessAttribute(
        const ::rtl::OUString sLocalName,
        const ::rtl::OUString sValue);
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.298); FILE MERGED 2005/09/05 14:37:57 rt 1.4.298.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLLineNumberingImportContext.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:52:39 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *
 ************************************************************************/

#ifndef _XMLOFF_XMLLINENUMBERINGIMPORTCONTEXT_HXX_
#define _XMLOFF_XMLLINENUMBERINGIMPORTCONTEXT_HXX_

#ifndef _XMLOFF_XMLSTYLE_HXX
#include "xmlstyle.hxx"
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

namespace com { namespace sun { namespace star {
    namespace xml { namespace sax { class XAttributeList; } }
} } }

enum LineNumberingToken
{
    XML_TOK_LINENUMBERING_STYLE_NAME,
    XML_TOK_LINENUMBERING_NUMBER_LINES,
    XML_TOK_LINENUMBERING_COUNT_EMPTY_LINES,
    XML_TOK_LINENUMBERING_COUNT_IN_TEXT_BOXES,
    XML_TOK_LINENUMBERING_RESTART_NUMBERING,
    XML_TOK_LINENUMBERING_OFFSET,
    XML_TOK_LINENUMBERING_NUM_FORMAT,
    XML_TOK_LINENUMBERING_NUM_LETTER_SYNC,
    XML_TOK_LINENUMBERING_NUMBER_POSITION,
    XML_TOK_LINENUMBERING_INCREMENT
//  XML_TOK_LINENUMBERING_LINENUMBERING_CONFIGURATION,
//  XML_TOK_LINENUMBERING_INCREMENT,
//  XML_TOK_LINENUMBERING_LINENUMBERING_SEPARATOR,
};

/** import <text:linenumbering-configuration> elements */
class XMLLineNumberingImportContext : public SvXMLStyleContext
{
    const ::rtl::OUString sCharStyleName;
    const ::rtl::OUString sCountEmptyLines;
    const ::rtl::OUString sCountLinesInFrames;
    const ::rtl::OUString sDistance;
    const ::rtl::OUString sInterval;
    const ::rtl::OUString sSeparatorText;
    const ::rtl::OUString sNumberPosition;
    const ::rtl::OUString sNumberingType;
    const ::rtl::OUString sIsOn;
    const ::rtl::OUString sRestartAtEachPage;
    const ::rtl::OUString sSeparatorInterval;

    ::rtl::OUString sStyleName;
    ::rtl::OUString sNumFormat;
    ::rtl::OUString sNumLetterSync;
    ::rtl::OUString sSeparator;
    sal_Int32 nOffset;
    sal_Int16 nNumberPosition;
    sal_Int16 nIncrement;
    sal_Int16 nSeparatorIncrement;
    sal_Bool bNumberLines;
    sal_Bool bCountEmptyLines;
    sal_Bool bCountInFloatingFrames;
    sal_Bool bRestartNumbering;

public:

    TYPEINFO();

    XMLLineNumberingImportContext(
        SvXMLImport& rImport,
        sal_uInt16 nPrfx,
        const ::rtl::OUString& rLocalName,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList);

    ~XMLLineNumberingImportContext();

    // to be used by child context: set separator info
    void SetSeparatorText(const ::rtl::OUString& sText);
    void SetSeparatorIncrement(sal_Int16 nIncr);

protected:

    virtual void StartElement(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList);

    void ProcessAttribute(
        enum LineNumberingToken eToken,
        ::rtl::OUString sValue);

    virtual void CreateAndInsert(sal_Bool bOverwrite);

    virtual SvXMLImportContext *CreateChildContext(
        sal_uInt16 nPrefix,
        const ::rtl::OUString& rLocalName,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList );

    void ProcessAttribute(
        const ::rtl::OUString sLocalName,
        const ::rtl::OUString sValue);
};

#endif
<|endoftext|>


<commit_before>#pragma once

#include <rai/lib/expected.hpp>
#include <string>
#include <system_error>
#include <type_traits>

using tl::expected;
using tl::make_unexpected;

namespace nano
{
/** Returns the error code if non-zero, otherwise the value */
template <class T>
auto either (T && value, std::error_code ec) -> expected<typename std::remove_reference<T>::type, std::error_code>
{
	if (ec)
	{
		return make_unexpected (ec);
	}
	else
	{
		return std::move (value);
	}
}

/** Common error codes */
enum class error_common
{
	generic = 1,
	account_not_found,
	account_not_found_wallet,
	account_exists,
	bad_account_number,
	bad_private_key,
	bad_public_key,
	bad_seed,
	bad_threshold,
	bad_wallet_number,
	bad_work_format,
	invalid_amount,
	invalid_amount_big,
	invalid_count,
	invalid_index,
	invalid_ip_address,
	invalid_port,
	invalid_work,
	insufficient_balance,
	numeric_conversion,
	wallet_lmdb_max_dbs,
	wallet_locked,
	wallet_not_found
};

/** Block related errors */
enum class error_blocks
{
	generic = 1,
	bad_hash_number,
	invalid_block,
	invalid_block_hash,
	invalid_type,
	not_found,
	work_low
};

/** RPC related errors */
enum class error_rpc
{
	generic = 1,
	bad_destination,
	bad_key,
	bad_link,
	bad_previous,
	bad_representative_number,
	bad_source,
	bad_timeout,
	block_create_balance_mismatch,
	block_create_key_required,
	block_create_public_key_mismatch,
	block_create_requirements_state,
	block_create_requirements_open,
	block_create_requirements_receive,
	block_create_requirements_change,
	block_create_requirements_send,
	invalid_balance,
	invalid_destinations,
	invalid_offset,
	invalid_missing_type,
	invalid_sources,
	payment_account_balance,
	payment_unable_create_account,
	rpc_control_disabled,
	source_not_found
};

/** process_result related errors */
enum class error_process
{
	generic = 1,
	bad_signature, // Signature was bad, forged or transmission error
	old, // Already seen and was valid
	negative_spend, // Malicious attempt to spend a negative amount
	fork, // Malicious fork based on previous
	unreceivable, // Source block doesn't exist or has already been received
	gap_previous, // Block marked as previous is unknown
	gap_source, // Block marked as source is unknown
	opened_burn_account, // The impossible happened, someone found the private key associated with the public key '0'.
	balance_mismatch, // Balance and amount delta don't match
	block_position, // This block cannot follow the previous block
	other
};
}

// Convenience macro to implement the standard boilerplate for using std::error_code with enums
// Use this at the end of any header defining one or more error code enums.
#define REGISTER_ERROR_CODES(namespace_name, enum_type)                                                                      \
	namespace namespace_name                                                                                \
	{                                                                                \
		static_assert (static_cast<int> (enum_type::generic) > 0, "The first error enum must be generic = 1");               \
		class enum_type##_messages : public std::error_category                                                              \
		{                                                                                \
		public:                                                                                \
			const char * name () const noexcept override                                                                     \
			{                                                                                \
				return #enum_type;                                                                                \
			}                                                                                \
                                                                                \
			std::string message (int ev) const override;                                                                     \
		};                                                                                \
                                                                                \
		inline const std::error_category & enum_type##_category ()                                                           \
		{                                                                                \
			static enum_type##_messages instance;                                                                            \
			return instance;                                                                                \
		}                                                                                \
                                                                                \
		inline std::error_code make_error_code (::namespace_name::enum_type err)                                             \
		{                                                                                \
			return { static_cast<int> (err), enum_type##_category () };                                                      \
		}                                                                                \
                                                                                \
		inline auto unexpected_error (::namespace_name::enum_type err) -> decltype (make_unexpected (make_error_code (err))) \
		{                                                                                \
			return make_unexpected (make_error_code (err));                                                                  \
		}                                                                                \
	}                                                                                \
	namespace std                                                                                \
	{                                                                                \
		template <>                                                                                \
		struct is_error_code_enum<::namespace_name::enum_type> : std::true_type                                              \
		{                                                                                \
		};                                                                                \
	}

REGISTER_ERROR_CODES (nano, error_common);
REGISTER_ERROR_CODES (nano, error_blocks);
REGISTER_ERROR_CODES (nano, error_rpc);
REGISTER_ERROR_CODES (nano, error_process);
<commit_msg>Clang formatting<commit_after>#pragma once

#include <rai/lib/expected.hpp>
#include <string>
#include <system_error>
#include <type_traits>

using tl::expected;
using tl::make_unexpected;

namespace nano
{
/** Returns the error code if non-zero, otherwise the value */
template <class T>
auto either (T && value, std::error_code ec) -> expected<typename std::remove_reference<T>::type, std::error_code>
{
	if (ec)
	{
		return make_unexpected (ec);
	}
	else
	{
		return std::move (value);
	}
}

/** Common error codes */
enum class error_common
{
	generic = 1,
	account_not_found,
	account_not_found_wallet,
	account_exists,
	bad_account_number,
	bad_private_key,
	bad_public_key,
	bad_seed,
	bad_threshold,
	bad_wallet_number,
	bad_work_format,
	invalid_amount,
	invalid_amount_big,
	invalid_count,
	invalid_index,
	invalid_ip_address,
	invalid_port,
	invalid_work,
	insufficient_balance,
	numeric_conversion,
	wallet_lmdb_max_dbs,
	wallet_locked,
	wallet_not_found
};

/** Block related errors */
enum class error_blocks
{
	generic = 1,
	bad_hash_number,
	invalid_block,
	invalid_block_hash,
	invalid_type,
	not_found,
	work_low
};

/** RPC related errors */
enum class error_rpc
{
	generic = 1,
	bad_destination,
	bad_key,
	bad_link,
	bad_previous,
	bad_representative_number,
	bad_source,
	bad_timeout,
	block_create_balance_mismatch,
	block_create_key_required,
	block_create_public_key_mismatch,
	block_create_requirements_state,
	block_create_requirements_open,
	block_create_requirements_receive,
	block_create_requirements_change,
	block_create_requirements_send,
	invalid_balance,
	invalid_destinations,
	invalid_offset,
	invalid_missing_type,
	invalid_sources,
	payment_account_balance,
	payment_unable_create_account,
	rpc_control_disabled,
	source_not_found
};

/** process_result related errors */
enum class error_process
{
	generic = 1,
	bad_signature, // Signature was bad, forged or transmission error
	old, // Already seen and was valid
	negative_spend, // Malicious attempt to spend a negative amount
	fork, // Malicious fork based on previous
	unreceivable, // Source block doesn't exist or has already been received
	gap_previous, // Block marked as previous is unknown
	gap_source, // Block marked as source is unknown
	opened_burn_account, // The impossible happened, someone found the private key associated with the public key '0'.
	balance_mismatch, // Balance and amount delta don't match
	block_position, // This block cannot follow the previous block
	other
};
}

// Convenience macro to implement the standard boilerplate for using std::error_code with enums
// Use this at the end of any header defining one or more error code enums.
#define REGISTER_ERROR_CODES(namespace_name, enum_type)                                                                      \
	namespace namespace_name                                                                                \
	{                                                                                \
		static_assert (static_cast<int> (enum_type::generic) > 0, "The first error enum must be generic = 1");               \
		class enum_type##_messages : public std::error_category                                                              \
		{                                                                                \
		public:                                                                                \
			const char * name () const noexcept override                                                                     \
			{                                                                                \
				return #enum_type;                                                                                \
			}                                                                                \
                                                                                \
			std::string message (int ev) const override;                                                                     \
		};                                                                                \
                                                                                \
		inline const std::error_category & enum_type##_category ()                                                           \
		{                                                                                \
			static enum_type##_messages instance;                                                                            \
			return instance;                                                                                \
		}                                                                                \
                                                                                \
		inline std::error_code make_error_code (::namespace_name::enum_type err)                                             \
		{                                                                                \
			return { static_cast<int> (err), enum_type##_category () };                                                      \
		}                                                                                \
                                                                                \
		inline auto unexpected_error (::namespace_name::enum_type err) -> decltype (make_unexpected (make_error_code (err))) \
		{                                                                                \
			return make_unexpected (make_error_code (err));                                                                  \
		}                                                                                \
	}                                                                                \
	namespace std                                                                                \
	{                                                                                \
		template <>                                                                                \
		struct is_error_code_enum<::namespace_name::enum_type> : std::true_type                                              \
		{                                                                                \
		};                                                                                \
	}

REGISTER_ERROR_CODES (nano, error_common);
REGISTER_ERROR_CODES (nano, error_blocks);
REGISTER_ERROR_CODES (nano, error_rpc);
REGISTER_ERROR_CODES (nano, error_process);
<|endoftext|>


<commit_before>#include <iostream>

int main(void)
{
  return 0;
}
<commit_msg>Delete mumford.cpp<commit_after><|endoftext|>


<commit_before><commit_msg>remotebridges: Use appropriate OUString functions on string constants<commit_after><|endoftext|>


<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include "aidaprops.hh"
#include "thread.hh"
#include <set>
#include <cstring>
#include <malloc.h>

namespace Rapicorn { namespace Aida {

static inline String
propcanonify (String s)
{
  for (uint i = 0; i < s.size(); i++)
    if (!((s[i] >= 'A' && s[i] <= 'Z') ||
          (s[i] >= 'a' && s[i] <= 'z') ||
          (s[i] >= '0' && s[i] <= '9') ||
          s[i] == '_'))
      s[i] = '_';
  return s;
}

// == PropertyHostInterface ==
const PropertyList&
PropertyHostInterface::_property_list ()
{
  static const PropertyList empty_property_list;
  return empty_property_list;
}

static Mutex plist_map_mutex;

Property*
PropertyHostInterface::_property_lookup (const String &property_name)
{
  // provide PropertyMaps globally
  typedef std::map<const String, Property*> PropertyMap;
  static std::map<const PropertyList*,PropertyMap*> *plist_map = NULL;
  do_once {
    static uint64 space[sizeof (*plist_map) / sizeof (uint64)];
    plist_map = new (space) std::map<const PropertyList*,PropertyMap*>();
  }
  // find or construct property map
  const PropertyList &plist = _property_list();
  ScopedLock<Mutex> plist_map_locker (plist_map_mutex);
  PropertyMap *pmap = (*plist_map)[&plist];
  if (!pmap)
    {
      pmap = new PropertyMap;
      size_t n_properties = 0;
      Property **properties = plist.list_properties (&n_properties);
      for (uint i = 0; i < n_properties; i++)
        {
          Property *prop = properties[i];
          if (prop)
            (*pmap)[prop->ident] = prop;
        }
      (*plist_map)[&plist] = pmap;
    }
  plist_map_locker.unlock();
  PropertyMap::iterator it = pmap->find (property_name);
  if (it == pmap->end())        // try canonicalized
    it = pmap->find (string_substitute_char (property_name, '-', '_'));
  if (it != pmap->end())
    return it->second;
  else
    return NULL;
}

bool
PropertyHostInterface::_property_set (const String &property_name, const String &value)
{
  Property *prop = _property_lookup (property_name);
  if (!prop)
    return false;
  prop->set_value (*this, value);
  return true;
}

String
PropertyHostInterface::_property_get (const String &property_name)
{
  Property *prop = _property_lookup (property_name);
  if (!prop)
    return ""; // be more verbose here?
  return prop->get_value (*this);
}

// == PropertyList ==
Property::Property (const char *cident, const char *clabel, const char *cblurb, const char *chints) :
  ident (cident),
  label (clabel ? strdup (clabel) : NULL),
  blurb (cblurb ? strdup (cblurb) : NULL),
  hints (chints ? strdup (chints) : NULL)
{
  assert (ident != NULL);
  ident = strdup (propcanonify (ident).c_str());
}

Property::~Property()
{
  if (ident)
    free (const_cast<char*> (ident));
  if (label)
    free (label);
  if (blurb)
    free (blurb);
  if (hints)
    free (hints);
}

bool
Property::readable () const
{
  if (hints)
    return string_option_check (hints, "rw") || string_option_check (hints, "ro");
  return false;
}

bool
Property::writable () const
{
  if (hints)
    return string_option_check (hints, "rw") || string_option_check (hints, "wo");
  return false;
}

// == PropertyList ==
void
PropertyList::append_properties (size_t n_props, Property **props, const PropertyList &c0, const PropertyList &c1,
                                 const PropertyList &c2, const PropertyList &c3, const PropertyList &c4, const PropertyList &c5,
                                 const PropertyList &c6, const PropertyList &c7, const PropertyList &c8, const PropertyList &c9)
{
  std::set<Property*> pset;
  std::vector<Property*> parray;
  for (size_t i = 0; i < m_n_properties; i++)
    if (pset.find (m_properties[i]) == pset.end())
      {
        pset.insert (m_properties[i]);
        parray.push_back (m_properties[i]);
      }
  for (size_t i = 0; i < n_props; i++)
    if (pset.find (props[i]) == pset.end())
      {
        pset.insert (props[i]);
        parray.push_back (props[i]);
      }
  const PropertyList *const chains[] = { &c0, &c1, &c2, &c3, &c4, &c5, &c6, &c7, &c8, &c9 };
  for (size_t j = 0; j < sizeof (chains) / sizeof (chains[0]); j++)
    for (size_t i = 0; i < chains[j]->m_n_properties; i++)
      if (pset.find (chains[j]->m_properties[i]) == pset.end())
        {
          pset.insert (chains[j]->m_properties[i]);
          parray.push_back (chains[j]->m_properties[i]);
        }
  delete[] m_properties;
  m_n_properties = parray.size();
  m_properties = new Property* [m_n_properties];
  for (size_t i = 0; i < m_n_properties; i++)
    m_properties[i] = parray[i];
}

Property**
PropertyList::list_properties (size_t *n_properties) const
{
  if (n_properties)
    {
      *n_properties = m_n_properties;
      return m_properties;
    }
  else
    return NULL;
}

PropertyList::~PropertyList ()
{
}

} } // Rapicorn::Aida
<commit_msg>RCORE: use a hash map for property lookups to reduce stress on strcmp<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include "aidaprops.hh"
#include "thread.hh"
#include <set>
#include <unordered_map>
#include <cstring>
#include <malloc.h>

namespace Rapicorn { namespace Aida {

static inline String
propcanonify (String s)
{
  for (uint i = 0; i < s.size(); i++)
    if (!((s[i] >= 'A' && s[i] <= 'Z') ||
          (s[i] >= 'a' && s[i] <= 'z') ||
          (s[i] >= '0' && s[i] <= '9') ||
          s[i] == '_'))
      s[i] = '_';
  return s;
}

// == PropertyHostInterface ==
const PropertyList&
PropertyHostInterface::_property_list ()
{
  static const PropertyList empty_property_list;
  return empty_property_list;
}

static Mutex plist_map_mutex;

Property*
PropertyHostInterface::_property_lookup (const String &property_name)
{
  // provide PropertyMaps globally
  typedef std::unordered_map<String, Property*> PropertyMap;
  static std::map<const PropertyList*,PropertyMap*> *plist_map = NULL;
  do_once {
    static uint64 space[sizeof (*plist_map) / sizeof (uint64)];
    plist_map = new (space) std::map<const PropertyList*,PropertyMap*>();
  }
  // find or construct property map
  const PropertyList &plist = _property_list();
  ScopedLock<Mutex> plist_map_locker (plist_map_mutex);
  PropertyMap *pmap = (*plist_map)[&plist];
  if (!pmap)
    {
      pmap = new PropertyMap;
      size_t n_properties = 0;
      Property **properties = plist.list_properties (&n_properties);
      for (uint i = 0; i < n_properties; i++)
        {
          Property *prop = properties[i];
          if (prop)
            (*pmap)[prop->ident] = prop;
        }
      (*plist_map)[&plist] = pmap;
    }
  plist_map_locker.unlock();
  PropertyMap::iterator it = pmap->find (property_name);
  if (it == pmap->end())        // try canonicalized
    it = pmap->find (string_substitute_char (property_name, '-', '_'));
  if (it != pmap->end())
    return it->second;
  else
    return NULL;
}

bool
PropertyHostInterface::_property_set (const String &property_name, const String &value)
{
  Property *prop = _property_lookup (property_name);
  if (!prop)
    return false;
  prop->set_value (*this, value);
  return true;
}

String
PropertyHostInterface::_property_get (const String &property_name)
{
  Property *prop = _property_lookup (property_name);
  if (!prop)
    return ""; // be more verbose here?
  return prop->get_value (*this);
}

// == PropertyList ==
Property::Property (const char *cident, const char *clabel, const char *cblurb, const char *chints) :
  ident (cident),
  label (clabel ? strdup (clabel) : NULL),
  blurb (cblurb ? strdup (cblurb) : NULL),
  hints (chints ? strdup (chints) : NULL)
{
  assert (ident != NULL);
  ident = strdup (propcanonify (ident).c_str());
}

Property::~Property()
{
  if (ident)
    free (const_cast<char*> (ident));
  if (label)
    free (label);
  if (blurb)
    free (blurb);
  if (hints)
    free (hints);
}

bool
Property::readable () const
{
  if (hints)
    return string_option_check (hints, "rw") || string_option_check (hints, "ro");
  return false;
}

bool
Property::writable () const
{
  if (hints)
    return string_option_check (hints, "rw") || string_option_check (hints, "wo");
  return false;
}

// == PropertyList ==
void
PropertyList::append_properties (size_t n_props, Property **props, const PropertyList &c0, const PropertyList &c1,
                                 const PropertyList &c2, const PropertyList &c3, const PropertyList &c4, const PropertyList &c5,
                                 const PropertyList &c6, const PropertyList &c7, const PropertyList &c8, const PropertyList &c9)
{
  std::set<Property*> pset;
  std::vector<Property*> parray;
  for (size_t i = 0; i < m_n_properties; i++)
    if (pset.find (m_properties[i]) == pset.end())
      {
        pset.insert (m_properties[i]);
        parray.push_back (m_properties[i]);
      }
  for (size_t i = 0; i < n_props; i++)
    if (pset.find (props[i]) == pset.end())
      {
        pset.insert (props[i]);
        parray.push_back (props[i]);
      }
  const PropertyList *const chains[] = { &c0, &c1, &c2, &c3, &c4, &c5, &c6, &c7, &c8, &c9 };
  for (size_t j = 0; j < sizeof (chains) / sizeof (chains[0]); j++)
    for (size_t i = 0; i < chains[j]->m_n_properties; i++)
      if (pset.find (chains[j]->m_properties[i]) == pset.end())
        {
          pset.insert (chains[j]->m_properties[i]);
          parray.push_back (chains[j]->m_properties[i]);
        }
  delete[] m_properties;
  m_n_properties = parray.size();
  m_properties = new Property* [m_n_properties];
  for (size_t i = 0; i < m_n_properties; i++)
    m_properties[i] = parray[i];
}

Property**
PropertyList::list_properties (size_t *n_properties) const
{
  if (n_properties)
    {
      *n_properties = m_n_properties;
      return m_properties;
    }
  else
    return NULL;
}

PropertyList::~PropertyList ()
{
}

} } // Rapicorn::Aida
<|endoftext|>


<commit_before>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>

#include "I22cCom.h"
// Sensors -------------------
#include "Sensor.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
// GUI includes
#include <QApplication>
#include "dialog.h"
#include "screenafterlogin.h"
#include "temperaturescreen.h"
#include "temperatuur.h"
// ----------
//#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"

#include <vector>
#include <iostream>
#include <wiringPi.h>  //compile with -lwiringPi

using namespace std;

vector<Sensor*> motionSensors;    //Vector of the sensors
vector<Light*> lights;      //Vector of the lights
vector<int> active;
PressureSensor* pressureSensor;
Camera* cam;                //Pointer to the camera
Log* log;

int pressureValue;
bool asleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;
long sleepTimer = 0;

void checkSleep();
void updateSensors();
void checkCam();
void sendAlert();
void init();

int main(int argc, char* argv[]) {

	QApplication a(argc, argv);
	Dialog w;
   	w.show();

  init();
  while(1) {
	a.processEvents();
        updateSensors();
        checkSleep();
        checkCam();
        checkTemperature();
  }
}

/*Init for the main*/
void init() {
	//GUI
    //thread GUIloop(GUImain);
	//GUIloop.join();
    //I2C
	wiringPiSetupGpio();
	I2CCom i2c(I2CLOC);     //the i2c to communicate with sensor

    //Create sensorobjects
    Light x(22);
	MotionSensor s1(0xFC,i2c);
	MotionSensor s2(0xBC,i2c);
	MotionSensor s3(0xEC,i2c);
	PressureSensor s4(0x06, i2c);
	Log l1(LOG);
	Camera c1;

    //Create pointers to the sensors
	cam = &c1;
	log = &l1;
	pressureSensor = &s4;
	motionSensors.push_back(&s1);
	motionSensors.push_back(&s2);
	motionSensors.push_back(&s3);
	lights.push_back(&x);

    active.resize(motionSensors.size());
}
/*Updates sensors*/
void updateSensors() {
    //update van elke sensor de value en de active
    bool alert = true;
    for(int i = 0; i<motionSensors.size();i++) {
        if(motionSensors[i]->check()) {
            //active[i]=1;
            alert = false;
		cout <<"halleyula" <<endl;
        } else{
            //active[i]=0;
        }
    }
    if (s4->check()) {
        asleep = true;
    }
    if(alert & !asleep) {
        sendAlert();
    }
    pressureValue = s4->getValue();
}

/*Send Alarm*/
void sendAlert(){
    cout<<"Alert"<<endl;
}

/*Sets the camera*/
void checkCam(){
    if(day) {
        cam->setCamera(true);
    } else if(anomaly) {
        cam->setCamera(true);
    } else {
        cam->setCamera(false);
    }
}

/*Checks if there is an anomaly, otherwise checks if Tim's asleep*/
void checkSleep(){
    if(pressureValue < 20) {
        asleep = false;
        sleepTimer = 0;
    } else if(pressureValue > 20 && pressureValue < 150) {
        anomaly = true;
        sleepTimer = 0;
    } else if(pressureValue > 150 && pressureValue < 200) {
        sleepTimer = 0;
        // Changing positions while asleep
        //Do nothing, maybe verify if person really is sleeping
    } else if(pressureValue > 200 && sleepTimer = 0) {
        sleepTimer = time(0) + 900;
    } else if(pressureValue >200 && sleepTimer != 0) {
        if( time(0) >= sleepTimer) {
            asleep = true
        }
    }

}

/*Checks the set temperature from the gui*/
checkTemperature() {
    temperature = IngesteldeTemperatuur;
}

<commit_msg>Bug fix.<commit_after>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>

#include "I22cCom.h"
// Sensors -------------------
#include "Sensor.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
// GUI includes
#include <QApplication>
#include "dialog.h"
#include "screenafterlogin.h"
#include "temperaturescreen.h"
#include "temperatuur.h"
// ----------
//#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"

#include <vector>
#include <iostream>
#include <wiringPi.h>  //compile with -lwiringPi

using namespace std;

vector<Sensor*> motionSensors;    //Vector of the sensors
vector<Light*> lights;      //Vector of the lights
vector<int> active;
PressureSensor* pressureSensor;
Camera* cam;                //Pointer to the camera
//Log* log;

int pressureValue;
bool asleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;
int IngesteldeTemperatuur = 20;
long sleepTimer = 0;

void checkSleep();
void updateSensors();
void checkCam();
void sendAlert();
void init();

int main(int argc, char* argv[]) {

	QApplication a(argc, argv);
	Dialog w;
   	w.show();

  init();
  while(1) {
	a.processEvents();
        updateSensors();
        checkSleep();
        checkCam();
        checkTemperature();
  }
}

/*Init for the main*/
void init() {
	//GUI
    //thread GUIloop(GUImain);
	//GUIloop.join();
    //I2C
	wiringPiSetupGpio();
	I2CCom i2c(I2CLOC);     //the i2c to communicate with sensor

    //Create sensorobjects
    Light x(22);
	MotionSensor s1(0xFC,i2c);
	MotionSensor s2(0xBC,i2c);
	MotionSensor s3(0xEC,i2c);
	PressureSensor s4(0x06, i2c);
	//Log l1(LOG);
	Camera c1;

    //Create pointers to the sensors
	cam = &c1;
	//log = &l1;
	pressureSensor = &s4;
	motionSensors.push_back(&s1);
	motionSensors.push_back(&s2);
	motionSensors.push_back(&s3);
	lights.push_back(&x);

    active.resize(motionSensors.size());
}
/*Updates sensors*/
void updateSensors() {
    //update van elke sensor de value en de active
    bool alert = true;
    for(unsigned int i = 0; i<motionSensors.size(); ++i) {
        if(motionSensors[i]->check()) {
            //active[i]=1;
            alert = false;
        } else{
            //active[i]=0;
        }
    }
    if (pressureSensor->check()) {
        asleep = true;
    }
    if(alert & !asleep) {
        sendAlert();
    }
    pressureValue = pressureSensor->getValue();
}

/*Send Alarm*/
void sendAlert(){
    cout<<"Alert"<<endl;
}

/*Sets the camera*/
void checkCam(){
    if(day) {
        cam->setCamera(true);
    } else if(anomaly) {
        cam->setCamera(true);
    } else {
        cam->setCamera(false);
    }
}

/*Checks if there is an anomaly, otherwise checks if Tim's asleep*/
void checkSleep(){
    if(pressureValue < 20) {
        asleep = false;
        sleepTimer = 0;
    } else if(pressureValue > 20 && pressureValue < 150) {
        anomaly = true;
        sleepTimer = 0;
    } else if(pressureValue > 150 && pressureValue < 200) {
        sleepTimer = 0;
        // Changing positions while asleep
        //Do nothing, maybe verify if person really is sleeping
    } else if(pressureValue > 200 && sleepTimer == 0) {
        sleepTimer = time(0) + 900;
    } else if(pressureValue >200 && sleepTimer != 0) {
        if( time(0) >= sleepTimer) {
            asleep = true;
        }
    }

}

/*Checks the set temperature from the gui*/
void checkTemperature() {
    temperature = IngesteldeTemperatuur;
}

<|endoftext|>


<commit_before>//===--- Builtins.cpp - Builtin function implementation -------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements various things for builtin functions.
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/Builtins.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/TargetInfo.h"
using namespace clang;

static const Builtin::Info BuiltinInfo[] = {
  { "not a builtin function", 0, 0, 0, false },
#define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, false },
#define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER, false },
#include "clang/Basic/Builtins.def"
};

const Builtin::Info &Builtin::Context::GetRecord(unsigned ID) const {
  if (ID < Builtin::FirstTSBuiltin)
    return BuiltinInfo[ID];
  assert(ID - Builtin::FirstTSBuiltin < NumTSRecords && "Invalid builtin ID!");
  return TSRecords[ID - Builtin::FirstTSBuiltin];
}

Builtin::Context::Context(const TargetInfo &Target) {
  // Get the target specific builtins from the target.
  Target.getTargetBuiltins(TSRecords, NumTSRecords);
}

/// InitializeBuiltins - Mark the identifiers for all the builtins with their
/// appropriate builtin ID # and mark any non-portable builtin identifiers as
/// such.
void Builtin::Context::InitializeBuiltins(IdentifierTable &Table,
                                          bool NoBuiltins) {
  // Step #1: mark all target-independent builtins with their ID's.
  for (unsigned i = Builtin::NotBuiltin+1; i != Builtin::FirstTSBuiltin; ++i)
    if (!BuiltinInfo[i].Suppressed &&
        (!NoBuiltins || !strchr(BuiltinInfo[i].Attributes, 'f')))
      Table.get(BuiltinInfo[i].Name).setBuiltinID(i);

  // Step #2: Register target-specific builtins.
  for (unsigned i = 0, e = NumTSRecords; i != e; ++i)
    if (!TSRecords[i].Suppressed &&
        (!NoBuiltins ||
         (TSRecords[i].Attributes &&
          !strchr(TSRecords[i].Attributes, 'f'))))
      Table.get(TSRecords[i].Name).setBuiltinID(i+Builtin::FirstTSBuiltin);
}

void
Builtin::Context::GetBuiltinNames(llvm::SmallVectorImpl<const char *> &Names,
                                  bool NoBuiltins) {
  // Final all target-independent names
  for (unsigned i = Builtin::NotBuiltin+1; i != Builtin::FirstTSBuiltin; ++i)
    if (!BuiltinInfo[i].Suppressed &&
        (!NoBuiltins || !strchr(BuiltinInfo[i].Attributes, 'f')))
      Names.push_back(BuiltinInfo[i].Name);

  // Find target-specific names.
  for (unsigned i = 0, e = NumTSRecords; i != e; ++i)
    if (!TSRecords[i].Suppressed &&
        (!NoBuiltins ||
         (TSRecords[i].Attributes &&
          !strchr(TSRecords[i].Attributes, 'f'))))
      Names.push_back(TSRecords[i].Name);
}

bool
Builtin::Context::isPrintfLike(unsigned ID, unsigned &FormatIdx,
                               bool &HasVAListArg) {
  const char *Printf = strpbrk(GetRecord(ID).Attributes, "pP");
  if (!Printf)
    return false;

  HasVAListArg = (*Printf == 'P');

  ++Printf;
  assert(*Printf == ':' && "p or P specifier must have be followed by a ':'");
  ++Printf;

  assert(strchr(Printf, ':') && "printf specifier must end with a ':'");
  FormatIdx = strtol(Printf, 0, 10);
  return true;
}

<commit_msg>follow-on to my patch: some targets (like sparc) do not have target-specific builtins, and do not set the count. Just default to 0 for these targets.<commit_after>//===--- Builtins.cpp - Builtin function implementation -------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements various things for builtin functions.
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/Builtins.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/TargetInfo.h"
using namespace clang;

static const Builtin::Info BuiltinInfo[] = {
  { "not a builtin function", 0, 0, 0, false },
#define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, false },
#define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER, false },
#include "clang/Basic/Builtins.def"
};

const Builtin::Info &Builtin::Context::GetRecord(unsigned ID) const {
  if (ID < Builtin::FirstTSBuiltin)
    return BuiltinInfo[ID];
  assert(ID - Builtin::FirstTSBuiltin < NumTSRecords && "Invalid builtin ID!");
  return TSRecords[ID - Builtin::FirstTSBuiltin];
}

Builtin::Context::Context(const TargetInfo &Target) {
  // Get the target specific builtins from the target.
  TSRecords = 0;
  NumTSRecords = 0;
  Target.getTargetBuiltins(TSRecords, NumTSRecords);
}

/// InitializeBuiltins - Mark the identifiers for all the builtins with their
/// appropriate builtin ID # and mark any non-portable builtin identifiers as
/// such.
void Builtin::Context::InitializeBuiltins(IdentifierTable &Table,
                                          bool NoBuiltins) {
  // Step #1: mark all target-independent builtins with their ID's.
  for (unsigned i = Builtin::NotBuiltin+1; i != Builtin::FirstTSBuiltin; ++i)
    if (!BuiltinInfo[i].Suppressed &&
        (!NoBuiltins || !strchr(BuiltinInfo[i].Attributes, 'f')))
      Table.get(BuiltinInfo[i].Name).setBuiltinID(i);

  // Step #2: Register target-specific builtins.
  for (unsigned i = 0, e = NumTSRecords; i != e; ++i)
    if (!TSRecords[i].Suppressed &&
        (!NoBuiltins ||
         (TSRecords[i].Attributes &&
          !strchr(TSRecords[i].Attributes, 'f'))))
      Table.get(TSRecords[i].Name).setBuiltinID(i+Builtin::FirstTSBuiltin);
}

void
Builtin::Context::GetBuiltinNames(llvm::SmallVectorImpl<const char *> &Names,
                                  bool NoBuiltins) {
  // Final all target-independent names
  for (unsigned i = Builtin::NotBuiltin+1; i != Builtin::FirstTSBuiltin; ++i)
    if (!BuiltinInfo[i].Suppressed &&
        (!NoBuiltins || !strchr(BuiltinInfo[i].Attributes, 'f')))
      Names.push_back(BuiltinInfo[i].Name);

  // Find target-specific names.
  for (unsigned i = 0, e = NumTSRecords; i != e; ++i)
    if (!TSRecords[i].Suppressed &&
        (!NoBuiltins ||
         (TSRecords[i].Attributes &&
          !strchr(TSRecords[i].Attributes, 'f'))))
      Names.push_back(TSRecords[i].Name);
}

bool
Builtin::Context::isPrintfLike(unsigned ID, unsigned &FormatIdx,
                               bool &HasVAListArg) {
  const char *Printf = strpbrk(GetRecord(ID).Attributes, "pP");
  if (!Printf)
    return false;

  HasVAListArg = (*Printf == 'P');

  ++Printf;
  assert(*Printf == ':' && "p or P specifier must have be followed by a ':'");
  ++Printf;

  assert(strchr(Printf, ':') && "printf specifier must end with a ':'");
  FormatIdx = strtol(Printf, 0, 10);
  return true;
}

<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/dom_ui/autofill_options_handler.h"

#include <vector>

#include "app/l10n_util.h"
#include "base/logging.h"
#include "base/values.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/credit_card.h"
#include "chrome/browser/profile.h"
#include "grit/generated_resources.h"

AutoFillOptionsHandler::AutoFillOptionsHandler()
    : personal_data_(NULL) {
}

AutoFillOptionsHandler::~AutoFillOptionsHandler() {
  if (personal_data_)
    personal_data_->RemoveObserver(this);
}

/////////////////////////////////////////////////////////////////////////////
// OptionsUIHandler implementation:
void AutoFillOptionsHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
  DCHECK(localized_strings);

  localized_strings->SetString("autoFillOptionsTitle",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_OPTIONS_TITLE));
  localized_strings->SetString("autoFillEnabled",
      l10n_util::GetStringUTF16(IDS_OPTIONS_AUTOFILL_ENABLE));
  localized_strings->SetString("addressesHeader",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_ADDRESSES_GROUP_NAME));
  localized_strings->SetString("creditCardsHeader",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_CREDITCARDS_GROUP_NAME));
  localized_strings->SetString("addAddressButton",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_ADD_ADDRESS_BUTTON));
  localized_strings->SetString("addCreditCardButton",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_ADD_CREDITCARD_BUTTON));
  localized_strings->SetString("editButton",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_EDIT_BUTTON));
  localized_strings->SetString("deleteButton",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_DELETE_BUTTON));
  localized_strings->SetString("helpButton",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_HELP_LABEL));
}

void AutoFillOptionsHandler::Initialize() {
  personal_data_ = dom_ui_->GetProfile()->GetPersonalDataManager();
  personal_data_->SetObserver(this);

  LoadAutoFillData();
}

/////////////////////////////////////////////////////////////////////////////
// PersonalDataManager::Observer implementation:
void  AutoFillOptionsHandler::OnPersonalDataLoaded() {
  LoadAutoFillData();
}

void AutoFillOptionsHandler::OnPersonalDataChanged() {
  LoadAutoFillData();
}

void AutoFillOptionsHandler::RegisterMessages() {
}

void AutoFillOptionsHandler::LoadAutoFillData() {
  if (!personal_data_->IsDataLoaded())
    return;

  ListValue addresses;
  for (std::vector<AutoFillProfile*>::const_iterator i =
           personal_data_->profiles().begin();
       i != personal_data_->profiles().end(); ++i) {
    DictionaryValue* address = new DictionaryValue();
    address->SetString("label", (*i)->PreviewSummary());
    addresses.Append(address);
  }

  dom_ui_->CallJavascriptFunction(L"AutoFillOptions.updateAddresses",
                                  addresses);

  ListValue credit_cards;
  for (std::vector<CreditCard*>::const_iterator i =
           personal_data_->credit_cards().begin();
       i != personal_data_->credit_cards().end(); ++i) {
    DictionaryValue* credit_card = new DictionaryValue();
    credit_card->SetString("label", (*i)->PreviewSummary());
    credit_cards.Append(credit_card);
  }

  dom_ui_->CallJavascriptFunction(L"AutoFillOptions.updateCreditCards",
                                  credit_cards);
}
<commit_msg>DOMUI: Use the OriginalProfile() to load the PersonalDataManager for AutoFill settings.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/dom_ui/autofill_options_handler.h"

#include <vector>

#include "app/l10n_util.h"
#include "base/logging.h"
#include "base/values.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/credit_card.h"
#include "chrome/browser/profile.h"
#include "grit/generated_resources.h"

AutoFillOptionsHandler::AutoFillOptionsHandler()
    : personal_data_(NULL) {
}

AutoFillOptionsHandler::~AutoFillOptionsHandler() {
  if (personal_data_)
    personal_data_->RemoveObserver(this);
}

/////////////////////////////////////////////////////////////////////////////
// OptionsUIHandler implementation:
void AutoFillOptionsHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
  DCHECK(localized_strings);

  localized_strings->SetString("autoFillOptionsTitle",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_OPTIONS_TITLE));
  localized_strings->SetString("autoFillEnabled",
      l10n_util::GetStringUTF16(IDS_OPTIONS_AUTOFILL_ENABLE));
  localized_strings->SetString("addressesHeader",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_ADDRESSES_GROUP_NAME));
  localized_strings->SetString("creditCardsHeader",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_CREDITCARDS_GROUP_NAME));
  localized_strings->SetString("addAddressButton",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_ADD_ADDRESS_BUTTON));
  localized_strings->SetString("addCreditCardButton",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_ADD_CREDITCARD_BUTTON));
  localized_strings->SetString("editButton",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_EDIT_BUTTON));
  localized_strings->SetString("deleteButton",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_DELETE_BUTTON));
  localized_strings->SetString("helpButton",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_HELP_LABEL));
}

void AutoFillOptionsHandler::Initialize() {
  personal_data_ =
      dom_ui_->GetProfile()->GetOriginalProfile()->GetPersonalDataManager();
  personal_data_->SetObserver(this);

  LoadAutoFillData();
}

/////////////////////////////////////////////////////////////////////////////
// PersonalDataManager::Observer implementation:
void  AutoFillOptionsHandler::OnPersonalDataLoaded() {
  LoadAutoFillData();
}

void AutoFillOptionsHandler::OnPersonalDataChanged() {
  LoadAutoFillData();
}

void AutoFillOptionsHandler::RegisterMessages() {
}

void AutoFillOptionsHandler::LoadAutoFillData() {
  if (!personal_data_->IsDataLoaded())
    return;

  ListValue addresses;
  for (std::vector<AutoFillProfile*>::const_iterator i =
           personal_data_->profiles().begin();
       i != personal_data_->profiles().end(); ++i) {
    DictionaryValue* address = new DictionaryValue();
    address->SetString("label", (*i)->PreviewSummary());
    addresses.Append(address);
  }

  dom_ui_->CallJavascriptFunction(L"AutoFillOptions.updateAddresses",
                                  addresses);

  ListValue credit_cards;
  for (std::vector<CreditCard*>::const_iterator i =
           personal_data_->credit_cards().begin();
       i != personal_data_->credit_cards().end(); ++i) {
    DictionaryValue* credit_card = new DictionaryValue();
    credit_card->SetString("label", (*i)->PreviewSummary());
    credit_cards.Append(credit_card);
  }

  dom_ui_->CallJavascriptFunction(L"AutoFillOptions.updateCreditCards",
                                  credit_cards);
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <gtk/gtk.h>

#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_profile.h"
#include "grit/theme_resources.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

// Converts a GdkColor to a SkColor.
SkColor GdkToSkColor(GdkColor* color) {
  return SkColorSetRGB(color->red >> 8,
                       color->green >> 8,
                       color->blue >> 8);
}

}  // namespace

class GtkThemeProviderTest : public testing::Test {
 public:
  GtkThemeProviderTest() : provider_(NULL) {}

  void SetUseGtkTheme(bool use_gtk_theme) {
    profile_.GetPrefs()->SetBoolean(prefs::kUsesSystemTheme, use_gtk_theme);
  }

  void BuildProvider() {
    profile_.InitThemes();
    provider_ = GtkThemeProvider::GetFrom(&profile_);
  }

 protected:
  TestingProfile profile_;

  GtkThemeProvider* provider_;
};

TEST_F(GtkThemeProviderTest, DefaultValues) {
  SetUseGtkTheme(false);
  BuildProvider();

  // Test that we get the default theme colors back when in normal mode.
  for (int i = BrowserThemeProvider::COLOR_FRAME;
       i <= BrowserThemeProvider::COLOR_BUTTON_BACKGROUND; ++i) {
    EXPECT_EQ(provider_->GetColor(i), BrowserThemeProvider::GetDefaultColor(i))
        << "Wrong default color for " << i;
  }
}

TEST_F(GtkThemeProviderTest, UsingGtkValues) {
  SetUseGtkTheme(true);
  BuildProvider();

  // This test only verifies that we're using GTK values. Because of Gtk's
  // large, implied global state, it would take some IN_PROCESS_BROWSER_TESTS
  // to write an equivalent of DefaultValues above in a way that wouldn't make
  // other tests flaky. kColorTabText is the only simple path where there's no
  // weird calculations for edge cases so use that as a simple test.
  GtkWidget* fake_label = provider_->fake_label();
  GtkStyle* label_style = gtk_rc_get_style(fake_label);
  GdkColor label_color = label_style->text[GTK_STATE_NORMAL];
  EXPECT_EQ(provider_->GetColor(BrowserThemeProvider::COLOR_TAB_TEXT),
            GdkToSkColor(&label_color));
}
<commit_msg>Fix GtkThemeProviderTest.UsingGtkValues unittest<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <gtk/gtk.h>

#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_profile.h"
#include "grit/theme_resources.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

// Converts a GdkColor to a SkColor.
SkColor GdkToSkColor(GdkColor* color) {
  return SkColorSetRGB(color->red >> 8,
                       color->green >> 8,
                       color->blue >> 8);
}

}  // namespace

class GtkThemeProviderTest : public testing::Test {
 public:
  GtkThemeProviderTest() : provider_(NULL) {}

  void SetUseGtkTheme(bool use_gtk_theme) {
    profile_.GetPrefs()->SetBoolean(prefs::kUsesSystemTheme, use_gtk_theme);
  }

  void BuildProvider() {
    profile_.InitThemes();
    provider_ = GtkThemeProvider::GetFrom(&profile_);
  }

 protected:
  TestingProfile profile_;

  GtkThemeProvider* provider_;
};

TEST_F(GtkThemeProviderTest, DefaultValues) {
  SetUseGtkTheme(false);
  BuildProvider();

  // Test that we get the default theme colors back when in normal mode.
  for (int i = BrowserThemeProvider::COLOR_FRAME;
       i <= BrowserThemeProvider::COLOR_BUTTON_BACKGROUND; ++i) {
    EXPECT_EQ(provider_->GetColor(i), BrowserThemeProvider::GetDefaultColor(i))
        << "Wrong default color for " << i;
  }
}

TEST_F(GtkThemeProviderTest, UsingGtkValues) {
  SetUseGtkTheme(true);
  BuildProvider();

  // This test only verifies that we're using GTK values. Because of Gtk's
  // large, implied global state, it would take some IN_PROCESS_BROWSER_TESTS
  // to write an equivalent of DefaultValues above in a way that wouldn't make
  // other tests flaky. kColorTabText is the only simple path where there's no
  // weird calculations for edge cases so use that as a simple test.
  GtkWidget* fake_label = provider_->fake_label();
  GtkStyle* label_style = gtk_rc_get_style(fake_label);
  GdkColor label_color = label_style->fg[GTK_STATE_NORMAL];
  EXPECT_EQ(provider_->GetColor(BrowserThemeProvider::COLOR_TAB_TEXT),
            GdkToSkColor(&label_color));
}
<|endoftext|>