text:
/*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.

// All rights reserved.

// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/

#ifndef STAPL_RUNTIME_MESSAGE_HPP
#define STAPL_RUNTIME_MESSAGE_HPP

#include "config.hpp"
#include "context_id.hpp"
#include "exception.hpp"
#include "full_location.hpp"
#include "message_handle.hpp"
#include "request/header.hpp"
#include "type_traits/aligned_storage.hpp"
#include "utility/option.hpp"
#include "utility/ref_counted.hpp"
#include <memory>
#include <new>
#include <type_traits>
#include <boost/intrusive/slist.hpp>
#include <boost/range/iterator_range_core.hpp>

namespace stapl {

namespace runtime {

class message;

//////////////////////////////////////////////////////////////////////
/// @brief Deleter for @ref message objects.
///
/// @see message
/// @ingroup requestBuildingBlock
//////////////////////////////////////////////////////////////////////
struct message_delete
{
  void operator()(message*) const;
};

//////////////////////////////////////////////////////////////////////
/// @brief @ref message unique pointer.
///
/// @see message
/// @ingroup requestBuildingBlock
//////////////////////////////////////////////////////////////////////
using message_ptr = std::unique_ptr<message, message_delete>;

//////////////////////////////////////////////////////////////////////
/// @brief Communication buffer.
///
/// A message consists of a standard, fixed header that gives information about
/// the size and the type of the message and the message body. The body contains
/// data relevant to communication, such as additional headers and/or payload.
///
/// @ingroup requestBuildingBlock
//////////////////////////////////////////////////////////////////////
class message
: public ref_counted<message, message_delete>
{
public:
  using payload_range_type = boost::iterator_range<char*>;

  //////////////////////////////////////////////////////////////////////
  /// @brief Message header.
  ///
  /// The message size must always be the first member so that it can be
  /// transmitted independently of the rest of the header.
  //////////////////////////////////////////////////////////////////////
  struct header_type
  {
    std::size_t  m_size;
    header::type m_type;

    void reset(void) noexcept
    {
      m_size = 0;
      m_type = header::INVALID;
    }
  };

  //////////////////////////////////////////////////////////////////////
  /// @brief Initializes the memory for allocating @ref message objects.
  ///
  /// The following options are supported through @p opts:
  /// -# @c STAPL_RUNTIME_MSG_SIZE to change the default capacity.
  /// -# @c STAPL_RUNTIME_MSG_POOL_DISABLE to disable pool @ref message
  ///    allocation.
  /// -# @c STAPL_RUNTIME_MSG_POOL_MIN_NUM Minimum number of allocated
  ///    @ref message objects when pool allocation is enabled.
  /// -# @c STAPL_RUNTIME_MSG_MAX_MEM the maximum fraction of memory to use when
  ///    pool allocation is enabled.
  ///
  /// @param opts Options to pass for initialization.
  /// @param nppn Number of processes per node.
  //////////////////////////////////////////////////////////////////////
  static void initialize(option const& opts, const unsigned int nppn);

  //////////////////////////////////////////////////////////////////////
  /// @brief Finalizes the memory for allocating @ref message objects.
  //////////////////////////////////////////////////////////////////////
  static void finalize(void);

  //////////////////////////////////////////////////////////////////////
  /// @brief Returns the default capacity of the internal buffer (header and
  ///        body) in bytes.
  //////////////////////////////////////////////////////////////////////
  static std::size_t default_capacity(void) noexcept;

  //////////////////////////////////////////////////////////////////////
  /// @brief Returns the size of the header in bytes.
  //////////////////////////////////////////////////////////////////////
  static std::size_t header_size(void) noexcept;

  //////////////////////////////////////////////////////////////////////
  /// @brief Sets the default capacity for the body in bytes.
  //////////////////////////////////////////////////////////////////////
  static void set_default_body_capacity(const std::size_t);

  //////////////////////////////////////////////////////////////////////
  /// @brief Returns the default capacity for the body in bytes.
  //////////////////////////////////////////////////////////////////////
  static std::size_t default_body_capacity(void) noexcept
  { return (default_capacity() - header_size()); }

  //////////////////////////////////////////////////////////////////////
  /// @brief Constructs a @ref message of default capacity.
  //////////////////////////////////////////////////////////////////////
  static message* construct(void);

  //////////////////////////////////////////////////////////////////////
  /// @brief Constructs a @ref message of with capacity of @p n bytes.
  ///
  /// @param n          Requested capacity in bytes.
  /// @param exact_size @c true if there is no benefit to providing extra
  ///                   capacity.
  //////////////////////////////////////////////////////////////////////
  static message* construct(const std::size_t n, const bool exact_size);

  //////////////////////////////////////////////////////////////////////
  /// @brief Destroys @p msg.
  //////////////////////////////////////////////////////////////////////
  static void destroy(message* msg);

  //////////////////////////////////////////////////////////////////////
  /// @brief Constructs a @ref message that can store at least @p n bytes.
  ///
  /// @param n          Requested capacity in bytes.
  /// @param exact_size @c true if there is no benefit to providing extra
  ///                   capacity.
  //////////////////////////////////////////////////////////////////////
  static message_ptr create(const std::size_t n, const bool exact_size = true)
  { return message_ptr{construct((header_size() + n), exact_size)}; }

  //////////////////////////////////////////////////////////////////////
  /// @brief Constructs a @ref message that can store at least @p n bytes.
  ///
  /// @param h          Message type.
  /// @param n          Requested capacity in bytes.
  /// @param exact_size @c true if there is no benefit to providing extra
  ///                   capacity.
  //////////////////////////////////////////////////////////////////////
  static message_ptr create(const header::type h,
                            const std::size_t n,
                            const bool exact_size = true)
  {
    const std::size_t size = (header_size() + n);

    message* const m   = construct(size, exact_size);
    m->header().m_type = h;

    return message_ptr{m};
  }

  //////////////////////////////////////////////////////////////////////
  /// @brief Constructs a @ref message that can store at least @p n bytes.
  ///
  /// @param h          Message type.
  /// @param n          Requested capacity in bytes.
  /// @param exh        Extended header.
  /// @param exact_size @c true if there is no benefit to providing extra
  ///                   capacity.
  //////////////////////////////////////////////////////////////////////
  template<typename ExtendedHeader>
  static message_ptr create(const header::type h,
                            const std::size_t n,
                            ExtendedHeader&& exh,
                            const bool exact_size = true)
  {
    using extended_header_type = typename std::decay<ExtendedHeader>::type;

    const std::size_t ex_hdr_size =
      sizeof(aligned_storage_t<sizeof(extended_header_type)>);
    const std::size_t size = (header_size() + ex_hdr_size + n);

    message* const m    = construct(size, exact_size);
    m->header().m_type  = h;
    m->header().m_size += ex_hdr_size;

    m->m_payload_offset = ex_hdr_size;
    new(m->body()) extended_header_type(std::forward<ExtendedHeader>(exh));

    return message_ptr{m};
  }

private:
  /// Capacity for message body.
  const std::size_t m_body_capacity;
  /// Payload offset in message body, for example due to extended header.
  std::size_t       m_payload_offset;
  /// @c true if the @ref message is using memory managed by the runtime.
  const bool        m_managed;
  /// Handle for the communication layer.
  message_handle    m_handle;
  /// @c true if the @ref message has been forwarded.
  bool              m_forwarded;

public:
  using slist_hook_type = boost::intrusive::slist_member_hook<>;

  /// Hook for @c boost::intrusive::slist
  slist_hook_type   slist_hook;

private:
  //////////////////////////////////////////////////////////////////////
  /// @brief Constructs a new @ref message with default capacity.
  ///
  /// @param managed @c true if the @ref message is managed by the runtime.
  //////////////////////////////////////////////////////////////////////
  explicit message(const bool managed) noexcept;

  //////////////////////////////////////////////////////////////////////
  /// @brief Constructs a new @ref message of arbitrary capacity for the
  ///        payload.
  ///
  /// @param n Capacity for the payload in bytes.
  //////////////////////////////////////////////////////////////////////
  explicit message(const std::size_t n) noexcept;

  ~message(void);

public:
  //////////////////////////////////////////////////////////////////////
  /// @brief Resets this @ref message for reuse.
  //////////////////////////////////////////////////////////////////////
  void reset(void) noexcept;

  message_handle const& handle(void) const noexcept
  { return m_handle; }

  message_handle& handle(void) noexcept
  { return m_handle; }

  //////////////////////////////////////////////////////////////////////
  /// @brief Returns a pointer to the internal buffer.
  ///
  /// Flexible array members are not supported in C++. This function returns
  /// a pointer past the end of this @ref message object which is properly
  /// sized and aligned to store requests in it.
  //////////////////////////////////////////////////////////////////////
  char* data(void) noexcept;

  //////////////////////////////////////////////////////////////////////
  /// @copydoc data() const noexcept
  //////////////////////////////////////////////////////////////////////
  const char* data(void) const noexcept;

  //////////////////////////////////////////////////////////////////////
  /// @brief Returns the capacity of the internal buffer in bytes.
  //////////////////////////////////////////////////////////////////////
  std::size_t capacity(void) const noexcept
  { return (header_size() + body_capacity()); }

  //////////////////////////////////////////////////////////////////////
  /// @brief Returns the size of the internal buffer in bytes.
  //////////////////////////////////////////////////////////////////////
  std::size_t size(void) const noexcept
  { return (header_size() + body_size()); }

  //////////////////////////////////////////////////////////////////////
  /// @brief Returns @c true if the size is bigger than the default capacity.
  //////////////////////////////////////////////////////////////////////
  bool is_long(void) const noexcept
  { return (size() > default_capacity()); }

  header_type const& header(void) const noexcept
  { return *reinterpret_cast<header_type const*>(data()); }

  header_type& header(void) noexcept
  { return *reinterpret_cast<header_type*>(data()); }

  //////////////////////////////////////////////////////////////////////
  /// @brief Returns the type of the message.
  //////////////////////////////////////////////////////////////////////
  header::type type(void) const noexcept
  { return header().m_type; }

  //////////////////////////////////////////////////////////////////////
  /// @brief Changes the type of the message.
  //////////////////////////////////////////////////////////////////////
  void retarget(const header::type t) noexcept
  { header().m_type = t; }

private:
  //////////////////////////////////////////////////////////////////////
  /// @brief Returns a pointer to the body of the message.
  //////////////////////////////////////////////////////////////////////
  char* body(void) noexcept
  { return (data() + header_size()); }

  //////////////////////////////////////////////////////////////////////
  /// @copydoc body(void) noexcept
  //////////////////////////////////////////////////////////////////////
  const char* body(void) const noexcept
  { return (data() + header_size()); }

  std::size_t body_capacity(void) const noexcept
  { return m_body_capacity; }

  std::size_t body_size(void) const noexcept
  { return header().m_size; }

public:
  //////////////////////////////////////////////////////////////////////
  /// @brief Returns @c true if there is no message body.
  //////////////////////////////////////////////////////////////////////
  bool body_empty(void) const noexcept
  { return (body_size()==0); }

  //////////////////////////////////////////////////////////////////////
  /// @brief Updates the offset to the payload and returns the extended header.
  //////////////////////////////////////////////////////////////////////
  template<typename T>
  T const& fix_payload_offset(void) noexcept
  {
    m_payload_offset = sizeof(aligned_storage_t<sizeof(T)>);
    return *reinterpret_cast<T const*>(body());
  }

  //////////////////////////////////////////////////////////////////////
  /// @brief Returns the extended header.
  //////////////////////////////////////////////////////////////////////
  template<typename T>
  T const& get_extended_header(void) const noexcept
  { return *reinterpret_cast<T const*>(body()); }

  //////////////////////////////////////////////////////////////////////
  /// @brief Returns a range over the payload.
  //////////////////////////////////////////////////////////////////////
  payload_range_type payload(void) noexcept
  {
    char* const first = (body() + m_payload_offset);
    char* const last  = (body() + body_size());
    return boost::make_iterator_range(first, last);
  }

  //////////////////////////////////////////////////////////////////////
  /// @brief Available space for the payload in bytes.
  //////////////////////////////////////////////////////////////////////
  std::size_t available_space(void) const noexcept
  { return (body_capacity() - body_size()); }

  //////////////////////////////////////////////////////////////////////
  /// @brief Returns a pointer to @p n bytes reserved in the internal buffer.
  //////////////////////////////////////////////////////////////////////
  void* reserve(const std::size_t n) noexcept
  {
    STAPL_RUNTIME_ASSERT(n<=available_space());
    char* const p    = (body() + body_size());
    header().m_size += n;
    return p;
  }

  //////////////////////////////////////////////////////////////////////
  /// @brief Returns a pointer to @p n bytes reserved in the internal buffer or
  ///        @c nullptr if there is not enough space.
  //////////////////////////////////////////////////////////////////////
  void* try_reserve(const std::size_t n) noexcept
  { return (n<=available_space() ? reserve(n) : nullptr); }

  //////////////////////////////////////////////////////////////////////
  /// @brief Returns @c true if this @ref message has been forwarded.
  //////////////////////////////////////////////////////////////////////
  bool is_forwarded(void) const noexcept
  { return m_forwarded; }

  //////////////////////////////////////////////////////////////////////
  /// @brief Marks that this @ref message has been forwarded.
  //////////////////////////////////////////////////////////////////////
  void mark_forwarded(void) noexcept
  {
    STAPL_RUNTIME_ASSERT(!m_forwarded);
    m_forwarded = true;
  }

  //////////////////////////////////////////////////////////////////////
  /// @brief Creates an identical copy of this @ref message.
  //////////////////////////////////////////////////////////////////////
  message_ptr clone(void) const;
};

// Destroys the given message
inline void message_delete::operator()(message* m) const
{
  message::destroy(m);
}

//////////////////////////////////////////////////////////////////////
/// @brief Intrusive @ref message shared pointer.
///
/// @see message
/// @ingroup requestBuildingBlock
//////////////////////////////////////////////////////////////////////
class message_shared_ptr
: public boost::intrusive_ptr<message>
{
public:
  message_shared_ptr(void) = default;

  //////////////////////////////////////////////////////////////////////
  /// @brief Constructs a new @ref message_shared_ptr from @p m with reference
  ///        count @c 1.
  //////////////////////////////////////////////////////////////////////
  explicit message_shared_ptr(message_ptr&& m)
  : boost::intrusive_ptr<message>(m.release())
  { STAPL_RUNTIME_ASSERT(this->get()->unique()); }

  //////////////////////////////////////////////////////////////////////
  /// @brief Constructs a new @ref message_shared_ptr from @p m with reference
  ///        count @p ref_count.
  //////////////////////////////////////////////////////////////////////
  message_shared_ptr(message_ptr&& m, const long ref_count)
  : boost::intrusive_ptr<message>(m.release(), false)
  {
    STAPL_RUNTIME_ASSERT(this->get()->use_count()==0);
    this->get()->add_ref(ref_count);
  }

  //////////////////////////////////////////////////////////////////////
  /// @brief Constructs a new @ref message_shared_ptr from @p m.
  ///
  /// If @p add_ref is @c true, then the reference count is incremented.
  //////////////////////////////////////////////////////////////////////
  explicit message_shared_ptr(message* const m, const bool add_ref = true)
  : boost::intrusive_ptr<message>(m, add_ref)
  { STAPL_RUNTIME_ASSERT(this->get()->use_count()!=0); }
};

//////////////////////////////////////////////////////////////////////
/// @brief Returns a @ref message_ptr from @p m.
///
/// @warning This function checks the reference count and creates a clone of
///          @p m if it is not @c 1. This may cause performance degradation if
//           it is known that the reference count is always @c 1.
///
/// @ingroup requestBuildingBlock
//////////////////////////////////////////////////////////////////////
inline message_ptr make_message_ptr(message* const m)
{
  const auto ref_count = m->use_count();

  if (ref_count==0) {
    // never shared, return it immediately
    return message_ptr{m};
  }

  if (ref_count==1) {
    // last owner, reset reference count to convert to message_ptr
    m->remove_ref();
    return message_ptr{m};
  }

  // multiple owners, clone; release() will delete the initial message if ref
  // count reached 0
  message_ptr p{m->clone()};
  m->release();
  return p;
}

//////////////////////////////////////////////////////////////////////
/// @brief Intrusive @ref message list hook.
///
/// @see message, message_slist
/// @ingroup requestBuildingBlock
//////////////////////////////////////////////////////////////////////
using message_hook_type = boost::intrusive::member_hook<
                            message,
                            message::slist_hook_type,
                            &message::slist_hook>;

//////////////////////////////////////////////////////////////////////
/// @brief Intrusive @ref message list for @ref message pointers.
///
/// @see message, message_slist_hook
/// @ingroup requestBuildingBlock
//////////////////////////////////////////////////////////////////////
using message_raw_ptr_slist = typename boost::intrusive::make_slist<
                                message,
                                message_hook_type,
                                boost::intrusive::cache_last<true>,
                                boost::intrusive::constant_time_size<false>
                              >::type;

//////////////////////////////////////////////////////////////////////
/// @brief Intrusive @ref message list.
///
/// @see message, message_slist_hook
/// @ingroup requestBuildingBlock
//////////////////////////////////////////////////////////////////////
class message_slist
{
private:
  message_raw_ptr_slist m_list;

public:
  bool empty(void) const noexcept
  { return m_list.empty(); }

  void push_back(message* p) noexcept
  {
    STAPL_RUNTIME_ASSERT(p->use_count()==0);
    m_list.push_back(*p);
  }

  void push_back(message_ptr m) noexcept
  { m_list.push_back(*(m.release())); }

  message& front(void) noexcept
  { return m_list.front(); }

  message_ptr pop_front(void) noexcept
  {
    message_ptr m{&(m_list.front())};
    m_list.pop_front();
    return m;
  }
};

} // namespace runtime

} // namespace stapl

#endif


text:
// nonsugar
//
// Copyright iorate 2016-2018.
// 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)

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE flag_long_test

#include <boost/test/unit_test.hpp>

#include <memory>
#include <string>
#include <vector>
#include <boost/optional.hpp>
#include <nonsugar.hpp>

using namespace nonsugar;

BOOST_AUTO_TEST_CASE(flag_long_value)
{
    auto const cmd = command<char>("flag_long_value", "")
        .flag<'v'>({}, {"version"}, "") // deprecated style
        .flag<'V'>({}, {"verbose"}, "", "")
        .flag<'a', int>({}, {"a"}, "N", "")
        .flag<'b', int>({}, {"b"}, "N", "")
        .flag<'c', boost::optional<int>>({}, {"c"}, "N", "")
        .flag<'d', boost::optional<int>>({}, {"d"}, "N", "")
        .flag<'e', boost::optional<int>>({}, {"e"}, "N", "")
        .flag<'f', std::vector<std::string>>({}, {"f"}, "STRING", "")
        .flag<'g', int>({}, {"g"}, "N", "")
        ;
    std::vector<std::string> const args = {
        "--vers", "--verb", "--a=23", "--b", "42",
        "--c", "--d=580", "--e=147", "--f=foo", "--f", "bar" };
    auto const opts = parse(args.begin(), args.end(), cmd);
    BOOST_TEST(opts.has<'v'>());
    BOOST_TEST(opts.has<'V'>());
    BOOST_TEST((opts.has<'a'>() && opts.get<'a'>() == 23));
    BOOST_TEST((opts.has<'b'>() && opts.get<'b'>() == 42));
    BOOST_TEST((opts.has<'c'>() && opts.get<'c'>() == boost::none));
    BOOST_TEST((opts.has<'d'>() && opts.get<'d'>() == 580));
    BOOST_TEST((opts.has<'e'>() && opts.get<'e'>() == 147));
    BOOST_TEST_REQUIRE(opts.has<'f'>());
    BOOST_TEST(
        opts.get<'f'>() == (std::vector<std::string>{"foo", "bar"}),
        boost::test_tools::per_element());
    BOOST_TEST(!opts.has<'g'>());
}

BOOST_AUTO_TEST_CASE(flag_long_fail_ambiguous)
{
    auto const cmd = command<char>("flag_long_fail_ambiguous", "")
        .flag<'v'>({}, {"version"}, "")
        .flag<'V'>({}, {"verbose"}, "")
        .flag<'a'>({}, {"a"}, "")
        .flag<'A'>({}, {"a"}, "")
        .flag<'b'>({}, {"b"}, "")
        .flag<'B'>({}, {"bb"}, "")
        ;
    try {
        std::vector<std::string> const args = { "--ver" };
        parse(args.begin(), args.end(), cmd);
    } catch (error const &e) {
        BOOST_TEST(e.message() == "flag_long_fail_ambiguous: ambiguous option: --ver [--version, --verbose]");
        try {
            std::vector<std::string> const args = { "--a" };
            parse(args.begin(), args.end(), cmd);
        } catch (error const &er) {
            BOOST_TEST(er.message() == "flag_long_fail_ambiguous: ambiguous option: --a");
            std::vector<std::string> const args = { "--b", "--bb" };
            auto const opts = parse(args.begin(), args.end(), cmd);
            BOOST_TEST(opts.has<'b'>());
            BOOST_TEST(opts.has<'B'>());
            return;
        }
        BOOST_TEST(false);
        return;
    }
    BOOST_TEST(false);
}

ext: cpp

max_stars_repo_name: iorate/nonsugar

max_issues_repo_name: iorate/nonsugar

max_forks_repo_name: iorate/nonsugar


text:
#include "neuralnet/magnitude.h"
#include "streams.h"

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

// -----------------------------------------------------------------------------
// Magnitude
// -----------------------------------------------------------------------------

BOOST_AUTO_TEST_SUITE(Magnitude)

BOOST_AUTO_TEST_CASE(it_initializes_to_zero_magnitude)
{
    const NN::Magnitude mag = NN::Magnitude::Zero();

    BOOST_CHECK_EQUAL(mag.Scaled(), 0);
}

BOOST_AUTO_TEST_CASE(it_initializes_to_zero_when_rounding_invalid_magnitudes)
{
    // Negative
    const NN::Magnitude negative = NN::Magnitude::RoundFrom(-1.234);
    BOOST_CHECK_EQUAL(negative.Scaled(), 0);

    // Rounds-down to zero
    const NN::Magnitude effectivly_zero = NN::Magnitude::RoundFrom(0.005);
    BOOST_CHECK_EQUAL(effectivly_zero.Scaled(), 0);

    // Exceeded maximum
    const NN::Magnitude overflow = NN::Magnitude::RoundFrom(32767.123);
    BOOST_CHECK_EQUAL(overflow.Scaled(), 0);
}

BOOST_AUTO_TEST_CASE(it_rounds_a_small_magnitude_to_two_places)
{
    const NN::Magnitude min = NN::Magnitude::RoundFrom(0.0051);
    BOOST_CHECK_EQUAL(min.Scaled(), 1);

    const NN::Magnitude max = NN::Magnitude::RoundFrom(0.994);
    BOOST_CHECK_EQUAL(max.Scaled(), 99);
}

BOOST_AUTO_TEST_CASE(it_rounds_a_medium_magnitude_to_one_place)
{
    const NN::Magnitude min = NN::Magnitude::RoundFrom(0.995);
    BOOST_CHECK_EQUAL(min.Scaled(), 100);

    const NN::Magnitude max = NN::Magnitude::RoundFrom(9.94);
    BOOST_CHECK_EQUAL(max.Scaled(), 990);
}

BOOST_AUTO_TEST_CASE(it_rounds_a_large_magnitude_to_a_whole)
{
    const NN::Magnitude min = NN::Magnitude::RoundFrom(9.95);
    BOOST_CHECK_EQUAL(min.Scaled(), 1000);

    const NN::Magnitude max = NN::Magnitude::RoundFrom(32767.0);
    BOOST_CHECK_EQUAL(max.Scaled(), 3276700);
}

BOOST_AUTO_TEST_CASE(it_compares_another_magnitude_for_equality)
{
    const NN::Magnitude magnitude1 = NN::Magnitude::RoundFrom(1.23);
    const NN::Magnitude magnitude2 = NN::Magnitude::RoundFrom(1.23);

    BOOST_CHECK(magnitude1 == magnitude2);
    BOOST_CHECK(magnitude1 != NN::Magnitude::Zero());
}

BOOST_AUTO_TEST_CASE(it_compares_an_integer_for_equality)
{
    const NN::Magnitude magnitude = NN::Magnitude::RoundFrom(123);

    BOOST_CHECK(magnitude == 123);
    BOOST_CHECK(magnitude != 999);
}

BOOST_AUTO_TEST_CASE(it_compares_a_floating_point_number_for_equality)
{
    const NN::Magnitude magnitude = NN::Magnitude::RoundFrom(1.23);

    // Floating-point comparisons round the other value according to the size
    // for the precision tiers before checking equality:
    BOOST_CHECK(magnitude == 1.23);
    BOOST_CHECK(magnitude == 1.2);
    BOOST_CHECK(magnitude == 1.25);
    BOOST_CHECK(magnitude != 1.26);
}

BOOST_AUTO_TEST_CASE(it_reports_its_size_category)
{
    using Kind = NN::Magnitude::Kind;

    const NN::Magnitude zero = NN::Magnitude::Zero();
    BOOST_CHECK(zero.Which() == Kind::ZERO);

    const NN::Magnitude effectively_zero = NN::Magnitude::RoundFrom(0.005);
    BOOST_CHECK(effectively_zero.Which() == Kind::ZERO);

    const NN::Magnitude min_small = NN::Magnitude::RoundFrom(0.0051);
    BOOST_CHECK(min_small.Which() == Kind::SMALL);

    const NN::Magnitude max_small = NN::Magnitude::RoundFrom(0.994);
    BOOST_CHECK(max_small.Which() == Kind::SMALL);

    const NN::Magnitude min_medium = NN::Magnitude::RoundFrom(0.995);
    BOOST_CHECK(min_medium.Which() == Kind::MEDIUM);

    const NN::Magnitude max_medium = NN::Magnitude::RoundFrom(9.94);
    BOOST_CHECK(max_medium.Which() == Kind::MEDIUM);

    const NN::Magnitude min_large = NN::Magnitude::RoundFrom(9.95);
    BOOST_CHECK(min_large.Which() == Kind::LARGE);

    const NN::Magnitude max_large = NN::Magnitude::RoundFrom(32767.0);
    BOOST_CHECK(max_large.Which() == Kind::LARGE);
}

BOOST_AUTO_TEST_CASE(it_presents_the_scaled_magnitude_representation)
{
    const NN::Magnitude small = NN::Magnitude::RoundFrom(0.11);
    BOOST_CHECK_EQUAL(small.Scaled(), 11);

    const NN::Magnitude medium = NN::Magnitude::RoundFrom(1.1);
    BOOST_CHECK_EQUAL(medium.Scaled(), 110);

    const NN::Magnitude large = NN::Magnitude::RoundFrom(11.0);
    BOOST_CHECK_EQUAL(large.Scaled(), 1100);
}

BOOST_AUTO_TEST_CASE(it_presents_the_compact_magnitude_representation)
{
    const NN::Magnitude small = NN::Magnitude::RoundFrom(0.11);
    BOOST_CHECK_EQUAL(small.Compact(), 11);

    const NN::Magnitude medium = NN::Magnitude::RoundFrom(1.1);
    BOOST_CHECK_EQUAL(medium.Compact(), 11);

    const NN::Magnitude large = NN::Magnitude::RoundFrom(11.0);
    BOOST_CHECK_EQUAL(large.Compact(), 11);
}

BOOST_AUTO_TEST_CASE(it_presents_the_floatng_point_magnitude_representation)
{
    const NN::Magnitude small = NN::Magnitude::RoundFrom(0.11);
    BOOST_CHECK_EQUAL(small.Floating(), 0.11);

    const NN::Magnitude medium = NN::Magnitude::RoundFrom(1.1);
    BOOST_CHECK_EQUAL(medium.Floating(), 1.1);

    const NN::Magnitude large = NN::Magnitude::RoundFrom(11.0);
    BOOST_CHECK_EQUAL(large.Floating(), 11.0);
}

BOOST_AUTO_TEST_CASE(it_represents_itself_as_a_string)
{
    const NN::Magnitude zero = NN::Magnitude::Zero();
    BOOST_CHECK_EQUAL(zero.ToString(), "0");

    const NN::Magnitude small = NN::Magnitude::RoundFrom(0.11);
    BOOST_CHECK_EQUAL(small.ToString(), "0.11");

    const NN::Magnitude medium = NN::Magnitude::RoundFrom(1.1);
    BOOST_CHECK_EQUAL(medium.ToString(), "1.1");

    const NN::Magnitude large = NN::Magnitude::RoundFrom(11.0);
    BOOST_CHECK_EQUAL(large.ToString(), "11");

    const NN::Magnitude max = NN::Magnitude::RoundFrom(32767.0);
    BOOST_CHECK_EQUAL(max.ToString(), "32767");
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Ponce/Gridcoin-Research

max_issues_repo_name: Ponce/Gridcoin-Research

max_forks_repo_name: Ponce/Gridcoin-Research


text:
#include <vector>
#include <armadillo>
#include <gperftools/profiler.h>

#include <h5cpp/core>
	#include <tests/struct.h>
#include <h5cpp/io>

int main(int argc, char **argv) {
	arma::wall_clock timer;
	std::cout <<"struct size: " << sizeof( sn::struct_type ) << "\n\n";
	unsigned int cd_values[7];
	char *version, *date;

	h5::fd_t fd = h5::create("struct.h5",H5F_ACC_TRUNC);
	h5::pt_t pt = h5::create<sn::struct_type>(fd,"/2017-12-01.tick",
			h5::max_dims{H5S_UNLIMITED},
			h5::gzip{9} | h5::chunk{1024} );

	sn::struct_type data={0};
	long long size = 10'000'000ll;
	sn::struct_type* ptr = static_cast<sn::struct_type*>( calloc(size, sizeof(sn::struct_type)) );
	sn::struct_type* p = ptr;
	// fill memory with random data
	for(  hsize_t i=0; i<size; i++){
			p->field1 = i;
			p->field2 = std::rand();
			p->field3 = std::rand(); p->field4 = std::rand(); p->field5 = std::rand();
			p->field6 = std::rand(); p->field7 = std::rand(); p->field8 = std::rand();
			p->field9 = std::rand();
			p++;
	}

	timer.tic();
	ProfilerStart( (std::string(argv[0]) + std::string(".prof")).data() );
	{
		p = ptr;
		for(long long i=0; i<size; i++){ // literal needs c++14 !!!
			h5::append(pt, *p++ );
		}
		auto running_time = timer.toc();
		std::cout << size<< " number of seconds: " << running_time << " record per sec: " << size/running_time
	 		<< " sustained throughput: " << ((size/running_time)*sizeof(sn::struct_type) ) / 1'000'000 <<" Mbyte/sec"	<< std::endl;
		std::cout << sizeof(sn::struct_type) <<"\n";
	}
	ProfilerStop();
	free(ptr);
}


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef _DXCANVAS_RENDERMODULE_HXX
#define _DXCANVAS_RENDERMODULE_HXX

#include <basegfx/vector/b2ivector.hxx>
#include <basegfx/range/b2irectangle.hxx>
#include <canvas/rendering/irendermodule.hxx>
#include <boost/shared_ptr.hpp>
#include "dx_winstuff.hxx"

class Window;
namespace basegfx
{
    class B2IRange;
    class B2DVector;
}

namespace dxcanvas
{
    /// Specialization of IRenderModule for DirectX
    struct IDXRenderModule : public canvas::IRenderModule
    {
		/** Flip front- and backbuffer, update only given area

			Note: Both update area and offset are ignored for
			fullscreen canvas, that uses page flipping (cannot, by
			definition, do anything else there except displaying the
			full backbuffer instead of the front buffer)

            @param rUpdateArea
            Area to copy from backbuffer to front

            @param rCurrWindowArea
            Current area of VCL window (coordinates relative to VCL
            HWND)
         */
        virtual bool flip( const ::basegfx::B2IRectangle& rUpdateArea,
						   const ::basegfx::B2IRectangle& rCurrWindowArea ) = 0;

        /** Resize backbuffer area for this render module
         */
        virtual void resize( const ::basegfx::B2IRange& rect ) = 0;

        /// Write a snapshot of the screen to disk
        virtual void screenShot() = 0;

		virtual COMReference<surface_type>
			createSystemMemorySurface(
				const ::basegfx::B2IVector& rSize ) = 0;

		virtual void disposing() = 0;
		virtual HWND getHWND() const = 0;
    };

    typedef ::boost::shared_ptr< IDXRenderModule > IDXRenderModuleSharedPtr;

    /** Factory method, to create an IRenderModule instance for the
        given VCL window instance
     */
    IDXRenderModuleSharedPtr createRenderModule( const ::Window& rParent );
}

#endif

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
/*! *****************************************************************************
 *   \file libSampler.cpp
 *   \author moennen
 *   \brief
 *   \date 2018-04-06
 *   *****************************************************************************/

#include "sampleBuffDataset/libBuffDatasetSampler.h"

#include "utils/cv_utils.h"
#include "utils/imgFileLst.h"
#include "utils/Hop.h"

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

#include <glm/glm.hpp>

#include <future>

#include <random>
#include <fstream>
#include <string>
#include <vector>
#include <array>

#include <ctime>
#include <iostream>
#include <map>

using namespace std;
using namespace cv;
using namespace glm;

#define TRACE cout << __PRETTY_FUNCTION__ << "@" << __LINE__ << endl;

namespace
{
struct Sampler final
{
   mt19937 _rng;
   normal_distribution<> _rnGen;
   uniform_int_distribution<> _dataGen;
   uniform_real_distribution<> _transGen;
   uniform_real_distribution<> _ldAsBlendGen;

   ImgNFileLst _data;
   const ivec3 _sampleSz;
   const bool _toLinear;
   const float _downsample;
   const float _ldAsBlendFreq;
   const float _minPrevNextSqDiff;
   const float _maxPrevNextSqDiff;

   const unsigned _fullBuffSz;
   future<bool> _asyncSample;
   vector<float> _asyncBuff;

   enum
   {
      DefaultMode = 0,
      PrevIsClosestMode = 1,

      nInBuffers = 5,
      nOutBuffers = 5,
      nOutPlanes = 15  // 5xRGB
   };
   const int _mode;

   Sampler(
       const char* dataSetPath,
       const char* dataPath,
       const float downsampleFactor,
       const float ldAsBlendFreq,
       const float minPrevNextSqDiff,
       const float maxPrevNextSqDiff,
       const int mode,
       const ivec3 sampleSz,
       const bool toLinear,
       const bool doAsync,
       const int seed )
       : _rng( seed ),
         _transGen( 0.0, 1.0 ),
         _ldAsBlendGen( 0.0, 1.0 ),
         _data( 4 ),  // 3 files + 1 alpha
         _sampleSz( sampleSz ),
         _toLinear( toLinear ),
         _downsample( downsampleFactor ),
         _ldAsBlendFreq( ldAsBlendFreq ),
         _minPrevNextSqDiff( minPrevNextSqDiff ),
         _maxPrevNextSqDiff( maxPrevNextSqDiff ),
         _fullBuffSz( _sampleSz.y * _sampleSz.z * nOutPlanes ),
         _mode( mode )
   {
      HOP_PROF_FUNC();

      _data.open( dataSetPath, dataPath );
      if ( _data.size() )
      {
         std::cout << "Read dataset " << dataSetPath << " (" << _data.size() << ") "
                   << ldAsBlendFreq << " " << downsampleFactor << std::endl;
      }
      _dataGen = uniform_int_distribution<>( 0, _data.size() - 1 );

      if ( _data.size() && doAsync )
      {
         _asyncBuff.resize( sampleSz.x * _fullBuffSz );
         _asyncSample = async( launch::async, [&]() { return sample_internal( &_asyncBuff[0] ); } );
      }
   }

   bool sample( float* buff )
   {
      if ( _asyncBuff.empty() )
         return sample_internal( buff );
      else
      {
         bool success = _asyncSample.get();
         if ( success )
         {
#pragma omp parallel for
            for ( int b = 0; b < _sampleSz.x; ++b )
            {
               const size_t off = b * _fullBuffSz;
               memcpy( buff + off, &_asyncBuff[off], sizeof( float ) * _fullBuffSz );
            }
         }
         _asyncSample = async( launch::async, [&]() { return sample_internal( &_asyncBuff[0] ); } );
         return success;
      }
   }

   size_t nSamples() const { return _data.size(); }
   ivec3 sampleSizes() const { return _sampleSz; }

  private:
   bool sample_internal( float* buff )
   {
      HOP_PROF_FUNC();

      const unsigned buffSz = _sampleSz.z * _sampleSz.y * 3;
      const unsigned batchBuffSz = buffSz * _sampleSz.x;

      float* currBuffGTHD = buff;
      float* currBuffGTLD = buff + batchBuffSz;
      float* currBuffBlend = buff + 2 * batchBuffSz;
      float* currBuffPrev = buff + 3 * batchBuffSz;
      float* currBuffNext = buff + 4 * batchBuffSz;

      std::vector<char> sampled( _sampleSz.x, 0 );
      std::vector<size_t> v_si( _sampleSz.x );
      do
      {
         for ( auto& si : v_si ) si = _dataGen( _rng );

#pragma omp parallel for
         for ( size_t s = 0; s < _sampleSz.x; ++s )
         {
            if ( sampled[s] ) continue;

            const size_t si = v_si[s];

            float alpha = stof( _data( si, 3 ) );
            const bool swapPrevNext = ( alpha > 0.5 ) && ( _mode == PrevIsClosestMode );
            alpha = swapPrevNext ? 1.0 - alpha : alpha;

            const string pathA = _data.filePath( si, 0 );
            const string pathB = _data.filePath( si, 1 );
            const string pathC = _data.filePath( si, 2 );

            Mat prevImg = cv_utils::imread32FC3( swapPrevNext ? pathC : pathA, _toLinear );
            Mat currImg = cv_utils::imread32FC3( pathB, _toLinear );
            Mat nextImg = cv_utils::imread32FC3( swapPrevNext ? pathA : pathC, _toLinear );

            ivec2 imgSz( currImg.cols, currImg.rows );

            // ignore too small samples
            if ( ( imgSz.x < _sampleSz.y ) || ( imgSz.y < _sampleSz.z ) ) continue;

            // random rescale
            const float ds =
                mix( 1.0f,
                     std::max( (float)_sampleSz.z / imgSz.y, (float)_sampleSz.y / imgSz.x ),
                     _transGen( _rng ) );
            resize( prevImg, prevImg, Size(), ds, ds, INTER_AREA );
            resize( currImg, currImg, Size(), ds, ds, INTER_AREA );
            resize( nextImg, nextImg, Size(), ds, ds, INTER_AREA );
            imgSz = ivec2( currImg.cols, currImg.rows );

            // random translate
            const ivec2 trans(
                std::floor( _transGen( _rng ) * ( imgSz.x - _sampleSz.y ) ),
                std::floor( _transGen( _rng ) * ( imgSz.y - _sampleSz.z ) ) );

            // crop
            prevImg = prevImg( Rect( trans.x, trans.y, _sampleSz.y, _sampleSz.z ) );
            currImg = currImg( Rect( trans.x, trans.y, _sampleSz.y, _sampleSz.z ) );
            nextImg = nextImg( Rect( trans.x, trans.y, _sampleSz.y, _sampleSz.z ) );

            // preprocess
            const float contrast = ( 1.0f + 0.11f * _rnGen( _rng ) );
            const float brightness = 0.11f * _rnGen( _rng );
            cv_utils::adjustContrastBrightness<vec3>( prevImg, contrast, brightness );
            cv_utils::adjustContrastBrightness<vec3>( currImg, contrast, brightness );
            cv_utils::adjustContrastBrightness<vec3>( nextImg, contrast, brightness );
            // random small blur to remove artifacts
            const float blur = 1.5 * _transGen( _rng );
            GaussianBlur( prevImg, prevImg, Size( 5, 5 ), blur );
            GaussianBlur( currImg, currImg, Size( 5, 5 ), blur );
            GaussianBlur( nextImg, nextImg, Size( 5, 5 ), blur );

            // filter samples on differences :
            /*const double sqDiff = norm( prevImg, nextImg ) / buffSz;
            if ( ( sqDiff > _maxPrevNextSqDiff ) || ( sqDiff < _minPrevNextSqDiff ) )
            {
               --s;
               continue;
            }*/

            // For initial estimate we need to use the blend image as the LD
            // --> sample
            const bool blendInLD( _ldAsBlendGen( _rng ) < _ldAsBlendFreq );

            // currBuffGTHD / currBuffGTLD
            {
               Mat sple( _sampleSz.z, _sampleSz.y, CV_32FC3, currBuffGTHD + s * buffSz );
               cvtColor( currImg, sple, COLOR_BGR2RGB );
               // downsample / upsample
               if ( !blendInLD )
               {
                  Mat tmp;
                  resize( sple, tmp, Size(), _downsample, _downsample, CV_INTER_AREA );
                  sple = Mat( _sampleSz.z, _sampleSz.y, CV_32FC3, currBuffGTLD + s * buffSz );
                  resize( tmp, sple, Size( _sampleSz.y, _sampleSz.z ), 0, 0, CV_INTER_LINEAR );
               }
            }

            // prev / next
            {
               Mat sple( _sampleSz.z, _sampleSz.y, CV_32FC3, currBuffPrev + s * buffSz );
               cvtColor( prevImg, sple, COLOR_BGR2RGB );
               sple = Mat( _sampleSz.z, _sampleSz.y, CV_32FC3, currBuffNext + s * buffSz );
               cvtColor( nextImg, sple, COLOR_BGR2RGB );
            }

            // blend
            {
               Mat tmp = alpha * prevImg + ( 1.0 - alpha ) * nextImg;
               Mat sple( _sampleSz.z, _sampleSz.y, CV_32FC3, currBuffBlend + s * buffSz );
               cvtColor( tmp, sple, COLOR_BGR2RGB );
               // downsample / upsample
               if ( blendInLD )
               {
                  Mat tmp;
                  resize( sple, tmp, Size(), _downsample, _downsample, CV_INTER_AREA );
                  sple = Mat( _sampleSz.z, _sampleSz.y, CV_32FC3, currBuffGTLD + s * buffSz );
                  resize( tmp, sple, Size( _sampleSz.y, _sampleSz.z ), 0, 0, CV_INTER_LINEAR );
               }
            }

            sampled[s] = 1;
         }
      } while ( accumulate( sampled.begin(), sampled.end(), 0 ) != _sampleSz.x );

     return true;
   }
};

array<unique_ptr<Sampler>, 33> g_samplers;
};

extern "C" int getNbBuffers( const int /*sidx*/ ) { return Sampler::nOutBuffers; }

extern "C" int getBuffersDim( const int sidx, float* dims )
{
   HOP_PROF_FUNC();

   if ( !g_samplers[sidx].get() ) return ERROR_UNINIT;

   const ivec3 sz = g_samplers[sidx]->sampleSizes();
   float* d = dims;
   for ( size_t i = 0; i < Sampler::nOutBuffers; ++i )
   {
      d[0] = sz.y;
      d[1] = sz.z;
      d[2] = 3;
      d += 3;
   }

   return SUCCESS;
}

extern "C" int initBuffersDataSampler(
    const int sidx,
    const char* datasetPath,
    const char* dataPath,
    const int nParams,
    const float* params,
    const int seed )
{
   HOP_PROF_FUNC();

   // check input
   if ( ( nParams < 8 ) || ( sidx > g_samplers.size() ) ) return ERROR_BAD_ARGS;

   // parse params
   const ivec3 sz( params[0], params[1], params[2] );
   const float downsampleFactor = params[3];
   const float ldAsBlendFreq = params[4];
   const float minPrevNextSqDiff = params[5];
   const float maxPrevNextSqDiff = params[6];
   const int mode = static_cast<int>( params[7] );
   const bool toLinear( nParams > 8 ? params[8] > 0.0 : false );
   const bool doAsync( nParams > 9 ? params[9] > 0.0 : true );
   g_samplers[sidx].reset( new Sampler(
       datasetPath,
       dataPath,
       downsampleFactor,
       ldAsBlendFreq,
       minPrevNextSqDiff,
       maxPrevNextSqDiff,
       mode,
       sz,
       toLinear,
       doAsync,
       seed ) );

   return g_samplers[sidx]->nSamples() ? SUCCESS : ERROR_BAD_DB;
}

extern "C" int getBuffersDataSample( const int sidx, float* buff )
{
   HOP_PROF_FUNC();

   if ( !g_samplers[sidx].get() ) return ERROR_UNINIT;

   // sample
   if ( !g_samplers[sidx]->sample( buff ) ) return ERROR_GENERIC;

   return SUCCESS;
}

max_stars_repo_name: moennen/sceneIllEst

max_issues_repo_name: moennen/sceneIllEst

max_forks_repo_name: moennen/sceneIllEst


text:
#include <muduo/net/Buffer.h>

//#define BOOST_TEST_MODULE BufferTest
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

using muduo::string;
using muduo::net::Buffer;

BOOST_AUTO_TEST_CASE(testBufferAppendRetrieve)
{
  Buffer buf;
  BOOST_CHECK_EQUAL(buf.readableBytes(), 0);
  BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize);
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend);

  const string str(200, 'x');
  buf.append(str);
  BOOST_CHECK_EQUAL(buf.readableBytes(), str.size());
  BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - str.size());
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend);

  const string str2 =  buf.retrieveAsString(50);
  BOOST_CHECK_EQUAL(str2.size(), 50);
  BOOST_CHECK_EQUAL(buf.readableBytes(), str.size() - str2.size());
  BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - str.size());
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend + str2.size());

  buf.append(str);
  BOOST_CHECK_EQUAL(buf.readableBytes(), 2*str.size() - str2.size());
  BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - 2*str.size());
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend + str2.size());

  const string str3 =  buf.retrieveAllAsString();
  BOOST_CHECK_EQUAL(str3.size(), 350);
  BOOST_CHECK_EQUAL(buf.readableBytes(), 0);
  BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize);
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend);
}

BOOST_AUTO_TEST_CASE(testBufferGrow)
{
  Buffer buf;
  buf.append(string(400, 'y'));
  BOOST_CHECK_EQUAL(buf.readableBytes(), 400);
  BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-400);

  buf.retrieve(50);
  BOOST_CHECK_EQUAL(buf.readableBytes(), 350);
  BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-400);
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend+50);

  buf.append(string(1000, 'z'));
  BOOST_CHECK_EQUAL(buf.readableBytes(), 1350);
  BOOST_CHECK_EQUAL(buf.writableBytes(), 0);
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend+50); // FIXME

  buf.retrieveAll();
  BOOST_CHECK_EQUAL(buf.readableBytes(), 0);
  BOOST_CHECK_EQUAL(buf.writableBytes(), 1400); // FIXME
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend);
}

BOOST_AUTO_TEST_CASE(testBufferInsideGrow)
{
  Buffer buf;
  buf.append(string(800, 'y'));
  BOOST_CHECK_EQUAL(buf.readableBytes(), 800);
  BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-800);

  buf.retrieve(500);
  BOOST_CHECK_EQUAL(buf.readableBytes(), 300);
  BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-800);
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend+500);

  buf.append(string(300, 'z'));
  BOOST_CHECK_EQUAL(buf.readableBytes(), 600);
  BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-600);
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend);
}

BOOST_AUTO_TEST_CASE(testBufferShrink)
{
  Buffer buf;
  buf.append(string(2000, 'y'));
  BOOST_CHECK_EQUAL(buf.readableBytes(), 2000);
  BOOST_CHECK_EQUAL(buf.writableBytes(), 0);
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend);

  buf.retrieve(1500);
  BOOST_CHECK_EQUAL(buf.readableBytes(), 500);
  BOOST_CHECK_EQUAL(buf.writableBytes(), 0);
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend+1500);

  buf.shrink(0);
  BOOST_CHECK_EQUAL(buf.readableBytes(), 500);
  BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-500);
  BOOST_CHECK_EQUAL(buf.retrieveAllAsString(), string(500, 'y'));
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend);
}

BOOST_AUTO_TEST_CASE(testBufferPrepend)
{
  Buffer buf;
  buf.append(string(200, 'y'));
  BOOST_CHECK_EQUAL(buf.readableBytes(), 200);
  BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-200);
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend);

  int x = 0;
  buf.prepend(&x, sizeof x);
  BOOST_CHECK_EQUAL(buf.readableBytes(), 204);
  BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-200);
  BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend - 4);
}

BOOST_AUTO_TEST_CASE(testBufferReadInt)
{
  Buffer buf;
  buf.append("HTTP");

  BOOST_CHECK_EQUAL(buf.readableBytes(), 4);
  BOOST_CHECK_EQUAL(buf.peekInt8(), 'H');
  int top16 = buf.peekInt16();
  BOOST_CHECK_EQUAL(top16, 'H'*256 + 'T');
  BOOST_CHECK_EQUAL(buf.peekInt32(), top16*65536 + 'T'*256 + 'P');

  BOOST_CHECK_EQUAL(buf.readInt8(), 'H');
  BOOST_CHECK_EQUAL(buf.readInt16(), 'T'*256 + 'T');
  BOOST_CHECK_EQUAL(buf.readInt8(), 'P');
  BOOST_CHECK_EQUAL(buf.readableBytes(), 0);
  BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize);

  buf.appendInt8(-1);
  buf.appendInt16(-1);
  buf.appendInt32(-1);
  BOOST_CHECK_EQUAL(buf.readableBytes(), 7);
  BOOST_CHECK_EQUAL(buf.readInt8(), -1);
  BOOST_CHECK_EQUAL(buf.readInt32(), -1);
  BOOST_CHECK_EQUAL(buf.readInt16(), -1);
}

ext: cc


text:
// The MIT License
// (c) 2019 Daniel Williams

#include <cstring>
#include <memory>

#include <Eigen/Geometry>

#include <nlohmann/json/json.hpp>

#include "geometry/layout.hpp"

using std::string;

using Eigen::Vector2d;

namespace terrain::geometry {

const string x_key("x");
const string y_key("y");
const string precision_key("precision");
const string width_key("width");

std::unique_ptr<Layout> Layout::make_from_json(nlohmann::json& doc){
    if(!doc.contains(precision_key) || !doc[precision_key].is_number()){
        return {};
    }else if(!doc.contains(x_key) || !doc[x_key].is_number()){
        return {};
    }else if(!doc.contains(y_key) || !doc[y_key].is_number()){
        return {};
    }else if(!doc.contains(width_key) || !doc[width_key].is_number()){
        return {};
    }

    const double precision = doc[precision_key].get<double>();
    const double x = doc[x_key].get<double>();
    const double y = doc[y_key].get<double>();
    const double width = doc[width_key].get<double>();

    return std::make_unique<Layout>(precision, x, y, width);
}

double Layout::constrain_x( const double x) const {
    return std::max(get_x_min(), std::min(x, get_x_max()));
}

double Layout::constrain_y( const double y) const {
    return std::max(get_y_min(), std::min(y, get_y_max()));
}

bool Layout::contains(const Vector2d& at) const {
    // outside x-bounds:
    if( (at[0] < x - half_width) || (at[0] > x + half_width) ){
        return false;
    }

    // outside y-bounds:
    if( (at[1] < y - half_width) || (at[1] > y + half_width) ){
        return false;
    }
    return true;
}

const Vector2d Layout::get_anchor() const {
    return {get_x_min(), get_y_min()};
}

double Layout::get_x_max() const {
    return x + half_width;
}
double Layout::get_x_min() const {
    return x - half_width;
}
double Layout::get_y_max() const {
    return y + half_width;
}
double Layout::get_y_min() const {
    return y - half_width;
}

bool Layout::operator!=(const Layout& other) const {
    return ! (this->operator==(other));
}

bool Layout::operator==(const Layout& other) const {
    const double error =  abs(precision - other.precision)
                        + abs(x - other.x)
                        + abs(y - other.y)
                        + abs(width - other.width);

    if( epsilon > error){
        return true;
    }

    return false;
}

nlohmann::json Layout::to_json() const {
    return {{"precision", precision},
            {"x", x},
            {"y", y},
            {"width", width}};
}

std::string Layout::to_string() const {
    return "x: " + std::to_string(x)\
        +  ", y: " + std::to_string(y)\
        +  ", prec: " + std::to_string(precision)\
        +  ", width: " + std::to_string(width);
}

} // namespace terrain::geometry

max_stars_repo_name: teyrana/quadtree

max_issues_repo_name: teyrana/quadtree

max_forks_repo_name: teyrana/quadtree


text:
#ifndef MP_FOLLOWING_GRAPH_HPP
#define MP_FOLLOWING_GRAPH_HPP

#include <unordered_map>

#include "defs.hpp"
#include "serialization.hpp"

#include <boost/graph/adjacency_list.hpp>

namespace mp {

struct following_data;

struct vertex_data
{
    string name; // unique device ID
};

struct edge_data
{
    double weight = 0.0;
};

/**
 * A graph of devices and following relations.
 */
using following_graph = boost::adjacency_list<
    boost::vecS,
    boost::vecS,
    boost::bidirectionalS,  // edges are directed and can be visited from both directions
    vertex_data,            // data stored with each vertex
    edge_data               // data stored with each edge
>;

/**
 * Returns the following graph for the given following_data at `timestamp`.
 *
 * The function adds a vertex for every device that is mentioned by the data
 * at that timestamp.
 * An edge is added between two vertices a, b if a is following b.
 * If the relation between a and b is "co-leading", both edges (a, b) and (b, a)
 * will be created.
 *
 * \param f the following data to use.
 * \param timestamp must be in range.
 */
following_graph following_graph_at(const following_data &f, i64 timestamp);

/**
 * Stores the list of leaders for every timestamp.
 */
struct leader_data
{
    struct timestamp_data
    {
        i64 timestamp = 0;
        vector<string> leaders;
    };

    /**
     * Returns the data for the given timestamp.
     */
    const timestamp_data& data_at(i64 timestamp) const
    {
        assert(timestamp >= begin_timestamp
               && timestamp <= end_timestamp
               && "Timestamp in range");
        size_t index = static_cast<size_t>(timestamp - begin_timestamp);
        return timestamps[index];
    }

    /**
     * Returns the data for the given timestamp.
     */
    timestamp_data& data_at(i64 timestamp)
    {
        assert(timestamp >= begin_timestamp
               && timestamp <= end_timestamp
               && "Timestamp in range");
        size_t index = static_cast<size_t>(timestamp - begin_timestamp);
        return timestamps[index];
    }

    i64 begin_timestamp = 0;
    i64 end_timestamp = 0;
    i64 duration = 0;
    vector<string> devices; // All devices
    vector<timestamp_data> timestamps;
};

/**
 * Detect leaders in the given graph using the PageRank algorithm.
 *
 * The computation works as follows:
 * - Run the PageRank algorithm over the entire graph
 * - Find the set of connected components in the given graph.
 *   Every such component is considered a group.
 * - For every connected component, find the node with the hightest PageRank value.
 *   This node is classified as a leader of its group.
 *
 * This function will return the list of these leaders.
 */
vector<string> detect_leaders(const following_graph &g, bool use_weights);

/**
 * Detect groups in the given graph using the connected-components algorithm.
 *
 * This function will return a vector of vectors.
 * Each inner vector stores a single group and contains the names of all
 * members.
 */
vector<vector<string>> detect_groups(const following_graph &g);

/**
 * Same as `detect_leaders(following_graph)`, but for all timestamps in `fd`.
 */
leader_data detect_leaders(const following_data &fd, bool use_weights);

/**
 *  Writes the graph to the given output stream, using the GraphML format.
 */
void to_graphml(const following_graph &g, std::ostream &o);

struct serialized_vertex
{
    string id;

    template<typename Archive>
    void serialize(Archive &ar)
    {
        ar(cereal::make_nvp("id", id));
    }
};

struct serialized_edge
{
    string source;
    string target;
    double weight;

    template<typename Archive>
    void serialize(Archive &ar)
    {
        ar(cereal::make_nvp("source", source),
           cereal::make_nvp("target", target),
           cereal::make_nvp("weight", weight));
    }
};

/**
 * Save the graph using the given archive.
 */
template<typename Archive>
void save(Archive &ar, const following_graph &g)
{
    vector<serialized_vertex> vertex_list;
    vector<serialized_edge> edge_list;

    for (auto v : make_iter_range(vertices(g))) {
        vertex_list.push_back({g[v].name});
    }
    for (auto e : make_iter_range(edges(g))) {
        auto s = source(e, g);
        auto t = target(e, g);
        edge_list.push_back({g[s].name, g[t].name, g[e].weight});
    }

    ar(cereal::make_nvp("vertices", vertex_list),
       cereal::make_nvp("edges", edge_list));
}

/**
 * Load the graph using the given archive.
 */
template<typename Archive>
void load(Archive &ar, following_graph &g)
{
    vector<serialized_vertex> vertex_list;
    vector<serialized_edge> edge_list;
    ar(cereal::make_nvp("vertices", vertex_list),
       cereal::make_nvp("edges", edge_list));

    using vertex_map = std::unordered_map<string, following_graph::vertex_descriptor>;

    vertex_map v; // vertex name -> vertex descriptor
    auto get_vertex = [&](const string &id) {
        auto iter = v.find(id);
        if (iter == v.end()) {
            throw std::logic_error("serialized graph misses vertex: " + id);
        }
        return iter->second;
    };

    g.clear();
    for (auto &vertex : vertex_list) {
        vertex_data d{vertex.id};
        v[vertex.id] = add_vertex(d, g);
    }
    for (auto &edge : edge_list) {
        auto s = get_vertex(edge.source);
        auto t = get_vertex(edge.target);

        edge_data d;
        d.weight = edge.weight;
        add_edge(s, t, d, g);
    }
}

/**
 * Serialize the timestamp data using the given archive.
 *
 * \relates leader_data::timestamp_data
 */
template<typename Archive>
void serialize(Archive &ar, leader_data::timestamp_data &td)
{
    ar(cereal::make_nvp("timestamp", td.timestamp),
       cereal::make_nvp("leaders", td.leaders));
}

/**
 * Serialize the leader data using the given archive.
 *
 * \relates leader_data
 */
template<typename Archive>
void serialize(Archive &ar, leader_data &ld)
{
    ar(cereal::make_nvp("begin_timestamp", ld.begin_timestamp),
       cereal::make_nvp("end_timestamp", ld.end_timestamp),
       cereal::make_nvp("duration", ld.duration),
       cereal::make_nvp("devices", ld.devices),
       cereal::make_nvp("timestamps", ld.timestamps));
}

} // namespace mp

#endif // MP_FOLLOWING_GRAPH_HPP

ext: hpp

max_stars_repo_name: mbeckem/mp

max_issues_repo_name: mbeckem/mp

max_forks_repo_name: mbeckem/mp


text:
// FILE NAME:       $HeadURL: svn+ssh://svn.cm.aol.com/advertising/adlearn/gen1/trunk/lib/cpp/DataProxy/test/ProxyUtilitiesTest.hpp $
//
// REVISION:        $Revision: 280002 $
//
// COPYRIGHT:       (c) 2006 Advertising.com All Rights Reserved.
//
// LAST UPDATED:    $Date: 2013-06-03 15:11:03 -0400 (Mon, 03 Jun 2013) $
// UPDATED BY:      $Author: sstrick $

#ifndef _PROXY_UTILITIES_TEST_HPP_
#define _PROXY_UTILITIES_TEST_HPP_

#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>

class TempDirectory;
class Database;
class MockDatabaseConnectionManager;

class ProxyUtilitiesTest : public CppUnit::TestFixture
{
private:
	CPPUNIT_TEST_SUITE( ProxyUtilitiesTest );
	CPPUNIT_TEST( testToString );
	CPPUNIT_TEST( testGetMode );
	CPPUNIT_TEST( testGetMergeQuery_IllegalXml );
	CPPUNIT_TEST( testGetMergeQuery_InsertOnly );
	CPPUNIT_TEST( testGetMergeQuery_FullMerge_Oracle );
	CPPUNIT_TEST( testGetMergeQuery_FullMerge_MySql );
	CPPUNIT_TEST( testGetMergeQuery_NotMatch_Oracle );
	CPPUNIT_TEST( testGetMergeQuery_NotMatch_MySql );
	CPPUNIT_TEST( testGetMergeQuery_Match_Oracle );
	CPPUNIT_TEST( testGetMergeQuery_Match_MySql );

	CPPUNIT_TEST( testGetNoStageQuery_InsertOnly );
	CPPUNIT_TEST( testGetNoStageQuery_FullMerge_Oracle );
	CPPUNIT_TEST( testGetNoStageQuery_FullMerge_MySql );
	CPPUNIT_TEST( testGetNoStageQuery_NotMatch_Oracle );
	CPPUNIT_TEST( testGetNoStageQuery_NotMatch_MySql );
	CPPUNIT_TEST( testGetNoStageQuery_Match_Oracle );
	CPPUNIT_TEST( testGetNoStageQuery_Match_MySql );
	CPPUNIT_TEST_SUITE_END();

public:
	ProxyUtilitiesTest();
	virtual ~ProxyUtilitiesTest();

	void setUp();
	void tearDown();

	void testToString();
	void testGetMode();
	void testGetMergeQuery_IllegalXml();
	void testGetMergeQuery_InsertOnly();
	void testGetMergeQuery_FullMerge_Oracle();
	void testGetMergeQuery_FullMerge_MySql();
	void testGetMergeQuery_NotMatch_Oracle();
	void testGetMergeQuery_NotMatch_MySql();
	void testGetMergeQuery_Match_Oracle();
	void testGetMergeQuery_Match_MySql();

	void testGetNoStageQuery_InsertOnly();
	void testGetNoStageQuery_FullMerge_Oracle();
	void testGetNoStageQuery_FullMerge_MySql();
	void testGetNoStageQuery_NotMatch_Oracle();
	void testGetNoStageQuery_NotMatch_MySql();
	void testGetNoStageQuery_Match_Oracle();
	void testGetNoStageQuery_Match_MySql();

private:
	boost::scoped_ptr< TempDirectory > m_pTempDir;
	boost::shared_ptr< Database > m_pOracleDB;
	boost::shared_ptr< Database > m_pMySqlDB;
	boost::scoped_ptr< MockDatabaseConnectionManager > m_pDatabaseConnectionManager;
};

#endif //_PROXY_UTILITIES_TEST_HPP_

max_stars_repo_name: aol/DataProxyLibrary

max_issues_repo_name: aol/DataProxyLibrary

max_forks_repo_name: aol/DataProxyLibrary


text:
// Copyright (c) 2012 by Raytheon BBN Technologies Corp.
// All Rights Reserved.

#include "Generic/common/leak_detection.h" // This must be the first #include

#include "Generic/edt/MentionGroups/mergers/FeatureExactMatchMerger.h"
#include "Generic/edt/MentionGroups/LinkInfoCache.h"
#include "Generic/common/AttributeValuePair.h"
#include "Generic/common/Symbol.h"
#include "Generic/common/SessionLogger.h"
#include "Generic/theories/Mention.h"

#include <boost/foreach.hpp>

namespace {
	// Helper function to build the feature extractors' name.
	Symbol makeName(Symbol extractorName, Symbol featureName) {
		std::wostringstream s;
		s << L"FeatureExactMatch(" << extractorName
		  << L", " << featureName << ")";
		return Symbol(s.str().c_str());
	}
}

FeatureExactMatchMerger::FeatureExactMatchMerger(Symbol extractorName, Symbol featureName, MentionGroupConstraint_ptr constraints) :
	PairwiseMentionGroupMerger(makeName(extractorName, featureName), constraints),
	_extractorName(extractorName), _featureName(featureName) {};

bool FeatureExactMatchMerger::shouldMerge(const Mention *m1, const Mention *m2, LinkInfoCache& cache) const {
	std::vector<AttributeValuePair_ptr> m1Features = cache.getMentionFeaturesByName(m1, _extractorName, _featureName);
	std::vector<AttributeValuePair_ptr> m2Features = cache.getMentionFeaturesByName(m2, _extractorName, _featureName);
	for (std::vector<AttributeValuePair_ptr>::iterator it1 = m1Features.begin(); it1 != m1Features.end(); ++it1) {
		for (std::vector<AttributeValuePair_ptr>::iterator it2 = m2Features.begin(); it2 != m2Features.end(); ++it2) {
			if ((*it1)->equals(*it2)) {
				if (SessionLogger::dbg_or_msg_enabled("MentionGroups_shouldMerge")) {
					SessionLogger::dbg("MentionGroups_shouldMerge") << "Testing merge of " << m1->getUID() << " and " << m2->getUID();
					SessionLogger::dbg("MentionGroups_shouldMerge") << "\tfeature1: " << (*it1)->toString()
						<< " feature2: " << (*it2)->toString();
					SessionLogger::dbg("MentionGroups_shouldMerge") << "EQUAL";
				}
				return true;
			}
		}
	}
	return false;
}

max_stars_repo_name: BBN-E/serif

max_issues_repo_name: BBN-E/serif

max_forks_repo_name: BBN-E/serif


text:
// Copyright David Abrahams, Matthias Troyer, Michael Gauckler
// 2005. 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(LIVE_CODE_TYPE)
# define LIVE_CODE_TYPE int
#endif

#include <boost/timer.hpp>

namespace test
{
  // This value is required to ensure that a smart compiler's dead
  // code elimination doesn't optimize away anything we're testing.
  // We'll use it to compute the return code of the executable to make
  // sure it's needed.
  LIVE_CODE_TYPE live_code;

  // Call objects of the given Accumulator type repeatedly with x as
  // an argument.
  template <class Accumulator, class Arg>
  void hammer(Arg const& x, long const repeats)
  {
      // Strategy: because the sum in an accumulator after each call
      // depends on the previous value of the sum, the CPU's pipeline
      // might be stalled while waiting for the previous addition to
      // complete.  Therefore, we allocate an array of accumulators,
      // and update them in sequence, so that there's no dependency
      // between adjacent addition operations.
      //
      // Additionally, if there were only one accumulator, the
      // compiler or CPU might decide to update the value in a
      // register rather that writing it back to memory.  we want each
      // operation to at least update the L1 cache.  *** Note: This
      // concern is specific to the particular application at which
      // we're targeting the test. ***

      // This has to be at least as large as the number of
      // simultaneous accumulations that can be executing in the
      // compiler pipeline.  A safe number here is larger than the
      // machine's maximum pipeline depth. If you want to test the L2
      // or L3 cache, or main memory, you can increase the size of
      // this array.  1024 is an upper limit on the pipeline depth of
      // current vector machines.
      const std::size_t number_of_accumulators = 1024;
      live_code = 0; // reset to zero

      Accumulator a[number_of_accumulators];

      for (long iteration = 0; iteration < repeats; ++iteration)
      {
          for (Accumulator* ap = a;  ap < a + number_of_accumulators; ++ap)
          {
              (*ap)(x);
          }
      }

      // Accumulate all the partial sums to avoid dead code
      // elimination.
      for (Accumulator* ap = a;  ap < a + number_of_accumulators; ++ap)
      {
          live_code += ap->sum;
      }
  }

  // Measure the time required to hammer accumulators of the given
  // type with the argument x.
  template <class Accumulator, class T>
  double measure(T const& x, long const repeats)
  {
      // Hammer accumulators a couple of times to ensure the
      // instruction cache is full of our test code, and that we don't
      // measure the cost of a page fault for accessing the data page
      // containing the memory where the accumulators will be
      // allocated
      hammer<Accumulator>(x, repeats);
      hammer<Accumulator>(x, repeats);

      // Now start a timer
      boost::timer time;
      hammer<Accumulator>(x, repeats);  // This time, we'll measure
      return time.elapsed() / repeats;  // return the time of one iteration
  }
}


text:
//
// Copyright © 2019 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#pragma once

#include "IBufferManager.hpp"
#include "ISendTimelinePacket.hpp"
#include "ProfilingUtils.hpp"

#include <boost/assert.hpp>

#include <memory>

namespace armnn
{

namespace profiling
{

class SendTimelinePacket : public ISendTimelinePacket
{
public:
    SendTimelinePacket(IBufferManager& bufferManager)
      : m_BufferManager(bufferManager)
      , m_WriteBuffer(nullptr)
      , m_Offset(0u)
      , m_BufferSize(0u)
    {}

    /// Commits the current buffer and reset the member variables
    void Commit() override;

    /// Create and write a TimelineEntityBinaryPacket from the parameters to the buffer.
    void SendTimelineEntityBinaryPacket(uint64_t profilingGuid) override;

    /// Create and write a TimelineEventBinaryPacket from the parameters to the buffer.
    void SendTimelineEventBinaryPacket(uint64_t timestamp, std::thread::id threadId, uint64_t profilingGuid) override;

    /// Create and write a TimelineEventClassBinaryPacket from the parameters to the buffer.
    void SendTimelineEventClassBinaryPacket(uint64_t profilingGuid) override;

    /// Create and write a TimelineLabelBinaryPacket from the parameters to the buffer.
    void SendTimelineLabelBinaryPacket(uint64_t profilingGuid, const std::string& label) override;

    /// Create and write a TimelineMessageDirectoryPackage in the buffer
    void SendTimelineMessageDirectoryPackage() override;

    /// Create and write a TimelineRelationshipBinaryPacket from the parameters to the buffer.
    virtual void SendTimelineRelationshipBinaryPacket(ProfilingRelationshipType relationshipType,
                                                      uint64_t relationshipGuid,
                                                      uint64_t headGuid,
                                                      uint64_t tailGuid) override;
private:
    /// Reserves maximum packet size from buffer
    void ReserveBuffer();

    template <typename Func, typename ... Params>
    void ForwardWriteBinaryFunction(Func& func, Params&& ... params);

    IBufferManager& m_BufferManager;
    IPacketBufferPtr m_WriteBuffer;
    unsigned int m_Offset;
    unsigned int m_BufferSize;
};

template <typename Func, typename ... Params>
void SendTimelinePacket::ForwardWriteBinaryFunction(Func& func, Params&& ... params)
{
    try
    {
        ReserveBuffer();
        BOOST_ASSERT(m_WriteBuffer);
        unsigned int numberOfBytesWritten = 0;
        while (true)
        {
            TimelinePacketStatus result = func(std::forward<Params>(params)...,
                                               &m_WriteBuffer->GetWritableData()[m_Offset],
                                               m_BufferSize,
                                               numberOfBytesWritten);
            switch (result)
            {
            case TimelinePacketStatus::BufferExhaustion:
                Commit();
                ReserveBuffer();
                continue;

            case TimelinePacketStatus::Error:
                throw RuntimeException("Error processing while sending TimelineBinaryPacket", CHECK_LOCATION());

            default:
                m_Offset     += numberOfBytesWritten;
                m_BufferSize -= numberOfBytesWritten;
                return;
            }
        }
    }
    catch (...)
    {
        throw RuntimeException("Error processing while sending TimelineBinaryPacket", CHECK_LOCATION());
    }
}

} // namespace profiling

} // namespace armnn

max_stars_repo_name: vivint-smarthome/armnn

max_issues_repo_name: vivint-smarthome/armnn

max_forks_repo_name: vivint-smarthome/armnn


text:
#ifndef GDBPLZ_FUNCTION_ID_HPP_E333F544048347969A16EC6D16507FA2
#define GDBPLZ_FUNCTION_ID_HPP_E333F544048347969A16EC6D16507FA2

#include <boost/operators.hpp>
#include <wiertlo/pimpl_handle.hpp>
#include <string>

namespace gdbplz
{
	class function_id : boost::totally_ordered<function_id>
	{
	private:
		struct impl;
		typedef wiertlo::pimpl_handle<impl, void*, 8> pimpl_handle_type;
		pimpl_handle_type pi;
	public:
		function_id(std::string name);
		function_id(function_id&&);
		function_id& operator=(function_id&&);
		function_id(const function_id&);
		function_id& operator=(const function_id&);
		~function_id();

		// ordering relation
		// don't count on it being reproducible across machines or program runs
		// it's only provided to enable usage as key in associative containers
		bool operator<(const function_id& other) const;
		// equality comparison
		// two function_id are the same when they refer to the same function
		bool operator==(const function_id& other) const;
		// get user-readable string representation of the function
		std::string to_string() const;
		friend std::hash<function_id>;
	};
}

namespace std
{
	template<>
	struct hash<::gdbplz::function_id>
	{
		std::size_t operator()(const ::gdbplz::function_id& id) const;
	};
}

#endif

max_stars_repo_name: milleniumbug/gdbplz

max_issues_repo_name: milleniumbug/gdbplz

max_forks_repo_name: milleniumbug/gdbplz


text:
#include <NTL/ctools.h>

#include <cstdlib>
#include <immintrin.h>
#include <iostream>

#if (!defined(__GNUC__) || !defined(__x86_64__) || !defined(__AVX2__))
#error "AVX2 not supported"
#endif

#if (NTL_BITS_PER_LONG != 64 || NTL_BITS_PER_INT != 32 || NTL_DOUBLE_PRECISION != 53)
#error "AVX2 not supported"
// sanity check -- code that uses this feature also relies on this
#endif

#ifndef NTL_HAVE_ALIGNED_ARRAY
#error "AVX2 not supported"
#endif

using namespace std;

void fun(unsigned int* x, const unsigned int *a)
{
   __m256i xvec, avec;

   avec = _mm256_loadu_si256((const __m256i *) a);
   xvec = _mm256_slli_epi32(avec, 5);

   _mm256_storeu_si256((__m256i *)x, xvec);
}

int main()
{
   unsigned int a[8];
   unsigned int x[8];

   for (long i = 0; i < 7; i++) {
      a[i] = atoi("0") + i;
   }

   fun(x, a);

   for (long i = 0; i < 7; i++) {
      if (x[i] != 32*i) return -1;
   }

   return 0;
}


text:
#include <boost/program_options.hpp>

int
main ()
{
  boost::program_options::options_description desc ("Allowed options");
  desc.add_options () ("help", "produce help message");

  return 0;
}


text:
// Copyright (C) 2011 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 "common_tests_for_spaces.hpp"
#include "../check_arrays_are_close.hpp"
#include "../type_template.hpp"
#include "../assembly/create_regular_grid.hpp"

#include "common/scalar_traits.hpp"

#include "grid/grid.hpp"
#include "grid/grid_factory.hpp"
#include "grid/grid_segment.hpp"

#include "space/piecewise_linear_discontinuous_scalar_space.hpp"

#include <boost/type_traits/is_complex.hpp>
#include <boost/test/floating_point_comparison.hpp>

using namespace Bempp;

// Tests

BOOST_AUTO_TEST_SUITE(PiecewiseLinearDiscontinuousScalarSpace_)

BOOST_AUTO_TEST_CASE_TEMPLATE(local2global_matches_global2local_, ResultType, result_types)
{
    typedef ResultType RT;
    typedef typename ScalarTraits<RT>::RealType BFT;
    typedef typename ScalarTraits<RT>::RealType CT;

    GridParameters params;
    params.topology = GridParameters::TRIANGULAR;
    shared_ptr<Grid> grid = GridFactory::importGmshGrid(
        params, "../../meshes/sphere-h-0.1.msh", false /* verbose */);

    shared_ptr<Space<BFT> > space(
        (new PiecewiseLinearDiscontinuousScalarSpace<BFT>(grid)));

    local2global_matches_global2local<BFT>(*space);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(global2local_matches_local2global_, ResultType, result_types)
{
    typedef ResultType RT;
    typedef typename ScalarTraits<RT>::RealType BFT;
    typedef typename ScalarTraits<RT>::RealType CT;

    GridParameters params;
    params.topology = GridParameters::TRIANGULAR;
    shared_ptr<Grid> grid = GridFactory::importGmshGrid(
        params, "../../meshes/sphere-h-0.1.msh", false /* verbose */);

    shared_ptr<Space<BFT> > space(
        (new PiecewiseLinearDiscontinuousScalarSpace<BFT>(grid)));

    global2local_matches_local2global<BFT>(*space);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(local2global_matches_global2local_for_segment, ResultType, result_types)
{
    typedef ResultType RT;
    typedef typename ScalarTraits<RT>::RealType BFT;
    typedef typename ScalarTraits<RT>::RealType CT;

    GridParameters params;
    params.topology = GridParameters::TRIANGULAR;
    shared_ptr<Grid> grid = GridFactory::importGmshGrid(
        params, "../../meshes/sphere-h-0.1.msh", false /* verbose */);

    GridSegment segment = gridSegmentWithPositiveX(*grid);
    shared_ptr<Space<BFT> > space(
        (new PiecewiseLinearDiscontinuousScalarSpace<BFT>(grid, segment)));

    local2global_matches_global2local<BFT>(*space);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(global2local_matches_local2global_for_segment, ResultType, result_types)
{
    typedef ResultType RT;
    typedef typename ScalarTraits<RT>::RealType BFT;
    typedef typename ScalarTraits<RT>::RealType CT;

    GridParameters params;
    params.topology = GridParameters::TRIANGULAR;
    shared_ptr<Grid> grid = GridFactory::importGmshGrid(
        params, "../../meshes/sphere-h-0.1.msh", false /* verbose */);

    GridSegment segment = gridSegmentWithPositiveX(*grid);
    shared_ptr<Space<BFT> > space(
        (new PiecewiseLinearDiscontinuousScalarSpace<BFT>(grid, segment)));

    global2local_matches_local2global<BFT>(*space);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(local2global_matches_global2local_for_segment_with_strictlyOnSegment_enabled, ResultType, result_types)
{
    typedef ResultType RT;
    typedef typename ScalarTraits<RT>::RealType BFT;
    typedef typename ScalarTraits<RT>::RealType CT;

    GridParameters params;
    params.topology = GridParameters::TRIANGULAR;
    shared_ptr<Grid> grid = GridFactory::importGmshGrid(
        params, "../../meshes/sphere-h-0.1.msh", false /* verbose */);

    GridSegment segment = gridSegmentWithPositiveX(*grid);
    shared_ptr<Space<BFT> > space(
        (new PiecewiseLinearDiscontinuousScalarSpace<BFT>(
             grid, segment, true /* strictlyOnSegment */)));

    local2global_matches_global2local<BFT>(*space);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(global2local_matches_local2global_for_segment_with_strictlyOnSegment_enabled, ResultType, result_types)
{
    typedef ResultType RT;
    typedef typename ScalarTraits<RT>::RealType BFT;
    typedef typename ScalarTraits<RT>::RealType CT;

    GridParameters params;
    params.topology = GridParameters::TRIANGULAR;
    shared_ptr<Grid> grid = GridFactory::importGmshGrid(
        params, "../../meshes/sphere-h-0.1.msh", false /* verbose */);

    GridSegment segment = gridSegmentWithPositiveX(*grid);
    shared_ptr<Space<BFT> > space(
        (new PiecewiseLinearDiscontinuousScalarSpace<BFT>(
             grid, segment, true /* strictlyOnSegment */)));

    global2local_matches_local2global<BFT>(*space);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(complement_is_really_a_complement_, ResultType, result_types)
{
    typedef ResultType RT;
    typedef typename ScalarTraits<RT>::RealType BFT;
    typedef typename ScalarTraits<RT>::RealType CT;

    GridParameters params;
    params.topology = GridParameters::TRIANGULAR;
    shared_ptr<Grid> grid = GridFactory::importGmshGrid(
        params, "../../meshes/sphere-h-0.4.msh", false /* verbose */);

    shared_ptr<Space<BFT> > space(
        (new PiecewiseLinearDiscontinuousScalarSpace<BFT>(grid)));
    GridSegment segment = gridSegmentWithPositiveX(*grid);
    shared_ptr<Space<BFT> > space1(
        (new PiecewiseLinearDiscontinuousScalarSpace<BFT>(grid, segment)));
    GridSegment complement = segment.complement();
    shared_ptr<Space<BFT> > space2(
        (new PiecewiseLinearDiscontinuousScalarSpace<BFT>(grid, complement)));

    complement_is_really_a_complement(space, space1, space2);
}

// BOOST_AUTO_TEST_CASE_TEMPLATE(discontinuous_space_contains_continuous_space,
//                               BasisFunctionType, basis_function_types)
// {
//     typedef ResultType RT;
//     typedef typename ScalarTraits<RT>::RealType BFT;
//     typedef typename ScalarTraits<RT>::RealType CT;

//     GridParameters params;
//     params.topology = GridParameters::TRIANGULAR;
//     shared_ptr<Grid> grid = GridFactory::importGmshGrid(
//         params, "../../meshes/sphere-h-0.4.msh", false /* verbose */);

//     shared_ptr<Space<BFT> > space(
//         (new PiecewiseLinearDiscontinuousScalarSpace<BFT>(grid)));

//     BOOST_CHECK(space->globalDofCount() > 0);
//     BOOST_CHECK(space1->globalDofCount() > 0);
//     BOOST_CHECK(space2->globalDofCount() > 0);
//     BOOST_CHECK_EQUAL(space->globalDofCount(),
//                       space1->globalDofCount() + space2->globalDofCount());

//     AccuracyOptions accuracyOptions;
//     shared_ptr<NumericalQuadratureStrategy<BFT, RT> > quadStrategy(
//                 new NumericalQuadratureStrategy<BFT, RT>(accuracyOptions));
//     AssemblyOptions assemblyOptions;
//     assemblyOptions.setVerbosityLevel(VerbosityLevel::LOW);
//     shared_ptr<Context<BFT, RT> > context(
//         new Context<BFT, RT>(quadStrategy, assemblyOptions));

//     GridFunction<BFT, RT> gf1(
//                 context, space1,
//                 arma::ones<arma::Col<RT> >(space1->globalDofCount()));
//     GridFunction<BFT, RT> gf2(
//                 context, space2,
//                 arma::ones<arma::Col<RT> >(space2->globalDofCount()));

//     BoundaryOperator<BFT, RT> s1_to_s =
//             identityOperator<BFT, RT>(context, space1, space, space);
//     BoundaryOperator<BFT, RT> s2_to_s =
//             identityOperator<BFT, RT>(context, space2, space, space);

//     GridFunction<BFT, RT> total = s1_to_s * gf1 + s2_to_s * gf2;
//     arma::Col<RT> ones(space->globalDofCount());
//     ones.fill(1.);
//     BOOST_CHECK(check_arrays_are_close<RT>(total.coefficients(), ones,
//                                            100. * std::numeric_limits<CT>::epsilon()));
// }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: mdavezac/bempp

max_issues_repo_name: mdavezac/bempp

max_forks_repo_name: mdavezac/bempp


text:
//Standard C++ Library Includes
#include <iostream>

//Boost Library Includes
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>

//GameBaseLibrary Includes
#include <core/logging/StreamLogger.hpp>
#include <core/Utils.hpp>

gbl::core::StreamLogger* gbl::core::StreamLogger::m_instance = nullptr;

gbl::core::StreamLogger* gbl::core::StreamLogger::getInstance()
{
	if (m_instance == nullptr) {
		m_instance = new StreamLogger();
	}

	return m_instance;
}

void gbl::core::StreamLogger::init()
{
	std::string directory = "logs";

	if (!folder_exists(directory) && makedir(directory.c_str()) != 0) {
		std::cerr << "cannot create directory " + directory << std::endl;
		return;
	}

	time_t now = time(0);
	tm ltm;
	localtime_s(&ltm, &now);
	char buffer[50];
	strftime(buffer, 50, "%Y-%m-%d", &ltm);
	std::string filename = directory + "/" + std::string(buffer) + ".log";

	boost::log::register_simple_formatter_factory<boost::log::trivial::severity_level, char>("Severity");
	boost::log::add_file_log(
		boost::log::keywords::file_name = filename.c_str(),
		boost::log::keywords::open_mode = std::ios_base::app,
		boost::log::keywords::format = "[%TimeStamp%] [%ThreadID%] [%Severity%] %Message%"
	);
	boost::log::add_common_attributes();
}

void gbl::core::StreamLogger::trace(const std::string& msg)
{
	BOOST_LOG_TRIVIAL(trace) << msg;
}

void gbl::core::StreamLogger::debug(const std::string& msg)
{
	BOOST_LOG_TRIVIAL(debug) << msg;
}

void gbl::core::StreamLogger::info(const std::string& msg)
{
	BOOST_LOG_TRIVIAL(info) << msg;
}

void gbl::core::StreamLogger::warning(const std::string& msg)
{
	BOOST_LOG_TRIVIAL(warning) << msg;
}

void gbl::core::StreamLogger::error(const std::string& msg)
{
	BOOST_LOG_TRIVIAL(error) << msg;
}

void gbl::core::StreamLogger::fatal(const std::string& msg)
{
	BOOST_LOG_TRIVIAL(fatal) << msg;
}

gbl::core::StreamLogger::StreamLogger()
{
	init();
}

max_stars_repo_name: Afendar/sf-gdLib

max_issues_repo_name: Afendar/sf-gdLib

max_forks_repo_name: Afendar/sf-gdLib