text:
// ====================================================================
// This file is part of FlexibleSUSY.
//
// FlexibleSUSY is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// FlexibleSUSY is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with FlexibleSUSY.  If not, see
// <http://www.gnu.org/licenses/>.
// ====================================================================

// File generated at Thu 10 May 2018 15:09:54

#include "config.h"

#include "MSSMatMGUT_info.hpp"
#include "MSSMatMGUT_input_parameters.hpp"
#include "MSSMatMGUT_observables.hpp"
#include "MSSMatMGUT_physical.hpp"
#include "MSSMatMGUT_slha_io.hpp"
#include "MSSMatMGUT_model_slha.hpp"

#ifdef ENABLE_TWO_SCALE_SOLVER
#include "MSSMatMGUT_two_scale_model.hpp"
#include "MSSMatMGUT_two_scale_spectrum_generator.hpp"
#endif

#include "array_view.hpp"
#include "error.hpp"
#include "physical_input.hpp"
#include "slha_io.hpp"
#include "spectrum_generator_settings.hpp"
#include "standard_model_two_scale_model.hpp"
#include "lowe.h"

#include "mathlink.h"
#include "mathlink_utils.hpp"
#include "WolframLibrary.h"

#include <cmath>
#include <iostream>
#include <limits>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <utility>

#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>

#define INPUTPARAMETER(p) input.p
#define MODELPARAMETER(p) model.get_##p()
#define PHYSICALPARAMETER(p) model.get_physical().p
#define OBSERVABLE(o) observables.o

namespace flexiblesusy {
namespace MSSMatMGUT_librarylink {

using Handle = mint;

class Redirect_output {
public:
   explicit Redirect_output(MLINK link_)
      : link(link_)
      , buffer()
      , old_cout(std::cout.rdbuf(buffer.rdbuf()))
      , old_cerr(std::cerr.rdbuf(buffer.rdbuf()))
      {}

   ~Redirect_output() {
      std::cout.rdbuf(old_cout);
      std::cerr.rdbuf(old_cerr);
      flush();
   }

private:
   MLINK link;               ///< redirect to this link
   std::stringstream buffer; ///< buffer caching stdout
   std::streambuf* old_cout; ///< original stdout buffer
   std::streambuf* old_cerr; ///< original stderr buffer

   void flush() {
      std::string line;
      while (std::getline(buffer, line)) {
         MLPutFunction(link, "CompoundExpression", 2);
         MLPutFunction(link, "FSMSSMatMGUTMessage", 1);
         MLPutString(link, line.c_str());
      }
   }
};

class EUnknownHandle : public Error {
public:
   explicit EUnknownHandle(Handle hid_) : hid(hid_) {}
   virtual ~EUnknownHandle() = default;
   virtual std::string what() const override {
      return "Unknown handle: " + ToString(hid);
   }
   Handle hid;
};

class ENotEnoughFreeHandles : public Error {
public:
   explicit ENotEnoughFreeHandles(std::size_t max_handles_)
      : max_handles(max_handles_) {}
   virtual ~ENotEnoughFreeHandles() = default;
   virtual std::string what() const override {
      return "Maximum number of open handles reached: "
         + ToString(max_handles) + ".  Please close some handles!";
   }
   std::size_t max_handles;
};

class EWrongNumberOfParameters : public Error {
public:
   EWrongNumberOfParameters(mint pars_, mint expected_)
      : pars(pars_), expected(expected_) {}
   virtual ~EWrongNumberOfParameters() = default;
   virtual std::string what() const override {
      return "Wrong number of arguments: " + ToString(pars)
         + ".  Expected: " + ToString(expected);
   }
   mint pars, expected;
};

class EInvalidSpectrum : public Error {
public:
   EInvalidSpectrum() {}
   virtual ~EInvalidSpectrum() = default;
   virtual std::string what() const override { return "Invalid spectrum"; }
};

class MSSMatMGUT_spectrum {
public:
   virtual ~MSSMatMGUT_spectrum() = default;

   virtual void put_model_spectra(MLINK link) const = 0;

   virtual const Spectrum_generator_problems& get_problems() const = 0;
   virtual void fill_slha_io(MSSMatMGUT_slha_io&) const = 0;
   virtual double get_model_scale() const = 0;
   virtual const MSSMatMGUT_observables& get_observables() const = 0;

   virtual void calculate_spectrum(
      const Spectrum_generator_settings&, const SLHA_io::Modsel&,
      const softsusy::QedQcd&, const MSSMatMGUT_input_parameters&) = 0;
   virtual void calculate_model_observables(const softsusy::QedQcd&, const Physical_input&) = 0;
};

template <typename Solver_type>
class MSSMatMGUT_spectrum_impl : public MSSMatMGUT_spectrum
{
public:
   virtual ~MSSMatMGUT_spectrum_impl() = default;

   virtual void put_model_spectra(MLINK link) const override;

   virtual const Spectrum_generator_problems& get_problems() const override { return problems; }
   virtual void fill_slha_io(MSSMatMGUT_slha_io&) const override;
   virtual double get_model_scale() const override { return std::get<0>(models).get_scale(); }
   virtual const MSSMatMGUT_observables& get_observables() const override { return observables; }

   virtual void calculate_spectrum(
      const Spectrum_generator_settings&, const SLHA_io::Modsel&,
      const softsusy::QedQcd&, const MSSMatMGUT_input_parameters&) override;
   virtual void calculate_model_observables(const softsusy::QedQcd&, const Physical_input&) override;

private:
   std::tuple<MSSMatMGUT_slha<MSSMatMGUT<Solver_type>>> models{};        ///< running parameters and pole masses
   Spectrum_generator_problems problems{};   ///< spectrum generator problems
   MSSMatMGUT_scales scales{};              ///< scale information
   MSSMatMGUT_observables observables{};    ///< observables
};

class Model_data {
public:
   Model_data() = default;
   Model_data(const Model_data&) = delete;
   Model_data(Model_data&&) = default;
   ~Model_data() = default;
   Model_data& operator=(const Model_data&) = delete;
   Model_data& operator=(Model_data&&) = default;

   void set_input_parameters(const MSSMatMGUT_input_parameters& input_) { input = input_; }
   void set_physical_input(const Physical_input& p) { physical_input = p; }
   void set_sm_input_parameters(const softsusy::QedQcd& qedqcd_) { qedqcd = qedqcd_; }
   void set_settings(const Spectrum_generator_settings& s) { settings = s; }
   void set_modsel(const SLHA_io::Modsel& m) { modsel = m; }

   void put_settings(MLINK link) const;
   void put_sm_input_parameters(MLINK link) const;
   void put_input_parameters(MLINK link) const;
   void put_observables(MLINK link) const;
   void put_slha(MLINK link) const;

   void put_problems(MLINK link) const;
   void put_problems(MLINK link, const Problems&) const;
   void put_problems(MLINK link, const BVP_solver_problems&) const;
   void put_warnings(MLINK link) const;
   void put_warnings(MLINK link, const Problems&) const;
   void put_warnings(MLINK link, const BVP_solver_problems&) const;
   void put_model_spectra(MLINK link) const;
   void calculate_spectrum();
   void check_spectrum(MLINK link) const;
   void calculate_model_observables();

   double get_model_scale() const { return spectrum->get_model_scale(); }
private:
   MSSMatMGUT_input_parameters input{};     ///< model input parameters
   Physical_input physical_input{};          ///< extra non-SLHA physical input
   softsusy::QedQcd qedqcd{};                ///< SLHA physical input
   Spectrum_generator_settings settings{};   ///< spectrum generator settings
   SLHA_io::Modsel modsel{};                 ///< MODSEL input
   std::unique_ptr<MSSMatMGUT_spectrum> spectrum{nullptr};  ///< spectrum information

   MSSMatMGUT_slha_io get_slha_io() const;

   void check_spectrum_pointer() const;
};

/// current handles
using Handle_map = std::map<Handle, Model_data>;
Handle_map handles;

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

Handle get_new_handle()
{
   static const std::size_t max_handles =
      static_cast<std::size_t>(std::exp2(std::numeric_limits<Handle>::digits) - 1);

   if (handles.size() >= max_handles)
      throw ENotEnoughFreeHandles(handles.size());

   Handle hid = 0;

   while (handles.find(hid) != handles.end())
      hid++;

   return hid;
}

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

auto find_handle(Handle hid) -> decltype(handles.find(hid))
{
   const auto handle = handles.find(hid);

   if (handle == handles.end())
      throw EUnknownHandle(hid);

   return handle;
}

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

Model_data& find_data(Handle hid)
{
   return find_handle(hid)->second;
}

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

Handle get_handle_from(MLINK link)
{
   Handle hid;
   MLGet(link, &hid);

   return hid;
}

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

Handle get_handle_from(MArgument arg)
{
   return MArgument_getInteger(arg);
}

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

long number_of_args(MLINK link, const std::string& head)
{
   long argc;

   if (!MLCheckFunction(link, head.c_str(), &argc))
      std::cerr << "Error: argument is not a " << head << std::endl;

   return argc;
}

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

bool check_number_of_args(MLINK link, long number_of_arguments,
                          const std::string& function_name)
{
   const auto n_given = number_of_args(link, "List");
   const bool ok = n_given == number_of_arguments;

   if (!ok) {
      std::cerr << "Error: " << function_name << " expects "
                << ToString(number_of_arguments) << " argument ("
                << n_given << " given)." << std::endl;
   }

   return ok;
}

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

void put_error_output(MLINK link)
{
   MLPutSymbol(link, "$Failed");
}

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

void put_message(MLINK link,
                 const std::string& function_name,
                 const std::string& message_tag,
                 const std::string& message_str)
{
   MLPutFunction(link, "CompoundExpression", 2);
   MLPutFunction(link, "Message", 2);
   MLPutFunction(link, "MessageName", 2);
   MLPutSymbol(link, function_name.c_str());
   MLPutString(link, message_tag.c_str());
   MLPutString(link, message_str.c_str());
}

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

void Model_data::check_spectrum_pointer() const
{
   if (!spectrum) {
      throw SetupError("no spectrum generator set");
   }
}

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

void Model_data::put_settings(MLINK link) const
{
   MLPutFunction(link, "List", Spectrum_generator_settings::NUMBER_OF_OPTIONS);

   MLPutRuleTo(link, settings.get(Spectrum_generator_settings::precision), "precisionGoal");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::max_iterations)), "maxIterations");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::solver)), "solver");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::calculate_sm_masses)), "calculateStandardModelMasses");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::pole_mass_loop_order)), "poleMassLoopOrder");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::ewsb_loop_order)), "ewsbLoopOrder");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::beta_loop_order)), "betaFunctionLoopOrder");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::threshold_corrections_loop_order)), "thresholdCorrectionsLoopOrder");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::higgs_2loop_correction_at_as)), "higgs2loopCorrectionAtAs");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::higgs_2loop_correction_ab_as)), "higgs2loopCorrectionAbAs");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::higgs_2loop_correction_at_at)), "higgs2loopCorrectionAtAt");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::higgs_2loop_correction_atau_atau)), "higgs2loopCorrectionAtauAtau");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::force_output)), "forceOutput");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::top_pole_qcd_corrections)), "topPoleQCDCorrections");
   MLPutRuleTo(link, settings.get(Spectrum_generator_settings::beta_zero_threshold), "betaZeroThreshold");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::force_positive_masses)), "forcePositiveMasses");
   MLPutRuleTo(link, settings.get(Spectrum_generator_settings::pole_mass_scale), "poleMassScale");
   MLPutRuleTo(link, settings.get(Spectrum_generator_settings::eft_pole_mass_scale), "eftPoleMassScale");
   MLPutRuleTo(link, settings.get(Spectrum_generator_settings::eft_matching_scale), "eftMatchingScale");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::eft_matching_loop_order_up)), "eftMatchingLoopOrderUp");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::eft_matching_loop_order_down)), "eftMatchingLoopOrderDown");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::eft_higgs_index)), "eftHiggsIndex");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::calculate_bsm_masses)), "calculateBSMMasses");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::threshold_corrections)), "thresholdCorrections");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::higgs_3loop_ren_scheme_atb_as2)), "higgs3loopCorrectionRenScheme");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::higgs_3loop_correction_at_as2)), "higgs3loopCorrectionAtAsAs");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::higgs_3loop_correction_ab_as2)), "higgs3loopCorrectionAbAsAs");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::higgs_3loop_correction_at2_as)), "higgs3loopCorrectionAtAtAs");
   MLPutRuleTo(link, static_cast<int>(settings.get(Spectrum_generator_settings::higgs_3loop_correction_at3)), "higgs3loopCorrectionAtAtAt");
   MLPutRuleTo(link, modsel.parameter_output_scale, "parameterOutputScale");

   MLEndPacket(link);
}

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

void Model_data::put_sm_input_parameters(MLINK link) const
{
   MLPutFunction(link, "List",softsusy::NUMBER_OF_LOW_ENERGY_INPUT_PARAMETERS
                              + Physical_input::NUMBER_OF_INPUT_PARAMETERS);

   MLPutRuleTo(link, qedqcd.displayAlphaEmInput(), "alphaEmMZ");
   MLPutRuleTo(link, qedqcd.displayFermiConstant(), "GF");
   MLPutRuleTo(link, qedqcd.displayAlphaSInput(), "alphaSMZ");
   MLPutRuleTo(link, qedqcd.displayPoleMZ(), "MZ");
   MLPutRuleTo(link, qedqcd.displayMbMb(), "mbmb");
   MLPutRuleTo(link, qedqcd.displayPoleMt(), "Mt");
   MLPutRuleTo(link, qedqcd.displayPoleMtau(), "Mtau");
   MLPutRuleTo(link, qedqcd.displayNeutrinoPoleMass(3), "Mv3");
   MLPutRuleTo(link, qedqcd.displayPoleMW(), "MW");
   MLPutRuleTo(link, qedqcd.displayPoleMel(), "Me");
   MLPutRuleTo(link, qedqcd.displayNeutrinoPoleMass(1), "Mv1");
   MLPutRuleTo(link, qedqcd.displayPoleMmuon(), "Mm");
   MLPutRuleTo(link, qedqcd.displayNeutrinoPoleMass(2), "Mv2");
   MLPutRuleTo(link, qedqcd.displayMd2GeV(), "md2GeV");
   MLPutRuleTo(link, qedqcd.displayMu2GeV(), "mu2GeV");
   MLPutRuleTo(link, qedqcd.displayMs2GeV(), "ms2GeV");
   MLPutRuleTo(link, qedqcd.displayMcMc(), "mcmc");

   const flexiblesusy::CKM_parameters ckm(qedqcd.displayCKM());
   MLPutRuleTo(link, ckm.theta_12, "CKMTheta12");
   MLPutRuleTo(link, ckm.theta_13, "CKMTheta13");
   MLPutRuleTo(link, ckm.theta_23, "CKMTheta23");
   MLPutRuleTo(link, ckm.delta   , "CKMDelta");

   const flexiblesusy::PMNS_parameters pmns(qedqcd.displayPMNS());
   MLPutRuleTo(link, pmns.theta_12, "PMNSTheta12");
   MLPutRuleTo(link, pmns.theta_13, "PMNSTheta13");
   MLPutRuleTo(link, pmns.theta_23, "PMNSTheta23");
   MLPutRuleTo(link, pmns.delta   , "PMNSDelta");
   MLPutRuleTo(link, pmns.alpha_1 , "PMNSAlpha1");
   MLPutRuleTo(link, pmns.alpha_2 , "PMNSAlpha2");

   MLPutRuleTo(link, physical_input.get(Physical_input::alpha_em_0), "alphaEm0");
   MLPutRuleTo(link, physical_input.get(Physical_input::mh_pole), "Mh");

   MLEndPacket(link);
}

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

void Model_data::put_input_parameters(MLINK link) const
{
   MLPutFunction(link, "List", 15);

   MLPutRuleTo(link, INPUTPARAMETER(TanBeta), "TanBeta");
   MLPutRuleTo(link, INPUTPARAMETER(SignMu), "SignMu");
   MLPutRuleTo(link, INPUTPARAMETER(mHd2IN), "mHd2IN");
   MLPutRuleTo(link, INPUTPARAMETER(mHu2IN), "mHu2IN");
   MLPutRuleTo(link, INPUTPARAMETER(Aeij), "Aeij");
   MLPutRuleTo(link, INPUTPARAMETER(Adij), "Adij");
   MLPutRuleTo(link, INPUTPARAMETER(Auij), "Auij");
   MLPutRuleTo(link, INPUTPARAMETER(mq2Input), "mq2Input");
   MLPutRuleTo(link, INPUTPARAMETER(ml2Input), "ml2Input");
   MLPutRuleTo(link, INPUTPARAMETER(md2Input), "md2Input");
   MLPutRuleTo(link, INPUTPARAMETER(mu2Input), "mu2Input");
   MLPutRuleTo(link, INPUTPARAMETER(me2Input), "me2Input");
   MLPutRuleTo(link, INPUTPARAMETER(MassBInput), "MassBInput");
   MLPutRuleTo(link, INPUTPARAMETER(MassWBInput), "MassWBInput");
   MLPutRuleTo(link, INPUTPARAMETER(MassGInput), "MassGInput");

   MLEndPacket(link);
}

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

int number_of_problems(const Problems& problems)
{
   return problems.have_tachyon()
      + problems.no_ewsb()
      + (problems.no_perturbative() || problems.have_non_perturbative_parameter())
      + problems.no_sinThetaW_convergence()
      + problems.have_thrown()
      + problems.have_failed_pole_mass_convergence();
}

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

int number_of_problems(const BVP_solver_problems& problems)
{
   return problems.no_convergence();
}

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

int number_of_warnings(const Problems& problems)
{
   return problems.have_bad_mass();
}

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

int number_of_warnings(const BVP_solver_problems&)
{
   return 0; // no warnings yet
}

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

template <typename F>
void put_masses(MLINK link, const F& flags,
                const std::vector<std::string>& heads = {})
{
   for (std::size_t i = 0; i < flags.size(); i++) {
      if (flags[i]) {
         MLPutHeads(link, heads);
         MLPutSymbol(link, MSSMatMGUT_info::particle_names[i].c_str());
      }
   }
}

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

template <typename F>
void put_masses(MLINK link, const std::string& rule, const F& flags,
                const std::vector<std::string>& heads)
{
   const auto n_masses = std::count(flags.cbegin(), flags.cend(), true);

   MLPutRule(link, rule);
   MLPutFunction(link, "List", n_masses);
   put_masses(link, flags, heads);
}

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

template <typename F>
void put_masses(MLINK link, const std::string& rule,
                const F& flags1, const std::vector<std::string>& heads1,
                const F& flags2, const std::vector<std::string>& heads2)
{
   const auto n_masses = std::count(flags1.cbegin(), flags1.cend(), true)
                       + std::count(flags2.cbegin(), flags2.cend(), true);

   MLPutRule(link, rule);
   MLPutFunction(link, "List", n_masses);
   put_masses(link, flags1, heads1);
   put_masses(link, flags2, heads2);
}

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

void Model_data::put_problems(MLINK link, const Problems& problems) const
{
   if (problems.have_tachyon())
      put_masses(link, "Tachyons",
                 problems.get_running_tachyons(), {"M"},
                 problems.get_pole_tachyons(), {"Pole", "M"});
   if (problems.no_ewsb())
      MLPutRuleTo(link, "True", "NoEWSB");
   if (problems.no_perturbative() || problems.have_non_perturbative_parameter())
      MLPutRuleTo(link, "True", "NonPerturbative");
   if (problems.no_sinThetaW_convergence())
      MLPutRuleTo(link, "True", "NoSinThetaWConvergence");
   if (problems.have_thrown())
      MLPutRuleTo(link, "True", "Exceptions");
   if (problems.have_failed_pole_mass_convergence())
      put_masses(link, "NoPoleMassConvergence", problems.get_failed_pole_mass_convergence(), {"Pole", "M"});
}

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

void Model_data::put_problems(MLINK link, const BVP_solver_problems& problems) const
{
   if (problems.no_convergence())
      MLPutRuleTo(link, "True", "NoConvergence");
}

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

void Model_data::put_problems(MLINK link) const
{
   check_spectrum_pointer();
   const auto problems = spectrum->get_problems();
   const auto models = problems.get_model_problems();
   const auto n_models = models.size();
   const auto solvers = problems.get_bvp_solver_problems();
   const auto n_solvers = solvers.size();

   MLPutFunction(link, "List", n_models + n_solvers);

   for (const auto& m: models) {
      const auto np = number_of_problems(m);
      MLPutRule(link, m.get_model_name());
      MLPutFunction(link, "List", np);
      put_problems(link, m);
   }

   for (const auto& m: solvers) {
      const auto np = number_of_problems(m);
      MLPutRule(link, m.get_solver_name());
      MLPutFunction(link, "List", np);
      put_problems(link, m);
   }

   MLEndPacket(link);
}

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

void Model_data::put_warnings(MLINK link, const Problems& problems) const
{
   if (problems.have_bad_mass())
      put_masses(link, "ImpreciseMasses", problems.get_bad_masses(), {"M"});
}

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

void Model_data::put_warnings(MLINK, const BVP_solver_problems&) const
{
   // no warnings yet
}

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

void Model_data::put_warnings(MLINK link) const
{
   check_spectrum_pointer();
   const auto problems = spectrum->get_problems();
   const auto models = problems.get_model_problems();
   const auto n_models = models.size();
   const auto solvers = problems.get_bvp_solver_problems();
   const auto n_solvers = solvers.size();

   MLPutFunction(link, "List", n_models + n_solvers);

   for (const auto& m: models) {
      const auto nw = number_of_warnings(m);
      MLPutRule(link, m.get_model_name());
      MLPutFunction(link, "List", nw);
      put_warnings(link, m);
   }

   for (const auto& m: solvers) {
      const auto nw = number_of_warnings(m);
      MLPutRule(link, m.get_solver_name());
      MLPutFunction(link, "List", nw);
      put_warnings(link, m);
   }

   MLEndPacket(link);
}

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

MSSMatMGUT_slha_io Model_data::get_slha_io() const
{
   check_spectrum_pointer();
   MSSMatMGUT_slha_io slha_io;

   slha_io.set_settings(settings);
   slha_io.set_sminputs(qedqcd);
   slha_io.set_physical_input(physical_input);
   slha_io.set_modsel(modsel);
   slha_io.set_input(input);
   slha_io.set_print_imaginary_parts_of_majorana_mixings(
      settings.get(Spectrum_generator_settings::force_positive_masses));

   spectrum->fill_slha_io(slha_io);

   return slha_io;
}

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

void Model_data::put_slha(MLINK link) const
{
   const auto slha_io = get_slha_io();
   std::ostringstream ostr;

   slha_io.write_to_stream(ostr);

   MLPutString(link, ostr.str().c_str());
   MLEndPacket(link);
}

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

template <typename Solver_type>
void put_spectrum(const standard_model::StandardModel<Solver_type>& model, MLINK link)
{
   MLPutRule(link, standard_model_info::model_name);
   MLPutFunction(link, "List", 46);

   MLPutRuleTo(link, MODELPARAMETER(MVG), "VG", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MHp), "Hp", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MFv), "Fv", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MAh), "Ah", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(Mhh), "hh", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MFd), "Fd", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MFu), "Fu", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MFe), "Fe", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MVWp), "VWp", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MVP), "VP", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MVZ), "VZ", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(Vd), "Vd");
   MLPutRuleTo(link, MODELPARAMETER(Ud), "Ud");
   MLPutRuleTo(link, MODELPARAMETER(Vu), "Vu");
   MLPutRuleTo(link, MODELPARAMETER(Uu), "Uu");
   MLPutRuleTo(link, MODELPARAMETER(Ve), "Ve");
   MLPutRuleTo(link, MODELPARAMETER(Ue), "Ue");
   MLPutRuleTo(link, MODELPARAMETER(ZZ), "ZZ");
   MLPutRuleTo(link, PHYSICALPARAMETER(MVG), "VG", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MHp), "Hp", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MFv), "Fv", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MAh), "Ah", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(Mhh), "hh", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MFd), "Fd", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MFu), "Fu", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MFe), "Fe", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MVWp), "VWp", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MVP), "VP", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MVZ), "VZ", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(Vd), "Vd", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(Ud), "Ud", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(Vu), "Vu", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(Uu), "Uu", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(Ve), "Ve", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(Ue), "Ue", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZZ), "ZZ", {"Pole"});
   MLPutRuleTo(link, MODELPARAMETER(g1), "g1");
   MLPutRuleTo(link, MODELPARAMETER(g2), "g2");
   MLPutRuleTo(link, MODELPARAMETER(g3), "g3");
   MLPutRuleTo(link, MODELPARAMETER(Lambdax), "\u03bb");
   MLPutRuleTo(link, MODELPARAMETER(Yu), "Yu");
   MLPutRuleTo(link, MODELPARAMETER(Yd), "Yd");
   MLPutRuleTo(link, MODELPARAMETER(Ye), "Ye");
   MLPutRuleTo(link, MODELPARAMETER(mu2), "mu2");
   MLPutRuleTo(link, MODELPARAMETER(v), "v");
   MLPutRuleTo(link, MODELPARAMETER(scale), "SCALE");
}

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

template <typename Model>
void put_spectrum(const MSSMatMGUT_slha<Model>& model, MLINK link)
{
   MLPutRule(link, MSSMatMGUT_info::model_name);
   MLPutFunction(link, "List", 94);

   MLPutRuleTo(link, MODELPARAMETER(MVG), "VG", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MGlu), "Glu", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MFv), "Fv", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MSd), "Sd", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MSv), "Sv", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MSu), "Su", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MSe), "Se", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(Mhh), "hh", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MAh), "Ah", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MHpm), "Hpm", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MChi), "Chi", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MCha), "Cha", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MFe), "Fe", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MFd), "Fd", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MFu), "Fu", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MVWm), "VWm", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MVP), "VP", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(MVZ), "VZ", {"M"});
   MLPutRuleTo(link, MODELPARAMETER(ZD), "ZD");
   MLPutRuleTo(link, MODELPARAMETER(ZV), "ZV");
   MLPutRuleTo(link, MODELPARAMETER(ZU), "ZU");
   MLPutRuleTo(link, MODELPARAMETER(ZE), "ZE");
   MLPutRuleTo(link, MODELPARAMETER(ZH), "ZH");
   MLPutRuleTo(link, MODELPARAMETER(ZA), "ZA");
   MLPutRuleTo(link, MODELPARAMETER(ZP), "ZP");
   MLPutRuleTo(link, MODELPARAMETER(ZN), "ZN");
   MLPutRuleTo(link, MODELPARAMETER(UM), "UM");
   MLPutRuleTo(link, MODELPARAMETER(UP), "UP");
   MLPutRuleTo(link, MODELPARAMETER(ZEL), "ZEL");
   MLPutRuleTo(link, MODELPARAMETER(ZER), "ZER");
   MLPutRuleTo(link, MODELPARAMETER(ZDL), "ZDL");
   MLPutRuleTo(link, MODELPARAMETER(ZDR), "ZDR");
   MLPutRuleTo(link, MODELPARAMETER(ZUL), "ZUL");
   MLPutRuleTo(link, MODELPARAMETER(ZUR), "ZUR");
   MLPutRuleTo(link, MODELPARAMETER(ZZ), "ZZ");
   MLPutRuleTo(link, PHYSICALPARAMETER(MVG), "VG", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MGlu), "Glu", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MFv), "Fv", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MSd), "Sd", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MSv), "Sv", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MSu), "Su", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MSe), "Se", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(Mhh), "hh", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MAh), "Ah", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MHpm), "Hpm", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MChi), "Chi", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MCha), "Cha", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MFe), "Fe", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MFd), "Fd", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MFu), "Fu", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MVWm), "VWm", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MVP), "VP", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(MVZ), "VZ", {"Pole", "M"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZD), "ZD", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZV), "ZV", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZU), "ZU", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZE), "ZE", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZH), "ZH", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZA), "ZA", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZP), "ZP", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZN), "ZN", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(UM), "UM", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(UP), "UP", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZEL), "ZEL", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZER), "ZER", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZDL), "ZDL", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZDR), "ZDR", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZUL), "ZUL", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZUR), "ZUR", {"Pole"});
   MLPutRuleTo(link, PHYSICALPARAMETER(ZZ), "ZZ", {"Pole"});
   MLPutRuleTo(link, MODELPARAMETER(Yd), "Yd");
   MLPutRuleTo(link, MODELPARAMETER(Ye), "Ye");
   MLPutRuleTo(link, MODELPARAMETER(Yu), "Yu");
   MLPutRuleTo(link, MODELPARAMETER(Mu), "\u03bc");
   MLPutRuleTo(link, MODELPARAMETER(g1), "g1");
   MLPutRuleTo(link, MODELPARAMETER(g2), "g2");
   MLPutRuleTo(link, MODELPARAMETER(g3), "g3");
   MLPutRuleTo(link, MODELPARAMETER(vd), "vd");
   MLPutRuleTo(link, MODELPARAMETER(vu), "vu");
   MLPutRuleTo(link, MODELPARAMETER(TYd), "Yd", {"T"});
   MLPutRuleTo(link, MODELPARAMETER(TYe), "Ye", {"T"});
   MLPutRuleTo(link, MODELPARAMETER(TYu), "Yu", {"T"});
   MLPutRuleTo(link, MODELPARAMETER(BMu), "\u03bc", {"B"});
   MLPutRuleTo(link, MODELPARAMETER(mq2), "mq2");
   MLPutRuleTo(link, MODELPARAMETER(ml2), "ml2");
   MLPutRuleTo(link, MODELPARAMETER(mHd2), "mHd2");
   MLPutRuleTo(link, MODELPARAMETER(mHu2), "mHu2");
   MLPutRuleTo(link, MODELPARAMETER(md2), "md2");
   MLPutRuleTo(link, MODELPARAMETER(mu2), "mu2");
   MLPutRuleTo(link, MODELPARAMETER(me2), "me2");
   MLPutRuleTo(link, MODELPARAMETER(MassB), "MassB");
   MLPutRuleTo(link, MODELPARAMETER(MassWB), "MassWB");
   MLPutRuleTo(link, MODELPARAMETER(MassG), "MassG");
   MLPutRuleTo(link, MODELPARAMETER(scale), "SCALE");

}

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

namespace {
struct Put_spectrum {
   MLINK link;
   explicit Put_spectrum(MLINK link_) : link(link_) {}
   template<typename T>
   void operator()(const T& model) const { put_spectrum(model, link); }
};
} // anonymous namespace

template<typename... Ts>
void put_spectra(const std::tuple<Ts...>& models, MLINK link)
{
   MLPutFunction(link, "List", std::tuple_size<std::tuple<Ts...>>::value);

   // @todo Use generic lambda instead of Put_spectrum in C++14
   Put_spectrum ps(link);
   boost::fusion::for_each(models, ps);

   MLEndPacket(link);
}

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

template <typename Solver_type>
void MSSMatMGUT_spectrum_impl<Solver_type>::put_model_spectra(MLINK link) const
{
   put_spectra(models, link);
}

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

void Model_data::put_model_spectra(MLINK link) const
{
   check_spectrum_pointer();
   spectrum->put_model_spectra(link);
}

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

template <typename Solver_type>
void MSSMatMGUT_spectrum_impl<Solver_type>::calculate_spectrum(
   const Spectrum_generator_settings& settings,
   const SLHA_io::Modsel& modsel,
   const softsusy::QedQcd& qedqcd,
   const MSSMatMGUT_input_parameters& input
)
{
   MSSMatMGUT_spectrum_generator<Solver_type> spectrum_generator;
   spectrum_generator.set_settings(settings);
   spectrum_generator.set_parameter_output_scale(modsel.parameter_output_scale);
   spectrum_generator.run(qedqcd, input);

   models = spectrum_generator.get_models_slha();
   problems = spectrum_generator.get_problems();
   scales.HighScale = spectrum_generator.get_high_scale();
   scales.SUSYScale = spectrum_generator.get_susy_scale();
   scales.LowScale  = spectrum_generator.get_low_scale();
   scales.pole_mass_scale = spectrum_generator.get_pole_mass_scale();
}

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

template <typename Solver_type>
void MSSMatMGUT_spectrum_impl<Solver_type>::calculate_model_observables(
   const softsusy::QedQcd& qedqcd, const Physical_input& physical_input)
{
   observables = calculate_observables(std::get<0>(models), qedqcd, physical_input, scales.pole_mass_scale);
}

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

template <typename Solver_type>
void MSSMatMGUT_spectrum_impl<Solver_type>::fill_slha_io(MSSMatMGUT_slha_io& slha_io) const
{
   const auto& problems = std::get<0>(models).get_problems();
   const auto force_output = std::get<0>(models).do_force_output();

   slha_io.set_spinfo(problems);
   if (!problems.have_problem() || force_output) {
      slha_io.set_spectrum(models);
      slha_io.set_extra(std::get<0>(models), scales, observables);
   }
}

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

void Model_data::put_observables(MLINK link) const
{
   check_spectrum_pointer();
   MSSMatMGUT_observables observables = spectrum->get_observables();

   MLPutFunction(link, "List", 1);
   MLPutRule(link, MSSMatMGUT_info::model_name);
   MLPutFunction(link, "List", 0);

   MLEndPacket(link);
}

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

void Model_data::check_spectrum(MLINK link) const
{
   check_spectrum_pointer();
   const auto& problems = spectrum->get_problems();

   for (const auto& s: problems.get_problem_strings())
      put_message(link, "FSMSSMatMGUTCalculateSpectrum", "error", s);

   for (const auto& s: problems.get_warning_strings())
      put_message(link, "FSMSSMatMGUTCalculateSpectrum", "warning", s);

   if (problems.have_problem() &&
       !settings.get(Spectrum_generator_settings::force_output))
      throw EInvalidSpectrum();
}

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

void Model_data::calculate_spectrum()
{
   const int solver_type = static_cast<int>(settings.get(
                                               Spectrum_generator_settings::solver));
   switch (solver_type) {
   case 0:
#ifdef ENABLE_TWO_SCALE_SOLVER
   case 1:
      spectrum.reset(new MSSMatMGUT_spectrum_impl<Two_scale>());
      spectrum->calculate_spectrum(settings, modsel, qedqcd, input);
      if (!spectrum->get_problems().have_problem() || solver_type != 0) break;
#endif

   default:
      if (solver_type != 0) {
         throw SetupError("invalid solver type");
      }
   }
}

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

void Model_data::calculate_model_observables()
{
   check_spectrum_pointer();
   spectrum->calculate_model_observables(qedqcd, physical_input);
}

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

template <typename Element_t>
Model_data make_data(const Dynamic_array_view<Element_t>& pars)
{
   using Index_t = typename Dynamic_array_view<Element_t>::Index_t;

   const Index_t n_settings = Spectrum_generator_settings::NUMBER_OF_OPTIONS,
      n_sm_parameters = softsusy::NUMBER_OF_LOW_ENERGY_INPUT_PARAMETERS
                        + Physical_input::NUMBER_OF_INPUT_PARAMETERS,
      n_input_pars = 79;
   const Index_t n_total = n_settings + n_sm_parameters + n_input_pars;

   if (pars.size() != n_total)
      throw EWrongNumberOfParameters(pars.size(), n_total);

   Index_t c = 0; // counter

   Spectrum_generator_settings settings;
   settings.set(Spectrum_generator_settings::precision, pars[c++]);
   settings.set(Spectrum_generator_settings::max_iterations, pars[c++]);
   settings.set(Spectrum_generator_settings::solver, pars[c++]);
   settings.set(Spectrum_generator_settings::calculate_sm_masses, pars[c++]);
   settings.set(Spectrum_generator_settings::pole_mass_loop_order, pars[c++]);
   settings.set(Spectrum_generator_settings::ewsb_loop_order, pars[c++]);
   settings.set(Spectrum_generator_settings::beta_loop_order, pars[c++]);
   settings.set(Spectrum_generator_settings::threshold_corrections_loop_order, pars[c++]);
   settings.set(Spectrum_generator_settings::higgs_2loop_correction_at_as, pars[c++]);
   settings.set(Spectrum_generator_settings::higgs_2loop_correction_ab_as, pars[c++]);
   settings.set(Spectrum_generator_settings::higgs_2loop_correction_at_at, pars[c++]);
   settings.set(Spectrum_generator_settings::higgs_2loop_correction_atau_atau, pars[c++]);
   settings.set(Spectrum_generator_settings::force_output, pars[c++]);
   settings.set(Spectrum_generator_settings::top_pole_qcd_corrections, pars[c++]);
   settings.set(Spectrum_generator_settings::beta_zero_threshold, pars[c++]);
   settings.set(Spectrum_generator_settings::force_positive_masses, pars[c++]);
   settings.set(Spectrum_generator_settings::pole_mass_scale, pars[c++]);
   settings.set(Spectrum_generator_settings::eft_pole_mass_scale, pars[c++]);
   settings.set(Spectrum_generator_settings::eft_matching_scale, pars[c++]);
   settings.set(Spectrum_generator_settings::eft_matching_loop_order_up, pars[c++]);
   settings.set(Spectrum_generator_settings::eft_matching_loop_order_down, pars[c++]);
   settings.set(Spectrum_generator_settings::eft_higgs_index, pars[c++]);
   settings.set(Spectrum_generator_settings::calculate_bsm_masses, pars[c++]);
   settings.set(Spectrum_generator_settings::threshold_corrections, pars[c++]);
   settings.set(Spectrum_generator_settings::higgs_3loop_ren_scheme_atb_as2, pars[c++]);
   settings.set(Spectrum_generator_settings::higgs_3loop_correction_at_as2, pars[c++]);
   settings.set(Spectrum_generator_settings::higgs_3loop_correction_ab_as2, pars[c++]);
   settings.set(Spectrum_generator_settings::higgs_3loop_correction_at2_as, pars[c++]);
   settings.set(Spectrum_generator_settings::higgs_3loop_correction_at3, pars[c++]);

   SLHA_io::Modsel modsel;
   modsel.parameter_output_scale = pars[c++];

   softsusy::QedQcd qedqcd;
   qedqcd.setAlpha(softsusy::ALPHA, pars[c]);
   qedqcd.setAlphaEmInput(pars[c++]);
   qedqcd.setFermiConstant(pars[c++]);
   qedqcd.setAlpha(softsusy::ALPHAS, pars[c]);
   qedqcd.setAlphaSInput(pars[c++]);
   qedqcd.setPoleMZ(pars[c]);
   qedqcd.set_scale(pars[c++]);
   qedqcd.setMass(softsusy::mBottom, pars[c]);
   qedqcd.setMbMb(pars[c++]);
   qedqcd.setPoleMt(pars[c++]);
   qedqcd.setMass(softsusy::mTau, pars[c]);
   qedqcd.setPoleMtau(pars[c++]);
   qedqcd.setNeutrinoPoleMass(3, pars[c++]);
   qedqcd.setPoleMW(pars[c++]);
   qedqcd.setMass(softsusy::mElectron, pars[c]);
   qedqcd.setPoleMel(pars[c++]);
   qedqcd.setNeutrinoPoleMass(1, pars[c++]);
   qedqcd.setMass(softsusy::mMuon, pars[c]);
   qedqcd.setPoleMmuon(pars[c++]);
   qedqcd.setNeutrinoPoleMass(2, pars[c++]);
   qedqcd.setMass(softsusy::mDown, pars[c]);
   qedqcd.setMd2GeV(pars[c++]);
   qedqcd.setMass(softsusy::mUp, pars[c]);
   qedqcd.setMu2GeV(pars[c++]);
   qedqcd.setMass(softsusy::mStrange, pars[c]);
   qedqcd.setMs2GeV(pars[c++]);
   qedqcd.setMass(softsusy::mCharm, pars[c]);
   qedqcd.setMcMc(pars[c++]);

   {
      flexiblesusy::CKM_parameters ckm;
      ckm.theta_12 = pars[c++];
      ckm.theta_13 = pars[c++];
      ckm.theta_23 = pars[c++];
      ckm.delta    = pars[c++];
      qedqcd.setCKM(ckm);
   }

   {
      flexiblesusy::PMNS_parameters pmns;
      pmns.theta_12 = pars[c++];
      pmns.theta_13 = pars[c++];
      pmns.theta_23 = pars[c++];
      pmns.delta    = pars[c++];
      pmns.alpha_1  = pars[c++];
      pmns.alpha_2  = pars[c++];
      qedqcd.setPMNS(pmns);
   }

   Physical_input physical_input;
   physical_input.set(Physical_input::alpha_em_0, pars[c++]);
   physical_input.set(Physical_input::mh_pole, pars[c++]);

   MSSMatMGUT_input_parameters input;
   INPUTPARAMETER(TanBeta) = pars[c++];
   INPUTPARAMETER(SignMu) = pars[c++];
   INPUTPARAMETER(mHd2IN) = pars[c++];
   INPUTPARAMETER(mHu2IN) = pars[c++];
   INPUTPARAMETER(Aeij(0,0)) = pars[c++];
   INPUTPARAMETER(Aeij(0,1)) = pars[c++];
   INPUTPARAMETER(Aeij(0,2)) = pars[c++];
   INPUTPARAMETER(Aeij(1,0)) = pars[c++];
   INPUTPARAMETER(Aeij(1,1)) = pars[c++];
   INPUTPARAMETER(Aeij(1,2)) = pars[c++];
   INPUTPARAMETER(Aeij(2,0)) = pars[c++];
   INPUTPARAMETER(Aeij(2,1)) = pars[c++];
   INPUTPARAMETER(Aeij(2,2)) = pars[c++];
   INPUTPARAMETER(Adij(0,0)) = pars[c++];
   INPUTPARAMETER(Adij(0,1)) = pars[c++];
   INPUTPARAMETER(Adij(0,2)) = pars[c++];
   INPUTPARAMETER(Adij(1,0)) = pars[c++];
   INPUTPARAMETER(Adij(1,1)) = pars[c++];
   INPUTPARAMETER(Adij(1,2)) = pars[c++];
   INPUTPARAMETER(Adij(2,0)) = pars[c++];
   INPUTPARAMETER(Adij(2,1)) = pars[c++];
   INPUTPARAMETER(Adij(2,2)) = pars[c++];
   INPUTPARAMETER(Auij(0,0)) = pars[c++];
   INPUTPARAMETER(Auij(0,1)) = pars[c++];
   INPUTPARAMETER(Auij(0,2)) = pars[c++];
   INPUTPARAMETER(Auij(1,0)) = pars[c++];
   INPUTPARAMETER(Auij(1,1)) = pars[c++];
   INPUTPARAMETER(Auij(1,2)) = pars[c++];
   INPUTPARAMETER(Auij(2,0)) = pars[c++];
   INPUTPARAMETER(Auij(2,1)) = pars[c++];
   INPUTPARAMETER(Auij(2,2)) = pars[c++];
   INPUTPARAMETER(mq2Input(0,0)) = pars[c++];
   INPUTPARAMETER(mq2Input(0,1)) = pars[c++];
   INPUTPARAMETER(mq2Input(0,2)) = pars[c++];
   INPUTPARAMETER(mq2Input(1,0)) = pars[c++];
   INPUTPARAMETER(mq2Input(1,1)) = pars[c++];
   INPUTPARAMETER(mq2Input(1,2)) = pars[c++];
   INPUTPARAMETER(mq2Input(2,0)) = pars[c++];
   INPUTPARAMETER(mq2Input(2,1)) = pars[c++];
   INPUTPARAMETER(mq2Input(2,2)) = pars[c++];
   INPUTPARAMETER(ml2Input(0,0)) = pars[c++];
   INPUTPARAMETER(ml2Input(0,1)) = pars[c++];
   INPUTPARAMETER(ml2Input(0,2)) = pars[c++];
   INPUTPARAMETER(ml2Input(1,0)) = pars[c++];
   INPUTPARAMETER(ml2Input(1,1)) = pars[c++];
   INPUTPARAMETER(ml2Input(1,2)) = pars[c++];
   INPUTPARAMETER(ml2Input(2,0)) = pars[c++];
   INPUTPARAMETER(ml2Input(2,1)) = pars[c++];
   INPUTPARAMETER(ml2Input(2,2)) = pars[c++];
   INPUTPARAMETER(md2Input(0,0)) = pars[c++];
   INPUTPARAMETER(md2Input(0,1)) = pars[c++];
   INPUTPARAMETER(md2Input(0,2)) = pars[c++];
   INPUTPARAMETER(md2Input(1,0)) = pars[c++];
   INPUTPARAMETER(md2Input(1,1)) = pars[c++];
   INPUTPARAMETER(md2Input(1,2)) = pars[c++];
   INPUTPARAMETER(md2Input(2,0)) = pars[c++];
   INPUTPARAMETER(md2Input(2,1)) = pars[c++];
   INPUTPARAMETER(md2Input(2,2)) = pars[c++];
   INPUTPARAMETER(mu2Input(0,0)) = pars[c++];
   INPUTPARAMETER(mu2Input(0,1)) = pars[c++];
   INPUTPARAMETER(mu2Input(0,2)) = pars[c++];
   INPUTPARAMETER(mu2Input(1,0)) = pars[c++];
   INPUTPARAMETER(mu2Input(1,1)) = pars[c++];
   INPUTPARAMETER(mu2Input(1,2)) = pars[c++];
   INPUTPARAMETER(mu2Input(2,0)) = pars[c++];
   INPUTPARAMETER(mu2Input(2,1)) = pars[c++];
   INPUTPARAMETER(mu2Input(2,2)) = pars[c++];
   INPUTPARAMETER(me2Input(0,0)) = pars[c++];
   INPUTPARAMETER(me2Input(0,1)) = pars[c++];
   INPUTPARAMETER(me2Input(0,2)) = pars[c++];
   INPUTPARAMETER(me2Input(1,0)) = pars[c++];
   INPUTPARAMETER(me2Input(1,1)) = pars[c++];
   INPUTPARAMETER(me2Input(1,2)) = pars[c++];
   INPUTPARAMETER(me2Input(2,0)) = pars[c++];
   INPUTPARAMETER(me2Input(2,1)) = pars[c++];
   INPUTPARAMETER(me2Input(2,2)) = pars[c++];
   INPUTPARAMETER(MassBInput) = pars[c++];
   INPUTPARAMETER(MassWBInput) = pars[c++];
   INPUTPARAMETER(MassGInput) = pars[c++];

   Model_data data;
   data.set_settings(settings);
   data.set_modsel(modsel);
   data.set_sm_input_parameters(qedqcd);
   data.set_physical_input(physical_input);
   data.set_input_parameters(input);

   return data;
}

} // namespace MSSMatMGUT_librarylink
} // namespace flexiblesusy

extern "C" {

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

DLLEXPORT mint WolframLibrary_getVersion()
{
   return WolframLibraryVersion;
}

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

DLLEXPORT int WolframLibrary_initialize(WolframLibraryData /* libData */)
{
   return LIBRARY_NO_ERROR;
}

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

DLLEXPORT int FSMSSMatMGUTGetSettings(WolframLibraryData /* libData */, MLINK link)
{
   using namespace flexiblesusy::MSSMatMGUT_librarylink;

   if (!check_number_of_args(link, 1, "FSMSSMatMGUTGetSettings"))
      return LIBRARY_TYPE_ERROR;

   const auto hid = get_handle_from(link);

   try {
      find_data(hid).put_settings(link);
   } catch (const flexiblesusy::Error& e) {
      std::cerr << e.what() << std::endl;
      put_error_output(link);
   }

   return LIBRARY_NO_ERROR;
}

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

DLLEXPORT int FSMSSMatMGUTGetSMInputParameters(WolframLibraryData /* libData */, MLINK link)
{
   using namespace flexiblesusy::MSSMatMGUT_librarylink;

   if (!check_number_of_args(link, 1, "FSMSSMatMGUTGetSMInputParameters"))
      return LIBRARY_TYPE_ERROR;

   const auto hid = get_handle_from(link);

   try {
      find_data(hid).put_sm_input_parameters(link);
   } catch (const flexiblesusy::Error& e) {
      std::cerr << e.what() << std::endl;
      put_error_output(link);
   }

   return LIBRARY_NO_ERROR;
}

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

DLLEXPORT int FSMSSMatMGUTGetInputParameters(WolframLibraryData /* libData */, MLINK link)
{
   using namespace flexiblesusy::MSSMatMGUT_librarylink;

   if (!check_number_of_args(link, 1, "FSMSSMatMGUTGetInputParameters"))
      return LIBRARY_TYPE_ERROR;

   const auto hid = get_handle_from(link);

   try {
      find_data(hid).put_input_parameters(link);
   } catch (const flexiblesusy::Error& e) {
      std::cerr << e.what() << std::endl;
      put_error_output(link);
   }

   return LIBRARY_NO_ERROR;
}

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

DLLEXPORT int FSMSSMatMGUTOpenHandle(
   WolframLibraryData libData, mint Argc, MArgument* Args, MArgument Res)
{
   using namespace flexiblesusy;
   using namespace flexiblesusy::MSSMatMGUT_librarylink;

   if (Argc != 1)
      return LIBRARY_TYPE_ERROR;

   MTensor pars = MArgument_getMTensor(Args[0]);

   if (libData->MTensor_getType(pars) != MType_Real ||
       libData->MTensor_getRank(pars) != 1)
      return LIBRARY_TYPE_ERROR;

   try {
      auto data = make_data(make_dynamic_array_view(
                          libData->MTensor_getRealData(pars),
                          libData->MTensor_getDimensions(pars)[0]));

      const auto hid = get_new_handle();

      handles.insert(std::make_pair(hid, std::move(data)));

      MArgument_setInteger(Res, hid);
   } catch (const flexiblesusy::Error& e) {
      std::cerr << e.what() << std::endl;
      return LIBRARY_FUNCTION_ERROR;
   }

   return LIBRARY_NO_ERROR;
}

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

DLLEXPORT int FSMSSMatMGUTCloseHandle(
   WolframLibraryData /* libData */, mint Argc, MArgument* Args, MArgument /* Res */)
{
   using namespace flexiblesusy::MSSMatMGUT_librarylink;

   if (Argc != 1)
      return LIBRARY_TYPE_ERROR;

   const auto hid = get_handle_from(Args[0]);
   const auto handle = handles.find(hid);

   if (handle != handles.end())
      handles.erase(handle);

   return LIBRARY_NO_ERROR;
}

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

DLLEXPORT int FSMSSMatMGUTSet(
   WolframLibraryData libData, mint Argc, MArgument* Args, MArgument /* Res */)
{
   using namespace flexiblesusy;
   using namespace flexiblesusy::MSSMatMGUT_librarylink;

   if (Argc != 2)
      return LIBRARY_TYPE_ERROR;

   const auto hid = get_handle_from(Args[0]);
   MTensor pars = MArgument_getMTensor(Args[1]);

   if (libData->MTensor_getType(pars) != MType_Real ||
       libData->MTensor_getRank(pars) != 1)
      return LIBRARY_TYPE_ERROR;

   try {
      find_data(hid) =
         make_data(make_dynamic_array_view(
                      libData->MTensor_getRealData(pars),
                      libData->MTensor_getDimensions(pars)[0]));
   } catch (const flexiblesusy::Error& e) {
      std::cerr << e.what() << std::endl;
      return LIBRARY_FUNCTION_ERROR;
   }

   return LIBRARY_NO_ERROR;
}

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

DLLEXPORT int FSMSSMatMGUTGetProblems(
   WolframLibraryData /* libData */, MLINK link)
{
   using namespace flexiblesusy::MSSMatMGUT_librarylink;

   if (!check_number_of_args(link, 1, "FSMSSMatMGUTGetProblems"))
      return LIBRARY_TYPE_ERROR;

   const auto hid = get_handle_from(link);

   try {
      find_data(hid).put_problems(link);
   } catch (const flexiblesusy::Error& e) {
      std::cerr << e.what() << std::endl;
      put_error_output(link);
   }

   return LIBRARY_NO_ERROR;
}

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

DLLEXPORT int FSMSSMatMGUTToSLHA(WolframLibraryData /* libData */, MLINK link)
{
   using namespace flexiblesusy::MSSMatMGUT_librarylink;

   if (!check_number_of_args(link, 1, "FSMSSMatMGUTToSLHA"))
      return LIBRARY_TYPE_ERROR;

   const auto hid = get_handle_from(link);

   try {
      find_data(hid).put_slha(link);
   } catch (const flexiblesusy::Error& e) {
      std::cerr << e.what() << std::endl;
      put_error_output(link);
   }

   return LIBRARY_NO_ERROR;
}

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

DLLEXPORT int FSMSSMatMGUTGetWarnings(
   WolframLibraryData /* libData */, MLINK link)
{
   using namespace flexiblesusy::MSSMatMGUT_librarylink;

   if (!check_number_of_args(link, 1, "FSMSSMatMGUTGetWarnings"))
      return LIBRARY_TYPE_ERROR;

   const auto hid = get_handle_from(link);

   try {
      find_data(hid).put_warnings(link);
   } catch (const flexiblesusy::Error& e) {
      std::cerr << e.what() << std::endl;
      put_error_output(link);
   }

   return LIBRARY_NO_ERROR;
}

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

DLLEXPORT int FSMSSMatMGUTCalculateSpectrum(
   WolframLibraryData /* libData */, MLINK link)
{
   using namespace flexiblesusy::MSSMatMGUT_librarylink;

   if (!check_number_of_args(link, 1, "FSMSSMatMGUTCalculateSpectrum"))
      return LIBRARY_TYPE_ERROR;

   const auto hid = get_handle_from(link);

   try {
      auto& data = find_data(hid);

      {
         Redirect_output crd(link);
         data.calculate_spectrum();
      }

      data.check_spectrum(link);
      data.put_model_spectra(link);
   } catch (const flexiblesusy::Error&) {
      put_error_output(link);
   }

   return LIBRARY_NO_ERROR;
}

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

DLLEXPORT int FSMSSMatMGUTCalculateObservables(
   WolframLibraryData /* libData */, MLINK link)
{
   using namespace flexiblesusy::MSSMatMGUT_librarylink;

   if (!check_number_of_args(link, 1, "FSMSSMatMGUTCalculateObservables"))
      return LIBRARY_TYPE_ERROR;

   const auto hid = get_handle_from(link);

   try {
      auto& data = find_data(hid);

      if (data.get_model_scale() == 0.) {
         put_message(link,
            "FSMSSMatMGUTCalculateObservables", "warning",
            "Renormalization scale is 0.  Did you run "
            "FSMSSMatMGUTCalculateSpectrum[]?");
      }

      {
         Redirect_output crd(link);
         data.calculate_model_observables();
      }

      data.put_observables(link);
   } catch (const flexiblesusy::Error& e) {
      put_message(link, "FSMSSMatMGUTCalculateObservables", "error", e.what());
      put_error_output(link);
   }

   return LIBRARY_NO_ERROR;
}

} // extern "C"


text:
/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2015
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/

#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <list>

#include <round/core/Route.h>

#include <string.h>

const std::string Round::RouteObjects::OBJECT_SEP = ".";
const int Round::RouteObjects::OBJECT_NUM = 3;

const int Round::RouteObjects::TARGET = 0;
const int Round::RouteObjects::NODE = 1;
const int Round::RouteObjects::CLUSTER = 2;

Round::RouteObjects::RouteObjects() {
}

Round::RouteObjects::RouteObjects(const std::string &value) {
  parse(value);
}

Round::RouteObjects::~RouteObjects() {
}

bool Round::RouteObjects::isValid() const {
  if (size() != OBJECT_NUM)
    return false;
  return true;
}

bool Round::RouteObjects::parse(const std::string &value) {
  clear();

  if (value.length() <= 0)
    return false;

  std::list<std::string> objectList;
  boost::split(objectList, value, boost::is_any_of(OBJECT_SEP));

  size_t objectSize = objectList.size();
  if ((objectSize < 1) || (OBJECT_NUM < objectSize))
    return false;

  this->insert(std::pair<int, std::string>(TARGET, Route::METHOD_DEFALUT));
  this->insert(std::pair<int, std::string>(NODE, Route::NODE_DEFALUT));
  this->insert(std::pair<int, std::string>(CLUSTER, Route::CLUSTER_DEFALUT));

  int objectIdx = 0;
  BOOST_REVERSE_FOREACH(std::string object, objectList) {
    RouteObjects::iterator objIt = find(objectIdx);
    if (objIt != RouteObjects::end()) {
      erase(objIt);
    }
    this->insert(std::pair<int, std::string>(objectIdx, object));
    objectIdx++;
  }

  return true;
}

bool Round::RouteObjects::getObject(int objIdx, std::string *value) const {
  RouteObjects::const_iterator objIt = find(objIdx);
  if (objIt == end())
    return false;
  *value = objIt->second;
  return true;
}

bool Round::RouteObjects::equals(const RouteObjects &otherObj) const {
  if (!isValid() || !otherObj.isValid())
    return false;

  for (RouteObjects::const_iterator objIt = begin(); objIt != end(); objIt++) {
    int objIdx = objIt->first;
    std::string objVal = objIt->second;
    RouteObjects::const_iterator otherObjIt = otherObj.find(objIdx);
    if (otherObjIt == otherObj.end())
      return false;
    if (objVal.compare(otherObjIt->second) != 0)
      return false;
  }

  return true;
}

bool Round::RouteObjects::isMethod(const std::string &value) const {
  std::string thisValue;
  if (!getTarget(&thisValue))
    return false;
  return (thisValue.compare(value) == 0) ? true : false;
}

bool Round::RouteObjects::isNode(const std::string &value) const {
  std::string thisValue;
  if (!getNode(&thisValue))
    return false;
  return (thisValue.compare(value) == 0) ? true : false;
}

bool Round::RouteObjects::isCluster(const std::string &value) const {
  std::string thisValue;
  if (!getCluster(&thisValue))
    return false;
  return (thisValue.compare(value) == 0) ? true : false;
}

bool Round::RouteObjects::equals(const std::string &otherRoute) const {
  RouteObjects otherRouteObjs(otherRoute);
  return equals(otherRouteObjs);
}

bool Round::RouteObjects::toString(std::string *value) const {
  if (!value)
    return false;

  *value = "";
  for (int n=(OBJECT_NUM-1); 0<=n; n--) {
    std::string objStr;
    if (!getObject(n, &objStr))
      continue;
    if (0 < (*value).length()) {
      *value += OBJECT_SEP;
    }
    *value += objStr;
  }
  return true;
}

ext: cpp

max_stars_repo_name: cybergarage/round-cc

max_issues_repo_name: cybergarage/round-cc

max_forks_repo_name: cybergarage/round-cc


text:
// copyright (c) 2009-2014 the moorecoin core developers
// distributed under the mit software license, see the accompanying
// file copying or http://www.opensource.org/licenses/mit-license.php.

#include "base58.h"
#include "rpcserver.h"
#include "init.h"
#include "main.h"
#include "script/script.h"
#include "script/standard.h"
#include "sync.h"
#include "util.h"
#include "utiltime.h"
#include "wallet.h"

#include <fstream>
#include <stdint.h>

#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include "univalue/univalue.h"

using namespace std;

void ensurewalletisunlocked();
bool ensurewalletisavailable(bool avoidexception);

std::string static encodedumptime(int64_t ntime) {
    return datetimestrformat("%y-%m-%dt%h:%m:%sz", ntime);
}

int64_t static decodedumptime(const std::string &str) {
    static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);
    static const std::locale loc(std::locale::classic(),
        new boost::posix_time::time_input_facet("%y-%m-%dt%h:%m:%sz"));
    std::istringstream iss(str);
    iss.imbue(loc);
    boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);
    iss >> ptime;
    if (ptime.is_not_a_date_time())
        return 0;
    return (ptime - epoch).total_seconds();
}

std::string static encodedumpstring(const std::string &str) {
    std::stringstream ret;
    boost_foreach(unsigned char c, str) {
        if (c <= 32 || c >= 128 || c == '%') {
            ret << '%' << hexstr(&c, &c + 1);
        } else {
            ret << c;
        }
    }
    return ret.str();
}

std::string decodedumpstring(const std::string &str) {
    std::stringstream ret;
    for (unsigned int pos = 0; pos < str.length(); pos++) {
        unsigned char c = str[pos];
        if (c == '%' && pos+2 < str.length()) {
            c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
                ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
            pos += 2;
        }
        ret << c;
    }
    return ret.str();
}

univalue importprivkey(const univalue& params, bool fhelp)
{
    if (!ensurewalletisavailable(fhelp))
        return nullunivalue;

    if (fhelp || params.size() < 1 || params.size() > 3)
        throw runtime_error(
            "importprivkey \"moorecoinprivkey\" ( \"label\" rescan )\n"
            "\nadds a private key (as returned by dumpprivkey) to your wallet.\n"
            "\narguments:\n"
            "1. \"moorecoinprivkey\"   (string, required) the private key (see dumpprivkey)\n"
            "2. \"label\"            (string, optional, default=\"\") an optional label\n"
            "3. rescan               (boolean, optional, default=true) rescan the wallet for transactions\n"
            "\nnote: this call can take minutes to complete if rescan is true.\n"
            "\nexamples:\n"
            "\ndump a private key\n"
            + helpexamplecli("dumpprivkey", "\"myaddress\"") +
            "\nimport the private key with rescan\n"
            + helpexamplecli("importprivkey", "\"mykey\"") +
            "\nimport using a label and without rescan\n"
            + helpexamplecli("importprivkey", "\"mykey\" \"testing\" false") +
            "\nas a json-rpc call\n"
            + helpexamplerpc("importprivkey", "\"mykey\", \"testing\", false")
        );

    if (fprunemode)
        throw jsonrpcerror(rpc_wallet_error, "importing keys is disabled in pruned mode");

    lock2(cs_main, pwalletmain->cs_wallet);

    ensurewalletisunlocked();

    string strsecret = params[0].get_str();
    string strlabel = "";
    if (params.size() > 1)
        strlabel = params[1].get_str();

    // whether to perform rescan after import
    bool frescan = true;
    if (params.size() > 2)
        frescan = params[2].get_bool();

    cmoorecoinsecret vchsecret;
    bool fgood = vchsecret.setstring(strsecret);

    if (!fgood) throw jsonrpcerror(rpc_invalid_address_or_key, "invalid private key encoding");

    ckey key = vchsecret.getkey();
    if (!key.isvalid()) throw jsonrpcerror(rpc_invalid_address_or_key, "private key outside allowed range");

    cpubkey pubkey = key.getpubkey();
    assert(key.verifypubkey(pubkey));
    ckeyid vchaddress = pubkey.getid();
    {
        pwalletmain->markdirty();
        pwalletmain->setaddressbook(vchaddress, strlabel, "receive");

        // don't throw error in case a key is already there
        if (pwalletmain->havekey(vchaddress))
            return nullunivalue;

        pwalletmain->mapkeymetadata[vchaddress].ncreatetime = 1;

        if (!pwalletmain->addkeypubkey(key, pubkey))
            throw jsonrpcerror(rpc_wallet_error, "error adding key to wallet");

        // whenever a key is imported, we need to scan the whole chain
        pwalletmain->ntimefirstkey = 1; // 0 would be considered 'no value'

        if (frescan) {
            pwalletmain->scanforwallettransactions(chainactive.genesis(), true);
        }
    }

    return nullunivalue;
}

univalue importaddress(const univalue& params, bool fhelp)
{
    if (!ensurewalletisavailable(fhelp))
        return nullunivalue;

    if (fhelp || params.size() < 1 || params.size() > 3)
        throw runtime_error(
            "importaddress \"address\" ( \"label\" rescan )\n"
            "\nadds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n"
            "\narguments:\n"
            "1. \"address\"          (string, required) the address\n"
            "2. \"label\"            (string, optional, default=\"\") an optional label\n"
            "3. rescan               (boolean, optional, default=true) rescan the wallet for transactions\n"
            "\nnote: this call can take minutes to complete if rescan is true.\n"
            "\nexamples:\n"
            "\nimport an address with rescan\n"
            + helpexamplecli("importaddress", "\"myaddress\"") +
            "\nimport using a label without rescan\n"
            + helpexamplecli("importaddress", "\"myaddress\" \"testing\" false") +
            "\nas a json-rpc call\n"
            + helpexamplerpc("importaddress", "\"myaddress\", \"testing\", false")
        );

    if (fprunemode)
        throw jsonrpcerror(rpc_wallet_error, "importing addresses is disabled in pruned mode");

    lock2(cs_main, pwalletmain->cs_wallet);

    cscript script;

    cmoorecoinaddress address(params[0].get_str());
    if (address.isvalid()) {
        script = getscriptfordestination(address.get());
    } else if (ishex(params[0].get_str())) {
        std::vector<unsigned char> data(parsehex(params[0].get_str()));
        script = cscript(data.begin(), data.end());
    } else {
        throw jsonrpcerror(rpc_invalid_address_or_key, "invalid moorecoin address or script");
    }

    string strlabel = "";
    if (params.size() > 1)
        strlabel = params[1].get_str();

    // whether to perform rescan after import
    bool frescan = true;
    if (params.size() > 2)
        frescan = params[2].get_bool();

    {
        if (::ismine(*pwalletmain, script) == ismine_spendable)
            throw jsonrpcerror(rpc_wallet_error, "the wallet already contains the private key for this address or script");

        // add to address book or update label
        if (address.isvalid())
            pwalletmain->setaddressbook(address.get(), strlabel, "receive");

        // don't throw error in case an address is already there
        if (pwalletmain->havewatchonly(script))
            return nullunivalue;

        pwalletmain->markdirty();

        if (!pwalletmain->addwatchonly(script))
            throw jsonrpcerror(rpc_wallet_error, "error adding address to wallet");

        if (frescan)
        {
            pwalletmain->scanforwallettransactions(chainactive.genesis(), true);
            pwalletmain->reacceptwallettransactions();
        }
    }

    return nullunivalue;
}

univalue importwallet(const univalue& params, bool fhelp)
{
    if (!ensurewalletisavailable(fhelp))
        return nullunivalue;

    if (fhelp || params.size() != 1)
        throw runtime_error(
            "importwallet \"filename\"\n"
            "\nimports keys from a wallet dump file (see dumpwallet).\n"
            "\narguments:\n"
            "1. \"filename\"    (string, required) the wallet file\n"
            "\nexamples:\n"
            "\ndump the wallet\n"
            + helpexamplecli("dumpwallet", "\"test\"") +
            "\nimport the wallet\n"
            + helpexamplecli("importwallet", "\"test\"") +
            "\nimport using the json rpc call\n"
            + helpexamplerpc("importwallet", "\"test\"")
        );

    if (fprunemode)
        throw jsonrpcerror(rpc_wallet_error, "importing wallets is disabled in pruned mode");

    lock2(cs_main, pwalletmain->cs_wallet);

    ensurewalletisunlocked();

    ifstream file;
    file.open(params[0].get_str().c_str(), std::ios::in | std::ios::ate);
    if (!file.is_open())
        throw jsonrpcerror(rpc_invalid_parameter, "cannot open wallet dump file");

    int64_t ntimebegin = chainactive.tip()->getblocktime();

    bool fgood = true;

    int64_t nfilesize = std::max((int64_t)1, (int64_t)file.tellg());
    file.seekg(0, file.beg);

    pwalletmain->showprogress(_("importing..."), 0); // show progress dialog in gui
    while (file.good()) {
        pwalletmain->showprogress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nfilesize) * 100))));
        std::string line;
        std::getline(file, line);
        if (line.empty() || line[0] == '#')
            continue;

        std::vector<std::string> vstr;
        boost::split(vstr, line, boost::is_any_of(" "));
        if (vstr.size() < 2)
            continue;
        cmoorecoinsecret vchsecret;
        if (!vchsecret.setstring(vstr[0]))
            continue;
        ckey key = vchsecret.getkey();
        cpubkey pubkey = key.getpubkey();
        assert(key.verifypubkey(pubkey));
        ckeyid keyid = pubkey.getid();
        if (pwalletmain->havekey(keyid)) {
            logprintf("skipping import of %s (key already present)\n", cmoorecoinaddress(keyid).tostring());
            continue;
        }
        int64_t ntime = decodedumptime(vstr[1]);
        std::string strlabel;
        bool flabel = true;
        for (unsigned int nstr = 2; nstr < vstr.size(); nstr++) {
            if (boost::algorithm::starts_with(vstr[nstr], "#"))
                break;
            if (vstr[nstr] == "change=1")
                flabel = false;
            if (vstr[nstr] == "reserve=1")
                flabel = false;
            if (boost::algorithm::starts_with(vstr[nstr], "label=")) {
                strlabel = decodedumpstring(vstr[nstr].substr(6));
                flabel = true;
            }
        }
        logprintf("importing %s...\n", cmoorecoinaddress(keyid).tostring());
        if (!pwalletmain->addkeypubkey(key, pubkey)) {
            fgood = false;
            continue;
        }
        pwalletmain->mapkeymetadata[keyid].ncreatetime = ntime;
        if (flabel)
            pwalletmain->setaddressbook(keyid, strlabel, "receive");
        ntimebegin = std::min(ntimebegin, ntime);
    }
    file.close();
    pwalletmain->showprogress("", 100); // hide progress dialog in gui

    cblockindex *pindex = chainactive.tip();
    while (pindex && pindex->pprev && pindex->getblocktime() > ntimebegin - 7200)
        pindex = pindex->pprev;

    if (!pwalletmain->ntimefirstkey || ntimebegin < pwalletmain->ntimefirstkey)
        pwalletmain->ntimefirstkey = ntimebegin;

    logprintf("rescanning last %i blocks\n", chainactive.height() - pindex->nheight + 1);
    pwalletmain->scanforwallettransactions(pindex);
    pwalletmain->markdirty();

    if (!fgood)
        throw jsonrpcerror(rpc_wallet_error, "error adding some keys to wallet");

    return nullunivalue;
}

univalue dumpprivkey(const univalue& params, bool fhelp)
{
    if (!ensurewalletisavailable(fhelp))
        return nullunivalue;

    if (fhelp || params.size() != 1)
        throw runtime_error(
            "dumpprivkey \"moorecoinaddress\"\n"
            "\nreveals the private key corresponding to 'moorecoinaddress'.\n"
            "then the importprivkey can be used with this output\n"
            "\narguments:\n"
            "1. \"moorecoinaddress\"   (string, required) the moorecoin address for the private key\n"
            "\nresult:\n"
            "\"key\"                (string) the private key\n"
            "\nexamples:\n"
            + helpexamplecli("dumpprivkey", "\"myaddress\"")
            + helpexamplecli("importprivkey", "\"mykey\"")
            + helpexamplerpc("dumpprivkey", "\"myaddress\"")
        );

    lock2(cs_main, pwalletmain->cs_wallet);

    ensurewalletisunlocked();

    string straddress = params[0].get_str();
    cmoorecoinaddress address;
    if (!address.setstring(straddress))
        throw jsonrpcerror(rpc_invalid_address_or_key, "invalid moorecoin address");
    ckeyid keyid;
    if (!address.getkeyid(keyid))
        throw jsonrpcerror(rpc_type_error, "address does not refer to a key");
    ckey vchsecret;
    if (!pwalletmain->getkey(keyid, vchsecret))
        throw jsonrpcerror(rpc_wallet_error, "private key for address " + straddress + " is not known");
    return cmoorecoinsecret(vchsecret).tostring();
}

univalue dumpwallet(const univalue& params, bool fhelp)
{
    if (!ensurewalletisavailable(fhelp))
        return nullunivalue;

    if (fhelp || params.size() != 1)
        throw runtime_error(
            "dumpwallet \"filename\"\n"
            "\ndumps all wallet keys in a human-readable format.\n"
            "\narguments:\n"
            "1. \"filename\"    (string, required) the filename\n"
            "\nexamples:\n"
            + helpexamplecli("dumpwallet", "\"test\"")
            + helpexamplerpc("dumpwallet", "\"test\"")
        );

    lock2(cs_main, pwalletmain->cs_wallet);

    ensurewalletisunlocked();

    ofstream file;
    file.open(params[0].get_str().c_str());
    if (!file.is_open())
        throw jsonrpcerror(rpc_invalid_parameter, "cannot open wallet dump file");

    std::map<ckeyid, int64_t> mapkeybirth;
    std::set<ckeyid> setkeypool;
    pwalletmain->getkeybirthtimes(mapkeybirth);
    pwalletmain->getallreservekeys(setkeypool);

    // sort time/key pairs
    std::vector<std::pair<int64_t, ckeyid> > vkeybirth;
    for (std::map<ckeyid, int64_t>::const_iterator it = mapkeybirth.begin(); it != mapkeybirth.end(); it++) {
        vkeybirth.push_back(std::make_pair(it->second, it->first));
    }
    mapkeybirth.clear();
    std::sort(vkeybirth.begin(), vkeybirth.end());

    // produce output
    file << strprintf("# wallet dump created by moorecoin %s (%s)\n", client_build, client_date);
    file << strprintf("# * created on %s\n", encodedumptime(gettime()));
    file << strprintf("# * best block at time of backup was %i (%s),\n", chainactive.height(), chainactive.tip()->getblockhash().tostring());
    file << strprintf("#   mined on %s\n", encodedumptime(chainactive.tip()->getblocktime()));
    file << "\n";
    for (std::vector<std::pair<int64_t, ckeyid> >::const_iterator it = vkeybirth.begin(); it != vkeybirth.end(); it++) {
        const ckeyid &keyid = it->second;
        std::string strtime = encodedumptime(it->first);
        std::string straddr = cmoorecoinaddress(keyid).tostring();
        ckey key;
        if (pwalletmain->getkey(keyid, key)) {
            if (pwalletmain->mapaddressbook.count(keyid)) {
                file << strprintf("%s %s label=%s # addr=%s\n", cmoorecoinsecret(key).tostring(), strtime, encodedumpstring(pwalletmain->mapaddressbook[keyid].name), straddr);
            } else if (setkeypool.count(keyid)) {
                file << strprintf("%s %s reserve=1 # addr=%s\n", cmoorecoinsecret(key).tostring(), strtime, straddr);
            } else {
                file << strprintf("%s %s change=1 # addr=%s\n", cmoorecoinsecret(key).tostring(), strtime, straddr);
            }
        }
    }
    file << "\n";
    file << "# end of dump\n";
    file.close();
    return nullunivalue;
}

max_stars_repo_name: moorecoin/MooreCoinMiningAlgorithm

max_issues_repo_name: moorecoin/MooreCoinMiningAlgorithm

max_forks_repo_name: moorecoin/MooreCoinMiningAlgorithm


text:
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
                                       http://flusspferd.org/contributors.txt)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "flusspferd/load_core.hpp"
#include "flusspferd/modules.hpp"
#include "flusspferd/evaluate.hpp"
#include "flusspferd/properties_functions.hpp"
#include "flusspferd/binary.hpp"
#include "flusspferd/encodings.hpp"
#include "flusspferd/system.hpp"
#include "flusspferd/getopt.hpp"
#include "flusspferd/io/io.hpp"
#include "flusspferd/io/filesystem-base.hpp"
#include "flusspferd/create.hpp"
#include <boost/filesystem.hpp>
#include <boost/spirit/include/phoenix.hpp>

namespace phoenix = boost::phoenix;
namespace args = phoenix::arg_names;

using namespace flusspferd;
using namespace flusspferd::param;

void flusspferd::load_core(object const &scope_, std::string const &argv0) {
  root_object scope(scope_);

  // Initalize boost's copy of cwd as early as possible
  boost::filesystem::path pwd = boost::filesystem::initial_path<boost::filesystem::path>();

  flusspferd::load_require_function(scope);

  flusspferd::load_properties_functions(scope);

  flusspferd::object require_fn = scope.get_property_object("require");
  flusspferd::require &require = flusspferd::get_native<flusspferd::require>(require_fn);

  root_object preload(require_fn.get_property_object("preload"));

  // Create the top level |module| and |exports| properties.
  scope.define_property("module", require_fn.get_property("main"), dont_enumerate);

  root_object exports(create<object>());
  scope.define_property("exports", exports, dont_enumerate);

  // Set the main.id to *something* so we always have properties.
  require.set_main_module( "file://" + (pwd / "<typein>").string() );

  flusspferd::create<method>(
    "binary",
    &flusspferd::load_binary_module,
    _container = preload);

  flusspferd::create<method>(
    "encodings",
    &flusspferd::load_encodings_module,
    _container = preload);

  flusspferd::create<method>(
    "io",
    &flusspferd::io::load_io_module,
    _container = preload);

  flusspferd::create<method>(
    "system",
    &flusspferd::load_system_module,
    _container = preload);

  flusspferd::create<method>(
    "getopt",
    &flusspferd::load_getopt_module,
    _container = preload);

  flusspferd::create<method>(
    "filesystem-base",
    &flusspferd::load_filesystem_base_module,
    _container = preload);
  // alias fs-base -> filesystem-base
  require_fn.get_property_object("alias").set_property("fs-base", "filesystem-base");

  // Curry argv[0] into the preload function
  flusspferd::create<method>(
    "flusspferd",
    phoenix::bind(&flusspferd::load_flusspferd_module, args::arg1, argv0),
    _signature = param::type<void (object)>(),
    _container = preload);
}

max_stars_repo_name: Flusspferd/flusspferd

max_issues_repo_name: Flusspferd/flusspferd

max_forks_repo_name: Flusspferd/flusspferd


text:
#ifndef LWTNN_EIGEN_TYPEDEFS_HH
#define LWTNN_EIGEN_TYPEDEFS_HH

#include <Eigen/Dense>

namespace lwt {

  template<typename T>
  using VectorX = Eigen::Matrix<T, Eigen::Dynamic, 1>;

  template<typename T>
  using MatrixX = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;

  template<typename T>
  using ArrayX = Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic>;

}

#endif // LWTNN_EIGEN_TYPEDEFS_HH

ext: hh

max_stars_repo_name: ishine/lwtnn

max_issues_repo_name: ishine/lwtnn

max_forks_repo_name: ishine/lwtnn


text:
/*
Copyright 2017 Houzz, 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 "path_walker.h"
#include "parser/ast_builder.h"
#include "ast/statement_list.h"
#include "visitor/signature_scanner.h"
#include "visitor/expression_visitor.h"
#include "visitor/full_analyzer.h"
#include "config.h"
#include "util/tap_context.h"
#include "entity/class_repo.h"
#include "entity/const_alias.h"
#include "util/error_collector.h"
#include "db/db.h"
#include <boost/filesystem.hpp>
#include <glog/logging.h>

namespace fs = boost::filesystem;
using HPHP::Scanner;
using HPHP::Compiler::Parser;

namespace Tap {

bool isValidPHP(const std::string &filename) {
  std::string suffix = ".php";
  if (filename.length() < suffix.length() ||
    filename.compare(filename.length() - suffix.length(), suffix.length(), suffix) != 0)
      return false;
  return true;
}

void scanSingleFile(const std::string& filename) {
  if (!isValidPHP(filename)) return;
  LOG(INFO) << "Trying to scan the signature of " << filename;
  Tap::TapContext::getInstance().setCurrentFilename(filename);

  Scanner* scanner = new Scanner(filename, 1);
  Parser* parser = new Parser(*scanner, filename.c_str());
  parser->initParseTree();
  bool result = parser->parse();
  if (!result) printf("parse failed.\n");

  HPHP::StatementListPtr tree = parser->getTree();

  Tap::SignatureScanner* sigScanner = new Tap::SignatureScanner();
  tree->accept(*sigScanner);
  LOG(INFO) << "Done scanning the signature of " << filename;
  delete scanner;
  delete parser;
  delete sigScanner;
}

void analyzeSingleFile(const std::string& filename) {
  if (!isValidPHP(filename)) return;
  LOG(INFO) << "Trying to full analyze " << filename;
  Tap::TapContext::getInstance().setCurrentFilename(filename);
  Scanner* scanner = new Scanner(filename, 1);
  Parser* parser = new Parser(*scanner, filename.c_str());
  parser->initParseTree();
  bool result = parser->parse();
  if (!result) printf("parse failed.\n");

  HPHP::StatementListPtr tree = parser->getTree();
  Tap::FullAnalyzer* analyzer = new Tap::FullAnalyzer();
  tree->simpleAccept(*analyzer);
  LOG(INFO) << "Done full analyzing " << filename;
  delete scanner;
  delete parser;
  delete analyzer;
}

void PathWalker::addFile(const std::string& filename) {
  scanSingleFile(filename);
  analyzeSingleFile(filename);
}

void PathWalker::removeFile(const std::string& filename) {
  ClassRepo::getInstance().removeFile(filename);
  DB::getInstance().clearFileError(filename);
}

void PathWalker::updateFile(const std::string& filename) {
  removeFile(filename);
  addFile(filename);
}

void PathWalker::start() {
  LOG(ERROR) << "before sig scan";
  Tap::TapContext::getInstance().setPassNo(1);
  fs::recursive_directory_iterator it(m_config.getSourceRoot()), eod;
  while (it != eod) {
    fs::path p = it->path();
    if (is_directory(p)) {
      if (m_config.shouldSkip(p.string())) {
        it.no_push();
      }
    } else if (is_regular_file(p)) {
      scanSingleFile(p.native());
    }
    ++it;
  }
  LOG(ERROR) << "start expanding";
  Tap::ClassRepo::getInstance().expandClasses();
  LOG(ERROR) << "start resolving";
  Tap::ConstAlias::getInstance().resolve();
  LOG(ERROR) << "finish resolving";
  Tap::TapContext::getInstance().setPassNo(2);
  /*
  if (!filename.empty()) {
    // scan whole directory, for analyze only one file
    // mostly for debugging
    Tap::TapContext::getInstance().setEmitterEnabled(true);
    analyzeSingleFile(filename);
    return;
  }
  */
  { // full analyze
    fs::recursive_directory_iterator it(m_config.getSourceRoot()), eod;
    while (it != eod) {
      fs::path p = it->path();
      if (is_directory(p)) {
        if (m_config.shouldSkip(p.string()) || m_config.shouldScanOnly(p.string())) {
          it.no_push();
        }
      } else if (is_regular_file(p)) {
        analyzeSingleFile(p.native());
      }
      ++it;
    }
  }
}

void PathWalker::handleSingleFile(const std::string& filename) {
  Tap::TapContext::getInstance().setPassNo(1);
  scanSingleFile(filename);
  LOG(INFO) << "start expanding";
  Tap::ClassRepo::getInstance().expandClasses();
  LOG(INFO) << "start resolving";
  Tap::ConstAlias::getInstance().resolve();
  LOG(INFO) << "finish resolving";
  Tap::TapContext::getInstance().setPassNo(2);
  analyzeSingleFile(filename);
}

}

max_stars_repo_name: Houzz/tap

max_issues_repo_name: Houzz/tap

max_forks_repo_name: Houzz/tap


text:
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_UNITS_TIME_BASE_DIMENSION_HPP
#define BOOST_UNITS_TIME_BASE_DIMENSION_HPP

#include <boost/units/config.hpp>
#include <boost/units/base_dimension.hpp>

namespace boost {

namespace units {

/// base dimension of time
struct time_base_dimension :
    boost::units::base_dimension<time_base_dimension,-7>
{ };

} // namespace units

} // namespace boost

#if BOOST_UNITS_HAS_BOOST_TYPEOF

#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()

BOOST_TYPEOF_REGISTER_TYPE(boost::units::time_base_dimension)

#endif

namespace boost {

namespace units {

/// dimension of time (T)
typedef time_base_dimension::dimension_type time_dimension;

} // namespace units

} // namespace boost

#endif // BOOST_UNITS_TIME_BASE_DIMENSION_HPP

ext: hpp

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
//--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//--------------------------------------------------------------------------
#include "CommBasicObjects/CommNavigationVelocityCore.hh"

// serialization/deserialization operators
//#include "CommBasicObjects/CommNavigationVelocityACE.hh"

// include the hash.idl containing the hash constant
#include "hash.hh"
#include <assert.h>
#include <cstring>
#include <iostream>

// SmartUtils used in from_xml method
#include "smartKnuthMorrisPratt.hh"

#ifdef ENABLE_HASH
	#include <boost/functional/hash.hpp>
#endif

namespace CommBasicObjects
{
	const char* CommNavigationVelocityCore::getCompiledHash()
	{
		return CommBasicObjectsIDL::REPO_HASH;
	}

	void CommNavigationVelocityCore::getAllHashValues(std::list<std::string> &hashes)
	{
		// get own hash value
		hashes.push_back(getCompiledHash());
	}

	void CommNavigationVelocityCore::checkAllHashValues(std::list<std::string> &hashes)
	{
		// check own hash value
		if (strcmp(getCompiledHash(), hashes.front().c_str()) != 0)
		{
			std::cerr << "###################################################" << std::endl;
			std::cerr << "WARNING: HASHES OF COMMUNICATION OBJECTS MISSMATCH!" << std::endl;
			std::cerr << "CommNavigationVelocityCore hash" << std::endl;
			std::cerr << "Expected: " << getCompiledHash() << std::endl;
			std::cerr << "Received: " << hashes.front() << std::endl;
			std::cerr << "###################################################" << std::endl;
		}
		assert(strcmp(getCompiledHash(), hashes.front().c_str()) == 0);
		hashes.pop_front();

	}

	#ifdef ENABLE_HASH
	size_t CommNavigationVelocityCore::generateDataHash(const DATATYPE &data)
	{
		size_t seed = 0;

		boost::hash_combine(seed, data.vX);
		boost::hash_combine(seed, data.vY);
		boost::hash_combine(seed, data.vZ);
		boost::hash_combine(seed, data.omega);

		return seed;
	}
	#endif

	// default constructor
	CommNavigationVelocityCore::CommNavigationVelocityCore()
	:	idl_CommNavigationVelocity()
	{
		setVX(0.0);
		setVY(0.0);
		setVZ(0.0);
		setOmega(0.0);
	}

	CommNavigationVelocityCore::CommNavigationVelocityCore(const DATATYPE &data)
	:	idl_CommNavigationVelocity(data)
	{  }

	CommNavigationVelocityCore::~CommNavigationVelocityCore()
	{  }

	void CommNavigationVelocityCore::to_ostream(std::ostream &os) const
	{
	  os << "CommNavigationVelocity(";
	  os << getVX() << " ";
	  os << getVY() << " ";
	  os << getVZ() << " ";
	  os << getOmega() << " ";
	  os << ") ";
	}

	// convert to xml stream
	void CommNavigationVelocityCore::to_xml(std::ostream &os, const std::string &indent) const {
		os << indent << "<vX>" << getVX() << "</vX>";
		os << indent << "<vY>" << getVY() << "</vY>";
		os << indent << "<vZ>" << getVZ() << "</vZ>";
		os << indent << "<omega>" << getOmega() << "</omega>";
	}

	// restore from xml stream
	void CommNavigationVelocityCore::from_xml(std::istream &is) {
		static const Smart::KnuthMorrisPratt kmp_vX("<vX>");
		static const Smart::KnuthMorrisPratt kmp_vY("<vY>");
		static const Smart::KnuthMorrisPratt kmp_vZ("<vZ>");
		static const Smart::KnuthMorrisPratt kmp_omega("<omega>");

		if(kmp_vX.search(is)) {
			double vXItem;
			is >> vXItem;
			setVX(vXItem);
		}
		if(kmp_vY.search(is)) {
			double vYItem;
			is >> vYItem;
			setVY(vYItem);
		}
		if(kmp_vZ.search(is)) {
			double vZItem;
			is >> vZItem;
			setVZ(vZItem);
		}
		if(kmp_omega.search(is)) {
			double omegaItem;
			is >> omegaItem;
			setOmega(omegaItem);
		}
	}

	/*
	void CommNavigationVelocityCore::get(ACE_Message_Block *&msg) const
	{
		// start with a default internal buffer size(will automatically grow if needed)
		ACE_OutputCDR cdr(ACE_DEFAULT_CDR_BUFSIZE);

		CommBasicObjectsIDL::HashList hashes;
		getAllHashValues(hashes);
		cdr << static_cast<ACE_CDR::Long>(hashes.size());
		for(CommBasicObjectsIDL::HashList::const_iterator it=hashes.begin(); it!=hashes.end(); it++)
		{
			cdr << ACE_CString(it->c_str());
		}

		// Here the actual serialization takes place using the OutputCDR serialization operator<<
		// (see CommNavigationVelocityACE.hh)
		cdr << idl_CommNavigationVelocity;

	#ifdef ENABLE_HASH
		ACE_CDR::ULong data_hash = generateDataHash(idl_CommNavigationVelocity);
		cdr << data_hash;
		// std::cout << "CommNavigationVelocityCore: current data hash: " << data_hash << std::endl;
	#endif

		// return a shallow copy of the serialized message
		// (no data is actually copied, only the internal reference counter is incremented)
		// in order to prevent memory leaks the caller of this get(msg) method must
		// manually free the memory by calling the release() method of the message block msg
		msg = cdr.begin()->duplicate();
	}

	void CommNavigationVelocityCore::set(const ACE_Message_Block *msg)
	{
		ACE_InputCDR cdr(msg);

		CommBasicObjectsIDL::HashList hashes;
		ACE_CDR::Long hashes_size;
		cdr >> hashes_size;
		for(int i=0; i<hashes_size; ++i)
		{
			ACE_CString hash;
			cdr >> hash;
			hashes.push_back(hash.c_str());
		}
		checkAllHashValues(hashes);

		// Here the actual de-serialization takes place using the InputCDR serialization operator>>
		// (see CommNavigationVelocityACE.hh)
		cdr >> idl_CommNavigationVelocity;

	#ifdef ENABLE_HASH
		ACE_CDR::Long data_hash;
		cdr >> data_hash;
		ACE_CDR::Long own_hash = generateDataHash(idl_CommNavigationVelocity);
		assert(data_hash == own_hash);
		// std::cout << "CommNavigationVelocityCore: own data hash: " << own_hash << "; received data hash: " << data_hash << std::endl;
	#endif
	}
	*/
} /* namespace CommBasicObjects */

ext: cc

max_stars_repo_name: skarvtech/DomainModelsRepositories

max_issues_repo_name: skarvtech/DomainModelsRepositories

max_forks_repo_name: skarvtech/DomainModelsRepositories


text:
//[ editor_main
#include "app_state.hpp"
#include "curses_interface.hpp"

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>

#include <iostream>

int main(int argc, char * argv[])
{
    if (argc < 2) {
        std::cerr << "error: You must supply at least a filename.\n";
        return 1;
    }

    boost::filesystem::path path(argv[1]);
    if (!exists(path)) {
        std::cerr << "error: Could not access filename " << argv[1] << ".\n";
        return 1;
    }

    // Requirement of libcurses.
    std::locale::global(std::locale(""));

    curses_interface_t curses_interface;

    // Read the size, but just this once; resizing is not supported.
    auto const screen_size = curses_interface.screen_size();

    app_state_t app_state = {
        // Initial state is the contents of the file from the command line.
        load_buffer(path, curses_interface.screen_size().col_),
        // Keybindings are simplified Emacs.
        emacs_lite()};
    // Initial render.
    render(app_state.buffer_, screen_size);

    // Loop until the user says we're done.  Each iteration blocks for an
    // event from libcurses, then passes the current app state and the event
    // to update(), which returns the new app state.
    boost::optional<app_state_t> next_app_state;
    while (
        (next_app_state =
             update(std::move(app_state), curses_interface.next_event()))) {
        app_state = *next_app_state;
        render(app_state.buffer_, screen_size);
    }
}
//]

max_stars_repo_name: eightysquirrels/text

max_issues_repo_name: eightysquirrels/text

max_forks_repo_name: eightysquirrels/text


text:
#ifndef PYOSMIUM_MERGED_INPUT_HPP
#define PYOSMIUM_MERGED_INPUT_HPP

#include <vector>

#include <boost/function_output_iterator.hpp>

#include <osmium/osm/object_comparisons.hpp>
#include <osmium/io/any_input.hpp>
#include <osmium/io/any_output.hpp>
#include <osmium/io/output_iterator.hpp>
#include <osmium/handler.hpp>
#include <osmium/handler/node_locations_for_ways.hpp>
#include <osmium/index/map/all.hpp>
#include <osmium/object_pointer_collection.hpp>
#include <osmium/visitor.hpp>

#include <boost/python.hpp>

namespace {

    /**
     *  Copy the first OSM object with a given Id to the output. Keep
     *  track of the Id of each object to do this.
     *
     *  We are using this functor class instead of a simple lambda, because the
     *  lambda doesn't build on MSVC.
     */
    class copy_first_with_id {
        osmium::io::Writer* writer;
        osmium::object_id_type id = 0;

    public:
        explicit copy_first_with_id(osmium::io::Writer& w) :
            writer(&w) {
        }

        void operator()(const osmium::OSMObject& obj) {
            if (obj.id() != id) {
                if (obj.visible()) {
                    (*writer)(obj);
                }
                id = obj.id();
            }
        }

    };

} // anonymous namespace

namespace pyosmium {

class MergeInputReader {
    void apply_without_location(BaseHandler& handler, bool simplify = true) {
        handler.apply_start();
        if (simplify) {
            objects.sort(osmium::object_order_type_id_reverse_version());
            osmium::item_type prev_type = osmium::item_type::undefined;
            osmium::object_id_type prev_id = 0;
            for (const auto &item: objects) {
                if (item.type() != prev_type || item.id() != prev_id) {
                    prev_type = item.type();
                    prev_id = item.id();
                    osmium::apply_item(item, handler);
                }
            }
        } else {
            objects.sort(osmium::object_order_type_id_version());
            osmium::apply(objects.cbegin(), objects.cend(), handler);
        }

        objects = osmium::ObjectPointerCollection();
        changes.clear();
    }

    void apply_with_location(BaseHandler& handler, const std::string &idx,
                             bool simplify = true) {
        const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance();
        std::unique_ptr<index_type> index = map_factory.create_map(idx);
        osmium::handler::NodeLocationsForWays<index_type> location_handler(*index);
        location_handler.ignore_errors();

        handler.apply_start();
        if (simplify) {
            objects.sort(osmium::object_order_type_id_reverse_version());
            osmium::item_type prev_type = osmium::item_type::undefined;
            osmium::object_id_type prev_id = 0;
            for (auto &item: objects) {
                if (item.type() != prev_type || item.id() != prev_id) {
                    prev_type = item.type();
                    prev_id = item.id();
                    osmium::apply_item(item, location_handler, handler);
                }
            }
        } else {
            objects.sort(osmium::object_order_type_id_version());
            osmium::apply(objects.begin(), objects.end(), location_handler, handler);
        }

        objects = osmium::ObjectPointerCollection();
        changes.clear();
    }

public:
    void apply(BaseHandler& handler, const std::string &idx = "",
               bool simplify = true) {
        if (idx.empty())
            apply_without_location(handler, simplify);
        else
            apply_with_location(handler, idx, simplify);
    }

    void apply_to_reader(osmium::io::Reader &reader, osmium::io::Writer &writer,
                         bool with_history = true) {
        auto input = osmium::io::make_input_iterator_range<osmium::OSMObject>(reader);
        if (with_history) {
            // For history files this is a straightforward sort of the change
            // files followed by a merge with the input file.
            objects.sort(osmium::object_order_type_id_version());

            auto out = osmium::io::make_output_iterator(writer);
            std::set_union(objects.begin(),
                    objects.end(),
                    input.begin(),
                    input.end(),
                    out);
        } else {
            // For normal data files we sort with the largest version of each
            // object first and then only copy this last version of any object
            // to the output.
            objects.sort(osmium::object_order_type_id_reverse_version());

            auto output_it = boost::make_function_output_iterator(
                    copy_first_with_id(writer)
                    );

            std::set_union(objects.begin(),
                    objects.end(),
                    input.begin(),
                    input.end(),
                    output_it,
                    osmium::object_order_type_id_reverse_version());
        }
    }

    size_t add_file(const std::string &filename) {
        return internal_add(osmium::io::File(filename));
    }

    size_t add_buffer(const boost::python::object &buf,
                      const boost::python::str &format) {
        Py_buffer pybuf;
        PyObject_GetBuffer(buf.ptr(), &pybuf, PyBUF_C_CONTIGUOUS);
        size_t len = (size_t) pybuf.len;
        const char *cbuf = reinterpret_cast<const char *>(pybuf.buf);
        const char *cfmt = boost::python::extract<const char *>(format);

        return internal_add(osmium::io::File(cbuf, len, cfmt));
    }

private:
    size_t internal_add(osmium::io::File change_file) {
        size_t sz = 0;
        osmium::io::Reader reader(change_file, osmium::osm_entity_bits::object);
        while (osmium::memory::Buffer buffer = reader.read()) {
            osmium::apply(buffer, objects);
            sz += buffer.committed();
            changes.push_back(std::move(buffer));
        }

        return sz;
    }

    std::vector<osmium::memory::Buffer> changes;
    osmium::ObjectPointerCollection objects;
};

}

#endif /* PYOSMIUM_MERGED_INPUT_HPP */

max_stars_repo_name: adamfranco/pyosmium

max_issues_repo_name: adamfranco/pyosmium

max_forks_repo_name: adamfranco/pyosmium