<commit_before>#ifndef V_SMC_CORE_SAMPLER_HPP
#define V_SMC_CORE_SAMPLER_HPP

#include <vSMC/internal/common.hpp>
#include <iostream>
#include <map>
#include <set>
#include <string>

namespace vSMC {

/// \brief SMC Sampler
///
/// \tparam T State state type. Requiment:
/// \li Consturctor: T (IntType N)
/// \li Method: copy (IntType from, IntType to)
template <typename T>
class Sampler
{
    public :

    /// The type of initialization functor
    typedef internal::function<unsigned (Particle<T> &, void *)>
        initialize_type;

    /// The type of move and mcmc functor
    typedef internal::function<unsigned (unsigned, Particle<T> &)>
        move_type;

    /// The type of ESS history vector
    typedef std::vector<double> ess_type;

    /// The type of resampling history vector
    typedef std::vector<bool> resampled_type;

    /// The type of accept count history vector
    typedef std::vector<unsigned> accept_type;

    /// \brief Construct a sampler with given number of particles
    ///
    /// \param N The number of particles
    /// \param init The functor used to initialize the particles
    /// \param move The functor used to move the particles and weights
    /// \param scheme The resampling scheme. See ResampleScheme
    /// \param threshold The threshold for performing resampling
    /// \param seed The seed to the parallel RNG system
    explicit Sampler (
            typename Particle<T>::size_type N,
            const initialize_type &init = NULL,
            const move_type &move = NULL,
            ResampleScheme scheme = STRATIFIED,
            double threshold = 0.5,
            typename Particle<T>::seed_type seed = V_SMC_CRNG_SEED) :
        initialized_(false), init_(init), move_(move),
        scheme_(scheme), threshold_(threshold),
        particle_(N, seed), iter_num_(0) {}

    /// \brief Size of the particle set
    ///
    /// \return The number of particles
    typename Particle<T>::size_type size () const
    {
        return particle_.size();
    }

    /// \brief The number of iterations recorded
    ///
    /// \return The number of iterations recorded so far (including the
    /// initialization)
    unsigned iter_size () const
    {
        return ess_.size();
    }

    /// \brief The number of iterations
    ///
    /// \return The number of iterations performed by iterate() so far (not
    /// including the initialization)
    unsigned iter_num () const
    {
        return iter_num_;
    }

    /// \brief Get the current resampling scheme
    ///
    /// \return The current resampling scheme
    ResampleScheme resample_scheme () const
    {
        return scheme_;
    }

    /// \brief Set new resampling scheme
    ///
    /// \param scheme The new scheme for resampling
    void resample_scheme (ResampleScheme scheme)
    {
        scheme_ = scheme;
    }

    /// \brief Get the current threshold
    ///
    /// \return The current threshold for resmapling
    double resample_threshold () const
    {
        return threshold_;
    }

    /// \brief Set new resampling threshold
    ///
    /// \param threshold The new threshold for resampling
    void resample_threshold (double threshold)
    {
        threshold_ = threshold;
    }

    /// \brief Reserve space for histories
    ///
    /// \param num Expected iteration number
    void reserve (unsigned num)
    {
        ess_.reserve(num);
        resampled_.reserve(num);
        accept_.reserve(num);

        for (typename std::map<std::string, Monitor<T> >::iterator
                imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
            if (!imap->second.empty())
                imap->second.reserve(num);
        }

        if (!path_.empty())
            path_.reserve(num);
    }

    /// \brief ESS history
    ///
    /// \return A const reference to the history of ESS
    const ess_type &ess () const
    {
        return ess_;
    }

    /// \brief Resampling history
    ///
    /// \return A const reference to the history of resampling
    const resampled_type &resampled () const
    {
        return resampled_;
    }

    /// \brief Accept count history
    ///
    /// \return A const reference to the history of accept count
    const accept_type &accept () const
    {
        return accept_;
    }

    /// \brief Read and write access to the particle set
    ///
    /// \return A reference to the latest particle set
    Particle<T> &particle ()
    {
        return particle_;
    }

    /// \brief Read only access to the particle set
    ///
    /// \return A const reference to the latest particle set.
    const Particle<T> &particle () const
    {
        return particle_;
    }

    /// \brief Replace initialization functor
    ///
    /// \param new_init New Initialization functor
    void init (const initialize_type &new_init)
    {
        init_ = new_init;
    }

    /// \brief Replace iteration functor
    ///
    /// \param new_move New Move functor
    void move (const move_type &new_move)
    {
        move_ = new_move;
    }

    /// \brief Replace iteration functor
    ///
    /// \param new_mcmc New MCMC Move functor
    void mcmc (const move_type &new_mcmc)
    {
        mcmc_.push_back(new_mcmc);
    }

    /// \brief Clear all MCMC moves
    void clear_mcmc ()
    {
        mcmc_.clear();
    }

    /// \brief Initialize the particle set
    ///
    /// \param param Additional parameters passed to the initialization
    /// functor
    void initialize (void *param = NULL)
    {
        assert(bool(init_));

        ess_.clear();
        resampled_.clear();
        accept_.clear();
        path_.clear();

        for (typename std::map<std::string, Monitor<T> >::iterator
                imap = monitor_.begin(); imap != monitor_.end(); ++imap)
            imap->second.clear();

        iter_num_ = 0;
        accept_.push_back(init_(particle_, param));
        post_move();
        particle_.reset_zconst();

        initialized_ = true;
    }

    /// \brief Perform iteration
    void iterate ()
    {
        assert(initialized_);
        assert(bool(move_));

        ++iter_num_;
        if (bool(move_))
            accept_.push_back(move_(iter_num_, particle_));
        for (typename std::vector<move_type>::iterator miter = mcmc_.begin();
                miter != mcmc_.end(); ++miter)
            accept_.back() = (*miter)(iter_num_, particle_);
        post_move();
    }

    /// \brief Perform iteration
    ///
    /// \param n The number of iterations to be performed
    void iterate (unsigned n)
    {
        for (unsigned i = 0; i != n; ++i)
            iterate();
    }

    /// \brief Perform importance sampling integration
    ///
    /// \param integral The functor used to compute the integrands
    /// \param res The result, an array of length dim
    template<typename MonitorType>
    void integrate (const MonitorType &integral, double *res)
    {
        Monitor<T> m(integral.dim(), integral);
        m.eval(iter_num_, particle_);
        Eigen::Map<Eigen::VectorXd> r(res, m.dim());
        r = m.record().back();
    }

    /// \brief Perform importance sampling integration
    ///
    /// \param dim The dimension of the parameter
    /// \param integral The functor used to compute the integrands
    /// \param res The result, an array of length dim
    void integrate (unsigned dim,
            const typename Monitor<T>::integral_type &integral, double *res)
    {
        assert(bool(integral));

        Monitor<T> m(dim, integral);
        m.eval(iter_num_, particle_);
        Eigen::Map<Eigen::VectorXd> r(res, m.dim());
        r = m.record().back();
    }

    /// \brief Add a monitor, similar to \b monitor in \b BUGS
    ///
    /// \param name The name of the monitor
    /// \param integral The functor used to compute the integrands
    template<typename MonitorType>
    void monitor (const std::string &name, const MonitorType &integral)
    {
        monitor_.insert(std::make_pair(
                    name, Monitor<T>(integral.dim(), integral)));
        monitor_name_.insert(name);
    }

    /// \brief Add a monitor, similar to \b monitor in \b BUGS
    ///
    /// \param name The name of the monitor
    /// \param dim The dimension of the monitor
    /// \param integral The functor used to compute the integrands
    void monitor (const std::string &name, unsigned dim,
            const typename Monitor<T>::integral_type &integral)
    {
        monitor_.insert(std::make_pair(name, Monitor<T>(dim, integral)));
        monitor_name_.insert(name);
    }

    /// \brief Read only access to a named monitor through iterator
    ///
    /// \param name The name of the monitor
    ///
    /// \return An const_iterator point to the monitor for the given name
    typename std::map<std::string, Monitor<T> >::const_iterator
        monitor (const std::string &name) const
    {
        return monitor_.find(name);
    }

    /// \brief Read only access to all monitors
    ///
    /// \return A const reference to monitors
    const std::map<std::string, Monitor<T> > &monitor () const
    {
        return monitor_;
    }

    /// \brief Erase a named monitor
    ///
    /// \param name The name of the monitor
    void clear_monitor (const std::string &name)
    {
        monitor_.erase(name);
        monitor_name_.erase(name);
    }

    /// \brief Erase all monitors
    void clear_monitor ()
    {
        monitor_.clear();
        monitor_name_.clear();
    }

    /// \brief Read only access to the Path sampling monitor
    ///
    /// \return A const reference to the Path sampling monitor
    const Path<T> &path () const
    {
        return path_;
    }

    /// \brief Set the path sampling integral
    ///
    /// \param integral The functor used to compute the integrands
    void path_sampling (const typename Path<T>::integral_type &integral)
    {
        path_.integral(integral);
    }

    /// \brief Path sampling estimate of normalizing constant
    ///
    /// \return The log ratio of normalizing constants
    double path_sampling () const
    {
        return path_.zconst();
    }

    /// \brief SMC estimate of normalizing constant
    ///
    /// \return The log of SMC normalizng constant estimate
    double zconst () const
    {
        return particle_.zconst();
    }

    /// \brief Print the history of the sampler
    ///
    /// \param os The ostream to which the contents are printed
    /// \param print_header Print header if \b true
    void print (std::ostream &os = std::cout, bool print_header = true) const
    {
        print(os, print_header, !path_.index().empty(), monitor_name_);
    }

    /// \brief Print the history of the sampler
    ///
    /// \param os The ostream to which the contents are printed
    /// \param print_path Print path sampling history if \b true
    /// \param print_monitor A set of monitor names to be printed
    /// \param print_header Print header if \b true
    void print (std::ostream &os, bool print_header, bool print_path,
            const std::set<std::string> &print_monitor) const
    {
        if (print_header) {
            os << "iter\tESS\tresample\taccept\t";
            if (print_path)
                os << "path.integrand\tpath.width\tpath.grid\t";
        }

        typename Path<T>::index_type::const_iterator iter_path_index
            = path_.index().begin();
        typename Path<T>::integrand_type::const_iterator iter_path_integrand
            = path_.integrand().begin();
        typename Path<T>::width_type::const_iterator iter_path_width
            = path_.width().begin();
        typename Path<T>::grid_type::const_iterator iter_path_grid
            = path_.grid().begin();

        std::vector<bool> monitor_index_empty;
        std::vector<unsigned> monitor_dim;
        std::vector<typename Monitor<T>::index_type::const_iterator>
            iter_monitor_index;
        std::vector<typename Monitor<T>::record_type::const_iterator>
            iter_monitor_record;
        for (typename std::map<std::string, Monitor<T> >::const_iterator
                imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
            if (print_monitor.count(imap->first)) {
                monitor_index_empty.push_back(imap->second.index().empty());
                monitor_dim.push_back(imap->second.dim());
                iter_monitor_index.push_back(imap->second.index().begin());
                iter_monitor_record.push_back(imap->second.record().begin());
                if (print_header) {
                    if (monitor_dim.back() > 1) {
                        for (unsigned d = 0; d != monitor_dim.back(); ++d)
                            os << imap->first << d + 1 << '\t';
                    } else {
                        os << imap->first << '\t';
                    }
                }
            }
        }

        if (print_header)
            os << '\n';

        for (unsigned i = 0; i != iter_num_ + 1; ++i) {
            os
                << i << '\t' << ess_[i] / size()
                << '\t' << resampled_[i]
                << '\t' << static_cast<double>(accept_[i]) / size();

            if (print_path) {
                if (!path_.index().empty() && *iter_path_index == i) {
                    os
                        << '\t' << *iter_path_integrand++
                        << '\t' << *iter_path_width++
                        << '\t' << *iter_path_grid++;
                    ++iter_path_index;
                } else {
                    os << '\t' << '.' << '\t' << '.' << '\t' << '.';
                }
            }

            for (unsigned m = 0; m != monitor_index_empty.size(); ++m) {
                if (!monitor_index_empty[m] && *iter_monitor_index[m] == i) {
                    for (unsigned d = 0; d != monitor_dim[m]; ++d)
                        os << '\t' << (*iter_monitor_record[m])[d];
                    ++iter_monitor_index[m];
                    ++iter_monitor_record[m];
                } else {
                    for (unsigned d = 0; d != monitor_dim[m]; ++d)
                        os << '\t' << '.';
                }
            }

            os << '\n';
        }
    }

    private :

    /// Initialization indicator
    bool initialized_;

    /// Initialization and movement
    initialize_type init_;
    move_type move_;
    std::vector<move_type> mcmc_;

    /// Resampling
    ResampleScheme scheme_;
    double threshold_;

    /// Particle sets
    Particle<T> particle_;
    unsigned iter_num_;
    ess_type ess_;
    resampled_type resampled_;
    accept_type accept_;

    /// Monte Carlo estimation by integration
    std::map<std::string, Monitor<T> > monitor_;
    std::set<std::string> monitor_name_;

    /// Path sampling
    Path<T> path_;

    void post_move ()
    {
        bool do_resample = particle_.ess() < threshold_ * size();
        if (do_resample)
            particle_.resample(scheme_);

        if (!path_.empty())
            path_.eval(iter_num_, particle_);

        for (typename std::map<std::string, Monitor<T> >::iterator
                imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
            if (!imap->second.empty())
                imap->second.eval(iter_num_, particle_);
        }

        ess_.push_back(particle_.ess());
        resampled_.push_back(do_resample);
        particle_.resampled(resampled_.back());
        particle_.accept(accept_.back());
    }
}; // class Sampler

} // namespace vSMC

namespace std {

/// \brief Print the sampler
///
/// \param os The ostream to which the contents are printed
/// \param sampler The sampler to be printed
///
/// \note This is the same as <tt>sampler.print(os)</tt>
template<typename T>
std::ostream & operator<< (std::ostream &os, const vSMC::Sampler<T> &sampler)
{
    sampler.print(os);

    return os;
}

} // namespace std

#endif // V_SMC_CORE_SAMPLER_HPP
<commit_msg>split accept count recording and accordingly new print<commit_after>#ifndef V_SMC_CORE_SAMPLER_HPP
#define V_SMC_CORE_SAMPLER_HPP

#include <vSMC/internal/common.hpp>
#include <iostream>
#include <map>
#include <set>
#include <string>

namespace vSMC {

/// \brief SMC Sampler
///
/// \tparam T State state type. Requiment:
/// \li Consturctor: T (IntType N)
/// \li Method: copy (IntType from, IntType to)
template <typename T>
class Sampler
{
    public :

    /// The type of initialization functor
    typedef internal::function<unsigned (Particle<T> &, void *)>
        initialize_type;

    /// The type of move and mcmc functor
    typedef internal::function<unsigned (unsigned, Particle<T> &)>
        move_type;

    /// The type of ESS history vector
    typedef std::deque<double> ess_type;

    /// The type of resampling history vector
    typedef std::deque<bool> resampled_type;

    /// The type of accept count history vector
    typedef std::deque<std::deque<unsigned> > accept_type;

    /// The type of Monitor map
    typedef std::map<std::string, Monitor<T> > monitor_map;

    /// \brief Construct a sampler with given number of particles
    ///
    /// \param N The number of particles
    /// \param init The functor used to initialize the particles
    /// \param move The functor used to move the particles and weights
    /// \param scheme The resampling scheme. See ResampleScheme
    /// \param threshold The threshold for performing resampling
    /// \param seed The seed to the parallel RNG system
    explicit Sampler (
            typename Particle<T>::size_type N,
            const initialize_type &init = NULL,
            const move_type &move = NULL,
            ResampleScheme scheme = STRATIFIED,
            double threshold = 0.5,
            typename Particle<T>::seed_type seed = V_SMC_CRNG_SEED) :
        initialized_(false), init_(init), move_(move),
        scheme_(scheme), threshold_(threshold),
        particle_(N, seed), iter_num_(0) {}

    /// \brief Size of the particle set
    ///
    /// \return The number of particles
    typename Particle<T>::size_type size () const
    {
        return particle_.size();
    }

    /// \brief The number of iterations recorded
    ///
    /// \return The number of iterations recorded so far (including the
    /// initialization)
    unsigned iter_size () const
    {
        return ess_.size();
    }

    /// \brief The number of iterations
    ///
    /// \return The number of iterations performed by iterate() so far (not
    /// including the initialization)
    unsigned iter_num () const
    {
        return iter_num_;
    }

    /// \brief Get the current resampling scheme
    ///
    /// \return The current resampling scheme
    ResampleScheme resample_scheme () const
    {
        return scheme_;
    }

    /// \brief Set new resampling scheme
    ///
    /// \param scheme The new scheme for resampling
    void resample_scheme (ResampleScheme scheme)
    {
        scheme_ = scheme;
    }

    /// \brief Get the current threshold
    ///
    /// \return The current threshold for resmapling
    double resample_threshold () const
    {
        return threshold_;
    }

    /// \brief Set new resampling threshold
    ///
    /// \param threshold The new threshold for resampling
    void resample_threshold (double threshold)
    {
        threshold_ = threshold;
    }

    /// \brief ESS history
    ///
    /// \return A const reference to the history of ESS
    const ess_type &ess () const
    {
        return ess_;
    }

    /// \brief Resampling history
    ///
    /// \return A const reference to the history of resampling
    const resampled_type &resampled () const
    {
        return resampled_;
    }

    /// \brief Accept count history
    ///
    /// \return A const reference to the history of accept count
    const accept_type &accept () const
    {
        return accept_;
    }

    /// \brief Read and write access to the particle set
    ///
    /// \return A reference to the latest particle set
    Particle<T> &particle ()
    {
        return particle_;
    }

    /// \brief Read only access to the particle set
    ///
    /// \return A const reference to the latest particle set.
    const Particle<T> &particle () const
    {
        return particle_;
    }

    /// \brief Replace initialization functor
    ///
    /// \param new_init New Initialization functor
    void init (const initialize_type &new_init)
    {
        init_ = new_init;
    }

    /// \brief Replace iteration functor
    ///
    /// \param new_move New Move functor
    void move (const move_type &new_move)
    {
        move_ = new_move;
    }

    /// \brief Replace iteration functor
    ///
    /// \param new_mcmc New MCMC Move functor
    void mcmc (const move_type &new_mcmc)
    {
        mcmc_.push_back(new_mcmc);
    }

    /// \brief Clear all MCMC moves
    void clear_mcmc ()
    {
        mcmc_.clear();
    }

    /// \brief Initialize the particle set
    ///
    /// \param param Additional parameters passed to the initialization
    /// functor
    void initialize (void *param = NULL)
    {
        assert(bool(init_));

        ess_.clear();
        resampled_.clear();
        accept_.clear();
        path_.clear();

        for (typename monitor_map::iterator miter = monitor_.begin();
                miter != monitor_.end(); ++miter)
            miter->second.clear();

        iter_num_ = 0;
        accept_.push_back(std::deque<unsigned>(1, init_(particle_, param)));
        post_move();
        particle_.reset_zconst();

        initialized_ = true;
    }

    /// \brief Perform iteration
    void iterate ()
    {
        ++iter_num_;
        std::deque<unsigned> acc;
        if (bool(move_))
            acc.push_back(move_(iter_num_, particle_));
        for (typename std::deque<move_type>::iterator miter = mcmc_.begin();
                miter != mcmc_.end(); ++miter)
            acc.push_back((*miter)(iter_num_, particle_));
        accept_.push_back(acc);
        post_move();
    }

    /// \brief Perform iteration
    ///
    /// \param n The number of iterations to be performed
    void iterate (unsigned n)
    {
        for (unsigned i = 0; i != n; ++i)
            iterate();
    }

    /// \brief Perform importance sampling integration
    ///
    /// \param dim The dimension of the parameter
    /// \param integral The functor used to compute the integrands
    /// \param res The result, an array of length dim
    void integrate (unsigned dim,
            const typename Monitor<T>::integral_type &integral, double *res)
    {
        assert(bool(integral));
        assert(dim > 0);

        Monitor<T> m(dim, integral);
        m.eval(iter_num_, particle_);
        for (unsigned d = 0; d += dim; ++d)
            res[d] = m.record()[d].back();
    }

    /// \brief Add a monitor, similar to \b monitor in \b BUGS
    ///
    /// \param name The name of the monitor
    /// \param integral The functor used to compute the integrands
    template<typename MonitorIntegralType>
    void monitor (const std::string &name, const MonitorIntegralType &integral)
    {
        monitor_.insert(std::make_pair(
                    name, Monitor<T>(integral.dim(), integral)));
        monitor_name_.insert(name);
    }

    /// \brief Add a monitor, similar to \b monitor in \b BUGS
    ///
    /// \param name The name of the monitor
    /// \param dim The dimension of the monitor
    /// \param integral The functor used to compute the integrands
    void monitor (const std::string &name, unsigned dim,
            const typename Monitor<T>::integral_type &integral)
    {
        monitor_.insert(std::make_pair(name, Monitor<T>(dim, integral)));
        monitor_name_.insert(name);
    }

    /// \brief Read only access to a named monitor through iterator
    ///
    /// \param name The name of the monitor
    ///
    /// \return An const_iterator point to the monitor for the given name
    typename monitor_map::const_iterator monitor (
            const std::string &name) const
    {
        return monitor_.find(name);
    }

    /// \brief Read and write access to a named monitor through iterator
    ///
    /// \param name The name of the monitor
    ///
    /// \return An iterator point to the monitor for the given name
    typename monitor_map::iterator monitor (const std::string &name)
    {
        return monitor_.find(name);
    }

    /// \brief Read only access to all monitors
    ///
    /// \return A const reference to monitors
    const monitor_map &monitor () const
    {
        return monitor_;
    }

    /// \brief Read and write access to all monitors
    ///
    /// \return A reference to monitors
    monitor_map &monitor ()
    {
        return monitor_;
    }

    /// \brief Erase a named monitor
    ///
    /// \param name The name of the monitor
    void clear_monitor (const std::string &name)
    {
        monitor_.erase(name);
        monitor_name_.erase(name);
    }

    /// \brief Erase all monitors
    void clear_monitor ()
    {
        monitor_.clear();
        monitor_name_.clear();
    }

    /// \brief Read only access to the Path sampling monitor
    ///
    /// \return A const reference to the Path sampling monitor
    const Path<T> &path () const
    {
        return path_;
    }

    /// \brief Set the path sampling integral
    ///
    /// \param integral The functor used to compute the integrands
    void path_sampling (const typename Path<T>::integral_type &integral)
    {
        path_.integral(integral);
    }

    /// \brief Path sampling estimate of normalizing constant
    ///
    /// \return The log ratio of normalizing constants
    double path_sampling () const
    {
        return path_.zconst();
    }

    /// \brief SMC estimate of normalizing constant
    ///
    /// \return The log of SMC normalizng constant estimate
    double zconst () const
    {
        return particle_.zconst();
    }

    /// \brief Print the history of the sampler
    ///
    /// \param os The ostream to which the contents are printed
    /// \param print_header Print header if \b true
    void print (std::ostream &os = std::cout, bool print_header = true) const
    {
        // Accept count
        unsigned accept_dim = 0;
        for (accept_type::const_iterator aiter = accept_.begin();
                aiter != accept_.end(); ++aiter)
            if (aiter->size() > accept_dim)
                accept_dim = aiter->size();
        Eigen::MatrixXd accept_data(iter_num_ + 1, accept_dim);
        accept_data.setConstant(0);
        double anorm = static_cast<double>(size());
        for (unsigned r = 0; r != iter_num_ + 1; ++r)
            for (unsigned c = 0; c != accept_[r].size(); ++c)
                accept_data(r, c) = accept_[r][c] / anorm;

        // Path sampling
        Eigen::MatrixXd path_data(iter_num_ + 1, 3);
        Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic>
            path_mask(iter_num_ + 1, 1);
        path_mask.setConstant(false);
        for (unsigned d = 0; d != path_.iter_size(); ++d) {
            unsigned prow = path_.index()[d];
            path_data(prow, 0) = path_.integrand()[d];
            path_data(prow, 1) = path_.width()[d];
            path_data(prow, 2) = path_.grid()[d];
            path_mask(prow) = true;
        }

        // Monitors
        unsigned monitor_dim = 0;
        for (typename monitor_map::const_iterator miter = monitor_.begin();
                miter != monitor_.end(); ++miter)
            monitor_dim += miter->second.dim();
        Eigen::MatrixXd monitor_data(iter_num_ + 1, monitor_dim);
        Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic>
            monitor_mask(iter_num_ + 1, monitor_.size());
        unsigned mcol = 0;
        unsigned mmask = 0;
        for (typename monitor_map::const_iterator miter = monitor_.begin();
                miter != monitor_.end(); ++miter) {
            unsigned mdim = miter->second.dim();
            for (unsigned d = 0; d != miter->second.iter_size(); ++d) {
                unsigned mrow = miter->second.index()[d];
                for (unsigned c = 0; c != mdim; ++c) {
                    monitor_data(mrow, c + mcol) =
                        miter->second.record()[c][d];
                }
                monitor_mask(mrow, mmask) = true;
            }
            mcol += miter->second.dim();
            ++mmask;
        }

        // Print header
        if (print_header) {
            os << "iter\tESS\tresample\t";
            if (accept_dim == 1) {
                os << "accept\t";
            }
            else {
                for (unsigned d = 0; d != accept_dim; ++d)
                    os << "accept" << d + 1 << '\t';
            }
            os << "path.integrand\tpath.width\tpath.grid\t";
            for (typename monitor_map::const_iterator miter = monitor_.begin();
                    miter != monitor_.end(); ++miter) {
                if (miter->second.dim() == 1) {
                    os << miter->first << '\t';
                } else {
                    for (unsigned d = 0; d != miter->second.dim(); ++d)
                        os << miter->first << d + 1 << '\t';
                }
            }
            os << '\n';
        }

        // Print data
        for (unsigned iter = 0; iter != iter_num_ + 1; ++iter) {
            os << iter << '\t';
            os << ess_[iter] / size() << '\t';
            os << resampled_[iter] << '\t';
            os << accept_data.row(iter) << '\t';
            if (path_mask(iter))
                os << path_data.row(iter) << '\t';
            else
                os << ".\t.\t.\t";
            unsigned mcol = 0;
            unsigned mmask = 0;
            for (typename monitor_map::const_iterator miter = monitor_.begin();
                    miter != monitor_.end(); ++miter) {
                unsigned mdim = miter->second.dim();
                if (monitor_mask(iter, mmask)) {
                    os << monitor_data.block(iter, mcol, 1, mdim) << '\t';
                } else {
                    for (unsigned m = 0; m != mdim; ++m)
                        os << ".\t";
                }
                mcol += miter->second.dim();
                ++mmask;
            }
            os << '\n';
        }
    }

    private :

    /// Initialization indicator
    bool initialized_;

    /// Initialization and movement
    initialize_type init_;
    move_type move_;
    std::deque<move_type> mcmc_;

    /// Resampling
    ResampleScheme scheme_;
    double threshold_;

    /// Particle sets
    Particle<T> particle_;
    unsigned iter_num_;
    ess_type ess_;
    resampled_type resampled_;
    accept_type accept_;

    /// Monte Carlo estimation by integration
    monitor_map monitor_;
    std::set<std::string> monitor_name_;

    /// Path sampling
    Path<T> path_;

    void post_move ()
    {
        bool do_resample = particle_.ess() < threshold_ * size();
        if (do_resample)
            particle_.resample(scheme_);

        if (!path_.empty())
            path_.eval(iter_num_, particle_);

        for (typename std::map<std::string, Monitor<T> >::iterator
                imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
            if (!imap->second.empty())
                imap->second.eval(iter_num_, particle_);
        }

        ess_.push_back(particle_.ess());
        resampled_.push_back(do_resample);
        particle_.resampled(resampled_.back());
        particle_.accept(accept_.back().back());
    }
}; // class Sampler

} // namespace vSMC

namespace std {

/// \brief Print the sampler
///
/// \param os The ostream to which the contents are printed
/// \param sampler The sampler to be printed
///
/// \note This is the same as <tt>sampler.print(os)</tt>
template<typename T>
std::ostream & operator<< (std::ostream &os, const vSMC::Sampler<T> &sampler)
{
    sampler.print(os);

    return os;
}

} // namespace std

#endif // V_SMC_CORE_SAMPLER_HPP
<|endoftext|>


<commit_before>#if defined(_MSC_VER)
#define _CRTDBG_MAP_ALLOC
#define _CRT_SECURE_NO_WARNINGS
#include <crtdbg.h>
#endif

#include "CoolPropDLL.h"
#include "CoolProp.h"
#include "HumidAirProp.h"
#include "DataStructures.h"
#include "Exceptions.h"

double convert_from_kSI_to_SI(long iInput, double value)
{
	if (get_debug_level() > 8){
		std::cout << format("%s:%d: convert_from_kSI_to_SI(i=%d,value=%g)\n",__FILE__,__LINE__,iInput,value).c_str();
	}

	switch (iInput)
	{
    case CoolProp::iP:
	case CoolProp::iCpmass:
	case CoolProp::iCp0mass:
	case CoolProp::iSmass:
	case CoolProp::iGmass:
	case CoolProp::iCvmass:
	case CoolProp::iHmass:
	case CoolProp::iUmass:
	case CoolProp::iconductivity:
        return value*1000.0;
	case CoolProp::iDmass:
	case CoolProp::ispeed_sound:
	case CoolProp::iQ:
	case CoolProp::iviscosity:
	case CoolProp::iT:
	case CoolProp::iPrandtl:
	case CoolProp::isurface_tension:
		return value;
	default:
		throw CoolProp::ValueError(format("index [%d] is invalid in convert_from_kSI_to_SI",iInput).c_str());
		break;
	}
	return _HUGE;
}

double convert_from_SI_to_kSI(long iInput, double value)
{
	if (get_debug_level() > 8){
		std::cout << format("%s:%d: convert_from_SI_to_kSI(%d,%g)\n",__FILE__,__LINE__,iInput,value).c_str();
	}

	switch (iInput)
	{
    case CoolProp::iP:
	case CoolProp::iCpmass:
	case CoolProp::iCp0mass:
	case CoolProp::iSmass:
	case CoolProp::iGmass:
	case CoolProp::iCvmass:
	case CoolProp::iHmass:
	case CoolProp::iUmass:
	case CoolProp::iconductivity:
        return value/1000.0;
	case CoolProp::iDmass:
	case CoolProp::iQ:
	case CoolProp::ispeed_sound:
	case CoolProp::iviscosity:
	case CoolProp::iT:
	case CoolProp::isurface_tension:
		return value;
	default:
		throw CoolProp::ValueError(format("index [%d] is invalid in convert_from_SI_to_kSI", iInput).c_str());
		break;
	}
	return _HUGE;
}

EXPORT_CODE long CONVENTION redirect_stdout(const char* file){
	freopen(file, "a+", stdout);
	return 0;
}
//EXPORT_CODE int CONVENTION set_reference_stateS(const char *Ref, const char *reference_state)
//{
//	return set_reference_stateS(std::string(Ref), std::string(reference_state));
//}
//EXPORT_CODE int CONVENTION set_reference_stateD(const char *Ref, double T, double rho, double h0, double s0)
//{
//	return set_reference_stateD(std::string(Ref), T, rho, h0, s0);
//}

// All the function interfaces that point to the single-input Props function
EXPORT_CODE double CONVENTION Props1(const char *FluidName, const char *Output){
    return PropsS(Output, "", 0, "", 0, FluidName);
}
EXPORT_CODE double CONVENTION PropsS(const char *Output, const char* Name1, double Prop1, const char* Name2, double Prop2, const char * Ref){
	double val = Props(Output,Name1[0],Prop1,Name2[0],Prop2,Ref);
	return val;
}
EXPORT_CODE double CONVENTION Props(const char *Output, char Name1, double Prop1, char Name2, double Prop2, const char * Ref)
{
    try
    {
        // Get parameter indices
        std::string sName1 = std::string(1, Name1), sName2 = std::string(1, Name2);
        long iOutput = get_param_index(Output);
        long iName1 = CoolProp::get_parameter_index(sName1);
        long iName2 = CoolProp::get_parameter_index(sName2);

        // Convert inputs to SI
        Prop1 = convert_from_kSI_to_SI(iName1, Prop1);
        Prop2 = convert_from_kSI_to_SI(iName2, Prop2);

	    // Call the SI function
        double val = PropsSI(Output, sName1.c_str(), Prop1, sName2.c_str(), Prop2, Ref);

	    // Convert back to unit system
        return convert_from_SI_to_kSI(iOutput, val);
    }
    catch(std::exception &e){CoolProp::set_error_string(e.what()); return _HUGE;}
    catch(...){CoolProp::set_error_string("Undefined error"); return _HUGE;}
}
EXPORT_CODE double CONVENTION Props1SI(const char *FluidName, const char *Output)
{
    std::string _Output = Output, _FluidName = FluidName;
    return CoolProp::PropsSI(_Output, "", 0, "", 0, _FluidName);
}
EXPORT_CODE double CONVENTION PropsSI(const char *Output, const char *Name1, double Prop1, const char *Name2, double Prop2, const char * FluidName)
{
    std::string _Output = Output, _Name1 = Name1, _Name2 = Name2, _FluidName = FluidName;
    return CoolProp::PropsSI(_Output, _Name1, Prop1, _Name2, Prop2, _FluidName);
}
EXPORT_CODE double CONVENTION PropsSIZ(const char *Output, const char *Name1, double Prop1, const char *Name2, double Prop2, const char * FluidName, const double *z, int n)
{
    std::string _Output = Output, _Name1 = Name1, _Name2 = Name2, _FluidName = FluidName;
    return CoolProp::PropsSI(_Output, _Name1, Prop1, _Name2, Prop2, _FluidName, std::vector<double>(z, z+n));
}
EXPORT_CODE void CONVENTION F77PropsSI(const char *Output, const char *Name1, double *Prop1, const char *Name2, double *Prop2, const char * FluidName, double *output)
{
    std::string _Output = Output, _Name1 = Name1, _Name2 = Name2, _FluidName = FluidName;
    *output = CoolProp::PropsSI(_Output, _Name1, *Prop1, _Name2, *Prop2, _FluidName);
}

EXPORT_CODE double CONVENTION K2F(double T){
    return T * 9 / 5 - 459.67;
}
EXPORT_CODE double CONVENTION F2K(double T_F){
    return (T_F + 459.67) * 5 / 9;
}
EXPORT_CODE int CONVENTION get_debug_level(){
    return CoolProp::get_debug_level();
}
EXPORT_CODE void CONVENTION set_debug_level(int level){
    CoolProp::set_debug_level(level);
}
EXPORT_CODE long CONVENTION get_param_index(const char * param){
    return CoolProp::get_parameter_index(param);
}
#ifndef SWIG
EXPORT_CODE long CONVENTION get_global_param_string(const char *param, char * Output)
{
	strcpy(Output,CoolProp::get_global_param_string(param).c_str());
	return 0;
}
//EXPORT_CODE long CONVENTION get_fluid_param_string(const char *fluid, const char *param, char * Output)
//{
//	strcpy(Output, get_fluid_param_string(std::string(fluid), std::string(param)).c_str());
//	return 0;
//}
#endif

EXPORT_CODE double CONVENTION HAPropsSI(const char *Output, const char *Name1, double Prop1, const char *Name2, double Prop2, const char * Name3, double Prop3)
{
	return HumidAir::HAPropsSI(Output, Name1, Prop1, Name2, Prop2, Name3, Prop3);
}
EXPORT_CODE void CONVENTION F77HAPropsSI(const char *Output, const char *Name1, double *Prop1, const char *Name2, double *Prop2, const char * Name3, double * Prop3, double *output)
{
	*output = HumidAir::HAPropsSI(Output, Name1, *Prop1, Name2, *Prop2, Name3, *Prop3);
}
<commit_msg>Added missing string.h header include<commit_after>#if defined(_MSC_VER)
#define _CRTDBG_MAP_ALLOC
#define _CRT_SECURE_NO_WARNINGS
#include <crtdbg.h>
#endif

#include "CoolPropDLL.h"
#include "CoolProp.h"
#include "HumidAirProp.h"
#include "DataStructures.h"
#include "Exceptions.h"

#include <string.h>
double convert_from_kSI_to_SI(long iInput, double value)
{
	if (get_debug_level() > 8){
		std::cout << format("%s:%d: convert_from_kSI_to_SI(i=%d,value=%g)\n",__FILE__,__LINE__,iInput,value).c_str();
	}

	switch (iInput)
	{
    case CoolProp::iP:
	case CoolProp::iCpmass:
	case CoolProp::iCp0mass:
	case CoolProp::iSmass:
	case CoolProp::iGmass:
	case CoolProp::iCvmass:
	case CoolProp::iHmass:
	case CoolProp::iUmass:
	case CoolProp::iconductivity:
        return value*1000.0;
	case CoolProp::iDmass:
	case CoolProp::ispeed_sound:
	case CoolProp::iQ:
	case CoolProp::iviscosity:
	case CoolProp::iT:
	case CoolProp::iPrandtl:
	case CoolProp::isurface_tension:
		return value;
	default:
		throw CoolProp::ValueError(format("index [%d] is invalid in convert_from_kSI_to_SI",iInput).c_str());
		break;
	}
	return _HUGE;
}

double convert_from_SI_to_kSI(long iInput, double value)
{
	if (get_debug_level() > 8){
		std::cout << format("%s:%d: convert_from_SI_to_kSI(%d,%g)\n",__FILE__,__LINE__,iInput,value).c_str();
	}

	switch (iInput)
	{
    case CoolProp::iP:
	case CoolProp::iCpmass:
	case CoolProp::iCp0mass:
	case CoolProp::iSmass:
	case CoolProp::iGmass:
	case CoolProp::iCvmass:
	case CoolProp::iHmass:
	case CoolProp::iUmass:
	case CoolProp::iconductivity:
        return value/1000.0;
	case CoolProp::iDmass:
	case CoolProp::iQ:
	case CoolProp::ispeed_sound:
	case CoolProp::iviscosity:
	case CoolProp::iT:
	case CoolProp::isurface_tension:
		return value;
	default:
		throw CoolProp::ValueError(format("index [%d] is invalid in convert_from_SI_to_kSI", iInput).c_str());
		break;
	}
	return _HUGE;
}

EXPORT_CODE long CONVENTION redirect_stdout(const char* file){
	freopen(file, "a+", stdout);
	return 0;
}
//EXPORT_CODE int CONVENTION set_reference_stateS(const char *Ref, const char *reference_state)
//{
//	return set_reference_stateS(std::string(Ref), std::string(reference_state));
//}
//EXPORT_CODE int CONVENTION set_reference_stateD(const char *Ref, double T, double rho, double h0, double s0)
//{
//	return set_reference_stateD(std::string(Ref), T, rho, h0, s0);
//}

// All the function interfaces that point to the single-input Props function
EXPORT_CODE double CONVENTION Props1(const char *FluidName, const char *Output){
    return PropsS(Output, "", 0, "", 0, FluidName);
}
EXPORT_CODE double CONVENTION PropsS(const char *Output, const char* Name1, double Prop1, const char* Name2, double Prop2, const char * Ref){
	double val = Props(Output,Name1[0],Prop1,Name2[0],Prop2,Ref);
	return val;
}
EXPORT_CODE double CONVENTION Props(const char *Output, char Name1, double Prop1, char Name2, double Prop2, const char * Ref)
{
    try
    {
        // Get parameter indices
        std::string sName1 = std::string(1, Name1), sName2 = std::string(1, Name2);
        long iOutput = get_param_index(Output);
        long iName1 = CoolProp::get_parameter_index(sName1);
        long iName2 = CoolProp::get_parameter_index(sName2);

        // Convert inputs to SI
        Prop1 = convert_from_kSI_to_SI(iName1, Prop1);
        Prop2 = convert_from_kSI_to_SI(iName2, Prop2);

	    // Call the SI function
        double val = PropsSI(Output, sName1.c_str(), Prop1, sName2.c_str(), Prop2, Ref);

	    // Convert back to unit system
        return convert_from_SI_to_kSI(iOutput, val);
    }
    catch(std::exception &e){CoolProp::set_error_string(e.what()); return _HUGE;}
    catch(...){CoolProp::set_error_string("Undefined error"); return _HUGE;}
}
EXPORT_CODE double CONVENTION Props1SI(const char *FluidName, const char *Output)
{
    std::string _Output = Output, _FluidName = FluidName;
    return CoolProp::PropsSI(_Output, "", 0, "", 0, _FluidName);
}
EXPORT_CODE double CONVENTION PropsSI(const char *Output, const char *Name1, double Prop1, const char *Name2, double Prop2, const char * FluidName)
{
    std::string _Output = Output, _Name1 = Name1, _Name2 = Name2, _FluidName = FluidName;
    return CoolProp::PropsSI(_Output, _Name1, Prop1, _Name2, Prop2, _FluidName);
}
EXPORT_CODE double CONVENTION PropsSIZ(const char *Output, const char *Name1, double Prop1, const char *Name2, double Prop2, const char * FluidName, const double *z, int n)
{
    std::string _Output = Output, _Name1 = Name1, _Name2 = Name2, _FluidName = FluidName;
    return CoolProp::PropsSI(_Output, _Name1, Prop1, _Name2, Prop2, _FluidName, std::vector<double>(z, z+n));
}
EXPORT_CODE void CONVENTION F77PropsSI(const char *Output, const char *Name1, double *Prop1, const char *Name2, double *Prop2, const char * FluidName, double *output)
{
    std::string _Output = Output, _Name1 = Name1, _Name2 = Name2, _FluidName = FluidName;
    *output = CoolProp::PropsSI(_Output, _Name1, *Prop1, _Name2, *Prop2, _FluidName);
}

EXPORT_CODE double CONVENTION K2F(double T){
    return T * 9 / 5 - 459.67;
}
EXPORT_CODE double CONVENTION F2K(double T_F){
    return (T_F + 459.67) * 5 / 9;
}
EXPORT_CODE int CONVENTION get_debug_level(){
    return CoolProp::get_debug_level();
}
EXPORT_CODE void CONVENTION set_debug_level(int level){
    CoolProp::set_debug_level(level);
}
EXPORT_CODE long CONVENTION get_param_index(const char * param){
    return CoolProp::get_parameter_index(param);
}
#ifndef SWIG
EXPORT_CODE long CONVENTION get_global_param_string(const char *param, char * Output)
{
	strcpy(Output,CoolProp::get_global_param_string(param).c_str());
	return 0;
}
//EXPORT_CODE long CONVENTION get_fluid_param_string(const char *fluid, const char *param, char * Output)
//{
//	strcpy(Output, get_fluid_param_string(std::string(fluid), std::string(param)).c_str());
//	return 0;
//}
#endif

EXPORT_CODE double CONVENTION HAPropsSI(const char *Output, const char *Name1, double Prop1, const char *Name2, double Prop2, const char * Name3, double Prop3)
{
	return HumidAir::HAPropsSI(Output, Name1, Prop1, Name2, Prop2, Name3, Prop3);
}
EXPORT_CODE void CONVENTION F77HAPropsSI(const char *Output, const char *Name1, double *Prop1, const char *Name2, double *Prop2, const char * Name3, double * Prop3, double *output)
{
	*output = HumidAir::HAPropsSI(Output, Name1, *Prop1, Name2, *Prop2, Name3, *Prop3);
}
<|endoftext|>


<commit_before>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Flavio Castelli <flavio.castelli@gmail.com>
 *                    Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "daemonconfigurator.h"
#include "../strigilogging.h"

#include <algorithm>
#include <fstream>
#include <sstream>
#include <stdlib.h>

using namespace std;
using namespace Strigi;

class FindRepository {
private:
    string m_repoName;

public:
    FindRepository(string repoName) { m_repoName = repoName; }

    bool operator()(Repository repo) {
        if (repo.a_name.compare(m_repoName) == 0) {
            return true;
        }
        return false;
    }
};

DaemonConfigurator::DaemonConfigurator (const string& confFile)
        : m_confFile (confFile) {
    // find the strigi directory
    string strigidir;
    string::size_type slashpos = confFile.rfind('/');
    if (slashpos != string::npos) {
        strigidir = confFile.substr(0, slashpos);
    } else {
        strigidir = getenv("HOME") + string("/.strigi");
    }

    stringbuf xml;
    ifstream f(confFile.c_str(), ios::binary);
    f.get(xml, '\0');
    f.close();

    if (xml.str().length()) {
        XMLStream stream(xml.str());
        stream >> *this;
    }
    FindRepository findRepository("localhost");
    list<Repository>::iterator match = find_if(e_repository.begin(),
                                               e_repository.end(),
                                               findRepository);

    // entry for localhost repository doesn't exists
    if (match == e_repository.end()) {
        a_useDBus = true;
        Repository r;
        r.a_name = "localhost";
        string home;
        if (getenv("HOME")) {
            home.assign(getenv("HOME"));
        }
        r.a_indexdir = strigidir + "/clucene";
        r.a_writeable = true;
        r.a_type = "clucene";
        r.a_pollingInterval = DEFAULT_POLLING_INTERVAL;

        Path p;
        p.a_path = home;                 r.e_path.push_back(p);
        p.a_path = home + "/.kde";       r.e_path.push_back(p);
        p.a_path = home + "/.kde4";      r.e_path.push_back(p);
        p.a_path = home + "/.gnome2";    r.e_path.push_back(p);
        p.a_path = home + "/.evolution"; r.e_path.push_back(p);
        p.a_path = home + "/.mozilla";   r.e_path.push_back(p);
        p.a_path = home + "/.mozilla-thunderbird";   r.e_path.push_back(p);
        e_repository.push_back(r);

        // add pattern to ignore hidden directories and hidden files
        Filter f;
        f.a_include = true;
        f.a_pattern = ".*.directory/"; // mail box directory
        e_filters.e_filter.push_back(f);
        f.a_include = false;
        f.a_pattern = ".*/";
        e_filters.e_filter.push_back(f);
        f.a_pattern = ".*";
        e_filters.e_filter.push_back(f);

        STRIGI_LOG_WARNING ("DaemonConfigurator",
                            "created default config for indexed dirs");
    }
    save();
}
void
DaemonConfigurator::setIndexedDirectories ( set<string>& dirs,
                                            const string& repositoryName,
                                            bool  merge) {
    FindRepository findRepository (repositoryName);

    list<Repository>::iterator match = find_if (e_repository.begin(),
                                                e_repository.end(),
                                                findRepository);

    Repository* r;

    if (match != e_repository.end()) {
        r = &(*match);
    } else {
        // create a new repository
        Repository repo;
        repo.a_name = repositoryName;
        e_repository.push_back(repo);
        return setIndexedDirectories (dirs, repositoryName, merge);
    }

    // clear old path
    if (!merge) {
        r->e_path.clear();
    }

    for (set<string>::const_iterator iter = dirs.begin(); iter != dirs.end();
            ++iter) {
        Path p;
        p.a_path = *iter;
        r->e_path.push_back(p);
    }
}
set<string>
DaemonConfigurator::getIndexedDirectories(const string& repositoryName) {
    set<string> dirs;

    FindRepository findRepository (repositoryName);

    list<Repository>::iterator match = find_if (e_repository.begin(),
                                                e_repository.end(),
                                                findRepository);

    if (match == e_repository.end()) {
        STRIGI_LOG_WARNING ("DaemonConfigurator.getIndexedDirs",
                       "cannot find repository name: |" + repositoryName + '|');
        return dirs;
    }

    Repository* r = &(*match);

    for (list<Path>::const_iterator iter = r->e_path.begin();
         iter != r->e_path.end(); ++iter) {
        dirs.insert (iter->a_path);
    }

    return dirs;
}
void
DaemonConfigurator::save(const char* file) {
    ofstream f;
    if (file == NULL) {
        f.open(m_confFile.c_str(), ios::binary);
    } else {
        f.open(file, ios::binary);
    }
    f << *this;
    f.close();
}
string
DaemonConfigurator::getWriteableIndexType() const {
    return (e_repository.size()) ?e_repository.begin()->a_type : "";
}
string
DaemonConfigurator::getWriteableIndexDir() const {
    return (e_repository.size()) ?e_repository.begin()->a_indexdir : "";
}
list<Repository>
DaemonConfigurator::getReadOnlyRepositories() const {
    list<Repository> ro;
    list<Repository>::const_iterator i;
    for (i = e_repository.begin(); i != e_repository.end(); ++i) {
        if (!i->a_writeable) {
            ro.push_back(*i);
        }
    }
    return ro;
}
void
DaemonConfigurator::setPollingInterval (unsigned int value,
                                        const string& repositoryName) {
    FindRepository findRepository (repositoryName);

    list<Repository>::iterator match = find_if (e_repository.begin(),
                                                e_repository.end(),
                                                findRepository);

    if (match != e_repository.end()) {
        Repository* r = &(*match);
        r->a_pollingInterval = value;
    } else {
        // create a new repository
        Repository repo;
        repo.a_name = repositoryName;
        repo.a_pollingInterval = value;
        e_repository.push_back(repo);
    }
}

unsigned int
DaemonConfigurator::getPollingInterval(const string& repositoryName) {
    FindRepository findRepository (repositoryName);

    list<Repository>::iterator match = find_if (e_repository.begin(),
                                                e_repository.end(),
                                                findRepository);

    Repository* r;

    if (match != e_repository.end()) {
        r = &(*match);
    } else {
        // create a new repository
        Repository repo;
        repo.a_name = repositoryName;
        e_repository.push_back(repo);
        r = &repo;
    }

    // check minimum polling interval
    if (r->a_pollingInterval < DEFAULT_POLLING_INTERVAL)
    {
        r->a_pollingInterval = DEFAULT_POLLING_INTERVAL;
        return DEFAULT_POLLING_INTERVAL;
    } else {
        return r->a_pollingInterval;
    }
}
void
DaemonConfigurator::loadFilteringRules(AnalyzerConfiguration& config) {
    vector<pair<bool,string> > filters;
    list<Filter>::const_iterator i;
    for (i = e_filters.e_filter.begin(); i != e_filters.e_filter.end(); ++i) {
        filters.push_back(make_pair<bool,string>(i->a_include, i->a_pattern));
    }
    config.setFilters(filters);
}
void
DaemonConfigurator::saveFilteringRules(const vector<pair<bool,string> >& f) {
    e_filters.e_filter.clear();
    vector<pair<bool,string> >::const_iterator i;
    for (i = f.begin(); i != f.end(); ++i) {
        Filter f;
        f.a_include = i->first;
        f.a_pattern = i->second;
        e_filters.e_filter.push_back(f);
    }
}
<commit_msg>Lower minimum for intervals between polling.<commit_after>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Flavio Castelli <flavio.castelli@gmail.com>
 *                    Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "daemonconfigurator.h"
#include "../strigilogging.h"

#include <algorithm>
#include <fstream>
#include <sstream>
#include <stdlib.h>

using namespace std;
using namespace Strigi;

class FindRepository {
private:
    string m_repoName;

public:
    FindRepository(string repoName) { m_repoName = repoName; }

    bool operator()(Repository repo) {
        if (repo.a_name.compare(m_repoName) == 0) {
            return true;
        }
        return false;
    }
};

DaemonConfigurator::DaemonConfigurator (const string& confFile)
        : m_confFile (confFile) {
    // find the strigi directory
    string strigidir;
    string::size_type slashpos = confFile.rfind('/');
    if (slashpos != string::npos) {
        strigidir = confFile.substr(0, slashpos);
    } else {
        strigidir = getenv("HOME") + string("/.strigi");
    }

    stringbuf xml;
    ifstream f(confFile.c_str(), ios::binary);
    f.get(xml, '\0');
    f.close();

    if (xml.str().length()) {
        XMLStream stream(xml.str());
        stream >> *this;
    }
    FindRepository findRepository("localhost");
    list<Repository>::iterator match = find_if(e_repository.begin(),
                                               e_repository.end(),
                                               findRepository);

    // entry for localhost repository doesn't exists
    if (match == e_repository.end()) {
        a_useDBus = true;
        Repository r;
        r.a_name = "localhost";
        string home;
        if (getenv("HOME")) {
            home.assign(getenv("HOME"));
        }
        r.a_indexdir = strigidir + "/clucene";
        r.a_writeable = true;
        r.a_type = "clucene";
        r.a_pollingInterval = DEFAULT_POLLING_INTERVAL;

        Path p;
        p.a_path = home;                 r.e_path.push_back(p);
        p.a_path = home + "/.kde";       r.e_path.push_back(p);
        p.a_path = home + "/.kde4";      r.e_path.push_back(p);
        p.a_path = home + "/.gnome2";    r.e_path.push_back(p);
        p.a_path = home + "/.evolution"; r.e_path.push_back(p);
        p.a_path = home + "/.mozilla";   r.e_path.push_back(p);
        p.a_path = home + "/.mozilla-thunderbird";   r.e_path.push_back(p);
        e_repository.push_back(r);

        // add pattern to ignore hidden directories and hidden files
        Filter f;
        f.a_include = true;
        f.a_pattern = ".*.directory/"; // mail box directory
        e_filters.e_filter.push_back(f);
        f.a_include = false;
        f.a_pattern = ".*/";
        e_filters.e_filter.push_back(f);
        f.a_pattern = ".*";
        e_filters.e_filter.push_back(f);

        STRIGI_LOG_WARNING ("DaemonConfigurator",
                            "created default config for indexed dirs");
    }
    save();
}
void
DaemonConfigurator::setIndexedDirectories ( set<string>& dirs,
                                            const string& repositoryName,
                                            bool  merge) {
    FindRepository findRepository (repositoryName);

    list<Repository>::iterator match = find_if (e_repository.begin(),
                                                e_repository.end(),
                                                findRepository);

    Repository* r;

    if (match != e_repository.end()) {
        r = &(*match);
    } else {
        // create a new repository
        Repository repo;
        repo.a_name = repositoryName;
        e_repository.push_back(repo);
        return setIndexedDirectories (dirs, repositoryName, merge);
    }

    // clear old path
    if (!merge) {
        r->e_path.clear();
    }

    for (set<string>::const_iterator iter = dirs.begin(); iter != dirs.end();
            ++iter) {
        Path p;
        p.a_path = *iter;
        r->e_path.push_back(p);
    }
}
set<string>
DaemonConfigurator::getIndexedDirectories(const string& repositoryName) {
    set<string> dirs;

    FindRepository findRepository (repositoryName);

    list<Repository>::iterator match = find_if (e_repository.begin(),
                                                e_repository.end(),
                                                findRepository);

    if (match == e_repository.end()) {
        STRIGI_LOG_WARNING ("DaemonConfigurator.getIndexedDirs",
                       "cannot find repository name: |" + repositoryName + '|');
        return dirs;
    }

    Repository* r = &(*match);

    for (list<Path>::const_iterator iter = r->e_path.begin();
         iter != r->e_path.end(); ++iter) {
        dirs.insert (iter->a_path);
    }

    return dirs;
}
void
DaemonConfigurator::save(const char* file) {
    ofstream f;
    if (file == NULL) {
        f.open(m_confFile.c_str(), ios::binary);
    } else {
        f.open(file, ios::binary);
    }
    f << *this;
    f.close();
}
string
DaemonConfigurator::getWriteableIndexType() const {
    return (e_repository.size()) ?e_repository.begin()->a_type : "";
}
string
DaemonConfigurator::getWriteableIndexDir() const {
    return (e_repository.size()) ?e_repository.begin()->a_indexdir : "";
}
list<Repository>
DaemonConfigurator::getReadOnlyRepositories() const {
    list<Repository> ro;
    list<Repository>::const_iterator i;
    for (i = e_repository.begin(); i != e_repository.end(); ++i) {
        if (!i->a_writeable) {
            ro.push_back(*i);
        }
    }
    return ro;
}
void
DaemonConfigurator::setPollingInterval (unsigned int value,
                                        const string& repositoryName) {
    FindRepository findRepository (repositoryName);

    list<Repository>::iterator match = find_if (e_repository.begin(),
                                                e_repository.end(),
                                                findRepository);

    if (match != e_repository.end()) {
        Repository* r = &(*match);
        r->a_pollingInterval = value;
    } else {
        // create a new repository
        Repository repo;
        repo.a_name = repositoryName;
        repo.a_pollingInterval = value;
        e_repository.push_back(repo);
    }
}

unsigned int
DaemonConfigurator::getPollingInterval(const string& repositoryName) {
    FindRepository findRepository (repositoryName);

    list<Repository>::iterator match = find_if (e_repository.begin(),
                                                e_repository.end(),
                                                findRepository);

    Repository* r;

    if (match != e_repository.end()) {
        r = &(*match);
    } else {
        // create a new repository
        Repository repo;
        repo.a_name = repositoryName;
        e_repository.push_back(repo);
        r = &repo;
    }

    // check minimum polling interval
    if (r->a_pollingInterval < 5)
    {
        r->a_pollingInterval = DEFAULT_POLLING_INTERVAL;
        return DEFAULT_POLLING_INTERVAL;
    } else {
        return r->a_pollingInterval;
    }
}
void
DaemonConfigurator::loadFilteringRules(AnalyzerConfiguration& config) {
    vector<pair<bool,string> > filters;
    list<Filter>::const_iterator i;
    for (i = e_filters.e_filter.begin(); i != e_filters.e_filter.end(); ++i) {
        filters.push_back(make_pair<bool,string>(i->a_include, i->a_pattern));
    }
    config.setFilters(filters);
}
void
DaemonConfigurator::saveFilteringRules(const vector<pair<bool,string> >& f) {
    e_filters.e_filter.clear();
    vector<pair<bool,string> >::const_iterator i;
    for (i = f.begin(); i != f.end(); ++i) {
        Filter f;
        f.a_include = i->first;
        f.a_pattern = i->second;
        e_filters.e_filter.push_back(f);
    }
}
<|endoftext|>


<commit_before>/**
 * @file lldiriterator.cpp
 * @brief Iterator through directory entries matching the search pattern.
 *
 * $LicenseInfo:firstyear=2010&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "lldiriterator.h"

#include <boost/filesystem.hpp>
#include <boost/regex.hpp>

namespace fs = boost::filesystem;

static std::string glob_to_regex(const std::string& glob);

class LLDirIterator::Impl
{
public:
	Impl(const std::string &dirname, const std::string &mask);
	~Impl();

	bool next(std::string &fname);

private:
	boost::regex			mFilterExp;
	fs::directory_iterator	mIter;
	bool					mIsValid;
};

LLDirIterator::Impl::Impl(const std::string &dirname, const std::string &mask)
	: mIsValid(false)
{
	fs::path dir_path(dirname);

	// Check if path exists.
	if (!fs::exists(dir_path))
	{
		llwarns << "Invalid path: \"" << dir_path.string() << "\"" << llendl;
		return;
	}

	// Initialize the directory iterator for the given path.
	try
	{
		mIter = fs::directory_iterator(dir_path);
	}
	catch (fs::basic_filesystem_error<fs::path>& e)
	{
		llerrs << e.what() << llendl;
		return;
	}

	// Convert the glob mask to a regular expression
	std::string exp = glob_to_regex(mask);

	// Initialize boost::regex with the expression converted from
	// the glob mask.
	// An exception is thrown if the expression is not valid.
	try
	{
		mFilterExp.assign(exp);
	}
	catch (boost::regex_error& e)
	{
		llerrs << "\"" << exp << "\" is not a valid regular expression: "
				<< e.what() << llendl;
		return;
	}

	mIsValid = true;
}

LLDirIterator::Impl::~Impl()
{
}

bool LLDirIterator::Impl::next(std::string &fname)
{
	fname = "";

	if (!mIsValid)
	{
		llwarns << "The iterator is not correctly initialized." << llendl;
		return false;
	}

	fs::directory_iterator end_itr; // default construction yields past-the-end
	bool found = false;
	while (mIter != end_itr && !found)
	{
		boost::smatch match;
		std::string name = mIter->path().filename();
		if (found = boost::regex_match(name, match, mFilterExp))
		{
			fname = name;
		}

		++mIter;
	}

	return found;
}

/**
Converts the incoming glob into a regex. This involves
converting incoming glob expressions to regex equivilents and
at the same time, escaping any regex meaningful characters which
do not have glob meaning, i.e.
            .()+|^$
in the input.
*/
std::string glob_to_regex(const std::string& glob)
{
	std::string regex;
	regex.reserve(glob.size()<<1);
	S32 braces = 0;
	bool escaped = false;
	bool square_brace_open = false;

	for (std::string::const_iterator i = glob.begin(); i != glob.end(); ++i)
	{
		char c = *i;

		switch (c)
		{
			case '*':
				if (glob.begin() == i)
				{
					regex+="[^.].*";
				}
				else
				{
					regex+= escaped ? "*" : ".*";
				}
				break;
			case '?':
				regex+= escaped ? '?' : '.';
				break;
			case '{':
				braces++;
				regex+='(';
				break;
			case '}':
				if (!braces)
				{
					llerrs << "glob_to_regex: Closing brace without an equivalent opening brace: " << glob << llendl;
				}

				regex+=')';
				braces--;
				break;
			case ',':
				regex+= braces ? '|' : c;
				break;
			case '!':
				regex+= square_brace_open ? '^' : c;
				break;
			case '.': // This collection have different regex meaning
			case '^': // and so need escaping.
			case '(':
			case ')':
			case '+':
			case '|':
			case '$':
				regex += '\\';
			default:
				regex += c;
				break;
		}

		escaped = ('\\' == c);
		square_brace_open = ('[' == c);
	}

	if (braces)
	{
		llerrs << "glob_to_regex: Unterminated brace expression: " << glob << llendl;
	}

	return regex;
}

LLDirIterator::LLDirIterator(const std::string &dirname, const std::string &mask)
{
	mImpl = new Impl(dirname, mask);
}

LLDirIterator::~LLDirIterator()
{
	delete mImpl;
}

bool LLDirIterator::next(std::string &fname)
{
	return mImpl->next(fname);
}
<commit_msg>STORM-1476 FIXED Replaced non-fatal errors in LLDirIterator constructor with warnings to avoid viewer crashes. Added exception handling case.<commit_after>/**
 * @file lldiriterator.cpp
 * @brief Iterator through directory entries matching the search pattern.
 *
 * $LicenseInfo:firstyear=2010&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "lldiriterator.h"

#include <boost/filesystem.hpp>
#include <boost/regex.hpp>

namespace fs = boost::filesystem;

static std::string glob_to_regex(const std::string& glob);

class LLDirIterator::Impl
{
public:
	Impl(const std::string &dirname, const std::string &mask);
	~Impl();

	bool next(std::string &fname);

private:
	boost::regex			mFilterExp;
	fs::directory_iterator	mIter;
	bool					mIsValid;
};

LLDirIterator::Impl::Impl(const std::string &dirname, const std::string &mask)
	: mIsValid(false)
{
	fs::path dir_path(dirname);

	bool is_dir = false;

	// Check if path is a directory.
	try
	{
		is_dir = fs::is_directory(dir_path);
	}
	catch (fs::basic_filesystem_error<fs::path>& e)
	{
		llwarns << e.what() << llendl;
		return;
	}

	if (!is_dir)
	{
		llwarns << "Invalid path: \"" << dir_path.string() << "\"" << llendl;
		return;
	}

	// Initialize the directory iterator for the given path.
	try
	{
		mIter = fs::directory_iterator(dir_path);
	}
	catch (fs::basic_filesystem_error<fs::path>& e)
	{
		llwarns << e.what() << llendl;
		return;
	}

	// Convert the glob mask to a regular expression
	std::string exp = glob_to_regex(mask);

	// Initialize boost::regex with the expression converted from
	// the glob mask.
	// An exception is thrown if the expression is not valid.
	try
	{
		mFilterExp.assign(exp);
	}
	catch (boost::regex_error& e)
	{
		llwarns << "\"" << exp << "\" is not a valid regular expression: "
				<< e.what() << llendl;
		return;
	}

	mIsValid = true;
}

LLDirIterator::Impl::~Impl()
{
}

bool LLDirIterator::Impl::next(std::string &fname)
{
	fname = "";

	if (!mIsValid)
	{
		llwarns << "The iterator is not correctly initialized." << llendl;
		return false;
	}

	fs::directory_iterator end_itr; // default construction yields past-the-end
	bool found = false;
	while (mIter != end_itr && !found)
	{
		boost::smatch match;
		std::string name = mIter->path().filename();
		if (found = boost::regex_match(name, match, mFilterExp))
		{
			fname = name;
		}

		++mIter;
	}

	return found;
}

/**
Converts the incoming glob into a regex. This involves
converting incoming glob expressions to regex equivilents and
at the same time, escaping any regex meaningful characters which
do not have glob meaning, i.e.
            .()+|^$
in the input.
*/
std::string glob_to_regex(const std::string& glob)
{
	std::string regex;
	regex.reserve(glob.size()<<1);
	S32 braces = 0;
	bool escaped = false;
	bool square_brace_open = false;

	for (std::string::const_iterator i = glob.begin(); i != glob.end(); ++i)
	{
		char c = *i;

		switch (c)
		{
			case '*':
				if (glob.begin() == i)
				{
					regex+="[^.].*";
				}
				else
				{
					regex+= escaped ? "*" : ".*";
				}
				break;
			case '?':
				regex+= escaped ? '?' : '.';
				break;
			case '{':
				braces++;
				regex+='(';
				break;
			case '}':
				if (!braces)
				{
					llerrs << "glob_to_regex: Closing brace without an equivalent opening brace: " << glob << llendl;
				}

				regex+=')';
				braces--;
				break;
			case ',':
				regex+= braces ? '|' : c;
				break;
			case '!':
				regex+= square_brace_open ? '^' : c;
				break;
			case '.': // This collection have different regex meaning
			case '^': // and so need escaping.
			case '(':
			case ')':
			case '+':
			case '|':
			case '$':
				regex += '\\';
			default:
				regex += c;
				break;
		}

		escaped = ('\\' == c);
		square_brace_open = ('[' == c);
	}

	if (braces)
	{
		llerrs << "glob_to_regex: Unterminated brace expression: " << glob << llendl;
	}

	return regex;
}

LLDirIterator::LLDirIterator(const std::string &dirname, const std::string &mask)
{
	mImpl = new Impl(dirname, mask);
}

LLDirIterator::~LLDirIterator()
{
	delete mImpl;
}

bool LLDirIterator::next(std::string &fname)
{
	return mImpl->next(fname);
}
<|endoftext|>


<commit_before>/*
qgvdial is a cross platform Google Voice Dialer
Copyright (C) 2010  Yuvraaj Kelkar

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

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

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Contact: yuvraaj@gmail.com
*/

#include "DialContext.h"
#include "Singletons.h"

DialContext::DialContext (const QString &strMy, const QString &strT,
                          QDeclarativeView *mV)
: QObject(mV)
, bDialOut (false)
, ci (NULL)
, strMyNumber (strMy)
, strTarget (strT)
, fallbackCi (NULL)
, mainView (mV)
{
    QObject *pRoot = mainView->rootObject ();
    bool rv = connect (pRoot, SIGNAL (sigMsgBoxDone(bool)),
                       this , SLOT (onSigMsgBoxDone(bool)));
    Q_ASSERT(rv); Q_UNUSED(rv);
}//DialContext::DialContext

DialContext::~DialContext() {
    hideMsgBox ();
}//DialContext::~DialContext

void
DialContext::showMsgBox ()
{
    ObserverFactory &obsF = Singletons::getRef().getObserverFactory ();
    obsF.startObservers (strMyNumber, this, SLOT (callStarted()));

    QString strMessage = QString("Dialing\n%1").arg(strTarget);

    QDeclarativeContext *ctx = mainView->rootContext();
    bool bTemp = true;
    ctx->setContextProperty ("g_bShowMsg", bTemp);
    ctx->setContextProperty ("g_strMsgText", strMessage);
}//DialContext::showMsgBox

void
DialContext::hideMsgBox ()
{
    QDeclarativeContext *ctx = mainView->rootContext();
    bool bTemp = false;
    ctx->setContextProperty ("g_bShowMsg", bTemp);
}//DialContext::hideMsgBox

void
DialContext::callStarted ()
{
    onSigMsgBoxDone (true);
}//DialContext::callStarted

void
DialContext::onSigMsgBoxDone (bool ok)
{
    ObserverFactory &obsF = Singletons::getRef().getObserverFactory ();
    obsF.stopObservers ();

    hideMsgBox ();

    emit sigDialComplete (this, ok);
}//DialContext::onSigMsgBoxDone
<commit_msg>Dial context failed to get the correct pointer for the MainPage.<commit_after>/*
qgvdial is a cross platform Google Voice Dialer
Copyright (C) 2010  Yuvraaj Kelkar

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

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

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Contact: yuvraaj@gmail.com
*/

#include "DialContext.h"
#include "Singletons.h"

DialContext::DialContext (const QString &strMy, const QString &strT,
                          QDeclarativeView *mV)
: QObject(mV)
, bDialOut (false)
, ci (NULL)
, strMyNumber (strMy)
, strTarget (strT)
, fallbackCi (NULL)
, mainView (mV)
{
    QObject *pMain = NULL;
    do { // Begin cleanup block (not a loop)
        QObject *pRoot = mainView->rootObject ();
        if (NULL == pRoot) {
            qWarning ("Couldn't get root object in QML for MainPage");
            break;
        }

        if (pRoot->objectName() == "MainPage") {
            pMain = pRoot;
            break;
        }

        pMain = pRoot->findChild <QObject*> ("MainPage");
        if (NULL == pMain) {
            qWarning ("Could not get to MainPage");
            break;
        }
    } while (0); // End cleanup block (not a loop)

    bool rv = connect (pMain, SIGNAL (sigMsgBoxDone(bool)),
                       this , SLOT (onSigMsgBoxDone(bool)));
    Q_ASSERT(rv); Q_UNUSED(rv);
}//DialContext::DialContext

DialContext::~DialContext() {
    hideMsgBox ();
}//DialContext::~DialContext

void
DialContext::showMsgBox ()
{
    ObserverFactory &obsF = Singletons::getRef().getObserverFactory ();
    obsF.startObservers (strMyNumber, this, SLOT (callStarted()));

    QString strMessage = QString("Dialing\n%1").arg(strTarget);

    QDeclarativeContext *ctx = mainView->rootContext();
    bool bTemp = true;
    ctx->setContextProperty ("g_bShowMsg", bTemp);
    ctx->setContextProperty ("g_strMsgText", strMessage);
}//DialContext::showMsgBox

void
DialContext::hideMsgBox ()
{
    QDeclarativeContext *ctx = mainView->rootContext();
    bool bTemp = false;
    ctx->setContextProperty ("g_bShowMsg", bTemp);
}//DialContext::hideMsgBox

void
DialContext::callStarted ()
{
    onSigMsgBoxDone (true);
}//DialContext::callStarted

void
DialContext::onSigMsgBoxDone (bool ok)
{
    ObserverFactory &obsF = Singletons::getRef().getObserverFactory ();
    obsF.stopObservers ();

    hideMsgBox ();

    emit sigDialComplete (this, ok);
}//DialContext::onSigMsgBoxDone
<|endoftext|>


<commit_before>#include "EditorScene.hpp"

EditorScene* EditorScene::activeScene = nullptr;

// ---------------------------------------------------------------------------
//  Prolog Interface to Scene Editing Commands
// ---------------------------------------------------------------------------
// TODO: Move to appropriate modules

PREDICATE0(pd_save) { return false; }

PREDICATE(pd_saveas, 1) { return false; }

PREDICATE0(pd_exit) { return false; }

PREDICATE(pd_add_actor, 1) {
	try {
		EditorScene::activeScene->addActor(static_cast<const char*>(A1));
	} catch(const std::exception& exception) {
		g_logger.write(Logger::LOG_ERROR, exception.what());
		return false;
	}
	return true;
}

PREDICATE(pd_select, 2) { return false; }

PREDICATE0(pd_deselect) { return false; }

PREDICATE0(pd_remove_actor) { return false; }

PREDICATE(pd_move_by, 3) { return false; }

PREDICATE(pd_move_to, 3) { return false; }

PREDICATE(pd_rotate, 3) { return false; }

PREDICATE0(pd_add_light) { return false; }

PREDICATE(pd_select_light, 1) { return false; }

PREDICATE0(pd_remove_light) { return false; }

PREDICATE0(pd_edit_light) { return false; }

PREDICATE0(pd_load_assets) { return false; }

// ---------------------------------------------------------------------------
//  Scene Overrides
// ---------------------------------------------------------------------------

EditorScene::EditorScene(const std::string& name)
  : Scene(name)
  , m_inputModel("SceneEdit")
  , m_mutex()
  , m_runConsole(true)
  , m_consoleThread([&]() {
	  while(m_runConsole) {
		  std::string command;
		  std::getline(std::cin, command);
		  if(command.at(command.size() - 1) == '\r')
			  command.resize(command.size() - 1);
		  m_mutex.lock();
		  m_commands.emplace(command);
		  m_mutex.unlock();
	  }
	}) {
	// TODO: Editor mode scene loading
	// The scene will load normally first.
	// If the scene file can't be found, we create a new one.
	// If the scene file is corrupt, we give up.
	try {
		m_defaultShader = new Shader("textured.vert.glsl", "textured.frag.glsl");
	} catch(const std::exception& exception) {
		g_logger.write(Logger::LOG_ERROR, exception.what());
	}
}

EditorScene::~EditorScene() {
	m_runConsole = false;
	std::cout << "Press ENTER to quit.\n";
	m_consoleThread.join();
	delete m_defaultShader;
}

// The editor works with the initial moment of a scene.
// We don't want these functions to do anything.
void EditorScene::update(std::chrono::milliseconds) {}
void EditorScene::simulate(std::chrono::milliseconds) {}

// Similarly, we don't want the Actors processing any input.
// Input processing is limited to editor and camera input.
void EditorScene::processInput(GLFWwindow& window) {
	m_inputModel.update(window);
	m_editorCamera.processInput(window);

	// Process command queue
	EditorScene::activeScene = this;
	std::lock_guard<std::mutex> lock(m_mutex);
	while(!m_commands.empty()) {
		std::string command = m_commands.front();
		std::cout << (PlCall("do_command", {{command.c_str()}}) ?
		                "Command Succeeded" :
		                "Command Failed")
		          << "\n";
		m_commands.pop();
	}
	EditorScene::activeScene = nullptr;
}

// The scene should draw as per usual, though.
//void EditorScene::draw() { Scene::draw(); }

void EditorScene::draw() {
	glm::mat4 projectionMatrix =
	  glm::perspective(45.0f,
	                   static_cast<float>(g_renderer.width()) /
	                     static_cast<float>(g_renderer.height()),
	                   0.1f,
	                   10000.0f);
	for(auto actor = m_actors.begin(); actor != m_actors.end(); ++actor) {
		m_defaultShader->setAmbience(m_ambience);

		// Send camera position to the GPU.
		m_defaultShader->setViewMatrix(m_editorCamera.getViewMatrix());
		m_defaultShader->setEyePosition(glm::vec3(m_editorCamera.getPosition()));

		m_defaultShader->setProjectionMatrix(projectionMatrix);
		m_defaultShader->setObjectID(actor->first);
		actor->second->draw(*m_defaultShader);
	}
}

// ---------------------------------------------------------------------------
//  Editor Functionality
// ---------------------------------------------------------------------------

void EditorScene::addActor(const std::string& name) {
	try {
		m_actors.emplace(
		  std::make_pair(++m_highestID, std::make_unique<Actor>(name)));
	} catch(const std::exception& exception) {
		g_logger.write(Logger::LOG_ERROR, exception.what());
		throw std::runtime_error("Failed to load Actor");
	}
}
<commit_msg>Add some ambient light.<commit_after>#include "EditorScene.hpp"

EditorScene* EditorScene::activeScene = nullptr;

// ---------------------------------------------------------------------------
//  Prolog Interface to Scene Editing Commands
// ---------------------------------------------------------------------------
// TODO: Move to appropriate modules

PREDICATE0(pd_save) { return false; }

PREDICATE(pd_saveas, 1) { return false; }

PREDICATE0(pd_exit) { return false; }

PREDICATE(pd_add_actor, 1) {
	try {
		EditorScene::activeScene->addActor(static_cast<const char*>(A1));
	} catch(const std::exception& exception) {
		g_logger.write(Logger::LOG_ERROR, exception.what());
		return false;
	}
	return true;
}

PREDICATE(pd_select, 2) { return false; }

PREDICATE0(pd_deselect) { return false; }

PREDICATE0(pd_remove_actor) { return false; }

PREDICATE(pd_move_by, 3) { return false; }

PREDICATE(pd_move_to, 3) { return false; }

PREDICATE(pd_rotate, 3) { return false; }

PREDICATE0(pd_add_light) { return false; }

PREDICATE(pd_select_light, 1) { return false; }

PREDICATE0(pd_remove_light) { return false; }

PREDICATE0(pd_edit_light) { return false; }

PREDICATE0(pd_load_assets) { return false; }

// ---------------------------------------------------------------------------
//  Scene Overrides
// ---------------------------------------------------------------------------

EditorScene::EditorScene(const std::string& name)
  : Scene(name)
  , m_inputModel("SceneEdit")
  , m_mutex()
  , m_runConsole(true)
  , m_consoleThread([&]() {
	  while(m_runConsole) {
		  std::string command;
		  std::getline(std::cin, command);
		  if(command.at(command.size() - 1) == '\r')
			  command.resize(command.size() - 1);
		  m_mutex.lock();
		  m_commands.emplace(command);
		  m_mutex.unlock();
	  }
	}) {
	// TODO: Editor mode scene loading
	// The scene will load normally first.
	// If the scene file can't be found, we create a new one.
	// If the scene file is corrupt, we give up.
	try {
		m_defaultShader = new Shader("textured.vert.glsl", "textured.frag.glsl");
	} catch(const std::exception& exception) {
		g_logger.write(Logger::LOG_ERROR, exception.what());
	}

	m_ambience = 0.2f;
}

EditorScene::~EditorScene() {
	m_runConsole = false;
	std::cout << "Press ENTER to quit.\n";
	m_consoleThread.join();
	delete m_defaultShader;
}

// The editor works with the initial moment of a scene.
// We don't want these functions to do anything.
void EditorScene::update(std::chrono::milliseconds) {}
void EditorScene::simulate(std::chrono::milliseconds) {}

// Similarly, we don't want the Actors processing any input.
// Input processing is limited to editor and camera input.
void EditorScene::processInput(GLFWwindow& window) {
	m_inputModel.update(window);
	m_editorCamera.processInput(window);

	// Process command queue
	EditorScene::activeScene = this;
	std::lock_guard<std::mutex> lock(m_mutex);
	while(!m_commands.empty()) {
		std::string command = m_commands.front();
		std::cout << (PlCall("do_command", {{command.c_str()}}) ?
		                "Command Succeeded" :
		                "Command Failed")
		          << "\n";
		m_commands.pop();
	}
	EditorScene::activeScene = nullptr;
}

// The scene should draw as per usual, though.
//void EditorScene::draw() { Scene::draw(); }

void EditorScene::draw() {
	glm::mat4 projectionMatrix =
	  glm::perspective(45.0f,
	                   static_cast<float>(g_renderer.width()) /
	                     static_cast<float>(g_renderer.height()),
	                   0.1f,
	                   10000.0f);
	for(auto actor = m_actors.begin(); actor != m_actors.end(); ++actor) {
		m_defaultShader->setAmbience(m_ambience);

		// Send camera position to the GPU.
		m_defaultShader->setViewMatrix(m_editorCamera.getViewMatrix());
		m_defaultShader->setEyePosition(glm::vec3(m_editorCamera.getPosition()));

		m_defaultShader->setProjectionMatrix(projectionMatrix);
		m_defaultShader->setObjectID(actor->first);
		actor->second->draw(*m_defaultShader);
	}
}

// ---------------------------------------------------------------------------
//  Editor Functionality
// ---------------------------------------------------------------------------

void EditorScene::addActor(const std::string& name) {
	try {
		m_actors.emplace(
		  std::make_pair(++m_highestID, std::make_unique<Actor>(name)));
	} catch(const std::exception& exception) {
		g_logger.write(Logger::LOG_ERROR, exception.what());
		throw std::runtime_error("Failed to load Actor");
	}
}
<|endoftext|>


<commit_before>#pragma once

#include "point2d.hpp"
#include "rect2d.hpp"
#include "rect_intersect.hpp"
#include "angles.hpp"
#include "../base/math.hpp"
#include <cmath>

namespace m2
{
  /// axis aligned rect
  template <typename T>
  class AnyRect
  {
    ang::Angle<T> m_angle;

    /// @todo No need to store orthos separately. They are stored in m_angle.
    Point<T> m_i;
    Point<T> m_j;

    Point<T> m_zero;
    Rect<T>  m_rect;

    static Point<T> const Convert(Point<T> const & p,
                                  Point<T> const & fromI, Point<T> const & fromJ,
                                  Point<T> const & toI, Point<T> const & toJ)
    {
      Point<T> res;

      res.x = p.x * DotProduct(fromI, toI) + p.y * DotProduct(fromJ, toI);
      res.y = p.x * DotProduct(fromI, toJ) + p.y * DotProduct(fromJ, toJ);

      return res;
    }

  public:
    AnyRect() : m_i(1, 0), m_j(0, 1), m_zero(0, 0), m_rect() {}

    /// creating from regular rect
    explicit AnyRect(Rect<T> const & r)
      : m_angle(0), m_i(m_angle.cos(), m_angle.sin()), m_j(-m_angle.sin(), m_angle.cos())
    {
      if (r.IsValid())
      {
        m_zero = Point<T>(r.minX(), r.minY());
        m_rect = Rect<T>(0, 0, r.SizeX(), r.SizeY());
      }
      else
      {
        m_zero = Point<T>(0, 0);
        m_rect = r;
      }
    }

    AnyRect(Point<T> const & zero, ang::Angle<T> const & angle, Rect<T> const & r)
      : m_angle(angle), m_i(m_angle.cos(), m_angle.sin()), m_j(-m_angle.sin(), m_angle.cos()),
        m_zero(Convert(zero, Point<T>(1, 0), Point<T>(0, 1), m_i, m_j)),
        m_rect(r)
    {
    }

    Point<T> const & LocalZero() const
    {
      return m_zero;
    }

    Point<T> const GlobalZero() const
    {
      m2::Point<T> i(1, 0);
      m2::Point<T> j(0, 1);
      return Convert(m_zero, m_i, m_j, i, j);
    }

    Point<T> const & i() const
    {
      return m_i;
    }

    Point<T> const & j() const
    {
      return m_j;
    }

    void SetAngle(ang::Angle<T> const & a)
    {
      m2::Point<T> glbZero = GlobalZero();

      m_angle = a;
      m_i = m2::Point<T>(m_angle.cos(), m_angle.sin());
      m_j = m2::Point<T>(-m_angle.sin(), m_angle.cos());

      m_zero = Convert(glbZero, Point<T>(1, 0), Point<T>(0, 1), m_i, m_j);
    }

    ang::Angle<T> const & Angle() const
    {
      return m_angle;
    }

    Point<T> const GlobalCenter() const
    {
      return ConvertFrom(m_rect.Center());
    }

    Point<T> const LocalCenter() const
    {
      return m_rect.Center();
    }

    bool IsPointInside(Point<T> const & pt) const
    {
      return m_rect.IsPointInside(ConvertTo(pt));
    }

    bool IsRectInside(AnyRect<T> const & r) const
    {
      m2::Point<T> pts[4];
      r.GetGlobalPoints(pts);
      ConvertTo(pts, 4);
      return m_rect.IsPointInside(pts[0])
          && m_rect.IsPointInside(pts[1])
          && m_rect.IsPointInside(pts[2])
          && m_rect.IsPointInside(pts[3]);
    }

    bool IsIntersect(AnyRect<T> const & r) const
    {
      m2::Point<T> pts[4];
      if (r.GetLocalRect() == Rect<T>())
        return false;
      r.GetGlobalPoints(pts);
      ConvertTo(pts, 4);

      m2::Rect<T> r1(pts[0], pts[0]);
      r1.Add(pts[1]);
      r1.Add(pts[2]);
      r1.Add(pts[3]);

      if (!GetLocalRect().IsIntersect(r1))
        return false;

      if (r.IsRectInside(*this))
        return true;

      if (IsRectInside(r))
        return true;

      return Intersect(GetLocalRect(), pts[0], pts[1])
          || Intersect(GetLocalRect(), pts[1], pts[2])
          || Intersect(GetLocalRect(), pts[2], pts[3])
          || Intersect(GetLocalRect(), pts[3], pts[0]);
    }

    /// Convert into coordinate system of this AnyRect
    Point<T> const ConvertTo(Point<T> const & p) const
    {
      m2::Point<T> i(1, 0);
      m2::Point<T> j(0, 1);
      return Convert(p - Convert(m_zero, m_i, m_j, i, j), i, j, m_i, m_j);
    }

    void ConvertTo(Point<T> * pts, size_t count) const
    {
      for (size_t i = 0; i < count; ++i)
        pts[i] = ConvertTo(pts[i]);
    }

    /// Convert into global coordinates from the local coordinates of this AnyRect
    Point<T> const ConvertFrom(Point<T> const & p) const
    {
      m2::Point<T> i(1, 0);
      m2::Point<T> j(0, 1);
      return Convert(p + m_zero, m_i, m_j, i, j);
    }

    void ConvertFrom(Point<T> * pts, size_t count) const
    {
      for (size_t i = 0; i < count; ++i)
        pts[i] = ConvertFrom(pts[i]);
    }

    Rect<T> const & GetLocalRect() const
    {
      return m_rect;
    }

    Rect<T> const GetGlobalRect() const
    {
      Point<T> pts[4];
      GetGlobalPoints(pts);

      Rect<T> res(pts[0].x, pts[0].y, pts[0].x, pts[0].y);

      res.Add(pts[1]);
      res.Add(pts[2]);
      res.Add(pts[3]);

      return res;
    }

    void GetGlobalPoints(Point<T> * pts) const
    {
      pts[0] = Point<T>(ConvertFrom(Point<T>(m_rect.minX(), m_rect.minY())));
      pts[1] = Point<T>(ConvertFrom(Point<T>(m_rect.minX(), m_rect.maxY())));
      pts[2] = Point<T>(ConvertFrom(Point<T>(m_rect.maxX(), m_rect.maxY())));
      pts[3] = Point<T>(ConvertFrom(Point<T>(m_rect.maxX(), m_rect.minY())));
    }

    template <typename U>
    void Inflate(U const & dx, U const & dy)
    {
      m_rect.Inflate(dx, dy);
    }

    void Add(AnyRect<T> const & r)
    {
      Point<T> pts[4];
      r.GetGlobalPoints(pts);
      ConvertTo(pts, 4);
      m_rect.Add(pts[0]);
      m_rect.Add(pts[1]);
      m_rect.Add(pts[2]);
      m_rect.Add(pts[3]);
    }

    void Offset(Point<T> const & p)
    {
      m_zero = ConvertTo(ConvertFrom(m_zero) + p);
    }
  };

  template <typename T>
  AnyRect<T> const Offset(AnyRect<T> const & r, Point<T> const & pt)
  {
    AnyRect<T> res(r);
    res.Offset(pt);
    return res;
  }

  template <typename T, typename U>
  AnyRect<T> const Inflate(AnyRect<T> const & r, U const & dx, U const & dy)
  {
    AnyRect<T> res = r;
    res.Inflate(dx, dy);
    return res;
  }

  template <typename T, typename U>
  AnyRect<T> const Inflate(AnyRect<T> const & r, Point<U> const & pt)
  {
    return Inflate(r, pt.x, pt.y);
  }

  typedef AnyRect<double> AnyRectD;
  typedef AnyRect<float> AnyRectF;

  template <typename T>
  inline string DebugPrint(m2::AnyRect<T> const & r)
  {
    return DebugPrint(r.GetGlobalRect());
  }
}
<commit_msg>Minor code fix.<commit_after>#pragma once

#include "point2d.hpp"
#include "rect2d.hpp"
#include "rect_intersect.hpp"
#include "angles.hpp"
#include "../base/math.hpp"
#include <cmath>

namespace m2
{
  /// axis aligned rect
  template <typename T>
  class AnyRect
  {
    ang::Angle<T> m_angle;

    /// @todo No need to store orthos separately. They are stored in m_angle.
    Point<T> m_i;
    Point<T> m_j;

    Point<T> m_zero;
    Rect<T>  m_rect;

    static Point<T> const Convert(Point<T> const & p,
                                  Point<T> const & fromI, Point<T> const & fromJ,
                                  Point<T> const & toI, Point<T> const & toJ)
    {
      Point<T> res;

      res.x = p.x * DotProduct(fromI, toI) + p.y * DotProduct(fromJ, toI);
      res.y = p.x * DotProduct(fromI, toJ) + p.y * DotProduct(fromJ, toJ);

      return res;
    }

  public:
    AnyRect() : m_i(1, 0), m_j(0, 1), m_zero(0, 0), m_rect() {}

    /// creating from regular rect
    explicit AnyRect(Rect<T> const & r)
      : m_angle(0), m_i(m_angle.cos(), m_angle.sin()), m_j(-m_angle.sin(), m_angle.cos())
    {
      if (r.IsValid())
      {
        m_zero = Point<T>(r.minX(), r.minY());
        m_rect = Rect<T>(0, 0, r.SizeX(), r.SizeY());
      }
      else
      {
        m_zero = Point<T>(0, 0);
        m_rect = r;
      }
    }

    AnyRect(Point<T> const & zero, ang::Angle<T> const & angle, Rect<T> const & r)
      : m_angle(angle), m_i(m_angle.cos(), m_angle.sin()), m_j(-m_angle.sin(), m_angle.cos()),
        m_zero(Convert(zero, Point<T>(1, 0), Point<T>(0, 1), m_i, m_j)),
        m_rect(r)
    {
    }

    Point<T> const & LocalZero() const
    {
      return m_zero;
    }

    Point<T> const GlobalZero() const
    {
      m2::Point<T> i(1, 0);
      m2::Point<T> j(0, 1);
      return Convert(m_zero, m_i, m_j, i, j);
    }

    Point<T> const & i() const
    {
      return m_i;
    }

    Point<T> const & j() const
    {
      return m_j;
    }

    void SetAngle(ang::Angle<T> const & a)
    {
      m2::Point<T> glbZero = GlobalZero();

      m_angle = a;
      m_i = m2::Point<T>(m_angle.cos(), m_angle.sin());
      m_j = m2::Point<T>(-m_angle.sin(), m_angle.cos());

      m_zero = Convert(glbZero, Point<T>(1, 0), Point<T>(0, 1), m_i, m_j);
    }

    ang::Angle<T> const & Angle() const
    {
      return m_angle;
    }

    Point<T> const GlobalCenter() const
    {
      return ConvertFrom(m_rect.Center());
    }

    Point<T> const LocalCenter() const
    {
      return m_rect.Center();
    }

    bool IsPointInside(Point<T> const & pt) const
    {
      return m_rect.IsPointInside(ConvertTo(pt));
    }

    bool IsRectInside(AnyRect<T> const & r) const
    {
      m2::Point<T> pts[4];
      r.GetGlobalPoints(pts);
      ConvertTo(pts, 4);
      return m_rect.IsPointInside(pts[0])
          && m_rect.IsPointInside(pts[1])
          && m_rect.IsPointInside(pts[2])
          && m_rect.IsPointInside(pts[3]);
    }

    bool IsIntersect(AnyRect<T> const & r) const
    {
      m2::Point<T> pts[4];
      if (r.GetLocalRect() == Rect<T>())
        return false;
      r.GetGlobalPoints(pts);
      ConvertTo(pts, 4);

      m2::Rect<T> r1(pts[0], pts[0]);
      r1.Add(pts[1]);
      r1.Add(pts[2]);
      r1.Add(pts[3]);

      if (!GetLocalRect().IsIntersect(r1))
        return false;

      if (r.IsRectInside(*this))
        return true;

      if (IsRectInside(r))
        return true;

      return Intersect(GetLocalRect(), pts[0], pts[1])
          || Intersect(GetLocalRect(), pts[1], pts[2])
          || Intersect(GetLocalRect(), pts[2], pts[3])
          || Intersect(GetLocalRect(), pts[3], pts[0]);
    }

    /// Convert into coordinate system of this AnyRect
    Point<T> const ConvertTo(Point<T> const & p) const
    {
      m2::Point<T> i(1, 0);
      m2::Point<T> j(0, 1);
      return Convert(p - Convert(m_zero, m_i, m_j, i, j), i, j, m_i, m_j);
    }

    void ConvertTo(Point<T> * pts, size_t count) const
    {
      for (size_t i = 0; i < count; ++i)
        pts[i] = ConvertTo(pts[i]);
    }

    /// Convert into global coordinates from the local coordinates of this AnyRect
    Point<T> const ConvertFrom(Point<T> const & p) const
    {
      m2::Point<T> i(1, 0);
      m2::Point<T> j(0, 1);
      return Convert(p + m_zero, m_i, m_j, i, j);
    }

    void ConvertFrom(Point<T> * pts, size_t count) const
    {
      for (size_t i = 0; i < count; ++i)
        pts[i] = ConvertFrom(pts[i]);
    }

    Rect<T> const & GetLocalRect() const
    {
      return m_rect;
    }

    Rect<T> const GetGlobalRect() const
    {
      Point<T> pts[4];
      GetGlobalPoints(pts);

      Rect<T> res(pts[0], pts[1]);
      res.Add(pts[2]);
      res.Add(pts[3]);

      return res;
    }

    void GetGlobalPoints(Point<T> * pts) const
    {
      pts[0] = Point<T>(ConvertFrom(Point<T>(m_rect.minX(), m_rect.minY())));
      pts[1] = Point<T>(ConvertFrom(Point<T>(m_rect.minX(), m_rect.maxY())));
      pts[2] = Point<T>(ConvertFrom(Point<T>(m_rect.maxX(), m_rect.maxY())));
      pts[3] = Point<T>(ConvertFrom(Point<T>(m_rect.maxX(), m_rect.minY())));
    }

    template <typename U>
    void Inflate(U const & dx, U const & dy)
    {
      m_rect.Inflate(dx, dy);
    }

    void Add(AnyRect<T> const & r)
    {
      Point<T> pts[4];
      r.GetGlobalPoints(pts);
      ConvertTo(pts, 4);
      m_rect.Add(pts[0]);
      m_rect.Add(pts[1]);
      m_rect.Add(pts[2]);
      m_rect.Add(pts[3]);
    }

    void Offset(Point<T> const & p)
    {
      m_zero = ConvertTo(ConvertFrom(m_zero) + p);
    }
  };

  template <typename T>
  AnyRect<T> const Offset(AnyRect<T> const & r, Point<T> const & pt)
  {
    AnyRect<T> res(r);
    res.Offset(pt);
    return res;
  }

  template <typename T, typename U>
  AnyRect<T> const Inflate(AnyRect<T> const & r, U const & dx, U const & dy)
  {
    AnyRect<T> res = r;
    res.Inflate(dx, dy);
    return res;
  }

  template <typename T, typename U>
  AnyRect<T> const Inflate(AnyRect<T> const & r, Point<U> const & pt)
  {
    return Inflate(r, pt.x, pt.y);
  }

  typedef AnyRect<double> AnyRectD;
  typedef AnyRect<float> AnyRectF;

  template <typename T>
  inline string DebugPrint(m2::AnyRect<T> const & r)
  {
    return DebugPrint(r.GetGlobalRect());
  }
}
<|endoftext|>