text:
/* Boost.MultiIndex test for rank operations.
 *
 * Copyright 2003-2017 Joaquin M Lopez Munoz.
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * See http://www.boost.org/libs/multi_index for library home page.
 */

#include "test_rank_ops.hpp"

#include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */
#include <algorithm>
#include <iterator>
#include <set>
#include <boost/detail/lightweight_test.hpp>
#include "pre_multi_index.hpp"
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/ranked_index.hpp>

using namespace boost::multi_index;

template<
  typename Sequence1,typename Iterator2,typename Sequence2
>
bool same_position(
  std::size_t n1,const Sequence1& s1,Iterator2 it2,const Sequence2& s2)
{
  typedef typename Sequence1::const_iterator const_iterator1;
  typedef typename Sequence2::const_iterator const_iterator2;

  const_iterator1 cit1=s1.begin();
  std::advance(cit1,n1);
  const_iterator2 cit2=it2;
  return std::distance(s1.begin(),cit1)==std::distance(s2.begin(),cit2);
}

struct less_equal_than
{
  less_equal_than(int n_):n(n_){}
  bool operator()(int x)const{return x<=n;}
  int n;
};

struct greater_equal_than
{
  greater_equal_than(int n_):n(n_){}
  bool operator()(int x)const{return x>=n;}
  int n;
};

template<typename Sequence>
static void local_test_rank_ops()
{
  int                data[]={2,2,1,5,6,7,9,10,9,6,9,6,9};
  Sequence           s(data,data+sizeof(data)/sizeof(data[0]));
  std::multiset<int> ss(s.begin(),s.end());

  typedef typename Sequence::iterator iterator;

  iterator it=s.begin();
  for(std::size_t n=0;n<=s.size()+1;++n){
    BOOST_TEST(s.nth(n)==it);
    BOOST_TEST(s.rank(it)==(std::min)(s.size(),n));
    if(it!=s.end())++it;
  }

  std::pair<std::size_t,std::size_t> p1;
  std::pair<iterator,iterator>       p2;

  p1=s.range_rank(unbounded,unbounded);
  p2=s.range(unbounded,unbounded);
  BOOST_TEST(same_position(p1.first,s,p2.first,s));
  BOOST_TEST(same_position(p1.second,s,p2.second,s));

  for(int i=0;i<12;++i){
    std::size_t pos=s.find_rank(i);
    BOOST_TEST((pos==s.size()&&ss.find(i)==ss.end())||(*s.nth(pos)==i));
    BOOST_TEST(same_position(s.lower_bound_rank(i),s,ss.lower_bound(i),ss));
    BOOST_TEST(same_position(s.upper_bound_rank(i),s,ss.upper_bound(i),ss));
    std::pair<std::size_t,std::size_t> posp=s.equal_range_rank(i);
    BOOST_TEST(same_position(posp.first,s,ss.lower_bound(i),ss));
    BOOST_TEST(same_position(posp.second,s,ss.upper_bound(i),ss));

    p1=s.range_rank(greater_equal_than(i),unbounded);
    p2=s.range(greater_equal_than(i),unbounded);
    BOOST_TEST(same_position(p1.first,s,p2.first,s));
    BOOST_TEST(same_position(p1.second,s,p2.second,s));
    p1=s.range_rank(unbounded,less_equal_than(i));
    p2=s.range(unbounded,less_equal_than(i));
    BOOST_TEST(same_position(p1.first,s,p2.first,s));
    BOOST_TEST(same_position(p1.second,s,p2.second,s));

    for(int j=0;j<12;++j){
      p1=s.range_rank(greater_equal_than(i),less_equal_than(j));
      p2=s.range(greater_equal_than(i),less_equal_than(j));
      BOOST_TEST(same_position(p1.first,s,p2.first,s));
      BOOST_TEST(same_position(p1.second,s,p2.second,s));
    }
  }

  Sequence se; /* empty */
  BOOST_TEST(se.nth(0)==se.end());
  BOOST_TEST(se.nth(1)==se.end());
  BOOST_TEST(se.rank(se.end())==0);
  BOOST_TEST(se.find_rank(0)==0);
  BOOST_TEST(se.lower_bound_rank(0)==0);
  BOOST_TEST(se.upper_bound_rank(0)==0);
  p1=se.equal_range_rank(0);
  BOOST_TEST(p1.first==0&&p1.second==0);
  p1=se.range_rank(unbounded,unbounded);
  BOOST_TEST(p1.first==0&&p1.second==0);
  p1=se.range_rank(greater_equal_than(0),unbounded);
  BOOST_TEST(p1.first==0&&p1.second==0);
  p1=se.range_rank(unbounded,less_equal_than(0));
  BOOST_TEST(p1.first==0&&p1.second==0);
  p1=se.range_rank(greater_equal_than(0),less_equal_than(0));
  BOOST_TEST(p1.first==0&&p1.second==0);
}

void test_rank_ops()
{
  typedef multi_index_container<
    int,
    indexed_by<
      ranked_unique<identity<int> >
    >
  > ranked_set;

  local_test_rank_ops<ranked_set>();

  typedef multi_index_container<
    int,
    indexed_by<
      ranked_non_unique<identity<int> >
    >
  > ranked_multiset;

  local_test_rank_ops<ranked_multiset>();

  /* testcase for https://svn.boost.org/trac/boost/ticket/12955 */

  typedef multi_index_container<
    int,
    indexed_by<
      ranked_unique<identity<int> >,
      ranked_non_unique<identity<int> >
    >
  > biranked_set;

  local_test_rank_ops<biranked_set>();
}


text:
//
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_HTTP_SERIALIZER_HPP
#define BOOST_BEAST_HTTP_SERIALIZER_HPP

#include <boost/beast/core/detail/config.hpp>
#include <boost/beast/core/buffers_cat.hpp>
#include <boost/beast/core/buffers_prefix.hpp>
#include <boost/beast/core/buffers_suffix.hpp>
#include <boost/beast/core/string.hpp>
#include <boost/beast/core/type_traits.hpp>
#include <boost/beast/core/detail/variant.hpp>
#include <boost/beast/http/message.hpp>
#include <boost/beast/http/chunk_encode.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/optional.hpp>

namespace boost {
namespace beast {
namespace http {

/** Provides buffer oriented HTTP message serialization functionality.

    An object of this type is used to serialize a complete
    HTTP message into a sequence of octets. To use this class,
    construct an instance with the message to be serialized.
    The implementation will automatically perform chunk encoding
    if the contents of the message indicate that chunk encoding
    is required.

    Chunked output produced by the serializer never contains chunk
    extensions or trailers, and the location of chunk boundaries
    is not specified. If callers require chunk extensions, trailers,
    or control over the exact contents of each chunk they should
    use the serializer to write just the message header, and then
    assume control over serializing the chunked payload by using
    the chunk buffer sequence types @ref chunk_body, @ref chunk_crlf,
    @ref chunk_header, and @ref chunk_last.

    @tparam isRequest `true` if the message is a request.

    @tparam Body The body type of the message.

    @tparam Fields The type of fields in the message.
*/
template<
    bool isRequest,
    class Body,
    class Fields = fields>
class serializer
{
public:
    static_assert(is_body<Body>::value,
        "Body requirements not met");

    static_assert(is_body_writer<Body>::value,
        "BodyWriter requirements not met");

    /** The type of message this serializer uses

        This may be const or non-const depending on the
        implementation of the corresponding @b BodyWriter.
    */
#if BOOST_BEAST_DOXYGEN
    using value_type = implementation_defined;
#else
    using value_type = typename std::conditional<
        (std::is_constructible<typename Body::writer,
            header<isRequest, Fields>&,
            typename Body::value_type&>::value &&
        ! std::is_constructible<typename Body::writer,
            header<isRequest, Fields> const&,
            typename Body::value_type const&>::value) ||
        // Deprecated BodyWriter Concept (v1.66)
        (std::is_constructible<typename Body::writer,
            message<isRequest, Body, Fields>&>::value &&
        ! std::is_constructible<typename Body::writer,
            message<isRequest, Body, Fields> const&>::value),
        message<isRequest, Body, Fields>,
        message<isRequest, Body, Fields> const>::type;
#endif

private:
    enum
    {
        do_construct        =   0,

        do_init             =  10,
        do_header_only      =  20,
        do_header           =  30,
        do_body             =  40,

        do_init_c           =  50,
        do_header_only_c    =  60,
        do_header_c         =  70,
        do_body_c           =  80,
        do_final_c          =  90,
    #ifndef BOOST_BEAST_NO_BIG_VARIANTS
        do_body_final_c     = 100,
        do_all_c            = 110,
    #endif

        do_complete         = 120
    };

    void fwrinit(std::true_type);
    void fwrinit(std::false_type);

    template<std::size_t, class Visit>
    void
    do_visit(error_code& ec, Visit& visit);

    using writer = typename Body::writer;

    using cb1_t = buffers_suffix<typename
        Fields::writer::const_buffers_type>;        // header
    using pcb1_t  = buffers_prefix_view<cb1_t const&>;

    using cb2_t = buffers_suffix<buffers_cat_view<
        typename Fields::writer::const_buffers_type,// header
        typename writer::const_buffers_type>>;      // body
    using pcb2_t = buffers_prefix_view<cb2_t const&>;

    using cb3_t = buffers_suffix<
        typename writer::const_buffers_type>;       // body
    using pcb3_t = buffers_prefix_view<cb3_t const&>;

    using cb4_t = buffers_suffix<buffers_cat_view<
        typename Fields::writer::const_buffers_type,// header
        detail::chunk_size,                         // chunk-size
        boost::asio::const_buffer,               // chunk-ext
        chunk_crlf,                                 // crlf
        typename writer::const_buffers_type,        // body
        chunk_crlf>>;                               // crlf
    using pcb4_t = buffers_prefix_view<cb4_t const&>;

    using cb5_t = buffers_suffix<buffers_cat_view<
        detail::chunk_size,                         // chunk-header
        boost::asio::const_buffer,               // chunk-ext
        chunk_crlf,                                 // crlf
        typename writer::const_buffers_type,        // body
        chunk_crlf>>;                               // crlf
    using pcb5_t = buffers_prefix_view<cb5_t const&>;

    using cb6_t = buffers_suffix<buffers_cat_view<
        detail::chunk_size,                         // chunk-header
        boost::asio::const_buffer,               // chunk-size
        chunk_crlf,                                 // crlf
        typename writer::const_buffers_type,        // body
        chunk_crlf,                                 // crlf
        boost::asio::const_buffer,               // chunk-final
        boost::asio::const_buffer,               // trailers
        chunk_crlf>>;                               // crlf
    using pcb6_t = buffers_prefix_view<cb6_t const&>;

    using cb7_t = buffers_suffix<buffers_cat_view<
        typename Fields::writer::const_buffers_type,// header
        detail::chunk_size,                         // chunk-size
        boost::asio::const_buffer,               // chunk-ext
        chunk_crlf,                                 // crlf
        typename writer::const_buffers_type,        // body
        chunk_crlf,                                 // crlf
        boost::asio::const_buffer,               // chunk-final
        boost::asio::const_buffer,               // trailers
        chunk_crlf>>;                               // crlf
    using pcb7_t = buffers_prefix_view<cb7_t const&>;

    using cb8_t = buffers_suffix<buffers_cat_view<
        boost::asio::const_buffer,               // chunk-final
        boost::asio::const_buffer,               // trailers
        chunk_crlf>>;                               // crlf
    using pcb8_t = buffers_prefix_view<cb8_t const&>;

    value_type& m_;
    writer wr_;
    boost::optional<typename Fields::writer> fwr_;
    beast::detail::variant<
        cb1_t, cb2_t, cb3_t, cb4_t,
        cb5_t ,cb6_t, cb7_t, cb8_t> v_;
    beast::detail::variant<
        pcb1_t, pcb2_t, pcb3_t, pcb4_t,
        pcb5_t ,pcb6_t, pcb7_t, pcb8_t> pv_;
    std::size_t limit_ =
        (std::numeric_limits<std::size_t>::max)();
    int s_ = do_construct;
    bool split_ = false;
    bool header_done_ = false;
    bool more_;

    serializer(value_type& msg, std::true_type);
    serializer(value_type& msg, std::false_type);
public:
    /// Constructor
    serializer(serializer&&) = default;

    /// Constructor
    serializer(serializer const&) = default;

    /// Assignment
    serializer& operator=(serializer const&) = delete;

    /** Constructor

        The implementation guarantees that the message passed on
        construction will not be accessed until the first call to
        @ref next. This allows the message to be lazily created.
        For example, if the header is filled in before serialization.

        @param msg A reference to the message to serialize, which must
        remain valid for the lifetime of the serializer. Depending on
        the type of Body used, this may or may not be a `const` reference.

        @note This function participates in overload resolution only if
        Body::writer is constructible from a `const` message reference.
    */
    explicit
    serializer(value_type& msg);

    /// Returns the message being serialized
    value_type&
    get()
    {
        return m_;
    }

    /// Returns the serialized buffer size limit
    std::size_t
    limit()
    {
        return limit_;
    }

    /** Set the serialized buffer size limit

        This function adjusts the limit on the maximum size of the
        buffers passed to the visitor. The new size limit takes effect
        in the following call to @ref next.

        The default is no buffer size limit.

        @param limit The new buffer size limit. If this number
        is zero, the size limit is removed.
    */
    void
    limit(std::size_t limit)
    {
        limit_ = limit > 0 ? limit :
            (std::numeric_limits<std::size_t>::max)();
    }

    /** Returns `true` if we will pause after writing the complete header.
    */
    bool
    split()
    {
        return split_;
    }

    /** Set whether the header and body are written separately.

        When the split feature is enabled, the implementation will
        write only the octets corresponding to the serialized header
        first. If the header has already been written, this function
        will have no effect on output.
    */
    void
    split(bool v)
    {
        split_ = v;
    }

    /** Return `true` if serialization of the header is complete.

        This function indicates whether or not all buffers containing
        serialized header octets have been retrieved.
    */
    bool
    is_header_done()
    {
        return header_done_;
    }

    /** Return `true` if serialization is complete.

        The operation is complete when all octets corresponding
        to the serialized representation of the message have been
        successfully retrieved.
    */
    bool
    is_done()
    {
        return s_ == do_complete;
    }

    /** Returns the next set of buffers in the serialization.

        This function will attempt to call the `visit` function
        object with a @b ConstBufferSequence of unspecified type
        representing the next set of buffers in the serialization
        of the message represented by this object.

        If there are no more buffers in the serialization, the
        visit function will not be called. In this case, no error
        will be indicated, and the function @ref is_done will
        return `true`.

        @param ec Set to the error, if any occurred.

        @param visit The function to call. The equivalent function
        signature of this object must be:
        @code
            template<class ConstBufferSequence>
            void visit(error_code&, ConstBufferSequence const&);
        @endcode
        The function is not copied, if no error occurs it will be
        invoked before the call to @ref next returns.

    */
    template<class Visit>
    void
    next(error_code& ec, Visit&& visit);

    /** Consume buffer octets in the serialization.

        This function should be called after one or more octets
        contained in the buffers provided in the prior call
        to @ref next have been used.

        After a call to @ref consume, callers should check the
        return value of @ref is_done to determine if the entire
        message has been serialized.

        @param n The number of octets to consume. This number must
        be greater than zero and no greater than the number of
        octets in the buffers provided in the prior call to @ref next.
    */
    void
    consume(std::size_t n);

    /** Provides low-level access to the associated @b BodyWriter (DEPRECATED)

        This function provides access to the instance of the writer
        associated with the body and created by the serializer
        upon construction. The behavior of accessing this object
        is defined by the specification of the particular writer
        and its associated body.

        @return A reference to the writer.
    */
    writer&
    reader_impl()
    {
    #ifndef BOOST_BEAST_ALLOW_DEPRECATED
        BOOST_STATIC_ASSERT_MSG(sizeof(Body) == 0,
            BOOST_BEAST_DEPRECATION_STRING);
    #endif
        return wr_;
    }

    /** Provides low-level access to the associated @b BodyWriter

        This function provides access to the instance of the writer
        associated with the body and created by the serializer
        upon construction. The behavior of accessing this object
        is defined by the specification of the particular writer
        and its associated body.

        @return A reference to the writer.
    */
    writer&
    writer_impl()
    {
        return wr_;
    }
};

/// A serializer for HTTP/1 requests
template<class Body, class Fields = fields>
using request_serializer = serializer<true, Body, Fields>;

/// A serializer for HTTP/1 responses
template<class Body, class Fields = fields>
using response_serializer = serializer<false, Body, Fields>;

} // http
} // beast
} // boost

#include <boost/beast/http/impl/serializer.ipp>

#endif

ext: hpp


text:
// semaphore.hpp, mach semaphores
//
// Copyright (C) 2013 Tim Blechmann
// Copyright (C) 2013 Andrey Semashev
//
// 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_SYNC_DETAIL_SEMAPHORE_SEMAPHORE_MACH_HPP_INCLUDED_
#define BOOST_SYNC_DETAIL_SEMAPHORE_SEMAPHORE_MACH_HPP_INCLUDED_

#include <boost/utility/enable_if.hpp>
#include <boost/sync/detail/config.hpp>
#include <boost/sync/detail/time_traits.hpp>
#include <boost/sync/detail/semaphore/basic_semaphore_mach.hpp>
#include <boost/sync/detail/header.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

namespace boost {

namespace sync  {

BOOST_SYNC_DETAIL_OPEN_ABI_NAMESPACE {

class semaphore
{
    BOOST_DELETED_FUNCTION(semaphore(semaphore const&))
    BOOST_DELETED_FUNCTION(semaphore& operator=(semaphore const&))

public:
    explicit semaphore(unsigned int i = 0) : m_sem(i)
    {
    }

    void post() { m_sem.post(); }
    void wait() { m_sem.wait(); }
    bool try_wait() { return m_sem.try_wait(); }

    template< typename Time >
    typename enable_if_c< sync::detail::time_traits< Time >::is_specialized, bool >::type timed_wait(Time const& t)
    {
        return m_sem.timed_wait(sync::detail::time_traits< Time >::to_sync_unit(t));
    }

    template< typename Duration >
    typename enable_if< detail::is_time_tag_of< Duration, detail::time_duration_tag >, bool >::type wait_for(Duration const& duration)
    {
        return m_sem.timed_wait(sync::detail::time_traits< Duration >::to_sync_unit(duration));
    }

    template< typename TimePoint >
    typename enable_if< detail::is_time_tag_of< TimePoint, detail::time_point_tag >, bool >::type wait_until(TimePoint const& abs_time)
    {
        return m_sem.timed_wait(sync::detail::time_traits< TimePoint >::to_sync_unit(abs_time));
    }

private:
    sync::detail::mach::basic_semaphore m_sem;
};

} // namespace posix

} // namespace sync

} // namespace boost

#include <boost/sync/detail/footer.hpp>

#endif // BOOST_SYNC_DETAIL_SEMAPHORE_SEMAPHORE_MACH_HPP_INCLUDED_

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
/** hoNFFT.cpp */

#include "hoNFFT.h"

#include "hoNDFFT.h"
#include "hoNDArray_elemwise.h"
#include "hoNDArray_reductions.h"
#include "hoNDArray_utils.h"

#include "vector_td_utilities.h"
#include "vector_td_operators.h"
#include "vector_td_io.h"

#include <algorithm>
#include <vector>
#include <cmath>
#include <stdexcept>

#include <boost/range/algorithm/transform.hpp>

#include "GadgetronTimer.h"

#include "NFFT.hpp"
#include "NDArray_utils.h"

#include "hoGriddingConvolution.h"

using namespace std;

namespace Gadgetron {

    namespace {

        template<typename T, unsigned int D>
        struct FFTD {
        };

        template<typename T>
        struct FFTD<T, 1> {
            using REAL = typename realType<T>::Type;

            static void fft(hoNDArray<T> &array, NFFT_fft_mode mode, bool do_scale) {
                if (mode == NFFT_fft_mode::FORWARDS) {
                    hoNDFFT<REAL>::instance()->fft1c(array);
                } else {
                    hoNDFFT<REAL>::instance()->ifft1c(array);
                }
                if (!do_scale) array *= std::sqrt(REAL(array.get_size(0)));
            }
        };

        template<typename T>
        struct FFTD<T, 2> {
            using REAL = typename realType<T>::Type;

            static void fft(hoNDArray<T> &array, NFFT_fft_mode mode, bool do_scale ) {
                if (mode == NFFT_fft_mode::FORWARDS) {
                    hoNDFFT<REAL>::instance()->fft2c(array);
                } else {
                    hoNDFFT<REAL>::instance()->ifft2c(array);
                }

                if (!do_scale) array *= std::sqrt(REAL(array.get_size(0)*array.get_size(1)));

            }
        };

        template<typename T>
        struct FFTD<T, 3> {
            using REAL = typename realType<T>::Type;

            static void fft(hoNDArray<T> &array, NFFT_fft_mode mode, bool do_scale) {
                if (mode == NFFT_fft_mode::FORWARDS) {
                    hoNDFFT<REAL>::instance()->fft3c(array);
                } else {
                    hoNDFFT<REAL>::instance()->ifft3c(array);
                }

                if (!do_scale) array *= std::sqrt(REAL(array.get_size(0)*array.get_size(1)*array.get_size(2)));
            }
        };

        template<class REAL, template<class, unsigned int> class K>
        hoNDArray<std::complex<REAL>> compute_deapodization_filter(
            const vector_td<size_t, 1>& image_dims,
            const ConvolutionKernel<REAL, 1, K>& kernel)
        {
            hoNDArray<std::complex<REAL>> deapodization(to_std_vector(image_dims));
            vector_td<REAL,1> image_dims_real(image_dims);
            for (int x = 0; x < image_dims[0]; x++){
                auto offset = x - image_dims_real[0]/2;
                deapodization(x) = kernel.get(offset, 0);
            }
            return deapodization;
        }

        template<class REAL, template<class, unsigned int> class K>
        hoNDArray<std::complex<REAL>> compute_deapodization_filter(
            const vector_td<size_t, 2>& image_dims,
            const ConvolutionKernel<REAL, 2, K>& kernel)
        {
            hoNDArray<std::complex<REAL>> deapodization(to_std_vector(image_dims));
            vector_td<REAL,2> image_dims_real(image_dims);
            for (int y = 0; y < image_dims[1]; y++) {
                auto offset_y = y - image_dims_real[1]/2;
                auto weight_y = kernel.get(offset_y, 1);

                for (int x = 0; x < image_dims[0]; x++) {
                    auto offset_x = x - image_dims_real[0]/2;
                    auto weight_x = kernel.get(offset_x, 0);

                    deapodization(x,y) = weight_x*weight_y;
                }
            }
            return deapodization;
        }

        template<class REAL, template<class, unsigned int> class K>
        hoNDArray<std::complex<REAL>> compute_deapodization_filter(
            const vector_td<size_t, 3>& image_dims,
            const ConvolutionKernel<REAL, 3, K>& kernel)
        {
            hoNDArray<std::complex<REAL>> deapodization(to_std_vector(image_dims));
            vector_td<REAL,3> image_dims_real(image_dims);
            for (int z = 0; z < image_dims[2]; z++) {
                auto offset_z = z - image_dims_real[2]/2;
                auto weight_z = kernel.get(offset_z, 2);

                for (int y = 0; y < image_dims[1]; y++) {
                    auto offset_y = y - image_dims_real[1]/2;
                    auto weight_y = kernel.get(offset_y, 1);

                    for (int x = 0; x < image_dims[0]; x++) {
                        auto offset_x = x - image_dims_real[0]/2;
                        auto weight_x = kernel.get(offset_x, 0);

                        deapodization(x,y,z) = weight_x*weight_y*weight_z;
                    }
                }
            }
            return deapodization;
        }
    }

    template<class REAL, unsigned int D>
    hoNFFT_plan<REAL, D>::hoNFFT_plan(
        const vector_td<size_t, D> &matrix_size,
        const vector_td<size_t, D> &matrix_size_os,
        REAL W)
      : NFFT_plan<hoNDArray,REAL,D>(matrix_size,matrix_size_os,W)
    {
        this->deapodization_filter_IFFT = compute_deapodization_filter(
            this->matrix_size_os_, this->conv_->get_kernel());
        this->deapodization_filter_FFT = deapodization_filter_IFFT;

        FFTD<std::complex<REAL>,D>::fft(
            deapodization_filter_IFFT, NFFT_fft_mode::BACKWARDS, true);
        FFTD<std::complex<REAL>,D>::fft(
            deapodization_filter_FFT, NFFT_fft_mode::FORWARDS, true);

        boost::transform(deapodization_filter_IFFT,
                         deapodization_filter_IFFT.begin(),
                         [](auto val) { return REAL(1)/val; });
        boost::transform(deapodization_filter_FFT,
                         deapodization_filter_FFT.begin(),
                         [](auto val) { return REAL(1)/val; });
    }

    template<class REAL, unsigned int D>
    hoNFFT_plan<REAL, D>::hoNFFT_plan(
        const vector_td<size_t, D> &matrix_size,
        REAL oversampling_factor,
        REAL W)
      : NFFT_plan<hoNDArray, REAL, D>(matrix_size, oversampling_factor, W)
    {
        this->deapodization_filter_IFFT = compute_deapodization_filter(
            this->matrix_size_os_, this->conv_->get_kernel());
        this->deapodization_filter_FFT = deapodization_filter_IFFT;

        FFTD<std::complex<REAL>, D>::fft(
            deapodization_filter_IFFT, NFFT_fft_mode::BACKWARDS, false);
        FFTD<std::complex<REAL>, D>::fft(
            deapodization_filter_FFT, NFFT_fft_mode::FORWARDS, false);

        boost::transform(deapodization_filter_IFFT,
                         deapodization_filter_IFFT.begin(),
                         [](auto val) { return REAL(1) / val; });
        boost::transform(deapodization_filter_FFT,
                         deapodization_filter_FFT.begin(),
                         [](auto val) { return REAL(1) / val; });
    }

    template<class REAL, unsigned int D>
    void hoNFFT_plan<REAL, D>::compute(
            const hoNDArray<ComplexType> &d,
            hoNDArray<ComplexType> &m,
            const hoNDArray<REAL> *dcw,
            NFFT_comp_mode mode
    ) {
        const auto *pd = reinterpret_cast<const hoNDArray<complext<REAL>> *>(&d);
        auto *pm = reinterpret_cast<hoNDArray<complext<REAL>> *>(&m);

        this->compute(*pd, *pm, dcw, mode);
    }

    template<class REAL, unsigned int D>
    void hoNFFT_plan<REAL, D>::compute(
            const hoNDArray<complext<REAL>> &d,
            hoNDArray<complext<REAL>> &m,
            const hoNDArray<REAL> *dcw,
            NFFT_comp_mode mode
    ) {
       NFFT_plan<hoNDArray,REAL,D>::compute(d,m,dcw,mode);
    }

    template<class REAL, unsigned int D>
    void hoNFFT_plan<REAL, D>::mult_MH_M(
            const hoNDArray<complext<REAL>> &in,
            hoNDArray<complext<REAL>> &out,
            const hoNDArray<REAL>* dcw
    ) {
        const hoNDArray<ComplexType> *pin = reinterpret_cast<const hoNDArray<ComplexType> *>(&in);
        hoNDArray<ComplexType> *pout = reinterpret_cast<hoNDArray<ComplexType> *>(&out);

        this->mult_MH_M(*pin, *pout, dcw);
    }

    template<class REAL, unsigned int D>
    void hoNFFT_plan<REAL, D>::mult_MH_M(
            const hoNDArray<ComplexType> &in,
            hoNDArray<ComplexType> &out,
            const hoNDArray<REAL>* dcw
    ) {
        std::vector<size_t> dims = {this->number_of_samples,this->number_of_frames};
        auto batches = in.get_number_of_elements()/(prod(this->matrix_size_)*this->number_of_frames);
        dims.push_back(batches);

        hoNDArray<ComplexType> tmp(dims);
        compute(in, tmp, dcw, NFFT_comp_mode::FORWARDS_C2NC);
        compute(tmp, out,dcw, NFFT_comp_mode::BACKWARDS_NC2C);
    }

    template<class REAL, unsigned int D>
    void hoNFFT_plan<REAL, D>::fft(
            hoNDArray<ComplexType> &d,
            NFFT_fft_mode mode,
            bool do_scale
    ) {
        FFTD<std::complex<REAL>, D>::fft(d, mode,do_scale);
    }

    template<class REAL, unsigned int D>
    void hoNFFT_plan<REAL, D>::fft(
            hoNDArray<complext<REAL>> &d,
            NFFT_fft_mode mode,
            bool do_scale
    ) {
        hoNDArray<ComplexType> *pd = reinterpret_cast<hoNDArray<ComplexType> *>(&d);
        this->fft(*pd,mode,do_scale);
    }

    template<class REAL, unsigned int D>
    void hoNFFT_plan<REAL, D>::deapodize(
            hoNDArray<ComplexType> &d,
            bool fourierDomain
    ) {
        if (fourierDomain){
            d *= deapodization_filter_FFT;
        } else {
            d *= deapodization_filter_IFFT;
        }
    }

    template<class REAL, unsigned int D>
    void hoNFFT_plan<REAL, D>::deapodize(
            hoNDArray<complext<REAL>> &d,
            bool fourierDomain
    ) {
        hoNDArray<ComplexType> *pd = reinterpret_cast<hoNDArray<ComplexType> *>(&d);
        this->deapodize(*pd,fourierDomain);
    }

    template<class REAL, unsigned int D>
    boost::shared_ptr<hoNFFT_plan<REAL,D>> NFFT<hoNDArray,REAL,D>::make_plan(const Gadgetron::vector_td<size_t, D> &matrix_size,
                                        const Gadgetron::vector_td<size_t, D> &matrix_size_os, REAL W) {
        return boost::make_shared<hoNFFT_plan<REAL,D>>(matrix_size,matrix_size_os,W);
    }

}

template
class Gadgetron::hoNFFT_plan<float, 1>;

template
class Gadgetron::hoNFFT_plan<float, 2>;

template
class Gadgetron::hoNFFT_plan<float, 3>;

template
class Gadgetron::hoNFFT_plan<double, 1>;

template
class Gadgetron::hoNFFT_plan<double, 2>;

template
class Gadgetron::hoNFFT_plan<double, 3>;

template class Gadgetron::NFFT<Gadgetron::hoNDArray,float,1>;
template class Gadgetron::NFFT<Gadgetron::hoNDArray,float,2>;
template class Gadgetron::NFFT<Gadgetron::hoNDArray,float,3>;

template class Gadgetron::NFFT<Gadgetron::hoNDArray,double,1>;
template class Gadgetron::NFFT<Gadgetron::hoNDArray,double,2>;
template class Gadgetron::NFFT<Gadgetron::hoNDArray,double,3>;

ext: cpp

max_stars_repo_name: roopchansinghv/gadgetron


text:
#pragma once

#include <ostream>
#include <memory>

#include <boost/optional.hpp>

namespace libral {
  /*
     A poor man's emulation of Rust's Result construct. The basic idea is
     that we want to avoid throwing exceptions and rather force our callers
     to be explicit about how they handle errors.

     One day we might be able to use std::expected but that's still
     experimental

     We would really like to use boost::variant here, but that runs into
     trouble along the lines of
     https://svn.boost.org/trac/boost/ticket/7120 so we do it the
     old-fashioned way with a lot more boilerplate code
  */

  // The basic error we use everywhere
  struct error {
    error(const std::string &det) : detail(det) {};
    std::string detail;
  };

  // Indication that something is not implemented
  struct not_implemented_error : public error {
    not_implemented_error() : error("not implemented") { }
  };

  /**
   * Immediately return if res is an error
   */
#define err_ret(res)                                         \
  do {                                                       \
    decltype(res) _x = (res);                                \
    if (_x.is_err()) return _x.err();                        \
  } while(0)

  /* A result is either an error or whatever we really wanted */
  template <class R>
  class result {
  private:
    enum class tag { err, ok };
  public:
    result() : result(R()) {};
    result(R& ok) : _tag(tag::ok), _ok(ok) {};
    result(const R& ok) : _tag(tag::ok), _ok(ok) {};
    result(R&& ok) : _tag(tag::ok), _ok(std::move(ok)) {};
    result(error& err) : _tag(tag::err), _err(err) {};
    result(const error& err) : _tag(tag::err), _err(err) {};
    result(error&& err) : _tag(tag::err), _err(std::move(err)) {};

    result(const result& other) { init(other); }
    result(result&& other) { init(std::move(other)); }

    result& operator=(const result& other) {
      assign(other);
      return *this;
    }

    result& operator=(result&& other) {
      assign(other);
      return *this;
    }

    result& operator=(const error& err) {
      assign(err);
      return *this;
    }

    ~result() {
      if (is_ok()) {
        _ok.~R();
      } else {
        _err.~error();
      }
    }

    /**
     * Returns true if the result is ok
     */
    operator bool() const {
      return _tag == tag::ok;
    }

    /**
     * Returns the ok value.
     *
     * @throws std::logic_error if the result is an error and not ok
     */
    R& ok() {
      if (is_ok()) {
        return this->_ok;
      } else {
        std::string msg = "attempt to get ok value from err: ";
        msg += _err.detail;
        throw std::logic_error(msg);
      }
    };

    /**
     * Returns the ok value.
     *
     * @throws std::logic_error if the result is an error and not ok
     */
    const R& ok() const {
      if (is_ok()) {
        return this->_ok;
      } else {
        std::string msg = "attempt to get ok value from err: ";
        msg += _err.detail;
        throw std::logic_error(msg);
      }
    };

    /**
     * Returns the err value.
     *
     * @throws std::logic_error if the result is ok and not an error
     */
    error& err() {
      if (is_err()) {
        return this->_err;
      } else {
        throw std::logic_error("tried to get error from ok result");
      }
    };

    /**
     * Returns the err value.
     *
     * @throws std::logic_error if the result is ok and not an error
     */
    const error& err() const {
      if (is_err()) {
        return this->_err;
      } else {
        throw std::logic_error("tried to get error from ok result");
      }
    };

    /**
     * Returns true if the result is ok
     */
    bool is_ok()  const { return _tag == tag::ok; }

    /**
     * Returns true if the result is an error
     */
    bool is_err() const { return _tag == tag::err; }

    /**
     * Returns true if the result is an error
     */
    bool operator!() const noexcept { return is_err(); }

    /**
     * Returns the ok value.
     *
     * @throws std::logic_error if the result is an error and not ok
     */
    R& operator*() { return ok(); }

    /**
     * Returns the const ok value.
     *
     * @throws std::logic_error if the result is an error and not ok
     */
    const R& operator*() const { return ok(); }

    /**
     * Returns a pointer to the ok value.
     *
     * @throws std::logic_error if the result is an error and not ok
     */
    R* operator->() { return &ok(); }

    /**
     * Returns a const pointer to the ok value.
     *
     * @throws std::logic_error if the result is an error and not ok
     */
    const R* operator->() const { return &ok(); }

    static std::unique_ptr<result<R>> make_unique() {
      return std::unique_ptr<result<R>>(new result<R>(R()));
    };

    static std::unique_ptr<result<R>> make_unique(const error& e) {
      return std::unique_ptr<result<R>>(new result<R>(e));
    };
  private:

    /* Assign by copy */
    void assign(const error& err) {
      if (_tag == tag::ok) {
        _ok.~R();
        new (&_err) error(err);
      } else {
        _err = err;
      }
      _tag = tag::err;
    }

    void assign(const R& ok) {
      if (_tag == tag::ok) {
        _ok = ok;
      } else {
        _err.~error();
        new (&_ok) R(ok);
      }
      _tag = tag::ok;
    }

    void assign(const result& other) {
      if (other._tag == tag::ok) {
        assign(other._ok);
      } else {
        assign(other._err);
      }
    }

    void init(const result& other) {
      _tag = other._tag;
      if (_tag == tag::ok) {
        new (&_ok) R(other._ok);
      } else {
        new (&_err) error(other._err);
      }
    }

    /* Assign by move */
    void assign(error&& err) {
      if (_tag == tag::ok) {
        _ok.~R();
        new (&_err) error(std::move(err));
      } else {
        _err = std::move(err);
      }
      _tag = tag::err;
    }

    void assign(R&& ok) {
      if (_tag == tag::ok) {
        _ok = std::move(ok);
      } else {
        _err.~error();
        new (&_ok) R(std::move(ok));
      }
      _tag = tag::ok;
    }

    void assign(result&& other) {
      if (other._tag == tag::ok) {
        assign(std::move(other._ok));
      } else {
        assign(std::move(other._err));
      }
    }

    void init(result&& other) {
      _tag = other._tag;
      if (_tag == tag::ok) {
        new (&_ok) R(std::move(other._ok));
      } else {
        new (&_err) error(std::move(other._err));
      }
    }

    tag _tag;
    union {
      error _err;
      R     _ok;
    };
  };

  template<typename T>
  std::ostream& operator<<(std::ostream& os, result<T> const& res) {
    if (res.is_ok()) {
      os << "tag:ok";
    } else if (res.is_err()) {
      os << "tag:err " << (*res.err()).detail;
    } else {
      os << "tag:???";
    }
    return os;
  }

  /* Specialication for void */
  template <>
  class result<void> {
  public:
    result() : _err(boost::none) {};
    result(error& err) : _err(err) {};
    result(const error& err) : _err(err) {};
    result(error&& err) : _err(std::move(err)) {};

    /**
     * Returns true if the result is ok
     */
    operator bool() const { return (bool) _err; }

    /**
     * Returns the err value.
     *
     * @throws std::logic_error if the result is ok and not an error
     */
    error& err() {
      if (is_err()) {
        return *_err;
      } else {
        throw std::logic_error("tried to get error from ok result");
      }
    };

    /**
     * Returns the err value.
     *
     * @throws std::logic_error if the result is ok and not an error
     */
    const error& err() const {
      if (is_err()) {
        return *_err;
      } else {
        throw std::logic_error("tried to get error from ok result");
      }
    };

    /**
     * Returns true if the result is ok
     */
    bool is_ok()  const { return ! _err; }

    /**
     * Returns true if the result is an error
     */
    bool is_err() const { return (bool) _err; }

    /**
     * Returns true if the result is an error
     */
    bool operator!() const noexcept { return is_err(); }

  private:
    boost::optional<error> _err;
  };
}

max_stars_repo_name: puppetlabs/libral

max_issues_repo_name: puppetlabs-toy-chest/libral

max_forks_repo_name: puppetlabs-toy-chest/libral


text:
#ifndef NETLIST_PATHS_PATH_HPP
#define NETLIST_PATHS_PATH_HPP

#include <vector>
#include <boost/log/trivial.hpp>
#include "netlist_paths/InternalGraph.hpp"
#include "netlist_paths/Options.hpp"

namespace netlist_paths {

/// A class to represent a path through the netlist graph.
class Path {

  std::vector<const Vertex*> vertices;

public:
  /// Construct an empty path.
  Path() {};

  /// Constrct a Path from a list of Vertices.
  ///
  /// \param sourceVertices A vector of vertices to copy.
  Path(const std::vector<const Vertex*> sourceVertices) {
    vertices.assign(sourceVertices.begin(), sourceVertices.end());
  }

  /// Copy constructor.
  ///
  /// \param path The Path to copy.
  Path(const Path &path) {
    vertices.assign(path.getVertices().begin(), path.getVertices().end());
  }

  /// Test equality with another path.
  ///
  /// \param other The Path to test against.
  ///
  /// \returns A Boolean indicating equal or not.
  bool operator==(const Path& other) const {
    return vertices == other.getVertices();
  }

  /// Return true if the vertex is contained in this path.
  ///
  /// \param vertex The Vertex to test.
  ///
  /// \returns A Boolean indicating whether vertex is contained in this path.
  bool contains(const Vertex *vertex) const {
    return std::find_if(vertices.begin(), vertices.end(),
                        [=](const Vertex *v) { return v->getID() == vertex->getID(); })
              != vertices.end();
  }

  /// Reverse the order of vertices in this path.
  void reverse() {
    std::reverse(std::begin(vertices), std::end(vertices));
  }

  /// Append a vertex to the end of this path.
  ///
  /// \param vertex The Vertex to append to this path.
  void appendVertex(const Vertex *vertex) { vertices.push_back(vertex); }

  /// Append a path to the end of this path.
  ///
  /// \param path The Path to append to this path.
  void appendPath(const Path &path) {
    vertices.insert(vertices.end(), path.getVertices().begin(), path.getVertices().end()-1);
  }

  // Various getters and setters.
  const std::vector<const Vertex*> &getVertices() const { return vertices; }
  const Vertex *getVertex(size_t index) const { return vertices[index]; }
  const Vertex *getStartVertex() const { return vertices.front(); }
  const Vertex *getFinishVertex() const { return vertices.back(); }
  size_t length() const { return vertices.size(); }
  bool empty() const { return vertices.empty(); }

  // Methods compatible with the boost::python wrappers by removing const from the Vertex* type.

  std::vector<Vertex*> getVerticesNoConst() const {
    std::vector<Vertex*> newVec;
    for (auto* vertex : vertices) {
      newVec.push_back(const_cast<Vertex*>(vertex));
    }
    return newVec;
  }
  Vertex *getVertexNoConst(size_t index) const { return const_cast<Vertex*>(vertices[index]); }
  Vertex *getStartVertexNoConst() const { return const_cast<Vertex*>(vertices.front()); }
  Vertex *getFinishVertexNoConst() const { return const_cast<Vertex*>(vertices.back()); }
};

} // End namespace.

#endif // NETLIST_PATHS_PATH_HPP

max_stars_repo_name: heiner-bauer/netlist-paths

max_issues_repo_name: heiner-bauer/netlist-paths

max_forks_repo_name: heiner-bauer/netlist-paths


text:
#pragma once
#include "config.h"
#include "../shared/protobuf/cpp/ResocaMessage.pb.h"
#include <boost/log/trivial.hpp>
#include <boost/asio.hpp>
#include <functional>

#include "CanDeviceManager.hpp"

#define PROTOBUF_MAX_DATA_LEN 1024
#define MAX_N_UNSENT 128

class TCPServer;
class CanDeviceManager;

class TCPSession {
public:
    TCPSession(uint32_t sid, boost::asio::ip::tcp::socket socket, TCPServer &server):
        sid(sid), socket(std::move(socket)), server(server) {}

    void start();

    void writeRSM(ResocaMessage &msg);

    bool handlePBMessage(ResocaMessage &rms);

    std::set<std::string> ifNotify;

    void kill();

private:
    uint32_t sid;
    boost::asio::ip::tcp::socket socket;
    TCPServer &server;

    int nUnsentRSM = 0;

    uint16_t lengthData[1];
    uint8_t data[PROTOBUF_MAX_DATA_LEN];

};

class TCPServer {
public:
    TCPServer(std::string interface, int portNumber, boost::asio::io_context &ioContext)
        : interface(interface), portNumber(portNumber),
            acceptor(ioContext,
            boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), portNumber)) {}
    //boost::asio::ip::address::from_string(interface)

    void listen();

    bool sendPBMessage(ResocaMessage &rms);

    void deleteSession(int sid);

    std::vector<std::string> getIfList();

    void setCDM(CanDeviceManager *cdm) {
        this->cdm = cdm;
    }

    bool handleCanEvent(CanEvent &ce);

private:

    CanDeviceManager *cdm;

    // next session id to be assigned.
    uint32_t nextSid = 1;
    std::map<uint32_t,TCPSession*> sessions;

    std::string interface;
    int portNumber;

    boost::asio::ip::tcp::acceptor acceptor;
};

max_stars_repo_name: x-zvf/resoca

max_issues_repo_name: x-zvf/resoca

max_forks_repo_name: x-zvf/resoca


text:
//
//  Copyright (C) 2009-2012 Artyom Beilis (Tonkikh)
//
//  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 <booster/thread.h>
#include "test.h"

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <errno.h>

int dowrite(int fd)
{
	char c='A';
	int r;
	while((r=::write(fd,&c,1))==-1 && errno==EINTR)
		;
	return r;
}

int doread(int fd)
{
	char c;
	int r;
	while((r=::read(fd,&c,1))==-1 && errno==EINTR)
		;
	return r;
}

int main()
{
	booster::fork_shared_mutex mutex_;
	int fd[2];
	int res =  pipe(fd);
	(void)(res);
	int pid = fork();
	try {
		if(pid!=0) { // parent

			std::cout << "Test try_lock" << std::endl;
			close(fd[0]);
			usleep(100000);
			dowrite(fd[1]);
			usleep(100000);
			TEST(!mutex_.try_lock());
			dowrite(fd[1]);
			usleep(100000);
			TEST(mutex_.try_lock());
			mutex_.unlock();
			std::cout << "Test shared/unique" << std::endl;
			mutex_.shared_lock();
			dowrite(fd[1]);
			usleep(100000);
			close(fd[1]);
			mutex_.unlock();
			std::cout << "Test unlock on exit" << std::endl;
			usleep(100000);
			TEST(!mutex_.try_lock());
			usleep(500000);
			TEST(mutex_.try_lock());
		}
		else { // child
			close(fd[1]);
			TEST(doread(fd[0])==1);
			TEST(mutex_.try_lock());
			TEST(doread(fd[0])==1);
			mutex_.unlock();
			// test 2
			TEST(doread(fd[0])==1);
			TEST(mutex_.try_shared_lock());
			mutex_.unlock();
			TEST(!mutex_.try_unique_lock());
			mutex_.unique_lock();
			TEST(doread(fd[0])==0);
			usleep(200000);
			return 0;
		}
	}
	catch(std::exception const &e) {
		std::cerr << e.what() << std::endl;
		if(pid!=0) {
			int res;
			::wait(&res);
		}
		return 1;
	}
	if(pid!=0) {
		int res;
		::wait(&res);
		if(WIFEXITED(res) && WEXITSTATUS(res)==0) {
			std::cerr << "Ok" <<std::endl;
			return 0;
		}
		return 1;
	}
	return 0;
}

max_stars_repo_name: gatehouse/cppcms

max_issues_repo_name: gatehouse/cppcms

max_forks_repo_name: gatehouse/cppcms


text:
//
// Copyright 2019-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
//
#if defined(BOOST_CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wconversion"
#pragma clang diagnostic ignored "-Wfloat-equal"
#pragma clang diagnostic ignored "-Wsign-conversion"
#elif BOOST_GCC >= 40700
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion"
#pragma GCC diagnostic ignored "-Wfloat-equal"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#endif

#include <boost/gil/channel.hpp>

#include <boost/core/lightweight_test.hpp>

#include <limits>
#include <ostream>

#include "test_fixture.hpp"
#include "test_utility_output_stream.hpp"

namespace gil = boost::gil;
namespace fixture = boost::gil::test::fixture;

struct test_pixel_value_default_constructor {
  template <typename Pixel> void operator()(Pixel const &) {
    using pixel_t = Pixel;
    fixture::pixel_value<pixel_t> fix;
    pixel_t const default_value{};
    BOOST_TEST_EQ(fix.pixel_, default_value);
  }
  static void run() {
    boost::mp11::mp_for_each<fixture::pixel_types>(
        test_pixel_value_default_constructor{});
  }
};

struct test_pixel_value_parameterized_constructor {
  template <typename Pixel> void operator()(Pixel const &) {
    using pixel_t = Pixel;
    using channel_t = typename gil::channel_type<pixel_t>::type;
    // Sample channel value, simplified, could be min, max, random
    channel_t const sample_channel = 2;
    pixel_t sample_pixel;
    gil::static_fill(sample_pixel, sample_channel);
    fixture::pixel_value<pixel_t> fix{sample_pixel};
    BOOST_TEST_EQ(fix.pixel_, sample_pixel);
  }
  static void run() {
    boost::mp11::mp_for_each<fixture::pixel_types>(
        test_pixel_value_parameterized_constructor{});
  }
};

struct test_pixel_reference_default_constructor {
  template <typename Pixel> void operator()(Pixel const &) {
    using pixel_t = Pixel;
    fixture::pixel_reference<pixel_t &> fix;
    pixel_t pix_default{};
    BOOST_TEST_EQ(fix.pixel_, pix_default);
  }
  static void run() {
    boost::mp11::mp_for_each<fixture::pixel_types>(
        test_pixel_reference_default_constructor{});
  }
};

struct test_pixel_reference_parameterized_constructor {
  template <typename Pixel> void operator()(Pixel const &) {
    using pixel_t = Pixel;
    using channel_t = typename gil::channel_type<pixel_t>::type;
    // Sample channel value, simplified, could be min, max, random
    channel_t const sample_channel = 3;
    pixel_t sample_pixel;
    gil::static_fill(sample_pixel, sample_channel);
    fixture::pixel_reference<pixel_t &> fix{sample_pixel};
    BOOST_TEST_EQ(fix.pixel_, sample_pixel);
  }
  static void run() {
    boost::mp11::mp_for_each<fixture::pixel_types>(
        test_pixel_reference_parameterized_constructor{});
  }
};

int main() {
  test_pixel_value_default_constructor::run();
  test_pixel_value_parameterized_constructor::run();
  test_pixel_reference_default_constructor::run();
  test_pixel_reference_parameterized_constructor::run();

  return boost::report_errors();
}

max_stars_repo_name: sdebionne/gil-reformated

max_issues_repo_name: sdebionne/gil-reformated

max_forks_repo_name: sdebionne/gil-reformated


text:
/*
Author: Gudakov Ramil Sergeevich a.k.a. Gauss
Гудаков Рамиль Сергеевич
Contacts: [ramil2085@mail.ru, ramil2085@gmail.com]
See for more information LICENSE.md.
*/

#include "EntitySplitter.h"

#include <boost/wave/token_ids.hpp>

using namespace nsCppParser;
using namespace boost::wave;

void TEntitySplitter::Work(const std::list<TTokenInfo>& tokenList, TBlockTokenEntity* root)
{
    mCurrentBlock = root;
    for ( auto tokenInfo : tokenList ) {
        HandleToken(tokenInfo);
    }
}
//---------------------------------------------------------------------------------------------
void TEntitySplitter::HandleToken(const TTokenInfo& tokenInfo)
{
    switch ( tokenInfo.id )
    {
        case T_LEFTBRACE:
        {
            AddLineToCurrentBlock();

            std::shared_ptr<TBlockTokenEntity> newBlock;
            newBlock.reset(new TBlockTokenEntity());
            mCurrentBlock->mTokens.push_back(newBlock);
            newBlock->mParentBlock = mCurrentBlock;

            mCurrentBlock = newBlock.get();
            break;
        }
        case T_RIGHTBRACE:
            AddLineToCurrentBlock();

            mCurrentBlock = mCurrentBlock->mParentBlock;
            break;
        case T_SEMICOLON:
            mLineToken.mTokens.push_back(tokenInfo);

            AddLineToCurrentBlock();
            break;
        default:
            mLineToken.mTokens.push_back(tokenInfo);
    }
}
//---------------------------------------------------------------------------------------------
void TEntitySplitter::AddLineToCurrentBlock()
{
    std::shared_ptr<TLineTokenEntity> newLine;

    newLine.reset(new TLineTokenEntity());
    *newLine = mLineToken;
    mCurrentBlock->mTokens.push_back(newLine);
    mLineToken.mTokens.clear();
}
//---------------------------------------------------------------------------------------------

max_stars_repo_name: RamilGauss/MMO-Framework

max_issues_repo_name: RamilGauss/MMO-Framework

max_forks_repo_name: RamilGauss/MMO-Framework


text:
//
// Copyright (c) 2015-2018 CNRS
//

#include "pinocchio/bindings/python/algorithm/algorithms.hpp"
#include "pinocchio/algorithm/center-of-mass.hpp"

#include <boost/python/overloads.hpp>

namespace pinocchio
{
  namespace python
  {

    BOOST_PYTHON_FUNCTION_OVERLOADS(jacobianCenterOfMassUpdate_overload,jacobianCenterOfMass,3,4)

    BOOST_PYTHON_FUNCTION_OVERLOADS(jacobianCenterOfMassNoUpdate_overload,jacobianCenterOfMass,2,3)

    static SE3::Vector3
    com_0_proxy(const Model& model,
                Data & data,
                const Eigen::VectorXd & q,
                bool computeSubtreeComs = true)
    {
      return centerOfMass(model,data,q,computeSubtreeComs);
    }

    static SE3::Vector3
    com_1_proxy(const Model& model,
                Data & data,
                const Eigen::VectorXd & q,
                const Eigen::VectorXd & v,
                bool computeSubtreeComs = true)
    {
      return centerOfMass(model,data,q,v,computeSubtreeComs);
    }

    static SE3::Vector3
    com_2_proxy(const Model & model,
                Data & data,
                const Eigen::VectorXd & q,
                const Eigen::VectorXd & v,
                const Eigen::VectorXd & a,
                bool computeSubtreeComs = true)
    {
      return centerOfMass(model,data,q,v,a,computeSubtreeComs);
    }

    static void
    com_level_proxy(const Model & model,
                    Data & data,
                    int LEVEL,
                    bool computeSubtreeComs = true)
    {
      centerOfMass(model,data,LEVEL,computeSubtreeComs);
    }

    static void
    com_default_proxy(const Model & model,
                Data & data,
                bool computeSubtreeComs = true)
    {
      centerOfMass(model,data,computeSubtreeComs);
    }

    static Data::Matrix3x
    jacobian_subtree_com_kinematics_proxy(const Model & model,
                                          Data & data,
                                          const Eigen::VectorXd & q,
                                          Model::JointIndex jointId)
    {
      Data::Matrix3x J(3,model.nv); J.setZero();
      jacobianSubtreeCenterOfMass(model, data, q, jointId, J);

      return J;
    }

    static Data::Matrix3x
    jacobian_subtree_com_proxy(const Model & model,
                               Data & data,
                               Model::JointIndex jointId)
    {
      Data::Matrix3x J(3,model.nv); J.setZero();
      jacobianSubtreeCenterOfMass(model, data, jointId, J);

      return J;
    }

    static Data::Matrix3x
    get_jacobian_subtree_com_proxy(const Model & model,
                                   Data & data,
                                   Model::JointIndex jointId)
    {
      Data::Matrix3x J(3,model.nv); J.setZero();
      getJacobianSubtreeCenterOfMass(model, data, jointId, J);

      return J;
    }

    BOOST_PYTHON_FUNCTION_OVERLOADS(com_0_overload, com_0_proxy, 3, 4)

    BOOST_PYTHON_FUNCTION_OVERLOADS(com_1_overload, com_1_proxy, 4, 5)

    BOOST_PYTHON_FUNCTION_OVERLOADS(com_2_overload, com_2_proxy, 5, 6)

    BOOST_PYTHON_FUNCTION_OVERLOADS(com_level_overload, com_level_proxy, 3, 4)

    BOOST_PYTHON_FUNCTION_OVERLOADS(com_default_overload, com_default_proxy, 2, 3)

    void exposeCOM()
    {
      using namespace Eigen;

      bp::def("computeTotalMass",
              (double (*)(const Model &))&computeTotalMass<double,0,JointCollectionDefaultTpl>,
              bp::args("Model"),
              "Compute the total mass of the model and return it.");

      bp::def("computeTotalMass",
              (double (*)(const Model &, Data &))&computeTotalMass<double,0,JointCollectionDefaultTpl>,
              bp::args("Model", "Data"),
              "Compute the total mass of the model, put it in data.mass[0] and return it.");

      bp::def("computeSubtreeMasses",
              (void (*)(const Model &, Data &))&computeSubtreeMasses<double,0,JointCollectionDefaultTpl>,
              bp::args("Model", "Data"),
              "Compute the mass of each kinematic subtree and store it in data.mass.");

      bp::def("centerOfMass",
              com_0_proxy,
              com_0_overload(
                  bp::args("Model","Data",
                           "Joint configuration q (size Model::nq)",
                           "computeSubtreeComs If true, the algorithm computes also the center of mass of the subtrees"
                  ),
                  "Compute the center of mass, putting the result in Data and return it."
              )[bp::return_value_policy<bp::return_by_value>()]
      );

      bp::def("centerOfMass",
              com_1_proxy,
              com_1_overload(
                  bp::args("Model","Data",
                           "Joint configuration q (size Model::nq)",
                           "Joint velocity v (size Model::nv)",
                           "computeSubtreeComs If true, the algorithm computes also the center of mass of the subtrees"
                  ),
                  "Computes the center of mass position and velocity by storing the result in Data."
              )[bp::return_value_policy<bp::return_by_value>()]
      );

      bp::def("centerOfMass",
              com_2_proxy,
              com_2_overload(
                  bp::args("Model","Data",
                           "Joint configuration q (size Model::nq)",
                           "Joint velocity v (size Model::nv)",
                           "Joint acceleration a (size Model::nv)",
                           "computeSubtreeComs If true, the algorithm computes also the center of mass of the subtrees"
                  ),
                  "Computes the center of mass position, velocity and acceleration by storing the result in Data."
              )[bp::return_value_policy<bp::return_by_value>()]
      );

      bp::def("centerOfMass",
              com_level_proxy,
              com_level_overload(
                  bp::args("Model","Data",
                           "level if = 0, computes CoM position, if = 1, also computes CoM velocity and if = 2, also computes CoM acceleration",
                           "computeSubtreeComs If true, the algorithm computes also the center of mass of the subtrees"
                  ),
                  "Computes the center of mass position, velocity and acceleration of a given model according to the current kinematic values contained in data and the requested level."
              )[bp::return_value_policy<bp::return_by_value>()]
      );

      bp::def("centerOfMass",
              com_default_proxy,
              com_default_overload(
                  bp::args("Model","Data",
                           "computeSubtreeComs If true, the algorithm computes also the center of mass of the subtrees"
                  ),
                  "Computes the center of mass position, velocity and acceleration of a given model according to the current kinematic values contained in data."
              )[bp::return_value_policy<bp::return_by_value>()]
      );

      bp::def("jacobianCenterOfMass",
              (const Data::Matrix3x & (*)(const Model &, Data &, const Eigen::MatrixBase<Eigen::VectorXd> &, bool))&jacobianCenterOfMass<double,0,JointCollectionDefaultTpl,VectorXd>,
              jacobianCenterOfMassUpdate_overload(bp::args("Model","Data",
                       "Joint configuration q (size Model::nq)",
                       "computeSubtreeComs If true, the algorithm computes also the center of mass of the subtrees"),
              "Computes the jacobian of the center of mass, puts the result in Data and return it.")[
              bp::return_value_policy<bp::return_by_value>()]);

      bp::def("jacobianCenterOfMass",
              (const Data::Matrix3x & (*)(const Model &, Data &, bool))&jacobianCenterOfMass<double,0,JointCollectionDefaultTpl>,
              jacobianCenterOfMassNoUpdate_overload(bp::args("Model","Data",
                       "computeSubtreeComs If true, the algorithm computes also the center of mass of the subtrees"),
              "Computes the jacobian of the center of mass, puts the result in Data and return it.")[
              bp::return_value_policy<bp::return_by_value>()]);

      bp::def("jacobianSubtreeCoMJacobian",jacobian_subtree_com_kinematics_proxy,
              bp::args("Model, the model of the kinematic tree",
                       "Data, the data associated to the model where the results are stored",
                       "Joint configuration q (size Model::nq)",
                       "Subtree root ID, the index of the subtree root joint."),
              "Computes the Jacobian of the CoM of the given subtree expressed in the world frame, according to the given joint configuration.");

      bp::def("jacobianSubtreeCoMJacobian",jacobian_subtree_com_proxy,
              bp::args("Model, the model of the kinematic tree",
                       "Data, the data associated to the model where the results are stored",
                       "Subtree root ID, the index of the subtree root joint."),
              "Computes the Jacobian of the CoM of the given subtree expressed in the world frame, according to the given entries in data.");

      bp::def("getJacobianSubtreeCenterOfMass",get_jacobian_subtree_com_proxy,
              bp::args("Model, the model of the kinematic tree",
                       "Data, the data associated to the model where the results are stored",
                       "Subtree root ID, the index of the subtree root joint."),
              "Get the Jacobian of the CoM of the given subtree expressed in the world frame, according to the given entries in data. It assumes that jacobianCenterOfMass has been called first.");

    }

  } // namespace python
} // namespace pinocchio

max_stars_repo_name: ikalevatykh/pinocchio

max_issues_repo_name: ikalevatykh/pinocchio

max_forks_repo_name: ikalevatykh/pinocchio


text:
// Copyright (C) 2011-2012 by the BEM++ Authors
//
// 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 "bempp/common/config_trilinos.hpp"

#ifdef WITH_TRILINOS

#include "belos_solver_wrapper.hpp"

#include "real_wrapper_of_complex_thyra_linear_operator.hpp"
#include "real_wrapper_of_complex_thyra_preconditioner.hpp"
#include "../fiber/explicit_instantiation.hpp"

#include <Teuchos_ArrayRCP.hpp>
#include <Thyra_BelosLinearOpWithSolveFactory_decl.hpp>
#include <Thyra_DefaultLinearOpSource.hpp>
#include <Thyra_DetachedMultiVectorView.hpp>
#include <Thyra_LinearOpSourceBase.hpp>
#include <Thyra_LinearOpWithSolveFactoryHelpers.hpp>
#include <Thyra_SolveSupportTypes.hpp>
#include <Thyra_OperatorVectorTypes.hpp>
#include <Thyra_PreconditionerBase.hpp>

#include <boost/type_traits/is_same.hpp>
#include <boost/utility/enable_if.hpp>

namespace Bempp
{

// Overloaded template helper functions
namespace
{

// Real ValueType
template <typename ValueType>
typename boost::enable_if<
boost::is_same<ValueType, typename ScalarTraits<ValueType>::RealType>,
Teuchos::RCP<Thyra::LinearOpWithSolveBase<typename ScalarTraits<ValueType>::RealType> >
>::type
makeOperatorWithSolve(
        const Teuchos::RCP<Teuchos::ParameterList>& paramList,
        const Teuchos::RCP<const Thyra::LinearOpBase<ValueType> >& linOp,
        const Teuchos::RCP<const Thyra::PreconditionerBase<ValueType> >& preconditioner)
{
    Teuchos::RCP<Teuchos::FancyOStream> out =
            Teuchos::VerboseObjectBase::getDefaultOStream();

    Thyra::BelosLinearOpWithSolveFactory<ValueType> invertibleOpFactory;
    invertibleOpFactory.setParameterList(paramList);
    invertibleOpFactory.setOStream(out);
    invertibleOpFactory.setVerbLevel(Teuchos::VERB_DEFAULT);

    Teuchos::RCP<Thyra::LinearOpWithSolveBase<ValueType> > result;
    if (preconditioner.is_null())
        // No preconditioner
        result = Thyra::linearOpWithSolve(invertibleOpFactory, linOp);
    else {
        // Preconditioner defined
        result = invertibleOpFactory.createOp();
        Teuchos::RCP<const Thyra::LinearOpSourceBase<ValueType> > linOpSourcePtr(
                    new Thyra::DefaultLinearOpSource<ValueType>(linOp));
        invertibleOpFactory.initializePreconditionedOp(
                    linOpSourcePtr, preconditioner, result.get(),
                    Thyra::SUPPORT_SOLVE_UNSPECIFIED);
    }
    return result;
}

// Complex ValueType
template <typename ValueType>
typename boost::disable_if<
boost::is_same<ValueType, typename ScalarTraits<ValueType>::RealType>,
Teuchos::RCP<Thyra::LinearOpWithSolveBase<typename ScalarTraits<ValueType>::RealType> >
>::type
makeOperatorWithSolve(
        const Teuchos::RCP<Teuchos::ParameterList>& paramList,
        const Teuchos::RCP<const Thyra::LinearOpBase<ValueType> >& linOp,
        const Teuchos::RCP<const Thyra::PreconditionerBase<ValueType> >& preconditioner)
{
    typedef typename ScalarTraits<ValueType>::RealType RealType;

    Teuchos::RCP<Teuchos::FancyOStream> out =
            Teuchos::VerboseObjectBase::getDefaultOStream();

    Thyra::BelosLinearOpWithSolveFactory<RealType> invertibleOpFactory;
    invertibleOpFactory.setParameterList(paramList);
    invertibleOpFactory.setOStream(out);
    invertibleOpFactory.setVerbLevel(Teuchos::VERB_DEFAULT);

    Teuchos::RCP<const Thyra::LinearOpBase<RealType> > realLinOp(
                new RealWrapperOfComplexThyraLinearOperator<RealType>(linOp));

    Teuchos::RCP<Thyra::LinearOpWithSolveBase<RealType> > result;
    if (preconditioner.is_null())
        // No preconditioner
        result = Thyra::linearOpWithSolve(invertibleOpFactory, realLinOp);
    else {
        // Preconditioner defined
        result = invertibleOpFactory.createOp();
        Teuchos::RCP<const Thyra::LinearOpSourceBase<RealType> > realLinOpSourcePtr(
                    new Thyra::DefaultLinearOpSource<RealType>(realLinOp));
        Teuchos::RCP<const Thyra::PreconditionerBase<RealType> > realPreconditioner(
                    new RealWrapperOfComplexThyraPreconditioner<RealType>(preconditioner));
        invertibleOpFactory.initializePreconditionedOp(
                    realLinOpSourcePtr, realPreconditioner, result.get(),
                    Thyra::SUPPORT_SOLVE_UNSPECIFIED);
    }
    return result;
}

// Real ValueType
template <typename ValueType>
typename boost::enable_if<
boost::is_same<ValueType, typename ScalarTraits<ValueType>::RealType>,
Thyra::SolveStatus<typename ScalarTraits<ValueType>::RealType>
>::type
reallySolve(
        const Thyra::LinearOpWithSolveBase<typename ScalarTraits<ValueType>::RealType>& op,
        const Thyra::EOpTransp trans,
        const Thyra::MultiVectorBase<ValueType>& rhs,
        const Teuchos::Ptr<Thyra::MultiVectorBase<ValueType> >& sol)
{
    return op.solve(trans, rhs, sol);
}

// Complex ValueType
template <typename ValueType>
typename boost::disable_if<
boost::is_same<ValueType, typename ScalarTraits<ValueType>::RealType>,
Thyra::SolveStatus<typename ScalarTraits<ValueType>::RealType>
>::type
reallySolve(
        const Thyra::LinearOpWithSolveBase<typename ScalarTraits<ValueType>::RealType>& op,
        const Thyra::EOpTransp trans,
        const Thyra::MultiVectorBase<ValueType>& rhs,
        const Teuchos::Ptr<Thyra::MultiVectorBase<ValueType> >& sol)
{
    typedef typename ScalarTraits<ValueType>::RealType MagnitudeType;

    // Wrap the right-hand-side data in a real multivector of twice as many rows

    const Teuchos::Ordinal rhsRowCount = rhs.range()->dim();
    const Teuchos::Ordinal rhsColCount = rhs.domain()->dim();

    Teuchos::ArrayRCP<const MagnitudeType> realRhsArray;
    RTOpPack::ConstSubMultiVectorView<MagnitudeType> realRhsView;
    Teuchos::RCP<const Thyra::MultiVectorBase<MagnitudeType> > realRhs;

    Thyra::ConstDetachedMultiVectorView<ValueType> rhsView(
                Teuchos::rcpFromRef(rhs));
    if (rhsView.leadingDim() == rhsRowCount) {
        // contiguous vector
        const MagnitudeType* realRhsData =
                reinterpret_cast<const MagnitudeType*>(rhsView.values());
        realRhsArray = Teuchos::arcp(realRhsData,
                                     0, // lowerOffset
                                     2 * rhsRowCount * rhsColCount,
                                     false); // doesn't own
        realRhsView.initialize(0, // globalOffset
                               2 * rhsRowCount,
                               0, // colOffset
                               rhsColCount,
                               realRhsArray,
                               2 * rhsRowCount); // leadingDim
        realRhs = Thyra::createMembersView(op.domain(), realRhsView);
    } else
        throw std::runtime_error("reallySolve(): discontiguous multivectors "
                                 "are not supported yet");

    // Wrap the solution data in a real multivector of twice as many rows

    const Teuchos::Ordinal solRowCount = sol->range()->dim();
    const Teuchos::Ordinal solColCount = sol->domain()->dim();

    Teuchos::ArrayRCP<MagnitudeType> realSolArray;
    RTOpPack::SubMultiVectorView<MagnitudeType> realSolView;
    Teuchos::RCP<Thyra::MultiVectorBase<MagnitudeType> > realSol;

    Thyra::DetachedMultiVectorView<ValueType> solView(
                Teuchos::rcpFromPtr(sol));
    if (solView.leadingDim() == solRowCount) {
        // contiguous vector
        MagnitudeType* realSolData =
                reinterpret_cast<MagnitudeType*>(solView.values());
        realSolArray = Teuchos::arcp(realSolData,
                                     0, // lowerOffset
                                     2 * solRowCount * solColCount,
                                     false); // doesn't own
        realSolView.initialize(0, // globalOffset
                               2 * solRowCount,
                               0, // colOffset
                               solColCount,
                               realSolArray,
                               2 * solRowCount); // leadingDim
        realSol = Thyra::createMembersView(op.range(), realSolView);
    } else
        throw std::runtime_error("reallySolve(): discontiguous multivectors "
                                 "are not supported yet");

    return op.solve(trans, *realRhs, realSol.ptr());
}

} // namespace

// BelosSolverWrapper member functions

template <typename ValueType>
BelosSolverWrapper<ValueType>::BelosSolverWrapper(
        const Teuchos::RCP<const Thyra::LinearOpBase<ValueType> >& linOp) :
    m_linOp(linOp)
{
}

template <typename ValueType>
BelosSolverWrapper<ValueType>::~BelosSolverWrapper()
{
}

template <typename ValueType>
void BelosSolverWrapper<ValueType>::setPreconditioner(
        const Teuchos::RCP<const Thyra::PreconditionerBase<ValueType> >& preconditioner)
{
    m_preconditioner = preconditioner;
}

template <typename ValueType>
void BelosSolverWrapper<ValueType>::initializeSolver(
        const Teuchos::RCP<Teuchos::ParameterList>& paramList)
{
    m_linOpWithSolve = makeOperatorWithSolve(
                paramList, m_linOp, m_preconditioner);
}

template <typename ValueType>
Thyra::SolveStatus<typename BelosSolverWrapper<ValueType>::MagnitudeType>
BelosSolverWrapper<ValueType>::solve(
        const Thyra::EOpTransp trans,
        const Thyra::MultiVectorBase<ValueType>& rhs,
        const Teuchos::Ptr<Thyra::MultiVectorBase<ValueType> >& sol) const
{
    if (m_linOpWithSolve.is_null())
        throw std::runtime_error("BelosSolverWrapper::solve(): "
                                 "solver not initialized");
    return reallySolve(*m_linOpWithSolve, trans, rhs, sol);
}

// nonmember functions

namespace
{

template <typename MagnitudeType>
Teuchos::RCP<Teuchos::ParameterList>
inline defaultGmresParameterListInternal(MagnitudeType tol, int maxIterationCount)
{
    Teuchos::RCP<Teuchos::ParameterList> paramList(
                new Teuchos::ParameterList("DefaultParameters"));
    paramList->set("Solver Type", "Pseudo Block GMRES");
    Teuchos::ParameterList& solverTypesList = paramList->sublist("Solver Types");
    Teuchos::ParameterList& pseudoBlockGmresList =
             solverTypesList.sublist("Pseudo Block GMRES");
    pseudoBlockGmresList.set("Convergence Tolerance", tol);
    pseudoBlockGmresList.set("Maximum Iterations", maxIterationCount);
    return paramList;
}

template <typename MagnitudeType>
Teuchos::RCP<Teuchos::ParameterList>
inline defaultCgParameterListInternal(MagnitudeType tol, int maxIterationCount)
{
    Teuchos::RCP<Teuchos::ParameterList> paramList(
                new Teuchos::ParameterList("DefaultParameters"));
    paramList->set("Solver Type", "Pseudo Block CG");
    Teuchos::ParameterList& solverTypesList = paramList->sublist("Solver Types");
    Teuchos::ParameterList& pseudoBlockCgList =
            solverTypesList.sublist("Pseudo Block CG");
    pseudoBlockCgList.set("Convergence Tolerance", tol);
    pseudoBlockCgList.set("Maximum Iterations", maxIterationCount);
    return paramList;
}

} // namespace

Teuchos::RCP<Teuchos::ParameterList> defaultGmresParameterList(
        double tol, int maxIterationCount)
{
    return defaultGmresParameterListInternal(tol, maxIterationCount);
}

Teuchos::RCP<Teuchos::ParameterList> defaultGmresParameterList(
        float tol, int maxIterationCount)
{
    return defaultGmresParameterListInternal(tol, maxIterationCount);
}

Teuchos::RCP<Teuchos::ParameterList> defaultCgParameterList(
        double tol, int maxIterationCount)
{
    return defaultCgParameterListInternal(tol, maxIterationCount);
}

Teuchos::RCP<Teuchos::ParameterList> defaultCgParameterList(
        float tol, int maxIterationCount)
{
    return defaultCgParameterListInternal(tol, maxIterationCount);
}

FIBER_INSTANTIATE_CLASS_TEMPLATED_ON_RESULT(BelosSolverWrapper);

} // namespace Bempp

#endif // WITH_TRILINOS

max_stars_repo_name: nicolas-chaulet/bempp

max_issues_repo_name: UCL/bempp

max_forks_repo_name: UCL/bempp


text:
/*
 * Copyright (c) 2011-2014 Dmitry Prokoptsev <dprokoptsev@yandex-team.ru>
 *
 * This file is part of mms, the memory-mapped storage library.
 *
 * 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 "test_config.h"

#include <boost/test/unit_test.hpp>

#include <mms/string.h>
#include <mms/vector.h>
#include <mms/map.h>
#include <mms/set.h>
#include <mms/writer.h>
#include <mms/copy.h>
#include <iostream>
#include <sstream>
#include <functional>
#include <boost/lexical_cast.hpp>

#include <boost/assign/std/vector.hpp>
#include "tools.h"

template <class T1, class T2, class T3>
struct TraverseSimple {

    T1 v1;
    T2 v2;
    T3 v3;

    template<class A> void traverseFields(A a) const { a(v1)(v2)(v3); }
    typedef TraverseSimple<T1, T2, T3> MmappedType;
};

template <class T1, class T2, class T3>
bool operator == (const TraverseSimple<T1, T2, T3>& lhs,
                  const TraverseSimple<T1, T2, T3>& rhs)
{
    return lhs.v1 == rhs.v1 && lhs.v2 == rhs.v2 && lhs.v3 == rhs.v3;
}

template <class T1, class T2, class T3>
TraverseSimple<T1, T2, T3> genTraverseSimple(int seed)
{
    TraverseSimple<T1, T2, T3> pod;
    pod.v1 = GenT<T1>()(seed);
    pod.v2 = GenT<T2>()(seed * 57);
    pod.v3 = GenT<T3>()(seed * 1543);
    return pod;
}

template <class T1, class T2, class T3>
void testTraverseSimple(int seed)
{
    typedef TraverseSimple<T1, T2, T3> SIMPLE;
    SIMPLE podOrig = genTraverseSimple<T1, T2, T3>(seed);
    std::stringstream out;
    mms::Writer w(out);
    size_t ofs = mms::unsafeWrite(w, podOrig);
    BOOST_CHECK_EQUAL(w.pos(), sizeof(SIMPLE));
    BOOST_CHECK_EQUAL(ofs, 0);

    std::string buf = out.str();
    SIMPLE podReaded = *((const SIMPLE*) (buf.c_str() + ofs));
    BOOST_CHECK(podOrig == podReaded);

    SIMPLE copied;
    mms::copy(podReaded, copied);
    BOOST_CHECK(podOrig == copied);
}

BOOST_AUTO_TEST_CASE( pod_test )
{
    for(int seed = -1300; seed <= 157092; seed += 10212) {
        testTraverseSimple<int, int, int>(seed);
        testTraverseSimple<char, int, int>(seed);
        testTraverseSimple<int, char, int>(seed);
        testTraverseSimple<int, int, char>(seed);
        testTraverseSimple<int, size_t, int>(seed);
        testTraverseSimple<char, size_t, int>(seed);
        testTraverseSimple<int, size_t, char>(seed);
        testTraverseSimple<char, char, int>(seed);
        testTraverseSimple<char, char, char>(seed);
        testTraverseSimple<uint32_t, uint16_t, uint32_t>(seed);
        testTraverseSimple<uint32_t, char, uint32_t>(seed);
        testTraverseSimple<uint16_t, char, uint16_t>(seed);
    }
}

max_stars_repo_name: HDSoft/mms

max_issues_repo_name: HDSoft/mms

max_forks_repo_name: HDSoft/mms


text:
/*=============================================================================
    Copyright (c) 2001-2011 Hartmut Kaiser
    Copyright (c) 2001-2011 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)
=============================================================================*/
#if !defined(BOOST_SPIRIT_UNICODE_1_JANUARY_12_2010_0728PM)
#define BOOST_SPIRIT_UNICODE_1_JANUARY_12_2010_0728PM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/cstdint.hpp>
#include <boost/spirit/home/support/char_encoding/unicode/query.hpp>

namespace boost { namespace spirit { namespace char_encoding
{
    ///////////////////////////////////////////////////////////////////////////
    //  Test characters for specified conditions (using iso8859-1)
    ///////////////////////////////////////////////////////////////////////////
    struct unicode
    {
        typedef ::boost::uint32_t char_type;

    ///////////////////////////////////////////////////////////////////////////
    //  Posix stuff
    ///////////////////////////////////////////////////////////////////////////
        static bool
        isascii_(char_type ch)
        {
            return 0 == (ch & ~0x7f);
        }

        static bool
        ischar(char_type ch)
        {
            // unicode code points in the range 0x00 to 0x10FFFF
            return ch <= 0x10FFFF;
        }

        static bool
        isalnum(char_type ch)
        {
            return ucd::is_alphanumeric(ch);
        }

        static bool
        isalpha(char_type ch)
        {
            return ucd::is_alphabetic(ch);
        }

        static bool
        isdigit(char_type ch)
        {
            return ucd::is_decimal_number(ch);
        }

        static bool
        isxdigit(char_type ch)
        {
            return ucd::is_hex_digit(ch);
        }

        static bool
        iscntrl(char_type ch)
        {
            return ucd::is_control(ch);
        }

        static bool
        isgraph(char_type ch)
        {
            return ucd::is_graph(ch);
        }

        static bool
        islower(char_type ch)
        {
            return ucd::is_lowercase(ch);
        }

        static bool
        isprint(char_type ch)
        {
            return ucd::is_print(ch);
        }

        static bool
        ispunct(char_type ch)
        {
            return ucd::is_punctuation(ch);
        }

        static bool
        isspace(char_type ch)
        {
            return ucd::is_white_space(ch);
        }

        static bool
        isblank BOOST_PREVENT_MACRO_SUBSTITUTION (char_type ch)
        {
            return ucd::is_blank(ch);
        }

        static bool
        isupper(char_type ch)
        {
            return ucd::is_uppercase(ch);
        }

    ///////////////////////////////////////////////////////////////////////////
    //  Simple character conversions
    ///////////////////////////////////////////////////////////////////////////

        static char_type
        tolower(char_type ch)
        {
            return ucd::to_lowercase(ch);
        }

        static char_type
        toupper(char_type ch)
        {
            return ucd::to_uppercase(ch);
        }

        static ::boost::uint32_t
        toucs4(char_type ch)
        {
            return ch;
        }

    ///////////////////////////////////////////////////////////////////////////
    //  Major Categories
    ///////////////////////////////////////////////////////////////////////////
#define BOOST_SPIRIT_MAJOR_CATEGORY(name)                                       \
        static bool                                                             \
        is_##name(char_type ch)                                                 \
        {                                                                       \
            return ucd::get_major_category(ch) == ucd::properties::name;        \
        }                                                                       \
        /***/

        BOOST_SPIRIT_MAJOR_CATEGORY(letter)
        BOOST_SPIRIT_MAJOR_CATEGORY(mark)
        BOOST_SPIRIT_MAJOR_CATEGORY(number)
        BOOST_SPIRIT_MAJOR_CATEGORY(separator)
        BOOST_SPIRIT_MAJOR_CATEGORY(other)
        BOOST_SPIRIT_MAJOR_CATEGORY(punctuation)
        BOOST_SPIRIT_MAJOR_CATEGORY(symbol)

    ///////////////////////////////////////////////////////////////////////////
    //  General Categories
    ///////////////////////////////////////////////////////////////////////////
#define BOOST_SPIRIT_CATEGORY(name)                                             \
        static bool                                                             \
        is_##name(char_type ch)                                                 \
        {                                                                       \
            return ucd::get_category(ch) == ucd::properties::name;              \
        }                                                                       \
        /***/

        BOOST_SPIRIT_CATEGORY(uppercase_letter)
        BOOST_SPIRIT_CATEGORY(lowercase_letter)
        BOOST_SPIRIT_CATEGORY(titlecase_letter)
        BOOST_SPIRIT_CATEGORY(modifier_letter)
        BOOST_SPIRIT_CATEGORY(other_letter)

        BOOST_SPIRIT_CATEGORY(nonspacing_mark)
        BOOST_SPIRIT_CATEGORY(enclosing_mark)
        BOOST_SPIRIT_CATEGORY(spacing_mark)

        BOOST_SPIRIT_CATEGORY(decimal_number)
        BOOST_SPIRIT_CATEGORY(letter_number)
        BOOST_SPIRIT_CATEGORY(other_number)

        BOOST_SPIRIT_CATEGORY(space_separator)
        BOOST_SPIRIT_CATEGORY(line_separator)
        BOOST_SPIRIT_CATEGORY(paragraph_separator)

        BOOST_SPIRIT_CATEGORY(control)
        BOOST_SPIRIT_CATEGORY(format)
        BOOST_SPIRIT_CATEGORY(private_use)
        BOOST_SPIRIT_CATEGORY(surrogate)
        BOOST_SPIRIT_CATEGORY(unassigned)

        BOOST_SPIRIT_CATEGORY(dash_punctuation)
        BOOST_SPIRIT_CATEGORY(open_punctuation)
        BOOST_SPIRIT_CATEGORY(close_punctuation)
        BOOST_SPIRIT_CATEGORY(connector_punctuation)
        BOOST_SPIRIT_CATEGORY(other_punctuation)
        BOOST_SPIRIT_CATEGORY(initial_punctuation)
        BOOST_SPIRIT_CATEGORY(final_punctuation)

        BOOST_SPIRIT_CATEGORY(math_symbol)
        BOOST_SPIRIT_CATEGORY(currency_symbol)
        BOOST_SPIRIT_CATEGORY(modifier_symbol)
        BOOST_SPIRIT_CATEGORY(other_symbol)

    ///////////////////////////////////////////////////////////////////////////
    //  Derived Categories
    ///////////////////////////////////////////////////////////////////////////
#define BOOST_SPIRIT_DERIVED_CATEGORY(name)                                     \
        static bool                                                             \
        is_##name(char_type ch)                                                 \
        {                                                                       \
            return ucd::is_##name(ch);                                          \
        }                                                                       \
        /***/

        BOOST_SPIRIT_DERIVED_CATEGORY(alphabetic)
        BOOST_SPIRIT_DERIVED_CATEGORY(uppercase)
        BOOST_SPIRIT_DERIVED_CATEGORY(lowercase)
        BOOST_SPIRIT_DERIVED_CATEGORY(white_space)
        BOOST_SPIRIT_DERIVED_CATEGORY(hex_digit)
        BOOST_SPIRIT_DERIVED_CATEGORY(noncharacter_code_point)
        BOOST_SPIRIT_DERIVED_CATEGORY(default_ignorable_code_point)

    ///////////////////////////////////////////////////////////////////////////
    //  Scripts
    ///////////////////////////////////////////////////////////////////////////
#define BOOST_SPIRIT_SCRIPT(name)                                               \
        static bool                                                             \
        is_##name(char_type ch)                                                 \
        {                                                                       \
            return ucd::get_script(ch) == ucd::properties::name;                \
        }                                                                       \
        /***/

        BOOST_SPIRIT_SCRIPT(arabic)
        BOOST_SPIRIT_SCRIPT(imperial_aramaic)
        BOOST_SPIRIT_SCRIPT(armenian)
        BOOST_SPIRIT_SCRIPT(avestan)
        BOOST_SPIRIT_SCRIPT(balinese)
        BOOST_SPIRIT_SCRIPT(bamum)
        BOOST_SPIRIT_SCRIPT(bengali)
        BOOST_SPIRIT_SCRIPT(bopomofo)
        BOOST_SPIRIT_SCRIPT(braille)
        BOOST_SPIRIT_SCRIPT(buginese)
        BOOST_SPIRIT_SCRIPT(buhid)
        BOOST_SPIRIT_SCRIPT(canadian_aboriginal)
        BOOST_SPIRIT_SCRIPT(carian)
        BOOST_SPIRIT_SCRIPT(cham)
        BOOST_SPIRIT_SCRIPT(cherokee)
        BOOST_SPIRIT_SCRIPT(coptic)
        BOOST_SPIRIT_SCRIPT(cypriot)
        BOOST_SPIRIT_SCRIPT(cyrillic)
        BOOST_SPIRIT_SCRIPT(devanagari)
        BOOST_SPIRIT_SCRIPT(deseret)
        BOOST_SPIRIT_SCRIPT(egyptian_hieroglyphs)
        BOOST_SPIRIT_SCRIPT(ethiopic)
        BOOST_SPIRIT_SCRIPT(georgian)
        BOOST_SPIRIT_SCRIPT(glagolitic)
        BOOST_SPIRIT_SCRIPT(gothic)
        BOOST_SPIRIT_SCRIPT(greek)
        BOOST_SPIRIT_SCRIPT(gujarati)
        BOOST_SPIRIT_SCRIPT(gurmukhi)
        BOOST_SPIRIT_SCRIPT(hangul)
        BOOST_SPIRIT_SCRIPT(han)
        BOOST_SPIRIT_SCRIPT(hanunoo)
        BOOST_SPIRIT_SCRIPT(hebrew)
        BOOST_SPIRIT_SCRIPT(hiragana)
        BOOST_SPIRIT_SCRIPT(katakana_or_hiragana)
        BOOST_SPIRIT_SCRIPT(old_italic)
        BOOST_SPIRIT_SCRIPT(javanese)
        BOOST_SPIRIT_SCRIPT(kayah_li)
        BOOST_SPIRIT_SCRIPT(katakana)
        BOOST_SPIRIT_SCRIPT(kharoshthi)
        BOOST_SPIRIT_SCRIPT(khmer)
        BOOST_SPIRIT_SCRIPT(kannada)
        BOOST_SPIRIT_SCRIPT(kaithi)
        BOOST_SPIRIT_SCRIPT(tai_tham)
        BOOST_SPIRIT_SCRIPT(lao)
        BOOST_SPIRIT_SCRIPT(latin)
        BOOST_SPIRIT_SCRIPT(lepcha)
        BOOST_SPIRIT_SCRIPT(limbu)
        BOOST_SPIRIT_SCRIPT(linear_b)
        BOOST_SPIRIT_SCRIPT(lisu)
        BOOST_SPIRIT_SCRIPT(lycian)
        BOOST_SPIRIT_SCRIPT(lydian)
        BOOST_SPIRIT_SCRIPT(malayalam)
        BOOST_SPIRIT_SCRIPT(mongolian)
        BOOST_SPIRIT_SCRIPT(meetei_mayek)
        BOOST_SPIRIT_SCRIPT(myanmar)
        BOOST_SPIRIT_SCRIPT(nko)
        BOOST_SPIRIT_SCRIPT(ogham)
        BOOST_SPIRIT_SCRIPT(ol_chiki)
        BOOST_SPIRIT_SCRIPT(old_turkic)
        BOOST_SPIRIT_SCRIPT(oriya)
        BOOST_SPIRIT_SCRIPT(osmanya)
        BOOST_SPIRIT_SCRIPT(phags_pa)
        BOOST_SPIRIT_SCRIPT(inscriptional_pahlavi)
        BOOST_SPIRIT_SCRIPT(phoenician)
        BOOST_SPIRIT_SCRIPT(inscriptional_parthian)
        BOOST_SPIRIT_SCRIPT(rejang)
        BOOST_SPIRIT_SCRIPT(runic)
        BOOST_SPIRIT_SCRIPT(samaritan)
        BOOST_SPIRIT_SCRIPT(old_south_arabian)
        BOOST_SPIRIT_SCRIPT(saurashtra)
        BOOST_SPIRIT_SCRIPT(shavian)
        BOOST_SPIRIT_SCRIPT(sinhala)
        BOOST_SPIRIT_SCRIPT(sundanese)
        BOOST_SPIRIT_SCRIPT(syloti_nagri)
        BOOST_SPIRIT_SCRIPT(syriac)
        BOOST_SPIRIT_SCRIPT(tagbanwa)
        BOOST_SPIRIT_SCRIPT(tai_le)
        BOOST_SPIRIT_SCRIPT(new_tai_lue)
        BOOST_SPIRIT_SCRIPT(tamil)
        BOOST_SPIRIT_SCRIPT(tai_viet)
        BOOST_SPIRIT_SCRIPT(telugu)
        BOOST_SPIRIT_SCRIPT(tifinagh)
        BOOST_SPIRIT_SCRIPT(tagalog)
        BOOST_SPIRIT_SCRIPT(thaana)
        BOOST_SPIRIT_SCRIPT(thai)
        BOOST_SPIRIT_SCRIPT(tibetan)
        BOOST_SPIRIT_SCRIPT(ugaritic)
        BOOST_SPIRIT_SCRIPT(vai)
        BOOST_SPIRIT_SCRIPT(old_persian)
        BOOST_SPIRIT_SCRIPT(cuneiform)
        BOOST_SPIRIT_SCRIPT(yi)
        BOOST_SPIRIT_SCRIPT(inherited)
        BOOST_SPIRIT_SCRIPT(common)
        BOOST_SPIRIT_SCRIPT(unknown)

#undef BOOST_SPIRIT_MAJOR_CATEGORY
#undef BOOST_SPIRIT_CATEGORY
#undef BOOST_SPIRIT_DERIVED_CATEGORY
#undef BOOST_SPIRIT_SCRIPT

    };

}}}

#endif


text:
#include "MeshingUtils.h"

#include <HierarchyManager.h>
#include <VascularModelingNodeTypes.h>
#include <VesselMeshingNodeTypes.h>

#include <boost/format.hpp>

namespace crimson {

MeshingParametersData* MeshingUtils::getMeshingParametersForSolid(mitk::DataNode* solidNode)
{
    if (!solidNode) {
        return nullptr;
    }

    auto hm = crimson::HierarchyManager::getInstance();

    crimson::HierarchyManager::NodeType ownerNodeType = crimson::VascularModelingNodeTypes::VesselPath();
    mitk::DataNode::Pointer meshingParametersOwnerNode = hm->getAncestor(solidNode, crimson::VascularModelingNodeTypes::VesselPath());

    if (meshingParametersOwnerNode.IsNull()) {
        // Put the meshing parameters under the vessel tree node if it's available
        ownerNodeType = crimson::VascularModelingNodeTypes::VesselTree();
        meshingParametersOwnerNode = hm->getAncestor(solidNode, crimson::VascularModelingNodeTypes::VesselTree());
    }

    if (meshingParametersOwnerNode.IsNull()) {
        // Alternatively, e.g. for imported models, put meshing parameters under the solid model itself
        // The drawback in this case is that the meshing parameters will be deleted along with the solid model
        // itself and cannot be reused
        MITK_WARN << "No suitable owner for meshing parameters data found. Using the solid itself";
        ownerNodeType = crimson::VascularModelingNodeTypes::Solid();
        meshingParametersOwnerNode = solidNode;
    }

    mitk::DataNode::Pointer currentMeshingParametersNode = hm->getFirstDescendant(meshingParametersOwnerNode, crimson::VesselMeshingNodeTypes::MeshingParameters(), true);

    if (!currentMeshingParametersNode) {
        // Create the meshing parameters node if it doesn't exist
        currentMeshingParametersNode = mitk::DataNode::New();
        currentMeshingParametersNode->SetName(meshingParametersOwnerNode->GetName() + " Meshing Parameters");
        currentMeshingParametersNode->SetBoolProperty("hidden object", true);
        currentMeshingParametersNode->SetData(crimson::MeshingParametersData::New());

        hm->addNodeToHierarchy(meshingParametersOwnerNode, ownerNodeType, currentMeshingParametersNode, crimson::VesselMeshingNodeTypes::MeshingParameters());
    }

    return static_cast<crimson::MeshingParametersData*>(currentMeshingParametersNode->GetData());
}

crimson::AsyncTaskManager::TaskUID MeshingUtils::getMeshingTaskUID(mitk::DataNode* solidNode)
{
    if (!solidNode) {
        return "";
    }

    return (boost::format("Meshing %1%") % solidNode).str();
}

}

max_stars_repo_name: carthurs/CRIMSONGUI

max_issues_repo_name: carthurs/CRIMSONGUI

max_forks_repo_name: carthurs/CRIMSONGUI


text:
/* CirKit: A circuit toolkit
 * Copyright (C) 2009-2015  University of Bremen
 * Copyright (C) 2015-2017  EPFL
 *
 * 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.
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE circuit_io

#include <boost/test/unit_test.hpp>
#include <boost/test/output_test_stream.hpp>

#include <reversible/circuit.hpp>
#include <reversible/functions/add_gates.hpp>
#include <reversible/io/print_circuit.hpp>
#include <reversible/io/read_realization.hpp>
#include <reversible/io/write_realization.hpp>
#include <reversible/io/write_verilog.hpp>

BOOST_AUTO_TEST_CASE(simple)
{
  using boost::test_tools::output_test_stream;

  using namespace cirkit;

  circuit circ( 3u ), circ2;
  std::string circ_str = "―⊕―○―――●―\n―――⊕―●―⨯―\n―○―●―⊕―⨯―\n";
  output_test_stream output, output2;

  /* create circuit */
  append_cnot( circ, make_var( 2u, false ), 0u );
  append_toffoli( circ )( make_var( 0u, false ), make_var( 2u ) )( 1u );
  append_cnot( circ, 1u, 2u );
  append_fredkin( circ )( make_var( 0u ) )( 1u, 2u );

  /* print circuit */
  output << circ;
  BOOST_CHECK( output.is_equal( circ_str ) );

  /* write and read circuit */
  write_realization( circ, "/tmp/test.real" );
  read_realization( circ2, "/tmp/test.real" );

  /* print read circuit */
  output2 << circ;
  BOOST_CHECK( output2.is_equal( circ_str ) );

  /* write verilog */
  write_verilog( circ, "/tmp/test.v" );
}

// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:

max_stars_repo_name: eletesta/cirkit

max_issues_repo_name: eletesta/cirkit

max_forks_repo_name: eletesta/cirkit