text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Howard Hinnant 2009
// (C) Copyright Ion Gaztanaga 2014-2014.
//
// 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/move for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/move/utility_core.hpp>
#include <boost/move/unique_ptr.hpp>
#include <boost/static_assert.hpp>
#include <boost/core/lightweight_test.hpp>

//////////////////////////////////////////////
//
// The initial implementation of these tests
// was written by Howard Hinnant.
//
// These test were later refactored grouping
// and porting them to Boost.Move.
//
// Many thanks to Howard for releasing his C++03
// unique_ptr implementation with such detailed
// test cases.
//
//////////////////////////////////////////////

#include "unique_ptr_test_utils_beg.hpp"

namespace bml = ::boost::movelib;

////////////////////////////////
//   unique_ptr_zero
////////////////////////////////
namespace unique_ptr_zero {

// test initialization/assignment from zero

void test()
{
   //Single unique_ptr
   reset_counters();
   {
   bml::unique_ptr<A> s2(0);
   BOOST_TEST(A::count == 0);
   }
   BOOST_TEST(A::count == 0);
   {
   bml::unique_ptr<A> s2(new A);
   BOOST_TEST(A::count == 1);
   s2 = 0;
   BOOST_TEST(A::count == 0);
   BOOST_TEST(s2.get() == 0);
   }
   BOOST_TEST(A::count == 0);

   //Unbounded array unique_ptr
   {
   bml::unique_ptr<A[]> s2(0);
   BOOST_TEST(A::count == 0);
   }
   BOOST_TEST(A::count == 0);
   {
   bml::unique_ptr<A[]> s2(new A[2]);
   BOOST_TEST(A::count == 2);
   s2 = 0;
   BOOST_TEST(A::count == 0);
   BOOST_TEST(s2.get() == 0);
   }
   BOOST_TEST(A::count == 0);

   //Bounded array unique_ptr
   {
   bml::unique_ptr<A[2]> s2(0);
   BOOST_TEST(A::count == 0);
   }
   BOOST_TEST(A::count == 0);
   {
   bml::unique_ptr<A[2]> s2(new A[2]);
   BOOST_TEST(A::count == 2);
   s2 = 0;
   BOOST_TEST(A::count == 0);
   BOOST_TEST(s2.get() == 0);
   }
   BOOST_TEST(A::count == 0);
}

}  //namespace unique_ptr_zero {

////////////////////////////////
//       unique_ptr_nullptr
////////////////////////////////

namespace unique_ptr_nullptr{

void test()
{
   #if !defined(BOOST_NO_CXX11_NULLPTR)
   //Single unique_ptr
   reset_counters();
   {
      bml::unique_ptr<A> p(new A);
      BOOST_TEST(A::count == 1);
      A* i = p.get();
      (void)i;
      p.reset(nullptr);
      BOOST_TEST(A::count == 0);
      BOOST_TEST(p.get() == 0);
   }
   BOOST_TEST(A::count == 0);
   {
      bml::unique_ptr<A> p(new A);
      BOOST_TEST(A::count == 1);
      A* i = p.get();
      (void)i;
      p = nullptr;
      BOOST_TEST(A::count == 0);
      BOOST_TEST(p.get() == 0);
   }
   BOOST_TEST(A::count == 0);

   {
      bml::unique_ptr<A> pi(nullptr);
      BOOST_TEST(pi.get() == nullptr);
      BOOST_TEST(pi.get() == 0);
   }
   BOOST_TEST(A::count == 0);
   {
      bml::unique_ptr<A> pi(nullptr, bml::unique_ptr<A>::deleter_type());
      BOOST_TEST(pi.get() == nullptr);
      BOOST_TEST(pi.get() == 0);
   }
   BOOST_TEST(A::count == 0);

   //Unbounded array unique_ptr
   reset_counters();
   {
      bml::unique_ptr<A[]> p(new A[2]);
      BOOST_TEST(A::count == 2);
      A* i = p.get();
      (void)i;
      p.reset(nullptr);
      BOOST_TEST(A::count == 0);
      BOOST_TEST(p.get() == 0);
   }
   BOOST_TEST(A::count == 0);
   {
      bml::unique_ptr<A[]> p(new A[2]);
      BOOST_TEST(A::count == 2);
      A* i = p.get();
      (void)i;
      p = nullptr;
      BOOST_TEST(A::count == 0);
      BOOST_TEST(p.get() == 0);
   }
   BOOST_TEST(A::count == 0);
   {
      bml::unique_ptr<A[]> pi(nullptr);
      BOOST_TEST(pi.get() == nullptr);
      BOOST_TEST(pi.get() == 0);
   }
   BOOST_TEST(A::count == 0);
   {
      bml::unique_ptr<A[]> pi(nullptr, bml::unique_ptr<A[]>::deleter_type());
      BOOST_TEST(pi.get() == nullptr);
      BOOST_TEST(pi.get() == 0);
   }
   BOOST_TEST(A::count == 0);

   //Bounded array unique_ptr
   reset_counters();
   {
      bml::unique_ptr<A[2]> p(new A[2]);
      BOOST_TEST(A::count == 2);
      A* i = p.get();
      (void)i;
      p.reset(nullptr);
      BOOST_TEST(A::count == 0);
      BOOST_TEST(p.get() == 0);
   }
   BOOST_TEST(A::count == 0);
   {
      bml::unique_ptr<A[2]> p(new A[2]);
      BOOST_TEST(A::count == 2);
      A* i = p.get();
      (void)i;
      p = nullptr;
      BOOST_TEST(A::count == 0);
      BOOST_TEST(p.get() == 0);
   }
   BOOST_TEST(A::count == 0);
   {
      bml::unique_ptr<A[2]> pi(nullptr);
      BOOST_TEST(pi.get() == nullptr);
      BOOST_TEST(pi.get() == 0);
   }
   BOOST_TEST(A::count == 0);
   {
      bml::unique_ptr<A[2]> pi(nullptr, bml::unique_ptr<A[2]>::deleter_type());
      BOOST_TEST(pi.get() == nullptr);
      BOOST_TEST(pi.get() == 0);
   }
   BOOST_TEST(A::count == 0);
   #endif
}

}  //namespace unique_ptr_nullptr{

////////////////////////////////
//             main
////////////////////////////////
int main()
{
   //nullptr
   unique_ptr_zero::test();
   unique_ptr_nullptr::test();

   //Test results
   return boost::report_errors();

}

#include "unique_ptr_test_utils_end.hpp"


text:
//******************************************************************************
// RCF - Remote Call Framework
//
// Copyright (c) 2005 - 2013, Delta V Software. All rights reserved.
// http://www.deltavsoft.com
//
// RCF is distributed under dual licenses - closed source or GPL.
// Consult your particular license for conditions of use.
//
// If you have not purchased a commercial license, you are using RCF
// under GPL terms.
//
// Version: 2.0
// Contact: support <at> deltavsoft.com
//
//******************************************************************************

#ifndef INCLUDE_RCF_OBJECTPOOL_HPP
#define INCLUDE_RCF_OBJECTPOOL_HPP

#include <vector>

#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>

#include <RCF/Tools.hpp>
#include <RCF/ThreadLibrary.hpp>

namespace RCF {

    static const std::size_t CbSize = 128;

    class ObjectPool;

    class RCF_EXPORT CbAllocatorBase
    {
    public:

        CbAllocatorBase(ObjectPool & objectPool);
        CbAllocatorBase(const CbAllocatorBase & rhs);

        void * allocate();
        void deallocate(void * pcb) ;

    private:
        ObjectPool & mObjectPool;
    };

    template<typename T>
    class CbAllocator : public CbAllocatorBase
    {
    public:

        typedef T value_type;
        typedef value_type* pointer;
        typedef std::size_t size_type;
        typedef std::ptrdiff_t difference_type;

        template<typename U>
        struct rebind
        {
            typedef CbAllocator<U> other;
        };

        CbAllocator(ObjectPool & objectPool) : CbAllocatorBase(objectPool)
        {
        }

        template<typename U>
        CbAllocator( const CbAllocator<U> & rhs) : CbAllocatorBase(rhs)
        {
        }

        pointer allocate(
            size_type cnt,
            typename std::allocator<void>::const_pointer = 0)
        {
            BOOST_STATIC_ASSERT( sizeof(T) <= CbSize );
            RCF_ASSERT_EQ(cnt , 1);
            RCF_UNUSED_VARIABLE(cnt);
            return reinterpret_cast<pointer>(CbAllocatorBase::allocate());
        }

        void deallocate(pointer p, size_type)
        {
            CbAllocatorBase::deallocate(p);
        }
    };

    class TypeInfo
    {
    public:
        TypeInfo(const std::type_info & ti) : mpTypeInfo(&ti)
        {

        }

        bool operator<(const TypeInfo & rhs) const
        {
            return (*mpTypeInfo).before(*rhs.mpTypeInfo) ? true : false;
        }

    private:
        const std::type_info * mpTypeInfo;
    };

    class ReallocBuffer;
    typedef boost::shared_ptr<ReallocBuffer> ReallocBufferPtr;

    class RCF_EXPORT ObjectPool
    {
    public:

        ObjectPool();
        ~ObjectPool();

        template<typename T>
        void enableCaching(std::size_t maxCount, boost::function1<void, T *> clearFunc)
        {
            enableCaching( (T *) NULL, maxCount, clearFunc);
        }

        template<typename T>
        void disableCaching()
        {
            disableCaching( (T *) NULL);
        }

        template<typename T>
        void enableCaching(T *, std::size_t maxCount, boost::function1<void, T *> clearFunc)
        {
            RCF::WriteLock lock(mObjPoolMutex);
            RCF::TypeInfo ti( typeid(T) );
            mObjPool[ti].reset( new RCF::ObjectPool::ObjList() );
            mObjPool[ti]->mMaxSize = maxCount;
            mObjPool[ti]->mOps.reset( new RCF::ObjectPool::Ops<T>(clearFunc) );
        }

        template<typename T>
        void disableCaching(T *)
        {
            RCF::WriteLock lock(mObjPoolMutex);
            RCF::TypeInfo ti( typeid(T) );
            mObjPool[ti]->mMaxSize = 0;
            mObjPool[ti]->clear();
        }

        template<typename T>
        bool isCachingEnabled(T *)
        {
            ReadLock lock(mObjPoolMutex);
            if (!mObjPool.empty())
            {
                RCF::TypeInfo ti( typeid(T) );
                ObjPool::iterator iter = mObjPool.find(ti);
                if (iter != mObjPool.end())
                {
                    if (iter->second->mMaxSize > 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        MemOstreamPtr getMemOstreamPtr();
        ReallocBufferPtr getReallocBufferPtr();

        void enumerateWriteBuffers(std::vector<std::size_t> & bufferSizes);
        void enumerateReadBuffers(std::vector<std::size_t> & bufferSizes);

        void setBufferCountLimit(std::size_t bufferCountLimit);
        std::size_t getBufferCountLimit();

        void setBufferSizeLimit(std::size_t bufferSizeLimit);
        std::size_t getBufferSizeLimit();

        template<typename T>
        void getObj(boost::shared_ptr<T> & objPtr, bool alwaysCreate = true)
        {
            T * pt = NULL;
            void * pv = NULL;
            boost::shared_ptr<void> spv;
            bool pfnDeleter = false;

            {
                ReadLock poolLock(mObjPoolMutex);

                if (mObjPool.empty())
                {
                    if (alwaysCreate)
                    {
                        pt = new T;
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    TypeInfo ti( typeid(T) );
                    ObjPool::iterator iter = mObjPool.find(ti);
                    if (iter == mObjPool.end())
                    {
                        if (alwaysCreate)
                        {
                            pt = new T;
                        }
                        else
                        {
                            return;
                        }
                    }
                    else
                    {
                        ObjList & objList = *(iter->second);
                        Lock listLock(objList.mMutex);
                        if (objList.mMaxSize == 0)
                        {
                            if (alwaysCreate)
                            {
                                pt = new T;
                            }
                            else
                            {
                                return;
                            }
                        }
                        else if (objList.mVec.empty())
                        {
                            pt = new T;
                            pfnDeleter = true;
                        }
                        else
                        {
                            pv = objList.mVec.back();
                            pt = static_cast<T *>(pv);
                            objList.mVec.pop_back();
                            pfnDeleter = true;
                        }
                    }
                }
            }

            RCF_ASSERT(pt);
            if (pfnDeleter)
            {
                TypeInfo ti( typeid(T) );

#if BOOST_VERSION < 103400

                // 1.33.1 shared_ptr, and earlier, does not have allocator support. Consequently we
                // have a (small) allocation each time a buffer is requested, and a corresponding
                // deallocation when the buffer is returned to the pool.

                objPtr = boost::shared_ptr<T>(
                    pt,
                    boost::bind(&ObjectPool::putObj, this, ti, _1));

#else

                // 1.34.0 shared_ptr has allocator support. Consequently we have no allocations
                // at all when a buffer is requested.

                objPtr = boost::shared_ptr<T>(
                    pt,
                    boost::bind(&ObjectPool::putObj, this, ti, _1),
                    CbAllocator<void>(*this) );

#endif
            }
            else
            {
                objPtr = boost::shared_ptr<T>(pt);
            }
        }

        void putObj(const TypeInfo & ti, void * pv)
        {
            ReadLock readLock(mObjPoolMutex);
            RCF_ASSERT(!mObjPool.empty());
            ObjPool::iterator iter = mObjPool.find(ti);
            RCF_ASSERT(iter != mObjPool.end());
            ObjList & objList = *(iter->second);
            Lock lock(objList.mMutex);
            if (objList.mVec.size() >= objList.mMaxSize)
            {
                lock.unlock();
                readLock.unlock();
                objList.mOps->kill(pv);
            }
            else
            {
                objList.mOps->clear(pv);
                objList.mVec.push_back(pv);
            }
        }

        class I_Ops
        {
        public:
            virtual ~I_Ops() {}
            virtual void kill(void * pv) = 0;
            virtual void clear(void * pv) = 0;
        };

        template<typename T>
        class Ops : public I_Ops
        {
        public:
            Ops(boost::function1<void, T *> clearFunc) :
                mClearFunc(clearFunc)
            {
            }

            void kill(void * pv)
            {
                T * pt = static_cast<T *>(pv);
                delete pt;
            }

            void clear(void * pv)
            {
                if (mClearFunc)
                {
                    T * pt = static_cast<T *>(pv);
                    mClearFunc(pt);
                }
            }

            boost::function1<void, T *> mClearFunc;
        };

        class ObjList : boost::noncopyable
        {
        public:
            ObjList() : mMaxSize(0)
            {
            }
            Mutex mMutex;
            std::size_t mMaxSize;
            std::vector<void *> mVec;
            boost::scoped_ptr<I_Ops> mOps;

            void clear()
            {
                for (std::size_t i=0; i<mVec.size(); ++i)
                {
                    mOps->kill(mVec[i]);
                }
                mVec.clear();
            }
        };

        typedef boost::shared_ptr<ObjList> ObjListPtr;

        typedef std::map< TypeInfo, ObjListPtr > ObjPool;
        ReadWriteMutex mObjPoolMutex;
        ObjPool mObjPool;

    private:

        friend class CbAllocatorBase;

        void * getPcb();
        void putPcb(void * pcb);

        void putMemOstream(MemOstream * pOs);
        void putReallocBuffer(ReallocBuffer * pRb);

        std::size_t                             mBufferCountLimit;
        std::size_t                             mBufferSizeLimit;

        Mutex                                   mOsPoolMutex;
        std::vector< MemOstream * >             mOsPool;

        Mutex                                   mRbPoolMutex;
        std::vector< ReallocBuffer * >          mRbPool;

        Mutex                                   mCbPoolMutex;
        std::vector< void * >                   mCbPool;

        template<typename T, typename Spt, typename PtrList, typename Pfn>
        void getPtr(
            T *,
            Spt &           spt,
            PtrList &       ptrList,
            Mutex &         ptrListMutex,
            Pfn             pfn)
        {
            T * pt = NULL;

            {
                Lock lock(ptrListMutex);

                if (ptrList.empty())
                {
                    pt = new T();
                }
                else
                {
                    pt = ptrList.back();
                    ptrList.pop_back();
                }
            }

#if BOOST_VERSION < 103400

            // 1.33.1 shared_ptr, and earlier, does not have allocator support. Consequently we
            // have a (small) allocation each time a buffer is requested, and a corresponding
            // deallocation when the buffer is returned to the pool.

            spt = boost::shared_ptr<T>(
                pt,
                boost::bind(pfn, this, _1));

#else

            // 1.34.0 shared_ptr has allocator support. Consequently we have no allocations
            // at all when a buffer is requested.

            spt = boost::shared_ptr<T>(
                pt,
                boost::bind(pfn, this, _1),
                CbAllocator<void>(*this) );

#endif

        }

    };

    RCF_EXPORT ObjectPool & getObjectPool();

} // namespace RCF

#endif // ! INCLUDE_RCF_OBJECTPOOL_HPP

ext: hpp

max_stars_repo_name: ASMlover/study

max_issues_repo_name: ASMlover/study

max_forks_repo_name: ASMlover/study


text:
/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2020 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <vector>
#include <limits>
#include <boost/algorithm/minmax_element.hpp>
#include <Core/Math/Histogram.h>
#include <Core/Math/MiscMath.h>

using namespace SCIRun::Core::Math;

namespace
{
  double Nan()
  {
    return std::numeric_limits<double>::quiet_NaN();
  }
}

Histogram::Histogram()
{
  this->min_ = Nan();
  this->max_ = Nan();
  this->bin_start_ = Nan();
  this->bin_size_ = Nan();
  this->histogram_.resize( 0 );
}

Histogram::Histogram( const double* data, size_t size )
{
  this->compute( data, size );
}

// For char and short data we do a single pass over the data to speed up the computation. The
// first pass is used to generate the histogram. In the next step we use this data to compute
// min and max
bool Histogram::compute( const double* data, size_t size )
{
  this->min_ = Nan();
  this->max_ = Nan();
  this->bin_start_ = Nan();
  this->bin_size_ = Nan();
  this->histogram_.resize( 0 );
  if ( size == 0 )
    return false;

  try
  {
    this->min_ = std::numeric_limits<double>::max();
    this->max_ = std::numeric_limits<double>::min();

    for ( size_t j = 0 ; j < size ; j++ )
    {
      double val = data[ j ];
      if ( ! IsFinite( val ) ) continue;
      if ( val < this->min_ ) this->min_ = val;
      if ( val > this->max_ ) this->max_ = val;
    }

    if ( this->min_ > this->max_ )
    {
      // Most likely all the data is NaN
      this->min_ = Nan();
      this->max_ = Nan();
      this->bin_start_ = Nan();
      this->bin_size_ = Nan();
      this->histogram_.resize( 0 );
      return false;
    }

    if ( this->min_ == this->max_ )
    {
      this->bin_size_  = 1.0;
      this->bin_start_ = this->min_ - ( this->bin_size_ * 0.5 );
      this->histogram_.resize( 1, 0 );
    }
    else
    {
      size_t hist_size = 0x100;
      this->histogram_.resize( hist_size, 0 );
      this->bin_size_ = ( this->max_ - this->min_ ) / static_cast<double>( hist_size - 1 );
      this->bin_start_ = this->min_ - ( this->bin_size_ * 0.5 );
    }

    double inv_bin_size = 1.0 / bin_size_;

    for ( size_t j = 1 ; j < size ; j++ )
    {
      double val = data[ j ];
      if ( IsFinite( val ) )
      {
        size_t idx = static_cast<size_t>( ( val - this->min_ ) * inv_bin_size );
        this->histogram_[ idx ]++;
      }
    }

    auto min_max = boost::minmax_element( this->histogram_.begin(), this->histogram_.end() );
    this->min_bin_ = (*min_max.first);
    this->max_bin_ = (*min_max.second);
  }
  catch( ... )
  {
    this->min_ = Nan();
    this->max_ = Nan();
    this->bin_start_ = Nan();
    this->bin_size_ = Nan();
    this->histogram_.resize( 0 );
    return false;
  }

  return true;
}

double Histogram::get_min() const
{
  return this->min_;
}

double Histogram::get_max() const
{
  return this->max_;
}

double Histogram::get_cum_value( double fraction ) const
{
  size_t tot_hist = 0;
  for ( size_t j = 0; j < this->histogram_.size(); j++ )
  {
    tot_hist += this->histogram_[ j ];
  }

  double multiplier = 1.0 / static_cast<double>( tot_hist );
  double jj = 0.0;
  size_t cur_hist = 0;

  for ( size_t j = 0; j < this->histogram_.size(); j++ )
  {
    double frac_start = static_cast<double>( cur_hist ) * multiplier;
    cur_hist += this->histogram_[ j ];
    double frac_end = static_cast<double>( cur_hist ) * multiplier;
    if ( fraction > frac_start && fraction <= frac_end )
    {
      jj = static_cast<double>( j ) + ( frac_end - fraction )/( frac_end - frac_start );
      break;
    }
  }

  return this->bin_start_ + ( jj * this->bin_size_ );
}

size_t Histogram::get_max_bin() const
{
  return this->max_bin_;
}

size_t Histogram::get_min_bin() const
{
  return this->min_bin_;
}

double Histogram::get_bin_size() const
{
  return this->bin_size_;
}

double Histogram::get_bin_start( size_t idx ) const
{
  return this->bin_start_ + idx * this->bin_size_;
}

double Histogram::get_bin_end( size_t idx ) const
{
  return this->bin_start_ + ( idx + 1 ) * this->bin_size_;
}

const std::vector<size_t>& Histogram::get_bins() const
{
  return this->histogram_;
}

size_t Histogram::get_size() const
{
  return this->histogram_.size();
}

bool Histogram::is_valid() const
{
  return !( IsNan( this->min_ ) || IsNan( this->max_ ) );
}

ext: cc

max_stars_repo_name: Haydelj/SCIRun

max_issues_repo_name: Haydelj/SCIRun

max_forks_repo_name: Haydelj/SCIRun


text:
#pragma once

#include "prx/simulation/plant.hpp"

#include <Eigen/Dense>
#include <Eigen/Core>

namespace prx
{
	class ackermann_FO : public plant_t
	{
	public:
		ackermann_FO(const std::string& path);
		virtual ~ackermann_FO();

		virtual void propagate(const double simulation_step) override final;

		virtual void update_configuration() override;

	protected:

		virtual void compute_derivative() override final;

		double x;
		double y;
		double theta;

		double x_dot;
		double y_dot;
		double theta_dot;

		double gamma;
		double V;

		// Distance between front and back wheels
		double L = 1.5;

		const double max_delta_deg = 60;
		const double max_delta_rad = max_delta_deg * PRX_PI / 180.0;

		std::vector<double> min_ctrl_bound = {-max_delta_rad, -30};
		std::vector<double> max_ctrl_bound = {max_delta_rad, 30};

		std::vector<double> min_state_bound = {-10, -10, -PRX_PI};
		std::vector<double> max_state_bound = { 10,  10, PRX_PI};
	};
}

PRX_REGISTER_SYSTEM(ackermann_FO, Ackermann_FO)
PRX_REGISTER_VELOCITY_FN(Ackermann_FO, [](system_ptr_t s){return s -> input_control_space -> get_bounds()[1].second;})


text:
//
// Copyright 2020 Mateusz Loskot <mateusz at loskot dot net>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#include <boost/gil/image.hpp>
#include <boost/gil/image_view.hpp>
#include <boost/gil/typedefs.hpp>

namespace boost {
namespace gil {
namespace test {
namespace fixture {

gil::gray8_pixel_t gray8_back_pixel{128};
gil::gray8_pixel_t gray8_draw_pixel{64};
gil::rgb8_pixel_t rgb8_back_pixel{255, 128, 64};
gil::rgb8_pixel_t rgb8_draw_pixel{64, 32, 16};

auto make_image_gray8() -> gil::gray8_image_t {
  gil::gray8_image_t image(2, 2, gray8_back_pixel);
  auto view = gil::view(image);
  view(0, 0) = gray8_draw_pixel;
  view(1, 1) = gray8_draw_pixel;
  return image;
}

auto make_image_rgb8() -> gil::rgb8_image_t {
  gil::rgb8_image_t image(2, 2, rgb8_back_pixel);
  auto view = gil::view(image);
  view(0, 0) = rgb8_draw_pixel;
  view(1, 1) = rgb8_draw_pixel;
  return image;
}

} // namespace fixture
} // namespace test
} // namespace gil
} // namespace boost

max_stars_repo_name: sdebionne/gil-reformated

max_issues_repo_name: sdebionne/gil-reformated

max_forks_repo_name: sdebionne/gil-reformated


text:
#include "particle_layer_repo.h"
#include "platform/jsonreader.h"
#include <boost/assign/list_of.hpp>

namespace render {
ParticleLayerRepo::ParticleLayerRepo()
    : Repository<ParticleLayer>( mDefaultParticleLayer )
    , mDefaultParticleLayer( Json::Value() )
{
    LoadParticleLayers();
}

void ParticleLayerRepo::LoadParticleLayers()
{
    Filesys& FSys = Filesys::Get();
    PathVect_t Paths;
    FSys.GetFileNames( Paths, "misc/particlelayers" );
    for( PathVect_t::const_iterator i = Paths.begin(), e = Paths.end(); i != e; ++i )
    {
        boost::filesystem::path const& Path = *i;
        if( Path.extension().string() != ".json" )
        {
            continue;
        }
        AutoFile JsonFile = FSys.Open( *i );
        if( !JsonFile.get() )
        {
            continue;
        }
        JsonReader Reader( *JsonFile );
        if( !Reader.IsValid() )
        {
            continue;
        }
        Json::Value Root = Reader.GetRoot();
        if( !Root.isArray() )
        {
            continue;
        }
        for( Json::Value::iterator i = Root.begin(), e = Root.end(); i != e; ++i )
        {
            Json::Value& part = *i;
            int32_t Idx = part["id"].asInt();
            mElements.insert( Idx, new ParticleLayer( part ) );
        }
    }
}

ParticleLayer::ParticleLayer( Json::Value const& json )
{
    sfactor = GL_SRC_ALPHA;
    dfactor = GL_ONE;
    typedef std::map<std::string, GLenum> glmap_t;
#define ELEM( x ) \
    ( std::string( #x ), x )

    static glmap_t const glmap = boost::assign::map_list_of
                                 ELEM( GL_ONE )
                                 ELEM( GL_ZERO )
                                 ELEM( GL_SRC_COLOR )
                                 ELEM( GL_ONE_MINUS_SRC_COLOR )
                                 ELEM( GL_DST_COLOR )
                                 ELEM( GL_ONE_MINUS_DST_COLOR )
                                 ELEM( GL_SRC_ALPHA )
                                 ELEM( GL_ONE_MINUS_SRC_ALPHA )
                                 ELEM( GL_DST_ALPHA )
                                 ELEM( GL_ONE_MINUS_DST_ALPHA )
                                 ELEM( GL_CONSTANT_COLOR )
                                 ELEM( GL_ONE_MINUS_CONSTANT_COLOR )
                                 ELEM( GL_CONSTANT_ALPHA )
                                 ELEM( GL_ONE_MINUS_CONSTANT_ALPHA );
#undef ELEM
    std::string str;
#define MAP( type, name ) \
    if( Json::GetStr( json[ #name ], str ) ) \
    { \
        type##map_t::const_iterator i = type##map.find( str ); \
        if( i != type##map.end() ) \
        { \
            name = i->second; \
        } \
    }
    MAP( gl, sfactor );
    MAP( gl, dfactor );
#undef MAP
}
}

ext: cpp


text:
/********************************************************************
 * guid.hpp - GncGUID struct definition.                            *
 * Copyright 2016 Aaron Laws                                        *
 * This program is free software; you can redistribute it and/or    *
 * modify it under the terms of the GNU General Public License as   *
 * published by the Free Software Foundation; either version 2 of   *
 * the License, or (at your option) any later version.              *
 *                                                                  *
 * This program is distributed in the hope that it will be useful,  *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of   *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    *
 * GNU General Public License for more details.                     *
 *                                                                  *
 * You should have received a copy of the GNU General Public License*
 * along with this program; if not, contact:                        *
 *                                                                  *
 * Free Software Foundation           Voice:  +1-617-542-5942       *
 * 51 Franklin Street, Fifth Floor    Fax:    +1-617-542-2652       *
 * Boston, MA  02110-1301,  USA       gnu@gnu.org                   *
 *                                                                  *
 *******************************************************************/
#ifndef GUID_HPP_HEADER
#define GUID_HPP_HEADER

#include <boost/uuid/uuid.hpp>
#include <stdexcept>
extern "C" {
#include "guid.h"
}

namespace gnc {
struct guid_syntax_exception : public std::invalid_argument
{
    guid_syntax_exception () noexcept;
};

struct GUID
{
    private:
    boost::uuids::uuid implementation;

    public:
    GUID (boost::uuids::uuid const &) noexcept;
    GUID (GncGUID const &) noexcept;
    GUID (GUID const &) noexcept = default;
    GUID () noexcept = default;
    GUID & operator = (GUID &&) noexcept;

    operator GncGUID () const noexcept;
    static GUID create_random () noexcept;
    static GUID const & null_guid () noexcept;
    static GUID from_string (std::string const &) throw (guid_syntax_exception);
    std::string to_string () const noexcept;
    auto begin () const noexcept -> decltype (implementation.begin ());
    auto end () const noexcept -> decltype (implementation.end ());
    bool operator < (GUID const &) noexcept;
    friend bool operator != (GUID const &, GUID const &) noexcept;
};

bool operator != (GUID const &, GUID const &) noexcept;
bool operator == (GUID const &, GncGUID const &) noexcept;

}
#endif

max_stars_repo_name: frapa/electrum

max_issues_repo_name: frapa/electrum

max_forks_repo_name: frapa/electrum


text:
/*
 *          Copyright Andrey Semashev 2007 - 2015.
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file   main.cpp
 * \author Andrey Semashev
 * \date   11.11.2007
 *
 * \brief  An example of basic library usage. See the library tutorial for expanded
 *         comments on this code. It may also be worthwhile reading the Wiki requirements page:
 *         http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?Boost.Logging
 */

// #define BOOST_LOG_USE_CHAR
// #define BOOST_ALL_DYN_LINK 1
// #define BOOST_LOG_DYN_LINK 1

#include <iostream>

#include <boost/log/common.hpp>
#include <boost/log/expressions.hpp>

#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>

#include <boost/log/attributes/timer.hpp>
#include <boost/log/attributes/named_scope.hpp>

#include <boost/log/sources/logger.hpp>

#include <boost/log/support/date_time.hpp>

namespace logging = boost::log;
namespace sinks = boost::log::sinks;
namespace attrs = boost::log::attributes;
namespace src = boost::log::sources;
namespace expr = boost::log::expressions;
namespace keywords = boost::log::keywords;

using boost::shared_ptr;

// Here we define our application severity levels.
enum severity_level
{
    normal,
    notification,
    warning,
    error,
    critical
};

// The formatting logic for the severity level
template< typename CharT, typename TraitsT >
inline std::basic_ostream< CharT, TraitsT >& operator<< (
    std::basic_ostream< CharT, TraitsT >& strm, severity_level lvl)
{
    static const char* const str[] =
    {
        "normal",
        "notification",
        "warning",
        "error",
        "critical"
    };
    if (static_cast< std::size_t >(lvl) < (sizeof(str) / sizeof(*str)))
        strm << str[lvl];
    else
        strm << static_cast< int >(lvl);
    return strm;
}

int main(int argc, char* argv[])
{
    // This is a simple tutorial/example of Boost.Log usage

    // The first thing we have to do to get using the library is
    // to set up the logging sinks - i.e. where the logs will be written to.
    logging::add_console_log(std::clog, keywords::format = "%TimeStamp%: %Message%");

    // One can also use lambda expressions to setup filters and formatters
    logging::add_file_log
    (
        "sample.log",
        keywords::filter = expr::attr< severity_level >("Severity") >= warning,
        keywords::format = expr::stream
            << expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d, %H:%M:%S.%f")
            << " [" << expr::format_date_time< attrs::timer::value_type >("Uptime", "%O:%M:%S")
            << "] [" << expr::format_named_scope("Scope", keywords::format = "%n (%f:%l)")
            << "] <" << expr::attr< severity_level >("Severity")
            << "> " << expr::message
/*
        keywords::format = expr::format("%1% [%2%] [%3%] <%4%> %5%")
            % expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d, %H:%M:%S.%f")
            % expr::format_date_time< attrs::timer::value_type >("Uptime", "%O:%M:%S")
            % expr::format_named_scope("Scope", keywords::format = "%n (%f:%l)")
            % expr::attr< severity_level >("Severity")
            % expr::message
*/
    );

    // Also let's add some commonly used attributes, like timestamp and record counter.
    logging::add_common_attributes();
    logging::core::get()->add_thread_attribute("Scope", attrs::named_scope());

    BOOST_LOG_FUNCTION();

    // Now our logs will be written both to the console and to the file.
    // Let's do a quick test and output something. We have to create a logger for this.
    src::logger lg;

    // And output...
    BOOST_LOG(lg) << "Hello, World!";

    // Now, let's try logging with severity
    src::severity_logger< severity_level > slg;

    // Let's pretend we also want to profile our code, so add a special timer attribute.
    slg.add_attribute("Uptime", attrs::timer());

    BOOST_LOG_SEV(slg, normal) << "A normal severity message, will not pass to the file";
    BOOST_LOG_SEV(slg, warning) << "A warning severity message, will pass to the file";
    BOOST_LOG_SEV(slg, error) << "An error severity message, will pass to the file";

    return 0;
}


text:
/**
 * @file particle.hpp
 * @author Vahid Bastani
 *
 * Generic particle filter.
 */
#ifndef SSMPACK_FILTER_PARTICLE_HPP
#define SSMPACK_FILTER_PARTICLE_HPP

#include "ssmkit/distribution/conditional.hpp"
#include "ssmkit/filter/recursive_bayesian_base.hpp"
#include "ssmkit/process/hierarchical.hpp"
#include "ssmkit/process/markov.hpp"
#include "ssmkit/process/memoryless.hpp"
#include <armadillo>

#include <tuple>

namespace ssmkit {
namespace filter {

using process::Hierarchical;
using process::Markov;
using process::Memoryless;
using distribution::Conditional;

/** Particle Filter.
 */
template <class Process, class Resampler>
class Particle : public RecursiveBayesianBase<Particle<Process, Resampler>> {
 public:
  /** Type of the state posterior
   *
   * \f$ \{\mathbf{x}^{(i)}_t,\omega^{(i)}\}_{i=1}^{M}\f$
   */
  using CompeleteState = std::tuple<arma::mat, arma::vec>;

 private:
  //! Particle weights \f$ \{\omega^{(i)}\}_{i=1}^{M}\f$.
  arma::vec w_;
  //! State particles \f$ \{\mathbf{x}^{(i)}_t\}_{i=1}^{M}\f$.
  arma::mat state_par_;
  //! The process model
  Process process_;
  //! Resampling algorithm
  Resampler resampler_;
  //! Number of particles \f$M\f$.
  unsigned long num_;

 private:
  //! Normalizes the sum of weights to one
  void normalizeWeights(void) { w_ = w_ / arma::sum(w_); }

 public:
  /** Constructor
   *
   * returns a Particle filter object.
   *
   * @param process The process model object that the PF is defined for
   * @param resampler The resampling algorithm
   * @param particles_num Number of particles \f$M\f$
   */
  Particle(Process process, Resampler resampler, unsigned long particles_num)
      : process_{process}, resampler_{resampler}, num_{particles_num} {
    // initialized w_ and state_par_
    w_.resize(num_);
    // take one sample to find out dimension
    auto tmp = process_.template getProcess<0>().getInitialPDF().random();
    state_par_.resize(tmp.size(), num_);
  }
  /** Prediction
   *
   * Performs prediction step.
   * \f{equation}{\mathbf{x}^{(i)}_t \sim p(\mathbf{x}_t| \tilde{\mathbf{x}}^{(i)}_{t-1}, y^d_1, \cdots, y^d_{N_d})
   * \quad \text{for} \quad i=1,\cdots,M\f}
   *
   * @param args... Control variables \f$y^d_1, \cdots, y^d_{N_d}\f$ of the dynamic process, if any.
   */
  template <class... Args>
  void predict(const Args &... args) {
    state_par_.each_col([this, &args...](arma::vec &v, const Args &... args) {
      v = process_.template getProcess<0>().getCPDF().random(v, args...);
    });
  }
  /** Correction
   *
   * Performs correction step.
   *
   * \f{equation}{ \omega^{(i)} = \tilde{\omega}^{(i)} p(\mathbf{z}_t| \mathbf{x}^{(i)}_t, y^m_1, \cdots, y^m_{N_m}) \f}
   * \f{equation}{\{\mathbf{x}^{(i)}_t,\omega^{(i)}\}_{i=1}^{M}
   * \overset{\mbox{resample}}{\longrightarrow}
   * \{\tilde{\mathbf{x}}^{(i)}_t,\tilde{\omega}^{(i)}\}_{i=1}^{M}\f}
   *
   * @param measurement Measurement vector \f$\mathbf{z}_t\f$.
   * @param args... Control variables \f$y^m_1, \cdots, y^m_{N_m}\f$ of the measurement process, if any.
   * @return Estimated state \f$\{\tilde{\mathbf{x}}^{(i)}_t,\tilde{\omega}^{(i)}\}_{i=1}^{M}\f$
   */
  template <class Measurement, class... TArgs>
  CompeleteState correct(const Measurement &measurement,
                         const TArgs &... args) {
    unsigned long cnt = 0;
    w_.for_each([this, &cnt, &measurement, &args...](double &e) {
      e *= process_.template getProcess<1>().getCPDF().likelihood(
          measurement, state_par_.col(cnt++), args...);
    });

    normalizeWeights();

    resampler_(state_par_, w_);

    return std::make_tuple(state_par_, w_);
  }
  /** Initialization
   *
   * @return Estimated state \f$\{\tilde{\mathbf{x}}^{(i)}_0,\tilde{\omega}^{(i)}\}_{i=1}^{M}\f$
   */
  CompeleteState initialize() {
    state_par_.each_col([this](arma::vec &v) {
      v = process_.template getProcess<0>().getInitialPDF().random();
    });

    unsigned long cnt = 0;
    w_.for_each([this, &cnt](double &e) {
      e = process_.template getProcess<0>().getInitialPDF().likelihood(
          state_par_.col(cnt++));
    });

    normalizeWeights();

    return std::make_tuple(state_par_, w_);
  }
  //! @return Estimated state \f$\{\tilde{\omega}^{(i)}\}_{i=1}^{M}\f$
  const arma::vec &getWeights(void) const { return w_; }
  //! @return Estimated state \f$\{\tilde{\mathbf{x}}^{(i)}_t\}_{i=1}^{M}\f$
  const arma::mat &getStateParticles(void) const { return state_par_; }
};

/**
 */
template <class StatePDF, class StateParamMap, class InitialPDF,
          class MeasurementPDF, class MeasurementParamMap, class Resampler>
auto makeParticle(
    Hierarchical<Markov<StatePDF, StateParamMap, InitialPDF>,
                 Memoryless<MeasurementPDF, MeasurementParamMap>> process,
    Resampler resampler, unsigned long particle_num) {
  return Particle<Hierarchical<Markov<StatePDF, StateParamMap, InitialPDF>,
                               Memoryless<MeasurementPDF, MeasurementParamMap>>,
                  Resampler>(process, resampler, particle_num);
}

} // namespace filter
} // namespace ssmkit

#endif // SSMPACK_FILTER_PARTICLE_HPP

max_stars_repo_name: vahid-bastani/ssmpack

max_issues_repo_name: vahidbas/ssmkit

max_forks_repo_name: vahidbas/ssmkit


text:
//
// Copyright Jason Rice 2016
// 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 NBDL_WEBUI_DETAIL_FLATTEN_SPEC_HPP
#define NBDL_WEBUI_DETAIL_FLATTEN_SPEC_HPP

#include <nbdl/fwd/webui/detail/flatten_spec.hpp>
#include <nbdl/ui_helper.hpp>
#include <nbdl/ui_spec.hpp>
#include <nbdl/webui/detail/dom_manips.hpp>
#include <nbdl/webui/html.hpp>

#include <boost/hana/flatten.hpp>
#include <boost/hana/type.hpp>
#include <boost/hana/unpack.hpp>
#include <boost/mp11/list.hpp>
#include <mpdef/list.hpp>
#include <mpdef/pair.hpp>
#include <type_traits>
#include <utility>

namespace nbdl::webui::detail
{
  namespace hana = boost::hana;
  using namespace boost::mp11;

  template <typename T>
  constexpr auto is_add_class_when_tag = hana::false_c;

  template <typename T>
  constexpr auto is_add_class_when_tag<html::tag::add_class_when_t<T>> = hana::true_c;

  template <typename FlattenSpecFn>
  struct flatten_named_node_fn
  {
    template <typename Tag, typename ChildNodes>
    constexpr auto operator()(Tag, ChildNodes) const
    {
      using Name  = decltype(hana::at_c<0>(ChildNodes{}));
      using Nodes = decltype(hana::drop_front(ChildNodes{}));
      constexpr auto children = hana::unpack(Nodes{}, [](auto ...x)
      {
        return mp_append<decltype(FlattenSpecFn{}(x))...>{};
      });

      return mp_append<
        mpdef::list<action_fn<begin, typename Tag::type, Name>>
      , std::decay_t<decltype(children)>
      , mpdef::list<action_fn<end, typename Tag::type, Name>>
      >{};
    }
  };

  template <typename Child>
  constexpr auto flatten_text_node(Child child)
  {
    if constexpr(hana::Product<Child>::value)
    {
      if constexpr(hana::equal(ui_spec::tag::concat, hana::typeid_(hana::first(child))))
      {
        return hana::unpack(hana::second(child), [](auto ...xs)
        {
          return mp_append<decltype(flatten_text_node(xs))...>{};
        });
      }
      else
      {
        // invalid argument to text node
        return mpdef::list<
          action_fn<html::tag::text_node_t, void>
        >{};
      }
    }
    else
    {
      return mpdef::list<
        action_fn<html::tag::text_node_t , decltype(child)>
      >{};
    }
  }

  template <typename Node>
  constexpr auto flatten_spec_fn::operator()(Node node) const
  {
    if constexpr(hana::Product<Node>::value)
    {
      // nodes are always pairs (tag, stuff)
      constexpr auto current_tag = hana::first(node);
      constexpr auto child_nodes = hana::second(node);

      if constexpr(decltype(hana::equal(current_tag, html::tag::element))::value)
      {
        return decltype(flatten_named_node_fn<flatten_spec_fn>{}(current_tag, child_nodes)){};
      }
      else if constexpr(
            decltype(hana::equal(current_tag, html::tag::attribute))::value
         or decltype(hana::equal(current_tag, html::tag::set_property))::value
      )
      {
        return mpdef::list<action_fn<
          typename decltype(current_tag)::type
        , decltype(hana::at_c<0>(child_nodes))
        , decltype(ui_helper::flatten_param_node(hana::at_c<1>(child_nodes)))
        >>{};
      }
      else if constexpr(decltype(hana::equal(current_tag, html::tag::text_node))::value)
      {
        return flatten_text_node(child_nodes);
      }
      else if constexpr(decltype(hana::equal(current_tag, html::tag::unsafe_set_inner_html))::value)
      {
        return mpdef::list<action_fn<
          typename decltype(current_tag)::type
        , std::decay_t<decltype(child_nodes)>
        >>{};
      }
      else if constexpr(decltype(hana::or_(
        hana::equal(current_tag, html::tag::add_attribute_if)
      , hana::equal(current_tag, html::tag::add_class_if)
      , hana::equal(current_tag, html::tag::event_attribute)
      , hana::equal(current_tag, html::tag::hidden_file_input)
      , is_add_class_when_tag<typename decltype(current_tag)::type>
      ))::value)
      {
        return mpdef::list<mp_append<
          action_fn<typename decltype(current_tag)::type>
        , std::decay_t<decltype(child_nodes)>
        >>{};
      }
      else
      {
        static_assert(std::is_void<decltype(current_tag)>::value);
      }
    }
    else if constexpr(hana::is_a<ui_spec::branch_spec_tag, Node>())
    {
      return ui_helper::flatten_branch_node(
        hana::template_<action_fn>
      , flatten_spec_fn{}
      , Node{}
      );
    }
    else if constexpr(hana::is_a<ui_spec::for_each_tag, Node>())
    {
      return ui_helper::flatten_for_each_node(
        hana::template_<action_fn>
      , flatten_spec_fn{}
      , Node{}
      );
    }
    else if constexpr(hana::is_a<ui_spec::noop_t, Node>())
    {
      return mpdef::list<>{};
    }
    else
    {
      return mpdef::list<Node>{};
    }
  }
}
#endif

max_stars_repo_name: ricejasonf/nbdl

max_issues_repo_name: ricejasonf/nbdl

max_forks_repo_name: ricejasonf/nbdl


text:
/*=============================================================================
    Copyright (c) 2001-2006 Joel de Guzman

    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_PP_IS_ITERATING
#if !defined(FUSION_MAKE_LIST_07192005_1239)
#define FUSION_MAKE_LIST_07192005_1239

#include <boost/preprocessor/iterate.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/enum_params_with_a_default.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/fusion/container/list/list.hpp>
#include <boost/fusion/support/detail/as_fusion_element.hpp>

namespace boost { namespace fusion
{
    struct void_;

    namespace result_of
    {
        template <
            BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(
                FUSION_MAX_LIST_SIZE, typename T, void_)
          , typename Extra = void_
        >
        struct make_list;

        template <>
        struct make_list<>
        {
            typedef list<> type;
        };
    }

    inline list<>
    make_list()
    {
        return list<>();
    }

#define BOOST_FUSION_AS_FUSION_ELEMENT(z, n, data)                               \
    typename detail::as_fusion_element<BOOST_PP_CAT(T, n)>::type

#define BOOST_PP_FILENAME_1 <boost/fusion/container/generation/make_list.hpp>
#define BOOST_PP_ITERATION_LIMITS (1, FUSION_MAX_LIST_SIZE)
#include BOOST_PP_ITERATE()

#undef BOOST_FUSION_AS_FUSION_ELEMENT

}}

#endif
#else // defined(BOOST_PP_IS_ITERATING)
///////////////////////////////////////////////////////////////////////////////
//
//  Preprocessor vertical repetition code
//
///////////////////////////////////////////////////////////////////////////////

#define N BOOST_PP_ITERATION()

    namespace result_of
    {
        template <BOOST_PP_ENUM_PARAMS(N, typename T)>
#if defined(BOOST_NO_PARTIAL_SPECIALIZATION_IMPLICIT_DEFAULT_ARGS)
        #define TEXT(z, n, text) , text
        struct make_list< BOOST_PP_ENUM_PARAMS(N, T) BOOST_PP_REPEAT_FROM_TO(BOOST_PP_DEC(N), FUSION_MAX_LIST_SIZE, TEXT, void_) >
        #undef TEXT
#else
        struct make_list<BOOST_PP_ENUM_PARAMS(N, T)>
#endif
        {
            typedef list<BOOST_PP_ENUM(N, BOOST_FUSION_AS_FUSION_ELEMENT, _)> type;
        };
    }

    template <BOOST_PP_ENUM_PARAMS(N, typename T)>
    inline list<BOOST_PP_ENUM(N, BOOST_FUSION_AS_FUSION_ELEMENT, _)>
    make_list(BOOST_PP_ENUM_BINARY_PARAMS(N, T, const& _))
    {
        return list<BOOST_PP_ENUM(N, BOOST_FUSION_AS_FUSION_ELEMENT, _)>(
            BOOST_PP_ENUM_PARAMS(N, _));
    }

#undef N
#endif // defined(BOOST_PP_IS_ITERATING)

max_stars_repo_name: EricBoittier/vina-carb-docker

max_issues_repo_name: EricBoittier/vina-carb-docker

max_forks_repo_name: EricBoittier/vina-carb-docker


text:
//
// Ryu
//
// Copyright (C) 2017 Jeff Panici
// All Rights Reserved.
//
// See the LICENSE file for details about the license covering
// this source code file.
//

#include <fstream>
#include <yaml-cpp/yaml.h>
#include <core/yaml_support.h>
#include <hardware/registry.h>
#include <common/stream_support.h>
#include <boost/filesystem/operations.hpp>
#include "project.h"
#include "project_file.h"

namespace ryu::core {

    core::project_shared_ptr core::project::_instance = nullptr;

    bool project::create(
            core::result& result,
            const fs::path& path) {
        fs::path project_path = path;

        if (!project_path.is_absolute()) {
            project_path = fs::current_path().append(project_path.string());
        }

        if (fs::is_directory(project_path)) {
            result.add_message(
                    "C031",
                    fmt::format("project directory already exists: {}", project_path.string()),
                    true);
            return false;
        }

        boost::system::error_code ec;
        if (!fs::create_directory(project_path, ec)) {
            result.add_message(
                    "C031",
                    fmt::format("unable to create directory: {}", ec.message()),
                    true);
            return false;
        }

        fs::path metadata_path(project_path);
        metadata_path.append(".ryu");
        if (!fs::create_directory(metadata_path, ec)) {
            result.add_message(
                    "C031",
                    fmt::format("unable to create metadata directory: {}", ec.message()),
                    true);
            return false;
        }

        _instance = core::project_shared_ptr(new core::project(project_path));
        _instance->_open = true;
        _instance->save(result);

        return !result.is_failed();
    }

    // XXX: would be nice to add feature to scan up parent directories
    //      to see if .ryu/arcade.rproj is found.
    bool project::load(
            core::result& result,
            const fs::path& path) {
        auto project_path = find_project_root(path);
        auto project_file = project_path;
        if (!does_project_file_exist(project_file)) {
            result.add_message(
                "C031",
                fmt::format("project file does not exist: {}", project_file.string()),
                true);
            return false;
        }

        auto root = YAML::LoadFile(project_file.string());

        std::string project_name;

        if (!get_optional(root["name"], project_name)) {
            result.add_message(
                "C031",
                "Project requires name.",
                true);
            return false;

        }

        _instance = core::project_shared_ptr(new core::project(project_path));
        _instance->suspend_notify();
        _instance->name(project_name);

        std::string project_description;
        if (get_optional(root["description"], project_description))
            _instance->description(project_description);

        uint32_t machine_id;
        hardware::machine* machine = nullptr;
        if (get_optional(root["machine"], machine_id)) {
            machine = hardware::registry::instance()->find_machine(machine_id);
            if (machine == nullptr) {
                result.add_message(
                    "C031",
                    fmt::format("no machine exists with id: {}", machine_id),
                    true);
                return false;
            }
            _instance->machine(machine);
        }

        auto files = root["files"];
        if (files != nullptr && files.IsSequence()) {
            for (auto it = files.begin(); it != files.end(); ++it) {
                auto file_node = *it;
                auto file = core::project_file::load(
                    result,
                    _instance.get(),
                    file_node);
                if (file->type() != core::project_file_type::uninitialized) {
                    _instance->add_file(file);
                }
            }
        }

        uint32_t active_environment_id;
        if (get_optional(root["active_environment"], active_environment_id)) {
            auto file = _instance->find_file(active_environment_id);
            if (file == nullptr) {
                result.add_message(
                    "C031",
                    fmt::format("no project_file exists with id: {}", active_environment_id),
                    true);
                return false;
            }
            _instance->active_environment(file);
        }

        auto props = root["props"];
        if (props != nullptr && props.IsSequence()) {
            for (auto it = props.begin(); it != props.end(); ++it) {
                auto prop_node = *it;
                _instance->prop(
                        prop_node["key"].as<std::string>(),
                        prop_node["value"].as<std::string>());
            }
        }

        _instance->_dirty = false;
        _instance->_open = true;
        _instance->resume_notify();

        return true;
    }

    bool project::clone(
            core::result& result,
            const fs::path& source_path,
            const fs::path& target_path) {
        if (_instance == nullptr) {
            result.add_message(
                    "C032",
                    "no project is loaded; clone failed",
                    true);
            return false;
        }

        return false;
    }

    bool project::close(core::result& result) {
        if (_instance == nullptr) {
            result.add_message(
                    "C032",
                    "no project is loaded; close failed",
                    true);
            return false;
        }

        _instance->_open = false;
        _instance->notify();
        _instance = nullptr;

        return true;
    }

    bool project::does_project_file_exist(fs::path& path) {
        if (!fs::exists(path))
            return false;
        path.append(".ryu").append("arcade.rproj");
        return fs::exists(path);
    }

    void project::notify() {
        if (!_notify_enabled)
            return;
        core::notification_center::instance()->notify(this);
    }

    bool project::open() const {
        return _open;
    }

    void project::resume_notify() {
        _notify_enabled = true;
        notify();
    }

    void project::suspend_notify() {
        _notify_enabled = false;
    }

    core::project* project::instance() {
        return _instance.get();
    }

    project::project(const fs::path& project_path) : _id(id_pool::instance()->allocate()),
                                                     _path(project_path),
                                                     _name(project_path.filename().string()) {
        core::notification_center::instance()->add_observable(this);
    }

    project::~project() {
        // static init/destroy issues
        //core::notification_center::instance()->remove_observable(this);
    }

    bool project::dirty() const {
        return _dirty;
    }

    uint32_t project::id() const {
        return _id;
    }

    fs::path project::path() const {
        return _path;
    }

    void project::remove_all_files() {
        _files.clear();
        _dirty = true;
        notify();
    }

    std::string project::name() const {
        return _name;
    }

    hardware::machine* project::machine() {
        return _machine;
    }

    fs::path project::find_project_root(const fs::path& current_path) {
        auto path = current_path.empty() ? fs::current_path() : current_path;
        while (true) {
            auto project_file_path = path;
            if (does_project_file_exist(project_file_path))
                break;
            if (!path.has_parent_path())
                break;
            path = path.parent_path();
        }
        return path;
    }

    observable_type project::type_id() const {
        return observables::types::project;
    }

    bool project::save(core::result& result) {
        YAML::Emitter emitter;

        emitter << YAML::BeginMap;
        emitter << YAML::Key << "name" << YAML::Value << _name;
        emitter << YAML::Key << "description" << YAML::Value << _description;

        auto machine_id = _machine != nullptr ? _machine->id() : 0;
        emitter << YAML::Key << "machine" << YAML::Value << machine_id;

        auto active_environment_id = _active_environment != nullptr ? _active_environment->id() : 0;
        emitter << YAML::Key << "active_environment" << YAML::Value << active_environment_id;

        emitter << YAML::Key << "files" << YAML::BeginSeq;
        for (const auto& file : _files)
            file->save(result, emitter);
        emitter << YAML::EndSeq;

        emitter << YAML::Key << "props" << YAML::BeginSeq;
        for (auto& it : _props) {
            emitter << YAML::BeginMap;
            emitter << YAML::Key << "key" << it.first;
            emitter << YAML::Key << "value" << it.second;
            emitter << YAML::EndMap;
        }
        emitter << YAML::EndSeq;

        fs::path project_file(_path);
        project_file
            .append(".ryu")
            .append("arcade.rproj");
        ryu::write_text(result, project_file, emitter.c_str());

        _dirty = false;
        if (!result.is_failed())
            notify();

        return !result.is_failed();
    }

    void project::remove_file(uint32_t id) {
        for (size_t i = 0; i < _files.size(); i++) {
            const auto& file = _files[i];
            if (file->id() == id) {
                _files.erase(_files.begin() + i);
                _dirty = true;
                notify();
                break;
            }
        }
        std::sort(
                _files.begin(),
                _files.end(),
                [](const project_file_shared_ptr& left, project_file_shared_ptr& right) {
                    return left->sequence() < right->sequence();
                });
    }

    std::string project::description() const {
        return _description;
    }

    project_file* project::active_environment() {
        return _active_environment;
    }

    void project::name(const std::string& value) {
        if (value != _name) {
            _name = value;
            _dirty = true;
            notify();
        }
    }

    project_file* project::find_file(uint32_t id) {
        for (size_t i = 0; i < _files.size(); i++) {
            const auto& file = _files[i];
            if (file->id() == id)
                return file.get();
        }
        return nullptr;
    }

    const project_file_list& project::files() const {
        return _files;
    }

    void project::machine(hardware::machine* machine) {
        if (machine != _machine) {
            _machine = machine;
            _dirty = true;
            notify();
        }
    }

    void project::add_file(const project_file_shared_ptr& value) {
        _files.push_back(value);
        std::sort(
                _files.begin(),
                _files.end(),
                [](const project_file_shared_ptr& left, const project_file_shared_ptr& right) {
                    return left->sequence() < right->sequence();
                });
        _dirty = true;
        notify();
    }

    void project::description(const std::string& value) {
        if (value != _description) {
            _description = value;
            _dirty = true;
            notify();
        }
    }

    void project::active_environment(project_file* value) {
        if (value != _active_environment) {
            _active_environment = value;
            _dirty = true;
            notify();
        }
    }

    project_file* project::find_file(const fs::path& path) {
        for (size_t i = 0; i < _files.size(); i++) {
            const auto& file = _files[i];
            if (file->path() == path)
                return file.get();
        }
        return nullptr;
    }

    std::string project::prop(const std::string& key) const {
        auto it = _props.find(key);
        if (it != _props.end())
            return it->second;
        return "";
    }

    void project::prop(const std::string& key, const std::string& value) {
        _props[key] = value;
        _dirty = true;
        notify();
    }

}


text:
//
// boost-geometry-render
//
// Copyright (c) 2011
// osyo-manga : http://d.hatena.ne.jp/osyo-manga/
//
// License:
// Boost Software License - Version 1.0
// <http://www.boost.org/LICENSE_1_0.txt>
//
#include <cstdlib>
#include <gl/glut.h>
#include <gl/graphics.hpp>
#include <gl/geometry_render.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <iostream>
#include <boost/thread.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/geometry/geometries/linestring.hpp>

namespace bg = boost::geometry;

template<typename Geometry>
struct geometry_renderer{
	geometry_renderer(Geometry& geometry) : geometry_(geometry){};
	void operator ()(){
		glColor3d(1.0f, 0.0f, 0.0f);
		gl::render(geometry_);
	}
private:
	Geometry& geometry_;
};

template<typename Geometry>
geometry_renderer<Geometry>
make_geometry_renderer(Geometry& geometry){
	return geometry_renderer<Geometry>(geometry);
}

int
main(int argc, char* argv[]){
	typedef bg::model::d2::point_xy<float> point_type;
	bg::model::polygon<point_type> polygon;
	bg::exterior_ring(polygon) = boost::assign::list_of<point_type>
		( 0.0f,  0.5f)
		( 0.5f,  0.0f)
		( 0.1f, -0.1f)
		( 0.0f, -0.5f)
		(-0.1f, -0.1f)
		(-0.5f,  0.0f);

	gl::graphics g(argc, argv, 500, 500);
	gl::displayfunc(g, make_geometry_renderer(polygon));

	g.run();
	return 0;
}

max_stars_repo_name: osyo-manga/boost-geometry-render

max_issues_repo_name: osyo-manga/boost-geometry-render

max_forks_repo_name: osyo-manga/boost-geometry-render


text:
#include <boost/test/unit_test.hpp>
#include <eosio/testing/tester.hpp>
#include <eosio/chain/merkle.hpp>
#include <fc/io/json.hpp>

using namespace eosio;
using namespace eosio::chain;
using namespace eosio::testing;

struct action_proof_data {
   account_name              receiver;
   scope_name                scope;
   action_name               name;
   bytes                     data;
   uint32_t                  region_id;
   uint32_t                  cycle_index;
   vector<data_access_info>  data_access;
};
FC_REFLECT(action_proof_data, (receiver)(scope)(name)(data)(region_id)(cycle_index)(data_access));

struct merkle_node {
   digest_type                   digest;
   optional<size_t>              left;
   optional<size_t>              right;
   optional<size_t>              parent;
};

digest_type process_merkle(vector<merkle_node>& nodes, vector<size_t> leaf_indices) {
   size_t num_nodes = leaf_indices.size();
   size_t base = 0;

   if (num_nodes == 0) {
      return digest_type();
   } else if (num_nodes == 1) {
      return nodes[leaf_indices.front()].digest;
   }

   while (num_nodes > 1) {
      size_t new_nodes = (num_nodes / 2) + (num_nodes % 2);
      for(size_t idx = 0; idx < new_nodes; idx++) {
         size_t l_idx = idx * 2;
         size_t r_idx = l_idx + 1;
         size_t left = leaf_indices.at(base + l_idx);
         if (r_idx >= num_nodes) {
            nodes.emplace_back(
               merkle_node{
                  digest_type::hash(make_canonical_pair(nodes[left].digest, nodes[left].digest)),
                  left
               });
            nodes[left].parent.emplace(nodes.size() - 1);
         } else {
            size_t right = leaf_indices.at(base + r_idx);
            nodes.emplace_back(
               merkle_node{
                  digest_type::hash(make_canonical_pair(nodes[left].digest, nodes[right].digest)),
                  left,
                  right
               });
            nodes[left].parent.emplace(nodes.size() - 1);
            nodes[right].parent.emplace(nodes.size() - 1);
         }

         leaf_indices.emplace_back(nodes.size() - 1);
      }

      base += num_nodes;
      num_nodes = new_nodes;
   }

   return nodes.back().digest;
}

auto get_proof_path(const vector<merkle_node>& nodes, size_t leaf) {
   vector<digest_type> path;
   digest_type current = nodes[leaf].digest;
   while (nodes[leaf].parent.valid()) {
      size_t parent = *nodes[leaf].parent;
      if (leaf == *nodes[parent].left) {
         if (nodes[parent].right.valid()) {
            size_t right = *nodes[parent].right;
            path.emplace_back(make_canonical_right(nodes[right].digest));
            current = digest_type::hash(make_canonical_pair(nodes[leaf].digest, nodes[right].digest));
         } else {
            path.emplace_back(make_canonical_right(nodes[leaf].digest));
            current = digest_type::hash(make_canonical_pair(nodes[leaf].digest, nodes[leaf].digest));
         }
      } else {
         size_t left = *nodes[parent].left;
         path.emplace_back(make_canonical_left(nodes[left].digest));
         current = digest_type::hash(make_canonical_pair(nodes[left].digest, nodes[leaf].digest));
      }

      leaf = parent;
   }

   return path;
}

digest_type apply_path(const digest_type& digest, const vector<digest_type>& path) {
   digest_type current = digest;

   for (const auto& p: path ) {
      if (is_canonical_left(p)) {
         current = digest_type::hash(make_canonical_pair(p, current));
      } else {
         current = digest_type::hash(make_canonical_pair(current, p));
      }
   }

   return current;
}

bool proof_is_valid(const digest_type& digest, const vector<digest_type>& path, const digest_type& expected_root) {
   return apply_path(digest, path) == expected_root;
}

BOOST_AUTO_TEST_SUITE(proof_tests)

BOOST_FIXTURE_TEST_CASE( prove_block_in_chain, tester ) { try {
   vector<block_id_type> known_blocks;
   known_blocks.reserve(100);
   block_header last_block_header;

    // register a callback on new blocks to record block information
   control->applied_block.connect([&](const block_trace& bt){
      known_blocks.emplace_back(bt.block.id());
      last_block_header = bt.block;
   });

   produce_blocks(100);

   vector<merkle_node> nodes;
   vector<digest_type> ids;
   vector<size_t> block_leaves;
   nodes.reserve(100);
   ids.reserve(100);
   for (const auto& blk_id: known_blocks) {
      nodes.emplace_back(merkle_node{blk_id});
      ids.push_back(blk_id);
      block_leaves.push_back(nodes.size() - 1);
   }

   digest_type block_mroot = process_merkle(nodes, move(block_leaves));

   BOOST_REQUIRE_EQUAL((std::string)block_mroot, (std::string)merkle(ids));

   produce_block();

   BOOST_REQUIRE_EQUAL((std::string)block_mroot, (std::string)last_block_header.block_mroot);

   for (int idx = 0; idx < 100; idx++) {
      vector<digest_type> path = get_proof_path(nodes, idx);

      BOOST_REQUIRE_EQUAL(true, proof_is_valid(nodes[idx].digest, path, last_block_header.block_mroot));

      /** UNCOMMENT TO PRODUCE PROOFS TO STD OUT
      std::cout << idx <<  ":" <<  std::string(known_blocks.at(idx)) << " = ";
      for (const auto& e: path) {
         std::cout << std::string(e) << " ";
      }

      std::cout << "-> " << std::string(last_block_header.block_mroot) << std::endl;
       */
   }

} FC_LOG_AND_RETHROW() } /// transfer_test

struct action_proof_info {
   action_trace trace;

   size_t action_leaf;
   size_t block_leaf;

   uint32_t cycle_index;
   uint32_t region_id;
};

/**
 *  This test case will attempt to allow one account to transfer on behalf
 *  of another account by updating the active authority.
 */
BOOST_FIXTURE_TEST_CASE( prove_action_in_block, tester ) { try {
   vector<merkle_node> nodes;
   vector<size_t> block_leaves;
   vector<action_proof_info> known_actions;
   map<digest_type, digest_type> block_action_mroots;
   block_header last_block_header;
   block_id_type last_block_id;

   // register a callback on new blocks to record block information
   control->applied_block.connect([&](const block_trace& bt){
      nodes.emplace_back(merkle_node{bt.block.id()});
      size_t block_leaf = nodes.size() - 1;
      block_leaves.push_back(block_leaf);
      vector<size_t> shard_leaves;

      for (uint32_t r_idx = 0; r_idx < bt.region_traces.size(); r_idx++) {
         const auto& rt = bt.region_traces.at(r_idx);
         for (uint32_t c_idx = 0; c_idx < rt.cycle_traces.size(); c_idx++) {
            const auto& ct = rt.cycle_traces.at(c_idx);

            for (const auto& st: ct.shard_traces) {
               vector<size_t> action_leaves;

               for (const auto& tt: st.transaction_traces) {
                  for (const auto& at: tt.action_traces) {
                     digest_type::encoder enc;

                     auto a_data = action_proof_data {
                        at.receiver,
                        at.act.account,
                        at.act.name,
                        at.act.data,
                        at.region_id,
                        at.cycle_index,
                        at.data_access
                     };
                     fc::raw::pack(enc, a_data);
                     nodes.emplace_back(merkle_node{enc.result()});
                     size_t action_leaf = nodes.size() - 1;
                     known_actions.emplace_back(action_proof_info{at, action_leaf, block_leaf, c_idx, r_idx });
                     action_leaves.emplace_back(action_leaf);
                  }
               }

               if (action_leaves.size() > 0) {
                  process_merkle(nodes, move(action_leaves));
                  shard_leaves.emplace_back(nodes.size() - 1);
               }
            }
         }
      }

      digest_type action_mroot = process_merkle(nodes, move(shard_leaves));
      BOOST_REQUIRE_EQUAL((std::string)bt.block.action_mroot, (std::string)action_mroot);

      last_block_header = bt.block;
      last_block_id = bt.block.id();
      block_action_mroots[bt.block.id()] = bt.block.action_mroot;
   });

   create_accounts( { N(alice), N(bob), N(carol), N(david), N(elvis) });

   produce_blocks(50);

   push_nonce( N(alice), "AB" );
   push_nonce( N(bob),   "BC" );
   push_nonce( N(carol), "CD" );
   push_nonce( N(david), "DE" );
   push_nonce( N(elvis), "EF" );

   produce_blocks(50);
   digest_type block_mroot = process_merkle(nodes, move(block_leaves));

   produce_block();
   BOOST_REQUIRE_EQUAL((std::string)block_mroot, (std::string)last_block_header.block_mroot);

   /* UNCOMMENT TO PRODUCE PROOFS TO STDOUT
   std::cout << "Best Block ID: " << (std::string)last_block_id << std::endl;
   std::cout << "  Merkle Root: " << (std::string)last_block_header.block_mroot << std::endl;

   for(const auto& ai : known_actions) {
      auto block_path = get_proof_path(nodes, ai.action_leaf);
      auto chain_path = get_proof_path(nodes, ai.block_leaf);

      // prove action in block
      auto shard_root = apply_path(nodes[ai.action_leaf].digest, block_path);
      BOOST_REQUIRE_EQUAL((std::string)shard_root, (std::string)block_action_mroots[nodes[ai.block_leaf].digest]);

      // prove that block is part of the chain
      auto expected_block_mroot = apply_path(nodes[ai.block_leaf].digest, chain_path);
      BOOST_REQUIRE_EQUAL((std::string)expected_block_mroot, (std::string)last_block_header.block_mroot);

      std::cout << "Proof for Action:" << std::endl;
      std::cout << std::setw(14) << "reciever" << ":" << (std::string) ai.trace.receiver << std::endl;
      std::cout << std::setw(14) << "scope" << ":" << (std::string) ai.trace.act.scope << std::endl;
      std::cout << std::setw(14) << "name" << ":" << (std::string) ai.trace.act.name << std::endl;
      std::cout << std::setw(14) << "data" << ":" << fc::json::to_string(ai.trace.act.as<contracts::transfer>()) << std::endl;
      std::cout << std::setw(14) << "data_access" << ":" << fc::json::to_string(ai.trace.data_access) << std::endl;
      std::cout << std::setw(14) << "region" << ":" << ai.region_id << std::endl;
      std::cout << std::setw(14) << "cycle" << ":" << ai.cycle_index << std::endl;
      std::cout << std::setw(14) << "block" << ":" << (std::string)nodes[ai.block_leaf].digest << std::endl;
      std::cout << std::setw(14) << "am_root" << ":" << (std::string)block_action_mroots[nodes[ai.block_leaf].digest] << std::endl;
      std::cout << std::endl;

      auto a_data = action_proof_data {
         ai.trace.receiver,
         ai.trace.act.scope,
         ai.trace.act.name,
         ai.trace.act.data,
         ai.trace.region_id,
         ai.trace.cycle_index,
         ai.trace.data_access
      };
      auto action_data = fc::raw::pack(a_data);

      std::cout << "Action Hex: " << fc::to_hex(action_data) << std::endl;
      std::cout << "Action Hash: " << (std::string)nodes[ai.action_leaf].digest << std::endl;

      std::cout << "Action Path: ";
      for (const auto& p: block_path) {
         std::cout << (std::string)p << " ";
      }
      std::cout << std::endl;

      std::cout << "Block Path: ";
      for (const auto& p: chain_path) {
         std::cout << (std::string)p << " ";
      }
      std::cout << std::endl;
   }*/

} FC_LOG_AND_RETHROW() }

BOOST_AUTO_TEST_SUITE_END()

max_issues_repo_name: ElementhFoundation/blockchain

max_forks_repo_name: ElementhFoundation/blockchain


text:
/*
 * Copyright 2012 Yahoo! Inc.
 *
 * 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.
 */

/**
 * This is a stub implementation of the mapkeeper interface that uses
 * std::map. Data is not persisted.
 */
#include <map>
#include <string>
#include <arpa/inet.h>
#include "MapKeeper.h"

#include <boost/thread/shared_mutex.hpp>
#include <protocol/TBinaryProtocol.h>
#include <server/TThreadedServer.h>
#include <transport/TServerSocket.h>
#include <transport/TBufferTransports.h>

using namespace std;
using namespace mapkeeper;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;

using boost::shared_ptr;

class StlMapServer: virtual public MapKeeperIf {
public:
    ResponseCode::type ping() {
        return ResponseCode::Success;
    }

    ResponseCode::type addMap(const string& mapName) {
        boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
        map<string, map<string, string> >::iterator itr = maps_.find(mapName);
        if (itr != maps_.end()) {
            return ResponseCode::MapExists;
        }
        map<string, string> newMap;
        pair<string, map<string, string> > entry(mapName, newMap);
        maps_.insert(entry);
        return ResponseCode::Success;
    }

    ResponseCode::type dropMap(const string& mapName) {
        boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
        map<string, map<string, string> >::iterator itr = maps_.find(mapName);
        if (itr == maps_.end()) {
            return ResponseCode::MapNotFound;
        }
        maps_.erase(itr);
        return ResponseCode::Success;
    }

    void listMaps(StringListResponse& _return) {
        boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
        map<string, map<string, string> >::iterator itr;
        for (itr = maps_.begin(); itr != maps_.end(); itr++) {
            _return.values.push_back(itr->first);
        }
        _return.responseCode = ResponseCode::Success;
    }

    void scan(RecordListResponse& _return, const string& mapName, const ScanOrder::type order,
              const string& startKey, const bool startKeyIncluded,
              const string& endKey, const bool endKeyIncluded,
              const int32_t maxRecords, const int32_t maxBytes) {
        boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
        map<string, map<string, string> >::iterator itr = maps_.find(mapName);
        if (itr == maps_.end()) {
            _return.responseCode = ResponseCode::MapNotFound;
            return;
        }
        if (order == ScanOrder::Ascending) {
          scanAscending(_return, itr->second, startKey, startKeyIncluded, endKey, endKeyIncluded, maxRecords, maxBytes);
        } else {
          scanDescending(_return, itr->second, startKey, startKeyIncluded, endKey, endKeyIncluded, maxRecords, maxBytes);
        }
    }

    void scanAscending(RecordListResponse& _return, const map<string, string>& mymap,
              const string& startKey, const bool startKeyIncluded,
              const string& endKey, const bool endKeyIncluded,
              const int32_t maxRecords, const int32_t maxBytes) {
        map<string, string>::const_iterator itr = startKeyIncluded ?
            mymap.lower_bound(startKey):
            mymap.upper_bound(startKey);
        int numBytes = 0;
        while (itr != mymap.end()) {
            if (!endKey.empty()) {
                if (endKeyIncluded && endKey < itr->first) {
                  break;
                }
                if (!endKeyIncluded && endKey <= itr->first) {
                  break;
                }
            }
            Record record;
            record.key = itr->first;
            record.value = itr->second;
            numBytes += record.key.size() + record.value.size();
            _return.records.push_back(record);
            if (_return.records.size() >= (uint32_t)maxRecords || numBytes >= maxBytes) {
                _return.responseCode = ResponseCode::Success;
                return;
            }
            itr++;
        }
        _return.responseCode = ResponseCode::ScanEnded;
    }

    void scanDescending(RecordListResponse& _return, const map<string, string>& mymap,
              const string& startKey, const bool startKeyIncluded,
              const string& endKey, const bool endKeyIncluded,
              const int32_t maxRecords, const int32_t maxBytes) {
        map<string, string>::const_iterator itr;
        if (endKey.empty()) {
            itr = mymap.end();
        } else {
            itr = endKeyIncluded ? mymap.upper_bound(endKey) : mymap.lower_bound(endKey);
        }
        int numBytes = 0;
        while (itr != mymap.begin()) {
            itr--;
            if (startKeyIncluded && startKey > itr->first) {
                break;
            }
            if (!startKeyIncluded && startKey >= itr->first) {
                break;
            }
            Record record;
            record.key = itr->first;
            record.value = itr->second;
            numBytes += record.key.size() + record.value.size();
            _return.records.push_back(record);
            if (_return.records.size() >= (uint32_t)maxRecords || numBytes >= maxBytes) {
                _return.responseCode = ResponseCode::Success;
                return;
            }
        }
        _return.responseCode = ResponseCode::ScanEnded;
    }

    void get(BinaryResponse& _return, const string& mapName, const string& key) {
        boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
        map<string, map<string, string> >::iterator itr = maps_.find(mapName);
        if (itr == maps_.end()) {
            _return.responseCode = ResponseCode::MapNotFound;
            return;
        }
        map<string, string>::iterator recordIterator = itr->second.find(key);
        if (recordIterator == itr->second.end()) {
            _return.responseCode = ResponseCode::RecordNotFound;
            return;
        }
        _return.responseCode = ResponseCode::Success;
        _return.value = recordIterator->second;
    }

    ResponseCode::type put(const string& mapName, const string& key, const string& value) {
        boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
        map<string, map<string, string> >::iterator itr = maps_.find(mapName);
        if (itr == maps_.end()) {
            return ResponseCode::MapNotFound;
        }
        itr->second[key] = value;
        return ResponseCode::Success;
    }

    ResponseCode::type insert(const string& mapName, const string& key, const string& value) {
        boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
        map<string, map<string, string> >::iterator itr = maps_.find(mapName);
        if (itr == maps_.end()) {
            return ResponseCode::MapNotFound;
        }
        if (itr->second.find(key) != itr->second.end()) {
            return ResponseCode::RecordExists;
        }
        itr->second.insert(pair<string, string>(key, value));
        return ResponseCode::Success;
    }

    ResponseCode::type update(const string& mapName, const string& key, const string& value) {
        boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
        map<string, map<string, string> >::iterator itr = maps_.find(mapName);
        if (itr == maps_.end()) {
            return ResponseCode::MapNotFound;
        }
        if (itr->second.find(key) == itr->second.end()) {
            return ResponseCode::RecordNotFound;
        }
        itr->second[key] = value;
        return ResponseCode::Success;
    }

    ResponseCode::type remove(const string& mapName, const string& key) {
        boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
        map<string, map<string, string> >::iterator itr = maps_.find(mapName);
        if (itr == maps_.end()) {
            return ResponseCode::MapNotFound;
        }
        map<string, string>::iterator recordIterator = itr->second.find(key);
        if (recordIterator  == itr->second.end()) {
            return ResponseCode::RecordNotFound;
        }
        itr->second.erase(recordIterator);
        return ResponseCode::Success;
    }

private:
    map<string, map<string, string> > maps_;
    boost::shared_mutex mutex_; // protect map_
};

int main(int argc, char **argv) {
    int port = 9090;
    shared_ptr<StlMapServer> handler(new StlMapServer());
    shared_ptr<TProcessor> processor(new MapKeeperProcessor(handler));
    shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
    shared_ptr<TTransportFactory> transportFactory(new TFramedTransportFactory());
    shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
    TThreadedServer server(processor, serverTransport, transportFactory, protocolFactory);
    server.serve();
    return 0;
}

max_stars_repo_name: addb-swstarlab/YCSB-leveldb

max_issues_repo_name: levyx/mapkeeper

max_forks_repo_name: levyx/mapkeeper


text:
// Boost.Bimap
//
// Copyright (c) 2006-2007 Matias Capeletto
//
// 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)

/// \file relation/mutant_relation.hpp
/// \brief Defines the mutant_relation class

#ifndef BOOST_BIMAP_RELATION_MUTANT_RELATION_HPP
#define BOOST_BIMAP_RELATION_MUTANT_RELATION_HPP

#if defined(_MSC_VER) && (_MSC_VER>=1200)
#pragma once
#endif

#include <boost/config.hpp>

#include <boost/mpl/vector.hpp>
#include <boost/operators.hpp>
#include <boost/call_traits.hpp>

#ifndef BOOST_BIMAP_DISABLE_SERIALIZATION
  #include <boost/serialization/nvp.hpp>
#endif // BOOST_BIMAP_DISABLE_SERIALIZATION

#include <boost/functional/hash/hash.hpp>

#include <boost/mpl/aux_/na.hpp>

// Boost.Bimap
#include <boost/bimap/tags/tagged.hpp>
#include <boost/bimap/tags/support/default_tagged.hpp>
#include <boost/bimap/tags/support/tag_of.hpp>
#include <boost/bimap/tags/support/value_type_of.hpp>

#include <boost/bimap/relation/member_at.hpp>
#include <boost/bimap/relation/detail/mutant.hpp>
#include <boost/bimap/relation/structured_pair.hpp>
#include <boost/bimap/relation/symmetrical_base.hpp>
#include <boost/bimap/relation/support/get.hpp>

namespace boost {
namespace bimaps {
namespace relation {

namespace detail {

// This class is included so structured_pair and mutant_relation share
// exactly the same class layout

template< class LeftType, class RightType, bool force_mutable >
class relation_storage :
    public symmetrical_base<LeftType,RightType,force_mutable>
{
    typedef symmetrical_base<LeftType,RightType,force_mutable> base_;

    typedef relation_storage storage_;

    public:

    typedef relation_storage<LeftType,RightType,false> non_mutable_storage;

    typedef ::boost::mpl::vector2
    <
        relation_storage< LeftType, RightType, true  >,
        relation_storage< LeftType, RightType, false >

    > mutant_views;

    //@{
        /// data
        BOOST_DEDUCED_TYPENAME base_::left_value_type  left;
        BOOST_DEDUCED_TYPENAME base_::right_value_type right;
    //@}

    relation_storage() {}

    relation_storage(BOOST_DEDUCED_TYPENAME ::boost::call_traits<
                         BOOST_DEDUCED_TYPENAME base_::left_value_type
                     >::param_type l,
                     BOOST_DEDUCED_TYPENAME ::boost::call_traits<
                        BOOST_DEDUCED_TYPENAME base_::right_value_type
                     >::param_type r)

        : left(l), right(r) {}

          BOOST_DEDUCED_TYPENAME base_:: left_value_type &  get_left()      { return left;  }
    const BOOST_DEDUCED_TYPENAME base_:: left_value_type &  get_left()const { return left;  }
          BOOST_DEDUCED_TYPENAME base_::right_value_type & get_right()      { return right; }
    const BOOST_DEDUCED_TYPENAME base_::right_value_type & get_right()const { return right; }
};

template< class TA, class TB, class Info, bool force_mutable >
class relation_info_hook : public
 ::boost::bimaps::relation::detail::relation_storage<TA,TB,force_mutable>
{
    typedef ::boost::bimaps::relation::detail::
                relation_storage<TA,TB,force_mutable> base_;

    typedef BOOST_DEDUCED_TYPENAME ::boost::bimaps::tags::support::
        default_tagged<Info,member_at::info>::type tagged_info_type;

    public:
    typedef BOOST_DEDUCED_TYPENAME tagged_info_type::value_type info_type;
    typedef BOOST_DEDUCED_TYPENAME tagged_info_type::tag        info_tag;

    info_type info;

    protected:

    relation_info_hook() {}

    relation_info_hook( BOOST_DEDUCED_TYPENAME ::boost::call_traits<
                           BOOST_DEDUCED_TYPENAME base_::left_value_type
                        >::param_type l,
                        BOOST_DEDUCED_TYPENAME ::boost::call_traits<
                            BOOST_DEDUCED_TYPENAME base_::right_value_type
                        >::param_type r,
                        BOOST_DEDUCED_TYPENAME ::boost::call_traits<
                            info_type
                        >::param_type i = info_type() )

        : base_(l,r), info(i) {}

    template< class Relation >
    relation_info_hook( const Relation & rel ) :
        base_(rel.left,rel.right),
        info(rel.info) {}

    template< class Relation >
    void change_to( const Relation & rel )
    {
        base_::left  = rel.left ;
        base_::right = rel.right;
        info         = rel.info ;
    }

    #ifndef BOOST_BIMAP_DISABLE_SERIALIZATION
    template< class Archive >
    void serialize(Archive & ar, const unsigned int)
    {
        ar & ::boost::serialization::make_nvp("left" , base_::left );
        ar & ::boost::serialization::make_nvp("right", base_::right);
        ar & ::boost::serialization::make_nvp("info" , info        );
    }
    #endif // BOOST_BIMAP_DISABLE_SERIALIZATION
};

template< class TA, class TB, bool force_mutable>
class relation_info_hook<TA,TB,::boost::mpl::na,force_mutable> :
    public ::boost::bimaps::relation::detail::relation_storage<TA,TB,force_mutable>
{
    typedef ::boost::bimaps::relation::detail::
                relation_storage<TA,TB,force_mutable> base_;

    public:
    typedef ::boost::mpl::na info_type;
    typedef member_at::info info_tag;

    protected:

    relation_info_hook() {}

    relation_info_hook( BOOST_DEDUCED_TYPENAME ::boost::call_traits<
                           BOOST_DEDUCED_TYPENAME base_::left_value_type
                        >::param_type l,
                        BOOST_DEDUCED_TYPENAME ::boost::call_traits<
                            BOOST_DEDUCED_TYPENAME base_::right_value_type
                        >::param_type r)

        : base_(l,r) {}

    template< class Relation >
    relation_info_hook( const Relation & rel ) :
        base_(rel.left,rel.right) {}

    template< class Relation >
    void change_to( const Relation & rel )
    {
        base_::left  = rel.left ;
        base_::right = rel.right;
    }

    #ifndef BOOST_BIMAP_DISABLE_SERIALIZATION
    template< class Archive >
    void serialize(Archive & ar, const unsigned int)
    {
        ar & ::boost::serialization::make_nvp("left" , base_::left );
        ar & ::boost::serialization::make_nvp("right", base_::right);
    }
    #endif // BOOST_BIMAP_DISABLE_SERIALIZATION
};

} // namespace detail

/// \brief Abstraction of a related pair of values, that extends the std::pair class.
/**
The mutant_relation is a mutant class. A mutant class can mutate
with zero overhead in other classes that are called views.
Each view has to be StorageCompatible with the base class
of the mutant. Note that all the views have the following
storage structure:

\verbatim
                        __________
                       |          |
                       |    TA    |
                       |__________|
                       |          |
                       |    TB    |
                       |__________|

\endverbatim

See also select_relation, standard_relation.
\ingroup relation_group
                                                           **/

template< class TA, class TB, class Info = ::boost::mpl::na, bool force_mutable = false >
class mutant_relation : public
    ::boost::bimaps::relation::detail::
        relation_info_hook<TA,TB,Info,force_mutable>
{
    typedef ::boost::bimaps::relation::detail::
        relation_info_hook<TA,TB,Info,force_mutable> base_;

    public:

    // We have to know the type of the base where the types are
    // defined because Boost.MultiIndex requires it.

    typedef ::boost::bimaps::relation::detail::
                relation_storage<TA,TB,force_mutable> storage_base;

    /// Above view, non mutable view of the relation

    typedef mutant_relation<TA,TB,Info,false> above_view;

    //@{
        /// A signature compatible std::pair that is a view of the relation.

        typedef structured_pair< TA, TB, Info, normal_layout >  left_pair;
        typedef structured_pair< TB, TA, Info, mirror_layout > right_pair;
    //@}

    typedef ::boost::mpl::vector4
    <
         left_pair,
        right_pair,

        mutant_relation< TA, TB, Info, true  >,
        mutant_relation< TA, TB, Info, false >

    > mutant_views;

    mutant_relation() {}

    mutant_relation(BOOST_DEDUCED_TYPENAME ::boost::call_traits<
                        BOOST_DEDUCED_TYPENAME base_:: left_value_type
                    >::param_type l,
                    BOOST_DEDUCED_TYPENAME ::boost::call_traits<
                        BOOST_DEDUCED_TYPENAME base_::right_value_type
                    >::param_type r) :
        base_(l,r) {}

    mutant_relation(BOOST_DEDUCED_TYPENAME ::boost::call_traits<
                        BOOST_DEDUCED_TYPENAME base_:: left_value_type
                    >::param_type l,
                    BOOST_DEDUCED_TYPENAME ::boost::call_traits<
                        BOOST_DEDUCED_TYPENAME base_::right_value_type
                    >::param_type r,
                    BOOST_DEDUCED_TYPENAME ::boost::call_traits<
                        BOOST_DEDUCED_TYPENAME base_::info_type
                    >::param_type i) :
        base_(l,r,i) {}

    mutant_relation(const mutant_relation<TA,TB,Info,false> & rel) :
        base_(rel) {}

    mutant_relation(const mutant_relation<TA,TB,Info,true> & rel) :
        base_(rel) {}

    // Operators

    template< bool FM >
    mutant_relation& operator=(const mutant_relation<TA,TB,Info,FM> & rel)
    {
        base_::change_to(rel);
        return *this;
    }

    // The following functions are redundant if you only consider this class.
    // They are included to make easier the construction of the get and the
    // pair_by metafunction. Remember that not all compiler supports the mutant
    // idiom.

    left_pair & get_left_pair()
    {
        return ::boost::bimaps::relation::detail::mutate<left_pair>(*this);
    }

    const left_pair & get_left_pair() const
    {
        return ::boost::bimaps::relation::detail::mutate<left_pair>(*this);
    }

    right_pair & get_right_pair()
    {
        return ::boost::bimaps::relation::detail::mutate<right_pair>(*this);
    }

    const right_pair & get_right_pair() const
    {
        return ::boost::bimaps::relation::detail::mutate<right_pair>(*this);
    }

    above_view & get_view()
    {
        return ::boost::bimaps::relation::detail::mutate<above_view>(*this);
    }

    const above_view & get_view() const
    {
        return ::boost::bimaps::relation::detail::mutate<above_view>(*this);
    }

    template< class Tag >
    const BOOST_DEDUCED_TYPENAME ::boost::bimaps::relation::support::
        result_of::get<Tag,const mutant_relation>::type
    get(BOOST_EXPLICIT_TEMPLATE_TYPE(Tag)) const
    {
        return ::boost::bimaps::relation::support::get<Tag>(*this);
    }

    template< class Tag >
    BOOST_DEDUCED_TYPENAME ::boost::bimaps::relation::support::
        result_of::get<Tag,mutant_relation>::type
    get(BOOST_EXPLICIT_TEMPLATE_TYPE(Tag))
    {
        return ::boost::bimaps::relation::support::get<Tag>(*this);
    }

    #ifndef BOOST_BIMAP_DISABLE_SERIALIZATION

    private:
    friend class ::boost::serialization::access;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        base_::serialize(ar,version);
    }

    #endif // BOOST_BIMAP_DISABLE_SERIALIZATION
};

// hash value

template< class FirstType, class SecondType, bool FM >
std::size_t hash_value(const detail::relation_storage<FirstType,SecondType,FM> & r)
{
    std::size_t seed = 0;
    ::boost::hash_combine(seed, r. left );
    ::boost::hash_combine(seed, r.right );

    return seed;
}

// mutant_relation - mutant_relation

template< class FirstType, class SecondType, bool FM1, bool FM2 >
bool operator==(const detail::relation_storage<FirstType,SecondType,FM1> & a,
                const detail::relation_storage<FirstType,SecondType,FM2> & b)
{
    return ( ( a.left  == b.left  ) &&
             ( a.right == b.right ) );
}

template< class FirstType, class SecondType, bool FM1, bool FM2 >
bool operator!=(const detail::relation_storage<FirstType,SecondType,FM1> & a,
                const detail::relation_storage<FirstType,SecondType,FM2> & b)
{
    return ! ( a == b );
}

template< class FirstType, class SecondType, bool FM1, bool FM2 >
bool operator<(const detail::relation_storage<FirstType,SecondType,FM1> & a,
               const detail::relation_storage<FirstType,SecondType,FM2> & b)
{
    return (  ( a.left  <  b.left  ) ||
             (( a.left == b.left ) && ( a.right < b.right )));
}

template< class FirstType, class SecondType, bool FM1, bool FM2 >
bool operator<=(const detail::relation_storage<FirstType,SecondType,FM1> & a,
                const detail::relation_storage<FirstType,SecondType,FM2> & b)
{
    return (  ( a.left  <  b.left  ) ||
             (( a.left == b.left ) && ( a.right <= b.right )));
}

template< class FirstType, class SecondType, bool FM1, bool FM2 >
bool operator>(const detail::relation_storage<FirstType,SecondType,FM1> & a,
               const detail::relation_storage<FirstType,SecondType,FM2> & b)
{
    return ( ( a.left  >  b.left  ) ||
             (( a.left == b.left ) && ( a.right > b.right )));
}

template< class FirstType, class SecondType, bool FM1, bool FM2 >
bool operator>=(const detail::relation_storage<FirstType,SecondType,FM1> & a,
                const detail::relation_storage<FirstType,SecondType,FM2> & b)
{
    return ( ( a.left  >  b.left  ) ||
             (( a.left == b.left ) && ( a.right >= b.right )));
}

namespace detail {

template< class TA, class TB, class Info, bool force_mutable>
mutant_relation<TA,TB,Info,force_mutable>
    copy_with_left_replaced(mutant_relation<TA,TB,Info,force_mutable> const& rel,
        BOOST_DEDUCED_TYPENAME ::boost::call_traits< BOOST_DEDUCED_TYPENAME
            mutant_relation<TA,TB,Info,force_mutable>::left_value_type>
                ::param_type l)
{
    return mutant_relation<TA,TB,Info,force_mutable>(l,rel.right,rel.info);
}

template< class TA, class TB, bool force_mutable>
mutant_relation<TA,TB,::boost::mpl::na,force_mutable>
    copy_with_left_replaced(mutant_relation<TA,TB,::boost::mpl::na,force_mutable> const& rel,
        BOOST_DEDUCED_TYPENAME ::boost::call_traits< BOOST_DEDUCED_TYPENAME
            mutant_relation<TA,TB,::boost::mpl::na,force_mutable>::left_value_type>
                ::param_type l)
{
    return mutant_relation<TA,TB,::boost::mpl::na,force_mutable>(l,rel.right);
}

template< class TA, class TB, class Info, bool force_mutable>
mutant_relation<TA,TB,Info,force_mutable>
    copy_with_right_replaced(mutant_relation<TA,TB,Info,force_mutable> const& rel,
        BOOST_DEDUCED_TYPENAME ::boost::call_traits< BOOST_DEDUCED_TYPENAME
            mutant_relation<TA,TB,Info,force_mutable>::right_value_type>
                ::param_type r)
{
    return mutant_relation<TA,TB,Info,force_mutable>(rel.left,r,rel.info);
}

template< class TA, class TB, bool force_mutable>
mutant_relation<TA,TB,::boost::mpl::na,force_mutable>
    copy_with_right_replaced(mutant_relation<TA,TB,::boost::mpl::na,force_mutable> const& rel,
        BOOST_DEDUCED_TYPENAME ::boost::call_traits< BOOST_DEDUCED_TYPENAME
            mutant_relation<TA,TB,::boost::mpl::na,force_mutable>::right_value_type>
                ::param_type r)
{
    return mutant_relation<TA,TB,::boost::mpl::na,force_mutable>(rel.left,r);
}

} // namespace detail

} // namespace relation
} // namespace bimaps
} // namespace boost

#endif // BOOST_BIMAP_RELATION_MUTANT_RELATION_HPP