text:
/*
 * GapFillPlugin.cpp
 *
 *  Created on: 5 Feb 2019
 *      Author: Alan Greer
 */
#include "GapFillPlugin.h"
#include "version.h"
#include "DebugLevelLogger.h"
#include <boost/algorithm/string.hpp>

#include "DataBlockFrame.h"

namespace FrameProcessor
{
    /* Config Names*/
    const std::string GapFillPlugin::CONFIG_GRID_SIZE = "grid_size";
    const std::string GapFillPlugin::CONFIG_CHIP_SIZE = "chip_size";
    const std::string GapFillPlugin::CONFIG_GRID_X_GAPS = "x_gaps";
    const std::string GapFillPlugin::CONFIG_GRID_Y_GAPS = "y_gaps";

    /**
     * Constructor for this class.
     */
    GapFillPlugin::GapFillPlugin()
    {
        logger_ = Logger::getLogger("FP.GapFillPlugin");
        logger_->setLevel(Level::getAll());
        LOG4CXX_INFO(logger_, "GapFillPlugin version " << this->get_version_long() << " loaded");
    }

    GapFillPlugin::~GapFillPlugin()
    {
        // Nothing to do in the destructor
    }

    /**
     * Process received frame.
     *
     * \param[in] frame - pointer to a frame object.
     */
    void GapFillPlugin::process_frame(boost::shared_ptr<Frame> frame)
    {
        LOG4CXX_TRACE(logger_, "GapFillPlugin Process Frame.");

        // Call the insert gaps method and push the resulting frame if it is not null
        if (this->configuration_valid(frame)){
            boost::shared_ptr<Frame> gap_frame = this->insert_gaps(frame);
            if (gap_frame){
                this->push(gap_frame);
            }
        }
    }

    /**
     * Check the validity of the configuration against the incoming frame.
     *
     * Checks the frame size is equal to the grid size X chip size in both directions.
     * Checks the number of gaps correspond to the specified grid size.
     *
     * \param[in] frame - pointer to a frame object.
     * \return verified - true if the configuration is valid, false otherwise.
     */
    bool GapFillPlugin::configuration_valid(boost::shared_ptr<Frame> frame)
    {
        bool verified = false;
        dimensions_t frame_dimensions = frame->get_meta_data().get_dimensions();
        // Check the size of the incoming image is correct for the defined grid and chip size
        if (frame_dimensions[0] != grid_[0] * chip_[0]){
            std::stringstream ss;
            ss << "GapFill - Inconsistent frame dimension[0] => "
               << frame_dimensions[0]
               << " compared with (grid[0] x chip[0]) => "
               << grid_[0] * chip_[0];
            this->set_error(ss.str());
        } else if (frame_dimensions[1] != grid_[1] * chip_[1]){
            std::stringstream ss;
            ss << "GapFill - Inconsistent frame dimension[1] => "
               << frame_dimensions[1]
               << " compared with (grid[1] x chip[1]) => "
               << grid_[1] * chip_[1];
            this->set_error(ss.str());
        } else if (grid_[1]+1 > gaps_x_.size()){
            std::stringstream ss;
            ss << "GapFill - Grid size [1] => "
               << grid_[1]
               << " not enough x gap values speficied (should be "
               << grid_[1]+1 << ")";
            this->set_error(ss.str());
        } else if (grid_[0]+1 > gaps_y_.size()){
            std::stringstream ss;
            ss << "GapFill - Grid size [0] => "
               << grid_[0]
               << " not enough y gap values speficied (should be "
               << grid_[0]+1 << ")";
            this->set_error(ss.str());
        } else if (grid_[1]+1 < gaps_x_.size()){
            std::stringstream ss;
            ss << "GapFill - Grid size [1] => "
               << grid_[1]
               << " too many x gap values speficied (should be "
               << grid_[1]+1 << ")";
            this->set_error(ss.str());
        } else if (grid_[0]+1 < gaps_y_.size()){
            std::stringstream ss;
            ss << "GapFill - Grid size [0] => "
               << grid_[0]
               << " too many y gap values speficied (should be "
               << grid_[0]+1 << ")";
            this->set_error(ss.str());
        } else {
            verified = true;
        }
        return verified;
    }

    /**
     * Insert gaps into the frame according to the grid, gap_x and gap_y values.
     *
     * A series of copies is made copying each row of each chip into the appropriate
     * destination offset.
     *
     * \param[in] frame - pointer to a frame object.
     * \return gap_frame - pointer to a frame that has gaps inserted.
     */
    boost::shared_ptr<Frame> GapFillPlugin::insert_gaps(boost::shared_ptr<Frame> frame) {

        boost::shared_ptr<Frame> gap_frame;

        dimensions_t frame_dimensions = frame->get_meta_data().get_dimensions();

        int img_x = grid_[1] * chip_[1];
        for (int index = 0; index <= grid_[1]; index++){
            img_x += gaps_x_[index];
        }
        LOG4CXX_TRACE(logger_, "New image width: " << img_x);
        int img_y = grid_[0] * chip_[0];
        for (int index = 0; index <= grid_[0]; index++){
            img_y += gaps_y_[index];
        }
        LOG4CXX_TRACE(logger_, "New image height: " << img_y);

        size_t frame_data_type_size = get_size_from_enum(frame->get_meta_data().get_data_type());
        // Malloc the required memory
        void *new_image = malloc(img_x * img_y * frame_data_type_size);
        // Memset to ensure empty values
        memset(new_image, 0, img_x * img_y * frame_data_type_size);

        // Loop over the y grid
        int current_offset_y = 0;
        for (int y_index = 0; y_index < grid_[0]; y_index++) {
            current_offset_y += gaps_y_[y_index];
            // Loop over the individual y rows for the grid item
            for (int y_row = 0; y_row < chip_[0]; y_row++) {
                int current_offset_x = 0;
                int current_src_row = (y_index * chip_[0]) + y_row;
                int current_dest_row = current_src_row + current_offset_y;
                // Loop over the x grid
                for (int x_index = 0; x_index < grid_[1]; x_index++) {
                    // Calculate the current total x gap in pixels
                    current_offset_x += gaps_x_[x_index];

                    // src offset is the src row multiplied by the width + the current grid multiplied by chip width
                    int src_offset = (current_src_row * frame_dimensions[1]) + (x_index * chip_[1]);
                    // Multiply dest_offset by the data type size
                    src_offset *= frame_data_type_size;

                    char *src_ptr = (char *)frame->get_image_ptr();
                    src_ptr += src_offset;

                    // Dest offset is full width * (current_y_gap + (y_grid_index * chip_y) + y_row)
                    int dest_offset = (current_dest_row * img_x) + current_offset_x + (x_index * chip_[1]);
                    // Multiply dest_offset by the data type size
                    dest_offset *= frame_data_type_size;

                    char *dest_ptr = (char *)new_image;
                    dest_ptr += dest_offset;
                    // Now copy a single row of a single chip from the src to the destination
                    memcpy(dest_ptr, src_ptr, chip_[1] * frame_data_type_size);
                }
            }
        }
        // Create the return frame
        dimensions_t img_dims(2);
        img_dims[0] = img_y;
        img_dims[1] = img_x;

       FrameProcessor::FrameMetaData frame_meta = frame->get_meta_data_copy();
       frame_meta.set_dimensions(img_dims);

       gap_frame = boost::shared_ptr<FrameProcessor::DataBlockFrame>(
                new FrameProcessor::DataBlockFrame(frame_meta, static_cast<void*>(new_image), img_x * img_y * get_size_from_enum(frame->get_meta_data().get_data_type())));

        // Free the allocated memory
        free(new_image);
        return gap_frame;
    }

    /**
     * Set configuration options for this Plugin.
     *
     * This sets up the Live View Plugin according to the configuration IpcMessage
     * objects that are received.
     *
     * \param[in] config - IpcMessage containing configuration data.
     * \param[out] reply - Response IpcMessage.
     */
    void GapFillPlugin::configure(OdinData::IpcMessage& config, OdinData::IpcMessage& reply)
    {
        try{
            // Check if the grid size is being set
            if (config.has_param(CONFIG_GRID_SIZE)){
                const rapidjson::Value& val = config.get_param<const rapidjson::Value&>(CONFIG_GRID_SIZE);
                // Loop over the grid size values
                grid_.clear();
                grid_.resize(val.Size());
                for (rapidjson::SizeType i = 0; i < val.Size(); i++) {
                    const rapidjson::Value& dim = val[i];
                    grid_[i] = dim.GetInt();
                }
                LOG4CXX_DEBUG_LEVEL(1, logger_, "Grid size set to [" << grid_[0] << " x " << grid_[1] << "]");
            }

            // Check if the chip size is being set
            if (config.has_param(CONFIG_CHIP_SIZE)){
                const rapidjson::Value& val = config.get_param<const rapidjson::Value&>(CONFIG_CHIP_SIZE);
                // Loop over the chip size values
                chip_.clear();
                chip_.resize(val.Size());
                for (rapidjson::SizeType i = 0; i < val.Size(); i++) {
                    const rapidjson::Value& dim = val[i];
                    chip_[i] = dim.GetInt();
                }
                LOG4CXX_DEBUG_LEVEL(1, logger_, "Chip size set to [" << chip_[0] << " x " << chip_[1] << "].");
            }

            // Check if the X grid gaps are being set
            if (config.has_param(CONFIG_GRID_X_GAPS)){
                const rapidjson::Value& val = config.get_param<const rapidjson::Value&>(CONFIG_GRID_X_GAPS);
                // Loop over the chip size values
                gaps_x_.clear();
                gaps_x_.resize(val.Size());
                std::stringstream ss;
                for (rapidjson::SizeType i = 0; i < val.Size(); i++) {
                    const rapidjson::Value& gap = val[i];
                    gaps_x_[i] = gap.GetInt();
                    ss << gaps_x_[i];
                    if (i < val.Size() - 1){
                        ss << ", ";
                    }
                }
                LOG4CXX_DEBUG_LEVEL(1, logger_, "X Gaps set to [" << ss.str() << "].");
            }

            // Check if the Y grid gaps are being set
            if (config.has_param(CONFIG_GRID_Y_GAPS)){
                const rapidjson::Value& val = config.get_param<const rapidjson::Value&>(CONFIG_GRID_Y_GAPS);
                // Loop over the chip size values
                gaps_y_.clear();
                gaps_y_.resize(val.Size());
                std::stringstream ss;
                for (rapidjson::SizeType i = 0; i < val.Size(); i++) {
                    const rapidjson::Value& gap = val[i];
                    gaps_y_[i] = gap.GetInt();
                    ss << gaps_y_[i];
                    if (i < val.Size() - 1){
                        ss << ", ";
                    }
                }
                LOG4CXX_DEBUG_LEVEL(1, logger_, "Y Gaps set to [" << ss.str() << "].");
            }

        }
        catch (std::runtime_error& e)
        {
            std::stringstream ss;
            ss << "Bad ctrl msg: " << e.what();
            this->set_error(ss.str());
            throw;
        }
    }

    int GapFillPlugin::get_version_major()
    {
        return ODIN_DATA_VERSION_MAJOR;
    }

    int GapFillPlugin::get_version_minor()
    {
        return ODIN_DATA_VERSION_MINOR;
    }

    int GapFillPlugin::get_version_patch()
    {
        return ODIN_DATA_VERSION_PATCH;
    }

    std::string GapFillPlugin::get_version_short()
    {
        return ODIN_DATA_VERSION_STR_SHORT;
    }

    std::string GapFillPlugin::get_version_long()
    {
        return ODIN_DATA_VERSION_STR;
    }

    /**
     * Get the configuration values for this Plugin.
     *
     * \param[out] reply - Response IpcMessage.
     */
    void GapFillPlugin::requestConfiguration(OdinData::IpcMessage& reply)
    {
        for (int index = 0; index < grid_.size(); index++) {
            reply.set_param(get_name() + "/" + CONFIG_GRID_SIZE + "[]", grid_[index]);
        }
        for (int index = 0; index < chip_.size(); index++) {
            reply.set_param(get_name() + "/" + CONFIG_CHIP_SIZE + "[]", chip_[index]);
        }
        for (int index = 0; index < gaps_x_.size(); index++) {
            reply.set_param(get_name() + "/" + CONFIG_GRID_X_GAPS + "[]", gaps_x_[index]);
        }
        for (int index = 0; index < gaps_y_.size(); index++) {
            reply.set_param(get_name() + "/" + CONFIG_GRID_Y_GAPS + "[]", gaps_y_[index]);
        }
    }

} //namespace FrameProcessor

max_stars_repo_name: dls-controls/odin-data

max_issues_repo_name: dls-controls/odin-data

max_forks_repo_name: dls-controls/odin-data


text:
#include "pch.h"

#include "config.h"

// stl
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

// boost::program_options
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
namespace po = boost::program_options;

const string cfg_file_name("player.cfg");

bool read_config(Configuration& cfg)
{
  // Declare a group of options that will be allowed both on command line and in
  // config file
  po::options_description desc("Configuration");
  desc.add_options()(
      "device", po::value<s32>(&cfg.device_)->default_value(-1), "CUDA device")(
      "vsync", po::value<bool>(&cfg.vsync_)->default_value(true),
      "Vertical sync")(
      "vsync_interval", po::value<u32>(&cfg.vsync_interval_)->default_value(1),
      "Vertical sync interval")(
      "fullscreen", po::value<bool>(&cfg.fullscreen_)->default_value(true),
      "Fullscreen")(
      "screen_w", po::value<u32>(&cfg.screen_w_)->default_value(1920),
      "Screen resolution, width")(
      "screen_h", po::value<u32>(&cfg.screen_h_)->default_value(1080),
      "Screen resolution, height")(
      "transform_ss_x", po::value<u32>(&cfg.transform_ss_x_)->default_value(1),
      "Supersampling, horizontal")(
      "transform_ss_y", po::value<u32>(&cfg.transform_ss_y_)->default_value(1),
      "Supersampling, vertical")(
      "zoom_step", po::value<double>(&cfg.zoom_step_)->default_value(1.005),
      "Zoom step")(
      "fractal_box_ss", po::value<u32>(&cfg.fractal_box_ss_)->default_value(1),
      "Fractal box supersampling")(
      "boxes_per_frame",
      po::value<u32>(&cfg.boxes_per_frame_)->default_value(1),
      "Fractal boxes per frame")(
      "bailout", po::value<u32>(&cfg.bailout_)->default_value(2000),
      "Mandelbrot bailout value")(
      "grayscale", po::value<bool>(&cfg.grayscale_)->default_value(false),
      "Grayscale")(
      "timers", po::value<bool>(&cfg.timers_)->default_value(false),
      "Display timer bars")(
      "single_precision",
      po::value<bool>(&cfg.single_precision_)->default_value(false),
      "Single precision fractal calculation");

  ifstream cfg_file;
  cfg_file.open(cfg_file_name.c_str());
  if (!cfg_file.good()) {
    cout << "Could not open configuration file: " << cfg_file_name << endl;
    return false;
  }

  po::variables_map vm;
  try {
    po::store(po::parse_config_file(cfg_file, desc, false), vm);
  } catch (std::exception& e) {
    cout << "Error in configuration file: " << cfg_file_name << endl;
    cout << e.what() << endl;
    return false;
  }
  po::notify(vm);

  // if (vm.count("compression")) {
  //  cout << "Compression level was set to "
  //    << vm["compression"].as<int>() << ".\n";
  //} else {
  //  cout << "Compression level was not set.\n";
  //}

  return true;
}

ext: cpp

max_stars_repo_name: rogerdahl/cuda-benoit

max_issues_repo_name: rogerdahl/cuda-benoit

max_forks_repo_name: rogerdahl/cuda-benoit


text:
/*
 * Copyright (c) 2016 Surround.IO Corporation. All Rights Reserved.
 * Copyright (c) 2017 Xevo Inc. All rights reserved.
 *
 * 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.
 */

#undef NDEBUG
#include <atomic>
#include <boost/asio.hpp>
#include <ellis/core/array_node.hpp>
#include <ellis/core/emigration.hpp>
#include <ellis/core/immigration.hpp>
#include <ellis/core/map_node.hpp>
#include <ellis/core/system.hpp>
#include <ellis/core/node.hpp>
#include <ellis/core/err.hpp>
#include <ellis/codec/json.hpp>
#include <ellis_op/call_trace.hpp>
#include <ellis_op/time.hpp>
#include <ellis_op_private/using.hpp>
#include <thread>

/* Needed for server. */
#include <nghttp2/asio_http2.h>
#include <nghttp2/asio_http2_client.h>
#include <nghttp2/asio_http2_server.h>

using namespace ellis;

namespace ellis_op {

using std::atomic;

// TODO(jmc): rip this out at once!

/**
 * Unique identifier for a request.
 *
 * This is used for tracking a request across systems, though proxies may
 * prepend a prefix, or remap, for their own purposes (the latter is likely
 * to be safer).  The scheduler is responsible for guaranteeing that
 * these identifiers are unique amongst currently outstanding requests.
 *
 * Design note: a fixed size integer, say 64 bits, might be slightly more
 * efficient, but we are assuming that the overhead of encoding as a string
 * will be relatively low in terms of overall bandwidth given that we will
 * generally be choosing reliability and flexibility over the complications
 * associated with minor speed improvements.  Using a string may allow for
 * easier debugging, and gives proxies options besides request ID translation
 * for dealing with collisions from multiple connections.
 */
using req_id = string;

req_id autogenerate_req_id()
{
  // TODO: better random string, maybe check with scheduler for unique.
  return std::to_string((unsigned long)random());
}

/**
 * Make a request, which is an ellis::node with a particular structure.
 *
 * A proper request will always have the following fields:
 *
 * - id
 * - module
 * - procedure
 * - params
 *
 * It may also optionally include:
 *
 * - is_tracing
 */
unique_ptr<node> make_request(
    const string &mod,
    const string &proc,
    const node &params,
    const req_id &id = autogenerate_req_id(),
    bool is_tracing = false)
{
  auto n = make_unique<node>(::ellis::type::MAP);
  auto & a = n->as_mutable_map();
  a.insert("id", id);
  a.insert("module", mod);
  a.insert("procedure", proc);
  a.insert("params", params);
  a.insert("is_tracing", is_tracing);
  return n;
}

/**
 * Make a response, patterned off of a request.
 *
 * A response is an ellis::node with a particular structure...
 * A proper response will always have the following fields:
 *
 * - id
 * - module
 * - procedure
 * - nanos
 *
 * It will eventually include exactly one of the following:
 *
 * - error
 * - result
 *
 * It may also optionally include:
 *
 * - trace_info
 */
unique_ptr<node> make_response(
    const node &req_model)
{
  auto n = make_unique<node>(::ellis::type::MAP);
  auto & a = n->as_mutable_map();
  auto &ra = req_model.as_map();
  auto id = (const char *)ra["id"];
  auto mod = (const char *)ra["module"];
  auto proc = (const char *)ra["procedure"];
  a.insert("id", id);
  a.insert("module", mod);
  a.insert("procedure", proc);
  return n;
}

/**
 * Convenience function to get access a particular field of a request or
 * response and convert it to const char pointer.
 */
const char * get_strfield(const node &n, const char *key)
{
  return (const char *)(n.as_map()[key]);
}

/**
 * Convenience function to get make a debug-friendly label for a request or
 * response, using its method, procedure, and id fields.
 */
string get_debugid(const node &n)
{
  return ELLIS_SSTRING(get_strfield(n, "module")
      << "/" << get_strfield(n, "procedure")
      << "[" << get_strfield(n, "id") << "]");
}

/**
 * The owner of the data associated with a procedure call, while in progress.
 *
 * This object is guaranteed to live until all the responses have been
 * consumed by callbacks.
 */
class call {
public:
  unique_ptr<node> m_req;
  unique_ptr<node> m_resp;
  call_telemetry m_telemetry;
public:
  call(unique_ptr<node> req, bool is_tracing = true) :
    m_req(std::move(req))
  {
    m_telemetry.m_is_tracing = is_tracing;
    m_telemetry.m_start_time = now();
    ELLIS_OP_TRACE(m_req, &m_telemetry, "CREATED");
  }
  void complete(unique_ptr<node> resp)
  {
    m_resp = std::move(resp);
    ELLIS_OP_TRACE(m_req, &m_telemetry, "COMPLETED");
    m_telemetry.m_total_nanos = (int64_t)(now() - m_telemetry.m_start_time);
    m_resp->as_mutable_map().insert("nanos", m_telemetry.m_total_nanos);
    if (m_telemetry.m_is_tracing) {
      auto trnode = node(ellis::type::ARRAY);
      auto & trnodea = trnode.as_mutable_array();
      for (auto &trent : m_telemetry.m_traces) {
        auto ent = node(ellis::type::ARRAY);
        ent.as_mutable_array().append(trent.m_stage);
        ent.as_mutable_array().append(trent.m_time.m_nanos_since_epoch);
        trnodea.append(ent);
      }
      m_resp->as_mutable_map().insert("trace_info", trnode);
    }
  }
};

/**
 * Exponential histogram, which records a histogram of the exponents
 * of values between 2**0 and 2**63.
 */
struct exp_histogram {
  int64_t m_counts[64];
};

/**
 * General stats object, for keeping track of count and sum, can do
 * average, min, max, population variance, and histogram.
 */
struct stats {
  int64_t m_count = 0;
  int64_t m_sum = 0;
  int64_t m_sum_square = 0;
  int64_t m_min = 0;
  int64_t m_max = 0;
  exp_histogram m_hist;
  void update(int64_t v)
  {
    m_count++;
    m_sum += v;
    m_sum_square += v*v;
    if (m_min > v) {
      m_min = v;
    }
    if (m_max < v) {
      m_max = v;
    }
  }
};

/**
 * A function to be called by a procedure implementation when it has
 * completed the response.
 */
using procedure_imp_cb = std::function<void(
    unique_ptr<node> resp)>;

/**
 * A procedure implementation.
 *
 * This is the function that does the work of computing the relevant response
 * for a given request.
 *
 * When complete, the implementation should call the complete() function on
 * the call object.
 */
using procedure_imp = std::function<void(
    call *c,
    const procedure_imp_cb &cb
    )>;

/**
 * Information that varies per procedure.
 */
struct procedure_info {
  string m_name;
  procedure_imp m_imp;
  // TODO: node m_schema;
  mutex m_stat_mutex;
  stats m_stats;  // since system start, for this procedure
  atomic<int64_t> m_num_in_flight {0};
  // TODO: actually update and use the stats

  procedure_info(const string &name, const procedure_imp &imp) :
    m_name(name),
    m_imp(imp)
  {
  }

  procedure_info(const procedure_info &) = delete;
  procedure_info & operator=(const procedure_info &) = delete;

  void update_stats(int64_t v)
  {
    unique_lock<mutex> lk(m_stat_mutex);
    m_stats.update(v);
  }
};

/**
 * A module is a collection of procedures and state that relate to a
 * particular type of functionality.
 */
class module_info {
  string m_name;
  map<string, unique_ptr<procedure_info>> m_procmap;
public:
  module_info(const string &name) : m_name(name)
  {
  }

  const string &get_name() const
  {
    return m_name;
  }

  /**
   * Add procedure info.
   */
  void add_procedure(const string &procname, const procedure_imp &imp)
  {
    m_procmap.emplace(procname, make_unique<procedure_info>(procname, imp));
  }

  /**
   * Lookup procedure info for the named procedure.
   *
   * Throws std::out_of_range if no such procedure name is known.
   */
  procedure_info &lookup_procedure_info(const string &procname)
  {
    return *(m_procmap.at(procname));
  }
};

/**
 * Callback function type.  This is the function that an async caller of
 * a procedure will provide, for notification when the procedure is finished
 * and the response ready, etc.
 *
 * Callee does not own the call (or by extension the request, response, or
 * call_telemetry contained inside).  Callee may assume that they will exist
 * until the callback function has finished, but must not assume that those
 * objects will continue to exist afterwards.
 */
using callback = std::function<void(call *)>;

/**
 * Config file example:
 *
 * {
 *   "module": {
 *     "video" : {
 *       "handler" : "video_server.so",
 *       "config" : { "synthesize_keyframes" : false }
 *     },
 *     "docdb" : {
 *       "handler" : "proxy.so",
 *       "config" : { "uris" : [ "http://w.x.y.z:port" ] }
 *     }
 *   }
 * }
 */

/**
 * This object schedules execution of calls, and arranges for cleanup on
 * completion.
 *
 * It maintains call lifetime by way of a shared_ptr that is bound by a
 * lambda, which is lower latency than having to synchronize manipulation
 * of a shared table, though it doesn't give us a way to ask about what calls
 * are in flight at any given moment.  If such features is later desired, we
 * can add such a table.
 *
 * At startup, there is one call tracker per system, which all threads
 * share.  Operations on this table, other than construction and destruction,
 * must be thread safe.  All outstanding calls tracked by this table are
 * guaranteed to have unique request ids.  If there are remote connections
 * made for a particular module (for forwarding requests to a remote server),
 * we'll share one connection per alias (e.g. server and role/credential).
 *
 * For now: always one copy, fossilized at startup.  In the future, as needed
 * for perf optimization: RCU map from thread local index to entry in vector of
 * scheduler that expands on demand.  Similarly, the internal thread
 * scheduling system may be changed in the future for higher performance.
 */
class scheduler {
  vector<std::thread> m_worker_threads;
  map<string, unique_ptr<module_info>> m_modules;
  boost::asio::io_service m_ios;
  boost::asio::io_service::work m_work;
  mutex m_sync_mu;
  condition_variable m_sync_cv;

public:
  scheduler() :
    m_ios(),
    m_work(m_ios)
  {
  }

  /* Not copyable. */
  scheduler(const scheduler &) = delete;
  scheduler & operator= (const scheduler &) = delete;

  ~scheduler()
  {
  }

  void add_module(unique_ptr<module_info> mi) {
    m_modules.emplace(mi->get_name(), std::move(mi));
  }

  void start()
  {
    // TODO: something less arbitrary here--depends on whether we will try to
    // preferentially isolate separate scheduler per thread and improve on
    // boost_asio's default semantics, external interactions, whether emphasis
    // would be on internal work vs RPC to server, etc.
    int num_threads = std::thread::hardware_concurrency();
    for (int i = 0; i < num_threads; i++) {
      m_worker_threads.emplace_back(
          [this, i]
          ()
          {
            ELLIS_LOG(DBUG, "worker thread %d starting", i);
            m_ios.run();
            ELLIS_LOG(DBUG, "worker thread %d stopping", i);
          });
    }
  }

  void stop()
  {
    m_ios.stop();
    // TODO: or should we do the work reset thing?  either way, what about
    // outstanding calls at stop() time?
    for (auto & thr : m_worker_threads) {
      thr.join();
    }
    m_worker_threads.clear();
  }

  void submit_async(
      unique_ptr<node> req,
      const callback &cb)
  {
    // TODO: replace std::out_of_range with different exception?
    const char *modname = get_strfield(*req, "module");
    ELLIS_LOG(DBUG, "looking up module %s", modname);
    auto &m = m_modules.at(modname);
    const char *procname = get_strfield(*req, "procedure");
    ELLIS_LOG(DBUG, "looking up procedure %s", procname);
    auto &procinfo = m->lookup_procedure_info(procname);
    procinfo.m_num_in_flight++;
    /* TODO: Validate request. */
    auto c = make_shared<call>(std::move(req));
    procedure_imp_cb finish =
      [this, cb, c, &procinfo]
      (unique_ptr<node> resp)
      {
        c->complete(std::move(resp));
        cb(c.get());
        procinfo.update_stats(c->m_telemetry.m_total_nanos);
        procinfo.m_num_in_flight--;
      };
    m_ios.post(
        [this, finish, c, &procinfo]
        ()
        {
          ELLIS_OP_TRACE(c->m_req, &c->m_telemetry, "CALL_RUN_IMP");
          (procinfo.m_imp)(c.get(), finish);
        });
  }

  unique_ptr<node> do_sync(
      unique_ptr<node> req)
  {
    unique_ptr<node> awaited_response;

    auto wake_func =
      [this, &awaited_response]
      (call *c)
      {
        ELLIS_LOG(DBUG, "waking up sync call");
        unique_lock<mutex> lk(m_sync_mu);
        /* Capture response to the awaited_response variable. */
        awaited_response = std::move(c->m_resp);
        lk.unlock();
        m_sync_cv.notify_one();
      };

    /* Submit request asynchronously... */
    submit_async(
        std::move(req),
        wake_func);

    /* Wait for completion signalling. */
    // TODO: improve all these log messages.
    ELLIS_LOG(DBUG, "sync call waiting for result");
    unique_lock<mutex> lk(m_sync_mu);
    m_sync_cv.wait(lk,
        [this, &awaited_response]()
        {
          /* Has the awaited response been furnished? */
          return (bool)awaited_response;
        });

    return awaited_response;
  }
};

namespace h2a = nghttp2::asio_http2;
namespace h2ac = nghttp2::asio_http2::client;
namespace h2as = nghttp2::asio_http2::server;

class h2_stream_handler {

  scheduler &m_sched;
  unique_ptr<decoder> m_deco;
  unique_ptr<encoder> m_enco;
  const h2as::request &m_h2req;
  const h2as::response &m_h2res;
  string m_path;
  node_progress m_st;
  unique_ptr<node> m_response_node;
  bool m_allow_chop = true;

public:
  h2_stream_handler(
      scheduler &sched,
      const h2as::request &h2req,
      const h2as::response &h2res) :
    m_sched(sched),
    m_deco(new json_decoder()),
    m_enco(new json_encoder()),
    m_h2req(h2req),
    m_h2res(h2res),
    m_st(stream_state::CONTINUE)
  {
    m_deco->reset();

    // TODO: don't hardcode decoder to json.
    // TODO: borrow from a pool of decoders rather than always creating.
    m_path = h2a::percent_decode(m_h2req.uri().path);
    // TODO: verify path, REST-compatibility logic, etc
  }

  void setup()
  {
    ELLIS_LOG(DBUG, "Setting up new h2 request handler.");
    /* First thing we do is make sure this stream state object will get
     * deleted when the stream is closed. */
    m_h2res.on_close(
        [this](uint32_t reason)
        {
          ELLIS_LOGSTREAM(DBUG, "Stream closed! reason: " << reason);
          delete this;
        });

    /* Set callback for data. */
    m_h2req.on_data(
        [this](const uint8_t *buf, size_t len)
        {
          ELLIS_LOG(DBUG, "Got data %zu bytes input payload:", len);
          if (len > 0) {
            if (m_st.state() == stream_state::CONTINUE) {
              /* Accumulate the data. */
              m_st = m_deco->consume_buffer((const byte *)buf, &len);
              if (m_st.state() == stream_state::SUCCESS) {
                m_allow_chop = false;
              }
            }
          }
          else {
            if (m_allow_chop) {
              m_st = m_deco->chop();
            }
            switch (m_st.state()) {
            case stream_state::ERROR:
              parse_fail(m_st.extract_error());
              return;

            case stream_state::CONTINUE:
              parse_fail(MAKE_UNIQUE_ELLIS_ERR(PARSE_FAIL,
                    "parse interrupted"));
              return;

            case stream_state::SUCCESS:
              parse_success(m_st.extract_value());
              return;
            }
          }
        });
  }
  void fill_header(
      unsigned int status_code,
      const std::initializer_list<pair<string,string>> &kvpairs)
  {
    ELLIS_LOG(DBUG, "Setting %u response status code", status_code);
    /* Set up h2 response headers. */
    auto hdrs = h2a::header_map();
    for (const auto &kv : kvpairs) {
      hdrs.emplace(kv.first, h2a::header_value{kv.second, false});
    }
    m_h2res.write_head(status_code, std::move(hdrs));
  }
  void parse_fail(unique_ptr<err> e)
  {
    string errtxt = e->summary();
    ELLIS_LOG(DBUG, "Sending parse failure response, error was %s",
        errtxt.c_str());
    fill_header(400, {
        {"Content-Type", "text/plain"},
        {"Content-Length", std::to_string(errtxt.size())}
        });
    m_h2res.end(errtxt);
  }
  void parse_success(unique_ptr<node> req)
  {
    ELLIS_LOG(DBUG, "Parse was successful; executing request.");
    m_sched.submit_async(std::move(req),
        [this]
        (call *c)
        {
          m_response_node = std::move(c->m_resp);
          got_response();
        });
  }
  void got_response()
  {
    ELLIS_LOG(DBUG, "Request finished executing; initiating repsonse.");
    // TODO: don't hardcode encoder type.
    fill_header(200, { {"Content-Type", "application/json" }});
    m_enco.reset(new json_encoder());
    m_enco->reset(m_response_node.get());
    h2a::generator_cb cb =
      [this]
      (uint8_t *buf, std::size_t len, uint32_t *data_flags)
      {
        ELLIS_LOG(DBUG, "Got output buffer, size %zu bytes", len);
        auto orig_len = len;
        auto st = m_enco->fill_buffer((byte *)buf, &len);
        switch (st.state()) {
        case stream_state::SUCCESS:
          ELLIS_LOG(DBUG, "Encoding successful, %zu bytes leftover", len);
          // TODO: don't hardcode content-type
          //fill_header(200, { "Content-Type", "application/json" });
          *data_flags = NGHTTP2_DATA_FLAG_EOF;
          return orig_len - len;
        case stream_state::ERROR:
          ELLIS_LOGSTREAM(DBUG, "Encoding error, "
              << st.extract_error()->summary());
          // TODO: how to handle error here?  I think we already have to have
          // set the headers before we call end() on the h2 response, in which
          // case how do we guard against partial encoding?
          //fill_header(500);
          *data_flags = NGHTTP2_DATA_FLAG_EOF;
          return (size_t)NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
        case stream_state::CONTINUE:
          ELLIS_LOG(DBUG, "Encoding used buffer completely, needs more...");
          *data_flags = 0;
          return orig_len - len;
        }
        ELLIS_ASSERT_UNREACHABLE();
      };
    m_h2res.end(cb);
  }
};

class h2_server {
  scheduler &m_sched;
  h2as::http2 m_srv;
  string m_ipaddr;
  string m_port;
  bool m_encrypted;
  string m_ssl_key_file;
  string m_ssl_cert_chain_file;
  boost::asio::ssl::context m_tls;
public:
  h2_server(
      scheduler &sched,
      const char *ipaddr,
      const char *port) :
    m_sched(sched),
    m_srv(),
    m_ipaddr(ipaddr),
    m_port(port),
    m_encrypted(false),
    m_ssl_key_file(),
    m_ssl_cert_chain_file(),
    m_tls(boost::asio::ssl::context::sslv23)
  {
  }
  h2_server(
      scheduler &sched,
      const char *ipaddr,
      const char *port,
      const char *ssl_key_file,
      const char *ssl_cert_chain_file) :
    m_sched(sched),
    m_srv(),
    m_ipaddr(ipaddr),
    m_port(port),
    m_encrypted(true),
    m_ssl_key_file(ssl_key_file),
    m_ssl_cert_chain_file(ssl_cert_chain_file),
    m_tls(boost::asio::ssl::context::sslv23)
  {
  }
  void start()
  {
    m_srv.num_threads(2);
    if (! m_srv.handle("/",
          [this]
          (const h2as::request &h2req, const h2as::response &h2res)
          {
            ELLIS_LOG(DBUG, "Creating new h2 stream handler.");
            auto rh = new h2_stream_handler(m_sched, h2req, h2res);
            rh->setup();
          })) {
      ELLIS_LOG(DBUG, "Oh no, handler registration failure.");
    }
    boost::system::error_code ec;
    if (m_encrypted) {
      ELLIS_LOG(DBUG, "Starting SSL server");
      m_tls.use_private_key_file(
          m_ssl_key_file.c_str(),
          boost::asio::ssl::context::pem);
      m_tls.use_certificate_chain_file(
          m_ssl_cert_chain_file.c_str());
      h2as::configure_tls_context_easy(ec, m_tls);
      if (m_srv.listen_and_serve(ec, m_tls, m_ipaddr, m_port, true)) {
        ELLIS_LOGSTREAM(DBUG, "error: " << ec.message());
      }
    }
    else {
      ELLIS_LOG(DBUG, "Starting non-SSL server");
      if (m_srv.listen_and_serve(ec, m_ipaddr, m_port, true)) {
        ELLIS_LOGSTREAM(DBUG, "error: " << ec.message());
      }
    }
  }
  void stop()
  {
    ELLIS_LOG(DBUG, "Stopping h2 server...");
    m_srv.stop();
  }
  void join()
  {
    ELLIS_LOG(DBUG, "Waiting for server shutdown...");
    m_srv.join();
  }
};

/**
 * An h2 client, for forwarding ellis op requests to a particular h2 server.
 */
class h2_client {
  enum class connect_state {
    NOT_CONNECTED,
    CONNECTING,
    CONNECTED,
    DISCONNECTING
  };
  boost::asio::io_service m_ios;
  vector<std::thread> m_worker_threads;
  unique_ptr<h2ac::session> m_sess;
  string m_ipaddr;
  string m_port;
  //bool m_encrypted;
  //string m_ssl_key_file;
  //string m_ssl_cert_chain_file;
  //boost::asio::ssl::context m_tls;
  mutex m_mutex;
  connect_state m_connect_state = connect_state::NOT_CONNECTED;
  deque<unique_ptr<node>> m_req_q;

public:
  h2_client(
      const char *ipaddr,
      const char *port) :
    m_ios(),
    m_worker_threads(),
    m_ipaddr(ipaddr),
    m_port(port)
    //m_encrypted(false),
    //m_ssl_key_file(),
    //m_ssl_cert_chain_file(),
    //m_tls(boost::asio::ssl::context::sslv23)
  {
    // TODO: don't automatically connect on construction; add logic to connect
    // on demand and disconnect after timeout.
    connect();
  }
  ~h2_client()
  {
    // TODO: assert disconnected?
  }
  void connect()
  {
    /* Update state. */
    {
      unique_lock<mutex> lk(m_mutex);
      m_connect_state = connect_state::CONNECTING;
    }
    ELLIS_LOG(DBUG, "Connecting to host %s port %s",
        m_ipaddr.c_str(), m_port.c_str());
    // TODO: session constructor can throw an exception.  What do we do when
    // a request can not be handled due to connection failure?  I guess we
    // reset connect retry timer--keep trying, don't fail the requests...
    // Possibly have a max tries parameter, defaults to forever...
    m_sess = make_unique<h2ac::session>(m_ios, m_ipaddr, m_port);
    m_sess->on_connect(
        [this]
        (boost::asio::ip::tcp::resolver::iterator endpoint_it)
        {
          std::cout << (*endpoint_it).endpoint();
          ELLIS_LOGSTREAM(DBUG, "connected to " << (*endpoint_it).endpoint());
          unique_lock<mutex> lk(m_mutex);
          m_connect_state = connect_state::CONNECTING;
          for (auto & c : m_req_q) {
            ELLIS_LOG(DBUG, "unqueued request: %s",
                get_debugid(*c).c_str());
            // TODO
            assert(0);
            /* submit */
          }
          m_req_q.clear();
        });
    int num_threads = 1;
    for (int i = 0; i < num_threads; i++) {
      m_worker_threads.emplace_back(
          [this, i]
          ()
          {
            ELLIS_LOG(DBUG, "h2_client worker thread %d starting", i);
            m_ios.run();
            ELLIS_LOG(DBUG, "h2_client worker thread %d stopping", i);
          });
    }
  }
  void disconnect()
  {
    ELLIS_LOG(DBUG, "Disconnecting h2_client...");
    // TODO: do I need to suspend/wait outstanding activity before shutdown?
    m_sess->shutdown();
    // TODO: verify that ios run will now exit on its own
    for (auto & thr : m_worker_threads) {
      thr.join();
    }
    m_worker_threads.clear();
  }
};

}  /* namespace ::ellis_op */

int main() {

  using namespace ::ellis_op;
  using namespace ::ellis;

  bool client_server_test = false;

  set_system_log_prefilter(log_severity::DBUG);
  auto hm = make_unique<module_info>("hello");
  hm->add_procedure("world",
      []
      (call *c, const procedure_imp_cb &cb)
      {
        /* Count the square of request's x parameter. */
        int64_t x = c->m_req->at("{params}{x}");
        auto resp = make_response(*(c->m_req));
        resp->install("{result}{x2}", x*x);
        cb(std::move(resp));
      });
  scheduler sched;
  sched.add_module(std::move(hm));
  sched.start();
  auto resp = sched.do_sync(make_request("hello", "world",
        {make_pair("x", 8)}));
  ELLIS_ASSERT_EQ(resp->at("{result}{x2}"), 64);

  if (client_server_test) {
    h2_server srv(sched, "127.0.0.1", "3350");
    srv.start();

    // block here
    srv.join();
  }

  sched.stop();
  return 0;
}

max_stars_repo_name: project-ellis/ellis-op


text:
#include "Exit.h"
// #include <boost/algorithm/string.hpp>
// #include <boost/bimap/bimap.hpp>
// #include <boost/bimap/unordered_set_of.hpp>
// using  namespace boost::bimaps;

using namespace std;

    //Constructors
    Exit::Exit(const string& exitName, const string& exitDescription, const std::string& cardinalDirection, std::string areaID, int roomID)
        : exitName(exitName), exitDescription(exitDescription)
        {
            exitDirection = getCardinalDirection(cardinalDirection);
            setTargetLocation(areaID, roomID);
        }

    /**
     * Returns the cardinal direction of a room as a string for viewing, displaying for the user to view
     */
    const string Exit::CardinalToString() const {
        const CardinalDirection &result = this->exitDirection;
        auto search = directionMap.find(result);
        if(search != directionMap.end()){
            return search->second;
        }

        return (stringManager.getString(Internationalization::STRING_CODE::DIRECTION_NOT_FOUND), "\n");

    }

    //REARRANGE THIS TO TAKE ADVANTAGE OF MAP "directionMap"
    //Getters
    Exit::CardinalDirection Exit::getCardinalDirection(const std::string& direction) {
        std::string input = direction;
        std::transform(input.begin(), input.end(), input.begin(), ::tolower);

        if(input == "north"){
            return Exit::CardinalDirection::NORTH;
        } else if(input == "northeast"){
            return Exit::CardinalDirection::NORTHEAST;
        } else if(input == "east"){
            return Exit::CardinalDirection::EAST;
        } else if(input == "southeast"){
            return Exit::CardinalDirection::SOUTHEAST;
        } else if(input == "south"){
            return Exit::CardinalDirection::SOUTH;
        } else if(input == "southwest"){
            return Exit::CardinalDirection::SOUTHWEST;
        } else if(input == "west"){
            return Exit::CardinalDirection::WEST;
        } else if(input == "northwest"){
            return Exit::CardinalDirection::NORTHWEST;
        } else if(input == "up"){
            return Exit::CardinalDirection::UP;
        } else if(input == "down"){
            return Exit::CardinalDirection::DOWN;
        }

        return Exit::CardinalDirection::NONE;
    }

    //A map that is used to convert ENUM's into strings for viewing
    const std::unordered_map<Exit::CardinalDirection, std::string> Exit::directionMap = {
            {NONE,"none"},
            {NORTH,"north"},
            {NORTHEAST,"northeast"},
            {EAST,"east"},
            {SOUTHEAST,"southeast"},
            {SOUTH,"south"},
            {SOUTHWEST,"southwest"},
            {WEST,"west"},
            {NORTHWEST,"northwest"},
            {UP,"up"},
            {DOWN,"down"}
    };

    /*
    Exit::CardinalDirection Exit::getCardinalDirection(const std::string& direction) {
        std::string input = direction;
        std::transform(input.begin(), input.end(), input.begin(), ::tolower);

        if(input == stringManager.getString(Internationalization::STRING_CODE::NORTH)){
            return Exit::CardinalDirection::NORTH;
        } else if(input == stringManager.getString(Internationalization::STRING_CODE::NORTHEAST)){
            return Exit::CardinalDirection::NORTHEAST;
        } else if(input == stringManager.getString(Internationalization::STRING_CODE::EAST)){
            return Exit::CardinalDirection::EAST;
        } else if(input == stringManager.getString(Internationalization::STRING_CODE::SOUTHEAST)){
            return Exit::CardinalDirection::SOUTHEAST;
        } else if(input == stringManager.getString(Internationalization::STRING_CODE::SOUTH)){
            return Exit::CardinalDirection::SOUTH;
        } else if(input == stringManager.getString(Internationalization::STRING_CODE::SOUTHWEST)){
            return Exit::CardinalDirection::SOUTHWEST;
        } else if(input == stringManager.getString(Internationalization::STRING_CODE::WEST)){
            return Exit::CardinalDirection::WEST;
        } else if(input == stringManager.getString(Internationalization::STRING_CODE::NORTHWEST)){
            return Exit::CardinalDirection::NORTHWEST;
        } else if(input == "up"){
            return Exit::CardinalDirection::UP;
        } else if(input == "down"){
            return Exit::CardinalDirection::DOWN;
        }

        return Exit::CardinalDirection::NONE;
    }

    //A map that is used to convert ENUM's into strings for viewing
    const std::unordered_map<Exit::CardinalDirection, std::string> Exit::directionMap = {
            {NONE,stringManager.getString(Internationalization::STRING_CODE::NONE)},
            {NORTH,stringManager.getString(Internationalization::STRING_CODE::NORTH)},
            {NORTHEAST,stringManager.getString(Internationalization::STRING_CODE::NORTHEAST)},
            {EAST,stringManager.getString(Internationalization::STRING_CODE::EAST)},
            {SOUTHEAST,stringManager.getString(Internationalization::STRING_CODE::SOUTHEAST)},
            {SOUTH,stringManager.getString(Internationalization::STRING_CODE::SOUTH)},
            {SOUTHWEST,stringManager.getString(Internationalization::STRING_CODE::SOUTHWEST)},
            {WEST,stringManager.getString(Internationalization::STRING_CODE::WEST)},
            {NORTHWEST,stringManager.getString(Internationalization::STRING_CODE::NORTHWEST)},
            {UP,"up"},
            {DOWN,"down"}
    };
    */

    const string &Exit::getExitName() const {return exitName;}

    const string Exit::getLowerCaseExitName() const {
        std::string result = exitName;
        // boost::algorithm::to_lower(result);
        return std::move(result);

    }

    const string Exit::getExitDescription() const {
        if (exitDescription.empty()) {
            return stringManager.getString(Internationalization::STRING_CODE::THIS_EXIT_HAS_NO_DESC);
        }
        return exitDescription;
    }

    Exit::CardinalDirection Exit::getCardinalDirection() const {return exitDirection;}
    LocationCoordinates Exit::getTargetLocation() const {return targetLocation;}

    //Setters
    void Exit::setExitName(const string &exitName) { Exit::exitName = exitName; }
    void Exit::setExitDescription(const string &exitDescription) { Exit::exitDescription = exitDescription; }
    void Exit::setCardinalDirection(Exit::CardinalDirection cardinalDirection) { exitDirection = cardinalDirection; }
    void Exit::setTargetLocation(std::string areaID, int roomID) {
        LocationCoordinates exitLocation;
        exitLocation.area = areaID;
        exitLocation.room = roomID;
        this->targetLocation = exitLocation;
    }
    void Exit::setTargetLocation(LocationCoordinates newLocation) {
        this->targetLocation = newLocation;
    }

    void Exit::setExitTargetLocation(const std::string & name) {
        this->exitTargetLocation = name;
    }

    std::string Exit::getExitTargetLocation() {
        return exitTargetLocation;
    }


text:
//==================================================================================================
/**
  EVE - Expressive Vector Engine
  Copyright : EVE Contributors & Maintainers
  SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include <boost/math/special_functions/laguerre.hpp>
#include <eve/function/laguerre.hpp>
#include <eve/constant/inf.hpp>
#include <eve/constant/minf.hpp>
#include <eve/constant/nan.hpp>
#include <eve/platform.hpp>
#include <cmath>

TTS_CASE_TPL("Check eve::laguerre return type", EVE_TYPE)
{
  TTS_EXPR_IS(eve::laguerre(0, T(0)), T);
}

TTS_CASE_TPL("Check eve::laguerre behavior", EVE_TYPE)
{

  auto eve__laguerre =  [](auto n, auto x) { return eve::laguerre(n, x); };
  auto boost_laguerre =  [](auto n, auto x) { return boost::math::laguerre(n, x); };
  using i_t = eve::as_integer_t<T,unsigned>;
  using elt_t = eve::element_type_t<T>;
  for(unsigned int i=0; i < 5; ++i)
  {
    for(elt_t v1 = -10; v1 <= 10; v1+=1)
    {
      auto v = v1/elt_t(10);
      TTS_ULP_EQUAL(eve__laguerre(i, T(v)), T(boost_laguerre(i, v)), 15);
      TTS_ULP_EQUAL(eve__laguerre(i_t(i), T(v)), T(boost_laguerre(i, v)), 15);
    }
  }
}

ext: hpp

max_stars_repo_name: orao/eve

max_issues_repo_name: orao/eve

max_forks_repo_name: orao/eve


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#include <boost/simd/bitwise/include/functions/bitwise_notand.hpp>
#include <boost/simd/sdk/simd/native.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/dispatch/functor/meta/call.hpp>
#include <nt2/sdk/unit/tests.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <boost/simd/constant/constant.hpp>

NT2_TEST_CASE_TPL ( bitwise_notand_real,  BOOST_SIMD_REAL_TYPES)
{

  using boost::simd::bitwise_notand;
  using boost::simd::tag::bitwise_notand_;
  typedef typename boost::dispatch::meta::call<bitwise_notand_(T,T)>::type r_t;
  typedef T wished_r_t;

  // return type conformity test
  NT2_TEST_TYPE_IS(r_t, wished_r_t);

  // specific values tests
#ifndef BOOST_SIMD_NO_INVALIDS
  NT2_TEST_EQUAL(bitwise_notand(boost::simd::Inf<T>(), boost::simd::Inf<T>()), boost::simd::Zero<r_t>());
  NT2_TEST_EQUAL(bitwise_notand(boost::simd::Minf<T>(), boost::simd::Minf<T>()), boost::simd::Zero<r_t>());
  NT2_TEST_EQUAL(bitwise_notand(boost::simd::Nan<T>(), boost::simd::Nan<T>()), boost::simd::Zero<r_t>());
#endif
  NT2_TEST_EQUAL(bitwise_notand(boost::simd::Zero<T>(), boost::simd::Zero<T>()), boost::simd::Zero<r_t>());
  NT2_TEST_EQUAL(bitwise_notand(boost::simd::Zero<T>(),boost::simd::One<T>()), boost::simd::One<r_t>());
} // end of test for floating_

NT2_TEST_CASE_TPL(bitwise_notand_mix, BOOST_SIMD_REAL_TYPES)
{
  using boost::simd::bitwise_notand;
  using boost::simd::tag::bitwise_notand_;
  using boost::simd::native;
  typedef typename  boost::dispatch::meta::as_integer<T>::type siT;
  typedef typename  boost::dispatch::meta::as_integer<T, unsigned>::type uiT;

  // return type conformity test
  NT2_TEST_TYPE_IS(typename boost::dispatch::meta::call<bitwise_notand_(T,uiT)>::type, T);
  NT2_TEST_TYPE_IS(typename boost::dispatch::meta::call<bitwise_notand_(T,siT)>::type, T);
  NT2_TEST_TYPE_IS(typename boost::dispatch::meta::call<bitwise_notand_(uiT, T)>::type, uiT);
  NT2_TEST_TYPE_IS(typename boost::dispatch::meta::call<bitwise_notand_(siT, T)>::type, siT);

  // specific values tests
  NT2_TEST_EQUAL(bitwise_notand(boost::simd::Zero<T>(),boost::simd::Valmax<uiT>()), boost::simd::Nan<T>());
  NT2_TEST_EQUAL(bitwise_notand(boost::simd::Zero<T>(), boost::simd::Mone<siT>()), boost::simd::Nan<T>());
  NT2_TEST_EQUAL(bitwise_notand(boost::simd::Zero<siT>(),boost::simd::Nan<T>()), boost::simd::Mone<siT>());
  NT2_TEST_EQUAL(bitwise_notand(boost::simd::Zero<uiT>(), boost::simd::Nan<T>()), boost::simd::Valmax<uiT>());
}


text: #include <boost/geometry/strategies/cartesian/azimuth.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <cctbx/boost_python/flex_fwd.h>

#include <boost/python.hpp>
#include <boost/python/class.hpp>
#include <scitbx/boost_python/is_polymorphic_workaround.h>
#include <cctbx/crystal/site_cluster_analysis.h>
#include <cctbx/crystal/workarounds_bpl.h>

SCITBX_BOOST_IS_POLYMORPHIC_WORKAROUND(
  cctbx::crystal::site_cluster_analysis<>)

namespace cctbx { namespace crystal {
namespace {

  struct site_cluster_analysis_wrappers : boost::python::pickle_suite
  {
    typedef site_cluster_analysis<> w_t;

    static boost::python::tuple
      getinitargs(w_t const& self)
    {
        return boost::python::make_tuple(self.init_space_group,
          self.init_asu,
          self.min_cross_distance,
          self.min_self_distance,
          self.general_positions_only,
          self.estimated_reduction_factor,
          self.init_asu_mappings_buffer_thickness,
          self.init_min_cubicle_edge,
          self.cubicle_epsilon_
          );
    }

    static void
    wrap()
    {
      using namespace boost::python;
      class_<w_t>("site_cluster_analysis", no_init)
        .def(init<
          sgtbx::space_group const&,
          direct_space_asu::float_asu<> const&,
          double const&,
          double const&,
          bool,
          unsigned,
          double const&,
          double const&,
          double const&>((
            arg("space_group"),
            arg("asu"),
            arg("min_cross_distance"),
            arg("min_self_distance"),
            arg("general_positions_only"),
            arg("estimated_reduction_factor")=4,
            arg("asu_mappings_buffer_thickness")=-1,
            arg("min_cubicle_edge")=5,
            arg("cubicle_epsilon")=-1)))
        .def_readonly("min_cross_distance",
                 &w_t::min_cross_distance)
        .def_readonly("min_self_distance",
                 &w_t::min_self_distance)
        .def_readonly("general_positions_only",
                 &w_t::general_positions_only)
        .def_readwrite("min_distance_sym_equiv",
                  &w_t::min_distance_sym_equiv)
        .def_readwrite("assert_min_distance_sym_equiv",
                  &w_t::assert_min_distance_sym_equiv)
        .def_readwrite("estimated_reduction_factor",
                  &w_t::estimated_reduction_factor)
        .def("asu_mappings", &w_t::asu_mappings)
        .def("insert_fixed_site_frac",
          (void(w_t::*)(fractional<> const&, sgtbx::site_symmetry_ops const&))
            &w_t::insert_fixed_site_frac, (
              arg("original_site"), arg("site_symmetry_ops")))
        .def("insert_fixed_site_frac",
          (void(w_t::*)(fractional<> const&))
            &w_t::insert_fixed_site_frac, (
              arg("original_site")))
        .def("discard_last", &w_t::discard_last)
        .def("process_site_frac",
          (bool(w_t::*)(fractional<> const&, sgtbx::site_symmetry_ops const&))
            &w_t::process_site_frac, (
              arg("original_site"), arg("site_symmetry_ops")))
        .def("process_site_frac",
          (bool(w_t::*)(fractional<> const&))
            &w_t::process_site_frac, (
              arg("original_site")))
        .def("process_sites_frac",
          (af::shared<std::size_t>(w_t::*)(
            af::const_ref<scitbx::vec3<double> > const&,
            sgtbx::site_symmetry_table const&,
            std::size_t))
              &w_t::process_sites_frac, (
                arg("original_sites"),
                arg("site_symmetry_table"),
                arg("max_clusters")=0))
        .def("process_sites_frac",
          (af::shared<std::size_t>(w_t::*)(
            af::const_ref<scitbx::vec3<double> > const&,
            std::size_t))
              &w_t::process_sites_frac, (
                arg("original_sites"),
                arg("max_clusters")=0))
        .def("process_sites_cart",
          (af::shared<std::size_t>(w_t::*)(
            af::const_ref<scitbx::vec3<double> > const&,
            sgtbx::site_symmetry_table const&,
            std::size_t))
              &w_t::process_sites_cart, (
                arg("original_sites"),
                arg("site_symmetry_table"),
                arg("max_clusters")=0))
        .def("process_sites_cart",
          (af::shared<std::size_t>(w_t::*)(
            af::const_ref<scitbx::vec3<double> > const&,
            std::size_t))
              &w_t::process_sites_cart, (
                arg("original_sites"),
                arg("max_clusters")=0))
         .def_pickle(site_cluster_analysis_wrappers())
        ;
    }
  };

  void
  wrap_all()
  {
    site_cluster_analysis_wrappers::wrap();
  }

} // namespace <anonymous>

namespace boost_python {

  void
  wrap_site_cluster_analysis() { wrap_all(); }

}}} // namespace cctbx::crystal::boost_python


text:
#include "kernel_poly6.hpp"

#include "kernel_test.hpp"

#include <boost/test/unit_test.hpp>

using namespace GooBalls;
using namespace d2;
using namespace Physics;

namespace utf = boost::unit_test;

using KKernel = Poly6;

BOOST_AUTO_TEST_CASE(poly6_zero_border_1d, *utf::tolerance(0.0001)){
    KKernel k;
    testZeroBorder1d(k);
}

BOOST_AUTO_TEST_CASE(poly6_normalization_1d, *utf::tolerance(0.0001)){
    KKernel k;
    testNormalization1d(k, 100);
}

BOOST_AUTO_TEST_CASE(poly6_zero_border_gradient_1d, *utf::tolerance(0.01)){
    KKernel k;
    testZeroBorderGradient1d(k);
}

BOOST_AUTO_TEST_CASE(poly6_grad_finite_diff_1d, *utf::tolerance(0.001)){
    KKernel k;
    testGradientFiniteDifference1d(k, 100);
}

BOOST_AUTO_TEST_CASE(poly6_lap_grad_finite_diff_1d, *utf::tolerance(0.0001)){
    KKernel k;
    testLaplacianFromGradientFiniteDifferences1d(k, 100);
}

BOOST_AUTO_TEST_CASE(poly6_lap_finite_diff_1d, *utf::tolerance(0.00001)){
    KKernel k;
    testLaplacianFiniteDifference1d(k, 100);
}

BOOST_AUTO_TEST_CASE(poly6_zero_border, *utf::tolerance(0.0001)){
    KKernel k;
    testZeroBorder(k, 100);
}

BOOST_AUTO_TEST_CASE(poly6_zero_border_gradient, *utf::tolerance(0.01)){
    KKernel k;
    testZeroBorderGradient(k, 100);
}

BOOST_AUTO_TEST_CASE(poly6_normalization, *utf::tolerance(0.0001)){
    KKernel k;
    testNormalization(k, 100);
}

BOOST_AUTO_TEST_CASE(poly6_monotonicity, *utf::tolerance(0.0001)){
    KKernel k;
    testMonotonicity(k, 10);
}

BOOST_AUTO_TEST_CASE(poly6_radial_symmetric){
    KKernel k;
    testRadialSymmetry(k, 100);
}

BOOST_AUTO_TEST_CASE(poly6_grad_finite_diff, *utf::tolerance(0.001)){
    KKernel k;
    testGradientFiniteDifference(k, 100);
}

BOOST_AUTO_TEST_CASE(poly6_lap_grad_finite_diff, *utf::tolerance(0.005)){
    KKernel k;
    testLaplacianFromGradientFiniteDifferences(k, 100);
}

BOOST_AUTO_TEST_CASE(poly6_lap_finite_diff, *utf::tolerance(0.001)){
    KKernel k;
    testLaplacianFiniteDifference(k, 100);
}

ext: cc

max_stars_repo_name: Fluci/GooBalls

max_issues_repo_name: Fluci/GooBalls

max_forks_repo_name: Fluci/GooBalls


text:
#include <unistd.h>
#include <iostream>
#include <pthread.h>
#include <boost/function.hpp>

class Thread {
public:
    using ThreadFunc = boost::function<void ()>;
    explicit Thread(const ThreadFunc& func);
    ~Thread();
    void Start();
    void Join();
    void SetAutoDelete(bool autodelete);
private:
    void Run();
    static void* ThreadRoutine(void* arg);
    pthread_t threadId_;
    bool autoDelete_;
    ThreadFunc func_;
};

Thread::Thread(const ThreadFunc& func) : autoDelete_(false), func_(func) {}

Thread::~Thread() {
    std::cout << "Thread deconstructing...." << std::endl;
}

void Thread::Start() {
    pthread_create(&threadId_, NULL, ThreadRoutine, this);
}

void Thread::Join() {
    pthread_join(threadId_, NULL);
}

void Thread::Run() {
    func_();
}

void Thread::SetAutoDelete(bool autodelete) {
    autoDelete_ = autodelete;
}

void* Thread::ThreadRoutine(void* arg) {
    Thread* thread = static_cast<Thread*> (arg);
    thread->Run();
    if (thread->autoDelete_) {
        delete thread;
    }
    return NULL;
}

void func() {
    std::cout << "this is test function " << std::endl;
}
int main() {
    Thread* t = new Thread(func);
    t->SetAutoDelete(true);
    t->Start();
    t->Join();
    sleep(1);
}


text:
/*
* Created by Mark Johnson on 1/4/2018.
*/

#ifndef VEHO_TRANSFORMATION_HPP
#define VEHO_TRANSFORMATION_HPP

#include <cstddef>
#include <utility>
#include <type_traits>

#include <boost/mp11/list.hpp>

#include "preprocessing/preprocessing.hpp"
#include "normalization/normalization.hpp"
#include "expansion/expansion.hpp"
#include "reduction/reduction.hpp"

namespace veho {
    namespace facet {
        namespace receiver {
            namespace optimization {
                namespace detail {
                    template <typename TypeMap, typename Callbacks>
                    struct dummy_optimizer {
                        constexpr explicit dummy_optimizer(Callbacks&& callbacks)
                                : new_callbacks(std::forward<Callbacks>(callbacks)) {}

                        using new_type_map_type = TypeMap;

                        using new_callbacks_type = Callbacks;

                        new_callbacks_type new_callbacks;
                    };

                    template <typename Controller, typename TypeMap, typename Callbacks, std::size_t UsableMailboxCount, typename Enable = void>
                    struct determine_optimization_process;

                    template <typename Controller, typename TypeMap, typename Callbacks, std::size_t UsableMailboxCount>
                    struct determine_optimization_process<Controller, TypeMap, Callbacks, UsableMailboxCount, typename std::enable_if<
                            (boost::mp11::mp_size<Callbacks>::value > UsableMailboxCount)
                    >::type> {
                        using optimizer = reduction::callback_reducer<
                                Controller,
                                TypeMap,
                                Callbacks,
                                UsableMailboxCount
                        >;
                    };

                    template <typename Controller, typename TypeMap, typename Callbacks, std::size_t UsableMailboxCount>
                    struct determine_optimization_process<Controller, TypeMap, Callbacks, UsableMailboxCount, typename std::enable_if<
                            (boost::mp11::mp_size<Callbacks>::value < UsableMailboxCount)
                    >::type> {
                        using optimizer = expansion::callback_expander<
                                Controller,
                                TypeMap,
                                Callbacks,
                                UsableMailboxCount
                        >;
                    };

                    template <typename Controller, typename TypeMap, typename Callbacks, std::size_t UsableMailboxCount>
                    struct determine_optimization_process<Controller, TypeMap, Callbacks, UsableMailboxCount, typename std::enable_if<
                            (boost::mp11::mp_size<Callbacks>::value == UsableMailboxCount)
                    >::type> {
                        using optimizer = dummy_optimizer<TypeMap, Callbacks>;
                    };
                }

                template <typename Controller, typename TypeMap, typename Callbacks, std::size_t UsableMailboxCount>
                struct callback_optimizer {
                private:
                    using preprocessor = preprocessing::callback_preprocessor<Controller, TypeMap, Callbacks>;

                    using preprocessed_type_map = typename preprocessor::new_type_map_type;

                    using preprocessed_callbacks_type = typename preprocessor::new_callbacks_type;

                    using normalizer = normalization::callback_normalizer<Controller, preprocessed_type_map, preprocessed_callbacks_type>;

                    using normalized_type_map = typename normalizer::new_type_map_type;

                    using normalized_callbacks_type = typename normalizer::new_callbacks_type;

                    using optimizer = typename detail::determine_optimization_process<
                            Controller, normalized_type_map, normalized_callbacks_type, UsableMailboxCount
                    >::optimizer;

                public:
                    constexpr explicit callback_optimizer(Callbacks&& callbacks)
                            : new_callbacks(optimizer(normalizer(std::forward<Callbacks>(callbacks)).new_callbacks).new_callbacks) {}

                    using new_type_map_type = typename optimizer::new_type_map_type;

                    using new_callbacks_type = typename optimizer::new_callbacks_type;

                    new_callbacks_type new_callbacks;
                };
            }
        }
    }
}

#endif //VEHO_TRANSFORMATION_HPP

max_issues_repo_name: notfoundry/veho

max_forks_repo_name: notfoundry/veho


text:
// Copyright (c) 2014-2016, The Monero Project
//
// 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.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers

#include "gtest/gtest.h"
#include "wallet/wallet2_api.h"
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>

#include <iostream>
#include <vector>

using namespace std;
//unsigned int epee::g_test_dbg_lock_sleep = 0;

struct WalletManagerTest : public testing::Test
{
    Bitmonero::WalletManager * wmgr;

    const char * WALLET_NAME = "testwallet";
    const char * WALLET_NAME_COPY = "testwallet_copy";
    const char * WALLET_NAME_WITH_DIR = "walletdir/testwallet_test";
    const char * WALLET_NAME_WITH_DIR_NON_WRITABLE = "/var/walletdir/testwallet_test";
    const char * WALLET_PASS = "password";
    const char * WALLET_PASS2 = "password22";
    const char * WALLET_LANG = "English";

    WalletManagerTest()
    {
        std::cout << __FUNCTION__ << std::endl;
        wmgr = Bitmonero::WalletManagerFactory::getWalletManager();
        deleteWallet(WALLET_NAME);
        deleteDir(boost::filesystem::path(WALLET_NAME_WITH_DIR).parent_path().string());
    }

    ~WalletManagerTest()
    {
        std::cout << __FUNCTION__ << std::endl;
        //deleteWallet(WALLET_NAME);
    }

    void deleteWallet(const std::string & walletname)
    {
        std::cout << "** deleting wallet: " << walletname << std::endl;
        boost::filesystem::remove(walletname);
        boost::filesystem::remove(walletname + ".address.txt");
        boost::filesystem::remove(walletname + ".keys");
    }

    void deleteDir(const std::string &path)
    {
        std::cout << "** removing dir recursively: " << path  << std::endl;
        boost::filesystem::remove_all(path);
    }

};

TEST_F(WalletManagerTest, WalletManagerCreatesWallet)
{

    Bitmonero::Wallet * wallet = wmgr->createWallet(WALLET_NAME, WALLET_PASS, WALLET_LANG);
    ASSERT_TRUE(wallet->status() == Bitmonero::Wallet::Status_Ok);
    ASSERT_TRUE(!wallet->seed().empty());
    std::vector<std::string> words;
    std::string seed = wallet->seed();
    boost::split(words, seed, boost::is_any_of(" "), boost::token_compress_on);
    ASSERT_TRUE(words.size() == 25);
    std::cout << "** seed: " << wallet->seed() << std::endl;
    ASSERT_FALSE(wallet->address().empty());
    std::cout << "** address: " << wallet->address() << std::endl;
    ASSERT_TRUE(wmgr->closeWallet(wallet));

}

TEST_F(WalletManagerTest, WalletManagerOpensWallet)
{

    Bitmonero::Wallet * wallet1 = wmgr->createWallet(WALLET_NAME, WALLET_PASS, WALLET_LANG);
    std::string seed1 = wallet1->seed();
    ASSERT_TRUE(wmgr->closeWallet(wallet1));
    Bitmonero::Wallet * wallet2 = wmgr->openWallet(WALLET_NAME, WALLET_PASS);
    ASSERT_TRUE(wallet2->status() == Bitmonero::Wallet::Status_Ok);
    ASSERT_TRUE(wallet2->seed() == seed1);
    std::cout << "** seed: " << wallet2->seed() << std::endl;
}

TEST_F(WalletManagerTest, WalletManagerChangesPassword)
{
    Bitmonero::Wallet * wallet1 = wmgr->createWallet(WALLET_NAME, WALLET_PASS, WALLET_LANG);
    std::string seed1 = wallet1->seed();
    ASSERT_TRUE(wallet1->setPassword(WALLET_PASS2));
    ASSERT_TRUE(wmgr->closeWallet(wallet1));
    Bitmonero::Wallet * wallet2 = wmgr->openWallet(WALLET_NAME, WALLET_PASS2);
    ASSERT_TRUE(wallet2->status() == Bitmonero::Wallet::Status_Ok);
    ASSERT_TRUE(wallet2->seed() == seed1);
    ASSERT_TRUE(wmgr->closeWallet(wallet2));
    Bitmonero::Wallet * wallet3 = wmgr->openWallet(WALLET_NAME, WALLET_PASS);
    ASSERT_FALSE(wallet3->status() == Bitmonero::Wallet::Status_Ok);
}

TEST_F(WalletManagerTest, WalletManagerRecoversWallet)
{
    Bitmonero::Wallet * wallet1 = wmgr->createWallet(WALLET_NAME, WALLET_PASS, WALLET_LANG);
    std::string seed1 = wallet1->seed();
    std::string address1 = wallet1->address();
    ASSERT_FALSE(address1.empty());
    ASSERT_TRUE(wmgr->closeWallet(wallet1));
    deleteWallet(WALLET_NAME);
    Bitmonero::Wallet * wallet2 = wmgr->recoveryWallet(WALLET_NAME, seed1);
    ASSERT_TRUE(wallet2->status() == Bitmonero::Wallet::Status_Ok);
    ASSERT_TRUE(wallet2->seed() == seed1);
    ASSERT_TRUE(wallet2->address() == address1);
    ASSERT_TRUE(wmgr->closeWallet(wallet2));
}

TEST_F(WalletManagerTest, WalletManagerStoresWallet1)
{
    Bitmonero::Wallet * wallet1 = wmgr->createWallet(WALLET_NAME, WALLET_PASS, WALLET_LANG);
    std::string seed1 = wallet1->seed();
    std::string address1 = wallet1->address();

    ASSERT_TRUE(wallet1->store(""));
    ASSERT_TRUE(wallet1->store(WALLET_NAME_COPY));
    ASSERT_TRUE(wmgr->closeWallet(wallet1));
    Bitmonero::Wallet * wallet2 = wmgr->openWallet(WALLET_NAME_COPY, WALLET_PASS);
    ASSERT_TRUE(wallet2->status() == Bitmonero::Wallet::Status_Ok);
    ASSERT_TRUE(wallet2->seed() == seed1);
    ASSERT_TRUE(wallet2->address() == address1);
    ASSERT_TRUE(wmgr->closeWallet(wallet2));
}

TEST_F(WalletManagerTest, WalletManagerStoresWallet2)
{
    Bitmonero::Wallet * wallet1 = wmgr->createWallet(WALLET_NAME, WALLET_PASS, WALLET_LANG);
    std::string seed1 = wallet1->seed();
    std::string address1 = wallet1->address();

    ASSERT_TRUE(wallet1->store(WALLET_NAME_WITH_DIR));
    ASSERT_TRUE(wmgr->closeWallet(wallet1));

    wallet1 = wmgr->openWallet(WALLET_NAME_WITH_DIR, WALLET_PASS);
    ASSERT_TRUE(wallet1->status() == Bitmonero::Wallet::Status_Ok);
    ASSERT_TRUE(wallet1->seed() == seed1);
    ASSERT_TRUE(wallet1->address() == address1);
    ASSERT_TRUE(wmgr->closeWallet(wallet1));
}

TEST_F(WalletManagerTest, WalletManagerStoresWallet3)
{
    Bitmonero::Wallet * wallet1 = wmgr->createWallet(WALLET_NAME, WALLET_PASS, WALLET_LANG);
    std::string seed1 = wallet1->seed();
    std::string address1 = wallet1->address();

    ASSERT_FALSE(wallet1->store(WALLET_NAME_WITH_DIR_NON_WRITABLE));
    ASSERT_TRUE(wmgr->closeWallet(wallet1));

    wallet1 = wmgr->openWallet(WALLET_NAME_WITH_DIR_NON_WRITABLE, WALLET_PASS);
    ASSERT_FALSE(wallet1->status() == Bitmonero::Wallet::Status_Ok);

    ASSERT_FALSE(wmgr->closeWallet(wallet1));

    wallet1 = wmgr->openWallet(WALLET_NAME, WALLET_PASS);
    ASSERT_TRUE(wallet1->status() == Bitmonero::Wallet::Status_Ok);
    ASSERT_TRUE(wallet1->seed() == seed1);
    ASSERT_TRUE(wallet1->address() == address1);
    ASSERT_TRUE(wmgr->closeWallet(wallet1));

}

int main(int argc, char** argv)
{
  //epee::debug::get_set_enable_assert(true, false);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

max_stars_repo_name: destenson/monero-project--bitmonero

max_issues_repo_name: destenson/monero-project--bitmonero

max_forks_repo_name: destenson/monero-project--bitmonero


text:
//  Copyright (c) 2007-2013 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <hpx/config.hpp>
#include <hpx/runtime/actions/action_support.hpp>

#include <hpx/plugins/plugin_registry.hpp>
#include <hpx/plugins/binary_filter_factory.hpp>
#include <hpx/plugins/binary_filter/zlib_serialization_filter.hpp>

#include <boost/format.hpp>

#include <cstddef>
#include <cstring>

///////////////////////////////////////////////////////////////////////////////
HPX_REGISTER_PLUGIN_MODULE();
HPX_REGISTER_BINARY_FILTER_FACTORY(
    hpx::plugins::compression::zlib_serialization_filter,
    zlib_serialization_filter);

///////////////////////////////////////////////////////////////////////////////
namespace hpx { namespace plugins { namespace compression
{
    namespace detail
    {
        zlib_compdecomp::zlib_compdecomp(bool compress,
                boost::iostreams::zlib_params const& params)
          : compress_(compress), eof_(false)
        {
            this->init(params, compress_, static_cast<allocator_type&>(*this));
        }

        zlib_compdecomp::~zlib_compdecomp()
        {
            this->reset(compress_, false);
        }

        bool zlib_compdecomp::save(char const*& src_begin, char const* src_end,
            char*& dest_begin, char* dest_end, bool flush)
        {
            using namespace boost::iostreams;
            using namespace boost::iostreams::zlib;

            this->before(src_begin, src_end, dest_begin, dest_end);
            int result = this->xdeflate(flush ? finish : no_flush);
            this->after(src_begin, dest_begin, true);
            (zlib_error::check)(result);
            return !(eof_ = result == stream_end);
        }

        bool zlib_compdecomp::load(char const*& src_begin, char const* src_end,
            char*& dest_begin, char* dest_end)
        {
            using namespace boost::iostreams;
            using namespace boost::iostreams::zlib;

            this->before(src_begin, src_end, dest_begin, dest_end);
            int result = this->xinflate(sync_flush);
            this->after(src_begin, dest_begin, false);
            (zlib_error::check)(result);
            return !(eof_ = result == stream_end);
        }

        void zlib_compdecomp::close()
        {
            eof_ = false;
            this->reset(compress_, true);
        }
    }

    void zlib_serialization_filter::set_max_length(std::size_t size)
    {
        buffer_.reserve(size);
    }

    ///////////////////////////////////////////////////////////////////////////
    std::size_t zlib_serialization_filter::load_impl(void* dst,
        std::size_t dst_count, void const* src, std::size_t src_count)
    {
        char const* src_begin = static_cast<char const*>(src);
        char* dst_begin = static_cast<char*>(dst);
        compdecomp_.load(src_begin, src_begin+src_count, dst_begin,
            dst_begin+dst_count);
        return src_begin-static_cast<char const*>(src);
    }

    std::size_t zlib_serialization_filter::init_data(
        char const* buffer, std::size_t size, std::size_t buffer_size)
    {
        buffer_.resize(buffer_size);
        std::size_t s = load_impl(buffer_.data(), buffer_size, buffer, size);
        if (s > size)
        {
            HPX_THROW_EXCEPTION(serialization_error,
                "zlib_serialization_filter::load",
                boost::str(boost::format("decompression failure, number of "
                    "bytes expected: %d, number of bytes decoded: %d") %
                        size % s) );
            return 0;
        }

        current_ = 0;
        return buffer_.size();
    }

    ///////////////////////////////////////////////////////////////////////////
    void zlib_serialization_filter::load(void* dst, std::size_t dst_count)
    {
        if (current_+dst_count > buffer_.size())
        {
            HPX_THROW_EXCEPTION(serialization_error,
                    "zlib_serialization_filter::load",
                    "archive data bstream is too short");
            return;
        }

        std::memcpy(dst, &buffer_[current_], dst_count);
        current_ += dst_count;
    }

    ///////////////////////////////////////////////////////////////////////////
    void zlib_serialization_filter::save(void const* src,
        std::size_t src_count)
    {
        char const* src_begin = static_cast<char const*>(src);
        std::copy(src_begin, src_begin+src_count, std::back_inserter(buffer_));
    }

    ///////////////////////////////////////////////////////////////////////////
    bool zlib_serialization_filter::flush(void* dst,
        std::size_t dst_count, std::size_t& written)
    {
        // compress everything in one go
        char* dst_begin = static_cast<char*>(dst);
        char const* src_begin = buffer_.data();
        bool eof = compdecomp_.save(src_begin, src_begin+buffer_.size(),
                dst_begin, dst_begin+dst_count, true);

        written = dst_begin-static_cast<char*>(dst);
        return !eof;
    }
}}}

max_stars_repo_name: brycelelbach/hpx

max_issues_repo_name: atrantan/hpx

max_forks_repo_name: atrantan/hpx


text:
#include <boost/mpl/list.hpp>

typedef boost::mpl::list<
	float,
	double,
	long double> float_types;

max_stars_repo_name: ChasingCarrots/vmath

max_issues_repo_name: kernan/math

max_forks_repo_name: kernan/vmath


text:
#ifndef mdi_interdataset_hpp
#define mdi_interdataset_hpp

#include <vector>
#include "stats.hpp"

#include <Eigen/Dense>

class interdataset {
  int _nfiles;
  std::vector<int> _phiord;    // was first
  std::vector<int> _weightord; // was second

public:
  interdataset(int nfiles);

  int nfiles() const { return _nfiles; }
  int nphis()  const { return _nfiles*(_nfiles-1)/2; }

  const std::vector<int> &getPhiOrd()    const { return _phiord; }
  const std::vector<int> &getWeightOrd() const { return _weightord; }
};

class mdisampler {
  const interdataset &_inter;

  Eigen::MatrixXf _weight;
  Eigen::VectorXf _dpmass, _phi;
  double _nu;

  Eigen::MatrixXf _prod;
  Eigen::VectorXf _prodsum;

  void updateAllocHistogram();
  void updateColumnProducts();

  Eigen::VectorXd calcProdCoef() const;
  double calcProdPhi(const Eigen::VectorXd &coef) const;

public:
  mdisampler(const interdataset &inter, int nclus)
    : _inter(inter),
      _weight(nclus, inter.nfiles()),
      _dpmass(Eigen::VectorXf::Zero(inter.nfiles())),
      _phi(Eigen::VectorXf::Zero(inter.nphis())),
      _nu(0.0),
      _prod(nclus, (1<<inter.nfiles())-1), _prodsum((1<<inter.nfiles())-1)
  { }

  int nclus()  const { return _weight.rows(); }
  int nfiles() const { return _weight.cols(); }
  int nphis()  const { return _inter.nphis(); }

  void setDpMass(int k, double mass);
  void setWeight(int k, const Eigen::VectorXf &weight);
  void setWeight(const Eigen::MatrixXf &x);
  void setPhi(int k, int l, double phi);
  void setNu(double x);

  // void setWeight(int j, int k, double weight);
  void setDpMass(const Eigen::VectorXf &x);
  void setPhis(const Eigen::VectorXf &x);

  double dpmass(int k)        const { return _dpmass(k); }
  double phi(int phi_kl)      const { return _phi(phi_kl); }
  double phi(int k, int l)    const { return _phi(phiBetween(k, l)); }
  double nu()                 const { return _nu; }
  double weight(int j, int k) const { return _weight(j, k); }

  const Eigen::VectorXf &dpmass()  const { return _dpmass; }
  const Eigen::MatrixXf &weights() const { return _weight; }
  const Eigen::VectorXf &phis()    const { return _phi;    }
  typename Eigen::MatrixXf::ConstColXpr weight(int k) const {
    return _weight.col(k); }

  Eigen::VectorXf phis(int k) const {
    Eigen::VectorXf out(nfiles());

    for (int j = 0; j < nfiles(); j++) {
      if (j < k)
        out[j] = phi(j, k);
      else if (j > k)
        out[j] = phi(k, j);
      else
        out[j] = NAN;
    }

    return out;
  }

  int phiBetween (int k, int l) const {
    assert(k < nfiles() && l < nfiles() && k < l);
    return nfiles()*k - (k+1)*k/2 + l-k - 1;
  }

  void sampleFromPrior();

  double nuConditionalBeta() const;
  double phiConditionalBeta(int k, int l) const;
  double gammaConditionalBeta(int k, int j) const;

  #ifndef NOCUDA

  #endif
};

#endif

max_stars_repo_name: fguitton/mdipp

max_issues_repo_name: fguitton/mdipp

max_forks_repo_name: fguitton/mdipp


text:
/*=========================================================================
 *
 *  Copyright David Doria 2011 daviddoria@gmail.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  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.
 *
 *=========================================================================*/

// Pixel descriptors
#include "PixelDescriptors/ImagePatchPixelDescriptor.h"

// Visitors
//#include "Visitors/DefaultInpaintingVisitor.hpp"
#include "Visitors/ImagePatchCreatorVisitor.hpp"

// Nearest neighbors
#include "NearestNeighbor/metric_space_search.hpp"

// Topologies
#include "Topologies/ImagePatchTopology.hpp"

// Initializers
//#include "Initializers/InitializeFromMaskImage.hpp"
#include "Initializers/SimpleInitializerFromMask.hpp"

// ITK
#include "itkImageFileReader.h"

// Boost
#include <boost/graph/grid_graph.hpp>
#include <boost/property_map/property_map.hpp>

namespace boost
{
  enum vertex_image_patch_t { vertex_image_patch };
  BOOST_INSTALL_PROPERTY(vertex, image_patch);
};

// Run with: Data/trashcan.mha Data/trashcan_mask.mha 15
int main(int argc, char *argv[])
{
  // Verify arguments
  if(argc != 4)
    {
    std::cerr << "Required arguments: image.mha imageMask.mha patchRadius" << std::endl;
    return EXIT_FAILURE;
    }

  // Parse arguments
  std::string imageFilename = argv[1];
  std::string maskFilename = argv[2];

  std::stringstream ssPatchRadius;
  ssPatchRadius << argv[3];
  unsigned int patch_half_width = 0;
  ssPatchRadius >> patch_half_width;

  // Output arguments
  std::cout << "Reading image: " << imageFilename << std::endl;
  std::cout << "Reading mask: " << maskFilename << std::endl;
  std::cout << "Patch half width: " << patch_half_width << std::endl;

  typedef FloatVectorImageType ImageType;

  typedef  itk::ImageFileReader<ImageType> ImageReaderType;
  ImageReaderType::Pointer imageReader = ImageReaderType::New();
  imageReader->SetFileName(imageFilename.c_str());
  imageReader->Update();

  ImageType::Pointer image = ImageType::New();
  ITKHelpers::DeepCopy(imageReader->GetOutput(), image.GetPointer());

  typedef  itk::ImageFileReader<Mask> MaskReaderType;

  MaskReaderType::Pointer maskReader = MaskReaderType::New();
  maskReader->SetFileName(maskFilename);
  maskReader->Update();
  std::cout << "hole pixels: " << maskReader->GetOutput()->CountHolePixels() << std::endl;
  std::cout << "valid pixels: " << maskReader->GetOutput()->CountValidPixels() << std::endl;

  // Create the graph
  typedef boost::grid_graph<2> VertexListGraphType;
  boost::array<std::size_t, 2> graphSideLengths = { { imageReader->GetOutput()->GetLargestPossibleRegion().GetSize()[0],
                                                      imageReader->GetOutput()->GetLargestPossibleRegion().GetSize()[1] } };
  VertexListGraphType graph(graphSideLengths);
  typedef boost::graph_traits<VertexListGraphType>::vertex_descriptor VertexDescriptorType;

  // Create the topology
  typedef ImagePatchTopology<ImageType> TopologyType;
  TopologyType space;

  // Get the index map
  typedef boost::property_map<VertexListGraphType, boost::vertex_index_t>::const_type IndexMapType;
  IndexMapType indexMap(get(boost::vertex_index, graph));

  // Create the descriptor map. This is where the data for each pixel is stored. The Topology
  typedef boost::vector_property_map<TopologyType::point_type, IndexMapType> DescriptorMapType;
  DescriptorMapType descriptorMap(num_vertices(graph), indexMap);

  //DefaultInpaintingVisitor visitor;
  ImagePatchCreatorVisitor<ImageType, DescriptorMapType> visitor(imageReader->GetOutput(), maskReader->GetOutput(), descriptorMap, patch_half_width);

  // Initialize
  SimpleInitializerFromMask(maskReader->GetOutput(), &visitor, graph);

  // Create the tree
  std::cout << "Creating tree..." << std::endl;
  typedef dvp_tree<VertexDescriptorType, TopologyType, DescriptorMapType > TreeType;
  // TreeType tree(graph, space, descriptorMap); // Create from all positions on the graph_traits - don't want to do this unless all positions on the topology are valid.

  // std::vector<TopologyType::point_type> validPositions; // Don't store the positions, but rather store the vertex_descriptors
  std::vector<VertexDescriptorType> validPositions;
  typename boost::graph_traits<VertexListGraphType>::vertex_iterator vi,vi_end;

  for (tie(vi,vi_end) = vertices(graph); vi != vi_end; ++vi)
  {
    if(get(descriptorMap, *vi).IsFullyValid())
      {
      validPositions.push_back(*vi);
      }
  }

  std::cout << "There are " << validPositions.size() << " validPositions" << " (out of " << imageReader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() << ")" << std::endl;

  TreeType tree(validPositions.begin(), validPositions.end(), space, descriptorMap);
  std::cout << "Finished creating tree." << std::endl;

  // Create the nearest neighbor finder
  typedef multi_dvp_tree_search<VertexListGraphType, TreeType> SearchType;
  SearchType nearestNeighborFinder;
  nearestNeighborFinder.graph_tree_map[&graph] = &tree;

  return EXIT_SUCCESS;
}

max_stars_repo_name: jingtangliao/ff

max_issues_repo_name: jingtangliao/ff

max_forks_repo_name: jingtangliao/ff