text:
//---------------------------------------------------------------------------//
//
// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//---------------------------------------------------------------------------//

#ifndef CRYPTO3_PBKDF_HPP
#define CRYPTO3_PBKDF_HPP

#include <boost/assert.hpp>
#include <boost/concept_check.hpp>

#include <boost/core/enable_if.hpp>

#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/concepts.hpp>
#include <boost/range/any_range.hpp>

#include <nil/crypto3/detail/type_traits.hpp>

namespace nil {
    namespace crypto3 {
        namespace pbkdf {
            /*!
             * @defgroup pbkdf Password Based Key Derivation Functions
             *
             * @brief There are various procedures for turning a passphrase into a arbitrary
             * length key for use with a symmetric cipher. A general interface for
             * such algorithms is presented in ``pbkdf.h``. The main function is
             * ``derive_key``, which takes a passphrase, a salt, an iteration count,
             * and the desired length of the output key, and returns a key of that
             * length, deterministically produced from the passphrase and salt. If an
             * algorithm can't produce a key of that size, it will throw an exception
             * (most notably, PKCS #5's PBKDF1 can only produce strings between 1 and
             * $n$ bytes, where $n$ is the output size of the underlying hash
             * function).
             *
             * The purpose of the iteration count is to make the algorithm take
             * longer to compute the final key (reducing the speed of brute-force
             * attacks of various kinds). Most standards recommend an iteration count
             * of at least 10000. Currently defined PBKDF algorithms are
             * "PBKDF1(static_digest)", "PBKDF2(static_digest)"; you can retrieve any of these
             * using the ``get_pbkdf``, found in ``lookup.h``. As of this writing,
             * "PBKDF2(SHA-256)" with at least 100000 iterations and a 16 byte salt
             * is recommend for new applications.
             *
             * @defgroup pbkdf_algorithms Algorithms
             * @ingroup pbkdf
             * @brief Algorithms are meant to provide key derivation interface similar to STL algorithms' one.
             */

            namespace detail {
                template<typename Hasher, typename SinglePassRange>
                using range_stream_hash_traits = typename Hasher::template stream_hash<
                    std::numeric_limits<
                        typename std::iterator_traits<typename SinglePassRange::iterator>::value_type>::digits +
                    std::numeric_limits<typename std::iterator_traits<typename SinglePassRange::iterator>::value_type>::
                        is_signed>::type;

                template<typename Hasher, typename InputIterator>
                using iterator_stream_hash_traits = typename Hasher::template stream_hash<
                    std::numeric_limits<typename std::iterator_traits<InputIterator>::value_type>::digits +
                    std::numeric_limits<typename std::iterator_traits<InputIterator>::value_type>::is_signed>::type;

#ifdef CRYPTO3_RAW_PBKDF_STRING_OUTPUT

                template<typename Hash, typename InputIterator, typename StreamHasher>
                typename Hash::digest_type hash_impl_f(InputIterator first, InputIterator last,
                                                       StreamHasher accumulator) {
                    typedef typename std::iterator_traits<InputIterator>::value_type value_type;

                    BOOST_STATIC_ASSERT(std::numeric_limits<value_type>::is_specialized);

                    return accumulator.update(first, last).end_message();
                };

                template<typename Hash, typename SinglePassRange, typename StreamHasher,
                         typename = typename std::enable_if<boost::has_range_iterator<SinglePassRange>::value>::type>
                typename Hash::digest_type hash_impl_f(const SinglePassRange &rng, StreamHasher accumulator) {
                    BOOST_RANGE_CONCEPT_ASSERT((boost::SinglePassRangeConcept<SinglePassRange>));

                    typedef typename std::iterator_traits<typename SinglePassRange::iterator>::value_type value_type;

                    BOOST_STATIC_ASSERT(std::numeric_limits<value_type>::is_specialized);

                    return accumulator.update(boost::begin(rng), boost::end(rng)).end_message();
                }
#else

                struct hash_impl {};

                template<typename Hasher, typename StreamHash>
                struct range_value_hash_impl : public hash_impl {
                private:
                    mutable StreamHash sh;

                public:
                    template<typename SinglePassRange>
                    range_value_hash_impl(const SinglePassRange &range, StreamHash stream_hash) :
                        sh(std::move(stream_hash)) {
                        BOOST_RANGE_CONCEPT_ASSERT((boost::SinglePassRangeConcept<SinglePassRange>));

                        typedef
                            typename std::iterator_traits<typename SinglePassRange::iterator>::value_type value_type;

                        BOOST_STATIC_ASSERT(std::numeric_limits<value_type>::is_specialized);

                        sh.update(boost::begin(range), boost::end(range));
                    }

                    template<typename OutputRange>
                    operator OutputRange() const {
                        typename Hasher::digest_type range = sh.end_message();

                        return OutputRange(range.begin(), range.end());
                    }

                    operator typename Hasher::digest_type() const {
                        return sh.end_message();
                    }

                    template<typename Char, typename CharTraits, typename Alloc>
                    operator std::basic_string<Char, CharTraits, Alloc>() const {
                        return sh.end_message().str();
                    }
                };

                template<typename Hasher, typename OutputIterator, typename StreamHash>
                struct range_itr_hash_impl : public hash_impl {
                private:
                    mutable StreamHash sh;

                    mutable OutputIterator out;

                public:
                    template<typename SinglePassRange>
                    range_itr_hash_impl(const SinglePassRange &range, OutputIterator out, StreamHash stream_hash) :
                        out(std::move(out)), sh(std::move(stream_hash)) {
                        BOOST_CONCEPT_ASSERT((boost::SinglePassRangeConcept<SinglePassRange>));

                        typedef
                            typename std::iterator_traits<typename SinglePassRange::iterator>::value_type value_type;

                        BOOST_STATIC_ASSERT(std::numeric_limits<value_type>::is_specialized);

                        sh.update(boost::begin(range), boost::end(range));
                    }

                    operator OutputIterator() const {
                        const auto &result = sh.end_message();

                        return std::move(result.begin(), result.end(), std::move(out));
                    }
                };

                template<typename Hasher, typename OutputIterator, typename StreamHash>
                struct itr_itr_hash_impl : public hash_impl {
                private:
                    mutable StreamHash sh;

                    mutable OutputIterator out;

                public:
                    template<typename InputIterator>
                    explicit itr_itr_hash_impl(InputIterator first, InputIterator last, OutputIterator out,
                                               StreamHash stream_hash) :
                        out(std::move(out)),
                        sh(std::move(stream_hash)) {
                        BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<InputIterator>));

                        typedef typename std::iterator_traits<InputIterator>::value_type value_type;

                        BOOST_STATIC_ASSERT(std::numeric_limits<value_type>::is_specialized);

                        sh.update(first, last);
                    }

                    operator OutputIterator() const {
                        const auto &result = sh.end_message();

                        return std::move(result.begin(), result.end(), std::move(out));
                    }
                };

                /*!
                 * @brief
                 * @tparam Hasher
                 * @tparam Input
                 * @note Such an implementation way is chosen because of no available ways to infer template by
                 * return type are available. So the type implicit conversion is the way.
                 */
                template<typename Hasher, typename Input>
                class hash {
                private:
                    const detail::hash_impl &impl;

                public:
                    template<typename OutputIterator, typename StreamHash>
                    explicit hash(Input first, Input last, OutputIterator out, StreamHash sh) :
                        impl(std::move(detail::itr_itr_hash_impl<Hasher, OutputIterator, StreamHash>(
                            first, last, std::move(out), std::move(sh)))) {
                    }

                    template<typename OutputIterator, typename StreamHash>
                    explicit hash(const Input &range, OutputIterator out, StreamHash sh) :
                        impl(std::move(detail::range_itr_hash_impl<Hasher, OutputIterator, StreamHash>(
                            range, std::move(out), std::move(sh)))) {
                    }

                    template<typename StreamHash>
                    explicit hash(const Input &range, StreamHash sh) :
                        impl(std::move(detail::range_value_hash_impl<Hasher, StreamHash>(range, sh))) {
                    }

                private:
                    template<typename OutputIterator,
                             typename std::enable_if<detail::is_iterator<OutputIterator>::value &&
                                                         detail::is_iterator<Input>::value,
                                                     bool>::type = false>
                    OutputIterator to() const {
                        return static_cast<const detail::itr_itr_hash_impl<
                            Hasher, OutputIterator, detail::iterator_stream_hash_traits<Hasher, Input>> &>(impl);
                    }

                    template<typename OutputIterator,
                             typename std::enable_if<detail::is_iterator<OutputIterator>::value &&
                                                         !detail::is_iterator<Input>::value,
                                                     bool>::type = false>
                    OutputIterator to() const {
                        return static_cast<const detail::range_itr_hash_impl<
                            Hasher, OutputIterator, detail::range_stream_hash_traits<Hasher, Input>> &>(impl);
                    }

                    template<typename OutputRange, typename std::enable_if<!detail::is_iterator<Input>::value &&
                                                                               !detail::is_iterator<OutputRange>::value,
                                                                           bool>::type = false>
                    OutputRange to() const {
                        return static_cast<const detail::range_value_hash_impl<
                            Hasher, detail::range_stream_hash_traits<Hasher, Input>> &>(impl);
                    }

                public:
                    template<typename Output>
                    operator Output() const {
                        return to<Output>();
                    }

                    template<typename Char, typename CharTraits, typename Alloc>
                    operator std::basic_string<Char, CharTraits, Alloc>() const {
                        return static_cast<const detail::range_value_hash_impl<
                            Hasher, detail::range_stream_hash_traits<Hasher, Input>> &>(impl);
                    }
                };

#endif
            }    // namespace detail

            /*!
             * @brief
             *
             * @ingroup hash_algorithms
             *
             * @tparam Hasher
             * @tparam InputIterator
             * @tparam OutputIterator
             * @tparam StreamHash
             * @param first
             * @param last
             * @param out
             * @param sh
             * @return
             */
            template<typename Hasher, typename InputIterator, typename OutputIterator,
                     typename StreamHash = detail::iterator_stream_hash_traits<Hasher, InputIterator>,
                     typename = typename std::enable_if<detail::is_stream_hash<StreamHash>::value>::type>
            OutputIterator hash(InputIterator first, InputIterator last, OutputIterator out,
                                StreamHash sh = StreamHash()) {
                return detail::hash<Hasher, InputIterator>(first, last, std::move(out), std::move(sh));
            };

            /*!
             * @brief
             *
             * @ingroup hash_algorithms
             *
             * @tparam Hasher
             * @tparam InputIterator
             * @tparam StreamHash
             * @param first
             * @param last
             * @param sh
             * @return
             */
            template<typename Hasher, typename InputIterator,
                     typename StreamHash = detail::iterator_stream_hash_traits<Hasher, InputIterator>,
                     typename = typename std::enable_if<detail::is_stream_hash<StreamHash>::value>::type>
            detail::hash<Hasher, InputIterator> hash(InputIterator first, InputIterator last,
                                                     StreamHash sh = StreamHash()) {
                return detail::hash<Hasher, InputIterator>(boost::any_range(first, last), std::move(sh));
            };

            /*!
             * @brief
             *
             * @ingroup hash_algorithms
             *
             * @tparam Hasher
             * @tparam SinglePassRange
             * @tparam OutputIterator
             * @tparam StreamHash
             * @param rng
             * @param out
             * @param sh
             * @return
             */
            template<typename Hasher, typename SinglePassRange, typename OutputIterator,
                     typename StreamHash = detail::range_stream_hash_traits<Hasher, SinglePassRange>,
                     typename = typename std::enable_if<detail::is_stream_hash<StreamHash>::value>::type>
            OutputIterator hash(const SinglePassRange &rng, OutputIterator out, StreamHash sh = StreamHash()) {
                return detail::hash<Hasher, SinglePassRange>(rng, std::move(out), std::move(sh));
            };

            /*!
             * @brief
             *
             * @ingroup hash_algorithms
             *
             * @tparam Hasher
             * @tparam SinglePassRange
             * @tparam StreamHash
             * @param rng
             * @param sh
             * @return
             */
            template<typename Hasher, typename SinglePassRange,
                     typename StreamHash = detail::range_stream_hash_traits<Hasher, SinglePassRange>,
                     typename = typename std::enable_if<detail::is_stream_hash<StreamHash>::value>::type>
            detail::hash<Hasher, SinglePassRange> hash(const SinglePassRange &rng, StreamHash sh = StreamHash()) {
                return detail::hash<Hasher, SinglePassRange>(rng, std::move(sh));
            };
        }    // namespace pbkdf
    }        // namespace crypto3
}    // namespace nil

#endif    // CRYPTO3_PBKDF_HPP


text:
#pragma once

#include <map>
#include <string>
#include <vector>
#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <class_loader/class_loader.h>
#include <base-logging/Singleton.hpp>
#include <glog/logging.h>

#include "PluginManager.hpp"
#include "Exceptions.hpp"

namespace plugin_manager
{

/**
 * @class PluginLoader
 * @brief A singleton class used to load class loader based plugins
 * This class inherits from the PluginManager
 */
class PluginLoader : public PluginManager, public boost::noncopyable
{
    friend class base::Singleton<PluginLoader>;
    typedef std::map<std::string, boost::shared_ptr<class_loader::ClassLoader> > LoaderMap;
    typedef std::map<std::string, boost::shared_ptr<void> > SingletonMap;

public:
    /**
     * @brief Returns the singleton instance of this class
     */
    static PluginLoader* getInstance();

    /**
     * @brief Returns true if the class is registerd
     * @param class_name the name of the plugin class
     * @returns True if class is available
     */
    bool hasClass(const std::string& class_name) const;

    /**
     * @brief Returns true if the class is registerd and inherits from the given base class.
     * @param class_name the name of the plugin class
     * @param base_class_name the name of the base class
     * @returns True if class is available
     */
    bool hasClassOfType(const std::string& class_name, const std::string& base_class_name) const;

    /**
     * @brief Creates an instance of the given class
     * @param class_name the name of the plugin class
     * @param instance pointer to the base class of the class
     * @return True if an instance of the class could be created
     */
    template<class BaseClass>
    bool createInstance(const std::string& class_name, boost::shared_ptr<BaseClass>& instance);

    /**
     * @brief Creates an instance of the given class and tries to down cast to the actual implementation.
     * @param class_name the name of the plugin class
     * @param instance pointer to the instance of the class
     * @return True if an instance of the class could be created
     * @throws DownCastException if the cast from BaseClass to InheritedClass isn't possible
     */
    template<class InheritedClass, class BaseClass>
    bool createInstance(const std::string& class_name, boost::shared_ptr<InheritedClass>& instance);

    /**
     * @brief Adds an additional library path to the set of library paths
     * Note: A set of paths is already looked up by using the environment variable LD_LIBRARY_PATH
     *       when this class is created.
     * @param library_path path to a library folder
     */
    void addLibraryPath(const std::string& library_path);

protected:
    /**
     * @brief Constructor for PluginLoader
     * It is protected because this class is a singleton class.
     * @param auto_load_xml_files if this is false reloadXMLPluginFiles must be triggered by a inherited class or manually
     */
    PluginLoader(bool auto_load_xml_files = true);

    /**
     * @brief Destructor for PluginLoader
     */
    virtual ~PluginLoader();

    /**
     * @brief Loads all paths set in the environment variable LD_LIBRARY_PATH
     *        to the set of library paths.
     */
    void loadLibraryPaths();

    /**
     * @brief Loads the library of the given plugin class
     * @param class_name name of the plugin class
     * @return True if the library could be loaded
     */
    bool loadLibrary(const std::string& class_name);

private:

    /**
     * @brief Uses the class_loader to create a new instance of the given class name.
     *        If the class is marked a singleton, only one instance will be created and
     *        returned on future queries.
     * @param derived_class_name name of the plugin class
     * @param loader the class loader
     * @param instance new or singleton instance
     */
    template<class BaseClass>
    void createInstanceIntern(const std::string& derived_class_name,
                                const boost::shared_ptr<class_loader::ClassLoader>& loader,
                                boost::shared_ptr< BaseClass >& instance);

private:
    /** Mapping between library name and class loader instances */
    LoaderMap loaders;

    /** Singleton instances that have been instantiated */
    SingletonMap singletons;

    /** Set of the known shared library folders */
    std::set<std::string> library_paths;
};

template<class BaseClass>
bool PluginLoader::createInstance(const std::string& class_name, boost::shared_ptr<BaseClass>& instance)
{
    // get library name of the class
    std::string lib_name;
    if(!getClassLibraryPath(class_name, lib_name))
    {
        LOG(ERROR) << "Could not find plugin library for class " << class_name;
        return false;
    }

    // find loader for the class
    LoaderMap::iterator it = loaders.find(lib_name);
    if(it == loaders.end() && loadLibrary(class_name))
        it = loaders.find(lib_name);

    if(it == loaders.end())
    {
        LOG(ERROR) << "Failed to load plugin library " << lib_name;
        return false;
    }

    // try to create an instance of the class
    if(it->second->isClassAvailable<BaseClass>(class_name))
    {
        createInstanceIntern<BaseClass>(class_name, it->second, instance);
        return true;
    }

    if(hasNamespace(class_name))
    {
        // try to create an instance of the class using the class name without namespace
        std::string short_class_name = removeNamespace(class_name);
        if(it->second->isClassAvailable<BaseClass>(short_class_name))
        {
            createInstanceIntern<BaseClass>(short_class_name, it->second, instance);
            return true;
        }
    }
    else
    {
        // try to create an instance of the class using the full class name
        std::string full_class_name;
        if(getFullClassName(class_name, full_class_name) && it->second->isClassAvailable<BaseClass>(full_class_name))
        {
            createInstanceIntern<BaseClass>(full_class_name, it->second, instance);
            return true;
        }
    }

    LOG(ERROR) << "Failed to create and instance of class " << class_name
                << ", it isn't available in the plugin library " << lib_name;
    return false;
}

template<class InheritedClass, class BaseClass>
bool PluginLoader::createInstance(const std::string& class_name, boost::shared_ptr<InheritedClass>& instance)
{
    boost::shared_ptr<BaseClass> base_instance;
    if(!createInstance<BaseClass>(class_name, base_instance))
        return false;

    instance = boost::dynamic_pointer_cast<InheritedClass>(base_instance);
    if(instance == NULL)
        throw DownCastException<InheritedClass, BaseClass>(class_name);
    return true;
}

template<class BaseClass>
void PluginLoader::createInstanceIntern(const std::string& derived_class_name,
                                        const boost::shared_ptr<class_loader::ClassLoader>& loader,
                                        boost::shared_ptr< BaseClass >& instance)
{
    bool singleton = false;
    if(getSingletonFlag(derived_class_name, singleton) && singleton)
    {
        // class is marked as singleton
        SingletonMap::iterator singleton_it = singletons.find(derived_class_name);
        if(singleton_it == singletons.end())
        {
            // create an stores a new instance
            instance = loader->createInstance<BaseClass>(derived_class_name);
            boost::shared_ptr< void > instance_ptr = boost::static_pointer_cast<void>(instance);
            singletons[derived_class_name] = instance_ptr;
        }
        else
        {
            // returns existing instance
            instance = boost::static_pointer_cast<BaseClass>(singleton_it->second);
        }
    }
    else
    {
        // create new instance
        instance = loader->createInstance<BaseClass>(derived_class_name);
    }
}

}

ext: hpp


text:
#ifndef CANNON_PHYSICS_SYSTEMS_SYSTEM_H
#define CANNON_PHYSICS_SYSTEMS_SYSTEM_H

#include <Eigen/Dense>

#include <ompl/config.h>
#include <ompl/control/ODESolver.h>

namespace oc = ompl::control;
namespace ob = ompl::base;

using namespace Eigen;

namespace cannon {
  namespace physics {
    namespace systems {

      class System {
        public:
          virtual void operator()(const VectorXd &s, VectorXd &dsdt,
                                  const double t) = 0;

          virtual void ompl_ode_adaptor(const oc::ODESolver::StateType &q,
                                        const oc::Control *control,
                                        oc::ODESolver::StateType &qdot) = 0;

          virtual std::tuple<MatrixXd, MatrixXd, VectorXd>
          get_linearization(const VectorXd &x) = 0;

          virtual void
          get_continuous_time_linearization(const oc::ODESolver::StateType &q,
                                            Ref<MatrixXd> A,
                                            Ref<MatrixXd> B) = 0;
      };

    } // namespace system
  } // namespace physics
} // namespace cannon

#endif /* ifndef CANNON_PHYSICS_SYSTEMS_SYSTEM_H */

max_stars_repo_name: cannontwo/cannon

max_issues_repo_name: cannontwo/cannon

max_forks_repo_name: cannontwo/cannon


text:
/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Fabio Massaioli
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "compiler.hpp"
#include "node.hpp"
#include "nodes/output.hpp"

#include <nodal/passes/cycle_detection.hpp>
#include <nodal/passes/dead_branch_removal.hpp>
#include <nodal/passes/topological_sort.hpp>

#include <boost/graph/graph_utility.hpp>

#include <algorithm>
#include <forward_list>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

using namespace nodal;

class print_graph_pass : public pass {
public:
    print_graph_pass(std::string const& title) : title(title) {}

    any run(graph& graph, nodal::context&) const override {
        if (!title.empty())
            std::cout << title << std::endl;

        boost::print_graph(graph, boost::get(boost::vertex_name, graph));

        std::cout << std::endl;

        return {};
    };

private:
    std::string title;
};

class type_check_pass : public pass {
public:
    any run(graph& graph, nodal::context&) const override {
        auto nodes = graph.nodes();
        for (auto n = nodes.first; n != nodes.second; ++n) {
            if (!dynamic_cast<::node const*>((*n)->node()))
                throw compiler_error("Invalid node found in graph");
        }

        return {};
    }
};

using sort_pass = topological_sort_pass<std::forward_list<graph_node*>>;

class compilation_pass : public pass {
public:
    using result_type = graph_fn;

    struct compiled_node {
        using link = std::pair<std::size_t, std::size_t>;

        compiled_node(node_fn&& fn, std::size_t input_offset,
                      std::vector<link>&& links = {})
            : fn(std::move(fn)), input_offset(input_offset),
              links(std::move(links))
            {}

        node_fn fn;
        std::size_t input_offset;
        std::vector<std::pair<std::size_t, std::size_t>> links;
    };

    any run(graph& graph, nodal::context& ctx) const override {
        auto& sorted_nodes = ctx.pass<sort_pass>();

        std::vector<compiled_node> compiled_nodes;
        bool graph_has_outputs = false;
        std::size_t graph_output_count = 0;

        std::unordered_map<graph_node*, std::size_t> node_index;
        std::size_t i = 0, input_offset = 0;

        for (auto n : sorted_nodes) {
            compiled_nodes.emplace_back(
                n->node()->cast<::node>()->compile(n->data()), input_offset);

            node_index[n] = i++;

            auto links = graph.input_links(n);
            for (auto link = links.first; link != links.second; ++link) {
                compiled_nodes[node_index[link->source_node]]
                    .links.emplace_back(link->source_socket,
                                        link->target_socket + input_offset);
            }

            input_offset += n->node()->input_count();

            if (dynamic_cast<output_node const*>(n->node())) {
                graph_has_outputs = true;
                graph_output_count = std::max(graph_output_count,
                                              n->data()->param<std::size_t>(0));
            }
        }

        if (graph_has_outputs) {
            if (graph_output_count ==
                std::numeric_limits<decltype(graph_output_count)>::max()) {
                throw compiler_error("Too many outputs required");
            }

            ++graph_output_count;
        }

        std::shared_ptr<double> input_data(new double[input_offset],
                                           std::default_delete<double[]>());

        for (auto const& n : node_index) {
            input_offset = compiled_nodes[n.second].input_offset;
            for (i = 0; i < n.first->node()->input_count(); ++i)
                input_data.get()[input_offset + i] =
                    n.first->data()->input<double>(i);
        }

        graph_fn result = [graph_output_count, input_data,
                           compiled_nodes](double* graph_inputs) {
            ::context context = {
                graph_inputs,
                graph_output_count ? new double[graph_output_count] : nullptr
            };

            for (auto const& c : compiled_nodes) {
                auto outputs = c.fn(&input_data.get()[c.input_offset], context);

                for (auto const& l : c.links)
                    input_data.get()[l.second] = outputs[l.first];

                if (outputs)
                    delete[] outputs;
            }

            return context.outputs;
        };

        return std::move(result);
    }
};

compiler create_compiler() {
    return { new print_graph_pass("Compiler input:"),
             new type_check_pass,
             new cycle_detection_pass([](graph_link const&, graph const&) {
                 throw compiler_error("Link cycle detected");
             }),
             new dead_branch_removal_pass([](graph_node const* n) {
                 return n->node()->cast<::node>()->keep();
             }),
             new print_graph_pass("Optimized graph:"),
             new sort_pass,
             new compilation_pass };
}

ext: cpp

max_stars_repo_name: fbbdev/nodal

max_issues_repo_name: fbbdev/nodal

max_forks_repo_name: nodal/nodal


text:
// Boost.Range 2.0 Extension library
// via PStade Oven Library
//
// Copyright Akira Takahashi 2011.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <boost/detail/lightweight_test.hpp>
#include <boost/range/algorithm/equal.hpp>

#include <vector>
#include <deque>
#include <list>

#include <boost/assign/list_of.hpp>
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/as_container.hpp>

bool is_odd(int x) { return x % 2 == 0; }

template <class Container>
void test()
{
    // pipe operator style
    {
        const Container c1 = boost::assign::list_of(1)(2)(3)(4)(5);

        const Container c2 = c1 | boost::adaptors::filtered(is_odd) | boost::as_container;

        BOOST_TEST(boost::equal(
            c2,
            boost::assign::list_of(2)(4)
        ));

        Container c3;
        c3 = c1 | boost::adaptors::filtered(is_odd) | boost::as_container;

        BOOST_TEST(boost::equal(
            c3,
            boost::assign::list_of(2)(4)
        ));
    }

    // function style
    {
        const Container c1 = boost::assign::list_of(1)(2)(3)(4)(5);
        const Container c2 = boost::as_container(boost::adaptors::filter(c1, is_odd));

        BOOST_TEST(boost::equal(
            c2,
            boost::assign::list_of(2)(4)
        ));

        Container c3;
        c3 = boost::as_container(boost::adaptors::filter(c1, is_odd));

        BOOST_TEST(boost::equal(
            c3,
            boost::assign::list_of(2)(4)
        ));
    }
}

int main()
{
    test<std::vector<int> >();
    test<std::deque<int> >();
    test<std::list<int> >();

    return boost::report_errors();
}

max_stars_repo_name: Flast/OvenToBoost

max_issues_repo_name: Flast/OvenToBoost

max_forks_repo_name: Flast/OvenToBoost


text:
//  Copyright Neil Groves 2009. Use, modification and
//  distribution is subject to the Boost Software License, Version
//  1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_ALGORITHM_PARTITION__HPP_INCLUDED
#define BOOST_RANGE_ALGORITHM_PARTITION__HPP_INCLUDED

#include <boost/concept_check.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/concepts.hpp>
#include <boost/range/detail/range_return.hpp>
#include <algorithm>

namespace boost
{
    namespace range
    {

/// \brief template function partition
///
/// range-based version of the partition std algorithm
///
/// \pre ForwardRange is a model of the ForwardRangeConcept
template<class ForwardRange, class UnaryPredicate>
inline BOOST_DEDUCED_TYPENAME range_iterator<ForwardRange>::type
partition(ForwardRange& rng, UnaryPredicate pred)
{
    BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<ForwardRange> ));
    return std::partition(boost::begin(rng),boost::end(rng),pred);
}

/// \overload
template<class ForwardRange, class UnaryPredicate>
inline BOOST_DEDUCED_TYPENAME range_iterator<ForwardRange>::type
partition(const ForwardRange& rng, UnaryPredicate pred)
{
    BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<const ForwardRange> ));
    return std::partition(boost::begin(rng),boost::end(rng),pred);
}

// range_return overloads

/// \overload
template< range_return_value re, class ForwardRange,
          class UnaryPredicate >
inline BOOST_DEDUCED_TYPENAME range_return<ForwardRange,re>::type
partition(ForwardRange& rng, UnaryPredicate pred)
{
    BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<ForwardRange> ));
    return boost::range_return<ForwardRange,re>::
        pack(std::partition(boost::begin(rng), boost::end(rng), pred), rng);
}

/// \overload
template< range_return_value re, class ForwardRange,
          class UnaryPredicate >
inline BOOST_DEDUCED_TYPENAME range_return<const ForwardRange,re>::type
partition(const ForwardRange& rng, UnaryPredicate pred)
{
    BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<const ForwardRange> ));
    return boost::range_return<const ForwardRange,re>::
        pack(std::partition(boost::begin(rng), boost::end(rng), pred), rng);
}

    } // namespace range
    using range::partition;
} // namespace boost

#endif // include guard


text:
#pragma once

#include <deal.II/base/tensor.h>
#include <complex>
#include <functional>
#include "aux/tensor_helpers.hpp"

namespace boltzmann {

template <int dim>
class QTrapz;
namespace _ {

template <class T>
struct NumberTraits;

template <int dim, int rank, class NUMBER>
struct NumberTraits<dealii::Tensor<dim, rank, NUMBER> >
{
  typedef NUMBER numeric_t;
};

template <>
struct NumberTraits<double>
{
  typedef double numeric_t;
};

template <>
struct NumberTraits<std::complex<double> >
{
  typedef std::complex<double> numeric_t;
};

}  // end namespace

template <>
class QTrapz<1>
{
 public:
  QTrapz(int npts, double a, double b);

  template <class NUMBER>
  NUMBER compute(const std::function<NUMBER(double)>& f) const;

  const std::vector<double>& get_weights() { return weights_; }

  const std::vector<double>& get_points() { return points_; }

 private:
  const double a;
  const double b;
  const int npts;
  std::vector<double> points_;
  std::vector<double> weights_;
};

/**
 * trapezoidal quadrature rule, works also with tensor valued functions
 *
 *
 * @return
 */
template <class NUMBER>
NUMBER
qtrapz1d(const std::function<NUMBER(double)>& f, double a, double b, int npts)
{
  typedef typename _::NumberTraits<NUMBER>::numeric_t numeric_t;
  const double h = (b - a) / double(npts - 1);

  NUMBER sum = 0;
  for (int i = 0; i < npts - 1; ++i) {
    const double x1 = a + h * (i);
    const double x2 = a + h * (i + 1);
    sum += f(x1) + f(x2);
  }
  sum *= numeric_t(0.5 * h);
  return sum;
}

QTrapz<1>::QTrapz(int npts, double a, double b)
    : a(a)
    , b(b)
    , npts(npts)
    , points_(npts)
    , weights_(npts)
{
  double h = (b - a) / (npts - 1);
  for (int i = 0; i < npts; ++i) {
    if (i == 0 || i == npts - 1)
      weights_[i] = 0.5 * h;
    else
      weights_[i] = h;
    points_[i] = a + i * h;
  }
}

}  // end namespace boltzmann


text:
/*******************************************************************************
 *         Copyright 2003-2010 LASMEA UMR 6602 CNRS/U.B.P
 *         Copyright 2009-2010 LRI    UMR 8623 CNRS/Univ Paris Sud XI
 *
 *          Distributed under the Boost Software License, Version 1.0.
 *                 See accompanying file LICENSE.txt or copy at
 *                     http://www.boost.org/LICENSE_1_0.txt
 ******************************************************************************/
#ifndef NT2_SDK_SIMD_PACK_EXPRESSION_HPP_INCLUDED
#define NT2_SDK_SIMD_PACK_EXPRESSION_HPP_INCLUDED

#include <boost/proto/proto.hpp>
#include <nt2/sdk/dsl/category.hpp>
#include <nt2/sdk/dsl/is_assignment_expression.hpp>

namespace nt2 { namespace container
{
  ////////////////////////////////////////////////////////////////////////////
  // Here is the domain-specific expression wrapper for table_ expression
  ////////////////////////////////////////////////////////////////////////////
  template<class Expr, class Dims>
  struct  expression<Expr,tag::table_,Dims>
        : boost::proto::extends < Expr
                                , expression<Expr,tag::table_,Dims>
                                , container::domain<tag::table_,Dims>
                                >
  {
    ////////////////////////////////////////////////////////////////////////////
    // Internal proto related types
    ////////////////////////////////////////////////////////////////////////////
    typedef boost::proto::extends < Expr
                                  , expression<Expr,tag::table_,Dims>
                                  , container::domain<tag::table_,Dims>
                                  >                                     parent;

    ////////////////////////////////////////////////////////////////////////////
    // expression hierarchy and semantic of container:::expression
    ////////////////////////////////////////////////////////////////////////////
    typedef typename
    details::hierarchy_of_expr<expression>::type nt2_hierarchy_tag;

    ////////////////////////////////////////////////////////////////////////////
    // Default explicit constructor
    ////////////////////////////////////////////////////////////////////////////
    explicit  expression( Expr const& xpr = Expr() )
            : parent(xpr), is_silent(false)
    {
      // If Expr is an assignment node, set xpr.is_evaluable to false
      //if(meta::is_assignment_expression<Expr>::value)
      //  boost::proto::right(*this).silence();
    }

    ////////////////////////////////////////////////////////////////////////////
    // Destructor performs evaluation if required
    ////////////////////////////////////////////////////////////////////////////
    ~expression()
    {
      // If *this is not silent, evaluates it
      if(!is_silent) (*this)();
    }

    ////////////////////////////////////////////////////////////////////////////
    // table expression are read-only Ranges
    ////////////////////////////////////////////////////////////////////////////

    ////////////////////////////////////////////////////////////////////////////
    // table expression have a n-ary operator()
    ////////////////////////////////////////////////////////////////////////////

    ////////////////////////////////////////////////////////////////////////////
    // table expression have a nullary operator() that evaluates itself
    ////////////////////////////////////////////////////////////////////////////
    void operator()()
    {
      // current_target::evaluate(*this);
    }

    ////////////////////////////////////////////////////////////////////////////
    // table expression have an operator[] that adds specific settings
    ////////////////////////////////////////////////////////////////////////////
    template<class Settings>
    expression& operator[](Settings const& )
    {
      // ????
      return *this;
    }

    ////////////////////////////////////////////////////////////////////////////
    // External accessor for evaluation trigger
    ////////////////////////////////////////////////////////////////////////////
    void silence() const { is_silent = true; }

    protected:
    ////////////////////////////////////////////////////////////////////////////
    // Trigger for non-evaluation at destruction-time.
    ////////////////////////////////////////////////////////////////////////////
    mutable bool is_silent;
  };
} }

#endif


text:
#include "ode/odeint.hpp"

/// Integrate routines
#include <boost/numeric/odeint/integrate/integrate.hpp>

namespace SOS {
    namespace ODE {
        namespace odeint = boost::numeric::odeint;

        Real Odeint::eval_ode(Ode_id ode_id_, Dt_id dt_id_,
                              Context&& context_) const
        {
            State x = move(context_.cx_init());
            auto f = [this, ode_id_, dt_id_]
                         (const State& x_, State& dx_, Time t_){
                         eval_ode_step(ode_id_, dt_id_,
                                       dx_[def_dt_id], x_, t_);
                     };
            integrate(f, x, context_.ct_init(), context_.ct_end(),
                      traject(ode_id_));
            return x[def_dt_id];
        }

        State Odeint::eval_unif_odes(Dt_ids&& dt_ids_,
                                     Context&& context_) const
        {
            State x = move(context_.cx_init());
            auto f = [this, &dt_ids_](const State& x_, State& dx_, Time t_){
                         eval_unif_odes_step(dt_ids_, dx_, x_, t_);
                     };
            integrate(f, x, context_.ct_init(), context_.ct_end(),
                      traject());
            return x;
        }

        size_t Odeint::integrate(Integrate_f f, State& x,
                                 Time t_init_, Time t_end_,
                                 Traject& traject_) const
        {
            auto observer = [&traject_](const State& x_, Time t_){
                traject_.add_step(x_, t_);
            };

            size_t n_steps = odeint::integrate(f, x,
                                               t_init_, t_end_,
                                               cstep_size(),
                                               observer);
            return n_steps;
        }
    }
}

max_stars_repo_name: Tomaqa/sos

max_issues_repo_name: Tomaqa/sos

max_forks_repo_name: Tomaqa/sos


text:
#ifndef _CHART_INTERFACE_HPP
#define _CHART_INTERFACE_HPP

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

#include <string>
#include <boost/document/detail/chart_type.hpp>
#include <boost/document/detail/chart_axis.hpp>

namespace boost {

	class chart_interface {
	 public:
    virtual void set_title(const std::string& title) = 0;
    virtual void set_legend(bool set) = 0;
		virtual void set_type(boost::chart_type::type t, bool enable_3d) = 0;
		virtual void set_axis_title(boost::chart_axis::type t, const std::string& title) = 0;
		virtual void set_axis_orientation(boost::chart_axis::type t, bool set) = 0;
		virtual void set_range(const std::string& cell_range) = 0;
		virtual void set_position(std::size_t top, std::size_t left) = 0;
		virtual void set_size(std::size_t width, std::size_t height) = 0;
		virtual ~chart_interface() {}
	};
} // namespace boost

#endif

max_stars_repo_name: anuragxel/generic-document-library

max_issues_repo_name: anuragxel/generic-document-library

max_forks_repo_name: anuragxel/generic-document-library


text:
#include <iostream>
#include <fstream>

#include <boost/filesystem.hpp>
#include <boost/array.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include "avhttp.hpp"

class downloader : public boost::enable_shared_from_this<downloader>
{
public:
	downloader(boost::asio::io_service &io)
		: m_io_service(io)
		, m_stream(io)
	{}
	~downloader()
	{}

public:
	void start(const std::string &url)
	{
		avhttp::proxy_settings p;
		p.type = avhttp::proxy_settings::http;
		p.hostname = "218.188.13.237";
		p.port = 8888;

		// 设置代理服务器.
		// m_stream.proxy(p);

		// 设置处理https不进行认证.
		m_stream.check_certificate(false);

		avhttp::request_opts opt;
		opt.insert(avhttp::http_options::accept_encoding, "gzip");
		// 设置接受gzip格式, 需要启用AVHTTP_ENABLE_ZLIB.
		// m_stream.request_options(opt);

		m_stream.async_open(url,
			boost::bind(&downloader::handle_open, shared_from_this(), boost::asio::placeholders::error));
	}

	void handle_open(const boost::system::error_code &ec)
	{
		if (!ec)
		{
			m_stream.async_read_some(boost::asio::buffer(m_buffer, 1024),
					boost::bind(&downloader::handle_read, shared_from_this(),
					boost::asio::placeholders::bytes_transferred,
					boost::asio::placeholders::error
				)
			);
//			也可以:
// 			boost::asio::async_read(m_stream, boost::asio::buffer(m_buffer, 597),
// 				boost::bind(&downloader::handle_read, shared_from_this(),
// 				boost::asio::placeholders::bytes_transferred,
// 				boost::asio::placeholders::error));
		}
	}

	void handle_read(int bytes_transferred, const boost::system::error_code &ec)
	{
		if (!ec)
		{
			std::cout.write(m_buffer.data(), bytes_transferred);
			m_stream.async_read_some(boost::asio::buffer(m_buffer),
					boost::bind(&downloader::handle_read, shared_from_this(),
					boost::asio::placeholders::bytes_transferred,
					boost::asio::placeholders::error
				)
			);
		}
		else if (ec == boost::asio::error::eof)
		{
			std::cout.write(m_buffer.data(), bytes_transferred);
		}
		std::cout.flush();
	}

private:
	boost::asio::io_service &m_io_service;
	avhttp::http_stream m_stream;
	boost::array<char, 1024> m_buffer;
};

int main(int argc, char* argv[])
{
	if (argc != 2)
	{
		std::cerr << "usage: " << argv[0] << " <url>\n";
		std::cerr << "usage: " << argv[0] << " <url_list.txt>\n";
		return -1;
	}

	boost::asio::io_service io;
	std::fstream file;
	std::string filename = argv[1];
	bool urllist = false;

	// 如果是存在的文件, 则查看是否是txt文件, 允许.txt文件中多个url.
	// 在一个txt文件中可以保存多行url, 比如文件urls.txt中可以是:
	// http://www.boost.org/LICENSE_1_0.txt
	// http://www.microsoft.com/en-us/default.aspx
	// 本程序将同时下载这两个链接, 并且是单线程的哦!!!
	if (boost::filesystem::exists(filename))
	{
		if (boost::filesystem::extension(filename) == ".txt")
		{
			urllist = true;
			file.open(filename.c_str());
		}
	}

	for (;;)
	{
		if (!urllist)	// 单个文件下载.
		{
			boost::shared_ptr<downloader> d(new downloader(io));
			d->start(filename);
			break;
		}
		else			// 从url列表中下载, txt文件中的每一行是一个url.
		{
			std::string url;
			std::getline(file, url);
			if (url.empty())
				break;
			boost::shared_ptr<downloader> d(new downloader(io));
			d->start(url);
		}
	}

	io.run();

	return 0;
}

max_stars_repo_name: k-stolyarov/avhttp

max_issues_repo_name: k-stolyarov/avhttp

max_forks_repo_name: k-stolyarov/avhttp


text:
/** find_mldb_environment.cc
    Jeremy Barnes, 26 August 2018
    Copyright (c) 2018 mldb.ai inc.  All rights reserved.
    This file is part of MLDB. Copyright 2018 mldb.ai inc. All rights reserved.

    Functionality to find, from a Python interpreter, the active MLDB
    environment and make it available to the rest of the Python machinery.

    In the case that we're importing MLDB from a Python program that runs
    under MLDB, then the environment is MLDB itself.

    In the case that we're importing MLDB directly from Python itself (by
    running a script directly), then we need to create the environment, and
    eventually hook it up to the inbuilt Python functionality for things
    like making network connections, etc.

    The goal is to make all Python code be the same no matter what the
    environment it runs in, and have this code do the work of handling the
    different environments.
*/

// Python includes aren't ready for c++17 which doesn't support register
#define register

#include <Python.h>
#include "mldb/builtin/python/pointer_fix.h" //must come before boost python
#include <boost/python.hpp>
#include "mldb/compiler/compiler.h"
#include <dlfcn.h>

#include "mldb/builtin/python/python_plugin_context.h"

using namespace std;
using namespace MLDB;

namespace MLDB {

/** MLDB environment search functions.

    This module exports a single python-callable function: findEnvironment().
    That function is responsible for finding or creating an MLDB environment
    for the currently active Python interpreter; it will always be called
    with the GIL held.  There are two main contexts in which it must work:
    firstly, when called from the mldb_runner executable (a standalone MLDB
    environment) that has an embedded Python runtime, and secondly when called
    from the Python executable that has imported MLDB and therefore needs an
    embedded MLDB runtime.  In other words, in one situation MLDB embeds Python
    and in the other situation Python embeds MLDB, but we want the two to
    appear identical to the Python code.

    That will call the findEnvironmentImpl() function.  If MLDB is already
    in the current process, then the weak version defined here (which always
    finds no environment) will be overridden with a stronger one from
    mldb_python_context.cc, which will look for the MldbPythonInterpreter
    that owns the current Python interpreter and return that.  If MLDB is
    not already in process, then findEnvironmentImpl() will return a null
    pointer; that is the behaviour of the default (weak) implementation here;
    this should only happen when the executable is python rather than mldb.

    In the case that the findEnvironment() function will perform the following
    steps to enable MLDB to be loaded:

    1.  Dynamic load libmldb_platform_python.so, which contains everything
        necessary to create an MldbEngine instance hooked into the Python.
        This will also load the entire set of MLDB runtime libraries.
    2.  Find the MLDB::getPythonEnvironment() function exported by that module.
    3.  Call that function to create an MldbEngine instance and a
        PythonPluginContext instance, which are then returned to the calling
        function.

    Finally, note that the library must be loaded by Python with RTLD_GLOBAL,
    or otherwise the symbols will be duplicated and typecasting, Any conversion
    and exception handling won't work (all of which MLDB relies on extensively).
*/

// This is defined in the MLDB server
extern std::mutex dlopenMutex;

std::shared_ptr<MldbPythonContext>
findEnvironmentImpl() MLDB_WEAK_FN;

std::shared_ptr<MldbPythonContext>
findEnvironmentImpl()
{
    return nullptr;
}

typedef std::shared_ptr<MldbPythonContext> (*FindEnvironmentFn) ();

/// See above for description.
/// Returns a pair with the function pointer and a handle that will unload the library
/// once released.
static std::pair<FindEnvironmentFn, std::shared_ptr<void> >
loadPythonEnvironment()
{
    std::shared_ptr<void> result;

    std::unique_lock<std::mutex> guard(dlopenMutex);

    string path = "libmldb_platform_python.so";

    dlerror();  // clear existing error

    void * handle = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL);
    if (!handle) {
        char * error = dlerror();
        throw Exception("Error loading python platform library " + path + ": "
                        + error);
    }

    FindEnvironmentFn fn = (FindEnvironmentFn)dlsym(handle, "_ZN4MLDB20getPythonEnvironmentEv");
    result.reset(handle, dlclose);
    if (!result) {
        throw Exception("Error loading python platform library " + path + ": no symbol "
                        " getPythonEnvironment defined");
    }

    return {fn, result};
}

static std::shared_ptr<MldbPythonContext>
findEnvironment()
{
    auto res = findEnvironmentImpl();
    if (res) {
        return res;
    }

    // We need to dlopen a separate library to create and initialize an MLDB instance that
    // is specialized for Python
    static auto env = loadPythonEnvironment();
    return (*env.first)();
}

} // namespace MLDB

BOOST_PYTHON_MODULE(_mldb)
{
    boost::python::def("find_mldb_environment", findEnvironment);
}

ext: cc

max_stars_repo_name: kstepanmpmg/mldb

max_issues_repo_name: tomzhang/mldb

max_forks_repo_name: matebestek/mldb


text:
/**
 * Copyright (c) 2018, University Osnabrück
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the University Osnabrück nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL University Osnabrück BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

 /*
 * Options.h
 *
 *  Created on: Nov 21, 2010
 *      Author: Thomas Wiemann
 */

#ifndef OPTIONS_H_
#define OPTIONS_H_

#include <iostream>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
#include <float.h>

#include "lvr2/config/BaseOption.hpp"

using std::ostream;
using std::cout;
using std::endl;
using std::string;
using std::vector;

namespace reconstruct
{

/**
 * @brief A class to parse the program options for the reconstruction
 *        executable.
 */
class Options : public lvr2::BaseOption{
public:

    /**
     * @brief   Ctor. Parses the command parameters given to the main
     *          function of the program
     */
    Options(int argc, char** argv);
    virtual ~Options();

    /**
     * @brief   Returns the given voxelsize
     */
    float   getVoxelsize()const;

    /**
     * @brief   Returns the number of used threads
     */
    int     getNumThreads() const;

    /**
     * @brief   Prints a usage message to stdout.
     */
    bool    printUsage() const;

    /**
     * @brief   Returns true if an output filen name was set
     */
    bool    filenameSet() const;

    /**
     * @brief   Returns true if the face normals of the
     *          reconstructed mesh should be saved to an
     *          extra file ("face_normals.nor")
     */
    bool    saveFaceNormals() const;

    /**
     *@brief    Returns true of region coloring is enabled.
     */
    bool    colorRegions() const;

    /**
     * @brief   Returns true if the interpolated normals
     *          should be saved in the putput file
     */
    bool    saveNormals() const;

    /**
     * @brief   Returns true if the Marching Cubes grid should be save
     */
    bool    saveGrid() const;

    /**
     * @brief   Returns true if the original points should be stored
     *          together with the reconstruction
     */
    bool    saveOriginalData() const;

    /**
     * @brief   Returns true if cluster optimization is enabled
     */
    bool    optimizePlanes() const;

    /**
     * @brief   Indicates whether to save the used points
     *          together with the interpolated normals.
     */
    bool    savePointNormals() const;

    /**
     * @brief   If true, normals should be calculated even if
     *          they are already given in the input file
     */
    bool    recalcNormals() const;

    /**
     * @brief   If true, RANSAC based normal estimation is used
     */
    bool    useRansac() const;

    /**
     * @brief   True if texture analysis is enabled
     */
    bool    doTextureAnalysis() const;

    /**
     * @brief   If true, textures will be generated during
     *          finalization of mesh.
     */
    bool    generateTextures() const;

    /**
     * @brief   Returns the number of neighbors
     *          for normal interpolation
     */
    int     getKi() const;

    /**
     * @brief   Returns the number of neighbors used for
     *          initial normal estimation
     */
    int     getKn() const;

    /**
     * @brief   Returns the number of neighbors used for distance
     *          function evaluation
     */
    int     getKd() const;

    /**
      * @brief Return whether the mesh should be retesselated or not.
      */
    bool      retesselate() const;

    /**
     * @brief  True if region clustering without plane optimization is required.
     */
    bool    clusterPlanes() const;

    /**
     * @brief  True if region clustering without plane optimization is required.
     */
    bool    writeClassificationResult() const;

    /**
     * @brief   Returns the input file name
     */
    string  getInputFileName() const;

    /**
     * @brief   Returns the output file name
     */
    string  getOutputFileName() const;

    /**
     * @brief   Returns the output file names
     */
    vector<string>  getOutputFileNames() const;

    /**
     * @brief   Returns the name of the classifier used to color the mesh
     */
    string  getClassifier() const;

    /**
     * @brief   Returns the name of the given file with scan poses used for normal flipping.
     */
    string  getScanPoseFile() const;

    /**
     * @brief   Returns the number of intersections. If the return value
     *          is positive it will be used for reconstruction instead of
     *          absolute voxelsize.
     */
    int     getIntersections() const;

    /**
     * @brief   Returns to number plane optimization iterations
     */
    int getPlaneIterations() const;

    /**
     * @brief   Returns the name of the used point cloud handler.
     */
    string getPCM() const;

    /**
     * @brief   Returns the name of the used point cloud handler.
     */
    string getDecomposition() const;

    /**
     * @brief   Returns the normal threshold for plane optimization.
     */
    float getNormalThreshold() const;

    /**
     * @brief   Returns the threshold for the size of small
     *          region deletion after plane optimization.
     */
    int   getSmallRegionThreshold() const;

    /**
     * @brief   Minimum value for plane optimzation
     */
    int   getMinPlaneSize() const;

    /**
     * @brief   Number of iterations for contour cleanup
     */
    int   getCleanContourIterations() const;

    /**
     * @brief   Returns the number of dangling artifacts to remove from
     *          a created mesh.
     */
    int   getDanglingArtifacts() const;

    /**
     * @brief   Returns the region threshold for hole filling
     */
    int   getFillHoles() const;

    /**
     * @brief   Returns the texel size for texture resolution
     */
    float getTexelSize() const;

    /**
     * @brief   Returns the sharp feature threshold when using sharp feature decomposition
     */
    float getSharpFeatureThreshold() const;

    /**
         * @brief   Returns the sharp corner threshold when using sharp feature decomposition
         */
    float getSharpCornerThreshold() const;

    /**
     * @brief   Returns the fusion threshold for tesselation
     */
    float getLineFusionThreshold() const;

    /**
     * @brief   Whether to extend the grid. Enable by default.
     */
    bool extrude() const;

    /**
     * @brief Reduction ratio for mesh reduction via edge collapse
     */
    float getEdgeCollapseReductionRatio() const;

    unsigned int getNumStatsColors() const;

    unsigned int getNumCCVColors() const;

    unsigned int getCoherenceThreshold() const;

    float getColorThreshold() const;

    float getStatsThreshold() const;

    float getFeatureThreshold() const;

    bool getUseCrossCorr() const;

    float getPatternThreshold() const;

    float* getStatsCoeffs()const;

    string getTexturePack() const;

    int getMinimumTransformationVotes() const;

    int getTexMinClusterSize() const;

    int getTexMaxClusterSize() const;

    bool vertexColorsFromPointcloud() const;

    bool useGPU() const;

    vector<float> getFlippoint() const;

    bool texturesFromImages() const;

    string getProjectDir() const;

private:

    /// The set voxelsize
    float                           m_voxelsize;

    /// The number of uesed threads
    int                             m_numThreads;

    /// The putput file name for face normals
    string                          m_faceNormalFile;

    /// The number of used default values
    int                             m_numberOfDefaults;

    /// The number of neighbors for distance function evaluation
    int                             m_kd;

    /// The number of neighbors for normal estimation
    int                             m_kn;

    /// The number of neighbors for normal interpolation
    int                             m_ki;

    /// The number of intersections used for reconstruction
    int                             m_intersections;

    /// Whether or not the mesh should be retesselated while being finalized
    bool                          m_retesselate;

    /// Whether or not the mesh should be retesselated while being finalized
    bool                           m_generateTextures;

    /// Whether or not the classifier shall dump meta data to a file 'clusters.clu'
    bool                           m_writeClassificationResult;

    /// The used point cloud manager
    string                          m_pcm;

    /// Number of iterations for plane optimzation
    int                             m_planeIterations;

    /// Threshold for plane optimization
    float                           m_planeNormalThreshold;

    /// Threshold for small ragions
    int                             m_smallRegionThreshold;

    /// Number of dangling artifacts to remove
    int                             m_rda;

    /// Threshold for hole filling
    int                             m_fillHoles;

    /// Threshold for plane optimization
    int                             m_minPlaneSize;

    int                             m_cleanContourIterations;

    /// Texel size
    float                           m_texelSize;

    /// Threshold for line fusing when tesselating
    float                           m_lineFusionThreshold;

    /// Sharp feature threshold when using sharp feature decomposition
    float                           m_sft;

    /// Sharp corner threshold when using sharp feature decomposition
    float                           m_sct;

    /// Name of the classifier object to color the mesh
    string                          m_classifier;

    /// Reduction ratio for mesh reduction via edge collapse
    float                           m_edgeCollapseReductionRatio;

    ///Path to texture pack
    string m_texturePack;

    ///Coefficents file for texture matching based on statistics
    string m_statsCoeffs;

    ///Number of colors for texture statistics
    unsigned int m_numStatsColors;

    ///Number of colors for texture matching based on color information
    unsigned int m_numCCVColors;

    ///Coherence threshold for texture matching based on color information
    unsigned int m_coherenceThreshold;

    ///Threshold for texture matching based on colors
    float m_colorThreshold;

    ///Threshold for texture matching based on statistics
    float m_statsThreshold;

    ///Threshold for texture matching based on features
    float m_featuresThreshold;

    ///Whether to use texture matching based on cross correlation
    bool m_useCrossCorr;

    ///Threshold for pattern extraction from textures
    float m_patternThreshold;

    ///Minimum number of vote to consider a texture transformation as "correct"
    int m_minimumTransformationVotes;

    ///Minimum number of textures of a cluster needed for generating textures
    int m_texMinClusterSize;

    int m_texMaxClusterSize;

    ///Use pointcloud colors to paint vertices
    bool m_vertexColorsFromPointcloud;

    // Flippoint for gpu normal calculation
    vector<float> m_flippoint;

};

/// Overlaoeded outpur operator
inline ostream& operator<<(ostream& os, const Options &o)
{
    o.printTransformation(os);

    if(o.getIntersections() > 0)
    {
        cout << "##### Intersections \t\t: " << o.getIntersections() << endl;
    }
    else
    {
        cout << "##### Voxelsize \t\t: " << o.getVoxelsize() << endl;
    }
    cout << "##### Number of threads \t: "    << o.getNumThreads()      << endl;
    cout << "##### Point cloud manager \t: " << o.getPCM()             << endl;
    if(o.useRansac())
    {
        cout << "##### Use RANSAC\t\t: YES" << endl;
    }
    else
    {
        cout << "##### Use RANSAC\t\t: NO" << endl;
    }

    cout << "##### Voxel decomposition: \t: " << o.getDecomposition()   << endl;
    cout << "##### Classifier:\t\t: "         << o.getClassifier()      << endl;
    if(o.writeClassificationResult())
    {
        cout << "##### Dump classification\t: YES" << endl;
    }
    else
    {
        cout << "##### Dump classification\t: NO" << endl;
    }
    cout << "##### k_n \t\t\t: "              << o.getKn()              << endl;
    cout << "##### k_i \t\t\t: "              << o.getKi()              << endl;
    cout << "##### k_d \t\t\t: "              << o.getKd()              << endl;
    if(o.getDecomposition() == "SF")
    {
        cout << "##### Sharp feature threshold \t: " << o.getSharpFeatureThreshold() << endl;
        cout << "##### Sharp corner threshold \t: " << o.getSharpCornerThreshold() << endl;
    }
    if(o.retesselate())
    {
        cout << "##### Retesselate \t\t: YES"     << endl;
        cout << "##### Line fusion threshold \t: " << o.getLineFusionThreshold() << endl;
    }
    if(o.saveFaceNormals())
    {
        cout << "##### Write Face Normals \t: YES" << endl;
    }

    if(o.getFillHoles())
    {
        cout << "##### Fill holes \t\t: " << o.getFillHoles() << endl;
    }
    else
    {
        cout << "##### Fill holes \t\t: NO" << endl;
    }

    if(o.getDanglingArtifacts())
    {
        cout << "##### Remove DAs \t\t: " << o.getDanglingArtifacts() << endl;
    }
    else
    {
        cout << "##### Remove DAs \t\t: NO" << endl;
    }

    if(o.optimizePlanes())
    {
        cout << "##### Optimize Planes \t\t: YES" << endl;
        cout << "##### Plane iterations\t\t: " << o.getPlaneIterations() << endl;
        cout << "##### Normal threshold \t\t: " << o.getNormalThreshold() << endl;
        cout << "##### Region threshold\t\t: " << o.getSmallRegionThreshold() << endl;
        cout << "##### Region min size\t\t: " << o.getMinPlaneSize() << endl;
    }
    if(o.saveNormals())
    {
        cout << "##### Save normals \t\t: YES" << endl;
    }
    if(o.saveOriginalData())
    {
        cout << "##### Save input data \t\t: YES" << endl;
    }

    if(o.recalcNormals())
    {
        cout << "##### Recalc normals \t\t: YES" << endl;
    }
    if(o.savePointNormals())
    {
        cout << "##### Save points normals \t: YES" << endl;
    }
    if(o.vertexColorsFromPointcloud())
    {
        cout << "##### Vertex colors: \t\t: YES" << endl;
    }
    if(o.generateTextures())
    {
        cout << "##### Generate Textures \t: YES" << endl;
        cout << "##### Texel size \t\t: " << o.getTexelSize() << endl;
        cout << "##### Texture Min#Cluster \t: " << o.getTexMinClusterSize() << endl;
        cout << "##### Texture Max#Cluster \t: " << o.getTexMaxClusterSize() << endl;

        if(o.doTextureAnalysis())
        {
            cout << "##### Texture Analysis \t: ON" << endl;
        }
        else
        {
            cout << "##### Texture Analysis \t\t: OFF" << endl;
        }
    }
    if(o.getEdgeCollapseReductionRatio() > 0.0)
    {
        cout << "##### Edge collapse reduction ratio\t: " << o.getEdgeCollapseReductionRatio() << endl;
    }

    if(o.useGPU())
    {
        cout << "##### GPU normal estimation \t: ON" << endl;
        std::vector<float> flipPoint = o.getFlippoint();
        cout << "##### Flippoint \t\t: ("
            << flipPoint[0] << ", "
            << flipPoint[1] << ", "
            << flipPoint[2] << ")" << endl;
    }else{
        cout << "##### GPU normal estimation \t: OFF" << endl;
    }

    return os;
}

} // namespace reconstruct

#endif /* OPTIONS_H_ */

max_stars_repo_name: uos/lvr

max_issues_repo_name: uos/lvr

max_forks_repo_name: uos/lvr


text:
/* Copyright 2008 (C) Nicira, Inc.
 *
 * This file is part of NOX.
 *
 * NOX is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * NOX is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with NOX.  If not, see <http://www.gnu.org/licenses/>.
 */
/* Tests for Co_cond. */

#include "threads/cooperative.hh"
#include <boost/bind.hpp>

using namespace vigil;

static void
thread1_hook()
{
    printf("hook\n");
}

static void
thread1()
{
    start.up();
    for (int i = 0; i < 10; i++) {
        printf("thread1\n");
        co_set_preblock_hook(thread1_hook);
        co_yield();
    }
    done.up();
}

static void
thread2()
{
    start.down();
    for (int i = 0; i < 10; i++) {
        printf("thread2\n");
        co_yield();
    }
    done.up();
}

int
main()
{
    co_init();
    co_thread_assimilate();
    co_migrate(&co_group_coop);
    co_thread_create(&co_group_coop, thread1);
    co_thread_create(&co_group_coop, thread2);
    done.down();
    done.down();
}

max_stars_repo_name: ayjazz/OESS

max_issues_repo_name: ayjazz/OESS

max_forks_repo_name: ayjazz/OESS


text:
#include <boost/test/unit_test.hpp>
#include <string>
#include <memory>

#include <vector>

#include <boost/format.hpp>

#include "aisql_connection.hpp"
#include "aisql_conns_manage.hpp"

using namespace aisqlpp::db_config;

BOOST_AUTO_TEST_SUITE(mysql_query_test_values)

BOOST_AUTO_TEST_CASE(mysql_template_querys)
{
    aisqlpp::conns_manage mng(3, host, user, passwd, db);
    aisqlpp::connection_ptr ptr = mng.request_conn();
    assert(ptr);

    string str = "SELECT uuid, YGSC, FYPJ, SSZY FROM v5_law_text WHERE uuid=3;";
    uint64_t uuid_r;
    string   ygsc_r;
    string   fypj_r;
    string   sszy_r;

    assert(ptr->execute_query_values(str, uuid_r, ygsc_r, fypj_r, sszy_r));
    cout << "查询信息：" << endl;
    cout << boost::format("查询信息: %llu, %s, %s, %s") %uuid_r%ygsc_r%sszy_r%sszy_r << endl;
    cout << "Finishied!" << endl;
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: taozhijiang/aisqlpp

max_issues_repo_name: taozhijiang/aisqlpp

max_forks_repo_name: taozhijiang/aisqlpp


text:
#pragma once

#include <xul/std/containers.hpp>
#include <xul/std/strings.hpp>
#include <xul/std/tstring.hpp>
#include <xul/data/string_table.hpp>
#include <boost/checked_delete.hpp>
#include <map>

namespace xul {

typedef std::map<std::string, std::string> string_dict;
typedef std::map<std::wstring, std::wstring> wstring_dict;
typedef std::map<tstring, tstring> tstring_dict;

class multimaps
{
public:
    template <typename KeyT, typename ValueT, typename TraitsT, typename AllocatorT>
    static ValueT get(const std::multimap<KeyT, ValueT, TraitsT, AllocatorT>& coll, const KeyT& key, const ValueT& defaultVal = ValueT())
    {
        typename std::multimap<KeyT, ValueT, TraitsT, AllocatorT>::const_iterator iter = coll.find(key);
        if (iter == coll.end())
            return defaultVal;
        return iter->second;
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static typename std::multimap<KeyT, ValueT, PredT, AllocatorT>::iterator
        find(std::multimap<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& key, const ValueT& value)
    {
        typedef std::multimap<KeyT, ValueT, PredT, AllocatorT> collection_type;
        typename collection_type::iterator iterUpperBound = coll.upper_bound(key);
        for (typename collection_type::iterator iter = coll.lower_bound(key); iter != iterUpperBound; ++iter)
        {
            if (iter->second == value)
                return iter;
        }
        return coll.end();
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static bool erase(std::multimap<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& key, const ValueT& value)
    {
        typedef std::multimap<KeyT, ValueT, PredT, AllocatorT> collection_type;
        typename collection_type::iterator iter = multimaps::find(coll, key, value);
        if (iter == coll.end())
            return false;
        coll.erase(iter);
        return true;
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static bool insert(std::multimap<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& key, const ValueT& value)
    {
        typedef std::multimap<KeyT, ValueT, PredT, AllocatorT> collection_type;
        typename collection_type::iterator iter = multimaps::find(coll, key, value);
        if (iter != coll.end())
            return false;
        coll.insert(make_pair(key, value));
        return true;
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static void update(std::multimap<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& oldKey, const KeyT& newKey, const ValueT& value)
    {
        multimaps::erase(coll, oldKey, value);
        coll.insert(make_pair(newKey, value));
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static bool update_if_exist(std::multimap<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& oldKey, const KeyT& newKey, const ValueT& value)
    {
        if (multimaps::erase(coll, oldKey, value))
        {
            coll.insert(make_pair(newKey, value));
            return true;
        }
        return false;
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static bool pop_front(std::multimap<KeyT, ValueT, PredT, AllocatorT>& coll, ValueT& val)
    {
        typedef std::multimap<KeyT, ValueT, PredT, AllocatorT> collection_type;
        if (coll.empty())
            return false;
        typename collection_type::iterator iter = coll.begin();
        assert(iter != coll.end());
        val = iter->second;
        coll.erase(iter);
        return true;
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static typename std::multimap<KeyT, ValueT, PredT, AllocatorT>::const_iterator
        max_less_than_or_equal(const std::multimap<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& key)
    {
        typedef std::multimap<KeyT, ValueT, PredT, AllocatorT> collection_type;
        typename collection_type::const_iterator lowerBound = coll.lower_bound(key);
        if (lowerBound == coll.end())
        {
            if (!coll.empty())
            {
                --lowerBound;
                assert(coll.key_comp()(lowerBound->first, key));
            }
        }
        else
        {
            if (lowerBound->first != key)
            {
                assert(coll.key_comp()(key, lowerBound->first));
                if (lowerBound == coll.begin())
                    lowerBound = coll.end();
                else
                {
                    --lowerBound;
                    assert(coll.key_comp()(lowerBound->first, key));
                }
            }
        }
        return lowerBound;
    }
};

class ptr_maps
{
public:
    template <typename KeyT, typename TypeT, typename PredT, typename AllocatorT>
    static TypeT find(const std::map<KeyT, TypeT, PredT, AllocatorT>& cont, const KeyT& key)
    {
        typename std::map<KeyT, TypeT, PredT, AllocatorT>::const_iterator pos = cont.find(key);
        if (pos == cont.end())
            return TypeT();
        return pos->second;
    }

    template <typename KeyT, typename TypeT, typename PredT, typename AllocatorT>
    static void clear(std::map<KeyT, TypeT, PredT, AllocatorT>& cont)
    {
        typedef std::map<KeyT, TypeT, PredT, AllocatorT> map_type;
        for (typename map_type::const_iterator iter = cont.begin(); iter != cont.end(); ++iter)
        {
            delete_element(iter->second);
        }
        cont.clear();
    }

    template <typename KeyT, typename TypeT, typename PredT, typename AllocatorT>
    static bool erase(std::map<KeyT, TypeT, PredT, AllocatorT>& cont,
        typename std::map<KeyT, TypeT, PredT, AllocatorT>::iterator iter)
    {
        if (iter == cont.end())
            return false;
        delete_element(iter->second);
        cont.erase(iter);
        return true;
    }

    template <typename KeyT, typename TypeT, typename PredT, typename AllocatorT>
    static bool erase(std::map<KeyT, TypeT, PredT, AllocatorT>& cont, const KeyT& key)
    {
        typename std::map<KeyT, TypeT, PredT, AllocatorT>::iterator iter = cont.find(key);
        if (iter == cont.end())
            return false;
        delete_element(iter->second);
        cont.erase(iter);
        return true;
    }
};

class ptr_multimaps
{
public:
    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static ValueT find(std::multimap<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& key, const ValueT& value)
    {
        typedef std::multimap<KeyT, ValueT, PredT, AllocatorT> collection_type;
        typename collection_type::iterator iter = multimaps::find(coll, key, value);
        if (iter == coll.end())
            return ValueT();
        return iter->second;
    }

};

class maps : public containers
{
public:
    template <typename KeyT, typename ValueT, typename TraitsT, typename AllocatorT>
    static bool try_get(ValueT& val, const std::map<KeyT, ValueT, TraitsT, AllocatorT>& coll, const KeyT& key)
    {
        typename std::map<KeyT, ValueT, TraitsT, AllocatorT>::const_iterator iter = coll.find(key);
        if (iter == coll.end())
            return false;
        val = iter->second;
        return true;
    }
    template <typename KeyT, typename ValueT, typename TraitsT, typename AllocatorT>
    static ValueT get(const std::map<KeyT, ValueT, TraitsT, AllocatorT>& coll, const KeyT& key, const ValueT& defaultVal = ValueT())
    {
        typename std::map<KeyT, ValueT, TraitsT, AllocatorT>::const_iterator iter = coll.find(key);
        if (iter == coll.end())
            return defaultVal;
        return iter->second;
    }

    template <typename KeyT, typename ValueT, typename TraitsT, typename AllocatorT>
    static bool try_get(ValueT& val, const std::multimap<KeyT, ValueT, TraitsT, AllocatorT>& coll, const KeyT& key)
    {
        typename std::multimap<KeyT, ValueT, TraitsT, AllocatorT>::const_iterator iter = coll.find(key);
        if (iter == coll.end())
            return false;
        val = iter->second;
        return true;
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static ValueT get_value(const std::map<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& key, const ValueT& defaultVal = ValueT())
    {
        return get(coll, key, defaultVal);
    }

    template <typename KeyT, typename TypeT, typename PredT, typename AllocatorT>
    static size_t count_range(const std::map<KeyT, TypeT, PredT, AllocatorT>& cont, const KeyT& rangeMin, const KeyT& rangeMax)
    {
        assert(!cont.key_comp()(rangeMax, rangeMin));
        return std::distance(cont.lower_bound(rangeMin), cont.upper_bound(rangeMax));
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static typename std::map<KeyT, ValueT, PredT, AllocatorT>::iterator
        find(std::map<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& key, const ValueT& value = ValueT())
    {
        return coll.find(key);
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static bool erase(std::map<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& key, const ValueT& value)
    {
        return coll.erase(key) == 1;
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static bool insert(std::map<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& key, const ValueT& value)
    {
        typedef std::map<KeyT, ValueT, PredT, AllocatorT> collection_type;
        std::pair<typename collection_type::iterator, bool> res = coll.insert(make_pair(key, value));
        return res.second;
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static void erase_lower(std::map<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& bound)
    {
        coll.erase(coll.begin(), coll.lower_bound(bound));
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static void erase_non_upper(std::map<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& bound)
    {
        coll.erase(coll.begin(), coll.upper_bound(bound));
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static void erase_upper(std::map<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& bound)
    {
        coll.erase(coll.upper_bound(bound), coll.end());
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static void erase_non_lower(std::map<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& bound)
    {
        coll.erase(coll.lower_bound(bound), coll.end());
    }

    /// find the biggest element which <= key
    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static typename std::map<KeyT, ValueT, PredT, AllocatorT>::iterator find_lower_floor(std::map<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& key)
    {
        typedef std::map<KeyT, ValueT, PredT, AllocatorT> map_type;
        typename map_type::iterator iter = coll.upper_bound(key);
        if (coll.begin() == iter)
        {
            return coll.end();
        }
        --iter;
        return iter;
    }

    /// find the biggest element which <= key
    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static typename std::map<KeyT, ValueT, PredT, AllocatorT>::const_iterator find_lower_floor(const std::map<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& key)
    {
        typedef std::map<KeyT, ValueT, PredT, AllocatorT> map_type;
        typename map_type::const_iterator iter = coll.upper_bound(key);
        if (coll.begin() == iter)
        {
            return coll.end();
        }
        --iter;
        return iter;
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static ValueT get_lower_floor(std::map<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& key, const ValueT& defval = ValueT())
    {
        typedef std::map<KeyT, ValueT, PredT, AllocatorT> map_type;
        typename map_type::iterator iter = find_lower_floor(coll, key);
        if (coll.end() == iter)
            return defval;
        return iter->second;
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static ValueT get_lower_floor(const std::map<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& key, const ValueT& defval = ValueT())
    {
        typedef std::map<KeyT, ValueT, PredT, AllocatorT> map_type;
        typename map_type::const_iterator iter = find_lower_floor(coll, key);
        if (coll.end() == iter)
            return defval;
        return iter->second;
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static typename std::map<KeyT, ValueT, PredT, AllocatorT>::iterator get_last_valid(std::map<KeyT, ValueT, PredT, AllocatorT>& coll)
    {
        typename std::map<KeyT, ValueT, PredT, AllocatorT>::iterator iter = coll.end();
        if (!coll.empty())
        {
            --iter;
        }
        return iter;
    }

    template <typename KeyT, typename ValueT, typename PredT, typename AllocatorT>
    static typename std::map<KeyT, ValueT, PredT, AllocatorT>::const_iterator get_last_valid(const std::map<KeyT, ValueT, PredT, AllocatorT>& coll, const KeyT& bound)
    {
        typename std::map<KeyT, ValueT, PredT, AllocatorT>::iterator iter = coll.end();
        if (!coll.empty())
        {
            --iter;
        }
        return iter;
    }
};

class string_dicts
{
public:
    template <typename PredT, typename AllocT>
    static std::string get_value(const std::map<std::string, std::string, PredT, AllocT>& dict, const std::string& key)
    {
        return maps::get_value(dict, key);
    }

    template <typename PredT, typename AllocT>
    static std::wstring get_value(const std::map<std::wstring, std::wstring, PredT, AllocT>& dict, const std::wstring& key)
    {
        return maps::get_value(dict, key);
    }

    template <typename PredT, typename AllocT>
    static size_t parse(std::map<std::string, std::string, PredT, AllocT>& dict, const std::string& src, char firstKey, char secondKey)
    {
        std::vector<std::string> strs;
        xul::strings::split(std::back_inserter(strs), src, firstKey);
        size_t count = 0;
        for (size_t index = 0; index < strs.size(); ++index)
        {
            std::pair<std::string, std::string> keyVal = xul::strings::split_pair(strs[index], secondKey);
            if (keyVal.first.size() > 0)
            {
                dict[keyVal.first] = keyVal.second;
                ++count;
            }
        }
        return count;
    }

    static size_t parse(string_table& dict, const std::string& src, char firstKey, char secondKey)
    {
        std::vector<std::string> strs;
        xul::strings::split(std::back_inserter(strs), src, firstKey);
        size_t count = 0;
        for (size_t index = 0; index < strs.size(); ++index)
        {
            std::pair<std::string, std::string> keyVal = xul::strings::split_pair(strs[index], secondKey);
            if (keyVal.first.size() > 0)
            {
                dict.set(keyVal.first.c_str(), keyVal.second.c_str());
                ++count;
            }
        }
        return count;
    }
};

}

max_stars_repo_name: hindsights/xul

max_issues_repo_name: hindsights/xul

max_forks_repo_name: hindsights/xul