text:
// Boost.Range library concept checks
//
//  Copyright Neil Groves 2009. Use, modification and distribution
//  are subject to the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
//  Copyright Daniel Walker 2006. Use, modification and distribution
//  are subject to the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org/libs/range/
//

#ifndef BOOST_RANGE_CONCEPTS_HPP
#define BOOST_RANGE_CONCEPTS_HPP

#include <boost/concept_check.hpp>
#include <boost/iterator/iterator_concepts.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/iterator.hpp>
#include <boost/range/value_type.hpp>
#include <boost/range/detail/misc_concept.hpp>
#include <boost/type_traits/remove_reference.hpp>

/*!
 * \file
 * \brief Concept checks for the Boost Range library.
 *
 * The structures in this file may be used in conjunction with the
 * Boost Concept Check library to insure that the type of a function
 * parameter is compatible with a range concept. If not, a meaningful
 * compile time error is generated. Checks are provided for the range
 * concepts related to iterator traversal categories. For example, the
 * following line checks that the type T models the ForwardRange
 * concept.
 *
 * \code
 * BOOST_CONCEPT_ASSERT((ForwardRangeConcept<T>));
 * \endcode
 *
 * A different concept check is required to ensure writeable value
 * access. For example to check for a ForwardRange that can be written
 * to, the following code is required.
 *
 * \code
 * BOOST_CONCEPT_ASSERT((WriteableForwardRangeConcept<T>));
 * \endcode
 *
 * \see http://www.boost.org/libs/range/doc/range.html for details
 * about range concepts.
 * \see http://www.boost.org/libs/iterator/doc/iterator_concepts.html
 * for details about iterator concepts.
 * \see http://www.boost.org/libs/concept_check/concept_check.htm for
 * details about concept checks.
 */

namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost {

    namespace range_detail {

#ifndef BOOST_RANGE_ENABLE_CONCEPT_ASSERT

// List broken compiler versions here:
#ifndef __clang__
    #ifdef __GNUC__
        // GNUC 4.2 has strange issues correctly detecting compliance with the Concepts
        // hence the least disruptive approach is to turn-off the concept checking for
        // this version of the compiler.
        #if __GNUC__ == 4 && __GNUC_MINOR__ == 2
            #define BOOST_RANGE_ENABLE_CONCEPT_ASSERT 0
        #endif
    #endif

    #ifdef __GCCXML__
        // GCC XML, unsurprisingly, has the same issues
        #if __GCCXML_GNUC__ == 4 && __GCCXML_GNUC_MINOR__ == 2
            #define BOOST_RANGE_ENABLE_CONCEPT_ASSERT 0
        #endif
    #endif
#endif

    #ifdef __BORLANDC__
        #define BOOST_RANGE_ENABLE_CONCEPT_ASSERT 0
    #endif

    #ifdef __PATHCC__
        #define BOOST_RANGE_ENABLE_CONCEPT_ASSERT 0
    #endif

// Default to using the concept asserts unless we have defined it off
// during the search for black listed compilers.
    #ifndef BOOST_RANGE_ENABLE_CONCEPT_ASSERT
        #define BOOST_RANGE_ENABLE_CONCEPT_ASSERT 1
    #endif

#endif

#if BOOST_RANGE_ENABLE_CONCEPT_ASSERT
    #define BOOST_RANGE_CONCEPT_ASSERT( x ) BOOST_CONCEPT_ASSERT( x )
#else
    #define BOOST_RANGE_CONCEPT_ASSERT( x )
#endif

        // Rationale for the inclusion of redefined iterator concept
        // classes:
        //
        // The Range algorithms often do not require that the iterators are
        // Assignable or default constructable, but the correct standard
        // conformant iterators do require the iterators to be a model of the
        // Assignable concept.
        // Iterators that contains a functor that is not assignable therefore
        // are not correct models of the standard iterator concepts,
        // despite being adequate for most algorithms. An example of this
        // use case is the combination of the geofeatures_boost::adaptors::filtered
        // class with a geofeatures_boost::lambda::bind generated functor.
        // Ultimately modeling the range concepts using composition
        // with the Boost.Iterator concepts would render the library
        // incompatible with many common Boost.Lambda expressions.
        template<class Iterator>
        struct IncrementableIteratorConcept : CopyConstructible<Iterator>
        {
#if BOOST_RANGE_ENABLE_CONCEPT_ASSERT
            typedef BOOST_DEDUCED_TYPENAME iterator_traversal<Iterator>::type traversal_category;

            BOOST_RANGE_CONCEPT_ASSERT((
                Convertible<
                    traversal_category,
                    incrementable_traversal_tag
                >));

            BOOST_CONCEPT_USAGE(IncrementableIteratorConcept)
            {
                ++i;
                (void)i++;
            }
        private:
            Iterator i;
#endif
        };

        template<class Iterator>
        struct SinglePassIteratorConcept
            : IncrementableIteratorConcept<Iterator>
            , EqualityComparable<Iterator>
        {
#if BOOST_RANGE_ENABLE_CONCEPT_ASSERT
            BOOST_RANGE_CONCEPT_ASSERT((
                Convertible<
                    BOOST_DEDUCED_TYPENAME SinglePassIteratorConcept::traversal_category,
                    single_pass_traversal_tag
                >));

            BOOST_CONCEPT_USAGE(SinglePassIteratorConcept)
            {
                Iterator i2(++i);
                geofeatures_boost::ignore_unused_variable_warning(i2);

                // deliberately we are loose with the postfix version for the single pass
                // iterator due to the commonly poor adherence to the specification means that
                // many algorithms would be unusable, whereas actually without the check they
                // work
                (void)(i++);

                BOOST_DEDUCED_TYPENAME geofeatures_boost::detail::iterator_traits<Iterator>::reference r1(*i);
                geofeatures_boost::ignore_unused_variable_warning(r1);

                BOOST_DEDUCED_TYPENAME geofeatures_boost::detail::iterator_traits<Iterator>::reference r2(*(++i));
                geofeatures_boost::ignore_unused_variable_warning(r2);
            }
        private:
            Iterator i;
#endif
        };

        template<class Iterator>
        struct ForwardIteratorConcept
            : SinglePassIteratorConcept<Iterator>
            , DefaultConstructible<Iterator>
        {
#if BOOST_RANGE_ENABLE_CONCEPT_ASSERT
            typedef BOOST_DEDUCED_TYPENAME geofeatures_boost::detail::iterator_traits<Iterator>::difference_type difference_type;

            BOOST_MPL_ASSERT((is_integral<difference_type>));
            BOOST_MPL_ASSERT_RELATION(std::numeric_limits<difference_type>::is_signed, ==, true);

            BOOST_RANGE_CONCEPT_ASSERT((
                Convertible<
                    BOOST_DEDUCED_TYPENAME ForwardIteratorConcept::traversal_category,
                    forward_traversal_tag
                >));

            BOOST_CONCEPT_USAGE(ForwardIteratorConcept)
            {
                // See the above note in the SinglePassIteratorConcept about the handling of the
                // postfix increment. Since with forward and better iterators there is no need
                // for a proxy, we can sensibly require that the dereference result
                // is convertible to reference.
                Iterator i2(i++);
                geofeatures_boost::ignore_unused_variable_warning(i2);
                BOOST_DEDUCED_TYPENAME geofeatures_boost::detail::iterator_traits<Iterator>::reference r(*(i++));
                geofeatures_boost::ignore_unused_variable_warning(r);
            }
        private:
            Iterator i;
#endif
         };

         template<class Iterator>
         struct BidirectionalIteratorConcept
             : ForwardIteratorConcept<Iterator>
         {
 #if BOOST_RANGE_ENABLE_CONCEPT_ASSERT
             BOOST_RANGE_CONCEPT_ASSERT((
                 Convertible<
                     BOOST_DEDUCED_TYPENAME BidirectionalIteratorConcept::traversal_category,
                     bidirectional_traversal_tag
                 >));

             BOOST_CONCEPT_USAGE(BidirectionalIteratorConcept)
             {
                 --i;
                 (void)i--;
             }
         private:
             Iterator i;
 #endif
         };

         template<class Iterator>
         struct RandomAccessIteratorConcept
             : BidirectionalIteratorConcept<Iterator>
         {
 #if BOOST_RANGE_ENABLE_CONCEPT_ASSERT
             BOOST_RANGE_CONCEPT_ASSERT((
                 Convertible<
                     BOOST_DEDUCED_TYPENAME RandomAccessIteratorConcept::traversal_category,
                     random_access_traversal_tag
                 >));

             BOOST_CONCEPT_USAGE(RandomAccessIteratorConcept)
             {
                 i += n;
                 i = i + n;
                 i = n + i;
                 i -= n;
                 i = i - n;
                 n = i - j;
             }
         private:
             BOOST_DEDUCED_TYPENAME RandomAccessIteratorConcept::difference_type n;
             Iterator i;
             Iterator j;
 #endif
         };

    } // namespace range_detail

    //! Check if a type T models the SinglePassRange range concept.
    template<class T>
    struct SinglePassRangeConcept
    {
#if BOOST_RANGE_ENABLE_CONCEPT_ASSERT
        // A few compilers don't like the rvalue reference T types so just
        // remove it.
        typedef BOOST_DEDUCED_TYPENAME remove_reference<T>::type Rng;

        typedef BOOST_DEDUCED_TYPENAME range_iterator<
            Rng const
        >::type const_iterator;

        typedef BOOST_DEDUCED_TYPENAME range_iterator<Rng>::type iterator;

        BOOST_RANGE_CONCEPT_ASSERT((
                range_detail::SinglePassIteratorConcept<iterator>));

        BOOST_RANGE_CONCEPT_ASSERT((
                range_detail::SinglePassIteratorConcept<const_iterator>));

        BOOST_CONCEPT_USAGE(SinglePassRangeConcept)
        {
            // This has been modified from assigning to this->i
            // (where i was a member variable) to improve
            // compatibility with Boost.Lambda
            iterator i1 = geofeatures_boost::begin(*m_range);
            iterator i2 = geofeatures_boost::end(*m_range);

            geofeatures_boost::ignore_unused_variable_warning(i1);
            geofeatures_boost::ignore_unused_variable_warning(i2);

            const_constraints(*m_range);
        }

    private:
        void const_constraints(const Rng& const_range)
        {
            const_iterator ci1 = geofeatures_boost::begin(const_range);
            const_iterator ci2 = geofeatures_boost::end(const_range);

            geofeatures_boost::ignore_unused_variable_warning(ci1);
            geofeatures_boost::ignore_unused_variable_warning(ci2);
        }

       // Rationale:
       // The type of m_range is T* rather than T because it allows
       // T to be an abstract class. The other obvious alternative of
       // T& produces a warning on some compilers.
       Rng* m_range;
#endif
    };

    //! Check if a type T models the ForwardRange range concept.
    template<class T>
    struct ForwardRangeConcept : SinglePassRangeConcept<T>
    {
#if BOOST_RANGE_ENABLE_CONCEPT_ASSERT
        BOOST_RANGE_CONCEPT_ASSERT((range_detail::ForwardIteratorConcept<BOOST_DEDUCED_TYPENAME ForwardRangeConcept::iterator>));
        BOOST_RANGE_CONCEPT_ASSERT((range_detail::ForwardIteratorConcept<BOOST_DEDUCED_TYPENAME ForwardRangeConcept::const_iterator>));
#endif
    };

    template<class T>
    struct WriteableRangeConcept
    {
#if BOOST_RANGE_ENABLE_CONCEPT_ASSERT
        typedef BOOST_DEDUCED_TYPENAME range_iterator<T>::type iterator;

        BOOST_CONCEPT_USAGE(WriteableRangeConcept)
        {
            *i = v;
        }
    private:
        iterator i;
        BOOST_DEDUCED_TYPENAME range_value<T>::type v;
#endif
    };

    //! Check if a type T models the WriteableForwardRange range concept.
    template<class T>
    struct WriteableForwardRangeConcept
        : ForwardRangeConcept<T>
        , WriteableRangeConcept<T>
    {
    };

    //! Check if a type T models the BidirectionalRange range concept.
    template<class T>
    struct BidirectionalRangeConcept : ForwardRangeConcept<T>
    {
#if BOOST_RANGE_ENABLE_CONCEPT_ASSERT
        BOOST_RANGE_CONCEPT_ASSERT((range_detail::BidirectionalIteratorConcept<BOOST_DEDUCED_TYPENAME BidirectionalRangeConcept::iterator>));
        BOOST_RANGE_CONCEPT_ASSERT((range_detail::BidirectionalIteratorConcept<BOOST_DEDUCED_TYPENAME BidirectionalRangeConcept::const_iterator>));
#endif
    };

    //! Check if a type T models the WriteableBidirectionalRange range concept.
    template<class T>
    struct WriteableBidirectionalRangeConcept
        : BidirectionalRangeConcept<T>
        , WriteableRangeConcept<T>
    {
    };

    //! Check if a type T models the RandomAccessRange range concept.
    template<class T>
    struct RandomAccessRangeConcept : BidirectionalRangeConcept<T>
    {
#if BOOST_RANGE_ENABLE_CONCEPT_ASSERT
        BOOST_RANGE_CONCEPT_ASSERT((range_detail::RandomAccessIteratorConcept<BOOST_DEDUCED_TYPENAME RandomAccessRangeConcept::iterator>));
        BOOST_RANGE_CONCEPT_ASSERT((range_detail::RandomAccessIteratorConcept<BOOST_DEDUCED_TYPENAME RandomAccessRangeConcept::const_iterator>));
#endif
    };

    //! Check if a type T models the WriteableRandomAccessRange range concept.
    template<class T>
    struct WriteableRandomAccessRangeConcept
        : RandomAccessRangeConcept<T>
        , WriteableRangeConcept<T>
    {
    };

} // namespace geofeatures_boost

#endif // BOOST_RANGE_CONCEPTS_HPP

ext: hpp

max_stars_repo_name: xarvey/Yuuuuuge

max_issues_repo_name: xarvey/Yuuuuuge

max_forks_repo_name: xarvey/Yuuuuuge


text:
#include <fc/log/console_appender.hpp>
#include <fc/log/log_message.hpp>
#include <fc/thread/unique_lock.hpp>
#include <fc/string.hpp>
#include <fc/variant.hpp>
#include <fc/reflect/variant.hpp>
#ifndef WIN32
#include <unistd.h>
#endif
#include <boost/thread/mutex.hpp>
#define COLOR_CONSOLE 1
#include "console_defines.h"
#include <fc/io/stdio.hpp>
#include <fc/exception/exception.hpp>
#include <iomanip>
#include <sstream>

namespace fc {
   console_appender::console_appender( const variant& args )
   {
      try
      {
         cfg = args.as<config>();//fc::variant_cast<config>(args);
         for( int i = 0; i < log_level::off+1; ++i )
            lc[i] = color::console_default;
         for( auto itr = cfg.level_colors.begin(); itr != cfg.level_colors.end(); ++itr )
            lc[itr->level] = itr->color;
      }
      catch ( exception& e )
      {
         fc::cerr<<e.to_detail_string()<<"\n";
         throw;
      }
   }

   const char* get_console_color(console_appender::color::type t ) {
   #ifndef _MSC_VER
      switch( t ) {
         case console_appender::color::red: return CONSOLE_RED;
         case console_appender::color::green: return CONSOLE_GREEN;
         case console_appender::color::brown: return CONSOLE_BROWN;
         case console_appender::color::blue: return CONSOLE_BLUE;
         case console_appender::color::magenta: return CONSOLE_MAGENTA;
         case console_appender::color::cyan: return CONSOLE_CYAN;
         case console_appender::color::white: return CONSOLE_WHITE;
         case console_appender::color::console_default:
         default:
            return CONSOLE_DEFAULT;
      }
   #else
      return "";
   #endif
   }

   boost::mutex& log_mutex() {
    static boost::mutex m; return m;
   }
   const char* console_appender::get_color( log_level l )const {
      return get_console_color( lc[l] );
   }
   void console_appender::log( const log_message& m ) {
      //fc::string message = fc::format_string( m.get_format(), m.get_data() );
      //fc::variant lmsg(m);

      FILE* out = stream::std_error ? stderr : stdout;

      //fc::string fmt_str = fc::format_string( cfg.format, mutable_variant_object(m.get_context())( "message", message)  );
      std::stringstream file_line;
      file_line << m.get_context().get_file() <<":"<<m.get_context().get_line_number() <<" ";

      ///////////////
      std::stringstream line;
      line << (m.get_context().get_timestamp().time_since_epoch().count() % (1000ll*1000ll*60ll*60))/1000 <<"ms ";
      line << std::setw( 10 ) << std::left << m.get_context().get_thread_name().substr(0,9).c_str() <<" "<<std::setw(30)<< std::left <<file_line.str();

      auto me = m.get_context().get_method();
      // strip all leading scopes...
      if( me.size() )
      {
         uint32_t p = 0;
         for( uint32_t i = 0;i < me.size(); ++i )
         {
             if( me[i] == ':' ) p = i;
         }

         if( me[p] == ':' ) ++p;
         line << std::setw( 20 ) << std::left << m.get_context().get_method().substr(p,20).c_str() <<" ";
      }
      line << "] ";
      fc::string message = fc::format_string( m.get_format(), m.get_data() );
      line << message;//.c_str();
      //
      //

      fc::unique_lock<boost::mutex> lock(log_mutex());
      #ifndef WIN32
      if(isatty(fileno(out))) fprintf( out, "\r%s", get_color( m.get_context().get_log_level() ) );
      #endif

      fprintf( out, "%s", line.str().c_str()); //fmt_str.c_str() );

      #ifndef WIN32
      if(isatty(fileno(out))) fprintf( out, "\r%s", CONSOLE_DEFAULT );
      #endif
      fprintf( out, "\n" );
      if( cfg.flush ) fflush( out );
   }

}

ext: cpp

max_stars_repo_name: CoderRaka/fc

max_issues_repo_name: CoderRaka/fc

max_forks_repo_name: CoderRaka/fc


text:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <tuple>
#include <numeric>
#include <random>
#include <boost/program_options.hpp>
#define VEXCL_USE_CUSPARSE
#include <vexcl/devlist.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/reductor.hpp>
#include <vexcl/random.hpp>
#include <vexcl/tagged_terminal.hpp>
#include <vexcl/element_index.hpp>
#include <vexcl/spmat.hpp>
#include <vexcl/stencil.hpp>
#include <vexcl/sort.hpp>
#include <vexcl/scan.hpp>

#ifdef VEXCL_HAVE_BOOST_COMPUTE
#  include <vexcl/external/boost_compute.hpp>
#endif

#ifdef VEXCL_HAVE_CLOGS
#  include <vexcl/external/clogs.hpp>
#endif

#ifdef _MSC_VER
#  pragma warning(disable : 4267)
#endif

//---------------------------------------------------------------------------
struct Options {
    bool bm_saxpy;
    bool bm_vector;
    bool bm_reductor;
    bool bm_stencil;
    bool bm_spmv;
    bool bm_rng;
    bool bm_sort;
    bool bm_scan;
    bool bm_cpu;

    Options() :
        bm_saxpy(true),
        bm_vector(true),
        bm_reductor(true),
        bm_stencil(true),
        bm_spmv(true),
        bm_rng(true),
        bm_sort(true),
        bm_scan(true),
        bm_cpu(true)
    {}

    void revert() {
        bm_saxpy    = !bm_saxpy;
        bm_vector   = !bm_vector;
        bm_reductor = !bm_reductor;
        bm_stencil  = !bm_stencil;
        bm_spmv     = !bm_spmv;
        bm_rng      = !bm_rng;
        bm_sort     = !bm_sort;
        bm_scan     = !bm_scan;
        bm_cpu      = !bm_cpu;
    }
} options;

//---------------------------------------------------------------------------
template <typename real>
std::vector<real> random_vector(size_t n) {
    std::default_random_engine rng( std::rand() );
    std::uniform_real_distribution<real> rnd(0.0, 1.0);

    std::vector<real> x(n);
    for(size_t i = 0; i < n; ++i) x[i] = rnd(rng);

    return x;
}

//---------------------------------------------------------------------------
template <typename real>
std::pair<double,double> benchmark_saxpy(
        const vex::Context &ctx, vex::profiler<> &prof
        )
{
    const size_t N = 1024 * 1024;
    const size_t M = 1024;
    double time_elapsed;

    std::vector<real> A(N, 0);
    std::vector<real> B = random_vector<real>(N);
    std::vector<real> alphavec = random_vector<real>(1);
    real alpha = alphavec[0];

    vex::vector<real> a(ctx, A);
    vex::vector<real> b(ctx, B);

    auto ta = vex::tag<1>(a);

    ta = alpha * ta + b;
    ta = static_cast<real>(0);

    prof.tic_cpu("OpenCL");
    for(size_t i = 0; i < M; i++)
        ta = alpha * ta + b;
    ctx.finish();
    time_elapsed = prof.toc("OpenCL");

    double gflops = (2.0 * N * M) / time_elapsed / 1e9;
    double bwidth = (3.0 * N * M * sizeof(real)) / time_elapsed / 1e9;

    std::cout
        << "Vector SAXPY (" << vex::type_name<real>() << ")\n"
        << "  OpenCL"
        << "\n    GFLOPS:    " << gflops
        << "\n    Bandwidth: " << bwidth
        << std::endl;

    if (options.bm_cpu) {
        prof.tic_cpu("C++");
        for(size_t i = 0; i < M; i++)
            for(size_t j = 0; j < N; j++)
                A[j] = alpha * A[j] + B[j];
        time_elapsed = prof.toc("C++");

        {
            double gflops = (2.0 * N * M) / time_elapsed / 1e9;
            double bwidth = (3.0 * N * M * sizeof(real)) / time_elapsed / 1e9;

            std::cout
                << "  C++"
                << "\n    GFLOPS:    " << gflops
                << "\n    Bandwidth: " << bwidth
                << std::endl;
        }

        vex::copy(A, b);
        vex::Reductor<real, vex::SUM> sum(ctx);

        a -= b;
        std::cout << "  res = " << sum(a * a)
                  << std::endl << std::endl;
    }

    return std::make_pair(gflops, bwidth);
}

//---------------------------------------------------------------------------
template <typename real>
std::pair<double,double> benchmark_vector(
        const vex::Context &ctx, vex::profiler<> &prof
        )
{
    const size_t N = 1024 * 1024;
    const size_t M = 1024;
    double time_elapsed;

    std::vector<real> A(N, 0);
    std::vector<real> B = random_vector<real>(N);
    std::vector<real> C = random_vector<real>(N);
    std::vector<real> D = random_vector<real>(N);

    vex::vector<real> a(ctx, A);
    vex::vector<real> b(ctx, B);
    vex::vector<real> c(ctx, C);
    vex::vector<real> d(ctx, D);

    a += b + c * d;
    a = 0;

    prof.tic_cpu("OpenCL");
    for(size_t i = 0; i < M; i++)
        a += b + c * d;
    ctx.finish();
    time_elapsed = prof.toc("OpenCL");

    double gflops = (3.0 * N * M) / time_elapsed / 1e9;
    double bwidth = (5.0 * N * M * sizeof(real)) / time_elapsed / 1e9;

    std::cout
        << "Vector arithmetic (" << vex::type_name<real>() << ")\n"
        << "  OpenCL"
        << "\n    GFLOPS:    " << gflops
        << "\n    Bandwidth: " << bwidth
        << std::endl;

    if (options.bm_cpu) {
        prof.tic_cpu("C++");
        for(size_t i = 0; i < M; i++)
            for(size_t j = 0; j < N; j++)
                A[j] += B[j] + C[j] * D[j];
        time_elapsed = prof.toc("C++");
        {
            double gflops = (3.0 * N * M) / time_elapsed / 1e9;
            double bwidth = (5.0 * N * M * sizeof(real)) / time_elapsed / 1e9;

            std::cout
                << "  C++"
                << "\n    GFLOPS:    " << gflops
                << "\n    Bandwidth: " << bwidth
                << std::endl;
        }

        vex::copy(A, b);
        vex::Reductor<real, vex::SUM> sum(ctx);

        a -= b;
        std::cout << "  res = " << sum(a * a)
                  << std::endl << std::endl;
    }

    return std::make_pair(gflops, bwidth);
}

//---------------------------------------------------------------------------
template <typename real>
std::pair<double, double> benchmark_reductor(
        const vex::Context &ctx, vex::profiler<> &prof
        )
{
    const size_t N = 16 * 1024 * 1024;
    const size_t M = 1024 / 16;
    double time_elapsed;

    std::vector<real> A = random_vector<real>(N);
    std::vector<real> B = random_vector<real>(N);

    vex::vector<real> a(ctx, A);
    vex::vector<real> b(ctx, B);

    vex::Reductor<real, vex::SUM> sum(ctx);

    real sum_cl = sum(a * b);
    sum_cl = 0;

    prof.tic_cpu("OpenCL");
    for(size_t i = 0; i < M; i++)
        sum_cl += sum(a * b);
    ctx.finish();
    time_elapsed = prof.toc("OpenCL");

    double gflops = 2.0 * N * M / time_elapsed / 1e9;
    double bwidth = 2.0 * N * M * sizeof(real) / time_elapsed / 1e9;

    std::cout
        << "Reduction (" << vex::type_name<real>() << ")\n"
        << "  OpenCL"
        << "\n    GFLOPS:    " << gflops
        << "\n    Bandwidth: " << bwidth
        << std::endl;

    if (options.bm_cpu) {
        real sum_cpp = 0;
        prof.tic_cpu("C++");
        for(size_t i = 0; i < M; i++)
            sum_cpp += std::inner_product(A.begin(), A.end(), B.begin(), static_cast<real>(0));
        time_elapsed = prof.toc("C++");

        {
            double gflops = 2.0 * N * M / time_elapsed / 1e9;
            double bwidth = 2.0 * N * M * sizeof(real) / time_elapsed / 1e9;

            std::cout
                << "  C++"
                << "\n    GFLOPS:    " << gflops
                << "\n    Bandwidth: " << bwidth
                << std::endl;
        }

        std::cout << "  res = " << fabs( (sum_cl - sum_cpp) / sum_cpp )
                  << std::endl << std::endl;
    }

    return std::make_pair(gflops, bwidth);
}

//---------------------------------------------------------------------------
template <typename real>
std::pair<double, double> benchmark_stencil(
        const vex::Context &ctx, vex::profiler<> &prof
        )
{
    const long N = 1024 * 1024;
    const long M = 1024;
    double time_elapsed;

    std::vector<real> A = random_vector<real>(N);
    std::vector<real> B(N);

    std::vector<real> S(21, static_cast<real>(1) / 21);
    long center = S.size() / 2;
    vex::stencil<real> s(ctx, S, center);

    vex::vector<real> a(ctx, A);
    vex::vector<real> b(ctx, N);

    b = a * s;

    prof.tic_cpu("OpenCL");
    for(long i = 0; i < M; i++)
        b = a * s;
    ctx.finish();
    time_elapsed = prof.toc("OpenCL");

    double gflops = 2.0 * S.size() * N * M / time_elapsed / 1e9;
    double bwidth = 2.0 * S.size() * N * M * sizeof(real) / time_elapsed / 1e9;

    std::cout
        << "Stencil convolution (" << vex::type_name<real>() << ")\n"
        << "  OpenCL"
        << "\n    GFLOPS:    " << gflops
        << "\n    Bandwidth: " << bwidth
        << std::endl;

    if (options.bm_cpu) {
        prof.tic_cpu("C++");
        for(long j = 0; j < M; j++) {
            for(long i = 0; i < N; i++) {
                real sum = 0;
                for(long k = 0; k < (long)S.size(); k++)
                    sum += S[k] * A[std::min<long>(N-1, std::max<long>(0, i + k - center))];
                B[i] = sum;
            }
        }
        time_elapsed = prof.toc("C++");

        {
            double gflops = 2.0 * S.size() * N * M / time_elapsed / 1e9;
            double bwidth = 2.0 * S.size() * N * M * sizeof(real) / time_elapsed / 1e9;

            std::cout
                << "  C++"
                << "\n    GFLOPS:    " << gflops
                << "\n    Bandwidth: " << bwidth
                << std::endl;
        }

        vex::Reductor<real, vex::MAX> max(ctx);
        copy(B, a);

        std::cout << "  res = " << max(fabs(a - b))
                  << std::endl << std::endl;
    }

    return std::make_pair(gflops, bwidth);
}

//---------------------------------------------------------------------------
template <typename real>
std::pair<double,double> benchmark_spmv(
        const vex::Context &ctx, vex::profiler<> &prof
        )
{
    // Construct matrix for 3D Poisson problem in cubic domain.
    const size_t n = 128;
    const size_t N = n * n * n;
    const size_t M = 1024;

    double time_elapsed;

    const real h2i = (n - 1) * (n - 1);

    std::vector<size_t> row;
    std::vector<uint>   col;
    std::vector<real>   val;
    std::vector<real>   X(n * n * n, static_cast<real>(1e-2));
    std::vector<real>   Y(n * n * n, 0);

    row.reserve(n * n * n + 1);
    col.reserve(6 * (n - 2) * (n - 2) * (n - 2) + n * n * n);
    val.reserve(6 * (n - 2) * (n - 2) * (n - 2) + n * n * n);

    row.push_back(0);
    for(size_t k = 0, idx = 0; k < n; k++) {
        for(size_t j = 0; j < n; j++) {
            for(size_t i = 0; i < n; i++, idx++) {
                if (
                        i == 0 || i == (n - 1) ||
                        j == 0 || j == (n - 1) ||
                        k == 0 || k == (n - 1)
                   )
                {
                    col.push_back(idx);
                    val.push_back(1);
                    row.push_back(row.back() + 1);
                } else {
                    col.push_back(idx - n * n);
                    val.push_back(-h2i);

                    col.push_back(idx - n);
                    val.push_back(-h2i);

                    col.push_back(idx - 1);
                    val.push_back(-h2i);

                    col.push_back(idx);
                    val.push_back(6 * h2i);

                    col.push_back(idx + 1);
                    val.push_back(-h2i);

                    col.push_back(idx + n);
                    val.push_back(-h2i);

                    col.push_back(idx + n * n);
                    val.push_back(-h2i);

                    row.push_back(row.back() + 7);
                }
            }
        }
    }

    size_t nnz = row.back();

    // Transfer data to compute devices.
    vex::SpMat<real,uint> A(ctx, n * n * n, n * n * n, row.data(), col.data(), val.data());

    vex::vector<real> x(ctx, X);
    vex::vector<real> y(ctx, Y);

    // Get timings.
    y += A * x;
    y = 0;

    prof.tic_cpu("OpenCL");
    for(size_t i = 0; i < M; i++)
        y += A * x;
    ctx.finish();
    time_elapsed = prof.toc("OpenCL");

    double gflops = M / time_elapsed / 1e9 * (2.0 * nnz + N);
    double bwidth = M / time_elapsed / 1e9 * (nnz * (2 * sizeof(real) + sizeof(size_t)) + 4 * N * sizeof(real));

    std::cout
        << "SpMV (" << vex::type_name<real>() << ")\n"
        << "  OpenCL"
        << "\n    GFLOPS:    " << gflops
        << "\n    Bandwidth: " << bwidth
        << std::endl;

    if (options.bm_cpu) {
        prof.tic_cpu("C++");
        for(size_t k = 0; k < M; k++)
            for(size_t i = 0; i < N; i++) {
                real s = 0;
                for(size_t j = row[i]; j < row[i + 1]; j++)
                    s += val[j] * X[col[j]];
                Y[i] += s;
            }
        time_elapsed = prof.toc("C++");

        {
            double gflops = M / time_elapsed / 1e9 * (2.0 * nnz + N);
            double bwidth = M / time_elapsed / 1e9 * (nnz * (2 * sizeof(real) + sizeof(size_t)) + 4 * N * sizeof(real));

            std::cout
                << "  C++"
                << "\n    GFLOPS:    " << gflops
                << "\n    Bandwidth: " << bwidth
                << std::endl;
        }

        copy(Y, x);

        y -= x;

        vex::Reductor<real, vex::SUM> sum(ctx);

        std::cout << "  res = " << sum(y * y) << std::endl << std::endl;
    }

    return std::make_pair(gflops, bwidth);
}

//---------------------------------------------------------------------------
template <typename real>
std::pair<double,double> benchmark_spmv_ccsr(
        const vex::Context &ctx, vex::profiler<> &prof
        )
{
    // Construct matrix for 3D Poisson problem in cubic domain.
    const uint n = 128;
    const uint N = n * n * n;
    const uint M = 1024;

    double time_elapsed;

    const real h2i = (n - 1) * (n - 1);

    std::vector<size_t> idx;
    std::vector<size_t> row(3);
    std::vector<int>    col(8);
    std::vector<real>   val(8);

    std::vector<real>   X(n * n * n, static_cast<real>(1e-2));
    std::vector<real>   Y(n * n * n, 0);

    idx.reserve(n * n * n);

    row[0] = 0;
    row[1] = 1;
    row[2] = 8;

    col[0] = 0;
    val[0] = 1;

    col[1] = -static_cast<int>(n * n);
    col[2] = -static_cast<int>(n);
    col[3] =    -1;
    col[4] =     0;
    col[5] =     1;
    col[6] =     n;
    col[7] =  (n * n);

    val[1] = -h2i;
    val[2] = -h2i;
    val[3] = -h2i;
    val[4] =  h2i * 6;
    val[5] = -h2i;
    val[6] = -h2i;
    val[7] = -h2i;

    for(size_t k = 0; k < n; k++) {
        for(size_t j = 0; j < n; j++) {
            for(size_t i = 0; i < n; i++) {
                if (
                        i == 0 || i == (n - 1) ||
                        j == 0 || j == (n - 1) ||
                        k == 0 || k == (n - 1)
                   )
                {
                    idx.push_back(0);
                } else {
                    idx.push_back(1);
                }
            }
        }
    }

    size_t nnz = 6 * (n - 2) * (n - 2) * (n - 2) + n * n * n;

    // Transfer data to compute devices.
    vex::SpMatCCSR<real,int> A(ctx.queue(0), n * n * n, 2,
            idx.data(), row.data(), col.data(), val.data());

    std::vector<vex::command_queue> q1(1, ctx.queue(0));
    vex::vector<real> x(q1, X);
    vex::vector<real> y(q1, Y);

    // Get timings.
    y += A * x;
    y = 0;

    prof.tic_cpu("OpenCL");
    for(size_t i = 0; i < M; i++)
        y += A * x;
    ctx.finish();
    time_elapsed = prof.toc("OpenCL");

    double gflops = (2.0 * nnz + N) * M / time_elapsed / 1e9;
    double bwidth = M * (nnz * (2 * sizeof(real) + sizeof(int)) + 4 * N * sizeof(real)) / time_elapsed / 1e9;

    std::cout
        << "SpMV (CCSR) (" << vex::type_name<real>() << ")\n"
        << "  OpenCL"
        << "\n    GFLOPS:    " << gflops
        << "\n    Bandwidth: " << bwidth
        << std::endl;

    if (options.bm_cpu) {
        prof.tic_cpu("C++");
        for(size_t k = 0; k < M; k++)
            for(size_t i = 0; i < N; i++) {
                real s = 0;
                for(size_t j = row[idx[i]]; j < row[idx[i] + 1]; j++)
                    s += val[j] * X[i + col[j]];
                Y[i] += s;
            }
        time_elapsed = prof.toc("C++");

        {
            double gflops = (2.0 * nnz + N) * M / time_elapsed / 1e9;
            double bwidth = M * (nnz * (2 * sizeof(real) + sizeof(int)) + 4 * N * sizeof(real)) / time_elapsed / 1e9;

            std::cout
                << "  C++"
                << "\n    GFLOPS:    " << gflops
                << "\n    Bandwidth: " << bwidth
                << std::endl;
        }

        copy(Y, x);

        y -= x;

        vex::Reductor<real, vex::SUM> sum(q1);

        std::cout << "  res = " << sum(y * y) << std::endl << std::endl;
    }

    return std::make_pair(gflops, bwidth);
}

//---------------------------------------------------------------------------
template <typename real, class GF>
double rng_throughput(const vex::Context &ctx, size_t N, size_t M) {

    vex::Random<real, GF> rnd;
    vex::Reductor<real, vex::MAX> max(ctx);

    real s = max( rnd( vex::element_index(0, N), std::rand() ) );

    vex::stopwatch<> w;

    for(size_t i = 0; i < M; i++)
        s = std::max(s, max( rnd( vex::element_index(0, N), std::rand() ) ));
    ctx.finish();

    return N * M / w.toc();
}

//---------------------------------------------------------------------------
template <typename real>
void benchmark_rng(
        const vex::Context &ctx, vex::profiler<> &prof
        )
{
    const size_t N = 16 * 1024 * 1024;
    const size_t M = 1024;

    prof.tic_cpu("OpenCL (threefry)");
    double rps = rng_throughput<real, vex::random::threefry>(ctx, N, M);
    prof.toc("OpenCL (threefry)");

    std::cout
        << "Random numbers per second (" << vex::type_name<real>() << ")\n"
        << "    OpenCL (threefry): " << rps << std::endl;

    prof.tic_cpu("OpenCL (philox)");
    rps = rng_throughput<real, vex::random::philox>(ctx, N, M);
    prof.toc("OpenCL (philox)");

    std::cout
        << "    OpenCL (philox):   " << rps << std::endl;

    if (options.bm_cpu) {
        std::mt19937 rng( std::rand() );
        std::uniform_real_distribution<real> rnd(0.0, 1.0);

        prof.tic_cpu("C++ (mt19937)");
        real s = 0;
        for(size_t j = 0; j < N; j++)
            s = std::max(s, rnd(rng));
        double time_elapsed = prof.toc("C++ (mt19937)");

        std::cout
            << "    C++    (mt19937):  " << N / time_elapsed << std::endl;
    }

    std::cout << std::endl;
}

//---------------------------------------------------------------------------
template <typename real>
void benchmark_sort(
        const vex::Context &ctx, vex::profiler<> &prof
        )
{
    const size_t N = 16 * 1024 * 1024;
    const size_t M = 16;

    typedef typename std::conditional<
        std::is_same<float, real>::value, cl_uint, cl_ulong
        >::type key_type;

    std::default_random_engine rng( std::rand() );
    std::uniform_int_distribution<key_type> rnd;

    std::vector<key_type> x0(N);
    std::vector<key_type> x1(N);

    std::generate(x0.begin(), x0.end(), [&]() { return rnd(rng); });

    vex::vector<key_type> X0(ctx, x0);
    vex::vector<key_type> X1(ctx, N);

    X1 = X0;
    vex::sort(X1);

    double tot_time = 0;
    for(size_t i = 0; i < M; i++) {
        X1 = X0;
        ctx.finish();
        prof.tic_cpu("VexCL");
        vex::sort(X1);
        ctx.finish();
        tot_time += prof.toc("VexCL");
    }

    std::cout
        << "Sort (" << vex::type_name<key_type>() << ")\n"
        << "    VexCL:         " << N * M / tot_time << " keys/sec\n";

#ifdef VEXCL_HAVE_BOOST_COMPUTE
    X1 = X0;
    vex::compute::sort(X1);

    tot_time = 0;
    for(size_t i = 0; i < M; i++) {
        X1 = X0;
        ctx.finish();
        prof.tic_cpu("Boost.Compute");
        vex::compute::sort(X1);
        ctx.finish();
        tot_time += prof.toc("Boost.Compute");
    }

    std::cout
        << "    Boost.Compute: " << N * M / tot_time << " keys/sec\n";
#endif

#ifdef VEXCL_HAVE_CLOGS
    X1 = X0;
    vex::clogs::sort(X1);

    tot_time = 0;
    for(size_t i = 0; i < M; i++) {
        X1 = X0;
        ctx.finish();
        prof.tic_cpu("CLOGS");
        vex::clogs::sort(X1);
        ctx.finish();
        tot_time += prof.toc("CLOGS");
    }

    std::cout
        << "    CLOGS:         " << N * M / tot_time << " keys/sec\n";
#endif

    if (options.bm_cpu) {
        tot_time = 0;
        for(size_t i = 0; i < M; i++) {
            std::copy(x0.begin(), x0.end(), x1.begin());
            prof.tic_cpu("STL");
            std::sort(x1.begin(), x1.end());
            tot_time += prof.toc("STL");
        }

        std::cout << "    STL:           " << N * M / tot_time << " keys/sec\n";
    }

    std::cout << std::endl;
}

//---------------------------------------------------------------------------
template <typename real>
void benchmark_scan(
        const vex::Context &ctx, vex::profiler<> &prof
        )
{
    const size_t N = 16 * 1024 * 1024;
    const size_t M = 16;

    typedef typename std::conditional<
        std::is_same<float, real>::value, cl_uint, cl_ulong
        >::type key_type;

    std::default_random_engine rng( std::rand() );
    std::uniform_int_distribution<key_type> rnd;

    std::vector<key_type> x0(N);
    std::vector<key_type> x1(N);

    std::generate(x0.begin(), x0.end(), [&]() { return rnd(rng); });

    vex::vector<key_type> X0(ctx, x0);
    vex::vector<key_type> X1(ctx, N);

    vex::exclusive_scan(X0, X1);

    ctx.finish();
    prof.tic_cpu("VexCL");

    for(size_t i = 0; i < M; i++)
        vex::exclusive_scan(X0, X1);

    ctx.finish();
    double tot_time = prof.toc("VexCL");

    std::cout
        << "Scan (" << vex::type_name<key_type>() << ")\n"
        << "    VexCL:         " << N * M / tot_time << " keys/sec\n";

#ifdef VEXCL_HAVE_BOOST_COMPUTE
    vex::compute::exclusive_scan(X0, X1);

    ctx.finish();
    prof.tic_cpu("Boost.Compute");

    for(size_t i = 0; i < M; i++)
        vex::compute::exclusive_scan(X0, X1);

    ctx.finish();
    tot_time = prof.toc("Boost.Compute");

    std::cout
        << "    Boost.Compute: " << N * M / tot_time << " keys/sec\n";
#endif

#ifdef VEXCL_HAVE_CLOGS
    vex::clogs::exclusive_scan(X0, X1);

    ctx.finish();
    prof.tic_cpu("CLOGS");

    for(size_t i = 0; i < M; i++)
        vex::clogs::exclusive_scan(X0, X1);

    ctx.finish();
    tot_time = prof.toc("CLOGS");

    std::cout
        << "    CLOGS:         " << N * M / tot_time << " keys/sec\n";
#endif

    if (options.bm_cpu) {
        prof.tic_cpu("CPU");
        for(size_t i = 0; i < M; i++) {
            key_type sum = key_type();
            for(size_t j = 0; j < N; ++j) {
                key_type next = sum + x0[j];
                x1[j] = sum;
                sum = next;
            }
        }
        tot_time = prof.toc("CPU");

        std::cout << "    CPU:           " << N * M / tot_time << " keys/sec\n";
    }

    std::cout << std::endl;
}

//---------------------------------------------------------------------------
template <typename real>
void run_tests(const vex::Context &ctx, vex::profiler<> &prof)
{
    std::cout
        << "----------------------------------------------------------\n"
        << "Profiling \"" << vex::type_name<real>() << "\" performance\n"
        << "----------------------------------------------------------\n"
        << ctx << std::endl;

    std::ostringstream fname;
    fname << "profile_" << vex::type_name<real>() << ".dat";
    std::ofstream log(fname.str().c_str(), std::ios::app);

    log << ctx.size() << " ";

    double gflops, bwidth;

    prof.tic_cpu( vex::type_name<real>() );

    if (options.bm_saxpy) {
        prof.tic_cpu("Vector SAXPY");
        std::tie(gflops, bwidth) = benchmark_saxpy<real>(ctx, prof);
        prof.toc("Vector SAXPY");

        log << gflops << " " << bwidth << " ";
    }

    if (options.bm_vector) {
        prof.tic_cpu("Vector arithmetic");
        std::tie(gflops, bwidth) = benchmark_vector<real>(ctx, prof);
        prof.toc("Vector arithmetic");

        log << gflops << " " << bwidth << " ";
    }

    if (options.bm_reductor) {
        prof.tic_cpu("Reduction");
        std::tie(gflops, bwidth) = benchmark_reductor<real>(ctx, prof);
        prof.toc("Reduction");

        log << gflops << " " << bwidth << " ";
    }

    if (options.bm_stencil) {
        prof.tic_cpu("Stencil");
        std::tie(gflops, bwidth) = benchmark_stencil<real>(ctx, prof);
        prof.toc("Stencil");

        log << gflops << " " << bwidth << " ";
    }

    if (options.bm_spmv) {
        prof.tic_cpu("SpMV");
        std::tie(gflops, bwidth) = benchmark_spmv<real>(ctx, prof);
        prof.toc("SpMV");

        log << gflops << " " << bwidth << std::endl;

        prof.tic_cpu("SpMV (CCSR)");
        std::tie(gflops, bwidth) = benchmark_spmv_ccsr<real>(ctx, prof);
        prof.toc("SpMV (CCSR)");
    }

    if (options.bm_rng) {
        prof.tic_cpu("Random number generation");
        benchmark_rng<real>(ctx, prof);
        prof.toc("Random number generation");
    }

    if (options.bm_sort) {
        prof.tic_cpu("Sorting");
        benchmark_sort<real>(ctx, prof);
        prof.toc("Sorting");
    }

    if (options.bm_scan) {
        prof.tic_cpu("Scanning");
        benchmark_scan<real>(ctx, prof);
        prof.toc("Scanning");
    }

    prof.toc( vex::type_name<real>() );

    std::cout << std::endl << std::endl;
}

//---------------------------------------------------------------------------
int main(int argc, char *argv[]) {
    namespace po = boost::program_options;
    po::options_description desc("Options");

    desc.add_options()
        ("help,h", "show help")
        ("revert,r", "revert options")
        ("bm_saxpy",
            po::value<bool>(&options.bm_saxpy)->default_value(true),
            "benchmark SAXPY (on/off)"
            )
        ("bm_vec",
            po::value<bool>(&options.bm_vector)->default_value(true),
            "benchmark vector arithmetics (on/off)"
            )
        ("bm_rdc",
            po::value<bool>(&options.bm_reductor)->default_value(true),
            "benchmark reduction (on/off)"
            )
        ("bm_stn",
            po::value<bool>(&options.bm_stencil)->default_value(true),
            "benchmark stencil convolution (on/off)"
            )
        ("bm_spm",
            po::value<bool>(&options.bm_spmv)->default_value(true),
            "benchmark sparse matrix - vector product (on/off)"
            )
        ("bm_rng",
            po::value<bool>(&options.bm_rng)->default_value(true),
            "benchmark random number generation (on/off)"
            )
        ("bm_sort",
            po::value<bool>(&options.bm_sort)->default_value(true),
            "benchmark sorting (on/off)"
            )
        ("bm_scan",
            po::value<bool>(&options.bm_sort)->default_value(true),
            "benchmark exclusive scan (on/off)"
            )
        ("bm_cpu",
            po::value<bool>(&options.bm_cpu)->default_value(true),
            "benchmark host CPU performance (on/off)"
            )
        ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }

    if (vm.count("revert")) {
        options.revert();
    }

    try {
        vex::profiler<> prof;

        {
            vex::Context ctx(vex::Filter::Env && vex::Filter::DoublePrecision);
            if (ctx) run_tests<double>(ctx, prof);
        }

        {
            vex::Context ctx(vex::Filter::Env);
            if (ctx) run_tests<float>(ctx, prof);
        }

        std::cout << prof << std::endl;
    } catch (const vex::error &e) {
        std::cerr << e << std::endl;
        return 1;
    }
}

// vim: et

max_stars_repo_name: lkusch/Kratos

max_issues_repo_name: lkusch/Kratos

max_forks_repo_name: lkusch/Kratos


text:
//
// Copyright (c) 2011-2012 Krzysztof Jusiak (krzysztof at jusiak dot net)
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef QFSM_BACK_DETAIL_UNEXPECTEDEVENT_HPP
#define QFSM_BACK_DETAIL_UNEXPECTEDEVENT_HPP

#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include "QFsm/Back/Aux/TransitionTypes.hpp"
#include "QFsm/Back/Aux/Contains.hpp"
#include "QFsm/Back/Detail/Visitor.hpp"
#include "QFsm/Front/Operations/None.hpp"

namespace QFsm
{
namespace Back
{
namespace Detail
{

template<typename TFsmBase>
class UnexpectedEvent
{
    template<typename Event> class UnexpectedEventVisitor
    {
    public:
        UnexpectedEventVisitor(typename TFsmBase::Pool& p_pool, const Event& p_event)
            : m_pool(p_pool), m_event(p_event)
        { }

        template<typename State> void operator()() const
        {
            TRACE("unexpected event [%s]", typeid(Event).name());
            TFsmBase::Log::template onUnexpectedEventReceived<State>(m_pool);
            (m_pool.template acquire<typename TFsmBase::Derived::UnexpectedEvent>()).operator()<Event, State>(m_event);
        }

    private:
        typename TFsmBase::Pool& m_pool;
        const Event& m_event;
    };

public:
    template<typename Event> static bool execute(TFsmBase&, const Event&, bool p_isHandled, typename boost::enable_if< boost::is_base_of<Front::Operations::None, Event> >::type* = 0)
    {
        return p_isHandled;
    }

    template<typename Event> static bool execute(TFsmBase& p_fsm, const Event& p_event, bool p_isHandled, typename boost::disable_if< boost::is_base_of<Front::Operations::None, Event> >::type* = 0)
    {
        if (!p_isHandled)
        {
            UnexpectedEventVisitor<Event> l_visitor(p_fsm.pool, p_event);
            Detail::Visitor<TFsmBase>::execute(p_fsm, l_visitor);
        }

        return p_isHandled;
    }
};

} // namespace Detail
} // namespace Back
} // namespace QFsm

#endif

max_stars_repo_name: krzysztof-jusiak/qfsm

max_issues_repo_name: krzysztof-jusiak/qfsm

max_forks_repo_name: krzysztof-jusiak/qfsm


text:
/*
 Copyright (C) 2016 Quaternion Risk Management Ltd
 All rights reserved.

 This file is part of ORE, a free-software/open-source library
 for transparent pricing and risk analysis - http://opensourcerisk.org

 ORE is free software: you can redistribute it and/or modify it
 under the terms of the Modified BSD License.  You should have received a
 copy of the license along with this program.
 The license is also available online at <http://opensourcerisk.org>

 This program is distributed on the basis that it will form a useful
 contribution to risk analytics and model standardisation, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/

#include "toplevelfixture.hpp"
#include <boost/test/unit_test.hpp>
#include <ql/time/calendars/target.hpp>
#include <qle/calendars/belgium.hpp>
#include <ql/time/schedule.hpp>

using namespace QuantLib;
using namespace QuantExt;
using namespace boost::unit_test_framework;
using namespace std;

namespace check {

    void checkDates(const Schedule& s,
                     const std::vector<Date>& expected) {
        BOOST_CHECK(s.size() == expected.size());
        for (Size i=0; i<expected.size(); ++i) {
            if (s[i] != expected[i]) {
                BOOST_ERROR("expected " << expected[i]
                            << " at index " << i << ", "
                            "found " << s[i]);
            }
        }
    }
    void checkDay(const Schedule& s,
                     Weekday w) {
        //we check all but the first and last dates
        for (Size i=1; i<s.size() - 1; ++i) {
            if (s[i].weekday() != w) {
                BOOST_ERROR("expected " << w
                            << " at index " << i << ", "
                            "found " << s[i].weekday());
            }
        }
    }
} // namespace check

BOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)

BOOST_AUTO_TEST_SUITE(DateGenerationTest)

BOOST_AUTO_TEST_CASE(testThirdThursday) {

    BOOST_TEST_MESSAGE("Testing ThirdThursday DateGeneration rule");

    std::vector<Date> expectedDates;

    expectedDates.push_back(Date(12, December, 2016));
    expectedDates.push_back(Date(16, March, 2017));
    expectedDates.push_back(Date(15, June, 2017));
    expectedDates.push_back(Date(21, September, 2017));
    expectedDates.push_back(Date(21, December, 2017));
    expectedDates.push_back(Date(15, March, 2018));
    expectedDates.push_back(Date(21, June, 2018));
    expectedDates.push_back(Date(20, September, 2018));
    expectedDates.push_back(Date(12, December, 2018));

    Schedule s =
        MakeSchedule().from(Date(12, December, 2016))
                      .to(Date(12, December, 2016) + Period(2, Years))
                      .withCalendar(TARGET())
                      .withTenor(3*Months)
                      .withConvention(ModifiedFollowing)
                      .withTerminationDateConvention(Unadjusted)
                      .withRule(DateGeneration::ThirdThursday);

    check::checkDates(s, expectedDates);
    check::checkDay(s, Thursday);
}

BOOST_AUTO_TEST_CASE(testThirdFriday) {

    BOOST_TEST_MESSAGE("Testing ThirdFriday DateGeneration rule");

    std::vector<Date> expectedDates;

    expectedDates.push_back(Date(12, December, 2016));
    expectedDates.push_back(Date(17, March, 2017));
    expectedDates.push_back(Date(16, June, 2017));
    expectedDates.push_back(Date(15, September, 2017));
    expectedDates.push_back(Date(15, December, 2017));
    expectedDates.push_back(Date(16, March, 2018));
    expectedDates.push_back(Date(15, June, 2018));
    expectedDates.push_back(Date(21, September, 2018));
    expectedDates.push_back(Date(12, December, 2018));

    Schedule s =
        MakeSchedule().from(Date(12, December, 2016))
                      .to(Date(12, December, 2016) + Period(2, Years))
                      .withCalendar(TARGET())
                      .withTenor(3*Months)
                      .withConvention(ModifiedFollowing)
                      .withTerminationDateConvention(Unadjusted)
                      .withRule(DateGeneration::ThirdFriday);

    check::checkDates(s, expectedDates);
    check::checkDay(s, Friday);
}

BOOST_AUTO_TEST_CASE(testMondayAfterThirdFriday) {

    BOOST_TEST_MESSAGE("Testing MondayAfterThirdFriday DateGeneration rule");

    std::vector<Date> expectedDates;

    expectedDates.push_back(Date(12, December, 2016));
    expectedDates.push_back(Date(20, March, 2017));
    expectedDates.push_back(Date(19, June, 2017));
    expectedDates.push_back(Date(18, September, 2017));
    expectedDates.push_back(Date(18, December, 2017));
    expectedDates.push_back(Date(19, March, 2018));
    expectedDates.push_back(Date(18, June, 2018));
    expectedDates.push_back(Date(24, September, 2018));
    expectedDates.push_back(Date(12, December, 2018));

    Schedule s =
        MakeSchedule().from(Date(12, December, 2016))
                      .to(Date(12, December, 2016) + Period(2, Years))
                      .withCalendar(TARGET())
                      .withTenor(3*Months)
                      .withConvention(ModifiedFollowing)
                      .withTerminationDateConvention(Unadjusted)
                      .withRule(DateGeneration::MondayAfterThirdFriday);

    check::checkDates(s, expectedDates);
    check::checkDay(s, Monday);
}

BOOST_AUTO_TEST_CASE(testTuesdayAfterThirdFriday) {

    BOOST_TEST_MESSAGE("Testing TuesdayAfterThirdFriday DateGeneration rule");

    std::vector<Date> expectedDates;

    expectedDates.push_back(Date(12, December, 2016));
    expectedDates.push_back(Date(21, March, 2017));
    expectedDates.push_back(Date(20, June, 2017));
    expectedDates.push_back(Date(19, September, 2017));
    expectedDates.push_back(Date(19, December, 2017));
    expectedDates.push_back(Date(20, March, 2018));
    expectedDates.push_back(Date(19, June, 2018));
    expectedDates.push_back(Date(25, September, 2018));
    expectedDates.push_back(Date(12, December, 2018));

    Schedule s =
        MakeSchedule().from(Date(12, December, 2016))
                      .to(Date(12, December, 2016) + Period(2, Years))
                      .withCalendar(TARGET())
                      .withTenor(3*Months)
                      .withConvention(ModifiedFollowing)
                      .withTerminationDateConvention(Unadjusted)
                      .withRule(DateGeneration::TuesdayAfterThirdFriday);

    check::checkDates(s, expectedDates);
    check::checkDay(s, Tuesday);
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: mrslezak/Engine

max_issues_repo_name: mrslezak/Engine

max_forks_repo_name: mrslezak/Engine


text:
#include "problemes.h"
#include "arithmetique.h"
#include "timer.h"

#include <boost/range/adaptor/reversed.hpp>

typedef unsigned long long nombre;
typedef std::vector<nombre> vecteur;

namespace {
    nombre maximum(const vecteur &fibonacci, const nombre &n) {
        for (const auto &f: boost::adaptors::reverse(fibonacci)) {
            if (f < n)
                return f;
        }

        return fibonacci.back();
    }

    nombre Zeckendorf(const vecteur &fibonacci, const nombre n) {
        if (n < 2)
            return 0;

        static std::map<nombre, nombre> cache;

        if (auto it = cache.find(n);it != cache.end())
            return it->second;

        nombre m = maximum(fibonacci, n);

        nombre resultat = n - m + Zeckendorf(fibonacci, m) + Zeckendorf(fibonacci, n - m);

        cache[n] = resultat;
        return resultat;
    }
}

ENREGISTRER_PROBLEME(297, "Zeckendorf Representation") {
    // Each new term in the Fibonacci sequence is generated by adding the previous two terms. Starting with 1 and 2, the
    // first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89.
    //
    // Every positive integer can be uniquely written as a sum of nonconsecutive terms of the Fibonacci sequence. For
    // example, 100 = 3 + 8 + 89. Such a sum is called the Zeckendorf representation of the number.
    //
    // For any integer n>0, let z(n) be the number of terms in the Zeckendorf representation of n.
    // Thus, z(5) = 1, z(14) = 2, z(100) = 3 etc.
    // Also, for 0<n<10**6, ∑ z(n) = 7894453.
    //
    // Find ∑ z(n) for 0<n<10**17.
    const auto limite = puissance::puissance<nombre, unsigned>(10, 17);
    vecteur fibonacci{1, 1};
    while (fibonacci.back() < limite) {
        fibonacci.push_back(fibonacci.back() + fibonacci.at(fibonacci.size() - 2));
    }

    nombre resultat = Zeckendorf(fibonacci, limite);
    return std::to_string(resultat);
}

max_stars_repo_name: ZongoForSpeed/ProjectEuler

max_issues_repo_name: ZongoForSpeed/ProjectEuler

max_forks_repo_name: ZongoForSpeed/ProjectEuler


text:
//          Copyright Camille Gillot 2012 - 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)

//[sm_smart_ptr
/*`
  [sm_pointer]
  [sm_specialize]
  [sm_declare]
  [sm_invoke]
 */
//]

#include "../classes.hpp"

#include <boost/test/unit_test.hpp>

using namespace rtti::mmethod;

//[sm_pointer
/*`
  In order to demonstrate the use of smart pointers
  with __mmethod__, here is a example of dispatch through
  a custom (dumb) pointer.
  The toy class we want to use is the following:
 */
// Do-nothing wrapper around raw pointer
template<typename T>
class noop_pointer {
public:
  // Constructor taking pointer
  explicit noop_pointer(T* p = NULL): px(p) {/**/}

  // Destructor: no-op
  ~noop_pointer() {/**/}

  // Copy
  noop_pointer(noop_pointer const& p)
  : px(p.px) {}
  noop_pointer& operator=(noop_pointer const& p) {
    px = p.px;
    return *this;
  }

  // Access
  typedef T element_type;
  bool valid()    const { return !!px; }

  T* get()        const { return   px; }
  T& operator* () const { return  *px; }
  T* operator->() const { return   px; }

  // Destruction
  void destroy() {
    delete px;
    px = NULL;
  }

private:
  T* px;
};
//]

//[sm_specialize
/*`
  Before declaring any __multimethod__, the `noop_pointer`
  type must be registered with __rtti__. This way, the __rtti__ subsystem
  will be able to retrieve the type informations and to downcast
  the `noop_pointer`.

  This is done via a specialization of the `__rtti_ns__::pointer_traits` structure.
 */
#include <boost/cast.hpp>

namespace rtti {

// begin partial specialization
template<typename T>
struct pointer_traits<noop_pointer<T> > {
  // pointer being manipulated
  typedef noop_pointer<T> pointer_type;

  // class being pointed to
  typedef typename boost::remove_cv<T>::type class_type;

  // check the pointer validity
  static bool valid(pointer_type const& v) { return v.valid(); }

  // fetch the pointed value
  static T& get(pointer_type const& v) { return *v; }

  // downcast the pointer
  template<typename U>
  static typename boost::remove_reference<U>::type
  cast(pointer_type const& v);
};

/*`
  The following method is used by the __mmethod__ system
  to downcast the passed pointers.

  The template parameter is the target pointer type.
  The function argument is the source pointer.
  `cast<U>(p)` must return an object convertible to type `U`,
  with value the pointer `p` casted to the right destination type.
  The type `U` will be the exact type expected by the
  __multimethod__ implementation,
  so it is often a constant reference to `noop_pointer`.
 */
template<typename T>
template<typename U>
typename boost::remove_reference<U>::type
pointer_traits<noop_pointer<T> >::cast(pointer_type const& v)
{
  typedef typename rtti::traits_detail::remove_all<U>::type Uclass;
  typedef typename Uclass::element_type O;
  O* po = boost::polymorphic_downcast<O*>(v.get());
  return Uclass(po);
}

} // namespace rtti
//]

namespace {

//[sm_declare
/*`
  Our `noop_pointer` type can now be used as a dispatched
  parameter, without further alteration of the __multimethod__ syntax.
 */
using tags::_v;
DECLARE_MMETHOD(smp, int, (_v<noop_pointer<foo> const&>));

/*`
  Our pointer type can now be used on the implementation function.
  When a call will be performed,
  the function `pointer_traits<noop_pointer<foo> >::cast<U>`
  will be called,
  with `U` the exact type appearing in the implementation definition.
  Here, the needed instantiations are respectively
  `U = noop_pointer<foo> const&`, `U = noop_pointer<bar> const&`
  and `U = noop_pointer<baz> const&`.
 */
IMPLEMENT_MMETHOD(smp, int, (noop_pointer<foo> const& a)) { return a->f(); }
IMPLEMENT_MMETHOD(smp, int, (noop_pointer<bar> const& a)) { return a->g(); }
IMPLEMENT_MMETHOD(smp, int, (noop_pointer<baz> const& a)) { return 2 * a->f(); }
//]

} // namespace

BOOST_AUTO_TEST_CASE(test_smart_ptr) {
  //[sm_invoke
  /*`
    Finally, the invocation of the __multimethod__
    is transparent for the user,
    everything behaves as with a native function taking `noop_pointer<foo>`
    by constant reference.
   */
  noop_pointer<foo> f ( new foo );
  noop_pointer<foo> r ( new bar );
  noop_pointer<foo> z ( new baz );
  noop_pointer<foo> l ( new lap );

  BOOST_CHECK_EQUAL( smp(f),  5 );
  BOOST_CHECK_EQUAL( smp(r), 42 );
  BOOST_CHECK_EQUAL( smp(z), 10 );
  BOOST_CHECK_EQUAL( smp(l), 42 ); // (lap is-a bar)

  f.destroy();
  r.destroy();
  z.destroy();
  l.destroy();
  //]
}

max_stars_repo_name: cjgillot/rtti

max_issues_repo_name: cjgillot/rtti

max_forks_repo_name: cjgillot/rtti


text:
#include "restfulservice.h"
#include "mongoose/mongoose.h"

#include <Helium/smiles.h>
#include <Helium/algorithms/isomorphism.h>

#include <signal.h>

#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>

#ifdef _WIN32
#define WINCDECL __cdecl
#else
#define WINCDECL
#endif

#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <boost/lexical_cast.hpp>

using namespace std;

// Have to define global instance as callback is C
static Helium::RESTfulService service;

// This function will be called by mongoose on every new request.
static int begin_request_handler(struct mg_connection *conn)
{
  return service.handleRequest(conn);
}

namespace Helium {

static string PREFIX = "/helium/";
static string SIMILARITY = "similarity";
static string SUBSTRUCTURE = "substructure";
static double TMIN =  0.7 - 10e-5;

RESTfulService::RESTfulService()
  : m_similarityIndex(NULL)
{

}

RESTfulService::~RESTfulService()
{
  delete m_similarityIndex;
}

string RESTfulService::createResponse(const string &status, const string &type,
    const string &content)
{
  ostringstream response;
  response << "HTTP/1.1 ";
  response << status << "\r\n";
  response << "Content-Type: ";
  response << type << "\r\n";
  response << "Content-Length: ";
  response << content.size() << "\r\n";
  response << "\r\n";
  response << content;

  return response.str();
}

int RESTfulService::handleRequest(struct mg_connection *conn)
{
  const struct mg_request_info *request_info = mg_get_request_info(conn);

  string method = request_info->request_method;
  string uri = request_info->uri;
  string queryString = request_info->query_string;

  // Is this a supported method
  if (method != "GET") {
    string response = createResponse("405 Method Not Allowed", "text/plain",
        "Unsupported method");
    mg_write(conn, response.c_str(), response.length());
    return 1;
  }

  // Now parse the URI
  if (uri.find(PREFIX) == string::npos) {
    string response = createResponse("404 Not Found", "text/plain",
        "Not Found");
    mg_write(conn, response.c_str(), response.length());
    return 1;
  }

  // Get the query var
  char buf[1024];

  int length = mg_get_var(request_info->query_string, queryString.length(),
      "q", buf, 1024);
  if (length <= 0) {
    string response = createResponse("400 Bad Request", "text/plain",
        "A query value must be provided");
    mg_write(conn, response.c_str(), response.length());
    return 1;
  }

  string query(buf, length);

  // Get the pretty var
  length = mg_get_var(request_info->query_string, queryString.length(),
      "pretty", buf, 1024);

  bool pretty = false;
  if (length == 0) {
    pretty = true;
  }
  else if (length > 0) {
    pretty = string(buf, length) == "true";
  }

  // Get the limit var
  length = mg_get_var(request_info->query_string, queryString.length(),
      "limit", buf, 1024);

  unsigned int limit = 100;
  if (length > 0) {
    try {
      limit = boost::lexical_cast<unsigned int>(string(buf, length));
    }
    catch(boost::bad_lexical_cast const&) {
      // Use the default
    }
  }

  try {
    // Substructure
    if (uri.find(SUBSTRUCTURE, PREFIX.length()) == PREFIX.length()) {

      // Are the necessary files loaded
      if (m_subStructureStorage.numFingerprints() == 0
          || m_moleculeFile.numMolecules() == 0) {
        string response = createResponse("503 Bad  Service Unavailable", "text/plain",
             "Service unavailable while indexes are loading");
        mg_write(conn, response.c_str(), response.length());
        return 1;
      }

      string result = subStructureSearch(query, pretty, limit);
      string response = createResponse("200 OK", "application/json", result);
      mg_write(conn, response.c_str(), response.length());
      return 1;
    }
    // Similarity
    else if (uri.find(SIMILARITY, PREFIX.length()) == PREFIX.length()) {

      // Is the index loaded?
      if (m_similarityIndex == NULL) {
        string response = createResponse("503 Bad  Service Unavailable", "text/plain",
             "Service unavailable while indexes are loading");
        mg_write(conn, response.c_str(), response.length());
        return 1;
      }

      string result = similaritySearch(query, pretty, limit);
      string response = createResponse("200 OK", "application/json", result);
      mg_write(conn, response.c_str(), response.length());
      return 1;
    }
    else {
      string response = createResponse("404 Not Found", "text/plain",
            "Supported searches are \"similarity\" and \"substructure\"");
      mg_write(conn, response.c_str(), response.length());
      return 1;
    }
  }
  catch (Smiley::Exception &exception) {
    string response = createResponse("400 Bad Request", "text/plain",
      exception.what());
    mg_write(conn, response.c_str(), response.length());
    return 1;
  }

}

Word* RESTfulService::computeFingerprint(const std::string &settings,
    const std::string &smiles)
{
  HeMol mol;
  Smiles SMILES;
  if (!SMILES.read(smiles, mol))
    throw std::runtime_error(SMILES.error().what());

  return computeFingerprint(settings, mol);
}

Word* RESTfulService::computeFingerprint(const std::string &settings,
    HeMol &mol)
{
  Json::Reader reader;
  Json::Value data;

  if (!reader.parse(settings, data)) {
    std::cerr << reader.getFormattedErrorMessages() << std::endl;
    return 0;
  }

  int bits = data["num_bits"].asInt();
  int words = bitvec_num_words_for_bits(bits);
  int k = data["fingerprint"]["k"].asInt();
  int prime = data["fingerprint"]["prime"].asInt();
  std::string type = data["fingerprint"]["type"].asString();

  Word *fingerprint = new Word[words];

  if (type == "Helium::paths_fingerprint") {
    path_fingerprint(mol, fingerprint, k, words, prime);
    return fingerprint;
  }

  if (type == "Helium::trees_fingerprint") {
    tree_fingerprint(mol, fingerprint, k, words, prime);
    return fingerprint;
  }

  if (type == "Helium::subgraph_fingerprint") {
    subgraph_fingerprint(mol, fingerprint, k, words, prime);
    return fingerprint;
  }

  logError("Fingerprint type \"" + type + "\" not recognised");

  delete [] fingerprint;
  return 0;
}

string RESTfulService::similaritySearch(const string &query, bool pretty,
    unsigned int limit)
{
  Word *fingerPrint = computeFingerprint(m_similarityStorage.header(), query);

  vector<pair<unsigned int, double> > result
    = m_similarityIndex->search(fingerPrint, TMIN);

  std::sort(result.begin(), result.end(),
            compare_second<unsigned int, double, std::greater>());

  if (result.size() < limit)
    limit = result.size();

  Json::Value data;
  data["hits"] = Json::Value(Json::arrayValue);
  for (std::size_t j = 0; j < limit; ++j) {
    data["hits"][Json::ArrayIndex(j)] = Json::Value(Json::objectValue);
    Json::Value &obj = data["hits"][Json::ArrayIndex(j)];
    obj["index"] = result[j].first;
    obj["tanimoto"] = result[j].second;
  }

  string content;

  if (pretty) {
    Json::StyledWriter writer;
    content = writer.write(data);
  } else {
    Json::FastWriter writer;
    content = writer.write(data);
  }

  delete[] fingerPrint;

  return content;
}

void RESTfulService::screen(Word *fingerprint, Word *result)
{
  bool first = true;
  for (int i = 0; i < m_subStructureStorage.numBits(); ++i) { // foreach bit
    // skip this bit if it is not set
    if (!bitvec_get(i, fingerprint))
      continue;

    if (first) {
      // if this is the first bit, just set result
      for (unsigned int j = 0; j < bitvec_num_words_for_bits(m_subStructureStorage.numFingerprints()); ++j)
        result[j] = m_subStructureStorage.bit(i)[j];
      first = false;
    } else {
      // do set intersection
      for (unsigned int j = 0; j < bitvec_num_words_for_bits(m_subStructureStorage.numFingerprints()); ++j)
        result[j] &= m_subStructureStorage.bit(i)[j];
    }
  }
}

string RESTfulService::subStructureSearch(const string &smiles, bool pretty,
    unsigned int limit)
{
  HeMol query;
  Smiles SMILES;
  if (!SMILES.read(smiles, query))
    throw std::runtime_error(SMILES.error().what());

  // compute query fingerprint
  Word *queryFingerprint = computeFingerprint(m_subStructureStorage.header(),
                                              query);

  // perform search
  Word *candidates = new Word[bitvec_num_words_for_bits(
                                m_subStructureStorage.numFingerprints())];

  screen(queryFingerprint, candidates);

  HeMol mol;
  std::vector<Index> result;
  int can =0;
  for (unsigned int i = 0; i < m_moleculeFile.numMolecules(); ++i) {
    if (bitvec_get(i, candidates)) {
      ++can;
      m_moleculeFile.readMolecule(i, mol);
      DefaultAtomMatcher<HeMol, HeMol> atomMatcher;
      DefaultBondMatcher<HeMol, HeMol> bondMatcher;
      if (isomorphism_search(mol, query, atomMatcher, bondMatcher))
        result.push_back(i);
    }

    if (result.size() == limit)
      break;
  }

  // print results
  Json::Value data;
  data["hits"] = Json::Value(Json::arrayValue);
  data["screened"] = Json::Value(bitvec_count(candidates,
                                 bitvec_num_words_for_bits(
                                     m_subStructureStorage.numFingerprints())));
  data["confirmed"] = Json::Value(static_cast<unsigned int>(result.size()));
  data["false_positives"] = Json::Value(1.0 - static_cast<double>(result.size())
      / bitvec_count(candidates,
          bitvec_num_words_for_bits(m_subStructureStorage.numFingerprints())));
  for (std::size_t i = 0; i < result.size(); ++i) {
    data["hits"][Json::ArrayIndex(i)] = Json::Value(Json::objectValue);
    Json::Value &obj = data["hits"][Json::ArrayIndex(i)];
    obj["index"] = result[i];
  }

  // deallocate fingerprint
  if (queryFingerprint)
    delete [] queryFingerprint;
  delete [] candidates;

  string content;

  if (pretty) {
    Json::StyledWriter writer;
    content = writer.write(data);
  } else {
    Json::FastWriter writer;
    content = writer.write(data);
  }

  return content;
}

void RESTfulService::init(const string &similarityIndex,
    const string &subStructureIndex, const string &moleculeFile)
{
  m_similarityStorage.load(similarityIndex);
  m_similarityIndex
    = new Helium::SimilaritySearchIndex<Helium::InMemoryRowMajorFingerprintStorage>(m_similarityStorage, 3);
  logInfo("Similarity index loaded: " + similarityIndex);
  m_subStructureStorage.load(subStructureIndex);
  logInfo("Substructure index loaded: " + subStructureIndex);
  m_moleculeFile.load(moleculeFile);
  logInfo("Molecules loaded: " + moleculeFile);
}

void RESTfulService::logInfo(const string &msg)
{
  cout << "[INFO] " << msg << endl;
}

void RESTfulService::logError(const string &msg)
{
  cerr << "[ERROR] " << msg << endl;
}

}

static int signal_number;

static void WINCDECL signal_handler(int sig_num) {
  signal_number = sig_num;
}

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

  // Process arguments
  int port;
  po::options_description desc("Options");
  desc.add_options()
    ("help", "produce help message")
    ("port", po::value<int>(&port)->default_value(8080), "the port to listen on")
    ("simindex", po::value<string>(), "similarity fingerprint index file")
    ("subindex", po::value<string>(), "substructure fingerprint index file")
    ("mol", po::value<string>(), "molecule file");

  po::variables_map vm;
  po::store(parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  if (vm.count("help") || !vm.count("simindex") || !vm.count("subindex")
      || !vm.count("mol")) {
    cerr << desc << endl;
    return 1;
  }

  string similarityIndex = vm["simindex"].as<string>();
  string subStructureIndex = vm["subindex"].as<string>();
  string molecules = vm["mol"].as<string>();

  struct mg_context *ctx;
  struct mg_callbacks callbacks;

  string portString = boost::lexical_cast<string>(port);

  // List of options. Last element must be NULL.
  const char *options[] = {"listening_ports", portString.c_str(),
                           NULL};

  string version = mg_version();
  service.logInfo("Mongoose version " + version);

  service.logInfo("Service listening on: " + portString);

  // Prepare callbacks structure. We have only one callback, the rest are NULL.
  memset(&callbacks, 0, sizeof(callbacks));
  callbacks.begin_request = begin_request_handler;

  // Start the web server.
  ctx = mg_start(&callbacks, NULL, options);

  if (!ctx) {
    service.logError("Error starting service on port: " + portString
        + " (is this port already is use?)");
    return 1;
  }

  // Load the indexes
  try {
    service.init(similarityIndex, subStructureIndex, molecules);
  } catch (const exception &e) {
    service.logError("Error loading index: " + string(e.what()));
    return 1;
  }

  service.logInfo("Ready to process requests");
  // Wait until user hits "enter". Server is running in separate thread.
  // Navigating to http://localhost:8080 will invoke begin_request_handler().

  signal(SIGTERM, signal_handler);
  signal(SIGINT, signal_handler);

  while (signal_number == 0)
    sleep(1);

  service.logInfo("Exiting with signal: "
      + boost::lexical_cast<string>(signal_number));

  // Stop the server.
  mg_stop(ctx);

  return 0;
}

max_stars_repo_name: timvdm/Helium

max_issues_repo_name: timvdm/Helium

max_forks_repo_name: timvdm/Helium


text:
#include <unet/detail/frame.hpp>

#include <cstring>

#include <boost/assert.hpp>

namespace unet {
namespace detail {

Frame::Frame(std::size_t dataLen)
    : dataLen{dataLen}, buf_{std::make_unique<std::uint8_t[]>(dataLen)} {
  data = buf_.get();
}

std::unique_ptr<Frame> Frame::makeUninitialized(std::size_t dataLen) {
  return std::unique_ptr<Frame>{new Frame{dataLen}};
}

std::unique_ptr<Frame> Frame::makeCopy(const Frame& f) {
  auto copy = makeUninitialized(f.dataLen);
  std::memcpy(copy->data, f.data, f.dataLen);
  if (f.net) {
    BOOST_ASSERT(f.net >= f.data);
    copy->net = copy->data + (f.net - f.data);
    copy->netLen = f.netLen;
  }
  if (f.transport) {
    BOOST_ASSERT(f.transport >= f.data);
    copy->transport = copy->data + (f.transport - f.data);
    copy->transportLen = f.transportLen;
  }
  return copy;
}

std::unique_ptr<Frame> Frame::makeBuf(const std::uint8_t* buf,
                                      std::size_t bufLen) {
  auto f = makeUninitialized(bufLen);
  std::memcpy(f->data, buf, bufLen);
  return f;
}

std::unique_ptr<Frame> Frame::makeStr(const std::string& s) {
  return makeBuf(reinterpret_cast<const std::uint8_t*>(s.data()), s.size());
}

bool Frame::operator==(const std::string& data) const {
  return (dataLen == data.size()) &&
         (std::memcmp(this->data,
                      reinterpret_cast<const std::uint8_t*>(data.data()),
                      dataLen) == 0);
}

}  // namespace detail
}  // namespace unet

max_stars_repo_name: andreimaximov/unet

max_issues_repo_name: andreimaximov/unet

max_forks_repo_name: andreimaximov/unet


text:
//==================================================================================================
/**
  Copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#include <boost/simd/function/ifrexp.hpp>
#include <boost/simd/function/pedantic.hpp>
#include <boost/simd/constant/nbmantissabits.hpp>
#include <boost/simd/constant/halfeps.hpp>
#include <scalar_test.hpp>

namespace bs = boost::simd;
namespace bd = boost::dispatch;

STF_CASE_TPL("Check basic behavior of pedantic_(ifrexp)", STF_IEEE_TYPES)
{
  STF_EXPR_IS ( (bs::pedantic_(bs::ifrexp)(T(0)))
              , (std::pair<T,bd::as_integer_t<T,signed>>)
              );

  auto p = bs::pedantic_(bs::ifrexp)(T(1));
  STF_EQUAL(p.first  , T(0.5));
  STF_EQUAL(p.second , T(1));
}

STF_CASE_TPL("Check behavior of pedantic_(ifrexp) on Zero", STF_IEEE_TYPES)
{
  auto r = bs::pedantic_(bs::ifrexp)(T(0));

  STF_EQUAL (r.first , T(0));
  STF_EQUAL (r.second, T(0));
  STF_EQUAL (ldexp(r.first,r.second), T(0));
}

STF_CASE_TPL("Check behavior of pedantic_(ifrexp) on Valmax", STF_IEEE_TYPES)
{
  auto r = bs::pedantic_(bs::ifrexp)(bs::Valmax<T>());

  STF_ULP_EQUAL (r.first , T(1)-bs::Halfeps<T>(), 1);
  STF_EQUAL     (r.second, bs::Limitexponent<T>());
  STF_EQUAL     (ldexp(r.first,r.second),bs::Valmax<T>());
}

#ifndef BOOST_SIMD_NO_INVALID
#include <boost/simd/constant/nan.hpp>

STF_CASE_TPL("Check behavior of pedantic_(ifrexp) on NaN", STF_IEEE_TYPES)
{
  auto r = bs::pedantic_(bs::ifrexp)(bs::Nan<T>());

  STF_IEEE_EQUAL(r.first , bs::Nan<T>());
  STF_EQUAL     (r.second, T(0));
  STF_IEEE_EQUAL(ldexp(r.first,r.second), bs::Nan<T>());
}
#endif

#ifndef BOOST_SIMD_NO_INFINITIES
#include <boost/simd/constant/inf.hpp>
#include <boost/simd/constant/minf.hpp>

STF_CASE_TPL("Check behavior of pedantic_(ifrexp) on infinites", STF_IEEE_TYPES)
{
  auto r = bs::pedantic_(bs::ifrexp)(bs::Inf<T>());
  auto q = bs::pedantic_(bs::ifrexp)(bs::Minf<T>());

  STF_IEEE_EQUAL(r.first , bs::Inf<T>());
  STF_EQUAL     (r.second, T(0));
  STF_IEEE_EQUAL(ldexp(r.first,r.second), bs::Inf<T>());

  STF_IEEE_EQUAL(q.first , bs::Minf<T>());
  STF_EQUAL     (q.second, T(0));
  STF_IEEE_EQUAL(ldexp(q.first,q.second), bs::Minf<T>());
}
#endif

#ifndef BOOST_SIMD_NO_DENORMALS
#include <boost/simd/detail/constant/minexponent.hpp>
#include <boost/simd/constant/mindenormal.hpp>

STF_CASE_TPL("Check behavior of pedantic_(ifrexp) on denormals", STF_IEEE_TYPES)
{
  auto r = bs::pedantic_(bs::ifrexp)(bs::Mindenormal<T>());

  STF_ULP_EQUAL (r.first, T(0.5), 1);
  STF_EQUAL     (r.second, bs::Minexponent<T>()-bs::Nbmantissabits<T>()+1);
  STF_EQUAL     (ldexp(r.first,r.second),bs::Mindenormal<T>());
}
#endif