<commit_before>
/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee++ — ConfigurationParser
 *
 * This file defines (Const)ConfigurationParser, a wrapper for ib_cfgparser_t,
 * and ConfigurationDirectivesRegistrar, a helper class for attaching
 * directives to an Engine.
 *
 * @remark Developers should be familiar with @ref ironbeepp to understand
 * aspects of this code, e.g., the public/non-virtual inheritance.
 *
 * @sa Engine::register_configuration_directives()
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 */

#ifndef __IBPP__CONFIGURATION_DIRECTIVES__
#define __IBPP__CONFIGURATION_DIRECTIVES__

#include <ironbeepp/common_semantics.hpp>
#include <ironbeepp/list.hpp>
#include <ironbeepp/engine.hpp>

#include <ostream>

#include <boost/function.hpp>

// IronBee C
typedef struct ib_cfgparser_t ib_cfgparser_t;

namespace IronBee {

class MemoryPool;
class Site;
class Location;
class Context;

/**
 * Const ConfigurationParser; equivalent to a const pointer to ib_cfgparser_t.
 *
 * Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for
 * singularity via CommonSemantics.
 *
 * See ConfigurationParser for discussion of configuration_parsers.
 *
 * @tparam T Value type for configuration_parser.
 *
 * @sa ConfigurationParser
 * @sa ironbeepp
 * @sa ib_cfgparser_t
 * @nosubgrouping
 **/
class ConstConfigurationParser :
    public CommonSemantics<ConstConfigurationParser>
{
public:
    //! C Type.
    typedef const ib_cfgparser_t* ib_type;

    /**
     * Construct singular ConstConfigurationParser.
     *
     * All behavior of a singular ConstConfigurationParser is undefined
     * except for assignment, copying, comparison, and evaluate-as-bool.
     **/
    ConstConfigurationParser();

    /**
     * @name C Interoperability
     * Methods to access underlying C types.
     **/
    ///@{

    //! const ib_cfgparser_t accessor.
    // Intentionally inlined.
    ib_type ib() const
    {
        return m_ib;
    }

    //! Construct ConfigurationParser from ib_cfgparser_t.
    explicit
    ConstConfigurationParser(ib_type ib_configuration_parser);

    ///@}

    //! Associated engine.
    Engine engine() const;

    //! Associated memory pool.
    MemoryPool memory_pool() const;

    //! Current configuration context.
    Context current_context() const;

    //! Current configuration site.
    Site current_site() const;

    //! Current configuration location.
    Location current_location() const;

    //! Current configuration block name.
    const char* current_block_name() const;

private:
    ib_type m_ib;
};

/**
 * ConfigurationParser; equivalent to a pointer to ib_cfgparser_t.
 *
 * ConfigurationParser can be treated as ConstConfigurationParser.  See @ref
 * ironbeepp for details on IronBee++ object semantics.
 *
 * At present, ConfigurationParser provides no additional functionality over
 * ConstConfigurationParser except providing a non-const @c ib_cfgparser_t*
 * via ib().
 *
 * @sa ConstConfigurationParser
 * @sa ironbeepp
 * @sa ib_cfgparser_t
 * @nosubgrouping
 **/
class ConfigurationParser :
    public ConstConfigurationParser
{
public:
    //! C Type.
    typedef ib_cfgparser_t* ib_type;

    /**
     * Remove the constness of a ConstConfigurationParser.
     *
     * @warning This is as dangerous as a @c const_cast, use carefully.
     *
     * @param[in] configuration_parser ConstConfigurationParser to remove
     *                                 const from.
     * @returns ConfigurationParser pointing to same underlying
     *          configuration_parser as @a configuration_parser.
     **/
    static ConfigurationParser remove_const(
         ConstConfigurationParser configuration_parser
    );

    /**
     * Construct singular ConfigurationParser.
     *
     * All behavior of a singular ConfigurationParser is undefined except for
     * assignment, copying, comparison, and evaluate-as-bool.
     **/
    ConfigurationParser();

    /**
     * @name C Interoperability
     * Methods to access underlying C types.
     **/
    ///@{

    //! ib_cfgparser_t accessor.
    ib_type ib() const
    {
        return m_ib;
    }

    //! Construct ConfigurationParser from ib_cfgparser_t.
    explicit
    ConfigurationParser(ib_type ib_configuration_parser);

    ///@}

private:
    ib_type m_ib;
};

/**
 * Output operator for ConfigurationParser.
 *
 * Outputs ConfigurationParser[@e value] where value is the current location
 * and current block name separated by :.
 *
 * @param[in] o Ostream to output to.
 * @param[in] configuration_parser ConfigurationParser to output.
 * @return @a o
 **/
std::ostream& operator<<(
    std::ostream& o,
    const ConstConfigurationParser& configuration_parser
);

/**
 * Helper class for Engine::register_configuration_directives().
 *
 * This class is returned by Engine::register_configuration_directives() and
 * provides methods to easily register multiple configuration directives.
 *
 * Example:
 * @code
 * engine.register_configuration_directives()
 *       .param1("FirstConfig", some_functional())
 *       .param2("SecondConfig", &some_function)
 *       ;
 * @endcode
 **/
class ConfigurationDirectivesRegistrar
{
public:
    //! Constructor.  Use Engine::register_configuration_directives() instead.
    explicit
    ConfigurationDirectivesRegistrar(Engine engine);

    /**
     * Start block handler.
     *
     * Takes configuration parser, directive name, and block parameter.
     **/
    typedef boost::function<void(
        ConfigurationParser,
        const char*,
        const char*
    )> start_block_t;

    /**
     * End block handler.
     *
     * Takes configuration parser and directive name.
     **/
    typedef boost::function<void(
        ConfigurationParser,
        const char*
    )> end_block_t;

    /**
     * Register block directive.
     *
     * @param[in] name           Name of directive.
     * @param[in] start_function Function to call at start of block.
     * @param[in] end_function   Function to call at end of block.
     * @returns *this
     **/
    ConfigurationDirectivesRegistrar& block(
        const char*   name,
        start_block_t start_function,
        end_block_t   end_function
    );

    /**
     * On-off handler.
     *
     * Takes configuration parser, directive name, and whether on or off.
     **/
    typedef boost::function<void(
        ConfigurationParser,
        const char*,
        bool
    )> on_off_t;

     /**
      * Register on-off directive.
      *
      * @param[in] name     Name of directive.
      * @param[in] function Function to call when directive given.
      * @returns *this
      **/
    ConfigurationDirectivesRegistrar& on_off(
        const char* name,
        on_off_t    function
    );

    /**
     * Single parameter handler.
     *
     * Takes configuration parser, directive name, and parameter.
     **/
    typedef boost::function<void(
        ConfigurationParser,
        const char*,
        const char*
    )> param1_t;

    /**
     * Register single parameter directive.
     *
     * @param[in] name     Name of directive.
     * @param[in] function Function to call when directive given.
     * @returns *this
     **/
    ConfigurationDirectivesRegistrar& param1(
        const char* name,
        param1_t    function
    );

    /**
     * Two parameter handler.
     *
     * Takes configuration parser, directive name, and two parameters.
     **/
    typedef boost::function<void(
        ConfigurationParser,
        const char*,
        const char*,
        const char*
    )> param2_t;

    /**
     * Register two parameter directive.
     *
     * @param[in] name     Name of directive.
     * @param[in] function Function to call when directive given.
     * @returns *this
     **/
    ConfigurationDirectivesRegistrar& param2(
        const char* name,
        param2_t    function
    );

     /**
      * Register many parameter directive.
      *
      * Takes configuration parameter, directive name, and list of parameters.
      **/
    typedef boost::function<void(
        ConfigurationParser,
        const char*,
        List<const char*>
    )> list_t;

     /**
      * Register many parameter directive.
      *
      * @param[in] name     Name of directive.
      * @param[in] function Function to call when directive given.
      * @returns *this
      **/
    ConfigurationDirectivesRegistrar& list(
        const char* name,
        list_t      function
    );

    /**
     * Opflag handler.
     *
     * Takes configuration parser, directive name, value of flags, and a mask
     * indicating which flags where set.  I.e., if bit N in the mask is set,
     * then that flag was changed to bit N of the value.
     **/
    typedef boost::function<void(
        ConfigurationParser,
        const char*,
        uint32_t,
        uint32_t
    )> op_flags_t;

    /**
     * Register op flags parameter directive.
     *
     * Consider boost::assign for easy construction of @a value_map.
     *
     * @param[in] name      Name of directive.
     * @param[in] function  Function to call when directive given.
     * @param[in] value_map Map of flag name to bit index.
     * @returns *this
     **/
    ConfigurationDirectivesRegistrar& op_flags(
        const char*                    name,
        op_flags_t                     function,
        std::map<std::string, int64_t> value_map
    );

private:
    Engine m_engine;
};

} // IronBee

#endif
<commit_msg>IronBee++/ConfigurationDirectives: Improve API doc for OpFlags.<commit_after>
/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee++ — ConfigurationParser
 *
 * This file defines (Const)ConfigurationParser, a wrapper for ib_cfgparser_t,
 * and ConfigurationDirectivesRegistrar, a helper class for attaching
 * directives to an Engine.
 *
 * @remark Developers should be familiar with @ref ironbeepp to understand
 * aspects of this code, e.g., the public/non-virtual inheritance.
 *
 * @sa Engine::register_configuration_directives()
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 */

#ifndef __IBPP__CONFIGURATION_DIRECTIVES__
#define __IBPP__CONFIGURATION_DIRECTIVES__

#include <ironbeepp/common_semantics.hpp>
#include <ironbeepp/list.hpp>
#include <ironbeepp/engine.hpp>

#include <ostream>

#include <boost/function.hpp>

// IronBee C
typedef struct ib_cfgparser_t ib_cfgparser_t;

namespace IronBee {

class MemoryPool;
class Site;
class Location;
class Context;

/**
 * Const ConfigurationParser; equivalent to a const pointer to ib_cfgparser_t.
 *
 * Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for
 * singularity via CommonSemantics.
 *
 * See ConfigurationParser for discussion of configuration_parsers.
 *
 * @tparam T Value type for configuration_parser.
 *
 * @sa ConfigurationParser
 * @sa ironbeepp
 * @sa ib_cfgparser_t
 * @nosubgrouping
 **/
class ConstConfigurationParser :
    public CommonSemantics<ConstConfigurationParser>
{
public:
    //! C Type.
    typedef const ib_cfgparser_t* ib_type;

    /**
     * Construct singular ConstConfigurationParser.
     *
     * All behavior of a singular ConstConfigurationParser is undefined
     * except for assignment, copying, comparison, and evaluate-as-bool.
     **/
    ConstConfigurationParser();

    /**
     * @name C Interoperability
     * Methods to access underlying C types.
     **/
    ///@{

    //! const ib_cfgparser_t accessor.
    // Intentionally inlined.
    ib_type ib() const
    {
        return m_ib;
    }

    //! Construct ConfigurationParser from ib_cfgparser_t.
    explicit
    ConstConfigurationParser(ib_type ib_configuration_parser);

    ///@}

    //! Associated engine.
    Engine engine() const;

    //! Associated memory pool.
    MemoryPool memory_pool() const;

    //! Current configuration context.
    Context current_context() const;

    //! Current configuration site.
    Site current_site() const;

    //! Current configuration location.
    Location current_location() const;

    //! Current configuration block name.
    const char* current_block_name() const;

private:
    ib_type m_ib;
};

/**
 * ConfigurationParser; equivalent to a pointer to ib_cfgparser_t.
 *
 * ConfigurationParser can be treated as ConstConfigurationParser.  See @ref
 * ironbeepp for details on IronBee++ object semantics.
 *
 * At present, ConfigurationParser provides no additional functionality over
 * ConstConfigurationParser except providing a non-const @c ib_cfgparser_t*
 * via ib().
 *
 * @sa ConstConfigurationParser
 * @sa ironbeepp
 * @sa ib_cfgparser_t
 * @nosubgrouping
 **/
class ConfigurationParser :
    public ConstConfigurationParser
{
public:
    //! C Type.
    typedef ib_cfgparser_t* ib_type;

    /**
     * Remove the constness of a ConstConfigurationParser.
     *
     * @warning This is as dangerous as a @c const_cast, use carefully.
     *
     * @param[in] configuration_parser ConstConfigurationParser to remove
     *                                 const from.
     * @returns ConfigurationParser pointing to same underlying
     *          configuration_parser as @a configuration_parser.
     **/
    static ConfigurationParser remove_const(
         ConstConfigurationParser configuration_parser
    );

    /**
     * Construct singular ConfigurationParser.
     *
     * All behavior of a singular ConfigurationParser is undefined except for
     * assignment, copying, comparison, and evaluate-as-bool.
     **/
    ConfigurationParser();

    /**
     * @name C Interoperability
     * Methods to access underlying C types.
     **/
    ///@{

    //! ib_cfgparser_t accessor.
    ib_type ib() const
    {
        return m_ib;
    }

    //! Construct ConfigurationParser from ib_cfgparser_t.
    explicit
    ConfigurationParser(ib_type ib_configuration_parser);

    ///@}

private:
    ib_type m_ib;
};

/**
 * Output operator for ConfigurationParser.
 *
 * Outputs ConfigurationParser[@e value] where value is the current location
 * and current block name separated by :.
 *
 * @param[in] o Ostream to output to.
 * @param[in] configuration_parser ConfigurationParser to output.
 * @return @a o
 **/
std::ostream& operator<<(
    std::ostream& o,
    const ConstConfigurationParser& configuration_parser
);

/**
 * Helper class for Engine::register_configuration_directives().
 *
 * This class is returned by Engine::register_configuration_directives() and
 * provides methods to easily register multiple configuration directives.
 *
 * Example:
 * @code
 * engine.register_configuration_directives()
 *       .param1("FirstConfig", some_functional())
 *       .param2("SecondConfig", &some_function)
 *       ;
 * @endcode
 **/
class ConfigurationDirectivesRegistrar
{
public:
    //! Constructor.  Use Engine::register_configuration_directives() instead.
    explicit
    ConfigurationDirectivesRegistrar(Engine engine);

    /**
     * Start block handler.
     *
     * Takes configuration parser, directive name, and block parameter.
     **/
    typedef boost::function<void(
        ConfigurationParser,
        const char*,
        const char*
    )> start_block_t;

    /**
     * End block handler.
     *
     * Takes configuration parser and directive name.
     **/
    typedef boost::function<void(
        ConfigurationParser,
        const char*
    )> end_block_t;

    /**
     * Register block directive.
     *
     * @param[in] name           Name of directive.
     * @param[in] start_function Function to call at start of block.
     * @param[in] end_function   Function to call at end of block.
     * @returns *this
     **/
    ConfigurationDirectivesRegistrar& block(
        const char*   name,
        start_block_t start_function,
        end_block_t   end_function
    );

    /**
     * On-off handler.
     *
     * Takes configuration parser, directive name, and whether on or off.
     **/
    typedef boost::function<void(
        ConfigurationParser,
        const char*,
        bool
    )> on_off_t;

     /**
      * Register on-off directive.
      *
      * @param[in] name     Name of directive.
      * @param[in] function Function to call when directive given.
      * @returns *this
      **/
    ConfigurationDirectivesRegistrar& on_off(
        const char* name,
        on_off_t    function
    );

    /**
     * Single parameter handler.
     *
     * Takes configuration parser, directive name, and parameter.
     **/
    typedef boost::function<void(
        ConfigurationParser,
        const char*,
        const char*
    )> param1_t;

    /**
     * Register single parameter directive.
     *
     * @param[in] name     Name of directive.
     * @param[in] function Function to call when directive given.
     * @returns *this
     **/
    ConfigurationDirectivesRegistrar& param1(
        const char* name,
        param1_t    function
    );

    /**
     * Two parameter handler.
     *
     * Takes configuration parser, directive name, and two parameters.
     **/
    typedef boost::function<void(
        ConfigurationParser,
        const char*,
        const char*,
        const char*
    )> param2_t;

    /**
     * Register two parameter directive.
     *
     * @param[in] name     Name of directive.
     * @param[in] function Function to call when directive given.
     * @returns *this
     **/
    ConfigurationDirectivesRegistrar& param2(
        const char* name,
        param2_t    function
    );

     /**
      * Register many parameter directive.
      *
      * Takes configuration parameter, directive name, and list of parameters.
      **/
    typedef boost::function<void(
        ConfigurationParser,
        const char*,
        List<const char*>
    )> list_t;

     /**
      * Register many parameter directive.
      *
      * @param[in] name     Name of directive.
      * @param[in] function Function to call when directive given.
      * @returns *this
      **/
    ConfigurationDirectivesRegistrar& list(
        const char* name,
        list_t      function
    );

    /**
     * Opflag handler.
     *
     * Takes configuration parser, directive name, value of flags, and a mask
     * indicating which flags where set.  I.e., if bit N in the mask is set,
     * then that flag was changed to bit N of the value.
     **/
    typedef boost::function<void(
        ConfigurationParser,
        const char*,
        uint32_t,
        uint32_t
    )> op_flags_t;

    /**
     * Register op flags parameter directive.
     *
     * Consider boost::assign for easy construction of @a value_map.
     *
     * @param[in] name      Name of directive.
     * @param[in] function  Function to call when directive given.
     * @param[in] value_map Map of flag name to flag bits.  If a flag name
     *                      is specified in the configuration, the bits in
     *                      its value are set to 1 in the mask and either
     *                      set to 1 or 0 in the value, depending on the
     *                      operation.
     * @returns *this
     **/
    ConfigurationDirectivesRegistrar& op_flags(
        const char*                    name,
        op_flags_t                     function,
        std::map<std::string, int64_t> value_map
    );

private:
    Engine m_engine;
};

} // IronBee

#endif
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
#define MAPNIK_GEOMETRY_WKT_GENERATOR_HPP

// mapnik
#include <mapnik/global.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/vertex.hpp>    // for CommandType::SEG_MOVETO

// boost
#include <boost/tuple/tuple.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_statement.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/type_traits/remove_pointer.hpp>
#include <boost/math/special_functions/trunc.hpp> // for vc++ and android whose c++11 libs lack std::trunct

namespace boost { namespace spirit { namespace traits {

// make gcc and darwin toolsets happy.
template <>
struct is_container<mapnik::geometry_container>
    : mpl::false_
{};

}}}

namespace mapnik { namespace util {

namespace karma = boost::spirit::karma;
namespace phoenix = boost::phoenix;

namespace detail {

template <typename Geometry>
struct get_type
{
    template <typename T>
    struct result { typedef int type; };

    int operator() (Geometry const& geom) const
    {
        return static_cast<int>(geom.type());
    }
};

template <typename T>
struct get_first
{
    typedef T geometry_type;

    template <typename U>
    struct result { typedef typename geometry_type::value_type const type; };

    typename geometry_type::value_type const operator() (geometry_type const& geom) const
    {
        typename geometry_type::value_type coord;
        geom.rewind(0);
        std::get<0>(coord) = geom.vertex(&std::get<1>(coord),&std::get<2>(coord));
        return coord;
    }
};

template <typename T>
struct multi_geometry_
{
    typedef T geometry_container;

    template <typename U>
    struct result { typedef bool type; };
    bool operator() (geometry_container const& geom) const
    {
        return geom.size() > 1 ? true : false;
    }
};

template <typename T>
struct get_x
{
    typedef T value_type;

    template <typename U>
    struct result { typedef double type; };

    double operator() (value_type const& val) const
    {
        return std::get<1>(val);
    }
};

template <typename T>
struct get_y
{
    typedef T value_type;

    template <typename U>
    struct result { typedef double type; };

    double operator() (value_type const& val) const
    {
        return std::get<2>(val);
    }
};

template <typename T>
struct multi_geometry_type
{
    typedef T geometry_container;

    template <typename U>
    struct result { typedef std::tuple<unsigned,bool> type; };

    std::tuple<unsigned,bool> operator() (geometry_container const& geom) const;
};

template <typename T>
struct wkt_coordinate_policy : karma::real_policies<T>
{
    typedef boost::spirit::karma::real_policies<T> base_type;
    static int floatfield(T n) { return base_type::fmtflags::fixed; }
    static unsigned precision(T n)
    {
        if (n == 0.0) return 0;
        using namespace boost::spirit;
        return static_cast<unsigned>(14 - boost::math::trunc(log10(traits::get_absolute_value(n))));
    }

    template <typename OutputIterator>
    static bool dot(OutputIterator& sink, T n, unsigned precision)
    {
        if (n == 0) return true;
        return base_type::dot(sink, n, precision);
    }

    template <typename OutputIterator>
    static bool fraction_part(OutputIterator& sink, T n
                       , unsigned adjprec, unsigned precision)
    {
        if (n == 0) return true;
        return base_type::fraction_part(sink, n, adjprec, precision);
    }
};

}

template <typename OutputIterator, typename Geometry>
struct wkt_generator :
    karma::grammar<OutputIterator, Geometry const& ()>
{
    typedef Geometry geometry_type;
    typedef typename boost::remove_pointer<typename geometry_type::value_type>::type coord_type;

    wkt_generator(bool single = false);
    // rules
    karma::rule<OutputIterator, geometry_type const& ()> wkt;
    karma::rule<OutputIterator, geometry_type const& ()> point;
    karma::rule<OutputIterator, geometry_type const& ()> linestring;
    karma::rule<OutputIterator, geometry_type const& ()> polygon;

    karma::rule<OutputIterator, geometry_type const& ()> coords;
    karma::rule<OutputIterator, karma::locals<unsigned,double,double>, geometry_type const& ()> coords2;
    karma::rule<OutputIterator, coord_type ()> point_coord;
    karma::rule<OutputIterator, karma::locals<double,double>, coord_type (unsigned&, double&, double& )> polygon_coord;

    // phoenix functions
    phoenix::function<detail::get_type<geometry_type> > _type;
    phoenix::function<detail::get_first<geometry_type> > _first;
    phoenix::function<detail::get_x<typename geometry_type::value_type> > _x;
    phoenix::function<detail::get_y<typename geometry_type::value_type> > _y;
    //
    karma::real_generator<double, detail::wkt_coordinate_policy<double> > coordinate;
};

template <typename OutputIterator, typename GeometryContainer>
struct wkt_multi_generator :
        karma::grammar<OutputIterator, karma::locals< std::tuple<unsigned,bool> >, GeometryContainer const& ()>
{
    typedef GeometryContainer geometry_contaner;
    typedef boost::remove_pointer<typename geometry_container::value_type>::type geometry_type;

    wkt_multi_generator();
    // rules
    karma::rule<OutputIterator, karma::locals<std::tuple<unsigned,bool> >, GeometryContainer const& ()> wkt;
    karma::rule<OutputIterator, GeometryContainer const& ()> geometry;
    karma::rule<OutputIterator, geometry_type const& ()> single_geometry;
    karma::rule<OutputIterator, GeometryContainer const& ()> multi_geometry;
    wkt_generator<OutputIterator, geometry_type >  path;
    // phoenix
    phoenix::function<detail::multi_geometry_<GeometryContainer> > is_multi;
    phoenix::function<detail::multi_geometry_type<GeometryContainer> > _multi_type;
    phoenix::function<detail::get_type<geometry_type> > _type;
    //
    karma::symbols<unsigned, char const*> geometry_types;
};

}}

#endif // MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
<commit_msg>fix wkt_multi_generator typedef - previously accidentally matched mapnik::geometry_container - bug spotted by @mojodna - refs #2098<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
#define MAPNIK_GEOMETRY_WKT_GENERATOR_HPP

// mapnik
#include <mapnik/global.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/vertex.hpp>    // for CommandType::SEG_MOVETO

// boost
#include <boost/tuple/tuple.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_statement.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/type_traits/remove_pointer.hpp>
#include <boost/math/special_functions/trunc.hpp> // for vc++ and android whose c++11 libs lack std::trunct

namespace boost { namespace spirit { namespace traits {

// make gcc and darwin toolsets happy.
template <>
struct is_container<mapnik::geometry_container>
    : mpl::false_
{};

}}}

namespace mapnik { namespace util {

namespace karma = boost::spirit::karma;
namespace phoenix = boost::phoenix;

namespace detail {

template <typename Geometry>
struct get_type
{
    template <typename T>
    struct result { typedef int type; };

    int operator() (Geometry const& geom) const
    {
        return static_cast<int>(geom.type());
    }
};

template <typename T>
struct get_first
{
    typedef T geometry_type;

    template <typename U>
    struct result { typedef typename geometry_type::value_type const type; };

    typename geometry_type::value_type const operator() (geometry_type const& geom) const
    {
        typename geometry_type::value_type coord;
        geom.rewind(0);
        std::get<0>(coord) = geom.vertex(&std::get<1>(coord),&std::get<2>(coord));
        return coord;
    }
};

template <typename T>
struct multi_geometry_
{
    typedef T geometry_container;

    template <typename U>
    struct result { typedef bool type; };
    bool operator() (geometry_container const& geom) const
    {
        return geom.size() > 1 ? true : false;
    }
};

template <typename T>
struct get_x
{
    typedef T value_type;

    template <typename U>
    struct result { typedef double type; };

    double operator() (value_type const& val) const
    {
        return std::get<1>(val);
    }
};

template <typename T>
struct get_y
{
    typedef T value_type;

    template <typename U>
    struct result { typedef double type; };

    double operator() (value_type const& val) const
    {
        return std::get<2>(val);
    }
};

template <typename T>
struct multi_geometry_type
{
    typedef T geometry_container;

    template <typename U>
    struct result { typedef std::tuple<unsigned,bool> type; };

    std::tuple<unsigned,bool> operator() (geometry_container const& geom) const;
};

template <typename T>
struct wkt_coordinate_policy : karma::real_policies<T>
{
    typedef boost::spirit::karma::real_policies<T> base_type;
    static int floatfield(T n) { return base_type::fmtflags::fixed; }
    static unsigned precision(T n)
    {
        if (n == 0.0) return 0;
        using namespace boost::spirit;
        return static_cast<unsigned>(14 - boost::math::trunc(log10(traits::get_absolute_value(n))));
    }

    template <typename OutputIterator>
    static bool dot(OutputIterator& sink, T n, unsigned precision)
    {
        if (n == 0) return true;
        return base_type::dot(sink, n, precision);
    }

    template <typename OutputIterator>
    static bool fraction_part(OutputIterator& sink, T n
                       , unsigned adjprec, unsigned precision)
    {
        if (n == 0) return true;
        return base_type::fraction_part(sink, n, adjprec, precision);
    }
};

}

template <typename OutputIterator, typename Geometry>
struct wkt_generator :
    karma::grammar<OutputIterator, Geometry const& ()>
{
    typedef Geometry geometry_type;
    typedef typename boost::remove_pointer<typename geometry_type::value_type>::type coord_type;

    wkt_generator(bool single = false);
    // rules
    karma::rule<OutputIterator, geometry_type const& ()> wkt;
    karma::rule<OutputIterator, geometry_type const& ()> point;
    karma::rule<OutputIterator, geometry_type const& ()> linestring;
    karma::rule<OutputIterator, geometry_type const& ()> polygon;

    karma::rule<OutputIterator, geometry_type const& ()> coords;
    karma::rule<OutputIterator, karma::locals<unsigned,double,double>, geometry_type const& ()> coords2;
    karma::rule<OutputIterator, coord_type ()> point_coord;
    karma::rule<OutputIterator, karma::locals<double,double>, coord_type (unsigned&, double&, double& )> polygon_coord;

    // phoenix functions
    phoenix::function<detail::get_type<geometry_type> > _type;
    phoenix::function<detail::get_first<geometry_type> > _first;
    phoenix::function<detail::get_x<typename geometry_type::value_type> > _x;
    phoenix::function<detail::get_y<typename geometry_type::value_type> > _y;
    //
    karma::real_generator<double, detail::wkt_coordinate_policy<double> > coordinate;
};

template <typename OutputIterator, typename GeometryContainer>
struct wkt_multi_generator :
        karma::grammar<OutputIterator, karma::locals< std::tuple<unsigned,bool> >, GeometryContainer const& ()>
{
    typedef typename boost::remove_pointer<typename GeometryContainer::value_type>::type geometry_type;

    wkt_multi_generator();
    // rules
    karma::rule<OutputIterator, karma::locals<std::tuple<unsigned,bool> >, GeometryContainer const& ()> wkt;
    karma::rule<OutputIterator, GeometryContainer const& ()> geometry;
    karma::rule<OutputIterator, geometry_type const& ()> single_geometry;
    karma::rule<OutputIterator, GeometryContainer const& ()> multi_geometry;
    wkt_generator<OutputIterator, geometry_type >  path;
    // phoenix
    phoenix::function<detail::multi_geometry_<GeometryContainer> > is_multi;
    phoenix::function<detail::multi_geometry_type<GeometryContainer> > _multi_type;
    phoenix::function<detail::get_type<geometry_type> > _type;
    //
    karma::symbols<unsigned, char const*> geometry_types;
};

}}

#endif // MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
<|endoftext|>


<commit_before>//============================================================================
// include/vsmc/rng/uniform_real_distribution.hpp
//----------------------------------------------------------------------------
//
//                         vSMC: Scalable Monte Carlo
//
// This file is distribured under the 2-clauses BSD License.
// See LICENSE for details.
//============================================================================

#ifndef VSMC_UNIFORM_REAL_DISTRIBUTION_HPP
#define VSMC_UNIFORM_REAL_DISTRIBUTION_HPP

#include <vsmc/rng/internal/common.hpp>
#include <vsmc/rng/u01.h>

#define VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUITON_PARAM_CHECK(a, b) \
    VSMC_RUNTIME_ASSERT((a <= b),                                            \
            ("**UniformRealDistribution** CONSTRUCTED WITH INVALID "         \
             "MINIMUM AND MAXIMUM PARAMTER VALUES"))

#define VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN(eng_min) \
    VSMC_RUNTIME_ASSERT((eng_min == 0),                                      \
            ("**UniformRealDistribution::operator()** "                      \
             "ENGINE MEMBER FUNCTION min() RETURN A VALUE OTHER THAN ZERO"))

#define VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX(eng_max) \
    VSMC_RUNTIME_ASSERT((eng_max == uint32_t_max_ || eng_max == uint64_t_max_),\
            ("**UniformRealDistribution::operator()** "                      \
             "ENGINE MEMBER FUNCTION max() RETURN A VALUE OTHER THAN "       \
             "THE MAXIMUM OF uint32_t OR uint64_t"))

namespace vsmc {

namespace internal {

template<uint64_t, uint64_t> struct UniformRealDistributionFullRangeIntgerType;

template<>
struct UniformRealDistributionFullRangeIntgerType<0,
    static_cast<uint64_t>(static_cast<uint32_t>(~(static_cast<uint32_t>(0))))>
{typedef uint32_t type;};

template<>
struct UniformRealDistributionFullRangeIntgerType<0,
    static_cast<uint64_t>(~(static_cast<uint64_t>(0)))>
{typedef uint64_t type;};

} // namespace vsmc::interal

/// \brief Parameter type for open interval
/// \ingroup RNG
struct Open {};

/// \brief Parameter type for closed interval
/// \ingroup RNG
struct Closed {};

/// \brief Uniform real distribution with variants open/closed variants
/// \ingroup RNG
///
/// \details
/// This distribution is almost identical to C++11
/// `std::uniform_real_distribution`. But it differs in two important aspects
/// - It allows the interval to be either open or closed on both sides.
/// - It requires that the uniform random number generator to produce integers
///   on the full range of either `uint32_t` or `uint64_t`.
template <typename FPType, typename Left, typename Right>
class UniformRealDistribution
{
    private :

    typedef cxx11::integral_constant<std::size_t, sizeof(float)> f24;
    typedef cxx11::integral_constant<std::size_t, sizeof(double)> f53;
    typedef cxx11::integral_constant<std::size_t, sizeof(uint32_t)> u32;
    typedef cxx11::integral_constant<std::size_t, sizeof(uint64_t)> u64;

    public :

    typedef FPType result_type;

    class param_type
    {
        public :

        typedef FPType result_type;

        typedef UniformRealDistribution<FPType, Left, Right> distribution_type;

        explicit param_type (result_type a = 0, result_type b = 1) :
            a_(a), b_(b) {}

        result_type a () const {return a_;}
        result_type b () const {return b_;}

        friend inline bool operator== (
                const param_type &param1, const param_type &param2)
        {
            if (param1.a_ < param2.a_ || param1.a_ > param2.a_)
                return false;
            if (param1.b_ < param2.b_ || param1.b_ > param2.b_)
                return false;
            return true;
        }

        friend inline bool operator!= (
                const param_type param1, const param_type param2)
        {return !(param1 == param2);}

        template <typename CharT, typename Traits>
        friend inline std::basic_ostream<CharT, Traits> &operator<< (
                std::basic_ostream<CharT, Traits> &os, const param_type &param)
        {
            if (!os.good())
                return os;

            os << param.a_ << ' ' << param.b_;

            return os;
        }

        template <typename CharT, typename Traits>
        friend inline std::basic_istream<CharT, Traits> &operator>> (
                std::basic_istream<CharT, Traits> &is, param_type &param)
        {
            if (!is.good())
                return is;

            result_type a = 1;
            result_type b = 0;
            is >> std::ws >> a;
            is >> std::ws >> b;

            if (is.good()) {
                if (a <= b) {
                    param.a_ = a;
                    param.b_ = b;
                } else {
                    is.setstate(std::ios_base::failbit);
                }
            }

            return is;
        }

        private :

        result_type a_;
        result_type b_;
    }; // class param_type

    explicit UniformRealDistribution (result_type a = 0, result_type b = 1) :
        a_(a), b_(b)
    {VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUITON_PARAM_CHECK(a_, b_);}

    UniformRealDistribution (const param_type &param) :
        a_(param.a()), b_(param.b())
    {VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUITON_PARAM_CHECK(a_, b_);}

    param_type param () const {return param_type(a_, b_);}

    void param (const param_type &param)
    {
        a_ = param.a();
        b_ = param.b();
    }

    void reset () const {}

    result_type a () const {return a_;}
    result_type b () const {return b_;}
    result_type min VSMC_MNE () const {return a_;}
    result_type max VSMC_MNE () const {return b_;}

    /// \brief Generate uniform random variates
    ///
    /// \tparam Eng Requirement:
    /// ~~~{.cpp}
    /// Eng::min() == 0 && (
    /// Eng::max() == std::numeric_limits<uint32_t>::max() ||
    /// Eng::max() == std::numeric_limits<uint64_t>::max()
    /// )
    /// ~~~
    template <typename Eng>
    result_type operator() (Eng &eng)
    {
#if VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX
	operator()(eng, cxx11::true_type());
#else
	operator()(eng, cxx11::false_type());
#endif
    }

    /// \brief static dispatch based on `Eng::min()` and `Eng::max()`, both
    /// need to be constant expression
    template <typename Eng>
    result_type operator() (Eng &eng, cxx11::true_type) const
    {
        typedef cxx11::integral_constant<std::size_t, sizeof(result_type)>
            fbits;
        typedef typename internal::UniformRealDistributionFullRangeIntgerType<
            Eng::min VSMC_MNE (), Eng::max VSMC_MNE ()>::type eng_uint_t;
        typedef cxx11::integral_constant<std::size_t, sizeof(eng_uint_t)>
            ubits;

        result_type u = u01(static_cast<eng_uint_t>(eng()), Left(), Right(),
                ubits(), fbits());

        return u * (b_ - a_) + a_;
    }

    /// \brief Dynamic dispatch based on `eng.min()` and `eng.max()`
    template <typename Eng>
    result_type operator() (Eng &eng, cxx11::false_type) const
    {
        typedef cxx11::integral_constant<std::size_t, sizeof(result_type)>
            fbits;

        static const uint64_t eng_max = static_cast<uint64_t>(
                eng.max VSMC_MNE ());

        VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN(
                (eng.min VSMC_MNE ()));
        VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX(eng_max);

        result_type u = 0;
        switch (eng_max) {
            case uint32_t_max_ :
                u = u01(static_cast<uint32_t>(eng()), Left(), Right(),
                        u32(), fbits());
                break;
            case uint64_t_max_ :
                u = u01(static_cast<uint64_t>(eng()), Left(), Right(),
                        u64(), fbits());
                break;
            default :
                return 0;
        }

        return u * (b_ - a_) + a_;
    }

    friend inline bool operator== (
            const UniformRealDistribution<FPType, Left, Right> &runif1,
            const UniformRealDistribution<FPType, Left, Right> &runif2)
    {
        if (runif1.a_ < runif2.a_ ||runif1.a_ > runif1.a_)
            return false;
        if (runif1.b_ < runif2.b_ ||runif1.b_ > runif1.b_)
            return false;
        return true;
    }

    friend inline bool operator!= (
            const UniformRealDistribution<FPType, Left, Right> &runif1,
            const UniformRealDistribution<FPType, Left, Right> &runif2)
    {return !(runif1 == runif2);}

    template <typename CharT, typename Traits>
    friend inline std::basic_ostream<CharT, Traits> &operator<< (
            std::basic_ostream<CharT, Traits> &os,
            const UniformRealDistribution<FPType, Left, Right> &runif)
    {
        if (!os.good())
            return os;

        os << runif.a_ << ' ' << runif.b_;

        return os;
    }

    template <typename CharT, typename Traits>
    friend inline std::basic_istream<CharT, Traits> &operator>> (
            std::basic_istream<CharT, Traits> &is,
            UniformRealDistribution<FPType, Left, Right> &runif)
    {
        if (!is.good())
            return is;

        result_type a = 1;
        result_type b = 0;
        is >> std::ws >> a;
        is >> std::ws >> b;
        if (is.good()) {
            if (a <= b) {
                runif.a_ = a;
                runif.b_ = b;
            } else {
                is.setstate(std::ios_base::failbit);
            }
        }

        return is;
    }

    private :

    result_type a_;
    result_type b_;

#if !VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX
    static VSMC_CONSTEXPR const uint64_t uint32_t_max_ = static_cast<uint64_t>(
            static_cast<uint32_t>(~(static_cast<uint32_t>(0))));
    static VSMC_CONSTEXPR const uint64_t uint64_t_max_ = static_cast<uint64_t>(
            ~(static_cast<uint64_t>(0)));
#endif

    static float u01(uint32_t i, Open, Open, u32, f24)
    {return ::u01_open_open_32_24(i);}

    static float u01(uint32_t i, Open, Closed, u32, f24)
    {return ::u01_open_closed_32_24(i);}

    static float u01(uint32_t i, Closed, Open, u32, f24)
    {return ::u01_closed_open_32_24(i);}

    static float u01(uint32_t i, Closed, Closed, u32, f24)
    {return ::u01_closed_closed_32_24(i);}

    static double u01(uint32_t i, Open, Open, u32, f53)
    {return ::u01_open_open_32_53(i);}

    static double u01(uint32_t i, Open, Closed, u32, f53)
    {return ::u01_open_closed_32_53(i);}

    static double u01(uint32_t i, Closed, Open, u32, f53)
    {return ::u01_closed_open_32_53(i);}

    static double u01(uint32_t i, Closed, Closed, u32, f53)
    {return ::u01_closed_closed_32_53(i);}

    static float u01(uint64_t i, Open, Open, u64, f24)
    {return static_cast<float>(::u01_open_open_64_53(i));}

    static float u01(uint64_t i, Open, Closed, u64, f24)
    {return static_cast<float>(::u01_open_closed_64_53(i));}

    static float u01(uint64_t i, Closed, Open, u64, f24)
    {return static_cast<float>(::u01_closed_open_64_53(i));}

    static float u01(uint64_t i, Closed, Closed, u64, f24)
    {return static_cast<float>(::u01_closed_closed_64_53(i));}

    static double u01(uint64_t i, Open, Open, u64, f53)
    {return ::u01_open_open_64_53(i);}

    static double u01(uint64_t i, Open, Closed, u64, f53)
    {return ::u01_open_closed_64_53(i);}

    static double u01(uint64_t i, Closed, Open, u64, f53)
    {return ::u01_closed_open_64_53(i);}

    static double u01(uint64_t i, Closed, Closed, u64, f53)
    {return ::u01_closed_closed_64_53(i);}
}; // class UniformRealDistributionBase

} // namespace vsmc

#endif // VSMC_UNIFORM_REAL_DISTRIBUTION_HPP
<commit_msg>fix for dynamic dispatch<commit_after>//============================================================================
// include/vsmc/rng/uniform_real_distribution.hpp
//----------------------------------------------------------------------------
//
//                         vSMC: Scalable Monte Carlo
//
// This file is distribured under the 2-clauses BSD License.
// See LICENSE for details.
//============================================================================

#ifndef VSMC_UNIFORM_REAL_DISTRIBUTION_HPP
#define VSMC_UNIFORM_REAL_DISTRIBUTION_HPP

#include <vsmc/rng/internal/common.hpp>
#include <vsmc/rng/u01.h>

#define VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUITON_PARAM_CHECK(a, b) \
    VSMC_RUNTIME_ASSERT((a <= b),                                            \
            ("**UniformRealDistribution** CONSTRUCTED WITH INVALID "         \
             "MINIMUM AND MAXIMUM PARAMTER VALUES"))

#define VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN(eng_min) \
    VSMC_RUNTIME_ASSERT((eng_min == 0),                                      \
            ("**UniformRealDistribution::operator()** "                      \
             "ENGINE MEMBER FUNCTION min() RETURN A VALUE OTHER THAN ZERO"))

#define VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX(eng_max) \
    VSMC_RUNTIME_ASSERT((eng_max == uint32_t_max_ || eng_max == uint64_t_max_),\
            ("**UniformRealDistribution::operator()** "                      \
             "ENGINE MEMBER FUNCTION max() RETURN A VALUE OTHER THAN "       \
             "THE MAXIMUM OF uint32_t OR uint64_t"))

namespace vsmc {

namespace internal {

template<uint64_t, uint64_t> struct UniformRealDistributionFullRangeIntgerType;

template<>
struct UniformRealDistributionFullRangeIntgerType<0,
    static_cast<uint64_t>(static_cast<uint32_t>(~(static_cast<uint32_t>(0))))>
{typedef uint32_t type;};

template<>
struct UniformRealDistributionFullRangeIntgerType<0,
    static_cast<uint64_t>(~(static_cast<uint64_t>(0)))>
{typedef uint64_t type;};

} // namespace vsmc::interal

/// \brief Parameter type for open interval
/// \ingroup RNG
struct Open {};

/// \brief Parameter type for closed interval
/// \ingroup RNG
struct Closed {};

/// \brief Uniform real distribution with variants open/closed variants
/// \ingroup RNG
///
/// \details
/// This distribution is almost identical to C++11
/// `std::uniform_real_distribution`. But it differs in two important aspects
/// - It allows the interval to be either open or closed on both sides.
/// - It requires that the uniform random number generator to produce integers
///   on the full range of either `uint32_t` or `uint64_t`.
template <typename FPType, typename Left, typename Right>
class UniformRealDistribution
{
    private :

    typedef cxx11::integral_constant<std::size_t, sizeof(float)> f24;
    typedef cxx11::integral_constant<std::size_t, sizeof(double)> f53;
    typedef cxx11::integral_constant<std::size_t, sizeof(uint32_t)> u32;
    typedef cxx11::integral_constant<std::size_t, sizeof(uint64_t)> u64;

    public :

    typedef FPType result_type;

    class param_type
    {
        public :

        typedef FPType result_type;

        typedef UniformRealDistribution<FPType, Left, Right> distribution_type;

        explicit param_type (result_type a = 0, result_type b = 1) :
            a_(a), b_(b) {}

        result_type a () const {return a_;}
        result_type b () const {return b_;}

        friend inline bool operator== (
                const param_type &param1, const param_type &param2)
        {
            if (param1.a_ < param2.a_ || param1.a_ > param2.a_)
                return false;
            if (param1.b_ < param2.b_ || param1.b_ > param2.b_)
                return false;
            return true;
        }

        friend inline bool operator!= (
                const param_type param1, const param_type param2)
        {return !(param1 == param2);}

        template <typename CharT, typename Traits>
        friend inline std::basic_ostream<CharT, Traits> &operator<< (
                std::basic_ostream<CharT, Traits> &os, const param_type &param)
        {
            if (!os.good())
                return os;

            os << param.a_ << ' ' << param.b_;

            return os;
        }

        template <typename CharT, typename Traits>
        friend inline std::basic_istream<CharT, Traits> &operator>> (
                std::basic_istream<CharT, Traits> &is, param_type &param)
        {
            if (!is.good())
                return is;

            result_type a = 1;
            result_type b = 0;
            is >> std::ws >> a;
            is >> std::ws >> b;

            if (is.good()) {
                if (a <= b) {
                    param.a_ = a;
                    param.b_ = b;
                } else {
                    is.setstate(std::ios_base::failbit);
                }
            }

            return is;
        }

        private :

        result_type a_;
        result_type b_;
    }; // class param_type

    explicit UniformRealDistribution (result_type a = 0, result_type b = 1) :
        a_(a), b_(b)
    {VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUITON_PARAM_CHECK(a_, b_);}

    UniformRealDistribution (const param_type &param) :
        a_(param.a()), b_(param.b())
    {VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUITON_PARAM_CHECK(a_, b_);}

    param_type param () const {return param_type(a_, b_);}

    void param (const param_type &param)
    {
        a_ = param.a();
        b_ = param.b();
    }

    void reset () const {}

    result_type a () const {return a_;}
    result_type b () const {return b_;}
    result_type min VSMC_MNE () const {return a_;}
    result_type max VSMC_MNE () const {return b_;}

    /// \brief Generate uniform random variates
    ///
    /// \tparam Eng Requirement:
    /// ~~~{.cpp}
    /// Eng::min() == 0 && (
    /// Eng::max() == std::numeric_limits<uint32_t>::max() ||
    /// Eng::max() == std::numeric_limits<uint64_t>::max()
    /// )
    /// ~~~
    template <typename Eng>
    result_type operator() (Eng &eng)
    {
#if VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX
	operator()(eng, cxx11::true_type());
#else
	operator()(eng, cxx11::false_type());
#endif
    }

    /// \brief static dispatch based on `Eng::min()` and `Eng::max()`, both
    /// need to be constant expression
    template <typename Eng>
    result_type operator() (Eng &eng, cxx11::true_type) const
    {
        typedef cxx11::integral_constant<std::size_t, sizeof(result_type)>
            fbits;
        typedef typename internal::UniformRealDistributionFullRangeIntgerType<
            Eng::min VSMC_MNE (), Eng::max VSMC_MNE ()>::type eng_uint_t;
        typedef cxx11::integral_constant<std::size_t, sizeof(eng_uint_t)>
            ubits;

        result_type u = u01(static_cast<eng_uint_t>(eng()), Left(), Right(),
                ubits(), fbits());

        return u * (b_ - a_) + a_;
    }

    /// \brief Dynamic dispatch based on `eng.min()` and `eng.max()`
    template <typename Eng>
    result_type operator() (Eng &eng, cxx11::false_type) const
    {
        typedef cxx11::integral_constant<std::size_t, sizeof(result_type)>
            fbits;

        static const uint64_t eng_max = static_cast<uint64_t>(
                eng.max VSMC_MNE ());

        VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN(
                (eng.min VSMC_MNE ()));
        VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX(eng_max);

        result_type u = 0;
        switch (eng_max) {
            case uint32_t_max_ :
                u = u01(static_cast<uint32_t>(eng()), Left(), Right(),
                        u32(), fbits());
                break;
            case uint64_t_max_ :
                u = u01(static_cast<uint64_t>(eng()), Left(), Right(),
                        u64(), fbits());
                break;
            default :
                return 0;
        }

        return u * (b_ - a_) + a_;
    }

    friend inline bool operator== (
            const UniformRealDistribution<FPType, Left, Right> &runif1,
            const UniformRealDistribution<FPType, Left, Right> &runif2)
    {
        if (runif1.a_ < runif2.a_ ||runif1.a_ > runif1.a_)
            return false;
        if (runif1.b_ < runif2.b_ ||runif1.b_ > runif1.b_)
            return false;
        return true;
    }

    friend inline bool operator!= (
            const UniformRealDistribution<FPType, Left, Right> &runif1,
            const UniformRealDistribution<FPType, Left, Right> &runif2)
    {return !(runif1 == runif2);}

    template <typename CharT, typename Traits>
    friend inline std::basic_ostream<CharT, Traits> &operator<< (
            std::basic_ostream<CharT, Traits> &os,
            const UniformRealDistribution<FPType, Left, Right> &runif)
    {
        if (!os.good())
            return os;

        os << runif.a_ << ' ' << runif.b_;

        return os;
    }

    template <typename CharT, typename Traits>
    friend inline std::basic_istream<CharT, Traits> &operator>> (
            std::basic_istream<CharT, Traits> &is,
            UniformRealDistribution<FPType, Left, Right> &runif)
    {
        if (!is.good())
            return is;

        result_type a = 1;
        result_type b = 0;
        is >> std::ws >> a;
        is >> std::ws >> b;
        if (is.good()) {
            if (a <= b) {
                runif.a_ = a;
                runif.b_ = b;
            } else {
                is.setstate(std::ios_base::failbit);
            }
        }

        return is;
    }

    private :

    result_type a_;
    result_type b_;

    static VSMC_CONSTEXPR const uint64_t uint32_t_max_ = static_cast<uint64_t>(
            static_cast<uint32_t>(~(static_cast<uint32_t>(0))));

    static VSMC_CONSTEXPR const uint64_t uint64_t_max_ = static_cast<uint64_t>(
            ~(static_cast<uint64_t>(0)));

    static float u01(uint32_t i, Open, Open, u32, f24)
    {return ::u01_open_open_32_24(i);}

    static float u01(uint32_t i, Open, Closed, u32, f24)
    {return ::u01_open_closed_32_24(i);}

    static float u01(uint32_t i, Closed, Open, u32, f24)
    {return ::u01_closed_open_32_24(i);}

    static float u01(uint32_t i, Closed, Closed, u32, f24)
    {return ::u01_closed_closed_32_24(i);}

    static double u01(uint32_t i, Open, Open, u32, f53)
    {return ::u01_open_open_32_53(i);}

    static double u01(uint32_t i, Open, Closed, u32, f53)
    {return ::u01_open_closed_32_53(i);}

    static double u01(uint32_t i, Closed, Open, u32, f53)
    {return ::u01_closed_open_32_53(i);}

    static double u01(uint32_t i, Closed, Closed, u32, f53)
    {return ::u01_closed_closed_32_53(i);}

    static float u01(uint64_t i, Open, Open, u64, f24)
    {return static_cast<float>(::u01_open_open_64_53(i));}

    static float u01(uint64_t i, Open, Closed, u64, f24)
    {return static_cast<float>(::u01_open_closed_64_53(i));}

    static float u01(uint64_t i, Closed, Open, u64, f24)
    {return static_cast<float>(::u01_closed_open_64_53(i));}

    static float u01(uint64_t i, Closed, Closed, u64, f24)
    {return static_cast<float>(::u01_closed_closed_64_53(i));}

    static double u01(uint64_t i, Open, Open, u64, f53)
    {return ::u01_open_open_64_53(i);}

    static double u01(uint64_t i, Open, Closed, u64, f53)
    {return ::u01_open_closed_64_53(i);}

    static double u01(uint64_t i, Closed, Open, u64, f53)
    {return ::u01_closed_open_64_53(i);}

    static double u01(uint64_t i, Closed, Closed, u64, f53)
    {return ::u01_closed_closed_64_53(i);}
}; // class UniformRealDistributionBase

} // namespace vsmc

#endif // VSMC_UNIFORM_REAL_DISTRIBUTION_HPP
<|endoftext|>


<commit_before>#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <iostream>
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <string>
#include <std_msgs/Int16.h>
/**
* listens to the "/questions" and "/balls" topics and sends messages to the "/makeSound", "/drive" and "/display" topic to make sounds, drive around and display various the question.
Subscribes to:
	/questions
	/balls

Publishes to:
	/makeSound
	/drive
	/display
*/
class mathasker{
	public:

	ros::Subscriber sub;
	ros::NodeHandle handle;

	ros::Publisher display;
	ros::Publisher sound;
	ros::Publisher drive;

	ros::Subscriber numberball;
	ros::Subscriber launch;

	const int balls[20]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
	std::vector<int> available_balls;

	int find(std::vector<int> vec, int seek)
	{
	    for (int i = 0; i < vec.size(); ++i)
	    {
	        if (vec[i] == seek) return i;
	    }
	    return -1;
	}

	//written by bob, muchos bugs
	/*void removecallback(std_msgs::Int16::ConstPtr &number){
		int lel = number->data;
		int index = find(balls, lel);
		if (index != -1){
			available_balls.erase(index);
		}
	}

	//written by bob, muchos bugs
	void donelaunchingcallback(std_msgs::String::ConstPtr &msg){
		if (msg->data == "donelaunching"){
			for(int i=1;i<20;i++){
				available_balls.push_back(balls[i]);
			}
		}
	}
	*/

	/* returns array of 3 integers first 2 are the once being summed third is the answer*/
	int* addition2dig(){
		int* result =new int[3];
		//select indexes
		int a;
		int b;
		do{
			a=available_balls[rand()%available_balls.size()];
			b=available_balls[rand()%available_balls.size()];
		}while(a!=b);
			result[2]=a*10+b;
			result[1]=rand()%result[2];
			result[0]=result[2]-result[1];
		return result;
	}

	int* addition1dig(){
		int* result =new int[3];
		result[2]=available_balls[rand()%available_balls.size()];
		if(result[2]!=0){
			result[1]=rand()%result[2];
		}else{
			result[1]=0;
		}
		result[0]=result[2]-result[1];
		return result;
	}

	int* substract1dig(){
		int* ans=addition1dig();
		int temp=ans[0];
		ans[0]=ans[2];
		ans[2]=temp;
		return ans;
	}
	int* substract2dig(){
		int* ans=addition2dig();
		int temp=ans[0];
		ans[0]=ans[2];
		ans[2]=temp;
		return ans;
		}

	void questioncallback(std_msgs::String request){

		int* questiondata;
		std_msgs::String soundmsg;
		std_msgs::String displaymsg;
		char opperator='0';

		if(request.data.compare("1digitAdditionfs")==0){

			questiondata=addition1dig();
			opperator='+';
		}
		if(request.data.compare("2digitAddition")==0){
			questiondata=addition2dig();
			opperator='+';
		}
		if(request.data.compare("1digitSubstraction")==0){
			questiondata=substract1dig();
			opperator='-';
		}
		if(request.data.compare("2digitSubstraction")==0){
			questiondata=substract2dig();
			opperator='-';
		}
		if (opperator=='0'){
			std::cout<<"/question:"<<request<<"is not understanable for the mathasker"<<std::endl;
			return;
		}
		std::stringstream ss;
		ss<<questiondata[0];
		switch (opperator){
			case '+': ss<<":";break;
			case '-': ss<<";";break;
			case 'x': ss<<"<";break;
			case '/': ss<<"=";break;
		}
		ss<<questiondata[1];
		soundmsg.data=ss.str();
		sound.publish(soundmsg);
		std::stringstream ds;
		ds<<"s"<<questiondata[0]<<opperator<<questiondata[1];
		displaymsg.data=ds.str();
		display.publish(displaymsg);
	}

	mathasker():handle("~"){
		srand (time(NULL));
		display=handle.advertise<std_msgs::String>("/display",100);
		sound=handle.advertise<std_msgs::String>("/tawi/media/audio",100);
		drive=handle.advertise<std_msgs::String>("/drive",100);
		sub = handle.subscribe<std_msgs::String>("/questions", 100, &mathasker::questioncallback,this); //question TRIGGER
		//numberball = handle.subscribe<std_msgs::Int16>("/tawi/core/number", 10, &mathasker::removecallback,this); //remove ball subscription
		//launch = handle.subscribe<std_msgs::String>("/tawi/core/launch", 100, &mathasker::donelaunchcallback,this); //done with launching subscription
		for(int i=1;i<20;i++){
			available_balls.push_back(balls[i]);
		}
	}
};

int main(int argc, char **argv){
	ros::init(argc, argv, "audioDriver");
	mathasker math;
	ros::Rate hz(100);

	while(ros::ok()){
		ros::spinOnce();
		hz.sleep();
	}
}
<commit_msg>fixed mofos<commit_after>#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <iostream>
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <string>
#include <std_msgs/Int16.h>
/**
* listens to the "/questions" and "/balls" topics and sends messages to the "/makeSound", "/drive" and "/display" topic to make sounds, drive around and display various the question.
Subscribes to:
	/questions
	/balls

Publishes to:
	/makeSound
	/drive
	/display
*/
class mathasker{
	public:

	ros::Subscriber sub;
	ros::NodeHandle handle;

	ros::Publisher display;
	ros::Publisher sound;
	ros::Publisher drive;

	ros::Subscriber numberball;
	ros::Subscriber launch;

	const int balls[20]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
	std::vector<int> available_balls;

	//written by bob, muchos bugs but working.
	void removecallback(std_msgs::Int16 number){
		int lel = number.data;
		printf("removing number: %d \n", lel);
		//int index = find(balls, lel);
		available_balls.erase(std::remove(available_balls.begin(), available_balls.end(), lel), available_balls.end());
		/*if (index != -1){
			available_balls.erase(index);
		}*/
		for (int i=0; i<available_balls.size(); i++){
			printf("%d, ", available_balls[i]);
		}
		printf("\n");
	}

	//written by bob, muchos bugs but working.
	void donelaunchcallback(std_msgs::String msg){
		if (msg.data == "donelaunching"){
			available_balls.clear();
			for(int i=1;i<20;i++){
				available_balls.push_back(balls[i]);
			}
		}
	}

	/* returns array of 3 integers first 2 are the once being summed third is the answer*/
	int* addition2dig(){
		int* result =new int[3];
		//select indexes
		int a;
		int b;
		do{
			a=available_balls[rand()%available_balls.size()];
			b=available_balls[rand()%available_balls.size()];
		}while(a!=b);
			result[2]=a*10+b;
			result[1]=rand()%result[2];
			result[0]=result[2]-result[1];
		return result;
	}

	int* addition1dig(){
		int* result =new int[3];
		result[2]=available_balls[rand()%available_balls.size()];
		if(result[2]!=0){
			result[1]=rand()%result[2];
		}else{
			result[1]=0;
		}
		result[0]=result[2]-result[1];
		return result;
	}

	int* substract1dig(){
		int* ans=addition1dig();
		int temp=ans[0];
		ans[0]=ans[2];
		ans[2]=temp;
		return ans;
	}
	int* substract2dig(){
		int* ans=addition2dig();
		int temp=ans[0];
		ans[0]=ans[2];
		ans[2]=temp;
		return ans;
		}

	void questioncallback(std_msgs::String request){

		int* questiondata;
		std_msgs::String soundmsg;
		std_msgs::String displaymsg;
		char opperator='0';

		if(request.data.compare("1digitAdditionfs")==0){

			questiondata=addition1dig();
			opperator='+';
		}
		if(request.data.compare("2digitAddition")==0){
			questiondata=addition2dig();
			opperator='+';
		}
		if(request.data.compare("1digitSubstraction")==0){
			questiondata=substract1dig();
			opperator='-';
		}
		if(request.data.compare("2digitSubstraction")==0){
			questiondata=substract2dig();
			opperator='-';
		}
		if (opperator=='0'){
			std::cout<<"/question:"<<request<<"is not understanable for the mathasker"<<std::endl;
			return;
		}
		std::stringstream ss;
		ss<<questiondata[0];
		switch (opperator){
			case '+': ss<<":";break;
			case '-': ss<<";";break;
			case 'x': ss<<"<";break;
			case '/': ss<<"=";break;
		}
		ss<<questiondata[1];
		soundmsg.data=ss.str();
		sound.publish(soundmsg);
		std::stringstream ds;
		ds<<"s"<<questiondata[0]<<opperator<<questiondata[1];
		displaymsg.data=ds.str();
		display.publish(displaymsg);
	}

	mathasker():handle("~"){
		srand (time(NULL));
		display=handle.advertise<std_msgs::String>("/display",100);
		sound=handle.advertise<std_msgs::String>("/tawi/media/audio",100);
		drive=handle.advertise<std_msgs::String>("/drive",100);
		sub = handle.subscribe<std_msgs::String>("/questions", 100, &mathasker::questioncallback,this); //question TRIGGER
		numberball = handle.subscribe<std_msgs::Int16>("/tawi/core/number", 1, &mathasker::removecallback,this); //remove ball subscription
		launch = handle.subscribe<std_msgs::String>("/tawi/core/launch", 100, &mathasker::donelaunchcallback,this); //done with launching subscription
		for(int i=1;i<20;i++){
			available_balls.push_back(balls[i]);
		}
	}
};

int main(int argc, char **argv){
	ros::init(argc, argv, "audioDriver");
	mathasker math;
	ros::Rate hz(100);

	while(ros::ok()){
		ros::spinOnce();
		hz.sleep();
	}
}
<|endoftext|>


<commit_before>#ifndef ORG_EEROS_CONTROL_ETHERCAT_ELMOOUTPUT_
#define ORG_EEROS_CONTROL_ETHERCAT_ELMOOUTPUT_

#include <eeros/control/Blockio.hpp>
#include <eeros/control/Input.hpp>
#include <eeros/core/System.hpp>
#include <EcMasterlibMain.hpp>
#include <device/Elmo.hpp>

namespace eeros {
namespace control {

/**
 * This block reads a Elmo drive over EtherCAT and outputs the position,
 * velocity and torque values onto three output signals. All values must be scaled
 * in order to get meaningful physical entities.
 *
 * @since v1.3
 */

class ElmoOutput : public Blockio<0,0,double,double> {

 public:
  /**
   * Constructs a EtherCAT receive block instance which receives its output
   * signals from a Elmo drive.
   *
   * @param iface - reference to Elmo drive
   */
  ElmoInput(ecmasterlib::device::Elmo& iface) : iface(iface) { }

  /**
   * Puts the drive inputs onto the output signals.
   */
  virtual void run() {
    using Mode = ecmasterlib::device::Elmo::Mode;
    const auto getValue = [](auto &input) { return input.getSignal().getValue(); };
    switch (elmo.getMode()) {
      case Mode::PROFILE_POSITION:
        elmo.setTargetPosition(getValue(position));
        elmo.setMaximumTorque(getValue(torqueMax));
        break;
      case Mode::PROFILE_VELOCITY:
        elmo.setTargetVelocity(getValue(velocity));
        elmo.setMaximumTorque(getValue(torqueMax));
        break;
      case Mode::PROFILE_TORQUE:
        elmo.setTargetTorque(getValue(torque));
        elmo.setMaximumTorque(getValue(torqueMax));
        break;
      default:
        break;
      }
  }

  /**
   * Gets the position input of the block.
   *
   * @return input
   */
  virtual Input<int32_t>& getPosIn() { return position; }

  /**
   * Gets the velocity input of the block.
   *
   * @return input
   */
  virtual Input<int32_t>& getVelIn() { return velocity; }

  /**
   * Gets the torque input of the block.
   *
   * @return input
   */
  virtual Input<int16_t>& getTorqueIn() { return torque; }

  /**
   * Gets the maximum torque input of the block.
   *
   * @return input
   */
  virtual Input<int16_t>& getTorqueMaxIn(){ return torqueMax; }

 private:
   ecmasterlib::device::Elmo& iface;
   Input<int32_t> position, velocity;
   Input<int16_t> torque, torqueMax;
};

}
}

#endif // ORG_EEROS_CONTROL_ETHERCAT_ELMOOUTPUT_
<commit_msg>Correct documentation<commit_after>#ifndef ORG_EEROS_CONTROL_ETHERCAT_ELMOOUTPUT_
#define ORG_EEROS_CONTROL_ETHERCAT_ELMOOUTPUT_

#include <eeros/control/Blockio.hpp>
#include <eeros/control/Input.hpp>
#include <eeros/core/System.hpp>
#include <EcMasterlibMain.hpp>
#include <device/Elmo.hpp>

namespace eeros {
namespace control {

/**
 * This block reads input signals for position, velocity and torque and sends
 * them over EtherCAT to an Elmo drive. All values must be scaled from physical
 * entities to fit into the transmit frame of EtherCAT.
 *
 * @since v1.3
 */

class ElmoOutput : public Blockio<0,0,double,double> {

 public:
  /**
   * Constructs an EtherCAT transmit block instance which sends its input
   * signals to an Elmo drive.
   *
   * @param iface - reference to Elmo drive
   */
  ElmoOutput(ecmasterlib::device::Elmo& iface) : iface(iface) { }

  /**
   * Puts the signal inputs to the Elmo drive.
   */
  virtual void run() {
    using Mode = ecmasterlib::device::Elmo::Mode;
    const auto getValue = [](auto &input) { return input.getSignal().getValue(); };
    switch (elmo.getMode()) {
      case Mode::PROFILE_POSITION:
        elmo.setTargetPosition(getValue(position));
        elmo.setMaximumTorque(getValue(torqueMax));
        break;
      case Mode::PROFILE_VELOCITY:
        elmo.setTargetVelocity(getValue(velocity));
        elmo.setMaximumTorque(getValue(torqueMax));
        break;
      case Mode::PROFILE_TORQUE:
        elmo.setTargetTorque(getValue(torque));
        elmo.setMaximumTorque(getValue(torqueMax));
        break;
      default:
        break;
      }
  }

  /**
   * Gets the position input of the block.
   *
   * @return input
   */
  virtual Input<int32_t>& getPosIn() { return position; }

  /**
   * Gets the velocity input of the block.
   *
   * @return input
   */
  virtual Input<int32_t>& getVelIn() { return velocity; }

  /**
   * Gets the torque input of the block.
   *
   * @return input
   */
  virtual Input<int16_t>& getTorqueIn() { return torque; }

  /**
   * Gets the maximum torque input of the block.
   *
   * @return input
   */
  virtual Input<int16_t>& getTorqueMaxIn(){ return torqueMax; }

 private:
   ecmasterlib::device::Elmo& iface;
   Input<int32_t> position, velocity;
   Input<int16_t> torque, torqueMax;
};

}
}

#endif // ORG_EEROS_CONTROL_ETHERCAT_ELMOOUTPUT_
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tabcol.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:18:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _TABCOL_HXX
#define _TABCOL_HXX

#ifndef _SVSTDARR_HXX
#define _SVSTDARR_LONGS
#define _SVSTDARR_BOOLS
#include <svtools/svstdarr.hxx>
#endif

#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

struct SwTabColsEntry
{
    long    nPos;
    long    nMin;
    long    nMax;
    BOOL    bHidden;    //Fuer jeden Eintrag ein Flag, Hidden oder nicht.
                        //Wenn das Flag Hidden TRUE ist liegt der Spalten-
                        //trenner nicht in der aktuellen Zeile; er muss
                        //mit gepflegt werden, darf aber nicht angezeigt
                        //werden.
};

typedef std::vector< SwTabColsEntry > SwTabColsEntries;

class SW_DLLPUBLIC SwTabCols
{
    long nLeftMin,      //Linker aeusserer Rand (Bezugspunkt) in
                        //Dokumentkordinaten.
                        //Alle anderen Werte relativ zu diesem Punkt!
            nLeft,      //Linker Rand der Tabelle.
           nRight,      //Rechter Rand der Tabelle.
           nRightMax;   //Maximaler rechter Rand der Tabelle.

    bool bLastRowAllowedToChange;       // if the last row of the table frame
                                        // is split across pages, it may not
                                        // change its size

    SwTabColsEntries aData;

    //fuer den CopyCTor
    const SwTabColsEntries& GetData() const { return aData; }

public:
    SwTabCols( USHORT nSize = 0 );
    SwTabCols( const SwTabCols& );
    SwTabCols &operator=( const SwTabCols& );
    BOOL operator==( const SwTabCols& rCmp ) const;
    long& operator[]( USHORT nPos ) { return aData[nPos].nPos; }
    long operator[]( USHORT nPos ) const { return aData[nPos].nPos; }
    USHORT Count() const { return aData.size(); }

    BOOL IsHidden( USHORT nPos ) const         { return aData[nPos].bHidden; }
    void SetHidden( USHORT nPos, BOOL bValue ) { aData[nPos].bHidden = bValue; }

    void Insert( long nValue, BOOL bValue, USHORT nPos );
    void Insert( long nValue, long nMin, long nMax, BOOL bValue, USHORT nPos );
    void Remove( USHORT nPos, USHORT nAnz = 1 );

    const SwTabColsEntry& GetEntry( USHORT nPos ) const { return aData[nPos]; }
          SwTabColsEntry& GetEntry( USHORT nPos )  { return aData[nPos]; }

    long GetLeftMin() const { return nLeftMin; }
    long GetLeft()  const { return nLeft;    }
    long GetRight() const { return nRight;   }
    long GetRightMax()const { return nRightMax;}

    void SetLeftMin ( long nNew )   { nLeftMin = nNew; }
    void SetLeft    ( long nNew )   { nLeft = nNew;    }
    void SetRight   ( long nNew )   { nRight = nNew;   }
    void SetRightMax( long nNew )   { nRightMax = nNew;}

    bool IsLastRowAllowedToChange() const { return bLastRowAllowedToChange; }
    void SetLastRowAllowedToChange( bool bNew ) { bLastRowAllowedToChange = bNew; }
};

#endif  //_TABCOL_HXX
<commit_msg>INTEGRATION: CWS swwarnings (1.4.710); FILE MERGED 2007/02/22 15:05:39 tl 1.4.710.1: #i69287# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tabcol.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 08:13:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _TABCOL_HXX
#define _TABCOL_HXX

#ifndef _SVSTDARR_HXX
#define _SVSTDARR_LONGS
#define _SVSTDARR_BOOLS
#include <svtools/svstdarr.hxx>
#endif

#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

struct SwTabColsEntry
{
    long    nPos;
    long    nMin;
    long    nMax;
    BOOL    bHidden;    //Fuer jeden Eintrag ein Flag, Hidden oder nicht.
                        //Wenn das Flag Hidden TRUE ist liegt der Spalten-
                        //trenner nicht in der aktuellen Zeile; er muss
                        //mit gepflegt werden, darf aber nicht angezeigt
                        //werden.
};

typedef std::vector< SwTabColsEntry > SwTabColsEntries;

class SW_DLLPUBLIC SwTabCols
{
    long nLeftMin,      //Linker aeusserer Rand (Bezugspunkt) in
                        //Dokumentkordinaten.
                        //Alle anderen Werte relativ zu diesem Punkt!
            nLeft,      //Linker Rand der Tabelle.
           nRight,      //Rechter Rand der Tabelle.
           nRightMax;   //Maximaler rechter Rand der Tabelle.

    bool bLastRowAllowedToChange;       // if the last row of the table frame
                                        // is split across pages, it may not
                                        // change its size

    SwTabColsEntries aData;

    //fuer den CopyCTor
    const SwTabColsEntries& GetData() const { return aData; }

public:
    SwTabCols( USHORT nSize = 0 );
    SwTabCols( const SwTabCols& );
    SwTabCols &operator=( const SwTabCols& );
    BOOL operator==( const SwTabCols& rCmp ) const;
    long& operator[]( USHORT nPos ) { return aData[nPos].nPos; }
    long operator[]( USHORT nPos ) const { return aData[nPos].nPos; }
    USHORT Count() const { return sal::static_int_cast< USHORT >(aData.size()); }

    BOOL IsHidden( USHORT nPos ) const         { return aData[nPos].bHidden; }
    void SetHidden( USHORT nPos, BOOL bValue ) { aData[nPos].bHidden = bValue; }

    void Insert( long nValue, BOOL bValue, USHORT nPos );
    void Insert( long nValue, long nMin, long nMax, BOOL bValue, USHORT nPos );
    void Remove( USHORT nPos, USHORT nAnz = 1 );

    const SwTabColsEntry& GetEntry( USHORT nPos ) const { return aData[nPos]; }
          SwTabColsEntry& GetEntry( USHORT nPos )  { return aData[nPos]; }

    long GetLeftMin() const { return nLeftMin; }
    long GetLeft()  const { return nLeft;    }
    long GetRight() const { return nRight;   }
    long GetRightMax()const { return nRightMax;}

    void SetLeftMin ( long nNew )   { nLeftMin = nNew; }
    void SetLeft    ( long nNew )   { nLeft = nNew;    }
    void SetRight   ( long nNew )   { nRight = nNew;   }
    void SetRightMax( long nNew )   { nRightMax = nNew;}

    bool IsLastRowAllowedToChange() const { return bLastRowAllowedToChange; }
    void SetLastRowAllowedToChange( bool bNew ) { bLastRowAllowedToChange = bNew; }
};

#endif  //_TABCOL_HXX
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: usrfld.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-12-14 14:47:12 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _USRFLD_HXX
#define _USRFLD_HXX

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

#ifndef _FLDBAS_HXX
#include "fldbas.hxx"
#endif

class SfxPoolItem;
class SwCalc;
class SwDoc;

/*--------------------------------------------------------------------
    Beschreibung: Benutzerfelder
 --------------------------------------------------------------------*/

class SW_DLLPUBLIC SwUserFieldType : public SwValueFieldType
{
    BOOL    bValidValue : 1;
    BOOL    bDeleted : 1;
    double  nValue;
    String  aName;
    String  aContent;
    USHORT  nType;

public:
    SwUserFieldType( SwDoc* pDocPtr, const String& );

    virtual const String&   GetName() const;
    virtual SwFieldType*    Copy() const;

    String                  Expand(sal_uInt32 nFmt, USHORT nSubType, USHORT nLng);

    String                  GetContent( sal_uInt32 nFmt = 0 );
           void             SetContent( const String& rStr, sal_uInt32 nFmt = 0 );
           void             CtrlSetContent( const String& rStr );

    inline BOOL             IsValid() const;
    inline void             ChgValid( BOOL bNew );

    virtual void            Modify( SfxPoolItem* pOld, SfxPoolItem* pNew );

           double           GetValue(SwCalc& rCalc);    // Member nValue neu berrechnen
    inline double           GetValue() const;
    inline void             SetValue(const double nVal);

    inline USHORT           GetType() const;
    inline void             SetType(USHORT);

    BOOL                    IsDeleted() const       { return bDeleted; }
    void                    SetDeleted( BOOL b )    { bDeleted = b; }

    virtual BOOL        QueryValue( com::sun::star::uno::Any& rVal, BYTE nMId ) const;
    virtual BOOL        PutValue( const com::sun::star::uno::Any& rVal, BYTE nMId );
};

inline BOOL SwUserFieldType::IsValid() const
    { return bValidValue; }

inline void SwUserFieldType::ChgValid( BOOL bNew )
    { bValidValue = bNew; }

inline double SwUserFieldType::GetValue() const
    { return nValue; }

inline void SwUserFieldType::SetValue(const double nVal)
    { nValue = nVal; }

inline USHORT SwUserFieldType::GetType() const
    { return nType; }

inline void SwUserFieldType::SetType(USHORT nSub)
{
    nType = nSub;
    EnableFormat(!(nSub & GSE_STRING));
}

/*--------------------------------------------------------------------
    Beschreibung: Benutzerfelder
 --------------------------------------------------------------------*/

class SwUserField : public SwValueField
{
    USHORT  nSubType;

public:
    SwUserField(SwUserFieldType*, USHORT nSub = 0, sal_uInt32 nFmt = 0);

    virtual USHORT          GetSubType() const;
    virtual void            SetSubType(USHORT nSub);

    virtual double          GetValue() const;
    virtual void            SetValue( const double& rVal );

    virtual String          Expand() const;
    virtual SwField*        Copy() const;
    virtual String          GetCntnt(BOOL bName = FALSE) const;

    // Name kann nicht geaendert werden
    virtual const String&   GetPar1() const;

    // Inhalt
    virtual String          GetPar2() const;
    virtual void            SetPar2(const String& rStr);
    virtual BOOL        QueryValue( com::sun::star::uno::Any& rVal, BYTE nMId ) const;
    virtual BOOL        PutValue( const com::sun::star::uno::Any& rVal, BYTE nMId );
};

#endif // _USRFLD_HXX
<commit_msg>INTEGRATION: CWS os94 (1.5.616); FILE MERGED 2007/03/12 08:07:33 os 1.5.616.1: #i75235# unused methods removed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: usrfld.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-25 08:58:06 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _USRFLD_HXX
#define _USRFLD_HXX

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

#ifndef _FLDBAS_HXX
#include "fldbas.hxx"
#endif

class SfxPoolItem;
class SwCalc;
class SwDoc;

/*--------------------------------------------------------------------
    Beschreibung: Benutzerfelder
 --------------------------------------------------------------------*/

class SW_DLLPUBLIC SwUserFieldType : public SwValueFieldType
{
    BOOL    bValidValue : 1;
    BOOL    bDeleted : 1;
    double  nValue;
    String  aName;
    String  aContent;
    USHORT  nType;

public:
    SwUserFieldType( SwDoc* pDocPtr, const String& );

    virtual const String&   GetName() const;
    virtual SwFieldType*    Copy() const;

    String                  Expand(sal_uInt32 nFmt, USHORT nSubType, USHORT nLng);

    String                  GetContent( sal_uInt32 nFmt = 0 );
           void             SetContent( const String& rStr, sal_uInt32 nFmt = 0 );

    inline BOOL             IsValid() const;
    inline void             ChgValid( BOOL bNew );

    virtual void            Modify( SfxPoolItem* pOld, SfxPoolItem* pNew );

           double           GetValue(SwCalc& rCalc);    // Member nValue neu berrechnen
    inline double           GetValue() const;
    inline void             SetValue(const double nVal);

    inline USHORT           GetType() const;
    inline void             SetType(USHORT);

    BOOL                    IsDeleted() const       { return bDeleted; }
    void                    SetDeleted( BOOL b )    { bDeleted = b; }

    virtual BOOL        QueryValue( com::sun::star::uno::Any& rVal, BYTE nMId ) const;
    virtual BOOL        PutValue( const com::sun::star::uno::Any& rVal, BYTE nMId );
};

inline BOOL SwUserFieldType::IsValid() const
    { return bValidValue; }

inline void SwUserFieldType::ChgValid( BOOL bNew )
    { bValidValue = bNew; }

inline double SwUserFieldType::GetValue() const
    { return nValue; }

inline void SwUserFieldType::SetValue(const double nVal)
    { nValue = nVal; }

inline USHORT SwUserFieldType::GetType() const
    { return nType; }

inline void SwUserFieldType::SetType(USHORT nSub)
{
    nType = nSub;
    EnableFormat(!(nSub & GSE_STRING));
}

/*--------------------------------------------------------------------
    Beschreibung: Benutzerfelder
 --------------------------------------------------------------------*/

class SwUserField : public SwValueField
{
    USHORT  nSubType;

public:
    SwUserField(SwUserFieldType*, USHORT nSub = 0, sal_uInt32 nFmt = 0);

    virtual USHORT          GetSubType() const;
    virtual void            SetSubType(USHORT nSub);

    virtual double          GetValue() const;
    virtual void            SetValue( const double& rVal );

    virtual String          Expand() const;
    virtual SwField*        Copy() const;
    virtual String          GetCntnt(BOOL bName = FALSE) const;

    // Name kann nicht geaendert werden
    virtual const String&   GetPar1() const;

    // Inhalt
    virtual String          GetPar2() const;
    virtual void            SetPar2(const String& rStr);
    virtual BOOL        QueryValue( com::sun::star::uno::Any& rVal, BYTE nMId ) const;
    virtual BOOL        PutValue( const com::sun::star::uno::Any& rVal, BYTE nMId );
};

#endif // _USRFLD_HXX
<|endoftext|>