text:
// ==========================================================================
// Paradice Rules
//
// Copyright (C) 2009 Matthew Chaplain, All Rights Reserved.
// This file is covered by the MIT Licence:
//
// 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 "paradice/rules.hpp"
#include "paradice/character.hpp"
#include "paradice/client.hpp"
#include "paradice/communication.hpp"
#include "paradice/connection.hpp"
#include "paradice/dice_roll_parser.hpp"
#include "paradice/active_encounter.hpp"
#include "paradice/context.hpp"
#include "paradice/random.hpp"
#include "odin/tokenise.hpp"
#include <boost/format.hpp>
#include <map>
#include <mutex>
#include <numeric>
#include <thread>
#include <vector>

namespace paradice {

namespace {
    BOOST_STATIC_CONSTANT(odin::u32, max_encounter_rolls = 10);

    static std::map<
        std::string,           // category.
        std::vector<roll_data> // list of rolls in that category.
    > roll_category;
    std::mutex roll_category_mutex;

    static bool sort_roll_data_by_score_ascending(
        roll_data const &lhs
      , roll_data const &rhs)
    {
        return lhs.score < rhs.score;
    }

    static bool sort_roll_data_by_score_descending(
        roll_data const &lhs
      , roll_data const &rhs)
    {
        return lhs.score > rhs.score;
    }

    static std::string const DEFAULT_ATTRIBUTE   = "\\x";      // Default
    static std::string const MAXIMUM_HIT         = "\\i>\\[2!\\x"; // Bold, Green "!"
    static std::string const TOTAL_ATTRIBUTE     = "\\i>";     // Bold
}

// ==========================================================================
// DESCRIBE_DICE
// ==========================================================================
std::string describe_dice(dice_roll const &roll)
{
    std::string description;

    if (roll.repetitions_ != 1)
    {
        description += boost::str(boost::format("%d*") % roll.repetitions_);
    }

    description += boost::str(boost::format("%dd%d")
        % roll.amount_
        % roll.sides_);

    if (roll.bonus_ > 0)
    {
        description += "+";
    }

    if (roll.bonus_ != 0)
    {
        description += boost::str(boost::format("%d") % roll.bonus_);
    }

    return description;
}

// ==========================================================================
// THROW_DICE
// ==========================================================================
static dice_result throw_dice(roller const &rlr, dice_roll const &roll)
{
    dice_result result;
    result.roller_ = rlr;
    result.roll_ = roll;

    for (odin::u32 repetition = 0; repetition < roll.repetitions_; ++repetition)
    {
        std::vector<odin::s32> raw_dice;

        for (odin::u32 die = 0; die < roll.amount_; ++die)
        {
            raw_dice.push_back(random_number(1, roll.sides_));
        }

        result.results_.push_back(raw_dice);
    }

    return result;
}

// ==========================================================================
// EXECUTE_ROLL
// ==========================================================================
static void execute_roll(
    std::shared_ptr<context> &ctx
  , std::string const        &category
  , dice_roll const          &roll
  , std::shared_ptr<client>  &player
  , bool                      is_rolling_privately)
{
    if (roll.repetitions_ == 0
     || roll.amount_      == 0)
    {
        send_to_player(
            ctx
          , "You roll no dice and score nothing.\n"
          , player);

        if (!is_rolling_privately)
        {
            send_to_room(
                ctx
              , boost::str(boost::format(
                    "%s rolls no dice and scores nothing.\n")
                  % player->get_character()->get_name())
              , player);
        }

        return;
    }

    if (roll.sides_ == 0)
    {
        send_to_player(
            ctx
          , "You fumble your roll and spill all your zero-sided dice on "
            "the floor.\n"
          , player);

        if (!is_rolling_privately)
        {
            send_to_room(
                ctx
              , boost::str(boost::format(
                    "%s fumbles their roll and spills a pile of zero-"
                    "sided dice on the floor.\n")
                  % player->get_character()->get_name())
              , player);
        }

        return;
    }

    if (roll.repetitions_ * roll.amount_ > 200)
    {
        send_to_player(
            ctx
          , "You can only roll at most 200 dice at once.\n"
          , player);

        return;
    }

    dice_result result = throw_dice(player, roll);
    auto dice_description = describe_dice(roll);

    odin::s32 total_score = 0;

    std::string dice_text;

    auto const theoretical_max_roll =
        (roll.sides_ * roll.amount_) + roll.bonus_;
    auto const theoretical_max_total =
        theoretical_max_roll * roll.repetitions_;

    for (auto repetition = result.results_.begin();
         repetition != result.results_.end();
         ++repetition)
    {
        if (repetition != result.results_.begin())
        {
            dice_text += ", ";
        }

        auto const subtotal = std::accumulate(
            repetition->begin(),
            repetition->end(),
            0);
        auto const total = subtotal + roll.bonus_;

        total_score += total;

        dice_text += TOTAL_ATTRIBUTE;
        dice_text += boost::str(boost::format("%d") % total);
        dice_text += DEFAULT_ATTRIBUTE;

        if (total == theoretical_max_roll)
        {
            dice_text += MAXIMUM_HIT;
        }

        if (roll.amount_ > 1)
        {
            dice_text += " [";

            for (auto current_roll = repetition->begin();
                 current_roll != repetition->end();
                 ++current_roll)
            {
                if (current_roll != repetition->begin())
                {
                    dice_text += ", ";
                }

                dice_text += boost::str(boost::format("%d") % *current_roll);

                if (*current_roll == roll.sides_)
                {
                    dice_text += MAXIMUM_HIT;
                }
            }

            dice_text += "]";
        }

        if (!category.empty())
        {
            dice_roll temp_roll = roll;
            temp_roll.repetitions_ = 1;

            roll_data data;
            data.roller = player;
            data.name = player->get_character()->get_name();
            data.roll_text = describe_dice(temp_roll);
            data.score = total;
            data.raw_score = subtotal;
            data.max_roll = (total == theoretical_max_roll);
            roll_category[category].push_back(data);
        }
    }

    if (roll.repetitions_ != 1)
    {
        dice_text += " for a grand total of ";
        dice_text += TOTAL_ATTRIBUTE;
        dice_text += boost::str(boost::format("%d") % total_score);
        dice_text += DEFAULT_ATTRIBUTE;

        if (total_score == theoretical_max_total)
        {
            dice_text += MAXIMUM_HIT;
        }
    }

    if (total_score != theoretical_max_total)
    {
        dice_text += ".";
    }

    dice_text += "\n";

    std::string second_person_lead =
        "You roll "
      + dice_description
      + (category.empty() ? "" : ("(category: " + category + ")"))
      + " and score ";

    send_to_player(ctx, second_person_lead + dice_text, player);

    if (!is_rolling_privately)
    {
        std::string third_person_lead =
            player->get_character()->get_name()
          + " rolls "
          + dice_description
          + (category.empty() ? "" : ("(category: " + category + ")"))
          + " and scores ";
            send_to_room(ctx, third_person_lead + dice_text, player);

        auto enc = ctx->get_active_encounter();
        for (auto &entry : enc->entries_)
        {
            auto ply = boost::get<active_encounter::player>(&entry.participant_);

            if (ply != NULL)
            {
                auto ch = ply->character_.lock();

                if (ch != NULL)
                {
                    if (ch->get_name() == player->get_character()->get_name())
                    {
                        entry.roll_data_.push_back(result);

                        if (entry.roll_data_.size() > max_encounter_rolls)
                        {
                            entry.roll_data_.pop_front();
                        }

                        ctx->update_active_encounter();
                    }
                }
            }
        }
    }
}

// ==========================================================================
// PARADICE COMMAND: ROLL
// ==========================================================================
PARADICE_COMMAND_IMPL(roll)
{
    static std::string const usage_message =
        "\n Usage:   roll [n*]<dice>d<sides>[<bonuses...>] [<category>]"
        "\n Example: roll 2d6+3-20"
        "\n Example: roll 20*2d6"
        "\n Example: roll 1d10+4 initiative"
        "\n";

    auto begin = arguments.begin();
    auto end   = arguments.end();

    auto rolls = parse_dice_roll(begin, end);

    if (!rolls)
    {
        send_to_player(ctx, usage_message, player);
        return;
    }

    // Store a category if the user entered one.
    auto category = odin::tokenise(std::string(begin, end)).first;

    execute_roll(ctx, category, rolls.get(), player, false);
}

// ==========================================================================
// PARADICE COMMAND: ROLLPRIVATE
// ==========================================================================
PARADICE_COMMAND_IMPL(rollprivate)
{
    static std::string const usage_message =
        "\n Usage:   rollprivate [n*]<dice>d<sides>[<bonuses...>] [<category>]"
        "\n Example: rollprivate 2d6+3-20"
        "\n Example: rollprivate 20*2d6"
        "\n";

    auto begin = arguments.begin();
    auto end   = arguments.end();

    auto rolls = parse_dice_roll(begin, end);

    if (!rolls)
    {
        send_to_player(ctx, usage_message, player);
        return;
    }

    execute_roll(ctx, "", rolls.get(), player, true);
}

// ==========================================================================
// PARADICE COMMAND: SHOWROLLS
// ==========================================================================
PARADICE_COMMAND_IMPL(showrolls)
{
    auto tokens   = odin::tokenise(arguments);
    auto category = tokens.first;

    tokens        = odin::tokenise(tokens.second);
    auto order    = tokens.first;

    if (category == "")
    {
        static std::string const usage_message =
            "\n USAGE:   showrolls <category> [desc|asc]"
            "\n EXAMPLE: showrolls initiative"
            "\n EXAMPLE: showrolls combat desc"
            "\n";

        send_to_player(ctx, usage_message, player);
        return;
    }

    std::vector<roll_data> rolls;

    {
        std::unique_lock<std::mutex> lock(roll_category_mutex);
        rolls = roll_category[category];
    }

    if (rolls.empty())
    {
        send_to_player(
            ctx
          , boost::str(boost::format("There are no rolls in the %s category\n")
                % category)
          , player);
        return;
    }

    if (order == "desc")
    {
        std::sort(
            rolls.begin()
          , rolls.end()
          , sort_roll_data_by_score_descending);
    }
    else if (order == "asc")
    {
        sort(
            rolls.begin()
          , rolls.end()
          , sort_roll_data_by_score_ascending);
    }

    auto output = boost::str(boost::format(
        "\n===== Rolls in the %s category =====")
        % category);

    for (odin::u32 index = 0; index < rolls.size(); ++index)
    {
        roll_data &data = rolls[index];
        auto roller = data.roller.lock();

        std::string name = (
            roller == NULL
          ? data.name
          : roller->get_character()->get_name());

        output += boost::str(boost::format(
            "\n%s rolled %s and scored %d [%d%s]")
            % name
            % data.roll_text
            % data.score
            % data.raw_score
            % (data.max_roll ? "!" : ""));
    }

    output += "\n";

    send_to_player(ctx, output, player);
}

// ==========================================================================
// PARADICE COMMAND: CLEARROLLS
// ==========================================================================
PARADICE_COMMAND_IMPL(clearrolls)
{
    auto category = odin::tokenise(arguments).first;

    if (category == "")
    {
        static std::string const usage_message =
            "\n USAGE:   clearrolls <category>"
            "\n EXAMPLE: clearrolls initiative"
            "\n";

        send_to_player(ctx, usage_message, player);
        return;
    }

    {
        std::unique_lock<std::mutex> lock(roll_category_mutex);
        roll_category[category].clear();
    }

    send_to_player(
        ctx
      , boost::str(boost::format("You clear the rolls for the %s category\n")
          % category)
      , player);

    send_to_room(
        ctx
      , boost::str(boost::format("%s clears the rolls for the %s category\n")
          % player->get_character()->get_name()
          % category)
      , player);
}

}


text:
#pragma once

/**
* \brief Allows iteration on member name and values of a Fusion adapted struct.
*
*
* BOOST_FUSION_ADAPT_STRUCT(ns::point,
* 		(int, x)
*		(int, y)
*		(int, z));
*
* template<class T>
* print_name_and_value(const char* name, T& value) const {
*    std::cout << name << "=" << value << std::endl;
* }
*
*
* int main(void) {
*
*	ns::point mypoint;
*
*
*      boost::boost::fusion::for_each_member(mypoint, &print_name_and_value);
*
*
* }
*
* ********
* Credits to Damien Buhl
*     https://gist.github.com/daminetreg/6b539973817ed8f4f87d
*/
#ifndef BOOST_FUSION_FOR_EACH_MEMBER_HPP
#define BOOST_FUSION_FOR_EACH_MEMBER_HPP

#include <functional>

#include <boost/fusion/include/adapt_struct.hpp>

#include <boost/fusion/sequence/intrinsic/begin.hpp>
#include <boost/fusion/sequence/intrinsic/end.hpp>
#include <boost/fusion/sequence/intrinsic/front.hpp>
#include <boost/fusion/iterator/equal_to.hpp>
#include <boost/fusion/iterator/next.hpp>
#include <boost/fusion/iterator/deref.hpp>
#include <boost/fusion/iterator/distance.hpp>
#include <boost/fusion/support/category_of.hpp>
#include <boost/mpl/bool.hpp>

namespace restc_cpp {
namespace detail {

template <typename First, typename Last, typename F>
inline void
for_each_member_linear(First const& first,
    Last const& last,
    F const& f,
    boost::mpl::true_)
{
}

template <typename First, typename Last, typename F>
inline void
for_each_member_linear(First const& first,
    Last const& last,
    F const& f,
    boost::mpl::false_) {

    using type_t = typename std::remove_const<typename std::remove_reference<typename First::seq_type>::type>::type;

    auto name = boost::fusion::extension::struct_member_name<type_t, First::index::value>::call();

    f(name, *first);

    for_each_member_linear(
        next(first),
        last,
        f,
        boost::fusion::result_of::equal_to< typename boost::fusion::result_of::next<First>::type, Last>()
    );
}

template <typename Sequence, typename F>
inline void
for_each_member(Sequence& seq, F const& f) {

    detail::for_each_member_linear(
        boost::fusion::begin(seq),
        boost::fusion::end(seq),
        f,
        boost::fusion::result_of::equal_to<
        typename boost::fusion::result_of::begin<Sequence>::type,
        typename boost::fusion::result_of::end<Sequence>::type>()
    );
}

} // detail

template <typename Sequence, typename F>
inline void
for_each_member(Sequence& seq, F f) {
    detail::for_each_member(seq, f);
}

} // restc_cpp

#endif

ext: hpp

max_stars_repo_name: vizzerdrix/restc-cpp

max_issues_repo_name: vizzerdrix/restc-cpp

max_forks_repo_name: vizzerdrix/restc-cpp


text:
#include "Worker.h"

#include <boost/asio.hpp>
#include <boost/thread.hpp>

#include <algorithm>
#include <memory>

#include "lib/ClockUtils.h"

using shark::Worker;
using shark::SimulatedWorker;
using shark::ScheduledTaskReference;

ScheduledTaskReference::ScheduledTaskReference() : cancelled{false} {
}

bool ScheduledTaskReference::isCancelled() {
  return cancelled;
}
void ScheduledTaskReference::cancel() {
  cancelled = true;
}

Worker::Worker(std::weak_ptr<Scheduler> scheduler, std::shared_ptr<Clock> the_clock)
    : scheduler_{scheduler},
      clock_{the_clock},
      service_{},
      service_worker_{new asio_worker::element_type(service_)},
      closed_{false} {
}

Worker::~Worker() {
}

void Worker::task(Task f) {
  service_.post(f);
}

void Worker::start() {
  auto promise = std::make_shared<std::promise<void>>();
  start(promise);
}

void Worker::start(std::shared_ptr<std::promise<void>> start_promise) {
  auto this_ptr = shared_from_this();
  auto worker = [this_ptr, start_promise] {
    start_promise->set_value();
    if (!this_ptr->closed_) {
      return this_ptr->service_.run();
    }
    return size_t(0);
  };
  boost::thread *t=new boost::thread(worker);
  pthread_setname_np((t->native_handle()),"proxy_worker");
  group_.add_thread(t);
}

void Worker::close() {
  closed_ = true;
  service_worker_.reset();
  group_.join_all();
  service_.stop();
}

std::shared_ptr<ScheduledTaskReference> Worker::scheduleFromNow(Task f, duration delta) {
  auto delta_ms = std::chrono::duration_cast<std::chrono::milliseconds>(delta);
  auto id = std::make_shared<ScheduledTaskReference>();
  if (auto scheduler = scheduler_.lock()) {
    scheduler->scheduleFromNow(safeTask([f, id](std::shared_ptr<Worker> this_ptr) {
      this_ptr->task(this_ptr->safeTask([f, id](std::shared_ptr<Worker> this_ptr) {
        {
          if (id->isCancelled()) {
            return;
          }
        }
        f();
      }));
    }), delta_ms);
  }
  return id;
}

void Worker::scheduleEvery(ScheduledTask f, duration period) {
  scheduleEvery(f, period, period);
}

void Worker::scheduleEvery(ScheduledTask f, duration period, duration next_delay) {
  time_point start = clock_->now();
  std::shared_ptr<Clock> clock = clock_;

  scheduleFromNow(safeTask([start, period, next_delay, f, clock](std::shared_ptr<Worker> this_ptr) {
    if (f()) {
      duration clock_skew = clock->now() - start - next_delay;
      duration delay = period - clock_skew;
      this_ptr->scheduleEvery(f, period, delay);
    }
  }), std::max(next_delay, duration{0}));
}

void Worker::unschedule(std::shared_ptr<ScheduledTaskReference> id) {
  id->cancel();
}

std::function<void()> Worker::safeTask(std::function<void(std::shared_ptr<Worker>)> f) {
  std::weak_ptr<Worker> weak_this = shared_from_this();
  return [f, weak_this] {
    if (auto this_ptr = weak_this.lock()) {
      f(this_ptr);
    }
  };
}

SimulatedWorker::SimulatedWorker(std::shared_ptr<SimulatedClock> the_clock)
    : Worker(std::make_shared<Scheduler>(1), the_clock), clock_{the_clock} {
}

void SimulatedWorker::task(Task f) {
  tasks_.push_back(f);
}

void SimulatedWorker::start() {
}

void SimulatedWorker::start(std::shared_ptr<std::promise<void>> start_promise) {
}

void SimulatedWorker::close() {
  scheduled_tasks_.clear();
  tasks_.clear();
}

std::shared_ptr<ScheduledTaskReference> SimulatedWorker::scheduleFromNow(Task f, duration delta) {
  auto id = std::make_shared<ScheduledTaskReference>();
  scheduled_tasks_[clock_->now() + delta] =  [f, id] {
      if (id->isCancelled()) {
        return;
      }
      f();
    };
  return id;
}

void SimulatedWorker::executeTasks() {
  for (Task f : tasks_) {
    f();
  }
  tasks_.clear();
}

void SimulatedWorker::executePastScheduledTasks() {
  time_point now = clock_->now();
  for (auto iter = scheduled_tasks_.begin(), last_iter = scheduled_tasks_.end(); iter != last_iter; ) {
    if (iter->first <= now) {
      iter->second();
      iter = scheduled_tasks_.erase(iter);
    } else {
      ++iter;
    }
  }
}

ext: cpp


text:
//
// Copyright (c) 2009 Rutger ter Borg
//
// 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_NUMERIC_BINDINGS_BEGIN_HPP
#define BOOST_NUMERIC_BINDINGS_BEGIN_HPP

#include <boost/numeric/bindings/detail/adaptor.hpp>
#include <boost/numeric/bindings/detail/linear_iterator.hpp>
#include <boost/numeric/bindings/detail/generate_functions.hpp>
#include <boost/numeric/bindings/rank.hpp>
#include <boost/numeric/bindings/stride.hpp>
#include <boost/numeric/bindings/value_type.hpp>
#include <iostream>

namespace boost {
namespace numeric {
namespace bindings {

namespace detail {

template< typename T, typename Tag >
struct begin_impl {};

template< typename T >
struct begin_impl< T, tag::value > {
    typedef typename bindings::value_type< T>::type* result_type;

    static result_type invoke( T& t ) {
        return adaptor_access<T>::begin_value( t );
    }
};

template< typename T, int Dimension >
struct begin_impl<T, tag::addressing_index<Dimension> > {

    typedef tag::addressing_index<Dimension> tag_type;

    typedef linear_iterator<
        typename bindings::value_type< T>::type,
        typename result_of::stride< T, tag_type >::type
    > result_type;

    static result_type invoke( T& t ) {
        return result_type( adaptor_access<T>::begin_value( t ), bindings::stride(t, tag_type() ) );
    }
};

template< typename T >
struct begin_impl< T, tag::index_major > {
    typedef typename detail::property_at< T, tag::index_type >::type* result_type;

    static result_type invoke( T& t ) {
        return adaptor_access<T>::begin_index_major( t );
    }
};

template< typename T >
struct begin_impl< T, tag::compressed_index_major > {
    typedef typename detail::property_at< T, tag::index_type >::type* result_type;

    static result_type invoke( T& t ) {
        return adaptor_access<T>::begin_compressed_index_major( t );
    }
};

template< typename T >
struct begin_impl< T, tag::index_minor > {
    typedef typename detail::property_at< T, tag::index_type >::type* result_type;

    static result_type invoke( T& t ) {
        return adaptor_access<T>::begin_index_minor( t );
    }
};

} // namespace detail

namespace result_of {

template< typename T, typename Tag = tag::addressing_index<1> >
struct begin {
    BOOST_STATIC_ASSERT( (is_tag<Tag>::value) );
    typedef typename detail::begin_impl<T,Tag>::result_type type;
};

} // namespace result_of

//
// Free Functions
//

//
// Overloads like begin( t, tag )
//
template< typename T, typename Tag >
inline typename result_of::begin<T,Tag>::type
begin( T& t, Tag ) {
    return detail::begin_impl<T,Tag>::invoke( t );
}

template< typename T, typename Tag >
inline typename result_of::begin<const T,Tag>::type
begin( const T& t, Tag ) {
    return detail::begin_impl<const T,Tag>::invoke( t );
}

// Overloads for types with rank <= 1 (scalars, vectors)
// In theory, we could provide overloads for matrices here, too,
// if their minimal_rank is at most 1.

template< typename T >
typename boost::enable_if< mpl::less< rank<T>, mpl::int_<2> >,
    typename result_of::begin< T >::type >::type
begin( T& t ) {
    return detail::begin_impl< T, tag::addressing_index<1> >::invoke( t );
}

template< typename T >
typename boost::enable_if< mpl::less< rank<T>, mpl::int_<2> >,
    typename result_of::begin< const T >::type >::type
begin( const T& t ) {
    return detail::begin_impl< const T, tag::addressing_index<1> >::invoke( t );
}

#define GENERATE_BEGIN_INDEX( z, which, unused ) \
GENERATE_FUNCTIONS( begin, which, tag::addressing_index<which> )

BOOST_PP_REPEAT_FROM_TO(1,3,GENERATE_BEGIN_INDEX,~)
GENERATE_FUNCTIONS( begin, _value, tag::value )
GENERATE_FUNCTIONS( begin, _row, tag::addressing_index<1> )
GENERATE_FUNCTIONS( begin, _column, tag::addressing_index<2> )

GENERATE_FUNCTIONS( begin, _index_major, tag::index_major )
GENERATE_FUNCTIONS( begin, _compressed_index_major, tag::compressed_index_major )
GENERATE_FUNCTIONS( begin, _index_minor, tag::index_minor )

} // namespace bindings
} // namespace numeric
} // namespace boost

#endif

max_stars_repo_name: ljktest/siconos

max_issues_repo_name: ljktest/siconos

max_forks_repo_name: ljktest/siconos


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2012-2013. 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/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_CONTAINER_THROW_EXCEPTION_HPP
#define BOOST_CONTAINER_THROW_EXCEPTION_HPP

#ifndef BOOST_CONFIG_HPP
#include <boost/config.hpp>
#endif

#if defined(BOOST_HAS_PRAGMA_ONCE)
#pragma once
#endif

#include <boost/container/detail/config_begin.hpp>
#include <boost/container/detail/workaround.hpp>

#ifndef BOOST_NO_EXCEPTIONS
#include <new>       //for std::bad_alloc
#include <stdexcept> //for std exception types
#include <string>    //for implicit std::string conversion
#else
#include <boost/assert.hpp>
#include <cstdlib> //for std::abort
#endif

namespace boost
{
namespace container
{

#if defined(BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS)
// The user must provide definitions for the following functions

void throw_bad_alloc();

void throw_out_of_range(const char* str);

void throw_length_error(const char* str);

void throw_logic_error(const char* str);

void throw_runtime_error(const char* str);

#elif defined(BOOST_NO_EXCEPTIONS)

inline void throw_bad_alloc()
{
    const char msg[] = "boost::container bad_alloc thrown";
    (void)msg;
    BOOST_ASSERT(!msg);
    std::abort();
}

inline void throw_out_of_range(const char* str)
{
    const char msg[] = "boost::container out_of_range thrown";
    (void)msg;
    (void)str;
    BOOST_ASSERT_MSG(!msg, str);
    std::abort();
}

inline void throw_length_error(const char* str)
{
    const char msg[] = "boost::container length_error thrown";
    (void)msg;
    (void)str;
    BOOST_ASSERT_MSG(!msg, str);
    std::abort();
}

inline void throw_logic_error(const char* str)
{
    const char msg[] = "boost::container logic_error thrown";
    (void)msg;
    (void)str;
    BOOST_ASSERT_MSG(!msg, str);
    std::abort();
}

inline void throw_runtime_error(const char* str)
{
    const char msg[] = "boost::container runtime_error thrown";
    (void)msg;
    (void)str;
    BOOST_ASSERT_MSG(!msg, str);
    std::abort();
}

#else // defined(BOOST_NO_EXCEPTIONS)

//! Exception callback called by Boost.Container when fails to allocate the
//! requested storage space.

If BOOST_NO_EXCEPTIONS is NOT defined
//! std::bad_alloc() is thrown.

//!
//!
If BOOST_NO_EXCEPTIONS is defined and
//! BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
//!   is NOT defined BOOST_ASSERT(!"boost::container bad_alloc
//!   thrown") is called and std::abort() if the former
//!   returns.

//!
//!
If BOOST_NO_EXCEPTIONS and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
//! are defined
//!   the user must provide an implementation and the function should not
//!   return.

//!

inline void throw_bad_alloc()
{
    throw std::bad_alloc();
}

//! Exception callback called by Boost.Container to signal arguments out of
//! range.

If BOOST_NO_EXCEPTIONS is NOT defined
//! std::out_of_range(str) is thrown.

//!
//!
If BOOST_NO_EXCEPTIONS is defined and
//! BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
//!   is NOT defined BOOST_ASSERT_MSG(!"boost::container out_of_range
//!   thrown", str) is called and std::abort() if the former
//!   returns.

//!
//!
If BOOST_NO_EXCEPTIONS and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
//! are defined
//!   the user must provide an implementation and the function should not
//!   return.

//!

inline void throw_out_of_range(const char* str)
{
    throw std::out_of_range(str);
}

//! Exception callback called by Boost.Container to signal errors resizing.
//!

//!
If BOOST_NO_EXCEPTIONS is NOT defined
//! std::length_error(str) is thrown.

//!
//!
If BOOST_NO_EXCEPTIONS is defined and
//! BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
//!   is NOT defined BOOST_ASSERT_MSG(!"boost::container length_error
//!   thrown", str) is called and std::abort() if the former
//!   returns.

//!
//!
If BOOST_NO_EXCEPTIONS and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
//! are defined
//!   the user must provide an implementation and the function should not
//!   return.

//!

inline void throw_length_error(const char* str)
{
    throw std::length_error(str);
}

//! Exception callback called by Boost.Container  to report errors in the
//! internal logical of the program, such as violation of logical preconditions
//! or class invariants.

If BOOST_NO_EXCEPTIONS is NOT defined
//! std::logic_error(str) is thrown.

//!
//!
If BOOST_NO_EXCEPTIONS is defined and
//! BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
//!   is NOT defined BOOST_ASSERT_MSG(!"boost::container logic_error
//!   thrown", str) is called and std::abort() if the former
//!   returns.

//!
//!
If BOOST_NO_EXCEPTIONS and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
//! are defined
//!   the user must provide an implementation and the function should not
//!   return.

//!

inline void throw_logic_error(const char* str)
{
    throw std::logic_error(str);
}

//! Exception callback called by Boost.Container  to report errors that can only
//! be detected during runtime.

If BOOST_NO_EXCEPTIONS is NOT defined
//! std::runtime_error(str) is thrown.

//!
//!
If BOOST_NO_EXCEPTIONS is defined and
//! BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
//!   is NOT defined BOOST_ASSERT_MSG(!"boost::container runtime_error
//!   thrown", str) is called and std::abort() if the former
//!   returns.

//!
//!
If BOOST_NO_EXCEPTIONS and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS
//! are defined
//!   the user must provide an implementation and the function should not
//!   return.

//!

inline void throw_runtime_error(const char* str)
{
    throw std::runtime_error(str);
}

#endif

} // namespace container
} // namespace boost

#include <boost/container/detail/config_end.hpp>

#endif //#ifndef BOOST_CONTAINER_THROW_EXCEPTION_HPP

max_stars_repo_name: sotaoverride/backup

max_issues_repo_name: sotaoverride/backup

max_forks_repo_name: sotaoverride/backup


text:
#include "core/cuda_array.hpp"
#include "core/macros.h"
#include "core/cuda_ptr.hpp"
#include "util/other/cpu_histogram.hpp"
#include "util/histogram/histogram.hpp"
#include "core/config.hpp"
#include "test/unittest_base.hpp"
#include "compression/delta/delta_encoding.hpp"

#include <cuda_runtime_api.h>
#include <vector>
#include <iostream>
#include <boost/bind.hpp>
#include <thrust/execution_policy.h>
#include <thrust/sort.h>

namespace ddj
{

class HistogramTest : public UnittestBase {};

template<typename T>
bool CheckMostFrequent(
    SharedCudaPtrPair<T,int> histogram,
    SharedCudaPtr<T> mostFrequent,
    int mostFreqCnt)
{
    auto h_histogramKeys = histogram.first->copyToHost();
    auto h_histogramValues = histogram.second->copyToHost();
    auto h_mostFrequent = mostFrequent->copyToHost();

    // Sort in descending order using thrust on host using values as keys (CPU)
    thrust::sort_by_key(
        thrust::host,
        h_histogramValues->data(),
        h_histogramValues->data() + h_histogramKeys->size(),
        h_histogramKeys->data(),
        thrust::greater<int>());

    for(int i = 0; i < mostFreqCnt; i++)
        if(h_mostFrequent->at(i) != h_histogramKeys->at(i))
            return false;

    return true;
}

TEST_F(HistogramTest, GetMostFrequent_fake_data)
{
    int mostFreqCnt = 3;
    auto fakeData = GetFakeIntDataForHistogram();
    auto fakedDictionaryCounter = Histogram().GetDictionaryCounter(fakeData);
    auto mostFrequent = Histogram().GetMostFrequent(fakedDictionaryCounter, mostFreqCnt);
    int expected = GetSize(), actual;
    CUDA_CALL( cudaMemcpy(&actual, mostFrequent->get(), sizeof(int), CPY_DTH) );
    EXPECT_EQ(expected, actual);
}

TEST_F(HistogramTest, GetMostFrequent_random_int)
{
    int mostFreqCnt = 4;
    auto randomHistogram = Histogram().GetDictionaryCounter(GetIntRandomData());
    auto mostFrequent = Histogram().GetMostFrequent(randomHistogram, mostFreqCnt);
    EXPECT_TRUE( CheckMostFrequent(randomHistogram, mostFrequent,  mostFreqCnt) );
}

TEST(CpuHistogramTest, Sparse_AllOnes)
{
    int N = 1000;
    CpuHistogramSparse histogram;
    std::vector<int> data(N);
    for(int i = 0; i < N; i++) data[i] = i;
    std::vector<int> expected(N);
    for(int i = 0; i < N; i++) expected[i] = 1;
    auto actual = histogram.Histogram(data);
    ASSERT_EQ(expected.size(), actual.size());
    for(int i = 0; i < N; i++) EXPECT_EQ(expected[i], actual[i]);
}

TEST(CpuHistogramTest, Dense_AllOnes)
{
    int N = 1000;
    CpuHistogramDense histogram;
    std::vector<int> data(N);
    for(int i = 0; i < N; i++) data[i] = i;
    std::vector<int> expected(N);
    for(int i = 0; i < N; i++) expected[i] = 1;
    auto actual = histogram.Histogram(data);
    ASSERT_EQ(expected.size(), actual.size());
    for(int i = 0; i < N; i++) EXPECT_EQ(expected[i], actual[i]);
}

TEST(CpuHistogramTest, Sparse_RepeatedNumbers_Modulo)
{
    int N = 1000;
    int M = 10;
    CpuHistogramSparse histogram;
    std::vector<int> data(N);
    for(int i = 0; i < N; i++) data[i] = i%M;
    std::vector<int> expected(M);
    for(int i = 0; i < M; i++) expected[i] = N/M;
    auto actual = histogram.Histogram(data);
    ASSERT_EQ(expected.size(), actual.size());
    for(int i = 0; i < M; i++) EXPECT_EQ(expected[i], actual[i]);
}

TEST(CpuHistogramTest, Dense_RepeatedNumbers_Modulo)
{
    int N = 1000;
    int M = 10;
    CpuHistogramDense histogram;
    std::vector<int> data(N);
    for(int i = 0; i < N; i++) data[i] = i%M;
    std::vector<int> expected(M);
    for(int i = 0; i < M; i++) expected[i] = N/M;
    auto actual = histogram.Histogram(data);
    ASSERT_EQ(expected.size(), actual.size());
    for(int i = 0; i < M; i++) EXPECT_EQ(expected[i], actual[i]);
}

template<typename T>
std::map<T, int> TransformToHostMap(const SharedCudaPtrPair<T, int>& d_map_data)
{
	if(d_map_data.first->size() != d_map_data.second->size())
		throw new std::runtime_error("sizes of arrays must match");
	int size = d_map_data.second->size();
	std::map<T, int> result;
	if(size > 0)
	{
		T* keys = new T[size];
		int* counts = new int[size];
		CUDA_CALL( cudaMemcpy(keys, d_map_data.first->get(), size*sizeof(T), CPY_DTH) );
		CUDA_CALL( cudaMemcpy(counts, d_map_data.second->get(), size*sizeof(int), CPY_DTH) );

		for(int i = 0; i < size; i++)
			result.insert(std::make_pair(keys[i], counts[i]));

		delete [] keys;
		delete [] counts;
	}
	return result;
}

template<typename T>
bool CompareHistograms(std::map<T, int> A, std::map<T, int> B)
{
	for(auto&& elem : A)
		if(elem.second != B[elem.first]) return false;
	return true;
}

template<typename T>
void PrintHostHistogram(std::map<T, int> histogram, std::string name)
{
    std::cout << name << std::endl;
    for(auto&& elem : histogram)
    {
        std::cout << "(" << elem.first << "," << elem.second << ")";
    }
    std::cout << std::endl;
}

template<typename T, class CPU_HIST>
void CheckHistogramResult(SharedCudaPtr<T> data, SharedCudaPtrPair<T, int> result)
{
	int size = data->size();
	CPU_HIST cpuHistogram;

	T* h_data = new T[size];
	CUDA_CALL( cudaMemcpy(h_data, data->get(), size*sizeof(T), CPY_DTH) );
	auto h_data_vector = std::vector<T>(h_data, h_data+size);
	auto h_expected = cpuHistogram.Histogram(h_data_vector);
	auto d_actual = result;
	ASSERT_TRUE(d_actual.first != NULL);
	ASSERT_TRUE(d_actual.second != NULL);
	auto h_actual = TransformToHostMap(d_actual);

	EXPECT_EQ( h_expected.size(), h_actual.size() );
	EXPECT_TRUE( CompareHistograms(h_expected, h_actual) );

//	    PrintHostHistogram(h_expected, "Expected");
//	    PrintHostHistogram(h_actual, "Actual");

	delete [] h_data;
}

TEST_F(HistogramTest, GetDictionaryCounter_RandomIntegerArray)
{
	auto randomData = GetIntRandomData();
	auto result = Histogram().GetDictionaryCounter(randomData);
	CheckHistogramResult<int, CpuHistogramSparse>(randomData, result);
}

TEST_F(HistogramTest, GetDictionaryCounter_RealData_Delta_Time)
{
	auto realData = GetTsIntDataFromTestFile();
	auto deltaEncoded = DeltaEncoding().Encode(realData);
	auto realDataDelta = MoveSharedCudaPtr<char, time_t>(deltaEncoded[1]);
	auto result = Histogram().GetDictionaryCounter(realDataDelta);
	CheckHistogramResult<time_t, CpuHistogramSparse>(realDataDelta, result);
}

TEST_F(HistogramTest, GetDictionaryCounter_FakeData)
{
	auto randomData = GetFakeIntDataForHistogram();
	auto result = Histogram().GetDictionaryCounter(randomData);
	CheckHistogramResult<int, CpuHistogramSparse>(randomData, result);
}

TEST_F(HistogramTest, GetDictionaryCounter_OneBin)
{
	std::vector<int> hData;
	for(int i = 0; i < _size; i++)
	hData.push_back(0);
	auto dData = CudaPtr<int>::make_shared(_size);
	dData->fillFromHost(hData.data(), _size);
	auto result = Histogram().GetDictionaryCounter(dData);
	CheckHistogramResult<int, CpuHistogramSparse>(dData, result);
}

TEST_F(HistogramTest, GetHistogream_FakeData)
{
	auto fakeData = GetFakeIntDataForHistogram();
	int bucketCnt = GetSize()-1;
	auto histogram = Histogram().GetHistogram(fakeData, bucketCnt);

	int actual, expected = 10;
	CUDA_CALL( cudaMemcpy(&actual, histogram->get(), sizeof(int), CPY_DTH) );
	EXPECT_EQ(expected, actual);
}

TEST_F(HistogramTest, GetHistogream_RandomFloat_MaxPrecision2)
{
	auto fakeData = GetFloatRandomDataWithMaxPrecision(2);
	int bucketCnt = 10;
	auto histogram = Histogram().GetHistogram(fakeData, bucketCnt);
//	HelperPrint::PrintSharedCudaPtr(fakeData, "fakeData");
//	HelperPrint::PrintSharedCudaPtr(histogram, "histogram");
	int actual;
	CUDA_CALL( cudaMemcpy(&actual, histogram->get(), sizeof(int), CPY_DTH) );
	EXPECT_GT(actual, 1000);
}

} /* namespace ddj */

max_stars_repo_licenses: MIT Unlicense

max_issues_repo_licenses: MIT Unlicense

max_forks_repo_licenses: MIT Unlicense


text:
///////////////////////////////////////////////////////////////
//  Copyright 2019 John Maddock. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt

#include "../performance_test.hpp"
#if defined(TEST_TOMMATH)
#include <boost/multiprecision/tommath.hpp>
#endif

void test48()
{
#ifdef TEST_TOMMATH
   test<boost::multiprecision::tom_int>("tommath_int", 1024*8);
   /*
   //
   // These are actually too slow to test!!!
   //
   test<boost::multiprecision::tom_rational>("tom_rational", 128);
   test<boost::multiprecision::tom_rational>("tom_rational", 256);
   test<boost::multiprecision::tom_rational>("tom_rational", 512);
   test<boost::multiprecision::tom_rational>("tom_rational", 1024);
   */
#endif
}

max_issues_repo_name: qingkouwei/mediaones


text:
// Copyright 2005-2009 Daniel James.
// 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)

// A non-portable hash function form non-zero floats on x86.
//
// Even if you're on an x86 platform, this might not work if their floating
// point isn't set up as this expects. So this should only be used if it's
// absolutely certain that it will work.

#if !defined(BOOST_FUNCTIONAL_HASH_DETAIL_HASH_FLOAT_X86_HEADER)
#define BOOST_FUNCTIONAL_HASH_DETAIL_HASH_FLOAT_X86_HEADER

#include <boost/cstdint.hpp>

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

namespace boost
{
    namespace hash_detail
    {
        inline void hash_float_combine(std::size_t& seed, std::size_t value)
        {
            seed ^= value + (seed<<6) + (seed>>2);
        }

        inline std::size_t float_hash_impl(float v)
        {
            boost::uint32_t* ptr = (boost::uint32_t*)&v;
            std::size_t seed = *ptr;
            return seed;
        }

        inline std::size_t float_hash_impl(double v)
        {
            boost::uint32_t* ptr = (boost::uint32_t*)&v;
            std::size_t seed = *ptr++;
            hash_float_combine(seed, *ptr);
            return seed;
        }

        inline std::size_t float_hash_impl(long double v)
        {
            boost::uint32_t* ptr = (boost::uint32_t*)&v;
            std::size_t seed = *ptr++;
            hash_float_combine(seed, *ptr++);
            hash_float_combine(seed, *(boost::uint16_t*)ptr);
            return seed;
        }
    }
}

#endif

max_stars_repo_name: dyzmapl/BumpTop

max_issues_repo_name: dyzmapl/BumpTop

max_forks_repo_name: dyzmapl/BumpTop


text: #include <boost/container/adaptive_pool.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <boost/test/unit_test.hpp>

#include <graphene/chain/database.hpp>
#include <graphene/app/database_api.hpp>
#include <graphene/chain/exceptions.hpp>
#include <graphene/chain/hardfork.hpp>
#include <graphene/chain/is_authorized_asset.hpp>

#include "../common/database_fixture.hpp"

using namespace graphene::chain;
using namespace graphene::chain::test;

namespace fc
{
   template<typename Ch, typename T>
   std::basic_ostream<Ch>& operator<<(std::basic_ostream<Ch>& os, safe<T> const& sf)
   {
      os << sf.value;
      return os;
   }
}

struct reward_database_fixture : database_fixture
{
   using whitelist_market_fee_sharing_t = fc::optional<flat_set<account_id_type>>;

   reward_database_fixture()
      : database_fixture(HARDFORK_1268_TIME - 100)
   {
   }

   void update_asset( const account_id_type& issuer_id,
                      const fc::ecc::private_key& private_key,
                      const asset_id_type& asset_id,
                      uint16_t reward_percent,
                      const whitelist_market_fee_sharing_t &whitelist_market_fee_sharing = whitelist_market_fee_sharing_t{},
                      const flat_set<account_id_type> &blacklist = flat_set<account_id_type>())
   {
      asset_update_operation op;
      op.issuer = issuer_id;
      op.asset_to_update = asset_id;
      op.new_options = asset_id(db).options;
      op.new_options.extensions.value.reward_percent = reward_percent;
      op.new_options.extensions.value.whitelist_market_fee_sharing = whitelist_market_fee_sharing;
      op.new_options.blacklist_authorities = blacklist;

      signed_transaction tx;
      tx.operations.push_back( op );
      db.current_fee_schedule().set_fee( tx.operations.back() );
      set_expiration( db, tx );
      sign( tx, private_key );
      PUSH_TX( db, tx );
   }

   void asset_update_blacklist_authority(const account_id_type& issuer_id,
                                         const asset_id_type& asset_id,
                                         const account_id_type& authority_account_id,
                                         const fc::ecc::private_key& issuer_private_key)
   {
      asset_update_operation uop;
      uop.issuer = issuer_id;
      uop.asset_to_update = asset_id;
      uop.new_options = asset_id(db).options;
      uop.new_options.blacklist_authorities.insert(authority_account_id);

      signed_transaction tx;
      tx.operations.push_back( uop );
      db.current_fee_schedule().set_fee( tx.operations.back() );
      set_expiration( db, tx );
      sign( tx, issuer_private_key );
      PUSH_TX( db, tx );
   }

   void add_account_to_blacklist(const account_id_type& authorizing_account_id,
                                 const account_id_type& blacklisted_account_id,
                                 const fc::ecc::private_key& authorizing_account_private_key)
   {
      account_whitelist_operation wop;
      wop.authorizing_account = authorizing_account_id;
      wop.account_to_list = blacklisted_account_id;
      wop.new_listing = account_whitelist_operation::black_listed;

      signed_transaction tx;
      tx.operations.push_back( wop );
      db.current_fee_schedule().set_fee( tx.operations.back() );
      set_expiration( db, tx );
      sign( tx, authorizing_account_private_key );
      PUSH_TX( db, tx);
   }

   void generate_blocks_past_hf1268()
   {
      database_fixture::generate_blocks( HARDFORK_1268_TIME );
      database_fixture::generate_block();
   }

   asset core_asset(int64_t x )
   {
       return asset( x*core_precision );
   };

   const share_type core_precision = asset::scaled_precision( asset_id_type()(db).precision );

   void create_vesting_balance_object(const account_id_type& account_id, vesting_balance_type balance_type )
   {
      auto block_time = db.head_block_time();

      db.create<vesting_balance_object>([&account_id, &block_time, balance_type] (vesting_balance_object &vbo) {
         vbo.owner = account_id;
         vbo.balance_type = balance_type;
      });
   };
};

BOOST_FIXTURE_TEST_SUITE( fee_sharing_tests, reward_database_fixture )

BOOST_AUTO_TEST_CASE(cannot_create_asset_with_additional_options_before_hf)
{
   try
   {
      ACTOR(issuer);

      price price(asset(1, asset_id_type(1)), asset(1));
      uint16_t market_fee_percent = 100;

      additional_asset_options_t options;
      options.value.reward_percent = 100;
      options.value.whitelist_market_fee_sharing = flat_set<account_id_type>{issuer_id};

      GRAPHENE_CHECK_THROW(create_user_issued_asset("USD",
                                                    issuer,
                                                    charge_market_fee,
                                                    price,
                                                    2,
                                                    market_fee_percent,
                                                    options),
                           fc::assert_exception);
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(create_asset_with_additional_options_after_hf)
{
   try
   {
      ACTOR(issuer);

      generate_blocks_past_hf1268();

      uint16_t reward_percent = 100;
      flat_set<account_id_type> whitelist = {issuer_id};
      price price(asset(1, asset_id_type(1)), asset(1));
      uint16_t market_fee_percent = 100;

      additional_asset_options_t options;
      options.value.reward_percent = reward_percent;
      options.value.whitelist_market_fee_sharing = whitelist;

      asset_object usd_asset = create_user_issued_asset("USD",
                                                        issuer,
                                                        charge_market_fee,
                                                        price,
                                                        2,
                                                        market_fee_percent,
                                                        options);

      additional_asset_options usd_options = usd_asset.options.extensions.value;
      BOOST_CHECK_EQUAL(reward_percent, *usd_options.reward_percent);
      BOOST_CHECK(whitelist == *usd_options.whitelist_market_fee_sharing);
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(cannot_update_additional_options_before_hf)
{
   try
   {
      ACTOR(issuer);

      asset_object usd_asset = create_user_issued_asset("USD", issuer, charge_market_fee);

      flat_set<account_id_type> whitelist = {issuer_id};
      GRAPHENE_CHECK_THROW(
                  update_asset(issuer_id, issuer_private_key, usd_asset.get_id(), 40, whitelist),
                  fc::assert_exception );
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(update_additional_options_after_hf)
{
   try
   {
      ACTOR(issuer);

      asset_object usd_asset = create_user_issued_asset("USD", issuer, charge_market_fee);

      generate_blocks_past_hf1268();

      uint16_t reward_percent = 40;
      flat_set<account_id_type> whitelist = {issuer_id};
      update_asset(issuer_id, issuer_private_key, usd_asset.get_id(), reward_percent, whitelist);

      asset_object updated_asset = usd_asset.get_id()(db);
      additional_asset_options options = updated_asset.options.extensions.value;
      BOOST_CHECK_EQUAL(reward_percent, *options.reward_percent);
      BOOST_CHECK(whitelist == *options.whitelist_market_fee_sharing);
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(asset_rewards_test)
{
   try
   {
      ACTORS((registrar)(alicereferrer)(bobreferrer)(izzy)(jill));

      auto register_account = [&](const string& name, const account_object& referrer) -> const account_object&
      {
         uint16_t referrer_percent = GRAPHENE_1_PERCENT;
         fc::ecc::private_key _private_key = generate_private_key(name);
         public_key_type _public_key = _private_key.get_public_key();
         return create_account(name, registrar, referrer, referrer_percent, _public_key);
      };

      // Izzy issues asset to Alice
      // Jill issues asset to Bob
      // Alice and Bob trade in the market and pay fees
      // Bob's and Alice's referrers can get reward
      upgrade_to_lifetime_member(registrar);
      upgrade_to_lifetime_member(alicereferrer);
      upgrade_to_lifetime_member(bobreferrer);

      auto alice = register_account("alice", alicereferrer);
      auto bob = register_account("bob", bobreferrer);

      transfer( committee_account, alice.id, core_asset(1000000) );
      transfer( committee_account, bob.id, core_asset(1000000) );
      transfer( committee_account, izzy_id, core_asset(1000000) );
      transfer( committee_account, jill_id, core_asset(1000000) );

      constexpr auto izzycoin_reward_percent = 10*GRAPHENE_1_PERCENT;
      constexpr auto jillcoin_reward_percent = 20*GRAPHENE_1_PERCENT;

      constexpr auto izzycoin_market_percent = 10*GRAPHENE_1_PERCENT;
      constexpr auto jillcoin_market_percent = 20*GRAPHENE_1_PERCENT;

      asset_id_type izzycoin_id = create_bitasset( "IZZYCOIN", izzy_id, izzycoin_market_percent ).id;
      asset_id_type jillcoin_id = create_bitasset( "JILLCOIN", jill_id, jillcoin_market_percent ).id;

      generate_blocks_past_hf1268();

      update_asset(izzy_id, izzy_private_key, izzycoin_id, izzycoin_reward_percent);
      update_asset(jill_id, jill_private_key, jillcoin_id, jillcoin_reward_percent);

      const share_type izzy_prec = asset::scaled_precision( asset_id_type(izzycoin_id)(db).precision );
      const share_type jill_prec = asset::scaled_precision( asset_id_type(jillcoin_id)(db).precision );

      auto _izzy = [&]( int64_t x ) -> asset
      {   return asset( x*izzy_prec, izzycoin_id );   };
      auto _jill = [&]( int64_t x ) -> asset
      {   return asset( x*jill_prec, jillcoin_id );   };

      update_feed_producers( izzycoin_id(db), { izzy_id } );
      update_feed_producers( jillcoin_id(db), { jill_id } );

      // Izzycoin is worth 100 BTS
      price_feed feed;
      feed.settlement_price = price( _izzy(1), core_asset(100) );
      feed.maintenance_collateral_ratio = 175 * GRAPHENE_COLLATERAL_RATIO_DENOM / 100;
      feed.maximum_short_squeeze_ratio = 150 * GRAPHENE_COLLATERAL_RATIO_DENOM / 100;
      publish_feed( izzycoin_id(db), izzy, feed );

      // Jillcoin is worth 30 BTS
      feed.settlement_price = price( _jill(1), core_asset(30) );
      feed.maintenance_collateral_ratio = 175 * GRAPHENE_COLLATERAL_RATIO_DENOM / 100;
      feed.maximum_short_squeeze_ratio = 150 * GRAPHENE_COLLATERAL_RATIO_DENOM / 100;
      publish_feed( jillcoin_id(db), jill, feed );

      enable_fees();

      // Alice and Bob create some coins
      borrow( alice.id, _izzy( 1500), core_asset( 600000) );
      borrow( bob.id, _jill(2000), core_asset(180000) );

      // Alice and Bob place orders which match
      create_sell_order( alice.id, _izzy(1000), _jill(1500) ); // Alice is willing to sell her 1000 Izzy's for 1.5 Jill
      create_sell_order( bob.id, _jill(1500), _izzy(1000) );   // Bob is buying up to 1500 Izzy's for up to 0.6 Jill

      // 1000 Izzys and 1500 Jills are matched, so the fees should be
      //   100 Izzy (10%) and 300 Jill (20%).
      // Bob's and Alice's referrers should get rewards
      share_type bob_refereer_reward = get_market_fee_reward( bob.referrer, izzycoin_id );
      share_type alice_refereer_reward = get_market_fee_reward( alice.referrer, jillcoin_id );

      // Bob's and Alice's registrars should get rewards
      share_type bob_registrar_reward = get_market_fee_reward( bob.registrar, izzycoin_id );
      share_type alice_registrar_reward = get_market_fee_reward( alice.registrar, jillcoin_id );

      auto calculate_percent = [](const share_type& value, uint16_t percent)
      {
         auto a(value.value);
         a *= percent;
         a /= GRAPHENE_100_PERCENT;
         return a;
      };

      BOOST_CHECK_GT( bob_refereer_reward, 0 );
      BOOST_CHECK_GT( alice_refereer_reward, 0 );
      BOOST_CHECK_GT( bob_registrar_reward, 0 );
      BOOST_CHECK_GT( alice_registrar_reward, 0 );

      const auto izzycoin_market_fee = calculate_percent(_izzy(1000).amount, izzycoin_market_percent);
      const auto izzycoin_reward = calculate_percent(izzycoin_market_fee, izzycoin_reward_percent);
      BOOST_CHECK_EQUAL( izzycoin_reward, bob_refereer_reward + bob_registrar_reward );
      BOOST_CHECK_EQUAL( calculate_percent(izzycoin_reward, bob.referrer_rewards_percentage), bob_refereer_reward );

      const auto jillcoin_market_fee = calculate_percent(_jill(1500).amount, jillcoin_market_percent);
      const auto jillcoin_reward = calculate_percent(jillcoin_market_fee, jillcoin_reward_percent);
      BOOST_CHECK_EQUAL( jillcoin_reward, alice_refereer_reward + alice_registrar_reward );
      BOOST_CHECK_EQUAL( calculate_percent(jillcoin_reward, alice.referrer_rewards_percentage), alice_refereer_reward );
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(asset_claim_reward_test)
{
   try
   {
      ACTORS((jill)(izzy));
      constexpr auto jillcoin_reward_percent = 2*GRAPHENE_1_PERCENT;

      upgrade_to_lifetime_member(izzy);

      price price(asset(1, asset_id_type(1)), asset(1));
      uint16_t market_fee_percent = 20 * GRAPHENE_1_PERCENT;
      const asset_object jillcoin = create_user_issued_asset( "JCOIN", jill,  charge_market_fee, price, 2, market_fee_percent );

      const account_object alice = create_account("alice", izzy, izzy, 50/*0.5%*/);
      const account_object bob   = create_account("bob",   izzy, izzy, 50/*0.5%*/);

      // prepare users' balance
      issue_uia( alice, jillcoin.amount( 20000000 ) );

      transfer( committee_account, alice.get_id(), core_asset(1000) );
      transfer( committee_account, bob.get_id(),   core_asset(1000) );
      transfer( committee_account, izzy.get_id(),  core_asset(1000) );

      generate_blocks_past_hf1268();
      // update_asset: set referrer percent
      update_asset(jill_id, jill_private_key, jillcoin.get_id(), jillcoin_reward_percent);

      // Alice and Bob place orders which match
      create_sell_order( alice, jillcoin.amount(200000), core_asset(1) );
      create_sell_order( bob, core_asset(1), jillcoin.amount(100000) );

      const int64_t izzy_reward = get_market_fee_reward( izzy, jillcoin );
      const int64_t izzy_balance = get_balance( izzy, jillcoin );

      BOOST_CHECK_GT(izzy_reward, 0);

      auto claim_reward = [&]( account_object referrer, asset amount_to_claim, fc::ecc::private_key private_key )
      {
        vesting_balance_withdraw_operation op;
        op.vesting_balance = vesting_balance_id_type(0);
        op.owner = referrer.get_id();
        op.amount = amount_to_claim;

        signed_transaction tx;
        tx.operations.push_back( op );
        db.current_fee_schedule().set_fee( tx.operations.back() );
        set_expiration( db, tx );
        sign( tx, private_key );
        PUSH_TX( db, tx );
      };

      const int64_t amount_to_claim = 3;
      claim_reward( izzy, jillcoin.amount(amount_to_claim), izzy_private_key );

      BOOST_CHECK_EQUAL(get_balance( izzy, jillcoin ), izzy_balance + amount_to_claim);
      BOOST_CHECK_EQUAL(get_market_fee_reward( izzy, jillcoin ), izzy_reward - amount_to_claim);
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(create_actors)
{
   try
   {
      ACTORS((jill)(izzyregistrar)(izzyreferrer));

      upgrade_to_lifetime_member(izzyregistrar);
      upgrade_to_lifetime_member(izzyreferrer);

      price price(asset(1, asset_id_type(1)), asset(1));
      uint16_t market_fee_percent = 20 * GRAPHENE_1_PERCENT;
      auto obj = jill_id(db);
      const asset_object jillcoin = create_user_issued_asset( "JCOIN", jill,  charge_market_fee, price, 2, market_fee_percent );

      const account_object alice = create_account("alice", izzyregistrar, izzyreferrer, 50/*0.5%*/);
      const account_object bob   = create_account("bob",   izzyregistrar, izzyreferrer, 50/*0.5%*/);

      // prepare users' balance
      issue_uia( alice, jillcoin.amount( 20000000 ) );

      transfer( committee_account, alice.get_id(), core_asset(1000) );
      transfer( committee_account, bob.get_id(),   core_asset(1000) );
      transfer( committee_account, izzyregistrar.get_id(),  core_asset(1000) );
      transfer( committee_account, izzyreferrer.get_id(),  core_asset(1000) );
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(white_list_is_empty_test)
{
   try
   {
      INVOKE(create_actors);

      generate_blocks_past_hf1268();
      GET_ACTOR(jill);

      constexpr auto jillcoin_reward_percent = 2*GRAPHENE_1_PERCENT;
      const asset_object &jillcoin = get_asset("JCOIN");

      flat_set<account_id_type> whitelist;
      update_asset(jill_id, jill_private_key, jillcoin.get_id(), jillcoin_reward_percent, whitelist);

      GET_ACTOR(izzyregistrar);
      GET_ACTOR(izzyreferrer);
      BOOST_CHECK_EQUAL( get_market_fee_reward( izzyregistrar, jillcoin ), 0 );
      BOOST_CHECK_EQUAL( get_market_fee_reward( izzyreferrer, jillcoin ), 0 );

      GET_ACTOR(alice);
      GET_ACTOR(bob);
      // Alice and Bob place orders which match
      create_sell_order( alice, jillcoin.amount(200000), core_asset(1) );
      create_sell_order( bob, core_asset(1), jillcoin.amount(100000) );

      const auto izzyregistrar_reward = get_market_fee_reward( izzyregistrar, jillcoin );
      const auto izzyreferrer_reward = get_market_fee_reward( izzyreferrer, jillcoin );
      BOOST_CHECK_GT(izzyregistrar_reward , 0);
      BOOST_CHECK_GT(izzyreferrer_reward , 0);
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(white_list_contains_registrar_test)
{
   try
   {
      INVOKE(create_actors);

      generate_blocks_past_hf1268();
      GET_ACTOR(jill);

      constexpr auto jillcoin_reward_percent = 2*GRAPHENE_1_PERCENT;
      const asset_object &jillcoin = get_asset("JCOIN");

      GET_ACTOR(izzyregistrar);
      GET_ACTOR(izzyreferrer);
      flat_set<account_id_type> whitelist = {jill_id, izzyregistrar_id};

      update_asset(jill_id, jill_private_key, jillcoin.get_id(), jillcoin_reward_percent, whitelist);

      BOOST_CHECK_EQUAL( get_market_fee_reward( izzyregistrar, jillcoin ), 0 );
      BOOST_CHECK_EQUAL( get_market_fee_reward( izzyreferrer, jillcoin ), 0 );

      GET_ACTOR(alice);
      GET_ACTOR(bob);
      // Alice and Bob place orders which match
      create_sell_order( alice, jillcoin.amount(200000), core_asset(1) );
      create_sell_order( bob, core_asset(1), jillcoin.amount(100000) );

      const auto izzyregistrar_reward = get_market_fee_reward( izzyregistrar, jillcoin );
      const auto izzyreferrer_reward = get_market_fee_reward( izzyreferrer, jillcoin );
      BOOST_CHECK_GT(izzyregistrar_reward , 0);
      BOOST_CHECK_GT(izzyreferrer_reward , 0);
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(white_list_contains_referrer_test)
{
   try
   {
      INVOKE(create_actors);

      generate_blocks_past_hf1268();
      GET_ACTOR(jill);

      constexpr auto jillcoin_reward_percent = 2*GRAPHENE_1_PERCENT;
      const asset_object &jillcoin = get_asset("JCOIN");

      GET_ACTOR(izzyregistrar);
      GET_ACTOR(izzyreferrer);
      flat_set<account_id_type> whitelist = {jill_id, izzyreferrer_id};

      update_asset(jill_id, jill_private_key, jillcoin.get_id(), jillcoin_reward_percent, whitelist);

      BOOST_CHECK_EQUAL( get_market_fee_reward( izzyregistrar, jillcoin ), 0 );
      BOOST_CHECK_EQUAL( get_market_fee_reward( izzyreferrer, jillcoin ), 0 );

      GET_ACTOR(alice);
      GET_ACTOR(bob);
      // Alice and Bob place orders which match
      create_sell_order( alice, jillcoin.amount(200000), core_asset(1) );
      create_sell_order( bob, core_asset(1), jillcoin.amount(100000) );

      BOOST_CHECK_EQUAL( get_market_fee_reward( izzyregistrar, jillcoin ), 0 );
      BOOST_CHECK_EQUAL( get_market_fee_reward( izzyreferrer, jillcoin ), 0 );
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(white_list_doesnt_contain_registrar_test)
{
   try
   {
      INVOKE(create_actors);

      generate_blocks_past_hf1268();
      GET_ACTOR(jill);

      constexpr auto jillcoin_reward_percent = 2*GRAPHENE_1_PERCENT;
      const asset_object &jillcoin = get_asset("JCOIN");

      GET_ACTOR(alice);
      flat_set<account_id_type> whitelist = {jill_id, alice_id};

      update_asset(jill_id, jill_private_key, jillcoin.get_id(), jillcoin_reward_percent, whitelist);

      GET_ACTOR(izzyregistrar);
      GET_ACTOR(izzyreferrer);
      BOOST_CHECK_EQUAL( get_market_fee_reward( izzyregistrar, jillcoin ), 0 );
      BOOST_CHECK_EQUAL( get_market_fee_reward( izzyreferrer, jillcoin ), 0 );

      GET_ACTOR(bob);
      // Alice and Bob place orders which match
      create_sell_order( alice, jillcoin.amount(200000), core_asset(1) );
      create_sell_order( bob, core_asset(1), jillcoin.amount(100000) );

      BOOST_CHECK_EQUAL( get_market_fee_reward( izzyregistrar, jillcoin ), 0 );
      BOOST_CHECK_EQUAL( get_market_fee_reward( izzyreferrer, jillcoin ), 0);
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(create_asset_via_proposal_test)
{
   try
   {
      ACTOR(issuer);
      price core_exchange_rate(asset(1, asset_id_type(1)), asset(1));

      asset_create_operation create_op;
      create_op.issuer = issuer.id;
      create_op.fee = asset();
      create_op.symbol = "ASSET";
      create_op.common_options.max_supply = 0;
      create_op.precision = 2;
      create_op.common_options.core_exchange_rate = core_exchange_rate;
      create_op.common_options.max_supply = GRAPHENE_MAX_SHARE_SUPPLY;
      create_op.common_options.flags = charge_market_fee;

      additional_asset_options_t options;
      options.value.reward_percent = 100;
      options.value.whitelist_market_fee_sharing = flat_set<account_id_type>{issuer_id};
      create_op.common_options.extensions = std::move(options);;

      const auto& curfees = *db.get_global_properties().parameters.current_fees;
      const auto& proposal_create_fees = curfees.get<proposal_create_operation>();
      proposal_create_operation prop;
      prop.fee_paying_account = issuer_id;
      prop.proposed_ops.emplace_back( create_op );
      prop.expiration_time =  db.head_block_time() + fc::days(1);
      prop.fee = asset( proposal_create_fees.fee + proposal_create_fees.price_per_kbyte );

      {
         signed_transaction tx;
         tx.operations.push_back( prop );
         db.current_fee_schedule().set_fee( tx.operations.back() );
         set_expiration( db, tx );
         sign( tx, issuer_private_key );
         GRAPHENE_CHECK_THROW(PUSH_TX( db, tx ), fc::exception);
      }

      generate_blocks_past_hf1268();

      {
         prop.expiration_time =  db.head_block_time() + fc::days(1);
         signed_transaction tx;
         tx.operations.push_back( prop );
         db.current_fee_schedule().set_fee( tx.operations.back() );
         set_expiration( db, tx );
         sign( tx, issuer_private_key );
         PUSH_TX( db, tx );
      }
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(update_asset_via_proposal_test)
{
   try
   {
      ACTOR(issuer);
      asset_object usd_asset = create_user_issued_asset("USD", issuer, charge_market_fee);

      additional_asset_options_t options;
      options.value.reward_percent = 100;
      options.value.whitelist_market_fee_sharing = flat_set<account_id_type>{issuer_id};

      asset_update_operation update_op;
      update_op.issuer = issuer_id;
      update_op.asset_to_update = usd_asset.get_id();
      asset_options new_options;
      update_op.new_options = usd_asset.options;
      update_op.new_options.extensions = std::move(options);

      const auto& curfees = *db.get_global_properties().parameters.current_fees;
      const auto& proposal_create_fees = curfees.get<proposal_create_operation>();
      proposal_create_operation prop;
      prop.fee_paying_account = issuer_id;
      prop.proposed_ops.emplace_back( update_op );
      prop.expiration_time =  db.head_block_time() + fc::days(1);
      prop.fee = asset( proposal_create_fees.fee + proposal_create_fees.price_per_kbyte );

      {
         signed_transaction tx;
         tx.operations.push_back( prop );
         db.current_fee_schedule().set_fee( tx.operations.back() );
         set_expiration( db, tx );
         sign( tx, issuer_private_key );
         GRAPHENE_CHECK_THROW(PUSH_TX( db, tx ), fc::exception);
      }

      generate_blocks_past_hf1268();

      {
         prop.expiration_time =  db.head_block_time() + fc::days(1);
         signed_transaction tx;
         tx.operations.push_back( prop );
         db.current_fee_schedule().set_fee( tx.operations.back() );
         set_expiration( db, tx );
         sign( tx, issuer_private_key );
         PUSH_TX( db, tx );
      }
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(issue_asset){
   try
   {
       ACTORS((alice)(bob)(izzy)(jill));
      // Izzy issues asset to Alice  (Izzycoin market percent - 10%)
      // Jill issues asset to Bob    (Jillcoin market percent - 20%)

      fund( alice, core_asset(1000000) );
      fund( bob, core_asset(1000000) );
      fund( izzy, core_asset(1000000) );
      fund( jill, core_asset(1000000) );

      price price(asset(1, asset_id_type(1)), asset(1));
      constexpr auto izzycoin_market_percent = 10*GRAPHENE_1_PERCENT;
      asset_object izzycoin = create_user_issued_asset( "IZZYCOIN", izzy,  charge_market_fee, price, 2, izzycoin_market_percent );

      constexpr auto jillcoin_market_percent = 20*GRAPHENE_1_PERCENT;
      asset_object jillcoin = create_user_issued_asset( "JILLCOIN", jill,  charge_market_fee, price, 2, jillcoin_market_percent );

      // Alice and Bob create some coins
      issue_uia( alice, izzycoin.amount( 100000 ) );
      issue_uia( bob, jillcoin.amount( 100000 ) );
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(accumulated_fees_before_hf_test)
{
   try
   {
      INVOKE(issue_asset);

      const asset_object &jillcoin = get_asset("JILLCOIN");
      const asset_object &izzycoin = get_asset("IZZYCOIN");

      GET_ACTOR(alice);
      GET_ACTOR(bob);

      // Alice and Bob place orders which match
      create_sell_order( alice_id, izzycoin.amount(100), jillcoin.amount(300) );   // Alice is willing to sell her Izzy's for 3 Jill
      create_sell_order(   bob_id, jillcoin.amount(700), izzycoin.amount(200) );   // Bob is buying up to 200 Izzy's for up to 3.5 Jill

      // 100 Izzys and 300 Jills are matched, so the fees should be
      // 10 Izzy (10%) and 60 Jill (20%).
      BOOST_CHECK( izzycoin.dynamic_asset_data_id(db).accumulated_fees == izzycoin.amount(10).amount );
      BOOST_CHECK( jillcoin.dynamic_asset_data_id(db).accumulated_fees == jillcoin.amount(60).amount );
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(accumulated_fees_after_hf_test)
{
   try
   {
      INVOKE(issue_asset);

      generate_blocks_past_hf1268();

      const asset_object &jillcoin = get_asset("JILLCOIN");
      const asset_object &izzycoin = get_asset("IZZYCOIN");

      GET_ACTOR(alice);
      GET_ACTOR(bob);

      // Alice and Bob place orders which match
      create_sell_order( alice_id, izzycoin.amount(100), jillcoin.amount(300) );   // Alice is willing to sell her Izzy's for 3 Jill
      create_sell_order(   bob_id, jillcoin.amount(700), izzycoin.amount(200) );   // Bob is buying up to 200 Izzy's for up to 3.5 Jill

      // 100 Izzys and 300 Jills are matched, so the fees should be
      // 10 Izzy (10%) and 60 Jill (20%).
      BOOST_CHECK( izzycoin.dynamic_asset_data_id(db).accumulated_fees == izzycoin.amount(10).amount );
      BOOST_CHECK( jillcoin.dynamic_asset_data_id(db).accumulated_fees == jillcoin.amount(60).amount );
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE(accumulated_fees_with_additional_options_after_hf_test)
{
   try
   {
      INVOKE(issue_asset);

      generate_blocks_past_hf1268();

      GET_ACTOR(jill);
      GET_ACTOR(izzy);

      const asset_object &jillcoin = get_asset("JILLCOIN");
      const asset_object &izzycoin = get_asset("IZZYCOIN");

      uint16_t reward_percent = 0;
      update_asset(jill_id, jill_private_key, jillcoin.get_id(), reward_percent);
      update_asset(izzy_id, izzy_private_key, izzycoin.get_id(), reward_percent);

      GET_ACTOR(alice);
      GET_ACTOR(bob);

      // Alice and Bob place orders which match
      create_sell_order( alice_id, izzycoin.amount(100), jillcoin.amount(300) );   // Alice is willing to sell her Izzy's for 3 Jill
      create_sell_order(   bob_id, jillcoin.amount(700), izzycoin.amount(200) );   // Bob is buying up to 200 Izzy's for up to 3.5 Jill

      // 100 Izzys and 300 Jills are matched, so the fees should be
      // 10 Izzy (10%) and 60 Jill (20%).
      BOOST_CHECK( izzycoin.dynamic_asset_data_id(db).accumulated_fees == izzycoin.amount(10).amount );
      BOOST_CHECK( jillcoin.dynamic_asset_data_id(db).accumulated_fees == jillcoin.amount(60).amount );
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE( create_vesting_balance_with_instant_vesting_policy_before_hf1268_test )
{ try {

   ACTOR(alice);
   fund(alice);

   const asset_object& core = asset_id_type()(db);

   vesting_balance_create_operation op;
   op.fee = core.amount( 0 );
   op.creator = alice_id;
   op.owner = alice_id;
   op.amount = core.amount( 100 );
   op.policy = instant_vesting_policy_initializer{};

   trx.operations.push_back(op);
   set_expiration( db, trx );
   sign(trx, alice_private_key);

   GRAPHENE_REQUIRE_THROW(PUSH_TX( db, trx, ~0 ), fc::exception);

} FC_LOG_AND_RETHROW() }

BOOST_AUTO_TEST_CASE( create_vesting_balance_with_instant_vesting_policy_after_hf1268_test )
{ try {

   ACTOR(alice);
   fund(alice);

   generate_blocks_past_hf1268();

   const asset_object& core = asset_id_type()(db);

   vesting_balance_create_operation op;
   op.fee = core.amount( 0 );
   op.creator = alice_id;
   op.owner = alice_id;
   op.amount = core.amount( 100 );
   op.policy = instant_vesting_policy_initializer{};

   trx.operations.push_back(op);
   set_expiration( db, trx );

   processed_transaction ptx = PUSH_TX( db, trx, ~0 );
   const vesting_balance_id_type& vbid = ptx.operation_results.back().get<object_id_type>();

   auto withdraw = [&](const asset& amount) {
      vesting_balance_withdraw_operation withdraw_op;
      withdraw_op.vesting_balance = vbid;
      withdraw_op.owner = alice_id;
      withdraw_op.amount = amount;

      signed_transaction withdraw_tx;
      withdraw_tx.operations.push_back( withdraw_op );
      set_expiration( db, withdraw_tx );
      sign(withdraw_tx, alice_private_key);
      PUSH_TX( db, withdraw_tx );
   };
   // try to withdraw more then it is on the balance
   GRAPHENE_REQUIRE_THROW(withdraw(op.amount.amount + 1), fc::exception);
   //to withdraw all that is on the balance
   withdraw(op.amount);
   // try to withdraw more then it is on the balance
   GRAPHENE_REQUIRE_THROW(withdraw( core.amount(1) ), fc::exception);
} FC_LOG_AND_RETHROW() }

BOOST_AUTO_TEST_CASE( create_vesting_balance_with_instant_vesting_policy_via_proposal_test )
{ try {

   ACTOR(actor);
   fund(actor);

   const asset_object& core = asset_id_type()(db);

   vesting_balance_create_operation create_op;
   create_op.fee = core.amount( 0 );
   create_op.creator = actor_id;
   create_op.owner = actor_id;
   create_op.amount = core.amount( 100 );
   create_op.policy = instant_vesting_policy_initializer{};

   const auto& curfees = *db.get_global_properties().parameters.current_fees;
   const auto& proposal_create_fees = curfees.get<proposal_create_operation>();
   proposal_create_operation prop;
   prop.fee_paying_account = actor_id;
   prop.proposed_ops.emplace_back( create_op );
   prop.expiration_time =  db.head_block_time() + fc::days(1);
   prop.fee = asset( proposal_create_fees.fee + proposal_create_fees.price_per_kbyte );

   {
      signed_transaction tx;
      tx.operations.push_back( prop );
      db.current_fee_schedule().set_fee( tx.operations.back() );
      set_expiration( db, tx );
      sign( tx, actor_private_key );
      GRAPHENE_CHECK_THROW(PUSH_TX( db, tx ), fc::exception);
   }

   generate_blocks_past_hf1268();

   {
      prop.expiration_time =  db.head_block_time() + fc::days(1);
      signed_transaction tx;
      tx.operations.push_back( prop );
      db.current_fee_schedule().set_fee( tx.operations.back() );
      set_expiration( db, tx );
      sign( tx, actor_private_key );
      PUSH_TX( db, tx );
   }
} FC_LOG_AND_RETHROW() }

BOOST_AUTO_TEST_CASE(white_list_asset_rewards_test)
{
   try
   {
      ACTORS((aliceregistrar)(bobregistrar)(alicereferrer)(bobreferrer)(izzy)(jill));

      // Izzy issues white_list asset to Alice
      // Jill issues white_list asset to Bob
      // Bobreferrer added to blacklist for izzycoin asset
      // Aliceregistrar added to blacklist for jillcoin asset
      // Alice and Bob trade in the market and pay fees
      // Check registrar/referrer rewards
      upgrade_to_lifetime_member(aliceregistrar);
      upgrade_to_lifetime_member(alicereferrer);
      upgrade_to_lifetime_member(bobregistrar);
      upgrade_to_lifetime_member(bobreferrer);
      upgrade_to_lifetime_member(izzy);
      upgrade_to_lifetime_member(jill);

      const account_object alice = create_account("alice", aliceregistrar, alicereferrer, 20*GRAPHENE_1_PERCENT);
      const account_object bob   = create_account("bob", bobregistrar, bobreferrer, 20*GRAPHENE_1_PERCENT);

      fund( alice, core_asset(1000000) );
      fund( bob, core_asset(1000000) );
      fund( izzy, core_asset(1000000) );
      fund( jill, core_asset(1000000) );

      price price(asset(1, asset_id_type(1)), asset(1));
      constexpr auto izzycoin_market_percent = 10*GRAPHENE_1_PERCENT;
      constexpr auto jillcoin_market_percent = 20*GRAPHENE_1_PERCENT;
      const asset_id_type izzycoin_id = create_user_issued_asset( "IZZYCOIN", izzy, charge_market_fee|white_list, price, 0, izzycoin_market_percent ).id;
      const asset_id_type jillcoin_id = create_user_issued_asset( "JILLCOIN", jill, charge_market_fee|white_list, price, 0, jillcoin_market_percent ).id;

      // Alice and Bob create some coins
      issue_uia( alice, izzycoin_id(db).amount( 200000 ) );
      issue_uia( bob, jillcoin_id(db).amount( 200000 ) );

      generate_blocks_past_hf1268();

      constexpr auto izzycoin_reward_percent = 50*GRAPHENE_1_PERCENT;
      constexpr auto jillcoin_reward_percent = 50*GRAPHENE_1_PERCENT;

      update_asset(izzy_id, izzy_private_key, izzycoin_id, izzycoin_reward_percent);
      update_asset(jill_id, jill_private_key, jillcoin_id, jillcoin_reward_percent);

      BOOST_TEST_MESSAGE( "Attempting to blacklist bobreferrer for izzycoin asset" );
      asset_update_blacklist_authority(izzy_id, izzycoin_id, izzy_id, izzy_private_key);
      add_account_to_blacklist(izzy_id, bobreferrer_id, izzy_private_key);
      BOOST_CHECK( !(is_authorized_asset( db, bobreferrer_id(db), izzycoin_id(db) )) );

      BOOST_TEST_MESSAGE( "Attempting to blacklist aliceregistrar for jillcoin asset" );
      asset_update_blacklist_authority(jill_id, jillcoin_id, jill_id, jill_private_key);
      add_account_to_blacklist(jill_id, aliceregistrar_id, jill_private_key);
      BOOST_CHECK( !(is_authorized_asset( db, aliceregistrar_id(db), jillcoin_id(db) )) );

      // Alice and Bob place orders which match
      create_sell_order( alice.id, izzycoin_id(db).amount(1000), jillcoin_id(db).amount(1500) ); // Alice is willing to sell her 1000 Izzy's for 1.5 Jill
      create_sell_order(   bob.id, jillcoin_id(db).amount(1500), izzycoin_id(db).amount(1000) );   // Bob is buying up to 1500 Izzy's for up to 0.6 Jill

      // 1000 Izzys and 1500 Jills are matched, so the fees should be
      //   100 Izzy (10%) and 300 Jill (20%).

      // Only Bob's registrar should get rewards
      share_type bob_registrar_reward = get_market_fee_reward( bob.registrar, izzycoin_id );
      BOOST_CHECK_GT( bob_registrar_reward, 0 );
      BOOST_CHECK_EQUAL( get_market_fee_reward( bob.referrer, izzycoin_id ), 0 );
      BOOST_CHECK_EQUAL( get_market_fee_reward( alice.registrar, jillcoin_id ), 0 );
      BOOST_CHECK_EQUAL( get_market_fee_reward( alice.referrer, jillcoin_id ), 0 );
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_CASE( create_vesting_balance_object_test )
{
   /**
    * Test checks that an account could have duplicates VBO (with the same asset_type)
    * for any type of vesting_balance_type
    * except vesting_balance_type::market_fee_sharing
   */
   try {

      ACTOR(actor);

      create_vesting_balance_object(actor_id, vesting_balance_type::unspecified);
      create_vesting_balance_object(actor_id, vesting_balance_type::unspecified);

      create_vesting_balance_object(actor_id, vesting_balance_type::cashback);
      create_vesting_balance_object(actor_id, vesting_balance_type::cashback);

      create_vesting_balance_object(actor_id, vesting_balance_type::witness);
      create_vesting_balance_object(actor_id, vesting_balance_type::witness);

      create_vesting_balance_object(actor_id, vesting_balance_type::worker);
      create_vesting_balance_object(actor_id, vesting_balance_type::worker);

      create_vesting_balance_object(actor_id, vesting_balance_type::market_fee_sharing);
      GRAPHENE_CHECK_THROW(create_vesting_balance_object(actor_id, vesting_balance_type::market_fee_sharing), fc::exception);

} FC_LOG_AND_RETHROW() }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: roths/bitshares-core

max_issues_repo_name: roths/bitshares-core

max_forks_repo_name: roths/bitshares-core


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

#include "rt_debug.h"
#include "xdp/rt_singleton.h"
#include "xrt/util/message.h"
#include "xocl/api/plugin/xdp/debug.h"
#include "core/include/xclbin.h"
#include "core/common/xclbin_parser.h"

#include <boost/filesystem/operations.hpp>

#include <fstream>
#include <sstream>
#include <cstdio>

namespace xdp {

void
cb_debug_reset (const axlf* xclbin)
{
  xdp::RTSingleton::Instance()->getDebugManager()->reset(xclbin);
}

RTDebug::RTDebug() : uid(-1), pid(-1),
      	       sdxDirectory(""), jsonFile(""), dwarfFile("")
{
  uid = getuid() ;
  pid = getpid() ;

  // On start up, check to see if the directory /tmp/sdx/$uid exists.
  //  If it does, then the sdx_server is running, so we have to
  //  create the directory /tmp/sdx/$uid/$pid.

  std::stringstream directoryName ;
  directoryName << "/tmp/sdx/" << uid ;
  if (exists(directoryName.str().c_str()))
  {
    directoryName << "/" << pid ;
    if (!exists(directoryName.str().c_str()))
    {
      sdxDirectory = directoryName.str() ;
      createDirectory(sdxDirectory.c_str()) ;
    }
  }

  xocl::debug::register_cb_reset(cb_debug_reset);
}

RTDebug::~RTDebug()
{
  // Clean up the files and the directory we created.
  //  Regardless of each removal succeeds or fails, just move on.
  int result = 0 ;
  if (jsonFile != "")
  {
    result = std::remove(jsonFile.c_str()) ;
  }
  if (dwarfFile != "")
  {
    result = std::remove(dwarfFile.c_str()) ;
  }
  if (sdxDirectory != "")
  {
    result = std::remove(sdxDirectory.c_str()) ;
  }
  (void) result ; // For Coverity
}

// When the binary is being loaded, this function is called and
//  the debug information is extracted and dumped to the common
//  directory.
void RTDebug::reset(const axlf* xclbin)
{
  if (sdxDirectory.empty())
  {
    // If the directory doesn't exist, then we cannot dump the debug
    //  information
    return ;
  }

  // Extract the Debug data, split it into a DWARF file and a JSON
  // file, Treat the memory as the consolidated format header, and
  // extract out the DWARF and JSON section if they exist.  and dump
  // it into the directory.
  auto header = xrt_core::xclbin::axlf_section_type<const FileHeader*>::
    get(xclbin,axlf_section_kind::DEBUG_DATA);
  if (!header)
    // If the debug data section does not exist, don't dump anything
    return ;

  //  In order to make sure the meta data files are unique
  //  amongst multiple xclbin files, use the address as an
  //  identifier.

  std::stringstream dwarfName ;
  dwarfName << sdxDirectory << "/"
            << reinterpret_cast<unsigned long long int>(xclbin)
            << ".DWARF" ;
  dwarfFile = dwarfName.str() ;
  std::stringstream jsonName ;
  jsonName << sdxDirectory << "/"
           << reinterpret_cast<unsigned long long int>(xclbin)
           << ".JSON" ;
  jsonFile = jsonName.str() ;

  std::ofstream dwarfOut(dwarfFile, std::ofstream::binary) ;
  std::ofstream jsonOut(jsonFile, std::ofstream::binary) ;

  // If we could not open either of these files, we should output
  //  a warning.
  if (!dwarfOut || !jsonOut) {
    dwarfFile = "" ;
    jsonFile = "" ;
    std::stringstream errMsg ;
    errMsg << "Kernel debug data exists, but cannot open files in "
           << sdxDirectory
           << "/"
           << uid
           << " directory.  "
           << "Breakpoints set in kernels may not be honored."
           << std::endl ;
    xrt::message::send(xrt::message::severity_level::XRT_WARNING, errMsg.str()) ;
    return ;
  }

  for (unsigned int i = 0 ; i < header->numSections ; ++i) {
    auto sh = reinterpret_cast<const SectionHeader*>(header + sizeof(FileHeader) + sizeof(SectionHeader) * i) ;
    if (sh->type == DWARF_SECTION)
      dwarfOut.write(reinterpret_cast<const char*>(header) + sh->offset, sh->size) ;
    if (sh->type == JSON_SECTION)
      jsonOut.write(reinterpret_cast<const char*>(header) + sh->offset, sh->size) ;
  }
  dwarfOut.close() ;
  jsonOut.close() ;

  setEnvironment() ;
}

bool RTDebug::exists(const char* filename)
{
  return boost::filesystem::exists(filename);
}

void RTDebug::createDirectory(const char* filename)
{
  // If this succeeds, or fails, just return.
  try {
    boost::filesystem::create_directory(filename);
  }
  catch (...) {
  }
}

// Before spawning the XSim process, set the three environment
//  variables that pass information to the xsim process
void RTDebug::setEnvironment()
{
  std::stringstream convert ;
  convert << pid ;
  setenv("XILINX_HOST_CODE_PID", convert.str().c_str(), 1) ;
  if (dwarfFile != "")
  {
    setenv("XILINX_DWARF_FILE", dwarfFile.c_str(), 1) ;
  }
  if (jsonFile != "")
  {
    setenv("XILINX_JSON_FILE", jsonFile.c_str(), 1) ;
  }
}

} // xdp


text:
#include "writeline_atom.hpp"

#include <boost/bind.hpp>

#include "schema.hpp"

namespace janus {

WritelineAtom::WritelineAtom() : output_buffer_(1024) {}

void WritelineAtom::Initialize(RestOfWorld* row)
{

  row_ = row;
  stdout_stream_.reset(new boost::asio::posix::stream_descriptor(row->GetIoService(), ::dup(STDOUT_FILENO)));

  SchemaPtr input_expectations = std::make_shared<Schema>();
  input_expectations->has_name = true;
  input_expectations->name = "Line";
  input_expectations->schema_type = SchemaType::SCALAR;
  input_expectations->scalar_type = ValueType::STRING;

  output_.reset(new Interface(shared_from_this(),
                              InterfaceId(0),
                              "output",
                              InterfaceType::OUTPUT,
                              input_expectations));

  SchemaPtr output_expectations = std::make_shared<Schema>();
  output_expectations->has_name = true;
  output_expectations->name = "LineWritten";
  output_expectations->schema_type = SchemaType::SCALAR;
  output_expectations->scalar_type = ValueType::SIGNAL;

  input_.reset(new Interface(shared_from_this(),
                             InterfaceId(1),
                             "input",
                             InterfaceType::INPUT,
                             output_expectations));

  row_->Ready(input_);
}

void WritelineAtom::GetInterfaces(std::vector<InterfacePtr>& interfaces) const
{
  interfaces.clear();
  interfaces.push_back(input_);
  interfaces.push_back(output_);
}

// Receieved a Line to write to stdout.
Status WritelineAtom::Write(InterfaceId, ValuePtr value)
{
  Status status;
  output_buffer_.clear();
  const std::string &s = value->value_string;
  output_buffer_.insert(output_buffer_.begin(), s.begin(), s.end());
  boost::asio::async_write(*stdout_stream_, boost::asio::buffer(output_buffer_),
                           boost::bind(&WritelineAtom::HandleWriteComplete, this, _1, _2));
  return status;
}

// Asynchronous write to stdout as completed.
void WritelineAtom::HandleWriteComplete(const boost::system::error_code& error, std::size_t length)
{
  row_->Ready(output_);
}

Status WritelineAtom::Read(InterfaceId, ValuePtr& value)
{
  Status status;
  value.reset(new Value());
  value->has_name = true;
  value->name = "LineWritten";
  value->value_type = ValueType::SIGNAL;
  row_->Ready(input_);
  return status;
}

} // namespace janus

max_stars_repo_name: rphilander/janus

max_issues_repo_name: rphilander/janus

max_forks_repo_name: rphilander/janus


text:
// Test of EN_addrule, EN_deletenode & EN_deletelink EPANET API Functions
#define _CRT_SECURE_NO_DEPRECATE

/*
This is a test for the API functions that adds rules and deletes
nodes and links from a project. Deletion can be conditional on
node or link appearing in any simple or rule-based controls.
*/

//#define NO_BOOST

#ifndef NO_BOOST
#define BOOST_TEST_MODULE "toolkit"
#include <boost/test/included/unit_test.hpp>
#endif

#include <iostream>
#include <string>
#include "epanet2_2.h"

#define DATA_PATH_INP "./net1.inp"
#define DATA_PATH_RPT "./test.rpt"
#define DATA_PATH_OUT "./test.out"

#ifdef NO_BOOST
#define BOOST_REQUIRE(x) (((x)) ? cout << "\nPassed at line " << __LINE__ : cout << "\nFailed at line " << __LINE__ )
#endif

using namespace std;

char R1[] = "RULE 1 \n IF NODE 2 LEVEL < 100 \n THEN LINK 9 STATUS = OPEN";
char R2[] = "RULE 2\nIF SYSTEM TIME = 4\nTHEN LINK 9 STATUS = CLOSED\nAND LINK 31 STATUS = CLOSED";
char R3[] = "RULE 3\nIF NODE 23 PRESSURE ABOVE 140\nAND NODE 2 LEVEL > 120\n"
            "THEN LINK 113 STATUS = CLOSED\nELSE LINK 22 STATUS = CLOSED";

#ifndef NO_BOOST
BOOST_AUTO_TEST_SUITE (test_toolkit)
BOOST_AUTO_TEST_CASE(test_setlinktype)
#else
int main(int argc, char *argv[])
#endif
{
    int error = 0;
    int ruleCount, nP, nTA, nEA;
    int link113, node23, link22, pump9_before, pump9_after;
    double priority;

    EN_Project ph = NULL;
    EN_createproject(&ph);

    std::string path_inp = std::string(DATA_PATH_INP);
    std::string path_rpt = std::string(DATA_PATH_RPT);
    std::string path_out = std::string(DATA_PATH_OUT);

    error = EN_open(ph, path_inp.c_str(), path_rpt.c_str(), "");
    BOOST_REQUIRE(error == 0);

    // Add the 3 rules to the project
    error = EN_addrule(ph, R1);
    BOOST_REQUIRE(error == 0);
    error = EN_addrule(ph, R2);
    BOOST_REQUIRE(error == 0);
    error = EN_addrule(ph, R3);
    BOOST_REQUIRE(error == 0);

    // Check that rules were added
    error = EN_getcount(ph, EN_RULECOUNT, &ruleCount);
    BOOST_REQUIRE(ruleCount == 3);

    // Check the number of clauses in rule 3
    error = EN_getrule(ph, 3, &nP, &nTA, &nEA, &priority);
    BOOST_REQUIRE(nP == 2);
    BOOST_REQUIRE(nTA == 1);
    BOOST_REQUIRE(nTA == 1);

    // Try to delete link 113 conditionally which will fail
    // because it's in rule 3
    EN_getlinkindex(ph, "113", &link113);
    error = EN_deletelink(ph, link113, EN_CONDITIONAL);
    BOOST_REQUIRE(error == 261);

    // Delete node 23 unconditionally which will result in the
    // deletion of rule 3 as well as links 22 and 113
    EN_getnodeindex(ph, "23", &node23);
    EN_getlinkindex(ph, "22", &link22);
    EN_getlinkindex(ph, "9", &pump9_before);
    error = EN_deletenode(ph, node23, EN_UNCONDITIONAL);
    BOOST_REQUIRE(error == 0);

    // Check that there are now only 2 rules
    error = EN_getcount(ph, EN_RULECOUNT, &ruleCount);
    BOOST_REQUIRE(ruleCount == 2);

    // Check that link 22 no longer exists
    error = EN_getlinkindex(ph, "22", &link22);
    BOOST_REQUIRE(error > 0);

    // Check that the index of pump9 has been reduced by 2
    error = EN_getlinkindex(ph, "9", &pump9_after);
    BOOST_REQUIRE(pump9_before - pump9_after == 2);

    // Close and delete project
    error = EN_close(ph);
    BOOST_REQUIRE(error == 0);
    EN_deleteproject(&ph);
}
#ifndef NO_BOOST
BOOST_AUTO_TEST_SUITE_END()
#endif


text: #include <boost/msm/back/bind_helpers.hpp>


text:
//
//  monero_fee_utils.hpp
//  Copyright (c) 2014-2019, MyMonero.com
//
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification, are
//  permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice, this list of
//	conditions and the following disclaimer.
//
//  2. Redistributions in binary form must reproduce the above copyright notice, this list
//	of conditions and the following disclaimer in the documentation and/or other
//	materials provided with the distribution.
//
//  3. Neither the name of the copyright holder nor the names of its contributors may be
//	used to endorse or promote products derived from this software without specific
//	prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
//  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
//  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
//  THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
//  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
//  THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
#ifndef monero_fee_utils_hpp
#define monero_fee_utils_hpp
//
#include <boost/optional.hpp>
//
#include "string_tools.h"
//
#include "crypto.h"
#include "cryptonote_basic.h"
#include "cryptonote_format_utils.h"
//
#include "monero_fork_rules.hpp"
//
namespace monero_fee_utils
{
	using namespace std;
	using namespace boost;
	using namespace cryptonote;
	using namespace monero_fork_rules;
	using namespace crypto;
	//
	uint32_t default_priority();
	//
	uint64_t get_upper_transaction_weight_limit(uint64_t upper_transaction_weight_limit__or_0_for_default, use_fork_rules_fn_type use_fork_rules_fn);
	uint64_t get_fee_multiplier(uint32_t priority, uint32_t default_priority, int fee_algorithm, use_fork_rules_fn_type use_fork_rules_fn);
	int get_fee_algorithm(use_fork_rules_fn_type use_fork_rules_fn);
	uint64_t get_base_fee(uint64_t fee_per_b);
	//
	uint64_t estimate_fee(bool use_per_byte_fee, bool use_rct, int n_inputs, int mixin, int n_outputs, size_t extra_size, bool bulletproof, bool clsag, uint64_t base_fee, uint64_t fee_multiplier, uint64_t fee_quantization_mask);
	//
	uint64_t calculate_fee_from_weight(uint64_t base_fee, uint64_t weight, uint64_t fee_multiplier, uint64_t fee_quantization_mask);
	uint64_t calculate_fee(bool use_per_byte_fee, const cryptonote::transaction &tx, size_t blob_size, uint64_t base_fee, uint64_t fee_multiplier, uint64_t fee_quantization_mask);
	//
	/*Added*/ uint64_t calculate_fee_from_size(uint64_t fee_per_b, size_t bytes, uint64_t fee_multiplier);
	//
	size_t estimate_rct_tx_size(int n_inputs, int mixin, int n_outputs, size_t extra_size, bool bulletproof, bool clsag);
	uint64_t estimate_tx_weight(bool use_rct, int n_inputs, int mixin, int n_outputs, size_t extra_size, bool bulletproof, bool clsag);
	size_t estimate_tx_size(bool use_rct, int n_inputs, int mixin, int n_outputs, size_t extra_size, bool bulletproof, bool clsag);
	uint64_t estimated_tx_network_fee( // convenience function for size + calc
		uint64_t fee_per_b,
		uint32_t priority, // when priority=0, falls back to monero_fee_utils::default_priority()
		use_fork_rules_fn_type use_fork_rules_fn // this is extracted to a function so that implementations can optionally query the daemon (although this presently implies that such a call remains blocking)
	);
}

#endif /* monero_fee_utils_hpp */

max_stars_repo_name: j-berman/havenwallet-core-cpp

max_issues_repo_name: j-berman/havenwallet-core-cpp

max_forks_repo_name: j-berman/havenwallet-core-cpp


text:
//
// Created by Rakesh on 10/05/2020.
//

#include "server.h"
#include "decoder.h"
#include "log/NanoLog.h"
#include "tcp/server.h"
#include "websocket/listener.h"

#include <boost/asio/dispatch.hpp>
#include <boost/asio/signal_set.hpp>

#include <cstdlib>
#include <thread>
#include <vector>

int spt::server::run( util::Configuration::Ptr configuration )
{
  GeoDecoder::instance( configuration->file );
  auto const address = boost::asio::ip::make_address( "0.0.0.0" );
  auto const port = static_cast<unsigned short>( configuration->wsport );

  boost::asio::io_context ioc{ configuration->threads };

  boost::asio::signal_set signals( ioc, SIGINT, SIGTERM );
  signals.async_wait( [&]( boost::system::error_code const&, int ) { ioc.stop(); });

  websocket::listen( ioc, boost::asio::ip::tcp::endpoint{ address, port } );
  tcp::Server s{ configuration, ioc };

  // Run the I/O service on the requested number of threads
  std::vector<std::thread> v;
  v.reserve( configuration->threads - 1 );
  for( auto i = configuration->threads - 1; i > 0; --i )
  {
    v.emplace_back( [&ioc] { ioc.run(); });
  }

  LOG_INFO << "HTTP service started on port " << configuration->wsport;
  ioc.run();

  LOG_INFO << "TCP and HTTP service stopping";

  for ( auto& t : v ) t.join();

  LOG_INFO << "All I/O threads stopped";

  return EXIT_SUCCESS;
}

max_stars_repo_name: sptrakesh/mmdb-ws

max_issues_repo_name: sptrakesh/mmdb-ws

max_forks_repo_name: sptrakesh/mmdb-ws