text:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <sys/time.h>

#include <boost/unordered_map.hpp>

#include "SignalRoutine.h"
#include "../Log.h"
#define CANARY_THREADS_MAX 32
/*
 * Define global log variables, each shared var has one
 */
static std::vector<g_llog_t *> llogs; // <g_llog_t *> size is not fixed, and should be determined at runtime
static g_flog_t flog;
static g_mlog_t mlog;

static l_rlog_t* rlogs[CANARY_THREADS_MAX];
static l_lrlog_t* lrlogs[CANARY_THREADS_MAX];
static l_wlog_t* wlogs[CANARY_THREADS_MAX];
static l_addmap_t* addlogs[CANARY_THREADS_MAX];

/*
 * number of shared variables
 */
static unsigned num_shared_vars = 0;
static unsigned num_local_vars = 0;

/*
 * set of active threads, not the original tid
 */
static std::set<unsigned> active_threads;

/*
 * locks for synchronization, each shared var has one
 */
static pthread_mutex_t* locks;
static pthread_mutex_t fork_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mutex_init_lock = PTHREAD_MUTEX_INITIALIZER;

/**/
static void * recorded_heap_start = NULL;
static void * recorded_heap_end = NULL;

static inline void lock(unsigned svId) {
    pthread_mutex_lock(&locks[svId]);
}

static inline void unlock(unsigned svId) {
    pthread_mutex_unlock(&locks[svId]);
}

static inline void forkLock() {
    pthread_mutex_lock(&fork_lock);
}

static inline void forkUnlock() {
    pthread_mutex_unlock(&fork_lock);
}

static inline void mutexInitLock() {
    pthread_mutex_lock(&mutex_init_lock);
}

static inline void mutexInitUnlock() {
    pthread_mutex_unlock(&mutex_init_lock);
}

extern "C" {
    extern void* get_canary_heap_start();

    extern void* get_canary_heap_end();

    void OnInit(unsigned svsNum, unsigned lvsNum) {
        printf("OnInit-Replay (canary replayer)\n");

        num_shared_vars = svsNum;
        num_local_vars = lvsNum;

        memset(addlogs, 0, sizeof (void*)*CANARY_THREADS_MAX);
        memset(wlogs, 0, sizeof (void*)*CANARY_THREADS_MAX);
        memset(rlogs, 0, sizeof (void*)*CANARY_THREADS_MAX);
        memset(lrlogs, 0, sizeof (void*)*CANARY_THREADS_MAX);

        // unzip
        int ret = system("if [ -f canary.zip ]; then unzip -o canary.zip; else exit 99; fi");
        if (WEXITSTATUS(ret) == 99) {
            printf("[ERROR] no logs can be detected!\n");
            exit(1);
        }

        {//flog
#ifdef DEBUG
            printf("loading flog...\n");
#endif
            FILE * fin = fopen("fork.dat", "rb");
            flog.load(fin);
            fclose(fin);
            printf("[INFO] Load fork.dat successfully\n");
        }

        {//mlog, llogs
#ifdef DEBUG
            printf("loading mlog, llog...\n");
#endif
            FILE * fin = fopen("mutex.dat", "rb");
            mlog.load(fin);

            unsigned size = 0;
            if(!fread(&size, sizeof (unsigned), 1, fin)){
                printf("[ERROR] IO error.");
            }

            for (unsigned i = 0; i < size; i++) {
                g_llog_t * llog = new g_llog_t;
                llog->load(fin);
                llogs.push_back(llog);
            }
            fclose(fin);
            printf("[INFO] Load mutex.dat successfully\n");
        }

        {//rlog
#ifdef DEBUG
            printf("loading rlog...\n");
#endif
            FILE * fin = fopen("read.dat", "rb");
            while (!feof(fin)) {
                unsigned tid = -1;
                fread(&tid, sizeof (unsigned), 1, fin);

                if (feof(fin)) { // we have to use feof again
                    break;
                }

                l_rlog_t* rlog = new l_rlog_t[num_shared_vars];
                rlogs[tid] = rlog;

                for (unsigned i = 0; i < num_shared_vars; i++) {
                    rlog[i].VAL_LOG.load(fin);
                    rlog[i].VER_LOG.load(fin);
                }
            }

            fclose(fin);
            printf("[INFO] Load read.dat successfully\n");
        }
        {//lrlog
#ifdef DEBUG
            printf("loading lrlog...\n");
#endif
            FILE * fin = fopen("lread.dat", "rb");
            while (!feof(fin)) {
                unsigned tid = -1;
                fread(&tid, sizeof (unsigned), 1, fin);

                if (feof(fin)) { // we have to use feof again
                    break;
                }

                l_lrlog_t* rlog = new l_lrlog_t[num_local_vars];
                lrlogs[tid] = rlog;

                for (unsigned i = 0; i < num_local_vars; i++) {
                    rlog[i].load(fin);
                }
            }

            fclose(fin);
            printf("[INFO] Load lread.dat successfully\n");
        }

        {//wlog
#ifdef DEBUG
            printf("loading wlog...\n");
#endif
            FILE * fin = fopen("write.dat", "rb");
            while (!feof(fin)) {
                unsigned tid = -1;
                fread(&tid, sizeof (unsigned), 1, fin);
                if (feof(fin)) { // we have to use feof again
                    break;
                }

                l_wlog_t* wlog = new l_wlog_t[num_shared_vars];
                wlogs[tid] = wlog;

                for (unsigned i = 0; i < num_shared_vars; i++) {
                    wlog[i].load(fin);
                }
            }

            fclose(fin);
            printf("[INFO] Load write.dat successfully\n");
        }

        {//address birthday map
#ifdef DEBUG
            printf("loading addressmap...\n");
#endif
            FILE * fin = fopen("addressmap.dat", "rb");

            fread(&recorded_heap_start, sizeof(void*), 1, fin);
            fread(&recorded_heap_end, sizeof(void*), 1, fin);

            while (!feof(fin)) {
                unsigned tid = -1;
                unsigned size = -1;

                fread(&size, sizeof (unsigned), 1, fin);
                fread(&tid, sizeof (unsigned), 1, fin);

                if (feof(fin)) { // we have to use feof again
                    break;
                }

                l_addmap_t * addmap = new l_addmap_t;
                addlogs[tid] = addmap;

                for (unsigned i = 0; i < size; i++) {
                    mem_t * m = new mem_t;
                    fread(m, sizeof (mem_t), 1, fin);
                    addmap->adds.push_back(m);
                }

            }

            fclose(fin);
            printf("[INFO] Load addressmap.dat successfully\n");
        }

        system("rm -f ./fork.dat ./mutex.dat ./addressmap.dat ./write.dat ./read.dat ./lread.dat");
    }

    void OnExit() {
        printf("OnExit-Replay (canary replayer)\n");
    }

    void OnAddressInit(void* value, size_t size, size_t n) {
    }

    void OnLoad(int svId, long address, long value, int debug) {
    }

    unsigned OnPreStore(int svId, int debug) {
        return 0;
    }

    void OnStore(int svId, unsigned version, long address, long value, int debug) {
    }

    void OnLock(pthread_mutex_t* mutex_ptr) {
    }

    void OnWait(pthread_cond_t* cond_ptr, pthread_mutex_t* mutex_ptr) {
    }

    void OnPreMutexInit(bool race) {
    }

    void OnMutexInit(pthread_mutex_t* mutex_ptr, bool race) {
    }

    void OnPreFork(bool race) {
    }

    void OnFork(pthread_t* forked_tid_ptr, bool race) {
    }

    void OnJoin(pthread_t tid, bool race) {
    }

    void OnLocal(long value, int id) {
    }

}

/* ************************************************************************
 * Signal Process
 * ************************************************************************/

void sigroutine(int dunno) {
    printSigInformation(dunno);

    OnExit();
    exit(dunno);
}

max_stars_repo_name: qingkaishi/canary

max_issues_repo_name: qingkaishi/canary

max_forks_repo_name: qingkaishi/canary


text:
/* Copyright 2016-2017 Joaquin M Lopez Munoz.
 * 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)
 *
 * See http://www.boost.org/libs/poly_collection for library home page.
 */

#include "test_insertion.hpp"

#include <algorithm>
#include <boost/core/lightweight_test.hpp>
#include <numeric>
#include <vector>
#include "any_types.hpp"
#include "base_types.hpp"
#include "function_types.hpp"
#include "test_utilities.hpp"

using namespace test_utilities;

template<typename PolyCollection,typename ValueFactory,typename... Types>
void test_insertion()
{
  {
    using unregistered_type=boost::poly_collection::unregistered_type;
    using type=first_of<constraints<is_copy_constructible>,Types...>;

    PolyCollection p,p2;
    ValueFactory   v;

    p2.insert(v.template make<type>());
    check_throw<unregistered_type>(
      [&]{p.insert(*p2.begin());},
      [&]{p.insert(p.end(),*p2.begin());},
      [&]{p.insert(p.cend(),*p2.begin());},
      [&]{p.insert(
        external_iterator(p2.begin()),external_iterator(p2.end()));},
      [&]{p.insert(
        p.end(),
        external_iterator(p2.begin()),external_iterator(p2.end()));},
      [&]{p.insert(
        p.cend(),
        external_iterator(p2.begin()),external_iterator(p2.end()));});
  }
  {
    using not_copy_constructible=
      boost::poly_collection::not_copy_constructible;
    using type=first_of<constraints<is_not_copy_constructible>,Types...>;

    PolyCollection p,p2;
    ValueFactory   v;

    p.template register_types<type>();
    p2.insert(v.template make<type>());
    auto p2b=external_iterator(p2.begin()),
         p2e=external_iterator(p2.end());
    auto p2lb=external_iterator(p2.template begin<type>()),
         p2le=external_iterator(p2.template end<type>());
    check_throw<not_copy_constructible>(
      [&]{p.insert(*p2.begin());},
      [&]{p.insert(p.end(),*p2.begin());},
      [&]{p.insert(p.cend(),*p2.cbegin());},
      [&]{p.insert(p.end(typeid(type)),*p2.begin());},
      [&]{p.insert(p.cend(typeid(type)),*p2.begin());},
      [&]{p.insert(p.template end<type>(),*p2.begin());},
      [&]{p.insert(p.template cend<type>(),*p2.begin());},
      [&]{p.insert(p2b,p2e);},
      [&]{p.insert(p2lb,p2le);},
      [&]{p.insert(p2.begin(),p2.end());},
      [&]{p.insert(p2.begin(typeid(type)),p2.end(typeid(type)));},
      [&]{p.insert(p2.template begin<type>(),p2.template end<type>());},
      [&]{p.insert(p.end(),p2b,p2e);},
      [&]{p.insert(p.end(),p2lb,p2le);},
      [&]{p.insert(p.end(),p2.begin(),p2.end());},
      [&]{p.insert(p.end(),p2.begin(typeid(type)),p2.end(typeid(type)));},
      [&]{p.insert(
        p.end(),p2.template begin<type>(),p2.template end<type>());},
      [&]{p.insert(p.cend(),p2b,p2e);},
      [&]{p.insert(p.cend(),p2lb,p2le);},
      [&]{p.insert(p.cend(),p2.begin(),p2.end());},
      [&]{p.insert(p.cend(),p2.begin(typeid(type)),p2.end(typeid(type)));},
      [&]{p.insert(
        p.cend(),p2.template begin<type>(),p2.template end<type>());},
      [&]{p.insert(p.end(typeid(type)),p2b,p2e);},
      [&]{p.insert(p.cend(typeid(type)),p2b,p2e);},
      [&]{p.insert(p.template end<type>(),p2b,p2e);},
      [&]{p.insert(p.template cend<type>(),p2b,p2e);});
  }
  {
    PolyCollection p;
    ValueFactory   v;

    fill<constraints<>,Types...>(p,v,2);

    do_((BOOST_TEST(
      is_last(
        p,typeid(Types),
        p.insert(constref_if_copy_constructible(v.template make<Types>())))
    ),0)...);
  }
  {
    PolyCollection p;
    ValueFactory   v;

    fill<constraints<>,Types...>(p,v,2);

    auto& info=p.segment_traversal().begin()->type_info();
    do_((BOOST_TEST(
      info==typeid(Types)?
        is_first(
          p,typeid(Types),
          p.insert(
            p.cbegin(),
            constref_if_copy_constructible(v.template make<Types>()))):
        is_last(
          p,typeid(Types),
          p.insert(
            p.cbegin(),
            constref_if_copy_constructible(v.template make<Types>())))
    ),0)...);

    do_((BOOST_TEST(
      is_first(
        p,typeid(Types),
        p.insert(
          p.cbegin(typeid(Types)),
          constref_if_copy_constructible(v.template make<Types>())))
    ),0)...);

    do_((BOOST_TEST(
      is_first<Types>(
        p,
        p.insert(
          p.template cbegin<Types>(),
          constref_if_copy_constructible(v.template make<Types>())))
    ),0)...);
  }
  {
    PolyCollection p,p2;
    ValueFactory   v;

    p.template register_types<Types...>();
    p2.template register_types<Types...>();
    fill<
      constraints<is_copy_constructible,is_equality_comparable>,
      Types...
    >(p2,v,2);

    p.insert(external_iterator(p2.begin()),external_iterator(p2.end()));
    BOOST_TEST(p==p2);
    p.clear();

    p.insert(p2.begin(),p2.end());
    BOOST_TEST(p==p2);
    p.clear();

    p.insert(p2.cbegin(),p2.cend());
    BOOST_TEST(p==p2);
    p.clear();

    for(auto s:p2.segment_traversal()){
      p.insert(s.begin(),s.end());
      BOOST_TEST(p.size()==p2.size(s.type_info()));
      p.clear();

      p.insert(s.cbegin(),s.cend());
      BOOST_TEST(p.size()==p2.size(s.type_info()));
      p.clear();
    }

    do_((
      p.insert(
        external_iterator(p2.template begin<Types>()),
        external_iterator(p2.template end<Types>())),
      BOOST_TEST(p.size()==p2.template size<Types>()),
      p.clear()
    ,0)...);

    do_((
      p.insert(p2.template begin<Types>(),p2.template end<Types>()),
      BOOST_TEST(p.size()==p2.template size<Types>()),
      p.clear()
    ,0)...);

    do_((
      p.insert(p2.template cbegin<Types>(),p2.template cend<Types>()),
      BOOST_TEST(p.size()==p2.template size<Types>()),
      p.clear()
    ,0)...);
  }
  {
    PolyCollection p,p1,p2;
    ValueFactory   v;

    p2.template register_types<Types...>();
    fill<
      constraints<is_copy_constructible,is_equality_comparable>,
      Types...
    >(p1,v,2);
    fill<
      constraints<is_copy_constructible,is_equality_comparable>,
      Types...
    >(p2,v,2);

    auto remove_original=[](PolyCollection& p)
    {
      bool first=true;
      for(auto s:p.segment_traversal()){
        if(first)p.erase(s.end()-2,s.end()),first=false;
        else     p.erase(s.begin(),s.begin()+2);
      }
    };

    p=p1;
    p.insert(
      p.begin(),external_iterator(p2.begin()),external_iterator(p2.end()));
    remove_original(p);
    BOOST_TEST(p==p2);

    p=p1;
    p.insert(p.begin(),p2.begin(),p2.end());
    remove_original(p);
    BOOST_TEST(p==p2);

    p=p1;
    p.insert(p.begin(),p2.cbegin(),p2.cend());
    remove_original(p);
    BOOST_TEST(p==p2);

    p=p1;
    for(auto s:p2.segment_traversal())p.insert(p.begin(),s.begin(),s.end());
    remove_original(p);
    BOOST_TEST(p==p2);

    p=p1;
    for(auto s:p2.segment_traversal())p.insert(p.begin(),s.cbegin(),s.cend());
    remove_original(p);
    BOOST_TEST(p==p2);

    p=p1;
    do_((p.insert(
      p.begin(),
      external_iterator(p2.template begin<Types>()),
      external_iterator(p2.template end<Types>())),0)...);
    remove_original(p);
    BOOST_TEST(p==p2);

    p=p1;
    do_((p.insert(
      p.begin(),p2.template begin<Types>(),p2.template end<Types>()),0)...);
    remove_original(p);
    BOOST_TEST(p==p2);

    p=p1;
    do_((p.insert(
      p.begin(),p2.template cbegin<Types>(),p2.template cend<Types>()),0)...);
    remove_original(p);
    BOOST_TEST(p==p2);
  }
  {
    using type=first_of<
      constraints<is_copy_constructible,is_equality_comparable>,
      Types...
    >;

    PolyCollection p,p1,p2;
    ValueFactory   v;

    fill<constraints<>,type>(p1,v,2);
    fill<constraints<>,type>(p2,v,2);

    auto remove_original=[](PolyCollection& p)
    {
      auto it=p.segment_traversal().begin()->end();
      p.erase(it-2,it);
    };

    p=p1;
    BOOST_TEST(is_first(
      p,typeid(type),
      p.insert(
        p.begin(typeid(type)),
        external_iterator(p2.begin()),external_iterator(p2.end()))));
    remove_original(p);
    BOOST_TEST(p==p2);

    p=p1;
    BOOST_TEST(is_first(
      p,typeid(type),
      p.insert(
        p.cbegin(typeid(type)),
        external_iterator(p2.begin()),external_iterator(p2.end()))));
    remove_original(p);
    BOOST_TEST(p==p2);

    p=p1;
    BOOST_TEST(is_first<type>(
      p,
      p.insert(
        p.template begin<type>(),
        external_iterator(p2.begin()),external_iterator(p2.end()))));
    remove_original(p);
    BOOST_TEST(p==p2);

    p=p1;
    BOOST_TEST(is_first<type>(
      p,
      p.insert(
        p.template cbegin<type>(),
        external_iterator(p2.begin()),external_iterator(p2.end()))));
    remove_original(p);
    BOOST_TEST(p==p2);
  }
  {
    using type=first_of<
      constraints<
        is_constructible_from_int,is_not_copy_constructible,
        is_equality_comparable
      >,
      Types...
    >;

    PolyCollection   p;
    std::vector<int> s(10);
    ValueFactory     v;

    fill<constraints<>,type>(p,v,2);
    std::iota(s.begin(),s.end(),0);
    BOOST_TEST(is_first<type>(
      p,
      p.insert(p.template begin<type>(),s.begin(),s.end())));
    BOOST_TEST(
      std::equal(s.begin(),s.end(),p.template begin<type>(),
      [](int x,const type& y){return type{x}==y;})
    );
  }
}

void test_insertion()
{
  test_insertion<
    any_types::collection,auto_increment,
    any_types::t1,any_types::t2,any_types::t3,
    any_types::t4,any_types::t5>();
  test_insertion<
    base_types::collection,auto_increment,
    base_types::t1,base_types::t2,base_types::t3,
    base_types::t4,base_types::t5>();
  test_insertion<
    function_types::collection,auto_increment,
    function_types::t1,function_types::t2,function_types::t3,
    function_types::t4,function_types::t5>();
}

ext: cpp


text:
#pragma once

#include "../../../Config/GpConfig.hpp"

#if defined(GP_USE_MULTITHREADING)
#if defined(GP_USE_MULTITHREADING_FIBERS)

#include "../../../Types/Numerics/GpNumericOps.hpp"

#include <iostream>

extern "C"
{
#   include <fcntl.h>
#   include <sys/mman.h>
#   include <sys/stat.h>
#   include <unistd.h>
}

#include <cmath>
#include <cstddef>
#include <new>

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

#include <boost/context/detail/config.hpp>
#include <boost/context/stack_context.hpp>
#include <boost/context/stack_traits.hpp>

#if defined(BOOST_USE_VALGRIND)
#include <valgrind/valgrind.h>
#endif

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_PREFIX
#endif

namespace GPlatform {

template<typename TraitsT>
class GpFixedSizeStack
{
public:
    using traits_type   = TraitsT;
    using stack_context = boost::context::stack_context;

public:
                        GpFixedSizeStack    (void) noexcept = delete;
                        GpFixedSizeStack    (const GpFixedSizeStack&) noexcept = delete;
                        GpFixedSizeStack    (GpFixedSizeStack&&) noexcept = delete;
                        GpFixedSizeStack    (const size_t aSize = traits_type::default_size()) noexcept;
                        ~GpFixedSizeStack   (void) noexcept;

    stack_context       allocate            (void);
    void                deallocate          (stack_context& aSctx) noexcept;

private:
    stack_context       NewCtx              (void);
    void                FreeCtx             (stack_context& aSctx) noexcept;
    void                MemAlloc            (void);
    void                MemFree             (void) noexcept;

private:
    const size_t        iSize           = 0;
    size_t              iAllocatedSize  = 0;
    void*               iMemPtr         = nullptr;
};

template<typename TraitsT>
GpFixedSizeStack<TraitsT>::GpFixedSizeStack (const size_t aSize) noexcept:
iSize(aSize)
{
}

template<typename TraitsT>
GpFixedSizeStack<TraitsT>::~GpFixedSizeStack (void) noexcept
{
    MemFree();
}

template<typename TraitsT>
typename GpFixedSizeStack<TraitsT>::stack_context
GpFixedSizeStack<TraitsT>::allocate (void)
{
    return NewCtx();
}

template<typename TraitsT>
void    GpFixedSizeStack<TraitsT>::deallocate (stack_context& aSctx) noexcept
{
    FreeCtx(aSctx);
}

template<typename TraitsT>
typename GpFixedSizeStack<TraitsT>::stack_context
GpFixedSizeStack<TraitsT>::NewCtx (void)
{
    MemAlloc();

    stack_context sctx;
    sctx.size   = iAllocatedSize;
    sctx.sp     = static_cast<std::byte*>(iMemPtr) + sctx.size;
#if defined(BOOST_USE_VALGRIND)
    sctx.valgrind_stack_id = VALGRIND_STACK_REGISTER(sctx.sp, iMemPtr);
#endif

    return sctx;
}

template<typename TraitsT>
void    GpFixedSizeStack<TraitsT>::FreeCtx (stack_context& aSctx) noexcept
{
    BOOST_ASSERT(aSctx.sp);

#if defined(BOOST_USE_VALGRIND)
    VALGRIND_STACK_DEREGISTER(aSctx.valgrind_stack_id);
#endif
}

template<typename TraitsT>
void    GpFixedSizeStack<TraitsT>::MemAlloc (void)
{
    if (iMemPtr != nullptr)
    {
        //MemFree();
        return;
    }

    const size_t pagesCount     = NumOps::SDivCeil<size_t>(iSize, traits_type::page_size());
    const size_t sizeToAllocate = NumOps::SMul<size_t>(NumOps::SAdd<size_t>(pagesCount, 1), traits_type::page_size());

    //iMemPtr = std::aligned_alloc(4096, sizeToAllocate);
    //iAllocatedSize = sizeToAllocate;

    //std::cout << iMemPtr << std::endl;

#if defined(BOOST_CONTEXT_USE_MAP_STACK)
    iMemPtr = ::mmap(0, sizeToAllocate, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_STACK, -1, 0);
#elif defined(MAP_ANON)
    iMemPtr = ::mmap(0, sizeToAllocate, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
#else
    iMemPtr = ::mmap(0, sizeToAllocate, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
#endif

    if (iMemPtr == MAP_FAILED)
    {
        iMemPtr = nullptr;
        throw std::bad_alloc();
    }

    iAllocatedSize = sizeToAllocate;

#if defined(BOOST_DISABLE_ASSERTS)
    ::mprotect(iMemPtr, traits_type::page_size(), PROT_NONE);
#else
    const int result(::mprotect(iMemPtr, traits_type::page_size(), PROT_NONE));
    BOOST_ASSERT(0 == result);
#endif
}

template<typename TraitsT>
void    GpFixedSizeStack<TraitsT>::MemFree (void) noexcept
{
    if (iMemPtr == nullptr)
    {
        return;
    }

    ::munmap(iMemPtr, iAllocatedSize);
    //std::free(iMemPtr);

    iAllocatedSize  = 0;
    iMemPtr         = nullptr;
}

}//namespace GPlatform

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

#endif//#if defined(GP_USE_MULTITHREADING_FIBERS)
#endif//#if defined(GP_USE_MULTITHREADING)

ext: hpp


text:
#include "../server_thread.hpp"
#include "../router.hpp"
#include "../request_filter.hpp"
#include "../work_queue.hpp"
#include "../settings.hpp"
#include "../project_info.hpp"

#include <catch.hpp>
#include <boost/thread/future.hpp>

namespace msrv {
namespace server_tests {

TEST_CASE("server")
{
    boost::promise<void> startedPromise;
    boost::unique_future<void> started = startedPromise.get_future();

    Router router;
    RequestFilterChain filters;
    filters.addFilter(std::make_unique<ExecuteHandlerFilter>());

    auto config = std::make_unique<ServerConfig>();
    config->allowRemote = false;
    config->port = MSRV_DEFAULT_TEST_PORT;
    config->router = &router;
    config->filters = &filters;

    ServerThread server([&] { startedPromise.set_value(); });
    server.restart(std::move(config));

    for (int i = 0; i < 10 && !started.is_ready(); i++)
        std::this_thread::sleep_for(std::chrono::milliseconds(100));

    REQUIRE(started.is_ready());
    started.get();
}

}}

max_stars_repo_name: courtarro/beefweb

max_issues_repo_name: courtarro/beefweb

max_forks_repo_name: courtarro/beefweb


text:
#pragma once

#include <boost/ptr_container/ptr_vector.hpp>
#include <stdexcept>

#include "Message.hpp"

#include "entities/Person.hpp"
#include "geospatial/network/SMSVehicleParking.hpp"

namespace sim_mob
{

// Set to false if the barycenter is not needed. If false, the compiler will avoid all the barycenter update
// overhead
const bool doWeComputeBarycenter = true;

enum MobilityServiceControllerMessage
{
    MSG_DRIVER_SUBSCRIBE = 7100000,
    MSG_DRIVER_UNSUBSCRIBE,
    MSG_UNSUBSCRIBE_SUCCESSFUL,
    MSG_DRIVER_AVAILABLE,
    MSG_DRIVER_SHIFT_END,
    MSG_DELAY_SHIFT_END,
    MSG_DRIVER_SCHEDULE_STATUS,
    MSG_TRIP_REQUEST,
    MSG_SCHEDULE_PROPOSITION,
    MSG_SCHEDULE_PROPOSITION_REPLY,
    MSG_SCHEDULE_UPDATE,
    MSG_SYNC_SCHEDULE
};

/**Enumeration to indicate the type of trip requested by the passenger*/
enum class RequestType
{
    /**Specifies that the trip must be exclusive to the passenger - single rider request*/
    TRIP_REQUEST_SINGLE,

    /**Specifies that the trip may be shared with another passenger - shared trip request*/
    TRIP_REQUEST_SHARED,

    /**Does not specify any preference - the controller will assign arbitrarily*/
    TRIP_REQUEST_DEFAULT
};

/**
 * Message to subscribe a driver
 */
class DriverSubscribeMessage : public messaging::Message
{
public:
    DriverSubscribeMessage(Person *p) : person(p)
    {
    }

    virtual ~DriverSubscribeMessage()
    {
    }

    Person *person;
};

/**
 * Message to unsubscribe a driver
 */
class DriverUnsubscribeMessage : public messaging::Message
{
public:
    DriverUnsubscribeMessage(Person *p) : person(p)
    {
    }

    virtual ~DriverUnsubscribeMessage()
    {
    }

    Person *person;
};

/**
 * Message to state that a driver is available
 */
class DriverAvailableMessage : public messaging::Message
{
public:
    DriverAvailableMessage(Person *p) : person(p)
    {
        priority = 8;
    }

    virtual ~DriverAvailableMessage()
    {
    }

    Person *person;
};

/**
 * Message indicating that a driver has completed its shift
 */
class DriverShiftCompleted : public messaging::Message
{
public:
    DriverShiftCompleted(Person *p) : person(p)
    {
    }

    virtual ~DriverShiftCompleted()
    {
    }

    Person *person;
};

class DelayShiftEndMessage : public messaging::Message
{
public:
    DelayShiftEndMessage(Person *p) : person(p)
    {
    }

    virtual ~DelayShiftEndMessage()
    {
    }

    Person *person;
};

/**
 * Message to indicate that the driver has completed one item in the schedule
 */
class DriverScheduleStatusMsg : public messaging::Message
{
public:
    DriverScheduleStatusMsg(Person *p) : person(p)
    {
        priority = 10;
    }

    virtual ~DriverScheduleStatusMsg()
    {
    }

    Person *person;
};

/**
 * Message to request a trip
 */
class TripRequestMessage : public messaging::Message
{
public:
    TripRequestMessage() : timeOfRequest(timeslice(0, 0)),person(nullptr), userId("no-id"), startNode(0),
                           destinationNode(0), extraTripTimeThreshold(0), requestType(RequestType::TRIP_REQUEST_DEFAULT)
    {};

    TripRequestMessage(const TripRequestMessage &r) :
            timeOfRequest(r.timeOfRequest),person(r.person), userId(r.userId), startNode(r.startNode),
            destinationNode(r.destinationNode), extraTripTimeThreshold(r.extraTripTimeThreshold),
            requestType(r.requestType)
    {
    };

    TripRequestMessage(const timeslice &ct,Person *person, const std::string &p, const Node *sn, const Node *dn,
                       const unsigned int &threshold, const RequestType reqType = RequestType::TRIP_REQUEST_DEFAULT) :
            timeOfRequest(ct),person(person), userId(p), startNode(sn), destinationNode(dn), extraTripTimeThreshold(threshold),
            requestType(reqType)
    {
    };

    ~TripRequestMessage()
    {
    }

    bool operator==(const TripRequestMessage &other) const;

    bool operator!=(const TripRequestMessage &other) const;

    bool operator<(const TripRequestMessage &other) const;

    bool operator>(const TripRequestMessage &other) const;

    timeslice timeOfRequest;
    std::string userId;
    const Node *startNode;
    const Node *destinationNode;
    RequestType requestType;
    Person *person;

    /**
     * The time the passenger can tolerate to spend more w.r.t. the fastest option in which
     * she travels alone without any other passenger to share the trip with
     */
    unsigned int extraTripTimeThreshold; // seconds
};

enum ScheduleItemType
{
    INVALID, PICKUP, DROPOFF, CRUISE, PARK
};

struct ScheduleItem
{
    ScheduleItem(const ScheduleItemType scheduleItemType_, const TripRequestMessage tripRequest_)
            : scheduleItemType(scheduleItemType_), tripRequest(tripRequest_), nodeToCruiseTo(NULL), parking(nullptr)
    {
#ifndef NDEBUG
        if (scheduleItemType != ScheduleItemType::PICKUP && scheduleItemType != ScheduleItemType::DROPOFF)
        {
            throw std::runtime_error("Only PICKUP or DROPOFF is admitted here");
        }
#endif

    };

    ScheduleItem(const ScheduleItemType scheduleItemType_, const Node *nodeToCruiseTo_)
            : scheduleItemType(scheduleItemType_), nodeToCruiseTo(nodeToCruiseTo_), tripRequest(), parking(nullptr)
    {
#ifndef NDEBUG
        if (scheduleItemType != ScheduleItemType::CRUISE)
        {
            throw std::runtime_error("Only CRUISE is admitted here");
        }
#endif
    };

    ScheduleItem(const ScheduleItemType scheduleItemType_, const SMSVehicleParking *parkingLocation)
            : scheduleItemType(scheduleItemType_), nodeToCruiseTo(NULL), tripRequest(), parking(parkingLocation)
    {
#ifndef NDEBUG
        if (scheduleItemType != ScheduleItemType::PARK)
        {
            throw std::runtime_error("Only PARK is admitted here");
        }
#endif
    };

    ScheduleItem()
    {
    };

    bool operator<(const ScheduleItem &other) const;

    bool operator==(const ScheduleItem &rhs) const;

    const Node *getNode() const;

    ScheduleItemType scheduleItemType;

    TripRequestMessage tripRequest;

    const Node *nodeToCruiseTo;

    const SMSVehicleParking *parking;
};

class Schedule
{
private:
    //TODO: It would be more elegant using std::variant, available from c++17
    //aa!!: Given that we are inserting many elements now, it may be better to use a list instead of a vector
    //          (see http://john-ahlgren.blogspot.com/2013/10/stl-container-performance.html)
    std::vector<ScheduleItem> items;

    /**
     * The barycenter of all the dropOff locations.
     * Only needed for the ProximityBased controller
     */
    Point dropOffBarycenter;

    short passengerCount;

public:
    Schedule() : passengerCount(0), dropOffBarycenter(Point())
    {};

    //{ EMULATE STANDARD CONTAINER FUNCTIONS
    typedef std::vector<ScheduleItem>::const_iterator const_iterator;
    typedef std::vector<ScheduleItem>::iterator iterator;

    const std::vector<ScheduleItem> &getItems() const;

    const size_t size() const;

    const bool empty() const;

    Schedule::iterator begin();

    Schedule::const_iterator begin() const;

    const_iterator end() const;

    iterator end();

    void insert(iterator position, const ScheduleItem scheduleItem);

    void insert(iterator position, iterator first, iterator last);

    const ScheduleItem &back() const;

    ScheduleItem &front();

    const ScheduleItem &front() const;

    void pop_back();

    void push_back(ScheduleItem item);

    iterator erase(iterator position);

    ScheduleItem &at(size_t n);

    const ScheduleItem &at(size_t n) const;

    const TripRequestMessage *findTrip(const ScheduleItem item);
    //} EMULATE STANDARD CONTAINER FUNCTIONS

    /**
     * Performs the appropriate internal data update when a pick up is added
     */
    void onAddingScheduleItem(const ScheduleItem &item);

    void onRemovingScheduleItem(const ScheduleItem &item);

    const Point &getDropOffBarycenter() const;

    short getPassengerCount() const;
};

class SchedulePropositionMessage : public messaging::Message
{
public:
    SchedulePropositionMessage(const timeslice currTick_, Schedule schedule_, messaging::MessageHandler *msgSender) :
            currTick(currTick_), schedule(schedule_)
    {
        sender = msgSender;
    };

    const Schedule &getSchedule() const;

    const timeslice currTick;

private:
    Schedule schedule;
};

/**
 * Message to inform the controller to update its locally stored schedule
 */
class SyncScheduleMsg : public messaging::Message
{
public:
    SyncScheduleMsg(Person *p, Schedule s) : person(p), schedule(s)
    {
    }

    Person *person;
    Schedule schedule;
};

/**
 * Message to respond to a trip proposition
 */
class SchedulePropositionReplyMessage : public messaging::Message
{
public:
    SchedulePropositionReplyMessage(timeslice ct, const std::string &p,
                                    Person *t, const Node *sn, const Node *dn,
                                    const unsigned int threshold, const bool s) : currTick(ct),
                                                                                personId(p), driver(t),
                                                                                startNode(sn),
                                                                                destinationNode(dn),
                                                                                extraTripTimeThreshold(threshold),
                                                                                success(s)
    {
    }

    virtual ~SchedulePropositionReplyMessage()
    {
    }

    const timeslice currTick;
    const bool success;
    const std::string personId;
    Person *driver;
    const Node *startNode;
    const Node *destinationNode;
    const unsigned int extraTripTimeThreshold;
};

class ScheduleException : public std::runtime_error
{
public:
    ScheduleException(const std::string &xmsg) : std::runtime_error(xmsg)
    {};

    virtual ~ScheduleException()
    {};
};

}

std::ostream &operator<<(std::ostream &strm, const sim_mob::TripRequestMessage &request);

std::ostream &operator<<(std::ostream &strm, const sim_mob::ScheduleItem &item);

std::ostream &operator<<(std::ostream &strm, const sim_mob::Schedule &schedule);


text:
#include <inttypes.h>
#include <iostream>

#include "sparta/sparta.hpp"
#include "sparta/simulation/TreeNode.hpp"
#include "sparta/statistics/Counter.hpp"
#include "sparta/statistics/ReadOnlyCounter.hpp"
#include "sparta/statistics/CycleCounter.hpp"
#include "sparta/statistics/StatisticSet.hpp"
#include "sparta/kernel/Scheduler.hpp"
#include "sparta/utils/SpartaTester.hpp"
#include "sparta/simulation/ResourceFactory.hpp"
#include "sparta/events/Event.hpp"
#include "sparta/events/StartupEvent.hpp"
#include "sparta/events/EventSet.hpp"

#include <boost/timer/timer.hpp>
/*!
 * \file main.cpp
 * \brief Test for Register
 *
 * Register is built on DataView and RegisterSet is built on ArchData.
 * The DataView test performs extensive testing so some test-cases related
 * to register sizes and layouts may be omitted from this test.
 */

TEST_INIT;

using sparta::Counter;
using sparta::CounterBase;
using sparta::ReadOnlyCounter;
using sparta::CycleCounter;
using sparta::StatisticSet;
using sparta::RootTreeNode;
using sparta::ResourceTreeNode;

//! Dummy device
class DummyDevice : public sparta::Resource
{
public:

    static constexpr const char* name = "DummyDevice";

    class ParameterSet : public sparta::ParameterSet
    {
    public:
        ParameterSet(sparta::TreeNode* tn) : sparta::ParameterSet(tn) {}
    };

    DummyDevice(sparta::TreeNode* node,
                const DummyDevice::ParameterSet*) :
        sparta::Resource(node),
        es(node)
    {
        sparta::StartupEvent(node, CREATE_SPARTA_HANDLER(DummyDevice, dummyCallback));
    }

    // Infinite loop
    void dummyCallback() {
        dummy_callback.schedule();
    }

    sparta::EventSet es;
    sparta::Event<> dummy_callback{&es, "dummy_callback",
            CREATE_SPARTA_HANDLER(DummyDevice, dummyCallback), 1};
};

int main()
{
    {
        sparta::Clock clk("clock");
        RootTreeNode root;
        root.setClock(&clk); // Set clock within configuration phase
        sparta::ResourceFactory<DummyDevice, DummyDevice::ParameterSet> rfact;
        sparta::ResourceTreeNode dummy(&root, "dummy", "dummy node", &rfact);
        StatisticSet cset(&dummy);

        // Print current counter set by the ostream insertion operator
        std::cout << cset << std::endl;

        // Print current counter set by iteration
        for(CounterBase* c : cset.getCounters()){
            std::cout << c << std::endl;
        }
        std::cout << std::endl;

        // Build the set
        Counter ctr_a(&cset, "A", "group", 0, "The A counter", Counter::COUNT_NORMAL);
        Counter ctr_b(&cset, "B", "group", 1, "The B counter", Counter::COUNT_INTEGRAL);
        Counter ctr_c(&cset, "C", "The C counter", Counter::COUNT_LATEST);
        Counter ctr_d(&cset, "D", "The D counter", Counter::COUNT_NORMAL);

        // Ensure construction of simple arrays
        Counter ctrarr[2] = {{&cset, "X", "test", 0, "The A counter", Counter::COUNT_NORMAL},
                             {&cset, "Y", "test", 1, "The B counter", Counter::COUNT_INTEGRAL}};
        (void) ctrarr;

        // Ensure counters can be move constructed from an initializer list
        //std::vector<Counter> initialized_ctr_vec = {
        //        std::move(Counter(&cset, "D_1", "groupd", 1001, "d counter", Counter::COUNT_NORMAL)),
        //        std::move(Counter(&cset, "D_2", "groupd", 1002, "d counter", Counter::COUNT_NORMAL)),
        //        std::move(Counter(&cset, "D_3", "groupd", 1003, "d counter", Counter::COUNT_NORMAL))
        //};

        // Ensure counters can be added to vectors (no reallocation going on)
        std::vector<Counter> small_ctr_vec;
        std::stringstream name;
        small_ctr_vec.emplace_back(&cset, "A_1", "groupa", 1001, "A counter", Counter::COUNT_NORMAL);

        // Ensure counters can be added to vectors (with reallocation and moving)
        std::vector<Counter> ctr_vec_reserved;
        ctr_vec_reserved.reserve(4);
        for(auto i : {1,2,3,4}){
            std::stringstream name;
            name << "B_" << i;
            ctr_vec_reserved.emplace_back(&cset, name.str(), "groupb", 1000+i, "B counter", Counter::COUNT_NORMAL);
        }

        //EXPECT_THROW((ctr_vec_reserved[0] = {&cset, "B_1", "groupb", 1001, "B counter", Counter::COUNT_NORMAL}));
        //ctr_vec_reserved[0] = std::move(Counter(&cset, "B_5", "groupb", 1005, "B counter", Counter::COUNT_NORMAL));

        // Ensure counters can be added to vectors (with reallocation and moving)
        std::vector<Counter> ctr_vec;
        for(auto i : {1,2,3,4,5,6,7,8,9}){
            std::stringstream name;
            name << "C_" << i;
            ctr_vec.emplace_back(&cset, name.str(), "groupc", 1000+i, "C counter", Counter::COUNT_NORMAL);
            ctr_vec.back() += i;
            std::cout << "The tree after " << name.str() << " at " << i << std::endl
                      << cset.renderSubtree(-1, true) << std::endl;
        }

        std::vector<Counter> moved_ctr_vec(std::move(ctr_vec));
        EXPECT_EQUAL(moved_ctr_vec.size(), 9);
        EXPECT_EQUAL(ctr_vec.size(), 0);

        // Attempt to access moved counters
        EXPECT_EQUAL(moved_ctr_vec.at(2).getName(), "C_3");
        EXPECT_EQUAL(moved_ctr_vec.at(2).get(), 3);
        ++moved_ctr_vec.at(2);
        EXPECT_EQUAL(moved_ctr_vec.at(2).get(), 4);
        EXPECT_EQUAL(cset.getChildAs<Counter>("C_3")->get(), 4);
        EXPECT_EQUAL(cset.getCounter("C_3")->get(), 4);
        EXPECT_EQUAL(moved_ctr_vec.at(8).get(), 9);

        uint64_t e_val = 0;
        ReadOnlyCounter ctr_e(&cset, "E", "The E counter (read only)", Counter::COUNT_NORMAL, &e_val);
        CycleCounter  cyc1(&cset, "F", "The F counter (cycle counter)", Counter::COUNT_NORMAL, &clk);
        CycleCounter  cyc2(&cset, "G", "The G counter (cycle counter)", Counter::COUNT_NORMAL, &clk);
        CycleCounter  cyc3(&cset, "H", "The H counter (cycle counter)", Counter::COUNT_NORMAL, &clk);
        CycleCounter  cyc4(&cset, "I", "The I counter (integral cycle counter)", Counter::COUNT_INTEGRAL, &clk);
        CycleCounter  cyc5(&cset, "J", "The J counter (cycle counter)", Counter::COUNT_NORMAL, &clk);

        EXPECT_THROW(cset.addChild(&ctr_a)); // Counter already added

        // Print a counter before tree finalization
        EXPECT_NOTHROW(std::cout << cset.getCounterAs<Counter>("A") << std::endl;);
        EXPECT_NOTHROW(std::cout << cset.getCounterAs<Counter>("B") << std::endl;);

        // Procedural addition of aliases to counter (NOT ALLOWED)
        EXPECT_TRUE(cset.getCounterAs<Counter>("A")->getParent());
        EXPECT_THROW(cset.getCounterAs<Counter>("A")->addAlias("alias_name_that_shouldnt_exist")); // Already has a parent node; Cannot add aliases

        // Jump through the phases for now. Other tests adequately test the tree-building phases.
        root.enterConfiguring();
        std::cout << "\nCONFIGURING" << std::endl;

        root.enterFinalized();
        EXPECT_TRUE(root.isFinalized());
        sparta::Scheduler::getScheduler()->finalize();
        std::cout << "\nFINALIZED" << std::endl;

        // Child Counter lookup:
        // by name
        Counter *a=0, *b=0, *c=0, *d=0;
        ReadOnlyCounter *e=0;
        CycleCounter *f=0, *g=0, *h=0, *i=0;
        EXPECT_NOTHROW(a = cset.getCounterAs<Counter>("A"));
        EXPECT_NOTEQUAL(a, nullptr);
        EXPECT_NOTHROW(b = cset.getCounterAs<Counter>("B"));
        EXPECT_NOTEQUAL(b, nullptr);
        EXPECT_NOTHROW(c = cset.getCounterAs<Counter>("C"));
        EXPECT_NOTEQUAL(c, nullptr);
        EXPECT_NOTHROW(d = cset.getCounterAs<Counter>("D"));
        EXPECT_NOTEQUAL(d, nullptr);
        EXPECT_THROW(cset.getCounterAs<ReadOnlyCounter>("D")); // D is not a RO counter
        EXPECT_NOTHROW(e = cset.getCounterAs<ReadOnlyCounter>("E"));
        EXPECT_NOTEQUAL(e, nullptr);
        EXPECT_NOTHROW(f = cset.getCounterAs<CycleCounter>("F"));
        EXPECT_NOTEQUAL(f, nullptr);
        EXPECT_NOTHROW(g = cset.getCounterAs<CycleCounter>("G"));
        EXPECT_NOTEQUAL(g, nullptr);
        EXPECT_NOTHROW(h = cset.getCounterAs<CycleCounter>("H"));
        EXPECT_NOTEQUAL(h, nullptr);
        EXPECT_NOTHROW(i = cset.getCounterAs<CycleCounter>("I"));
        EXPECT_NOTEQUAL(i, nullptr);
        EXPECT_THROW(cset.getCounterAs<Counter>("E")); // E is not a sparta::counter counter
        EXPECT_THROW(cset.getCounterAs<Counter>("there_is_no_counter_by_this_name_here_or_anywhere")); // No counter by this name

        // Advance simulation time for the CycleCounters
        cyc1.startCounting();
        cyc3.startCounting();
        cyc4.startCountingWithMultiplier(4);
        cyc5.startCounting();
        sparta::Scheduler::getScheduler()->run(1);
        cyc5.stopCounting();
        sparta::Scheduler::getScheduler()->run(9);
        cyc1.stopCounting();

        cyc2.startCounting();
        cyc4.stopCounting();
        sparta::Scheduler::getScheduler()->run(15);
        cyc2.stopCounting();

        // Counter printing by pointer
        std::cout << "Counters: "
                  << a << " "
                  << b << " "
                  << c << " "
                  << d << " "
                  << e << " "
                  << f << " "
                  << g << " "
                  << h << " "
                  << i << " "
                  << std::endl;

        // Counter printing by value/reference
        if(a){
            std::cout << *a << std::endl;
        }
        if(b){
            std::cout << *b << std::endl;
        }
        if(e){
            std::cout << *e << std::endl;
        }
        if(f){
            std::cout << *f << std::endl;
        }
        if(g){
            std::cout << *g << std::endl;
        }
        if(h){
            std::cout << *h << std::endl;
        }
        if(i){
            std::cout << *i << std::endl;
        }

        // Printing
        //
        //! \todo register printing by group
        // TODO
        // by group + index
        // TODO
        // by name expression
        // TODO

        // Counter Reads
        EXPECT_EQUAL((uint64_t)*a, 0);
        EXPECT_EQUAL((uint64_t)*b, 0);
        EXPECT_EQUAL((uint64_t)*c, 0);
        EXPECT_EQUAL((uint64_t)*d, 0);
        EXPECT_EQUAL((uint64_t)*e, 0);

        EXPECT_EQUAL(a->get(), 0);
        EXPECT_EQUAL(b->get(), 0);
        EXPECT_EQUAL(c->get(), 0);
        EXPECT_EQUAL(d->get(), 0);
        EXPECT_EQUAL(e->get(), 0);

        EXPECT_EQUAL(cyc1.get(), 10);
        EXPECT_EQUAL(cyc2.get(), 15);
        EXPECT_EQUAL(cyc3.get(), 25);
        EXPECT_EQUAL(f->get(), 10);
        EXPECT_EQUAL(g->get(), 15);
        EXPECT_EQUAL(h->get(), 25);
        EXPECT_EQUAL(i->get(), 40);
        EXPECT_EQUAL(*f, 10u);
        EXPECT_EQUAL(*g, 15u);
        EXPECT_EQUAL(*h, 25u);

        // Counter comparison
        // (No lt/le/gt/ge today)
        EXPECT_TRUE(*a == 0);
        EXPECT_TRUE(*b == 0);
        EXPECT_TRUE(*c == 0);
        EXPECT_TRUE(*d == 0);
        EXPECT_TRUE(*e == 0);

        // Counter cast
        Counter::counter_type tmp=0;
        tmp = *a;
        EXPECT_EQUAL(tmp, 0);
        tmp = *b;
        EXPECT_EQUAL(tmp, 0);
        tmp = *c;
        EXPECT_EQUAL(tmp, 0);
        tmp = *d;
        EXPECT_EQUAL(tmp, 0);
        tmp = *e;
        EXPECT_EQUAL(tmp, 0);

        // Counter Writes
        EXPECT_THROW(a->set(100)); // Cannot set on COUNT_NORMAL
        EXPECT_THROW(b->set(100)); // Cannot set on COUNT_INTEGRAL
        EXPECT_NOTHROW(c->set(100));

        EXPECT_THROW(*a = 100); // Cannot set on COUNT_NORMAL
        EXPECT_THROW(*b = 100); // Cannot set on COUNT_INTEGRAL
        EXPECT_NOTHROW(*c = 100);

        EXPECT_THROW(*a = 100); // Cannot set on COUNT_NORMAL
        EXPECT_THROW(*b = 100); // Cannot set on COUNT_INTEGRAL
        EXPECT_NOTHROW(*c = 100);

        // Counter increments
        EXPECT_NOTHROW(a->increment(100));
        EXPECT_NOTHROW(b->increment(100));
        EXPECT_NOTHROW(c->increment(100));

        EXPECT_NOTHROW(*a += 100);
        EXPECT_NOTHROW(*b += 100);
        EXPECT_NOTHROW(*c += 100);

        EXPECT_NOTHROW(++*a);
        EXPECT_NOTHROW(++*b);
        EXPECT_NOTHROW(++*c);
        ++*d;
        // NO postincrement: EXPECT_EQUAL((*d)++, 1u);
        EXPECT_EQUAL(++*d, 2_u64);
        EXPECT_EQUAL(*e, 0_u64);
        ++e_val;

        // Counter Reads (validate)
        EXPECT_EQUAL((uint64_t)*a, 201);
        EXPECT_EQUAL((uint64_t)*b, 201);
        EXPECT_EQUAL((uint64_t)*c, 301);
        EXPECT_EQUAL((uint64_t)*d, 2);
        EXPECT_EQUAL((uint64_t)*e, 1);

        // Test rollover
        EXPECT_EQUAL((uint64_t)*a, 201);
        *a += (~(Counter::counter_type)0) - *a;
        EXPECT_EQUAL((uint64_t)*a, ~(Counter::counter_type)0);
        EXPECT_NOTHROW(*a += 11); // 0xffff...ffff -> 0 + 10 -> 10  Old code assumed 0 to not be included
        EXPECT_EQUAL((uint64_t)*a, 10); // look for a sane result nonetheless
        *a += (~(Counter::counter_type)0) - *a - 30;
        EXPECT_EQUAL((uint64_t)*a, (~(Counter::counter_type)0) - 30);
        EXPECT_NOTHROW(*a += 50); // overflow!
        EXPECT_EQUAL((uint64_t)*a, 19); // look for a sane result nonetheless

        boost::timer::cpu_timer t;
        t.start();
        //performance test
        const uint64_t outer = 500;
        const uint64_t inner = 10000000;
        for(uint32_t i =0; i < outer; i++)
        {
            for(uint32_t t = 0; t < inner; ++t)
            {
                ++*b;
            }
        }
        t.stop();
        EXPECT_EQUAL((uint64_t)*b, 201 + (outer * inner));

        // Render Tree

        std::cout << "The tree from the top with builtins: " << std::endl << root.renderSubtree(-1, true) << std::endl;
        std::cout << "The tree from the top without builtins: " << std::endl << root.renderSubtree() << std::endl;
        std::cout << "The tree from statisticset: " << std::endl << cset.renderSubtree(-1, true);
        std::cout << "The tree from a: " << std::endl << a->renderSubtree(-1, true);
        std::cout << "The tree from b: " << std::endl << b->renderSubtree(-1, true);
        std::cout << "The performance (sec) is: " << t.elapsed().user/1000000000.0 << std::endl;

        root.enterTeardown();
    }

    // Show remaining nodes
    std::cout << sparta::TreeNode::formatAllNodes() << std::endl;

    // Done

    REPORT_ERROR;

    return ERROR_CODE;
}

max_stars_repo_name: criusx/map

max_issues_repo_name: criusx/map

max_forks_repo_name: criusx/map


text: #include <boost/spirit/home/qi/stream.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//  Copyright (c) 2005-2009 Hartmut Kaiser
//
//  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 <saga/saga-defs.hpp>

#ifdef SAGA_WINDOWS

#include <map>
#include <vector>
#include <ctime>

#include <boost/algorithm/string/predicate.hpp>

#include <saga/saga/util.hpp>
#include <saga/saga/exception.hpp>
#include <saga/saga/url.hpp>
#include <saga/saga/adaptors/task.hpp>
#include <saga/saga/packages/job/adaptors/job.hpp>
#include <saga/saga/packages/job/adaptors/job_self.hpp>
#include <saga/saga/adaptors/attribute.hpp>
#include <saga/saga/adaptors/utils/is_local_address.hpp>
#include <saga/saga/adaptors/utils/utils.hpp>

#include <saga/impl/config.hpp>

#include "default_job_service.hpp"

#ifndef  MAX_PATH
# define MAX_PATH _POSIX_PATH_MAX
#endif

///////////////////////////////////////////////////////////////////////////////
namespace {

    // wrapper for gethostname()
    inline std::string get_hostname()
    {
        char buffer[MAX_PATH] = { '\0' };
        gethostname(buffer, sizeof(buffer));
        return std::string(buffer);
    }

    // ensure to get a non-empty resource manager name
    inline std::string ensure_resourcemanager(saga::url rm_url)
    {
        if ( rm_url.get_host ().empty () )
             rm_url.set_host (get_hostname ());
        if ( rm_url.get_scheme ().empty () )
             rm_url.set_scheme("fork");
        return rm_url.get_url();
    }

} // namespace

/*
 * constructor
 */
job_service_cpi_impl::job_service_cpi_impl (proxy                * p,
                                            cpi_info       const & info,
                                            saga::ini::ini const & glob_ini,
                                            saga::ini::ini const & adap_ini,
                                            TR1::shared_ptr<saga::adaptor> adaptor)
    : base_cpi (p, info, adaptor, cpi::Noflags)
{
    // check if we can handle this request
    instance_data data(this);
    if (!data->rm_.get_url().empty())
    {
        saga::url rm(data->rm_);
        std::string host(rm.get_host());
        if (!saga::adaptors::utils::is_local_address(host))
        {
            SAGA_ADAPTOR_THROW("Can't use remote hosts for job submission.",
                saga::adaptors::AdaptorDeclined);
        }

        std::string scheme(rm.get_scheme());
        if (!scheme.empty() && scheme != "fork" && scheme != "any")
        {
            SAGA_ADAPTOR_THROW("Can't use schemes others from 'any' or 'fork' "
                "for job submission.", saga::adaptors::AdaptorDeclined);
        }
    }
}

/*
 * destructor
 */
job_service_cpi_impl::~job_service_cpi_impl (void)
{
}

/*
 * SAGA API functions
 */

///////////////////////////////////////////////////////////////////////////////
void
job_service_cpi_impl::sync_create_job(saga::job::job& ret, saga::job::description jd)
{
    // make sure the executable path is given
    saga::attribute attr (jd);
    if (!attr.attribute_exists(saga::job::attributes::description_executable) ||
        attr.get_attribute(saga::job::attributes::description_executable).empty())
    {
        SAGA_ADAPTOR_THROW("Missing 'Executable' attribute on job description.",
            saga::BadParameter);
    }

    // get resource manager string
    saga::url rm;
    {
        instance_data data(this);
        rm = data->rm_;             // use resource manager as provided
    }

    saga::job::job job = saga::adaptors::job(rm, jd, proxy_->get_session());

    // set the created attribute
    saga::adaptors::attribute jobattr (job);
    std::time_t current = 0;
    std::time(&current);
    jobattr.set_attribute(saga::job::attributes::created, ctime(&current));

    ret = job;
}

///////////////////////////////////////////////////////////////////////////////
void
job_service_cpi_impl::sync_run_job_noio(saga::job::job& ret, std::string commandline,
    std::string host)
{
    std::vector<std::string> cmdline = saga::adaptors::utils::split_commandline (commandline);
    std::string executable = cmdline[0];

    saga::job::description jd;

    std::vector <std::string> chosts;
    chosts.push_back (host);
    jd.set_vector_attribute(saga::job::attributes::description_candidate_hosts, chosts);

    jd.set_attribute(saga::job::attributes::description_executable, executable);
    if (cmdline.size() > 1)
    {
        cmdline.erase(cmdline.begin());
        jd.set_vector_attribute(saga::job::attributes::description_arguments,
                                cmdline);
    }

    // get resource manager string
    saga::url rm;
    {
        instance_data data(this);
        rm = data->rm_;             // use resource manager as provided
    }

    // create a new job instance
    saga::job::job job = saga::adaptors::job(rm, jd, proxy_->get_session());

    // set the created attribute
    saga::adaptors::attribute attr (job);
    std::time_t current = 0;
    std::time(&current);
    attr.set_attribute(saga::job::attributes::created, ctime(&current));

    job.run();    // start this job

    ret = job;
}

void
job_service_cpi_impl::sync_run_job(saga::job::job& ret,
                                   std::string commandline,
                                   std::string host,
                                   saga::job::ostream& in,
                                   saga::job::istream& out,
                                   saga::job::istream& err)
{
    std::vector<std::string> cmdline = saga::adaptors::utils::split_commandline (commandline);
    std::string executable = cmdline[0];

    saga::job::description jd;

    std::vector <std::string> chosts;
    chosts.push_back (host);
    jd.set_vector_attribute(saga::job::attributes::description_candidate_hosts, chosts);

    jd.set_attribute(saga::job::attributes::description_executable, executable);
    if (cmdline.size() > 1)
    {
        cmdline.erase(cmdline.begin());
        jd.set_vector_attribute(saga::job::attributes::description_arguments,
                                cmdline);
    }
    jd.set_attribute(saga::job::attributes::description_interactive,
        saga::attributes::common_true);

    // get resource manager string
    saga::url rm;
    {
        instance_data data(this);
        rm = data->rm_;             // use resource manager as provided
    }

    // create a new job instance
    saga::job::job job = saga::adaptors::job(rm, jd, proxy_->get_session());

    // set the created attribute
    saga::adaptors::attribute attr (job);
    std::time_t current = 0;
    std::time(&current);
    attr.set_attribute(saga::job::attributes::created, ctime(&current));

    job.run();    // start this job

    in = job.get_stdin();
    out = job.get_stdout();
    err = job.get_stderr();

    ret = job;
}

///////////////////////////////////////////////////////////////////////////////
//  return the list of jobs created by this job_service
void job_service_cpi_impl::sync_list(std::vector<std::string>& list_of_jobids)
{
    adaptor_data_type data(this);
    list_of_jobids = data->list_jobs();
}

void job_service_cpi_impl::sync_get_job(saga::job::job & ret, std::string jobid)
{
    // get resource manager string
    saga::url rm;
    {
        instance_data data(this);
        rm = data->rm_;             // use resource manager as provided
    }
    saga::job::job job = saga::adaptors::job(rm, jobid, proxy_->get_session());

    // set initial attribute if this is a new job
    if (saga::job::New == job.get_state()) {
        saga::adaptors::attribute attr (job);
        std::time_t current = 0;
        std::time(&current);
        attr.set_attribute(saga::job::attributes::created, ctime(&current));
    }

    ret = job;
}

///////////////////////////////////////////////////////////////////////////////
namespace
{
    // keep track of the time this adaptor was loaded
    struct started_time
    {
        started_time()
        :   started_(0)
        {
            std::time(&started_);
        }

        std::time_t started_;
    };
    static started_time started;
}

void job_service_cpi_impl::sync_get_self(saga::job::self& ret)
{
    // get resource manager string
    saga::url rm;
    {
        instance_data data(this);
        rm = data->rm_;     // use resource manager as provided
    }

    // get at our jobid
    SAGA_OSSTREAM strm;
    strm << "[" << ensure_resourcemanager(rm) << "]-["
         << get_hostname() << ":" << getpid() << "]";
    std::string jobid = SAGA_OSSTREAM_GETSTRING(strm);

    // create the job_self instance
    saga::job::self job = saga::adaptors::self(rm, jobid, proxy_->get_session());

    // set/modify some of the job attributes
    saga::adaptors::attribute jobattr (job);
    std::time_t current = started.started_;
    jobattr.set_attribute(saga::job::attributes::created, ctime(&current));

    std::vector<std::string> hosts;
    hosts.push_back(get_hostname());
    jobattr.set_vector_attribute(saga::job::attributes::execution_hosts, hosts);

    ret = job;
}

///////////////////////////////////////////////////////////////////////////////
#if !defined (SAGA_DEFAULT_JOB_ADAPTOR_NO_ASYNCS)
// This adaptor implements the async functions based on its own synchronous
// functions for testing purposes only. Since there is no principal need
// to do so, we allow these to be 'switched off'.

saga::task
job_service_cpi_impl::async_create_job(saga::job::description jd)
{
    return saga::adaptors::task("job_service_cpi_impl::async_create_job",
        shared_from_this(), &job_service_cpi_impl::sync_create_job, jd);
}

saga::task
job_service_cpi_impl::async_run_job(std::string commandline,
                                    std::string host,
                                    saga::job::ostream& in,
                                    saga::job::istream& out,
                                    saga::job::istream& err)
{
    return saga::adaptors::task("job_service_cpi_impl::async_run_job",
        shared_from_this(), &job_service_cpi_impl::sync_run_job,
        commandline, host, TR1::ref(in), TR1::ref(out), TR1::ref(err));
}

saga::task
job_service_cpi_impl::async_list()
{
    return saga::adaptors::task("job_service_cpi_impl::async_list",
        shared_from_this(), &job_service_cpi_impl::sync_list);
}

saga::task
job_service_cpi_impl::async_get_job(std::string jobid)
{
    return saga::adaptors::task("job_service_cpi_impl::async_get_job",
        shared_from_this(), &job_service_cpi_impl::sync_get_job, jobid);
}

saga::task
job_service_cpi_impl::async_get_self()
{
    return saga::adaptors::task("job_service_cpi_impl::async_get_self",
        shared_from_this(), &job_service_cpi_impl::sync_get_self);
}

#endif  // !defined (SAGA_DEFAULT_JOB_ADAPTOR_NO_ASYNCS)

#endif // SAGA_WINDOWS

max_stars_repo_name: saga-project/saga-cpp

max_issues_repo_name: saga-project/saga-cpp

max_forks_repo_name: saga-project/saga-cpp


text:
// -----------------------------------------------------------------------------
// Fern © Geoneric
//
// This file is part of Geoneric Fern which is available under the terms of
// the GNU General Public License (GPL), version 2. If you do not want to
// be bound by the terms of the GPL, you may purchase a proprietary license
// from Geoneric (http://www.geoneric.eu/contact).
// -----------------------------------------------------------------------------
#define BOOST_TEST_MODULE fern ast
#include <boost/test/unit_test.hpp>
#include "fern/interpreter/Interpreter.h"
#include "fern/language/ast/optimize_visitor.h"
#include "fern/language/ast/script_visitor.h"

class Support
{

public:

    Support()
        : _interpreter(),
          _script_visitor(),
          _optimize_visitor()
    {
    }

protected:

    fern::Interpreter _interpreter;

    fern::ScriptVisitor _script_visitor;

    fern::OptimizeVisitor _optimize_visitor;
};

BOOST_FIXTURE_TEST_SUITE(optimize_visitor, Support)

BOOST_AUTO_TEST_CASE(remove_temporary_identifier)
{
    std::shared_ptr<fern::ModuleVertex> tree;
    std::string script;

    // Make sure that temporary identifiers which are only used as input to
    // one expression, are removed.
    {
        // This script should be rewritten in the tree as d = 5.
        script =
            "a = 5\n"
            "d = a\n";
        tree = _interpreter.parse_string(script);
        _interpreter.annotate(tree);
        tree->Accept(_optimize_visitor);
        tree->Accept(_script_visitor);
        BOOST_CHECK_EQUAL(_script_visitor.script(), "d = 5\n");

        // This script should be rewritten in the tree as e = 5.
        script =
            "a = 5\n"
            "d = a\n"
            "e = d\n";
        tree = _interpreter.parse_string(script);
        _interpreter.annotate(tree);
std::cout << "--------------------------" << std::endl;
        tree->Accept(_optimize_visitor);
        tree->Accept(_script_visitor);
std::cout << _script_visitor.script().encode_in_utf8() << std::endl;
        BOOST_CHECK_EQUAL(_script_visitor.script(), "e = 5\n");

        return;

        // This script should be rewritten in the tree as d = f(5).
        script =
            "a = 5\n"
            "d = f(a)\n";
        tree = _interpreter.parse_string(script);
        _interpreter.annotate(tree);
        tree->Accept(_optimize_visitor);
        tree->Accept(_script_visitor);
        std::cout << _script_visitor.script().encode_in_utf8() << std::endl;
        BOOST_CHECK_EQUAL(_script_visitor.script(),
            "d = f(5)");
    }

    // Make sure that temporary identifiers which are only used as input to
    // more than one expression, are removed.
    {
        // This script should not be rewritten.
        script =
            "a = 5\n"
            "d = f(a)\n"
            "e = g(a)\n";
        tree = _interpreter.parse_string(script);
        _interpreter.annotate(tree);
        tree->Accept(_optimize_visitor);
        tree->Accept(_script_visitor);
        BOOST_CHECK_EQUAL(_script_visitor.script(), script);
    }
}

BOOST_AUTO_TEST_SUITE_END()

ext: cc

max_stars_repo_name: quanpands/wflow

max_issues_repo_name: quanpands/wflow

max_forks_repo_name: quanpands/wflow


text:
#include "entities/Element.hpp"
#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Relation.hpp"
#include "mapcss/StyleProvider.hpp"
#include "test_utils/ElementUtils.hpp"

#include <boost/test/unit_test.hpp>
#include "test_utils/DependencyProvider.hpp"

using namespace utymap::entities;
using namespace utymap::mapcss;
using namespace utymap::tests;

namespace {
struct Index_StyleProviderFixture {
  Index_StyleProviderFixture() :
      dependencyProvider(),
      stylesheet(new StyleSheet()) {
  }

  void setSingleSelector(int zoomStart, int zoomEnd,
                         const std::initializer_list<std::string> &names,
                         const std::initializer_list<utymap::mapcss::Condition> &conditions,
                         const std::initializer_list<utymap::mapcss::Declaration> &declarations = {}) {
    auto selector = Selector();
    selector.names.insert(selector.names.begin(), names.begin(), names.end());
    selector.zoom.start = static_cast<std::uint8_t>(zoomStart);
    selector.zoom.end = static_cast<std::uint8_t>(zoomEnd);
    for (const auto &condition : conditions) {
      selector.conditions.push_back(condition);
    }

    Rule rule;
    for (const auto &declaration : declarations) {
      rule.declarations.push_back(declaration);
    }

    rule.selectors.push_back(selector);
    stylesheet->rules.push_back(rule);
    styleProvider = std::make_shared<StyleProvider>(
        *stylesheet,
        *dependencyProvider.getStringTable());
  }

  DependencyProvider dependencyProvider;
  std::shared_ptr<StyleProvider> styleProvider;
  std::shared_ptr<StyleSheet> stylesheet;
};
}

BOOST_FIXTURE_TEST_SUITE(Index_StyleProvider, Index_StyleProviderFixture)

BOOST_AUTO_TEST_CASE(GivenSimpleEqualsCondition_WhenHasStyle_ThenReturnTrue) {
  int zoomLevel = 1;
  setSingleSelector(zoomLevel, zoomLevel, {"node"}, {{"amenity", "=", "biergarten"}});
  Node node = ElementUtils::createElement<Node>(*dependencyProvider.getStringTable(), 0,
                                                {
                                                    std::make_pair("amenity", "biergarten")
                                                });

  BOOST_CHECK(styleProvider->hasStyle(node, zoomLevel));
}

BOOST_AUTO_TEST_CASE(GivenSimpleLessCondition_WhenHasStyle_ThenReturnsExpectedLogicalResult) {
  int zoomLevel = 1;
  setSingleSelector(zoomLevel, zoomLevel, {"node"}, {{"level", "<", "0"}});

  BOOST_CHECK(styleProvider->hasStyle(
      ElementUtils::createElement<Node>(*dependencyProvider.getStringTable(), 0, {{"level", "-1"}}),
      zoomLevel));

  BOOST_CHECK(!styleProvider->hasStyle(
      ElementUtils::createElement<Node>(*dependencyProvider.getStringTable(), 0, {{"level", "1"}}),
      zoomLevel));
}

BOOST_AUTO_TEST_CASE(GivenSimpleGreaterCondition_WhenHasStyle_ThenReturnsExpectedLogicalResult) {
  int zoomLevel = 1;
  setSingleSelector(zoomLevel, zoomLevel, {"node"}, {{"level", ">", "0"}});

  BOOST_CHECK(styleProvider->hasStyle(
      ElementUtils::createElement<Node>(*dependencyProvider.getStringTable(), 0, {{"level", "1"}}),
      zoomLevel));

  BOOST_CHECK(!styleProvider->hasStyle(
      ElementUtils::createElement<Node>(*dependencyProvider.getStringTable(), 0, {{"level", "-1"}}),
      zoomLevel));
}

BOOST_AUTO_TEST_CASE(GivenTwoNamesAndSimpleEqualsCondition_WhenHasStyleForSecondName_ThenReturnTrue) {
  int zoomLevel = 1;
  setSingleSelector(zoomLevel, zoomLevel, {"way", "node"}, {{"amenity", "=", "biergarten"}});
  Node node = ElementUtils::createElement<Node>(*dependencyProvider.getStringTable(), 0,
                                                {
                                                    std::make_pair("amenity", "biergarten")
                                                });

  BOOST_CHECK(styleProvider->hasStyle(node, zoomLevel));
}

BOOST_AUTO_TEST_CASE(GivenSimpleEqualsConditionButDifferentZoomLevel_WhenHasStyle_ThenReturnFalse) {
  int zoomLevel = 1;
  setSingleSelector(zoomLevel, zoomLevel, {"node"}, {{"amenity", "=", "biergarten"}});
  Node node = ElementUtils::createElement<Node>(*dependencyProvider.getStringTable(), 0,
                                                {
                                                    std::make_pair("amenity", "biergarten")
                                                });

  BOOST_CHECK(!styleProvider->hasStyle(node, 2));
}

BOOST_AUTO_TEST_CASE(GivenTwoEqualsConditions_WhenHasStyle_ThenReturnTrue) {
  int zoomLevel = 1;
  setSingleSelector(zoomLevel, zoomLevel, {"node"},
                    {
                        {"amenity", "=", "biergarten"},
                        {"address", "=", "Invalidstr."}
                    });
  Node node = ElementUtils::createElement<Node>(*dependencyProvider.getStringTable(), 0,
                                                {
                                                    std::make_pair("amenity", "biergarten"),
                                                    std::make_pair("address", "Invalidstr.")
                                                });

  BOOST_CHECK(styleProvider->hasStyle(node, zoomLevel));
}

BOOST_AUTO_TEST_CASE(GivenTwoNotEqualsConditions_WhenHasStyle_ThenReturnFalse) {
  int zoomLevel = 1;
  setSingleSelector(zoomLevel, zoomLevel, {"node"},
                    {
                        {"amenity", "=", "biergarten"},
                        {"address", "!=", "Invalidstr."}
                    });
  Node node = ElementUtils::createElement<Node>(*dependencyProvider.getStringTable(), 0,
                                                {
                                                    std::make_pair("amenity", "biergarten"),
                                                    std::make_pair("address", "Invalidstr.")
                                                });

  BOOST_CHECK(!styleProvider->hasStyle(node, zoomLevel));
}

BOOST_AUTO_TEST_CASE(GivenCustomElementRuleOverridesDefault_WhenForElement_ThenStyleHasOnlyCustomRule) {
  int zoomLevel = 1;
  setSingleSelector(zoomLevel, zoomLevel, {"node"},
                    {{"amenity", "=", "biergarten"}},
                    {{"key1", "value1"}});
  setSingleSelector(zoomLevel, zoomLevel, {"element"},
                    {{"id", "=", "7"}},
                    {{"key2", "value2"}});
  Node node = ElementUtils::createElement<Node>(*dependencyProvider.getStringTable(), 7,
                                                {std::make_pair("amenity", "biergarten")});

  Style style = styleProvider->forElement(node, zoomLevel);

  BOOST_CHECK(style.has(dependencyProvider.getStringTable()->getId("key2"), "value2"));
  BOOST_CHECK(!style.has(dependencyProvider.getStringTable()->getId("key1")));
}

BOOST_AUTO_TEST_CASE(GivenTwoDifferentStyles_WhenConstructed_ThenTheyHaveDifferentTags) {
  int zoomLevel = 1;
  setSingleSelector(zoomLevel, zoomLevel, {"node"}, {{"a", "=", "b"}}, {{"k", "v"}});
  auto tag1 = styleProvider->getTag();
  stylesheet->rules.clear();

  setSingleSelector(zoomLevel, zoomLevel, {"node"}, {{"a", "!=", "b"}}, {{"k", "v"}});
  auto tag2 = styleProvider->getTag();

  BOOST_CHECK_NE(tag1, tag2);
}

BOOST_AUTO_TEST_CASE(GivenTwoEqualStyles_WhenConstructed_ThenTheyHaveTheSameTag) {
  int zoomLevel = 1;
  setSingleSelector(zoomLevel, zoomLevel, {"node"}, {{"a", "=", "b"}}, {{"k", "v"}});
  auto tag1 = styleProvider->getTag();
  stylesheet->rules.clear();

  setSingleSelector(zoomLevel, zoomLevel, {"node"}, {{"a", "=", "b"}}, {{"k", "v"}});
  auto tag2 = styleProvider->getTag();

  BOOST_CHECK_EQUAL(tag1, tag2);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: roscopecoltran/SniperKit-Core

max_issues_repo_name: roscopecoltran/SniperKit-Core

max_forks_repo_name: roscopecoltran/SniperKit-Core


text:
/*
 *  Copyright 2011-2014 Maxim Milakov
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include "varying_data_stream_writer.h"

#include "varying_data_stream_schema.h"
#include "neural_network_exception.h"

#include <boost/format.hpp>

namespace nnforge
{
	varying_data_stream_writer::varying_data_stream_writer(
		nnforge_shared_ptr<std::ostream> output_stream,
		unsigned int entry_count)
		: out_stream(output_stream), entry_written_count(0), entry_offsets(entry_count + 1, 0)
	{
		out_stream->exceptions(std::ostream::failbit | std::ostream::badbit);

		out_stream->write(reinterpret_cast<const char*>(varying_data_stream_schema::varying_data_stream_guid.data), sizeof(varying_data_stream_schema::varying_data_stream_guid.data));

		out_stream->write(reinterpret_cast<const char*>(&entry_count), sizeof(entry_count));

		entry_offsets_pos = out_stream->tellp();
		out_stream->write(reinterpret_cast<const char*>(&(*entry_offsets.begin())), sizeof(unsigned long long) * entry_offsets.size());

		start_pos = out_stream->tellp();
		entry_offsets[0] = out_stream->tellp() - start_pos;
	}

	varying_data_stream_writer::~varying_data_stream_writer()
	{
		std::ostream::pos_type current_pos = out_stream->tellp();

		// write entry offsets
		out_stream->seekp(entry_offsets_pos);
		out_stream->write(reinterpret_cast<const char*>(&(*entry_offsets.begin())), sizeof(unsigned long long) * entry_offsets.size());

		out_stream->seekp(current_pos);

		out_stream->flush();
	}

 	void varying_data_stream_writer::raw_write(
		const void * all_entry_data,
		size_t data_length)
	{
		if (entry_written_count >= entry_offsets.size() - 1)
			throw neural_network_exception((boost::format("Writing extra entries to supervised_varying_data_stream_writer not allowed, it was created with entry count %1%") % (entry_offsets.size() - 1)).str());

		out_stream->write(reinterpret_cast<const char*>(all_entry_data), data_length);

		++entry_written_count;

		entry_offsets[entry_written_count] = out_stream->tellp() - start_pos;
	}
}

max_stars_repo_name: anshumang/nnForgeINST

max_issues_repo_name: yanshanjing/nnForge

max_forks_repo_name: yanshanjing/nnForge


text:
#define BOOST_TEST_MODULE Storage Server Tests
#include <boost/test/unit_test.hpp>

max_stars_repo_name: sachaaaaa/loki-storage-server-old

max_issues_repo_name: sachaaaaa/loki-storage-server-old

max_forks_repo_name: sachaaaaa/loki-storage-server-old


text:
//
// Channel.hpp
//

#include "Channel.hpp"
#include <boost/filesystem.hpp>

using namespace boost::filesystem;

Channel::Channel()
{
	Load();
}

void Channel::Load()
{
	pt_.clear();

	path default_json_path("./channels/default.config.json");
	if (exists(default_json_path) && !is_directory(default_json_path)) {
		try {
			boost::property_tree::ptree config_pt;
			read_json(default_json_path.string(), config_pt);
			pt_.put_child("ch000", config_pt);

		} catch (const std::exception& e) {
			Logger::Error("%d", e.what());
		}
	}

	path p("./channels");
	if (exists(p) && is_directory(p)) {
		for (auto it_dir = directory_iterator(p); it_dir != directory_iterator(); ++it_dir) {
			if (is_directory(*it_dir)) {
				path json_path = it_dir->path() / "config.json";
				if (exists(json_path)) {
					auto channel_str = it_dir->path().leaf().string();
					try {
						boost::property_tree::ptree config_pt;
						read_json(json_path.string(), config_pt);
						pt_.put_child(channel_str, config_pt);

					} catch (const std::exception& e) {
						Logger::Error("%d", e.what());
					}
				}
			}
        }
    }
}

const boost::property_tree::ptree& Channel::pt() const
{
	return pt_;
}

std::string Channel::GetDefaultStage() const
{
	return pt_.get<std::string>("ch000.stage");
}

int Channel::GetDefaultCapacity() const
{
	return pt_.get<int>("ch000.capacity");
}


text:
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Hidekazu Ikeno
 *
 * 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.
 */

///
/// \file aak_reduction.hpp
///
/// Sparse approximation of exponential sum using modified Prony method.
///
#ifndef MXPFIT_MODIFIED_PRONY_REDUCTION_HPP
#define MXPFIT_MODIFIED_PRONY_REDUCTION_HPP

#include <Eigen/Core>
#include <Eigen/Eigenvalues>
#include <Eigen/QR>

#include <mxpfit/exponential_sum.hpp>

namespace mxpfit
{
///
/// ### ModifiedPronyReduction
///
/// \brief Find a truncated exponential sum function with smaller number of
///        terms by the modified balanced truncation method.
///
/// \tparam T  Scalar type of exponential sum function.
///
/// Let us consider an exponential sum function, in which the weights and
/// exponetns are strictly positive, i.e.,
///
/// \f[
///   f(t)=\sum_{j=1}^{n} w_{j}^{} e^{-a_{j}^{} t}, \quad
///   (a_{j} > 0, \, w_{j} > 0).
/// \f]
///
/// This class calculates truncated exponential \f$\hat{f}(t)\f$ sum such that
///
/// \f[
///   \hat{f}(t)=\sum_{j=1}^{k} \hat{w}_{j}^{}e^{-\hat{a}_{j}^{} t}, \quad
///   \left| f(t)-\hat{f}(t) \right| < \epsilon, \, (k < n)
/// \f]
///
/// where \f$\epsilon > 0\f$ is the prescribed accuracy. The weights
/// \f$\hat{w}_{j}\f$ and exponents \f$\hat{w}_{j}\f$ in the trucated sum are
/// all positive.
///
/// The modified Prony method proposed by Beylkin and Monzon are adopted. We
/// refer to the literature listed below for the detial about the method.
///
/// #### References
///
/// 1. G. Beylkin and L. Monz\'{o}n, "Approximation by exponential sums
///    revisited", Appl. Comput. Harmon. Anal. 28 (2010) 131-149.
///    [DOI: https://doi.org/10.1016/j.acha.2009.08.011]
/// 2. W. McLean, "Exponential sum approximations for \f$t^{-\beta}\f$",
///    arXiv:1606.00123 [math]
///
template <typename T>
class ModifiedPronyReduction
{
public:
    using Scalar        = T;
    using RealScalar    = typename Eigen::NumTraits<Scalar>::Real;
    using ComplexScalar = std::complex<RealScalar>;
    using Index         = Eigen::Index;

    using VectorType = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;
    using MatrixType = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;
    using ResultType = ExponentialSum<Scalar, Scalar>;

    ///
    /// Compute truncated exponential sum \f$ \hat{f}(t) \f$
    ///
    /// \tparam DerivedF type of exponential sum inheriting ExponentialSumBase
    ///
    /// \param[in] orig original exponential sum function, \f$ f(t) \f$
    /// \param[in] n_target Index smaller than `orig.size()`, which denotes
    ///            number of terms to be target for reduction.
    /// \param[in] threshold  prescribed accuracy \f$0 < \epsilon \ll 1\f$
    ///
    /// \pre The weights \f$w_{j}\f$ and exponents \f${a_{j}}\f$ are strictly
    /// positive and \f$a_{j}\f$ must be sorted in ascending order.
    ///
    /// \remark The exponents \f$\hat{a}_{j}\f$ of truncated sum are obtained as
    /// a root of Prony polynomials, which might not be real and positive.
    /// Internaly, obtaind roots of polynomial is casted to be a real number,
    /// which might introduce significant errors in the approximation.
    ///
    /// \return An instance of ExponentialSum represents \f$\hat{f}(t)\f$
    ///
    template <typename DerivedF>
    ResultType compute(const ExponentialSumBase<DerivedF>& orig, Index n_target,
                       RealScalar threshold);
};

template <typename T>
template <typename DerivedF>
typename ModifiedPronyReduction<T>::ResultType
ModifiedPronyReduction<T>::compute(const ExponentialSumBase<DerivedF>& orig,
                                   Index n_target, RealScalar eps)
{
    using Eigen::numext::abs;
    using Eigen::numext::real;
    assert(Index(0) <= n_target && n_target <= orig.size());
    assert(eps > RealScalar());

    if (n_target == Index())
    {
        ResultType ret(orig);
        return ret; // quick return
    }

    //
    // Compute a sequence
    //
    // \f[
    //   h_{j} = \sum_{k=1}^{n} w_{k} a_{k}^{j}
    // \f]
    //
    VectorType h(2 * n_target);
    const auto w_target = orig.weights().head(n_target);
    const auto a_target = orig.exponents().head(n_target);
    VectorType a_pow(a_target);

    h(0) = w_target.sum();
    h(1) = -(w_target * a_pow.array()).sum();

    Index m        = 1;
    auto factorial = RealScalar(1);
    for (; m < n_target; ++m)
    {
        a_pow.array() *= a_target;
        h(2 * m + 0) = (w_target * a_pow.array()).sum();
        a_pow.array() *= a_target;
        h(2 * m + 1) = -(w_target * a_pow.array()).sum();
        factorial *= RealScalar(2 * m * (2 * m + 1));

        if (abs(h(2 * m + 1)) / factorial < eps)
        {
            // Taylor expansion converges with the tolerance eps.
            ++m;
            break;
        }
    }

    if (m == n_target)
    {
        // no further reduction
        ResultType ret(orig);
        return ret;
    }

    //
    // Construct a Hankel matrix from the sequence h, and solve the linear
    // equation, H q = b, with b = -h(m:2m-1).
    //
    MatrixType H(m, m);
    for (Index i = 0; i < m; ++i)
    {
        H.col(i) = h.segment(i, m);
    }
    VectorType q(H.colPivHouseholderQr().solve(-h.segment(m, m)));

    //
    // Find the roots of the Prony polynomial,
    //
    // q(z) = \sum_{k=0}^{m-1} q_k z^{k}.
    //
    // The roots of q(z) can be obtained as the eigenvalues of the companion
    // matrix,
    //
    //     (0  0  ...  0 -p[0]  )
    //     (1  0  ...  0 -p[1]  )
    // C = (0  1  ...  0 -p[2]  )
    //     (.. .. ...  .. ..    )
    //     (0  0  ...  1 -p[m-1])
    //

    MatrixType companion(MatrixType::Zero(m, m));
    companion.diagonal(-1).setOnes();
    companion.col(m - 1) = -q;
    VectorType gamma(companion.eigenvalues().real());

    // --- Update exponents & weights
    const Index keep = orig.size() - n_target;
    ResultType ret(keep + m);
    ret.exponents().head(m)    = -gamma;
    ret.exponents().tail(keep) = orig.exponents().tail(keep);

    //
    // Construct Vandermonde matrix from Prony roots
    //
    MatrixType V(2 * m, m);
    for (Index i = 0; i < m; ++i)
    {
        const RealScalar z = gamma(i);
        V(0, i)            = RealScalar(1);
        for (Index j = 1; j < V.rows(); ++j)
        {
            V(j, i) = V(j - 1, i) * z; // z[i]**j
        }
    }

    //
    // Solve overdetermined Vandermonde system,
    //
    // V(0:2m-1,0:m-1) w(0:m-1) = h(0:2m-1)
    //
    // by the least square method.
    //
    ret.weights().head(m)    = V.colPivHouseholderQr().solve(h.head(2 * m));
    ret.weights().tail(keep) = orig.weights().tail(keep);

    return ret;
}

} // namespace mxpfit

#endif /* MXPFIT_MODIFIED_PRONY_REDUCTION_HPP */

max_stars_repo_name: hydeik/mxpfit

max_issues_repo_name: hydeik/mxpfit

max_forks_repo_name: hydeik/mxpfit


text:
#include "deposit_service_impl.hpp"

#include "repositories/account_repository.hpp"
#include "repositories/deposit_repository.hpp"

#include "model/savings_deposit.hpp"
#include "model/fixed_deposit.hpp"
#include "model/current_deposit.hpp"
#include "model/exceptions_messages.hpp"

#include <boost/format.hpp>
#include <boost/uuid/uuid_io.hpp>

namespace Service {
namespace Impl {

    struct Withdrawer : public Model::DepositVisitor {

        static void withdraw(Model::Deposit& deposit, double amount) {
            Withdrawer withdrawer;
            withdrawer.ammount_ = amount;
            deposit.accept(withdrawer);
        }

        void visit(Model::SavingsDeposit& savings) override {
            double currentBalance = savings.getBalance();
            double minBalance = savings.getMinBalance();

            if(currentBalance - ammount_ < minBalance) {
                throw std::domain_error(Model::Exceptions::minBalanceViolation);
            }

            savings.withdraw(ammount_);
        }

        void visit(Model::FixedDeposit& entity) override {
            throw std::domain_error(Model::Exceptions::wrongFixedDepositOperation);
        }

        void visit(Model::CurrentDeposit& current) override {
            double currentBalance = current.getBalance();
            double newBalance = currentBalance - ammount_;

            if(newBalance < 0){
                double overdraftLimit = current.getOverdraftLimit();
                double allowedSum = currentBalance > 0 ? overdraftLimit : overdraftLimit + currentBalance;

                if(std::abs(newBalance) > allowedSum){
                    throw std::domain_error(Model::Exceptions::ovedraftOverflow);
                }
            }

            current.withdraw(ammount_);
        }

        double ammount_ = 0.0;
    };

    struct YearProcessor : public Model::DepositVisitor {
        static void process(Model::Deposit& deposit) {
            YearProcessor processor;
            deposit.accept(processor);
        }

        void visit(Model::SavingsDeposit& savings) override {
            savings.refill(savings.getBalance() * (savings.getRateOfInterest() / 100.0));
        }

        void visit(Model::FixedDeposit& entity) override {
            static double maturityInterest = 0.2;
            double maturityCharge = entity.getMaturity() * maturityInterest;
            entity.refill(entity.getBalance() * ((entity.getRateOfInterest() + maturityCharge) / 100.0));
            entity.mature();
        }

        void visit(Model::CurrentDeposit& current) override {
            // Current deposit has 0 rate of interest. The holder pays operational charge
            static const double operationalChargeInterest = 0.2;
            double operationalCharge = current.getOverdraftLimit() * operationalChargeInterest;
            current.withdraw(operationalCharge);
        }
    };

    DepositServiceImpl::DepositServiceImpl(
            Repository::DepositRepository& depositRepo, Repository::AccountRepository& accountRepo)
    : BaseClass(depositRepo), accountRepo_(accountRepo)
    {}

    Model::EntityID
    DepositServiceImpl::createCurrentDeposit(const Model::EntityID& ownerId, double initialBalance,
                                                             double overDraftLimit) {
        using namespace Model;
        auto owner = accountRepo_.resolveEntity(ownerId);

        if(!owner){
            throw std::domain_error((boost::format(Exceptions::unknownAccount) % boost::uuids::to_string(ownerId)).str());
        }

        return create<Model::CurrentDeposit>(generator_(), overDraftLimit, initialBalance, *owner);
    }

    Model::EntityID
    DepositServiceImpl::createSavingsDeposit(const Model::EntityID& ownerId, double initialBalance, double minBalance,
                                             double rateOfInterest) {
        using namespace Model;

        auto owner = accountRepo_.resolveEntity(ownerId);

        if(!owner){
            throw std::domain_error((boost::format(Exceptions::unknownAccount) % boost::uuids::to_string(ownerId)).str());
        }

        return create<Model::SavingsDeposit>(generator_(), minBalance, initialBalance, rateOfInterest, *owner);
    }

    Model::EntityID
    DepositServiceImpl::createFixedDeposit(const Model::EntityID& ownerId, double initialBalance, double rateOfInterest) {
        using namespace Model;

        auto owner = accountRepo_.resolveEntity(ownerId);
        if(!owner){
            throw std::domain_error((boost::format(Exceptions::unknownAccount) % boost::uuids::to_string(ownerId)).str());
        }

        return create<Model::FixedDeposit>(generator_(), *owner, initialBalance, rateOfInterest);
    }

    boost::optional<const Model::SavingsDeposit&> DepositServiceImpl::getSavingsDeposit(const Model::EntityID& depositId) const {
        return constCast(repository_.findSavingsDeposit(depositId));
    }

    boost::optional<const Model::CurrentDeposit&> DepositServiceImpl::getCurrentDeposit(
            const Model::EntityID &depositId) const {
        return constCast(repository_.findCurrentDeposit(depositId));
    }

    boost::optional<const Model::FixedDeposit&> DepositServiceImpl::getFixedDeposit(
            const Model::EntityID &depositId) const {
        return constCast(repository_.findFixedDeposit(depositId));
    }

    void DepositServiceImpl::refill(const Model::EntityID& depositID, double amount) {
        using namespace Model;

        if(amount <= 0) {
            throw std::domain_error(Model::Exceptions::negativeValue);
        }

        auto deposit = repository_.resolveEntity(depositID);

        if(!deposit) {
            throw std::domain_error((boost::format(Exceptions::unknownDeposit) % boost::uuids::to_string(depositID)).str());
        }

        if(Model::DepositCast<FixedDeposit>().cast(*deposit)){
            throw std::domain_error(Exceptions::wrongFixedDepositOperation);
        }

        deposit->refill(amount);
    }

    double DepositServiceImpl::getRateOfInterest(const Model::EntityID& depositId) const {
        auto deposit = repository_.resolveEntity(depositId);

        if(!deposit) {
            throw std::domain_error((boost::format(Model::Exceptions::unknownDeposit) % boost::uuids::to_string(depositId)).str());
        }

        return deposit->getRateOfInterest();
    }

    double DepositServiceImpl::getBalance(const Model::EntityID& depositId) const {
        auto deposit = repository_.resolveEntity(depositId);

        if(!deposit) {
            throw std::domain_error((boost::format(Model::Exceptions::unknownDeposit) % boost::uuids::to_string(depositId)).str());
        }

        return deposit->getBalance();
    }

    void DepositServiceImpl::withdraw(const Model::EntityID& depositId, double amount) {
        if(amount <= 0) {
            throw std::domain_error(Model::Exceptions::negativeValue);
        }

        auto deposit = repository_.resolveEntity(depositId);

        if(!deposit) {
            throw std::domain_error((boost::format(Model::Exceptions::unknownDeposit) % boost::uuids::to_string(depositId)).str());
        }

        Withdrawer::withdraw(*deposit, amount);
    }

    void DepositServiceImpl::setOverdraftLimit(const Model::EntityID& depositId, double overdraftLimit) {
        using namespace Model;

        auto deposit = repository_.resolveEntity(depositId);

        if(!deposit) {
            throw std::domain_error((boost::format(Exceptions::unknownDeposit) % boost::uuids::to_string(depositId)).str());
        }

        auto currentDeposit = Model::DepositCast<CurrentDeposit>().cast(*deposit);

        if(!currentDeposit){
            throw std::domain_error((boost::format(Exceptions::depositExpected) % "Current").str());
        }

        currentDeposit->setOverdraftLimit(overdraftLimit);
    }

    double DepositServiceImpl::closeDeposit(const Model::EntityID& depositId) {
        auto deposit = repository_.resolveEntity(depositId);

        if(!deposit) {
            throw std::domain_error((boost::format(Model::Exceptions::unknownDeposit) % boost::uuids::to_string(depositId)).str());
        }

        double balance = deposit->getBalance();
        repository_.remove(depositId);

        return balance;
    }

    void DepositServiceImpl::onBankPeriodPassed(const Model::EntityID& depositId) {
        auto deposit = repository_.resolveEntity(depositId);

        if(!deposit) {
            throw std::domain_error((boost::format(Model::Exceptions::unknownDeposit) % boost::uuids::to_string(depositId)).str());
        }

        YearProcessor::process(*deposit);
    }

    int DepositServiceImpl::getDepositsAmount() const {
        return repository_.getSize();
    }
}
}


text:
///////////////////////////////////////////////////////////////////////////////
// initializer.hpp                                                           //
//                                                                           //
//  Copyright 2010 Erwann Rogard. 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 BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_CELLS_INITIALIZER_HPP_ER_2010
#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_CELLS_INITIALIZER_HPP_ER_2010
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/next.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/mpl/vector/vector10.hpp>
#include <boost/numeric/conversion/converter.hpp>
#include <boost/range/algorithm/for_each.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/fusion/include/pair.hpp>
#include <boost/fusion/include/map.hpp>
#include <boost/fusion/include/joint_view.hpp>
#include <boost/statistics/detail/non_parametric/contingency_table/factor/levels.hpp>
#include <boost/statistics/detail/non_parametric/contingency_table/cells/traits.hpp>

// Usage
//    initialize<Keys>(acc)
// All the cells of contingency table are created and initialized to zero.

namespace boost{
namespace statistics{
namespace detail{
namespace contingency_table{
namespace cells_aux{

    template<typename K,typename T>
    struct op{

        typedef boost::fusion::pair<K,T> pair_; // maybe const T& ?
        typedef boost::fusion::map< pair_ > result_type;

        op(){}

        result_type operator()(const T& t)const
        {
            return result_type( pair_( t ) );
        }

    };

    template<typename Keys,typename AccSet,typename V,
        typename F, typename L, bool exit = boost::is_same<F,L>::value
    >
    struct initializer{

        initializer(AccSet& acc,const V& view)
        :acc_( acc ),view_( view ){}

        typedef typename boost::mpl::next<F>::type next_it_;
        typedef typename boost::mpl::deref<F>::type key_;
        typedef boost::mpl::vector1<key_> vec_key_;

        typedef void result_type;

        template<typename M>
        void operator()(const M& map)
        {

            namespace ct = statistics::detail::contingency_table;
            typedef boost::fusion::joint_view<const V,const M> next_view_;
            typedef cells_aux::initializer<
                Keys, AccSet, next_view_, next_it_, L> next_;
            next_view_ next_view( this->view_, map );
            typedef typename ct::result_of::extract::levels<
                key_,AccSet>::type ref_levels_;
            typedef typename boost::remove_cv<
                typename boost::remove_reference<
                    ref_levels_
                >::type
            >::type levels_;
            typedef typename levels_aux::value_of<key_,AccSet>::type value_;
            typedef cells_aux::op<key_,value_> op_;
            boost::for_each(
                ct::extract::levels<key_>( this->acc_ )
                    | boost::adaptors::transformed( op_() ),
                next_( this->acc_, next_view )
            );

        }

        private:

        AccSet& acc_;
        const V& view_;

    };

    template<typename Keys, typename AccSet, typename V, typename F, typename L>
    struct initializer<Keys, AccSet, V, F, L, true>
    {

        initializer(AccSet& acc, const V& view)
        :acc_( acc ),view_( view ){}

        typedef void result_type;

        template<typename M>
        void operator()(const M& map)
        {
            namespace ct = statistics::detail::contingency_table;
            typedef boost::fusion::joint_view<const V,const M> next_view_;
            next_view_ next_view( this->view_, map );
            typedef typename ct::cells_traits::mapped_of<
               Keys, AccSet>::type count_;
            typedef boost::numeric::converter<count_,int> converter_;
            count_ zero = converter_::convert( 0 );
            ct::extract::cells<Keys>( this->acc_ )[ next_view ] = zero;

        }

        private:
        AccSet& acc_;
        const V& view_;

    };

}// cells_aux

    template<typename Keys,typename AccSet>
    void initialize(AccSet& acc)
    {
        namespace ct = statistics::detail::contingency_table;
        typedef boost::fusion::map<> empty_map_;
        typedef typename boost::mpl::begin<Keys>::type first_it_;
        typedef typename boost::mpl::deref<first_it_>::type key_;
        typedef typename boost::mpl::vector1<key_> vec_key_;
        typedef typename boost::mpl::next<first_it_>::type second_it_;
        typedef typename boost::mpl::end<Keys>::type last_;

        typedef cells_aux::initializer<
            Keys, AccSet, empty_map_, second_it_, last_> initializer_;
        empty_map_ empty_map;
        initializer_ initializer( acc, empty_map );
        typedef typename levels_aux::value_of<key_,AccSet>::type value_;
        typedef cells_aux::op<key_,value_> op_;
        op_ op;
        boost::for_each(
            ct::extract::levels<key_>( acc )
                | boost::adaptors::transformed( op_() ),
            initializer
        );

    }

}// contingency_table
}// detail
}// statistics
}// boost

#endif