text:
//=============================================================================================================
/**
* @file     realtimesourceestimatewidget.cpp
* @author   Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     July, 2012
*
* @section  LICENSE
*
* Copyright (C) 2012, Christoph Dinh and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * 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.
*     * Neither the name of MNE-CPP authors 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 OWNER 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.
*
*
* @brief    Implementation of the RealTimeSourceEstimateWidget Class.
*
*/

//ToDo Paint to render area

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "realtimesourceestimatewidget.h"

#include <scMeas/realtimesourceestimate.h>

#include <disp3D/engine/model/items/sourceactivity/mneestimatetreeitem.h>
#include <disp3D/engine/view/view3D.h>
#include <disp3D/engine/control/control3dwidget.h>
#include <disp3D/engine/model/data3Dtreemodel.h>

#include <mne/mne_forwardsolution.h>
#include <mne/mne_inverse_operator.h>

#include <fs/surfaceset.h>
#include <fs/annotationset.h>

#include <inverse/minimumNorm/minimumnorm.h>

#include <math.h>

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QSlider>
#include <QAction>
#include <QLabel>
#include <QGridLayout>
#include <QSettings>
#include <QDebug>
#include <QStringList>

//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================

#include <Eigen/Core>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace SCDISPLIB;
using namespace DISP3DLIB;
using namespace MNELIB;
using namespace SCMEASLIB;
using namespace INVERSELIB;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

RealTimeSourceEstimateWidget::RealTimeSourceEstimateWidget(QSharedPointer<RealTimeSourceEstimate> &pRTSE, QWidget* parent)
: NewMeasurementWidget(parent)
, m_pRTSE(pRTSE)
, m_bInitialized(false)
, m_pRtItem(Q_NULLPTR)
{
    m_pAction3DControl = new QAction(QIcon(":/images/3DControl.png"), tr("Shows the 3D control widget (F9)"),this);
    m_pAction3DControl->setShortcut(tr("F9"));
    m_pAction3DControl->setToolTip(tr("Shows the 3D control widget (F9)"));
    connect(m_pAction3DControl, &QAction::triggered,
            this, &RealTimeSourceEstimateWidget::show3DControlWidget);
    addDisplayAction(m_pAction3DControl);
    m_pAction3DControl->setVisible(true);

    m_p3DView = View3D::SPtr(new View3D());
    m_pData3DModel = Data3DTreeModel::SPtr(new Data3DTreeModel());

    m_p3DView->setModel(m_pData3DModel);

    m_pControl3DView = Control3DWidget::SPtr(new Control3DWidget(this,
                                                                 QStringList() << "Minimize" << "Data" << "Window" << "View" << "Light",
                                                                 Qt::Window));
    m_pControl3DView->init(m_pData3DModel, m_p3DView);

    QGridLayout *mainLayoutView = new QGridLayout;
    QWidget *pWidgetContainer = QWidget::createWindowContainer(m_p3DView.data());
    mainLayoutView->addWidget(pWidgetContainer);

    this->setLayout(mainLayoutView);

    getData();
}

//*************************************************************************************************************

RealTimeSourceEstimateWidget::~RealTimeSourceEstimateWidget()
{
    //
    // Store Settings
    //
    if(!m_pRTSE->getName().isEmpty())
    {
    }
}

//*************************************************************************************************************

void RealTimeSourceEstimateWidget::update(SCMEASLIB::NewMeasurement::SPtr)
{
    getData();
}

//*************************************************************************************************************

void RealTimeSourceEstimateWidget::getData()
{
    if(m_bInitialized)
    {
        //
        // Add rt brain data
        //
        if(!m_pRtItem) {
            qDebug()<<"RealTimeSourceEstimateWidget::getData - Creating m_lRtItem list";
            m_pRtItem = m_pData3DModel->addSourceData("Subject", "Data", *m_pRTSE->getValue(), *m_pRTSE->getFwdSolution());

            m_pRtItem->setLoopState(false);
            m_pRtItem->setTimeInterval(17);
            m_pRtItem->setNormalization(QVector3D(0.0,5,10));
            m_pRtItem->setColortable("Hot");
            m_pRtItem->setVisualizationType("Annotation based");
            //m_pRtItem->onTimeIntervalChanged(m_pRTSE->getValue()->tstep*1000000);
            m_pRtItem->setNumberAverages(1);
            m_pRtItem->setStreamingActive(true);
        } else {
            qDebug()<<"RealTimeSourceEstimateWidget::getData - Working with m_lRtItem list";

            if(m_pRtItem) {
                m_pRtItem->addData(*m_pRTSE->getValue());
            }
        }
    }
    else
    {
        if(m_pRTSE->getAnnotSet() && m_pRTSE->getSurfSet())
        {
            m_pRTSE->m_bStcSend = false;
            init();

            //
            // Add brain data
            //
            m_pData3DModel->addSurfaceSet("Subject", "MRI", *m_pRTSE->getSurfSet(), *m_pRTSE->getAnnotSet());
        }
    }
}

//*************************************************************************************************************

void RealTimeSourceEstimateWidget::init()
{
    m_bInitialized = true;
    m_pRTSE->m_bStcSend = true;
}

//*************************************************************************************************************

void RealTimeSourceEstimateWidget::show3DControlWidget()
{
    if(m_pControl3DView->isActiveWindow())
        m_pControl3DView->hide();
    else {
        m_pControl3DView->activateWindow();
        m_pControl3DView->show();
    }
}

//*************************************************************************************************************
//=============================================================================================================
// STATIC DEFINITIONS
//=============================================================================================================


text:
#include <boost/algorithm/string/predicate.hpp>
#include <fc/io/raw.hpp>
#include <fc/io/varint.hpp>
#include <fc/uint128.hpp>
#include <graphene/chain/abi_serializer.hpp>
#include <graphene/chain/protocol/contract_asset.hpp>
#include <graphene/chain/symbol.hpp>
#include <graphene/chain/config.hpp>

using namespace boost;

namespace graphene
{
namespace chain
{

const size_t abi_serializer::max_recursion_depth;

using boost::algorithm::ends_with;
using std::string;

template <typename T>
inline fc::variant variant_from_stream(fc::datastream<const char *> &stream, uint32_t max_depth)
{
    T temp;
    fc::raw::unpack(stream, temp);
    return fc::variant(temp, max_depth);
}

template <typename T>
auto pack_unpack()
{
    return std::make_pair<abi_serializer::unpack_function, abi_serializer::pack_function>(
        [](fc::datastream<const char *> &stream, bool is_array, bool is_optional) -> fc::variant {
            if (is_array)
                return variant_from_stream<vector<T>>(stream, GRAPHENE_MAX_NESTED_OBJECTS);
            else if (is_optional)
                return variant_from_stream<optional<T>>(stream, GRAPHENE_MAX_NESTED_OBJECTS);
            return variant_from_stream<T>(stream, GRAPHENE_MAX_NESTED_OBJECTS);
        },
        [](const fc::variant &var, fc::datastream<char *> &ds, bool is_array, bool is_optional) {
            if (is_array)
                fc::raw::pack(ds, var.as<vector<T>>(20));
            else if (is_optional)
                fc::raw::pack(ds, var.as<optional<T>>(20));
            else
                fc::raw::pack(ds, var.as<T>(20));
        });
}

map<type_name, pair<graphene::chain::abi_serializer::unpack_function, graphene::chain::abi_serializer::pack_function>> abi_serializer::built_in_types;

abi_serializer::abi_serializer(const abi_def &abi, const fc::microseconds &max_serialization_time)
{
    configure_built_in_types();
    set_abi(abi, max_serialization_time);
}

void abi_serializer::configure_built_in_types()
{
    if(built_in_types.size() > 0) return;

    built_in_types.emplace("bool", pack_unpack<uint8_t>());
    built_in_types.emplace("int8", pack_unpack<int8_t>());
    built_in_types.emplace("uint8", pack_unpack<uint8_t>());
    built_in_types.emplace("int16", pack_unpack<int16_t>());
    built_in_types.emplace("uint16", pack_unpack<uint16_t>());
    built_in_types.emplace("int32", pack_unpack<int32_t>());
    built_in_types.emplace("uint32", pack_unpack<uint32_t>());
    built_in_types.emplace("int64", pack_unpack<int64_t>());
    built_in_types.emplace("uint64", pack_unpack<uint64_t>());
    // built_in_types.emplace("int128", pack_unpack<fc::int128_t>());
    // built_in_types.emplace("uint128", pack_unpack<fc::uint128_t>());
    // built_in_types.emplace("varint32", pack_unpack<fc::signed_int>());
    // built_in_types.emplace("varuint32", pack_unpack<fc::unsigned_int>());

    // TODO: Add proper support for floating point types. For now this is good enough.
    built_in_types.emplace("float32", pack_unpack<float>());
    built_in_types.emplace("float64", pack_unpack<double>());
    // built_in_types.emplace("float128", pack_unpack<fc::uint128_t>());

    built_in_types.emplace("time_point", pack_unpack<fc::time_point>());
    built_in_types.emplace("time_point_sec", pack_unpack<fc::time_point_sec>());
    //      built_in_types.emplace("block_timestamp_type",      pack_unpack<block_timestamp_type>());

    built_in_types.emplace("name", pack_unpack<name>());

    built_in_types.emplace("bytes", pack_unpack<bytes>());
    built_in_types.emplace("string", pack_unpack<string>());

    built_in_types.emplace("block_id_type", pack_unpack<checksum160_type>());
    built_in_types.emplace("checksum160", pack_unpack<checksum160_type>());
    built_in_types.emplace("checksum256", pack_unpack<checksum256_type>());
    built_in_types.emplace("checksum512", pack_unpack<checksum512_type>());

    built_in_types.emplace("public_key", pack_unpack<public_key_type>());
    built_in_types.emplace("signature", pack_unpack<signature_type>());

    built_in_types.emplace("symbol", pack_unpack<symbol>());
    built_in_types.emplace("symbol_code", pack_unpack<symbol_code>());
    built_in_types.emplace("contract_asset", pack_unpack<contract_asset>());
}

void abi_serializer::set_abi(const abi_def &abi, const fc::microseconds &max_serialization_time)
{
    const fc::time_point deadline = fc::time_point::now() + max_serialization_time;
    typedefs.clear();
    structs.clear();
    actions.clear();
    tables.clear();
    error_messages.clear();

    for (const auto &st : abi.structs)
        structs[st.name] = st;

    for (const auto &td : abi.types) {
        FC_ASSERT(_is_type(td.type, 0, deadline, max_serialization_time), "invalid type", ("type", td.type));
        FC_ASSERT(!_is_type(td.new_type_name, 0, deadline, max_serialization_time), "type already exists", ("new_type_name", td.new_type_name));
        typedefs[td.new_type_name] = td.type;
    }

    for (const auto &a : abi.actions)
        actions[a.name] = a.type;

    for (const auto &t : abi.tables)
        tables[t.name] = t.type;

    for (const auto &e : abi.error_messages)
        error_messages[e.error_code] = e.error_msg;

    /**
       *  The ABI vector may contain duplicates which would make it
       *  an invalid ABI
       */
    FC_ASSERT(typedefs.size() == abi.types.size());
    FC_ASSERT(structs.size() == abi.structs.size());
    FC_ASSERT(actions.size() == abi.actions.size());
    FC_ASSERT(tables.size() == abi.tables.size());
    FC_ASSERT(error_messages.size() == abi.error_messages.size());

    validate(deadline, max_serialization_time);
}

bool abi_serializer::is_builtin_type(const type_name &type) const
{
    return built_in_types.find(type) != built_in_types.end();
}

bool abi_serializer::is_integer(const type_name &type) const
{
    string stype = type;
    return boost::starts_with(stype, "uint") || boost::starts_with(stype, "int");
}

int abi_serializer::get_integer_size(const type_name &type) const
{
    string stype = type;
    FC_ASSERT(is_integer(type), "${stype} is not an integer type", ("stype", stype));
    if (boost::starts_with(stype, "uint")) {
        return boost::lexical_cast<int>(stype.substr(4));
    } else {
        return boost::lexical_cast<int>(stype.substr(3));
    }
}

bool abi_serializer::is_struct(const type_name &type) const
{
    return structs.find(resolve_type(type)) != structs.end();
}

bool abi_serializer::is_array(const type_name &type) const
{
    return ends_with(string(type), "[]");
}

bool abi_serializer::is_optional(const type_name &type) const
{
    return ends_with(string(type), "?");
}

type_name abi_serializer::fundamental_type(const type_name &type) const
{
    if (is_array(type)) {
        return type_name(string(type).substr(0, type.size() - 2));
    } else if (is_optional(type)) {
        return type_name(string(type).substr(0, type.size() - 1));
    } else {
        return type;
    }
}

bool abi_serializer::_is_type(const type_name &rtype, size_t recursion_depth, const fc::time_point &deadline, const fc::microseconds &max_serialization_time) const
{
    FC_ASSERT(fc::time_point::now() < deadline, "serialization time limit ${t}us exceeded", ("t", max_serialization_time));
    if (++recursion_depth > max_recursion_depth) return false;
    auto type = fundamental_type(rtype);
    if (built_in_types.find(type) != built_in_types.end()) return true;
    if (typedefs.find(type) != typedefs.end()) return _is_type(typedefs.find(type)->second, recursion_depth, deadline, max_serialization_time);
    if (structs.find(type) != structs.end()) return true;
    return false;
}

const struct_def &abi_serializer::get_struct(const type_name &type) const
{
    auto itr = structs.find(resolve_type(type));
    FC_ASSERT(itr != structs.end(), "Unknown struct ${type}", ("type", type));
    return itr->second;
}

void abi_serializer::validate(const fc::time_point &deadline, const fc::microseconds &max_serialization_time) const
{
    for (const auto &t : typedefs) {
        try {
            vector<type_name> types_seen{t.first, t.second};
            auto itr = typedefs.find(t.second);
            while (itr != typedefs.end()) {
                FC_ASSERT(fc::time_point::now() < deadline, "serialization time limit ${t}us exceeded", ("t", max_serialization_time));
                FC_ASSERT(find(types_seen.begin(), types_seen.end(), itr->second) == types_seen.end(), "Circular reference in type ${type}", ("type", t.first));
                types_seen.emplace_back(itr->second);
                itr = typedefs.find(itr->second);
            }
        }
        FC_CAPTURE_AND_RETHROW((t))
    }
    for (const auto &t : typedefs) {
        try {
            FC_ASSERT(fc::time_point::now() < deadline, "serialization time limit ${t}us exceeded", ("t", max_serialization_time));
            FC_ASSERT(_is_type(t.second, 0, deadline, max_serialization_time), "", ("type", t.second));
        }
        FC_CAPTURE_AND_RETHROW((t))
    }
    for (const auto &s : structs) {
        try {
            if (s.second.base != type_name()) {
                struct_def current = s.second;
                vector<type_name> types_seen{current.name};
                while (current.base != type_name()) {
                    FC_ASSERT(fc::time_point::now() < deadline, "serialization time limit ${t}us exceeded", ("t", max_serialization_time));
                    const auto &base = get_struct(current.base); //<-- force struct to inherit from another struct
                    FC_ASSERT(find(types_seen.begin(), types_seen.end(), base.name) == types_seen.end(), "Circular reference in struct ${type}", ("type", s.second.name));
                    types_seen.emplace_back(base.name);
                    current = base;
                }
            }
            for (const auto &field : s.second.fields) {
                try {
                    FC_ASSERT(fc::time_point::now() < deadline, "serialization time limit ${t}us exceeded", ("t", max_serialization_time));
                    FC_ASSERT(_is_type(field.type, 0, deadline, max_serialization_time));
                }
                FC_CAPTURE_AND_RETHROW((field))
            }
        }
        FC_CAPTURE_AND_RETHROW((s))
    }
    for (const auto &a : actions) {
        try {
            FC_ASSERT(fc::time_point::now() < deadline, "serialization time limit ${t}us exceeded", ("t", max_serialization_time));
            FC_ASSERT(_is_type(a.second, 0, deadline, max_serialization_time), "", ("type", a.second));
        }
        FC_CAPTURE_AND_RETHROW((a))
    }

    for (const auto &t : tables) {
        try {
            FC_ASSERT(fc::time_point::now() < deadline, "serialization time limit ${t}us exceeded", ("t", max_serialization_time));
            FC_ASSERT(_is_type(t.second, 0, deadline, max_serialization_time), "", ("type", t.second));
        }
        FC_CAPTURE_AND_RETHROW((t))
    }
}

type_name abi_serializer::resolve_type(const type_name &type) const
{
    auto itr = typedefs.find(type);
    if (itr != typedefs.end()) {
        for (auto i = typedefs.size(); i > 0; --i) { // avoid infinite recursion
            const type_name &t = itr->second;
            itr = typedefs.find(t);
            if (itr == typedefs.end()) return t;
        }
    }
    return type;
}

void abi_serializer::_binary_to_variant(const type_name &type, fc::datastream<const char *> &stream,
                                        fc::mutable_variant_object &obj, size_t recursion_depth,
                                        const fc::time_point &deadline, const fc::microseconds &max_serialization_time) const
{
    FC_ASSERT(++recursion_depth < max_recursion_depth, "recursive definition, max_recursion_depth ${r} ", ("r", max_recursion_depth));
    FC_ASSERT(fc::time_point::now() < deadline, "serialization time limit ${t}us exceeded", ("t", max_serialization_time));

    const auto &st = get_struct(type);
    if (st.base != type_name()) {
        _binary_to_variant(resolve_type(st.base), stream, obj, recursion_depth, deadline, max_serialization_time);
    }
    for (const auto &field : st.fields) {
        obj(field.name, _binary_to_variant(resolve_type(field.type), stream, recursion_depth, deadline, max_serialization_time));
    }
}

fc::variant abi_serializer::_binary_to_variant(const type_name &type, fc::datastream<const char *> &stream,
                                               size_t recursion_depth, const fc::time_point &deadline, const fc::microseconds &max_serialization_time) const
{
    FC_ASSERT(++recursion_depth < max_recursion_depth, "recursive definition, max_recursion_depth ${r} ", ("r", max_recursion_depth));
    FC_ASSERT(fc::time_point::now() < deadline, "serialization time limit ${t}us exceeded", ("t", max_serialization_time));

    type_name rtype = resolve_type(type);
    auto ftype = fundamental_type(rtype);
    auto btype = built_in_types.find(ftype);
    if (btype != built_in_types.end()) {
        return btype->second.first(stream, is_array(rtype), is_optional(rtype));
    }
    if (is_array(rtype)) {
        fc::unsigned_int size;
        fc::raw::unpack(stream, size);
        vector<fc::variant> vars;
        for (decltype(size.value) i = 0; i < size; ++i) {
            auto v = _binary_to_variant(ftype, stream, recursion_depth, deadline, max_serialization_time);
            FC_ASSERT(!v.is_null(), "Invalid packed array");
            vars.emplace_back(std::move(v));
        }
        FC_ASSERT(vars.size() == size.value,
                  "packed size does not match unpacked array size, packed size ${p} actual size ${a}",
                  ("p", size)("a", vars.size()));
        return fc::variant(std::move(vars), GRAPHENE_MAX_NESTED_OBJECTS);

    } else if (is_optional(rtype)) {
        char flag;
        fc::raw::unpack(stream, flag);
        return flag ? _binary_to_variant(ftype, stream, recursion_depth, deadline, max_serialization_time) : fc::variant();
    }

    fc::mutable_variant_object mvo;
    _binary_to_variant(rtype, stream, mvo, recursion_depth, deadline, max_serialization_time);
    FC_ASSERT(mvo.size() > 0, "Unable to unpack stream ${type}", ("type", type));
    return fc::variant(std::move(mvo), GRAPHENE_MAX_NESTED_OBJECTS);
}

fc::variant abi_serializer::_binary_to_variant(const type_name &type, const bytes &binary,
                                               size_t recursion_depth, const fc::time_point &deadline, const fc::microseconds &max_serialization_time) const
{
    FC_ASSERT(++recursion_depth < max_recursion_depth, "recursive definition, max_recursion_depth ${r} ", ("r", max_recursion_depth));
    FC_ASSERT(fc::time_point::now() < deadline, "serialization time limit ${t}us exceeded", ("t", max_serialization_time));
    fc::datastream<const char *> ds(binary.data(), binary.size());
    return _binary_to_variant(type, ds, recursion_depth, deadline, max_serialization_time);
}

void abi_serializer::_variant_to_binary(const type_name &type, const fc::variant &var, fc::datastream<char *> &ds,
                                        size_t recursion_depth, const fc::time_point &deadline, const fc::microseconds &max_serialization_time) const
{
    try {
        FC_ASSERT(++recursion_depth < max_recursion_depth, "recursive definition, max_recursion_depth ${r} ", ("r", max_recursion_depth));
        FC_ASSERT(fc::time_point::now() < deadline, "serialization time limit ${t}us exceeded", ("t", max_serialization_time));
        auto rtype = resolve_type(type);

        auto btype = built_in_types.find(fundamental_type(rtype));
        if (btype != built_in_types.end()) {
            btype->second.second(var, ds, is_array(rtype), is_optional(rtype));
        } else if (is_array(rtype)) {
            vector<fc::variant> vars = var.get_array();
            fc::raw::pack(ds, (fc::unsigned_int) vars.size());
            for (const auto &var : vars) {
                _variant_to_binary(fundamental_type(rtype), var, ds, recursion_depth, deadline, max_serialization_time);
            }
        } else {
            const auto &st = get_struct(rtype);

            if (var.is_object()) {
                const auto &vo = var.get_object();

                if (st.base != type_name()) {
                    _variant_to_binary(resolve_type(st.base), var, ds, recursion_depth, deadline, max_serialization_time);
                }
                for (const auto &field : st.fields) {
                    if (vo.contains(string(field.name).c_str())) {
                        _variant_to_binary(field.type, vo[field.name], ds, recursion_depth, deadline, max_serialization_time);
                    } else {
                        _variant_to_binary(field.type, fc::variant(), ds, recursion_depth, deadline, max_serialization_time);
                        /// TODO: default construct field and write it out
                        FC_THROW("Missing '${f}' in variant object", ("f", field.name));
                    }
                }
            } else if (var.is_array()) {
                const auto &va = var.get_array();
                FC_ASSERT(st.base == type_name(), "support for base class as array not yet implemented");
                uint32_t i = 0;
                if (va.size() > 0) {
                    for (const auto &field : st.fields) {
                        if (va.size() > i)
                            _variant_to_binary(field.type, va[i], ds, recursion_depth, deadline, max_serialization_time);
                        else
                            _variant_to_binary(field.type, fc::variant(), ds, recursion_depth, deadline, max_serialization_time);
                        ++i;
                    }
                }
            }
        }
    }
    FC_CAPTURE_AND_RETHROW((type)(var))
}

bytes abi_serializer::_variant_to_binary(const type_name &type, const fc::variant &var,
                                         size_t recursion_depth, const fc::time_point &deadline, const fc::microseconds &max_serialization_time) const
{
    try {
        FC_ASSERT(++recursion_depth < max_recursion_depth, "recursive definition, max_recursion_depth ${r} ", ("r", max_recursion_depth));
        FC_ASSERT(fc::time_point::now() < deadline, "serialization time limit ${t}us exceeded", ("t", max_serialization_time));
        if (!_is_type(type, recursion_depth, deadline, max_serialization_time)) {
            return var.as<bytes>(20);
        }

        bytes temp(1024 * 1024);
        fc::datastream<char *> ds(temp.data(), temp.size());
        _variant_to_binary(type, var, ds, recursion_depth, deadline, max_serialization_time);
        temp.resize(ds.tellp());
        return temp;
    }
    FC_CAPTURE_AND_RETHROW((type)(var))
}

type_name abi_serializer::get_action_type(name action) const
{
    auto itr = actions.find(action);
    if (itr != actions.end()) return itr->second;
    return type_name();
}
type_name abi_serializer::get_table_type(name action) const
{
    auto itr = tables.find(action);
    if (itr != tables.end()) return itr->second;
    return type_name();
}

optional<string> abi_serializer::get_error_message(uint64_t error_code) const
{
    auto itr = error_messages.find(error_code);
    if (itr == error_messages.end())
        return optional<string>();

    return itr->second;
}
}
}

ext: cpp

max_stars_repo_name: InsurChain/insur-core

max_issues_repo_name: InsurChain/insur-core

max_forks_repo_name: InsurChain/insur-core


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

#include "DataMgr/ForeignStorage/ForeignStorageInterface.h"
#include "ThriftHandler/DBHandler.h"

#ifdef HAVE_THRIFT_THREADFACTORY
#include <thrift/concurrency/ThreadFactory.h>
#else
#include <thrift/concurrency/PlatformThreadFactory.h>
#endif

#include <thrift/concurrency/ThreadManager.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/protocol/TJSONProtocol.h>
#include <thrift/server/TThreadedServer.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/transport/THttpServer.h>
#include <thrift/transport/TSSLServerSocket.h>
#include <thrift/transport/TSSLSocket.h>
#include <thrift/transport/TServerSocket.h>

#include "Logger/Logger.h"
#include "Shared/SystemParameters.h"
#include "Shared/file_delete.h"
#include "Shared/mapd_shared_mutex.h"
#include "Shared/mapd_shared_ptr.h"
#include "Shared/scope.h"

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/filesystem.hpp>
#include <boost/locale/generator.hpp>
#include <boost/make_shared.hpp>
#include <boost/program_options.hpp>

#include <csignal>
#include <cstdlib>
#include <sstream>
#include <thread>
#include <vector>

#ifdef HAVE_AWS_S3
#include "DataMgr/OmniSciAwsSdk.h"
#endif
#include "DataMgr/ForeignStorage/ForeignTableRefresh.h"
#include "MapDRelease.h"
#include "Shared/Compressor.h"
#include "Shared/SystemParameters.h"
#include "Shared/file_delete.h"
#include "Shared/mapd_shared_ptr.h"
#include "Shared/scope.h"

using namespace ::apache::thrift;
using namespace ::apache::thrift::concurrency;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::server;
using namespace ::apache::thrift::transport;

extern bool g_enable_thrift_logs;

std::atomic<bool> g_running{true};
std::atomic<int> g_saw_signal{-1};

mapd_shared_mutex g_thrift_mutex;
TThreadedServer* g_thrift_http_server{nullptr};
TThreadedServer* g_thrift_buf_server{nullptr};

mapd::shared_ptr<DBHandler> g_warmup_handler =
    0;  // global "g_warmup_handler" needed to avoid circular dependency
// between "DBHandler" & function "run_warmup_queries"
mapd::shared_ptr<DBHandler> g_mapd_handler = 0;
std::once_flag g_shutdown_once_flag;

void shutdown_handler() {
  if (g_mapd_handler) {
    std::call_once(g_shutdown_once_flag, []() { g_mapd_handler->shutdown(); });
  }
}

void register_signal_handler(int signum, void (*handler)(int)) {
#ifdef _WIN32
  signal(signum, handler);
#else
  struct sigaction act;
  memset(&act, 0, sizeof(act));
  if (handler != SIG_DFL && handler != SIG_IGN) {
    // block all signal deliveries while inside the signal handler
    sigfillset(&act.sa_mask);
  }
  act.sa_handler = handler;
  sigaction(signum, &act, NULL);
#endif
}

// Signal handler to set a global flag telling the server to exit.
// Do not call other functions inside this (or any) signal handler
// unless you really know what you are doing. See also:
//   man 7 signal-safety
//   man 7 signal
//   https://en.wikipedia.org/wiki/Reentrancy_(computing)
void omnisci_signal_handler(int signum) {
  // Record the signal number for logging during shutdown.
  // Only records the first signal if called more than once.
  int expected_signal{-1};
  if (!g_saw_signal.compare_exchange_strong(expected_signal, signum)) {
    return;  // this wasn't the first signal
  }

  // This point should never be reached more than once.

  // Tell heartbeat() to shutdown by unsetting the 'g_running' flag.
  // If 'g_running' is already false, this has no effect and the
  // shutdown is already in progress.
  g_running = false;

  // Handle core dumps specially by pausing inside this signal handler
  // because on some systems, some signals will execute their default
  // action immediately when and if the signal handler returns.
  // We would like to do some emergency cleanup before core dump.
  if (signum == SIGABRT || signum == SIGSEGV || signum == SIGFPE
#ifndef _WIN32
      || signum == SIGQUIT
#endif
  ) {
    // Wait briefly to give heartbeat() a chance to flush the logs and
    // do any other emergency shutdown tasks.
    std::this_thread::sleep_for(std::chrono::seconds(2));

    // Explicitly trigger whatever default action this signal would
    // have done, such as terminate the process or dump core.
    // Signals are currently blocked so this new signal will be queued
    // until this signal handler returns.
    register_signal_handler(signum, SIG_DFL);
#ifdef _WIN32
    raise(signum);
#else
    kill(getpid(), signum);
#endif
    std::this_thread::sleep_for(std::chrono::seconds(5));

#ifndef __APPLE__
    // as a last resort, abort
    // primary used in Docker environments, where we can end up with PID 1 and fail to
    // catch unix signals
    quick_exit(signum);
#endif
  }
}

void register_signal_handlers() {
  register_signal_handler(SIGINT, omnisci_signal_handler);
#ifndef _WIN32
  register_signal_handler(SIGQUIT, omnisci_signal_handler);
  register_signal_handler(SIGHUP, omnisci_signal_handler);
#endif
  register_signal_handler(SIGTERM, omnisci_signal_handler);
  register_signal_handler(SIGSEGV, omnisci_signal_handler);
  register_signal_handler(SIGABRT, omnisci_signal_handler);
#ifndef _WIN32
  // Thrift secure socket can cause problems with SIGPIPE
  register_signal_handler(SIGPIPE, SIG_IGN);
#endif
}

void start_server(TThreadedServer& server, const int port) {
  try {
    server.serve();
    if (errno != 0) {
      throw std::runtime_error(std::string("Thrift server exited: ") +
                               std::strerror(errno));
    }
  } catch (std::exception& e) {
    LOG(ERROR) << "Exception: " << e.what() << ": port " << port << std::endl;
  }
}

void releaseWarmupSession(TSessionId& sessionId, std::ifstream& query_file) {
  query_file.close();
  if (sessionId != g_warmup_handler->getInvalidSessionId()) {
    g_warmup_handler->disconnect(sessionId);
  }
}

void run_warmup_queries(mapd::shared_ptr<DBHandler> handler,
                        std::string base_path,
                        std::string query_file_path) {
  // run warmup queries to load cache if requested
  if (query_file_path.empty()) {
    return;
  }
  LOG(INFO) << "Running DB warmup with queries from " << query_file_path;
  try {
    g_warmup_handler = handler;
    std::string db_info;
    std::string user_keyword, user_name, db_name;
    std::ifstream query_file;
    Catalog_Namespace::UserMetadata user;
    Catalog_Namespace::DBMetadata db;
    TSessionId sessionId = g_warmup_handler->getInvalidSessionId();

    ScopeGuard session_guard = [&] { releaseWarmupSession(sessionId, query_file); };
    query_file.open(query_file_path);
    while (std::getline(query_file, db_info)) {
      if (db_info.length() == 0) {
        continue;
      }
      std::istringstream iss(db_info);
      iss >> user_keyword >> user_name >> db_name;
      if (user_keyword.compare(0, 4, "USER") == 0) {
        // connect to DB for given user_name/db_name with super_user_rights (without
        // password), & start session
        g_warmup_handler->super_user_rights_ = true;
        g_warmup_handler->connect(sessionId, user_name, "", db_name);
        g_warmup_handler->super_user_rights_ = false;

        // read and run one query at a time for the DB with the setup connection
        TQueryResult ret;
        std::string single_query;
        while (std::getline(query_file, single_query)) {
          boost::algorithm::trim(single_query);
          if (single_query.length() == 0 || single_query[0] == '-') {
            continue;
          }
          if (single_query[0] == '}') {
            single_query.clear();
            break;
          }
          if (single_query.find(';') == single_query.npos) {
            std::string multiline_query;
            std::getline(query_file, multiline_query, ';');
            single_query += multiline_query;
          }

          try {
            g_warmup_handler->sql_execute(ret, sessionId, single_query, true, "", -1, -1);
          } catch (...) {
            LOG(WARNING) << "Exception while executing '" << single_query
                         << "', ignoring";
          }
          single_query.clear();
        }

        // stop session and disconnect from the DB
        g_warmup_handler->disconnect(sessionId);
        sessionId = g_warmup_handler->getInvalidSessionId();
      } else {
        LOG(WARNING) << "\nSyntax error in the file: " << query_file_path.c_str()
                     << " Missing expected keyword USER. Following line will be ignored: "
                     << db_info.c_str() << std::endl;
      }
      db_info.clear();
    }
  } catch (...) {
    LOG(WARNING) << "Exception while executing warmup queries. "
                 << "Warmup may not be fully completed. Will proceed nevertheless."
                 << std::endl;
  }
}

void heartbeat() {
#ifndef _WIN32
  // Block all signals for this heartbeat thread, only.
  sigset_t set;
  sigfillset(&set);
  int result = pthread_sigmask(SIG_BLOCK, &set, NULL);
  if (result != 0) {
    throw std::runtime_error("heartbeat() thread startup failed");
  }
#endif

  // Sleep until omnisci_signal_handler or anything clears the g_running flag.
  VLOG(1) << "heartbeat thread starting";
  while (::g_running) {
    using namespace std::chrono;
    std::this_thread::sleep_for(1s);
  }
  VLOG(1) << "heartbeat thread exiting";

  // Get the signal number if there was a signal.
  int signum = g_saw_signal;
  if (signum >= 1 && signum != SIGTERM) {
    LOG(INFO) << "Interrupt signal (" << signum << ") received.";
  }

  // if dumping core, try to do some quick stuff
  if (signum == SIGABRT || signum == SIGSEGV || signum == SIGFPE
#ifndef _WIN32
      || signum == SIGQUIT
#endif
  ) {
    if (g_mapd_handler) {
      std::call_once(g_shutdown_once_flag,
                     []() { g_mapd_handler->emergency_shutdown(); });
    }
    logger::shutdown();
    return;
    // core dump should begin soon after this, see omnisci_signal_handler()
  }

  // trigger an orderly shutdown by telling Thrift to stop serving
  {
    mapd_shared_lock<mapd_shared_mutex> read_lock(g_thrift_mutex);
    auto httpserv = g_thrift_http_server;
    if (httpserv) {
      httpserv->stop();
    }
    auto bufserv = g_thrift_buf_server;
    if (bufserv) {
      bufserv->stop();
    }
    // main() should return soon after this
  }
}

int startMapdServer(CommandLineOptions& prog_config_opts, bool start_http_server = true) {
  // try to enforce an orderly shutdown even after a signal
  register_signal_handlers();

  // register shutdown procedures for when a normal shutdown happens
  // be aware that atexit() functions run in reverse order
  atexit(&logger::shutdown);
  atexit(&shutdown_handler);

#ifdef HAVE_AWS_S3
  omnisci_aws_sdk::init_sdk();
  ScopeGuard aws_sdk_guard = [] { omnisci_aws_sdk::shutdown_sdk(); };
#endif

  // start background thread to clean up _DELETE_ME files
  const unsigned int wait_interval =
      3;  // wait time in secs after looking for deleted file before looking again
  std::thread file_delete_thread(file_delete,
                                 std::ref(g_running),
                                 wait_interval,
                                 prog_config_opts.base_path + "/mapd_data");
  std::thread heartbeat_thread(heartbeat);

  if (!g_enable_thrift_logs) {
    apache::thrift::GlobalOutput.setOutputFunction([](const char* msg) {});
  }

  if (g_enable_experimental_string_functions) {
    // Use the locale setting of the server by default. The generate parameter can be
    // updated appropriately if a locale override option is ever supported.
    boost::locale::generator generator;
    std::locale::global(generator.generate(""));
  }

  try {
    g_mapd_handler =
        mapd::make_shared<DBHandler>(prog_config_opts.db_leaves,
                                     prog_config_opts.string_leaves,
                                     prog_config_opts.base_path,
                                     prog_config_opts.allow_multifrag,
                                     prog_config_opts.jit_debug,
                                     prog_config_opts.intel_jit_profile,
                                     prog_config_opts.read_only,
                                     prog_config_opts.allow_loop_joins,
                                     prog_config_opts.enable_rendering,
                                     prog_config_opts.renderer_use_vulkan_driver,
                                     prog_config_opts.enable_auto_clear_render_mem,
                                     prog_config_opts.render_oom_retry_threshold,
                                     prog_config_opts.render_mem_bytes,
                                     prog_config_opts.max_concurrent_render_sessions,
                                     prog_config_opts.reserved_gpu_mem,
                                     prog_config_opts.render_compositor_use_last_gpu,
                                     prog_config_opts.num_reader_threads,
                                     prog_config_opts.authMetadata,
                                     prog_config_opts.system_parameters,
                                     prog_config_opts.enable_legacy_syntax,
                                     prog_config_opts.idle_session_duration,
                                     prog_config_opts.max_session_duration,
                                     prog_config_opts.enable_runtime_udf,
                                     prog_config_opts.udf_file_name,
                                     prog_config_opts.udf_compiler_path,
                                     prog_config_opts.udf_compiler_options,
#ifdef ENABLE_GEOS
                                     prog_config_opts.libgeos_so_filename,
#endif
                                     prog_config_opts.disk_cache_config,
                                     false);
  } catch (const std::exception& e) {
    LOG(FATAL) << "Failed to initialize service handler: " << e.what();
  }

  if (g_enable_fsi) {
    foreign_storage::ForeignTableRefreshScheduler::start(g_running);
  }

  mapd::shared_ptr<TServerSocket> serverSocket;
  mapd::shared_ptr<TServerSocket> httpServerSocket;
  if (!prog_config_opts.system_parameters.ssl_cert_file.empty() &&
      !prog_config_opts.system_parameters.ssl_key_file.empty()) {
    mapd::shared_ptr<TSSLSocketFactory> sslSocketFactory;
    sslSocketFactory =
        mapd::shared_ptr<TSSLSocketFactory>(new TSSLSocketFactory(SSLProtocol::SSLTLS));
    sslSocketFactory->loadCertificate(
        prog_config_opts.system_parameters.ssl_cert_file.c_str());
    sslSocketFactory->loadPrivateKey(
        prog_config_opts.system_parameters.ssl_key_file.c_str());
    if (prog_config_opts.system_parameters.ssl_transport_client_auth) {
      sslSocketFactory->authenticate(true);
    } else {
      sslSocketFactory->authenticate(false);
    }
    sslSocketFactory->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
    serverSocket = mapd::shared_ptr<TServerSocket>(new TSSLServerSocket(
        prog_config_opts.system_parameters.omnisci_server_port, sslSocketFactory));
    httpServerSocket = mapd::shared_ptr<TServerSocket>(
        new TSSLServerSocket(prog_config_opts.http_port, sslSocketFactory));
    LOG(INFO) << " OmniSci server using encrypted connection. Cert file ["
              << prog_config_opts.system_parameters.ssl_cert_file << "], key file ["
              << prog_config_opts.system_parameters.ssl_key_file << "]";
  } else {
    LOG(INFO) << " OmniSci server using unencrypted connection";
    serverSocket = mapd::shared_ptr<TServerSocket>(
        new TServerSocket(prog_config_opts.system_parameters.omnisci_server_port));
    httpServerSocket =
        mapd::shared_ptr<TServerSocket>(new TServerSocket(prog_config_opts.http_port));
  }

  ScopeGuard pointer_to_thrift_guard = [] {
    mapd_lock_guard<mapd_shared_mutex> write_lock(g_thrift_mutex);
    g_thrift_buf_server = g_thrift_http_server = nullptr;
  };

  if (prog_config_opts.system_parameters.ha_group_id.empty()) {
    mapd::shared_ptr<TProcessor> processor(
        new TrackingProcessor(g_mapd_handler, prog_config_opts.log_user_origin));
    mapd::shared_ptr<TTransportFactory> bufTransportFactory(
        new TBufferedTransportFactory());
    mapd::shared_ptr<TProtocolFactory> bufProtocolFactory(new TBinaryProtocolFactory());

    mapd::shared_ptr<TServerTransport> bufServerTransport(serverSocket);
    TThreadedServer bufServer(
        processor, bufServerTransport, bufTransportFactory, bufProtocolFactory);
    {
      mapd_lock_guard<mapd_shared_mutex> write_lock(g_thrift_mutex);
      g_thrift_buf_server = &bufServer;
    }

    std::thread bufThread(start_server,
                          std::ref(bufServer),
                          prog_config_opts.system_parameters.omnisci_server_port);

    // TEMPORARY
    auto warmup_queries = [&prog_config_opts]() {
      // run warm up queries if any exists
      run_warmup_queries(
          g_mapd_handler, prog_config_opts.base_path, prog_config_opts.db_query_file);
      if (prog_config_opts.exit_after_warmup) {
        g_running = false;
      }
    };

    mapd::shared_ptr<TServerTransport> httpServerTransport(httpServerSocket);
    mapd::shared_ptr<TTransportFactory> httpTransportFactory(
        new THttpServerTransportFactory());
    mapd::shared_ptr<TProtocolFactory> httpProtocolFactory(new TJSONProtocolFactory());
    TThreadedServer httpServer(
        processor, httpServerTransport, httpTransportFactory, httpProtocolFactory);
    if (start_http_server) {
      {
        mapd_lock_guard<mapd_shared_mutex> write_lock(g_thrift_mutex);
        g_thrift_http_server = &httpServer;
      }
      std::thread httpThread(
          start_server, std::ref(httpServer), prog_config_opts.http_port);

      warmup_queries();

      bufThread.join();
      httpThread.join();
    } else {
      warmup_queries();
      bufThread.join();
    }
  } else {  // running ha server
    LOG(FATAL) << "No High Availability module available, please contact OmniSci support";
  }

  g_running = false;
  file_delete_thread.join();
  heartbeat_thread.join();

  if (g_enable_fsi) {
    foreign_storage::ForeignTableRefreshScheduler::stop();
  }

  int signum = g_saw_signal;
  if (signum <= 0 || signum == SIGTERM) {
    return 0;
  } else {
    return signum;
  }
}

int main(int argc, char** argv) {
  bool has_clust_topo = false;

  CommandLineOptions prog_config_opts(argv[0], has_clust_topo);

  try {
    if (auto return_code =
            prog_config_opts.parse_command_line(argc, argv, !has_clust_topo)) {
      return *return_code;
    }

    if (!has_clust_topo) {
      prog_config_opts.validate_base_path();
      prog_config_opts.validate();
      return (startMapdServer(prog_config_opts));
    }
  } catch (std::runtime_error& e) {
    std::cerr << "Can't start: " << e.what() << std::endl;
    return 1;
  } catch (boost::program_options::error& e) {
    std::cerr << "Usage Error: " << e.what() << std::endl;
    return 1;
  }
}

max_stars_repo_name: weiting-chen/omniscidb

max_issues_repo_name: weiting-chen/omniscidb

max_forks_repo_name: weiting-chen/omniscidb


text:
/*!
 * Copyright (c) 2021 Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See LICENSE file in the project root for license information.
 */
#include "FunctionType.h"

#include <boost/foreach.hpp>
#include "FreeForm2Assert.h"
#include <sstream>
#include "TypeManager.h"

FreeForm2::FunctionType::FunctionType(TypeManager &p_typeManager,
                                      const TypeImpl &p_returnType,
                                      const TypeImpl *const *p_parameterTypes,
                                      size_t p_numParameters)
    : TypeImpl(Type::Function, true, &p_typeManager),
      m_returnType(&p_returnType),
      m_numParameters(p_numParameters)
{
    if (m_numParameters > 0)
    {
        m_parameterTypes[0] = p_parameterTypes[0];

        for (size_t i = 1; i < m_numParameters; i++)
        {
            m_parameterTypes[i] = p_parameterTypes[i];
        }
    }
}

const FreeForm2::TypeImpl &
FreeForm2::FunctionType::GetReturnType() const
{
    return *m_returnType;
}

FreeForm2::FunctionType::ParameterIterator
FreeForm2::FunctionType::BeginParameters() const
{
    return const_cast<FreeForm2::FunctionType::ParameterIterator>(&m_parameterTypes[0]);
}

FreeForm2::FunctionType::ParameterIterator
FreeForm2::FunctionType::EndParameters() const
{
    return BeginParameters() + m_numParameters;
}

size_t
FreeForm2::FunctionType::GetParameterCount() const
{
    return m_numParameters;
}

const std::string &
FreeForm2::FunctionType::GetName() const
{
    if (m_name.size() == 0)
    {
        m_name = FunctionType::GetName(GetReturnType(), BeginParameters(), GetParameterCount());
    }

    return m_name;
}

std::string
FreeForm2::FunctionType::GetName(const TypeImpl &p_returnType,
                                 const TypeImpl *const *p_parameterTypes,
                                 size_t p_numParams)
{
    std::ostringstream out;
    out << p_returnType << "(";

    bool first = true;

    for (int i = 0; i < p_numParams; i++)
    {
        if (!first)
        {
            out << ", ";
        }

        out << *p_parameterTypes[i];

        first = false;
    }

    out << ")";

    return out.str();
}

const FreeForm2::TypeImpl &
FreeForm2::FunctionType::AsConstType() const
{
    return *this;
}

const FreeForm2::TypeImpl &
FreeForm2::FunctionType::AsMutableType() const
{
    FF2_ASSERT("Functions cannot be mutable." && false);
    Unreachable(__FILE__, __LINE__);
}

bool FreeForm2::FunctionType::IsSameSubType(const TypeImpl &p_other, bool p_ignoreConst) const
{
    FF2_ASSERT(p_other.Primitive() == Type::Function);
    const FunctionType &other = static_cast<const FunctionType &>(p_other);

    if (m_numParameters != other.m_numParameters)
    {
        return false;
    }

    for (size_t i = 0; i < m_numParameters; i++)
    {
        const TypeImpl &m1 = *m_parameterTypes[i];
        const TypeImpl &m2 = *other.m_parameterTypes[i];
        if (!m1.IsSameAs(m2, p_ignoreConst))
        {
            return false;
        }
    }

    return GetReturnType().IsSameAs(other.GetReturnType(), p_ignoreConst);
}

max_stars_repo_name: ltxtech/lightgbm-transform

max_issues_repo_name: ltxtech/lightgbm-transform

max_forks_repo_name: ltxtech/lightgbm-transform


text:
#include "SupportGraphs.hpp"

#include <boost/graph/adjacency_matrix.hpp>
#include <boost/graph/boykov_kolmogorov_max_flow.hpp>
#include <boost/graph/filtered_graph.hpp>
#include <boost/property_map/function_property_map.hpp>

#include <xtensor/xvectorize.hpp>
#include <xtensor/xview.hpp>

tsplp::graph::PiSigmaSupportGraph::PiSigmaSupportGraph(const xt::xtensor<Variable, 3>& variables,
    const DependencyGraph& dependencies, const Model& model)
    : m_graph(variables.shape(1)), m_variables(variables), m_dependencies(dependencies), m_model(model)
{
    const auto N = variables.shape(1);
    assert(variables.shape(2) == N);

    for (size_t u = 0; u < N; ++u)
    {
        for (size_t v = 0; v < N; ++v)
        {
            if (u != v)
                add_edge(u, v, m_graph);
        }
    }

    assert(num_vertices(m_graph) == N);
    assert(num_edges(m_graph) == N * N - N);
}

std::pair<double, std::vector<std::pair<tsplp::graph::PiSigmaVertex, tsplp::graph::PiSigmaVertex>>>
tsplp::graph::PiSigmaSupportGraph::FindMinCut(PiSigmaVertex s, PiSigmaVertex t, ConstraintType x)
{
    struct Filter // cannot be a lambda because the filter must be default constructible
    {
        const DependencyGraph* d;
        ConstraintType x;
        PiSigmaVertex s;
        PiSigmaVertex t;

        bool operator()(PiSigmaVertex v) const
        {
            switch (x)
            {
            case ConstraintType::Pi: return !d->HasArc(v, s);
            case ConstraintType::Sigma: return !d->HasArc(t, v);
            case ConstraintType::PiSigma: return !d->HasArc(v, s) && !d->HasArc(t, v);
            }
            return true;
        }
    };

    auto filteredSupportGraph = make_filtered_graph(m_graph, boost::keep_all{}, Filter{ &m_dependencies, x, s, t });

    const auto getCapacity = [&](const PiSigmaEdge& e)
    {
        // const auto vf = xt::vectorize([](Variable v) { return v.GetObjectiveValue(); });
        // const auto values = xt::view(m_variables, xt::all(), source(e, filteredSupportGraph), target(e, filteredSupportGraph));
        // return xt::sum(vf(values))();

        const auto A = m_variables.shape(0);

        // it turns out that this manual summing is much faster than the outcommented "nicer" version above
        double sum = 0.0;
        for (size_t a = 0; a < A; ++a)
            sum += m_variables(a, source(e, filteredSupportGraph), target(e, filteredSupportGraph)).GetObjectiveValue(m_model);
        return sum;
    };

    const auto getReverseEdge = [&](const PiSigmaEdge& e)
    {
        return edge(target(e, filteredSupportGraph), source(e, filteredSupportGraph), filteredSupportGraph).first;
    };

    const auto cutSize = boost::boykov_kolmogorov_max_flow(filteredSupportGraph,
        boost::make_function_property_map<PiSigmaEdge>(getCapacity),
        get(boost::edge_residual_capacity, filteredSupportGraph),
        boost::make_function_property_map<PiSigmaEdge>(getReverseEdge),
        get(boost::vertex_predecessor, filteredSupportGraph),
        get(boost::vertex_color, filteredSupportGraph),
        get(boost::vertex_distance, filteredSupportGraph),
        get(boost::vertex_index, filteredSupportGraph),
        s, t);

    if (cutSize >= 1.0 - 1.e-10)
        return { cutSize, {} };

    const auto colorMap = get(boost::vertex_color, filteredSupportGraph);

    [[maybe_unused]] const auto black = get(colorMap, s);
    assert(black == boost::black_color);
    assert(get(colorMap, t) != black);

    std::vector<std::pair<PiSigmaVertex, PiSigmaVertex>> result;
    result.reserve(num_edges(filteredSupportGraph));
    for (const auto& edge : boost::make_iterator_range(edges(filteredSupportGraph)))
    {
        const auto u = source(edge, filteredSupportGraph);
        const auto v = target(edge, filteredSupportGraph);
        if (get(colorMap, u) == boost::black_color && get(colorMap, v) != boost::black_color)
            result.emplace_back(u, v);
    }

    return { cutSize, result };
}

max_stars_repo_name: sebrockm/mtsp-vrp

max_issues_repo_name: sebrockm/mtsp-vrp

max_forks_repo_name: sebrockm/mtsp-vrp


text:
/*
 * The MIT License (MIT)
 *
 * Copyright (c) <2015> <Stephan Gatzka>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE string

#include <boost/test/unit_test.hpp>

#include "jet_string.h"

BOOST_AUTO_TEST_CASE(strcase)
{
	const char haystack[] = "abcdefgh";
	BOOST_CHECK(jet_strcasestr(haystack, "ijkl") == NULL);
	BOOST_CHECK(jet_strcasestr(haystack, "bcd") == haystack + 1);
	BOOST_CHECK(jet_strcasestr(haystack, "DEF") == haystack + 3);
}

max_stars_repo_name: mloy/cjet

max_issues_repo_name: mloy/cjet

max_forks_repo_name: mloy/cjet


text:
/*
 * date: 23/01/2019
 * modified: 24/01/2019 16:09:08
 *
 * Author: Viktor Lavrentev
 * ------------------------------
 * description: Dynamic Library Loader
 * ------------------------------
 */

#include <Python.h>
#include <iostream>
#include <string>
#include <boost/dll.hpp>
#include <boost/python.hpp>
#include <boost/filesystem.hpp>

using namespace std;
namespace py = boost::python;

py::object call(const py::tuple &args, const py::dict &kw)
{
    py::str lib_pystr = py::extract<py::str>(kw["lib"]);
    string lib_str = py::extract<string>(lib_pystr);
    boost::filesystem::path lib_path = lib_str;
    string func_name = py::extract<string>(kw["func"]);
    function<py::object(const py::tuple&, const py::dict&)> func_ext;
    func_ext = boost::dll::import<py::object(const py::tuple&, const py::dict&)>(lib_path, func_name.c_str());
    py::object out_object = func_ext(args, kw);
    return out_object;
}

BOOST_PYTHON_MODULE(lib_loader)
{
    py::def("call", py::raw_function(call));
}

max_stars_repo_name: shrimo/Dynamic-Library-Loader

max_issues_repo_name: shrimo/Dynamic-Library-Loader

max_forks_repo_name: shrimo/Dynamic-Library-Loader


text:
#include "web_site_interfaces.hpp"
#include "web_site_interface.hpp"
#include <warpcoil/beast.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <silicium/error_or.hpp>
#include <iostream>
#include <warpcoil/beast_push_warnings.hpp>
#include <beast/websocket/stream.hpp>
#include <beast/http/read.hpp>
#include <warpcoil/pop_warnings.hpp>
#include <warpcoil/javascript.hpp>
#include <ventura/read_file.hpp>
#include <boost/intrusive/list.hpp>

namespace
{
    struct websocket_client : boost::intrusive::list_base_hook<
                                  boost::intrusive::link_mode<boost::intrusive::auto_unlink>>
    {
        typedef beast::websocket::stream<boost::asio::ip::tcp::socket &> websocket_type;
        typedef warpcoil::beast::async_stream_adaptor<websocket_type &> adaptor_type;

        boost::asio::ip::tcp::socket socket;
        beast::streambuf receive_buffer;
        websocket_type websocket;
        adaptor_type adaptor;
        warpcoil::cpp::message_splitter<adaptor_type> splitter;
        warpcoil::cpp::buffered_writer<adaptor_type> writer;
        async_publisher_server<async_publisher, adaptor_type, adaptor_type> server_adaptor;
        async_viewer_client<adaptor_type, adaptor_type> viewer_client;

        websocket_client(boost::asio::ip::tcp::socket socket, beast::streambuf receive_buffer,
                         async_publisher &server_impl)
            : socket(std::move(socket))
            , receive_buffer(std::move(receive_buffer))
            , websocket(this->socket)
            , adaptor(this->websocket, beast::streambuf())
            , splitter(this->adaptor)
            , writer(this->adaptor)
            , server_adaptor(server_impl, this->splitter, this->writer)
            , viewer_client(writer, splitter)
        {
        }
    };

    void begin_serve(std::shared_ptr<websocket_client> client)
    {
        client->server_adaptor.serve_one_request([client](boost::system::error_code const ec)
                                                 {
                                                     Si::throw_if_error(ec);
                                                     begin_serve(client);
                                                 });
    }

    struct web_site_publisher : async_publisher
    {
        typedef boost::intrusive::list<
            websocket_client, boost::intrusive::constant_time_size<false>> websocket_client_list;

        websocket_client_list all_clients;

        void publish(std::string message,
                     std::function<void(Si::error_or<std::tuple<>>)> on_result) override
        {
            for (websocket_client &client : all_clients)
            {
                client.viewer_client.display(message, [](Si::error_or<std::tuple<>> result)
                                             {
                                                 result.throw_if_error();
                                             });
            }
            // does not make sense to wait for responses from the clients here
            on_result(std::make_tuple());
        }
    };

    struct file_client
    {
        boost::asio::ip::tcp::socket socket;
        beast::streambuf receive_buffer;
        beast::http::response<beast::http::string_body> response;

        explicit file_client(boost::asio::ip::tcp::socket socket, beast::streambuf receive_buffer)
            : socket(std::move(socket))
            , receive_buffer(std::move(receive_buffer))
        {
        }
    };

    struct http_client
    {
        boost::asio::ip::tcp::socket socket;
        beast::streambuf receive_buffer;
        beast::http::request<beast::http::string_body> request;

        explicit http_client(boost::asio::ip::tcp::socket socket, beast::streambuf receive_buffer)
            : socket(std::move(socket))
            , receive_buffer(std::move(receive_buffer))
        {
        }
    };

    void begin_serve(std::shared_ptr<http_client> client, web_site_publisher &server_impl,
                     ventura::absolute_path const &document_root);

    void serve_prepared_response(std::shared_ptr<file_client> client, bool const is_keep_alive,
                                 web_site_publisher &server_impl,
                                 ventura::absolute_path const &document_root,
                                 boost::string_ref const content_type)
    {
        client->response.version = 11;
        client->response.fields.insert(
            "Content-Length", boost::lexical_cast<std::string>(client->response.body.size()));
        client->response.fields.insert("Content-Type", content_type);
        beast::http::async_write(
            client->socket, client->response,
            [client, is_keep_alive, &server_impl, document_root](boost::system::error_code const ec)
            {
                Si::throw_if_error(ec);
                if (is_keep_alive)
                {
                    auto http_client_again = std::make_shared<http_client>(
                        std::move(client->socket), std::move(client->receive_buffer));
                    begin_serve(http_client_again, server_impl, document_root);
                }
                else
                {
                    client->socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
                }
            });
    }

    void serve_static_file(std::shared_ptr<file_client> client, bool const is_keep_alive,
                           web_site_publisher &server_impl,
                           ventura::absolute_path const &document_root,
                           ventura::absolute_path const &served_document,
                           boost::string_ref const content_type)
    {
        Si::visit<void>(
            ventura::read_file(ventura::safe_c_str(ventura::to_os_string(served_document))),
            [&](std::vector<char> content)
            {
                // TODO: avoid the copy of the content
                client->response.body.assign(content.begin(), content.end());
                client->response.reason = "OK";
                client->response.status = 200;
            },
            [&](boost::system::error_code const ec)
            {
                std::cerr << "Could not read file " << served_document << ": " << ec << '\n';
                client->response.reason = "Internal Server Error";
                client->response.status = 500;
                client->response.body = client->response.reason;
            },
            [&](ventura::read_file_problem const problem)
            {
                std::cerr << "Could not read file " << served_document << " due to problem "
                          << static_cast<int>(problem) << '\n';
                client->response.reason = "Internal Server Error";
                client->response.status = 500;
                client->response.body = client->response.reason;
            });
        serve_prepared_response(client, is_keep_alive, server_impl, document_root, content_type);
    }

    void serve_interface_library(std::shared_ptr<file_client> client, bool const is_keep_alive,
                                 web_site_publisher &server_impl,
                                 ventura::absolute_path const &document_root)
    {
        auto code_writer =
            Si::Sink<char, Si::success>::erase(Si::make_container_sink(client->response.body));
        Si::append(code_writer, "\"use strict\";\n");

        Si::append(code_writer, "var library = ");
        warpcoil::javascript::generate_common_library(code_writer, warpcoil::indentation_level());
        Si::append(code_writer, ";\n");

        Si::memory_range const library = Si::make_c_str_range("library");
        Si::append(code_writer, "var make_receiver = ");
        warpcoil::javascript::generate_input_receiver(code_writer, warpcoil::indentation_level(),
                                                      warpcoil::create_viewer_interface(), library);
        Si::append(code_writer, ";\n");

        warpcoil::types::interface_definition const service =
            warpcoil::create_publisher_interface();
        Si::append(code_writer, "var make_client = ");
        warpcoil::javascript::generate_client(code_writer, warpcoil::indentation_level(), service,
                                              library);
        Si::append(code_writer, ";\n");

        client->response.reason = "OK";
        client->response.status = 200;
        serve_prepared_response(client, is_keep_alive, server_impl, document_root,
                                "text/javascript");
    }

    void begin_serve(std::shared_ptr<http_client> client, web_site_publisher &server_impl,
                     ventura::absolute_path const &document_root)
    {
        beast::http::async_read(
            client->socket, client->receive_buffer, client->request,
            [client, &server_impl, document_root](boost::system::error_code const ec)
            {
                Si::throw_if_error(ec);
                if (beast::http::is_upgrade(client->request))
                {
                    auto new_client = std::make_shared<websocket_client>(
                        std::move(client->socket), std::move(client->receive_buffer), server_impl);
                    new_client->websocket.async_accept(
                        client->request,
                        [new_client, &server_impl](boost::system::error_code const ec)
                        {
                            Si::throw_if_error(ec);
                            server_impl.all_clients.push_back(*new_client);
                            begin_serve(new_client);
                        });
                }
                else
                {
                    auto new_client = std::make_shared<file_client>(
                        std::move(client->socket), std::move(client->receive_buffer));
                    if (client->request.url == "/index.js")
                    {
                        serve_static_file(new_client, beast::http::is_keep_alive(client->request),
                                          server_impl, document_root,
                                          document_root / ventura::relative_path("index.js"),
                                          "text/javascript");
                    }
                    else if (client->request.url == "/service.js")
                    {
                        serve_interface_library(new_client,
                                                beast::http::is_keep_alive(client->request),
                                                server_impl, document_root);
                    }
                    else
                    {
                        serve_static_file(new_client, beast::http::is_keep_alive(client->request),
                                          server_impl, document_root,
                                          document_root / ventura::relative_path("index.html"),
                                          "text/html");
                    }
                }
            });
    }

    void begin_accept(boost::asio::ip::tcp::acceptor &acceptor, web_site_publisher &server_impl,
                      ventura::absolute_path const &document_root)
    {
        auto client = std::make_shared<http_client>(
            boost::asio::ip::tcp::socket(acceptor.get_io_service()), beast::streambuf());
        acceptor.async_accept(client->socket, [&acceptor, client, &server_impl,
                                               document_root](boost::system::error_code const ec)
                              {
                                  Si::throw_if_error(ec);
                                  begin_accept(acceptor, server_impl, document_root);
                                  begin_serve(client, server_impl, document_root);
                              });
    }
}

int main()
{
    using namespace boost::asio;

    web_site_publisher server_impl;
    io_service io;

    boost::uint16_t const port = 8080;

    ventura::absolute_path const document_root =
        *ventura::parent(*ventura::absolute_path::create(__FILE__));

    ip::tcp::acceptor acceptor_v6(io, ip::tcp::endpoint(ip::tcp::v6(), port), true);
    acceptor_v6.listen();
    begin_accept(acceptor_v6, server_impl, document_root);

    ip::tcp::acceptor acceptor_v4(io, ip::tcp::endpoint(ip::tcp::v4(), port), true);
    acceptor_v4.listen();
    begin_accept(acceptor_v4, server_impl, document_root);

    while (!io.stopped())
    {
        try
        {
            io.run();
        }
        catch (std::exception const &ex)
        {
            std::cerr << "Exception: " << ex.what() << '\n';
            io.reset();
        }
    }
}

max_stars_repo_name: TyRoXx/warpcoil

max_issues_repo_name: TyRoXx/warpcoil

max_forks_repo_name: TyRoXx/warpcoil


text:
/***************************************************************
 * Name:      MultiRNGMain.cpp
 * Purpose:   Code for Application Frame
 * Author:    Uli Koehler ()
 * Created:   2008-01-20
 * Copyright: Uli Koehler ()
 * License: GPLv2
 **************************************************************/

#include "wx_pch.h"
#include "MultiRNGMain.h"
#include <wx/msgdlg.h>

//(*InternalHeaders(MultiRNGFrame)
#include <wx/settings.h>
#include <wx/string.h>
#include <wx/intl.h>
//*)
///Custom include
#include "Generators.h"

#include <boost/random.hpp>

//helper functions
enum wxbuildinfoformat {
    short_f, long_f };

wxString wxbuildinfo(wxbuildinfoformat format)
{
    wxString wxbuild(wxVERSION_STRING);

    if (format == long_f )
    {
#if defined(__WXMSW__)
        wxbuild << _T("-Windows");
#elif defined(__UNIX__)
        wxbuild << _T("-Linux");
#endif

#if wxUSE_UNICODE
        wxbuild << _T("-Unicode build");
#else
        wxbuild << _T("-ANSI build");
#endif // wxUSE_UNICODE
    }

    return wxbuild;
}

//(*IdInit(MultiRNGFrame)
const long MultiRNGFrame::ID_TEXTCTRL23 = wxNewId();
const long MultiRNGFrame::ID_ALGOLABEL = wxNewId();
const long MultiRNGFrame::ID_ALGOCHOICE = wxNewId();
const long MultiRNGFrame::ID_AMOUNTLABEL = wxNewId();
const long MultiRNGFrame::ID_AMOUNTFIELD = wxNewId();
const long MultiRNGFrame::ID_FILELABEL = wxNewId();
const long MultiRNGFrame::ID_FILEFIELD = wxNewId();
const long MultiRNGFrame::ID_OKBUTTON = wxNewId();
const long MultiRNGFrame::ID_DISTCHOICE = wxNewId();
const long MultiRNGFrame::ID_STATICTEXT1 = wxNewId();
const long MultiRNGFrame::ID_TEXTCTRL1 = wxNewId();
//*)

BEGIN_EVENT_TABLE(MultiRNGFrame,wxFrame)
    //(*EventTable(MultiRNGFrame)
    //*)
END_EVENT_TABLE()

MultiRNGFrame::MultiRNGFrame(wxWindow* parent,wxWindowID id)
{
    //(*Initialize(MultiRNGFrame)
    Create(parent, wxID_ANY, _("MultiRNG"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE, _T("wxID_ANY"));
    SetClientSize(wxSize(585,174));
    distributionLabel = new wxTextCtrl(this, ID_TEXTCTRL23, _("Range:"), wxPoint(224,8), wxSize(56,21), wxTE_READONLY|wxTE_RIGHT|wxNO_BORDER, wxDefaultValidator, _T("ID_TEXTCTRL23"));
    distributionLabel->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_APPWORKSPACE));
    algorithmLabel = new wxStaticText(this, ID_ALGOLABEL, _("Algorithm:"), wxPoint(8,16), wxDefaultSize, 0, _T("ID_ALGOLABEL"));
    algorithmChoice = new wxChoice(this, ID_ALGOCHOICE, wxPoint(64,8), wxSize(160,27), 0, 0, 0, wxDefaultValidator, _T("ID_ALGOCHOICE"));
    amountLabel = new wxStaticText(this, ID_AMOUNTLABEL, _("Amount:"), wxPoint(8,48), wxDefaultSize, 0, _T("ID_AMOUNTLABEL"));
    amountField = new wxTextCtrl(this, ID_AMOUNTFIELD, _("100"), wxPoint(56,48), wxDefaultSize, 0, wxDefaultValidator, _T("ID_AMOUNTFIELD"));
    fileLabel = new wxStaticText(this, ID_FILELABEL, _("File:"), wxPoint(144,48), wxDefaultSize, 0, _T("ID_FILELABEL"));
    filenameField = new wxTextCtrl(this, ID_FILEFIELD, _("random.txt"), wxPoint(176,48), wxSize(216,21), 0, wxDefaultValidator, _T("ID_FILEFIELD"));
    okButton = new wxButton(this, ID_OKBUTTON, _("OK"), wxPoint(8,136), wxSize(384,23), 0, wxDefaultValidator, _T("ID_OKBUTTON"));
    distributionChoice = new wxChoice(this, ID_DISTCHOICE, wxPoint(296,8), wxSize(152,32), 0, 0, 0, wxDefaultValidator, _T("ID_DISTCHOICE"));
    distParam1Label = new wxStaticText(this, ID_STATICTEXT1, _("Dist param 1:"), wxPoint(24,96), wxDefaultSize, 0, _T("ID_STATICTEXT1"));
    distParam1Field = new wxTextCtrl(this, ID_TEXTCTRL1, _("10.0"), wxPoint(104,96), wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL1"));

    Connect(ID_OKBUTTON,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&MultiRNGFrame::OnOkButtonClick);
    Connect(wxID_ANY,wxEVT_CLOSE_WINDOW,(wxObjectEventFunction)&MultiRNGFrame::OnClose);
    //*)
    //Fill the algorithm and distribution combo boxes
    ///Set Algorithm choices
    algorithmChoice->Append(_("Mersenne Twister 19937"));   ///1
    algorithmChoice->Append(_("MInstdRand (LC Variant)"));  ///2
    algorithmChoice->Append(_("Ecuyer 1988"));              ///3
    algorithmChoice->Append(_("Kreutzer 1986"));            ///4
    algorithmChoice->Append(_("Hellekalek 1995"));          ///5
    algorithmChoice->Append(_("Mersenne Twister 11213b"));  ///6
    algorithmChoice->Append(_("Lagged Fibonacci 607"));     ///7
    algorithmChoice->Append(_("Lagged Fibonacci 1279"));    ///8
    algorithmChoice->Append(_("Lagged Fibonacci 2281"));    ///9
    algorithmChoice->Append(_("Lagged Fibonacci 3217"));    ///10
    algorithmChoice->Append(_("Lagged Fibonacci 4423"));    ///11
    algorithmChoice->Append(_("Lagged Fibonacci 9689"));    ///12
    algorithmChoice->Append(_("Lagged Fibonacci 19937"));   ///13
    algorithmChoice->Append(_("Lagged Fibonacci 23209"));   ///14
    algorithmChoice->Append(_("Lagged Fibonacci 44497"));   ///15
    algorithmChoice->SetSelection(0);
    ///Set Distribution choices
    distributionChoice->Append(wxT("Uniform Small Integer"));
    distributionChoice->Append(wxT("Uniform Integer"));
    distributionChoice->Append(wxT("Uniform Real"));
    distributionChoice->Append(wxT("Triangle"));
    distributionChoice->Append(wxT("Bernoulli"));
    distributionChoice->Append(wxT("Cauchy"));
    distributionChoice->Append(wxT("Exponential"));
    distributionChoice->Append(wxT("Geometric"));
    distributionChoice->Append(wxT("Normal"));
    distributionChoice->Append(wxT("Lognormal"));
    distributionChoice->Append(wxT("Uniform on Sphere"));
    distributionChoice->SetSelection(0);
}

MultiRNGFrame::~MultiRNGFrame()
{
    //(*Destroy(MultiRNGFrame)
    //*)
}

void MultiRNGFrame::OnQuit(wxCommandEvent& event)
{
    Close();
}

void MultiRNGFrame::OnAbout(wxCommandEvent& event)
{
    wxString msg = wxbuildinfo(long_f);
    wxMessageBox(msg, _("Welcome to..."));
}

void MultiRNGFrame::OnOkButtonClick(wxCommandEvent& event)
{
    ///Init static variables
    amountParam = lexical_cast<unsigned long long>(amountField->GetValue().mb_str());
    seedParam = generateSeed();
    ulParam = 100000; //TODO
    llParam = 1; //TODO
    distributionSelectionParam = distributionChoice->GetCurrentSelection();
    algorithmSelectionParam = algorithmChoice->GetCurrentSelection();
    filenameParam = lexical_cast<string>(filenameField->GetValue().mb_str());
    distParam1 = lexical_cast<string>(distParam1Field->GetValue().mb_str());
    ///Create a new thread if Multithreading is enabled or call function directly else
    //boost::thread boostThread(&GenRandBoost);
    GenRandBoost();
}

unsigned long MultiRNGFrame::generateSeed()
{
    return 1000100;
    unsigned long seed;
    ///Read from /dev/random if we are using linux or use time(0) on windows
    #ifdef __linux__
    ifstream f;
    ///Dependent on the state of highEntropyCheckbox open either /dev/random or /dev/urandom for read
    f.open("/dev/urandom", ifstream::in);
    f.read(reinterpret_cast<char*>(&seed), sizeof(unsigned long));
    f.close();
    #else
    MTRand mtr(time(0)); ///Create random state variable and seed with time(0)
    seed = mtr.randInt();
    #endif
    return seed;
}

void MultiRNGFrame::OnClose(wxCloseEvent& event)
{
    exit(0);
}

max_stars_repo_name: ulikoehler/MultiRNG

max_issues_repo_name: ulikoehler/MultiRNG

max_forks_repo_name: ulikoehler/MultiRNG


text:
//==================================================================================================
/*
  Copyright 2017 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
//! [inverse_hyperbolic]
#include <boost/simd/hyperbolic.hpp>
#include <boost/simd/pack.hpp>
#include <boost/simd/function/enumerate.hpp>
#include <iostream>

namespace bs =  boost::simd;
using pack_ft =  bs::pack <float, 8>;

int main()
{
  pack_ft p = bs::enumerate<pack_ft>(-2.0f, 0.5f);
  std::cout << " p =  " << p << std::endl
            <<  " -> bs::acosh(p) =  " << bs::acosh(p) << std::endl
            <<  " -> bs::asinh(p) =  " << bs::asinh(p) << std::endl
            <<  " -> bs::atanh(p) =  " << bs::atanh(p) << std::endl
            <<  " -> bs::asech(p) =  " << bs::asech(p) << std::endl
            <<  " -> bs::acsch(p) =  " << bs::acsch(p) << std::endl;
  return 0;
}
//! [inverse_hyperbolic]