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

#include <cctbx/xray/twin_targets.h>

#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python/class.hpp>
#include <boost/python/args.hpp>
#include <boost/python/tuple.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/copy_const_reference.hpp>
#include <scitbx/boost_python/is_polymorphic_workaround.h>

SCITBX_BOOST_IS_POLYMORPHIC_WORKAROUND(
  cctbx::xray::twin_targets::single_twin_likelihood<double>)

namespace cctbx { namespace xray { namespace twin_targets { namespace boost_python {
  namespace {

    struct twin_completion_wrappers
    {
      typedef twin_completion<double> w_t;
      static void
      wrap()
      {
        using namespace boost::python;

        class_<w_t>("twin_completion", no_init)
          .def(init< scitbx::af::const_ref< cctbx::miller::index<> > const&,
                     sgtbx::space_group const&,
                     bool const&,
                     scitbx::mat3<double> const& >
               (( arg("hkl"),
                  arg("space_group"),
                  arg("anomalous_flag"),
                  arg("twin_law") )))
          .def("twin_complete", &w_t::twin_complete )
          .def("check_free_flags", &w_t::check_free_flags)
          .def("get_free_model_selection", &w_t::get_free_model_selection)
          .def("twin_sum", &w_t::twin_sum)
          ;
      }

    };

    struct least_squares_hemihedral_twinning_on_i_wrappers
    {
      typedef least_squares_hemihedral_twinning_on_i<double> w_t;

      // A thin wrapper that wraps up the derivatives
      static boost::python::tuple
      d_target_d_ab(w_t const& self, scitbx::af::const_ref<std::complex<double> > const& f_model)
      {
        scitbx::af::tiny<scitbx::af::shared<double>, 2> result;
        result = self.d_target_d_ab( f_model );
        return boost::python::make_tuple( result[0], result[1] );
      }

      static void
      wrap()
      {
        using namespace boost::python;

        class_<w_t>("least_squares_hemihedral_twinning_on_i", no_init)
          .def(init<
               scitbx::af::const_ref< cctbx::miller::index<> > const&,  // 1 indices
               scitbx::af::const_ref< double > const&,                  // 2 i_obs
               scitbx::af::const_ref< double > const&,                  // 3 w_obs
               scitbx::af::const_ref< cctbx::miller::index<> > const&,  // 4 hl_obs
               sgtbx::space_group const&,                               // 5 space group
               bool const&,                                             // 6 anomalous flag
               double const&,                                           // 7 alpha
               scitbx::mat3<double> const&                              // 8 twin law)
               >
               ((arg("hkl_obs"),
                 arg("i_obs"),
                 arg("w_obs"),
                 arg("hkl_calc"),
                 arg("space_group"),
                 arg("anomalous_flag"),
                 arg("alpha"),
                 arg("twin_law")
                 )))
          .def("target", &w_t::target)
          .def("d_target_d_ab", d_target_d_ab )
          .def("d_target_d_fmodel", &w_t::d_target_d_fmodel)
          .def("d_target_d_alpha", &w_t::d_target_d_alpha )
          .def("alpha", (void(w_t::*)(double)) &w_t::alpha)
          .def("alpha", (double(w_t::*)()) &w_t::alpha)
          .def("set_weights", &w_t::set_weights)
          ;
      }
    };

    struct least_squares_hemihedral_twinning_on_f_wrappers
    {
      typedef least_squares_hemihedral_twinning_on_f<double> w_t;

      // A thin wrapper that wraps up the derivatives
      static boost::python::tuple
      d_target_d_ab(w_t const& self, scitbx::af::const_ref<std::complex<double> > const& f_model)
      {
        scitbx::af::tiny<scitbx::af::shared<double>, 2> result;
        result = self.d_target_d_ab( f_model );
        return boost::python::make_tuple( result[0], result[1] );
      }

      static void
      wrap()
      {
        using namespace boost::python;

        class_<w_t>("least_squares_hemihedral_twinning_on_f", no_init)
          .def(init<
               scitbx::af::const_ref< cctbx::miller::index<> > const&,  // 1 indices
               scitbx::af::const_ref< double > const&,                  // 2 i_obs
               scitbx::af::const_ref< double > const&,                  // 3 w_obs
               scitbx::af::const_ref< cctbx::miller::index<> > const&,  // 4 hl_obs
               sgtbx::space_group const&,                               // 5 space group
               bool const&,                                             // 6 anomalous flag
               double const&,                                           // 7 alpha
               scitbx::mat3<double> const&                              // 8 twin law)
               >
               ((arg("hkl_obs"),
                 arg("f_obs"),
                 arg("w_obs"),
                 arg("hkl_calc"),
                 arg("space_group"),
                 arg("anomalous_flag"),
                 arg("alpha"),
                 arg("twin_law")
                 )))
          .def("target", &w_t::target)
          .def("d_target_d_ab", d_target_d_ab )
          .def("d_target_d_fmodel", &w_t::d_target_d_fmodel)
          .def("d_target_d_alpha", &w_t::d_target_d_alpha )
          .def("alpha", (void(w_t::*)(double)) &w_t::alpha)
          .def("alpha", (double(w_t::*)()) &w_t::alpha)
          .def("set_weights", &w_t::set_weights)
          ;
      }
    };

    struct hemihedral_r_values_wrappers
    {
      typedef hemihedral_r_values<double> w_t;

      static void
      wrap()
      {
        using namespace boost::python;
        class_<w_t>("hemihedral_r_values", no_init)
        .def(init<
             scitbx::af::const_ref< cctbx::miller::index<> > const&,   // 1 obs indices
             scitbx::af::const_ref< cctbx::miller::index<> > const&,   // 2 calc indices
             sgtbx::space_group const&,                                // 3 space group
             bool const&,                                              // 4 anomalous flag
             scitbx::mat3<double> const&                               // 5 twin law
             >
             ((arg("hkl_obs"),
               arg("hkl_calc"),
               arg("space_group"),
               arg("anomalous_flag"),
               arg("twin_law")
             )))
        .def("r_intensity_abs", &w_t::r_intensity_abs,
             ( arg("f_obs"),
               arg("f_model"),
               arg("selection"),
               arg("twin_fraction")
             )
            )
        .def("r_intensity_sq", &w_t::r_intensity_sq,
             ( arg("f_obs"),
               arg("f_model"),
               arg("selection"),
               arg("twin_fraction")
             )
            )
        .def("r_amplitude_abs", &w_t::r_amplitude_abs,
             ( arg("f_obs"),
               arg("f_model"),
               arg("selection"),
               arg("twin_fraction")
             )
            )
        .def("r_amplitude_sq", &w_t::r_amplitude_sq,
             ( arg("f_obs"),
               arg("f_model"),
               arg("selection"),
               arg("twin_fraction")
             )
            )

        ;
      }
    };

   struct hemihedral_detwinner_wrappers
   {
     typedef hemihedral_detwinner<double> w_t;

      static boost::python::tuple
      detwin_with_twin_fraction(w_t const& self,
                                scitbx::af::const_ref<double> const& i_obs,
                                scitbx::af::const_ref<double> const& sig_obs,
                                double const& twin_fraction)
      {
        scitbx::af::tiny<scitbx::af::shared<double>, 2> result;
        result = self.detwin_with_twin_fraction(i_obs,sig_obs,twin_fraction);
        return boost::python::make_tuple( result[0], result[1] );
      }

      static boost::python::tuple
      twin_with_twin_fraction(w_t const& self,
                                scitbx::af::const_ref<double> const& i_obs,
                                scitbx::af::const_ref<double> const& sig_obs,
                                double const& twin_fraction)
      {
        scitbx::af::tiny<scitbx::af::shared<double>, 2> result;
        result = self.twin_with_twin_fraction(i_obs,sig_obs,twin_fraction);
        return boost::python::make_tuple( result[0], result[1] );
      }

      static boost::python::tuple
      detwin_with_model_data(w_t const& self,
                             scitbx::af::const_ref<double> const& i_obs,
                             scitbx::af::const_ref<double> const& sig_obs,
                             scitbx::af::const_ref<std::complex<double> > const& f_model,
                             double const& twin_fraction)
      {
        scitbx::af::tiny<scitbx::af::shared<double>, 2> result;
        result = self.detwin_with_model_data(i_obs,sig_obs,f_model,twin_fraction);
        return boost::python::make_tuple( result[0], result[1] );
      }

      static boost::python::tuple
      detwin_with_abs_model_data(w_t const& self,
                             scitbx::af::const_ref<double> const& i_obs,
                             scitbx::af::const_ref<double> const& sig_obs,
                             scitbx::af::const_ref<double> const& f_model,
                             double const& twin_fraction)
      {
        scitbx::af::tiny<scitbx::af::shared<double>, 2> result;
        result = self.detwin_with_model_data(i_obs,sig_obs,f_model,twin_fraction);
        return boost::python::make_tuple( result[0], result[1] );
      }

     static void
     wrap()
     {
       using namespace boost::python;
       class_<w_t>("hemihedral_detwinner", no_init)
       .def(init< scitbx::af::const_ref< cctbx::miller::index<> > const&,   // 1 obs indices
                  scitbx::af::const_ref< cctbx::miller::index<> > const&,   // 2 calc indices
                  sgtbx::space_group const&,                                // 3 space group
                  bool const&,                                              // 4 anomalous flag
                  scitbx::mat3<double> const&                               // 5 twin law
                >
                ((arg("hkl_obs"),
                  arg("hkl_calc"),
                  arg("space_group"),
                  arg("anomalous_flag"),
                  arg("twin_law")
                )))

       .def("detwin_with_twin_fraction", detwin_with_twin_fraction,
             ( arg("i_obs"),
               arg("sigma_obs"),
               arg("twin_fraction")
             ) )

       .def("twin_with_twin_fraction", twin_with_twin_fraction,
             ( arg("i_obs"),
               arg("sigma_obs"),
               arg("twin_fraction")
             ) )

       .def("detwin_with_model_data", detwin_with_model_data,
             ( arg("i_obs"),
               arg("sigma_obs"),
               arg("f_model"),
               arg("twin_fraction")
             ) )

       .def("detwin_with_abs_model_data", detwin_with_abs_model_data,
             ( arg("i_obs"),
               arg("sigma_obs"),
               arg("f_model"),
               arg("twin_fraction")
             ) )
       .def("obs_to_twin_obs", &w_t::obs_to_twin_obs)

       .def("obs_to_calc", &w_t::obs_to_calc )

       .def("obs_to_twin_calc", &w_t::obs_to_twin_calc)

       .def("calc_to_twin_calc", &w_t::calc_to_twin_calc)

         ;
     }
   };

   struct single_twin_likelihood_wrappers
   {
     typedef single_twin_likelihood<double> w_t;
     static void wrap()
     {
       using namespace boost::python;
       class_<w_t>("single_twin_likelihood", no_init)
         .def(init<
              double const&, double const&,
              double const&, double const&,
              double const&, double const&,
              double const&, double const&,
              bool   const&, bool   const&,
              double const&, double const&,
              double const&, int    const&
              >
              ((arg("i_obs1"),  arg("s_obs1"),
                arg("i_obs2"),  arg("s_obs2"),
                arg("f_calc1"), arg("f_calc2"),
                arg("eps1"),    arg("eps2"),
                arg("centric1"),arg("centric2"),
                arg("alpha"),   arg("beta"),
                arg("twin_fraction"), arg("n_quad")
                ))
              )
         .def("log_p" , &w_t::log_p)
         .def("d_log_p_d_f", &w_t::d_log_p_d_f)
         .def("dd_log_p_dd_f", &w_t::dd_log_p_dd_f)
         .def("num_integrate", &w_t::num_integrate)
         .def("laplace_integrate", &w_t::laplace_integrate)
         ;
     }

   };

  }}} // namespace cctbx::xray

  namespace boost_python {

    void wrap_twin_targets()
    {
      twin_targets::boost_python::twin_completion_wrappers::wrap();
      twin_targets::boost_python::least_squares_hemihedral_twinning_on_i_wrappers::wrap();
      twin_targets::boost_python::least_squares_hemihedral_twinning_on_f_wrappers::wrap();
      twin_targets::boost_python::hemihedral_r_values_wrappers::wrap();
      twin_targets::boost_python::hemihedral_detwinner_wrappers::wrap();
      twin_targets::boost_python::single_twin_likelihood_wrappers::wrap();
    }

  }

}}


text:
#include <string>

#include <geometry_msgs/PoseStamped.h>
#include <ros/init.h>
#include <ros/node_handle.h>
#include <ros/param.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/MagneticField.h>
#include <sensor_msgs/Temperature.h>
#include <tf/transform_broadcaster.h>

#include <bno055_usb_stick/bno055_usb_stick.hpp>
#include <bno055_usb_stick/decoder.hpp>
#include <bno055_usb_stick_msgs/Output.h>

#include <boost/asio/io_service.hpp>
#include <boost/shared_ptr.hpp>

namespace bus = bno055_usb_stick;

ros::Publisher out_pub;
ros::Publisher imu_pub;
ros::Publisher pose_pub;
std::string pose_frame_id;
ros::Publisher mag_pub;
ros::Publisher temp_pub;
boost::shared_ptr< tf::TransformBroadcaster > tf_pub;
std::string tf_frame_id, tf_child_frame_id;
bool invert_tf;

void publish(const bno055_usb_stick_msgs::Output &output) {
  if (out_pub.getNumSubscribers() > 0) {
    out_pub.publish(output);
  }
  if (imu_pub.getNumSubscribers() > 0) {
    imu_pub.publish(bus::Decoder::toImuMsg(output));
  }
  if (pose_pub.getNumSubscribers() > 0) {
    pose_pub.publish(bus::Decoder::toPoseMsg(output, pose_frame_id));
  }
  if (mag_pub.getNumSubscribers() > 0) {
    mag_pub.publish(bus::Decoder::toMagMsg(output));
  }
  if (temp_pub.getNumSubscribers() > 0) {
    temp_pub.publish(bus::Decoder::toTempMsg(output));
  }
  if (tf_pub) {
    tf_pub->sendTransform(
        bus::Decoder::toTFTransform(output, tf_frame_id, tf_child_frame_id, invert_tf));
  }
}

int main(int argc, char *argv[]) {
  // init ROS
  ros::init(argc, argv, "bno055_usb_stick_node");
  ros::NodeHandle nh;

  // load parameters
  pose_frame_id = ros::param::param< std::string >("~pose_frame_id", "fixed");
  const bool publish_tf(ros::param::param("~publish_tf", false));
  tf_frame_id = ros::param::param< std::string >("~tf_frame_id", "fixed");
  tf_child_frame_id = ros::param::param< std::string >("~tf_child_frame_id", "imu_link");
  invert_tf = ros::param::param("~invert_tf", false);

  // setup publishers
  out_pub = nh.advertise< bno055_usb_stick_msgs::Output >("output", 1);
  imu_pub = nh.advertise< sensor_msgs::Imu >("imu", 1);
  pose_pub = nh.advertise< geometry_msgs::PoseStamped >("pose", 1);
  mag_pub = nh.advertise< sensor_msgs::MagneticField >("magnetic_field", 1);
  temp_pub = nh.advertise< sensor_msgs::Temperature >("temperature", 1);
  if (publish_tf) {
    tf_pub.reset(new tf::TransformBroadcaster);
  }

  // construct the worker
  boost::asio::io_service asio_service;
  bus::BNO055USBStick device(asio_service, publish);

  // run the worker
  while (nh.ok()) {
    asio_service.run_one();
  }

  return 0;
}

ext: cpp


text:
/**
 * Copyright 2012 JDS Uniphase. All rights reserved.
 * CPP manager implementations
 */
#include "xtreme/cpp/cpp_manager.h"
#include <boost/foreach.hpp>
#include "xtreme/common/xtreme_types.h"
#include "xtreme/cs/cs.h"
#include "xtreme/cpp/cpp_logging.h"
#include "xtreme/cpp/internal/cpp_pipeline.h"

CPP_SYM_EL xtreme::IComponent* create_component(xtreme::cs::CS& cs) {
  CPP_LOG(INFO, "Creating CPP component...");
  return new xtreme::cpp::CPPManager(cs);
}

CPP_SYM_EL int32_t destroy_component(xtreme::IComponent* p_cpp) {
  CPP_LOG(INFO, "Destroying CPP component...");
  delete p_cpp;
  return 0;
}

namespace xtreme {

namespace cpp {

CPPManager::CPPManager(xtreme::cs::CS& cs) : cs_(cs) {
}

CPPManager::~CPPManager() {
  // Destroy CPP pipelines
  BOOST_FOREACH(CPPPipeline* p_pipeline, pipelines_) {
    if (p_pipeline != nullptr) {
      delete p_pipeline;
    }
  }
}

IPublisherList CPPManager::GetPublisherForType(const EventType& event_type) {
  CPP_LOG(INFO, "Getting publishers for " << event_type << "...");
  IPublisherList publishers;
  IPublisherList tmp;
  BOOST_FOREACH(CPPPipeline* p_pipeline, pipelines_) {
    if (nullptr != p_pipeline) {
      p_pipeline->GetPublishers(event_type, tmp);
      publishers.splice(publishers.end(), tmp);
    } else {
      CPP_LOG(ERROR, "CPP pipeline is invalid");
    }
  }
  CPP_LOG(DEBUG, publishers.size() <<
          " publishers has been found for " << event_type << ".");
  return publishers;
}

bool CPPManager::InitComponent() {
  CPP_LOG(INFO, "Initializing CPP component...");
  return true;
}

bool CPPManager::StartComponent() {
  CPP_LOG(INFO, "Starting CPP component...");

  // Construct CPP pipelines
  IPublisherList msgPublishers = cs_.GetPublisherForType(kEVENT_CP_FRAME);
  if (msgPublishers.empty()) {
    CPP_LOG(ERROR, "No CP message publishers can be found!");
    return false;
  } else {
    CPP_LOG(DEBUG, msgPublishers.size() << " CP publishers has been found.");
    BOOST_FOREACH(IPublisher* p_publisher, msgPublishers) {
      CPPPipeline* p_pipeline = new CPPPipeline(&cs_, p_publisher);
      if (nullptr == p_pipeline ||
          kCppOK != p_pipeline->Initialize()) {
        CPP_LOG(ERROR, "CPP pipeline cannot be initialized!");
        return false;
      }
      pipelines_.push_back(p_pipeline);
    }
  }

  // Start CPP pipelines
  BOOST_FOREACH(CPPPipeline* p_pipeline, pipelines_) {
    if (nullptr == p_pipeline ||
        kCppOK != p_pipeline->Start()) {
      CPP_LOG(ERROR, "CPP pipeline cannot started!");
      return false;
    }
  }

  return true;
}

bool CPPManager::StopComponent() {
  CPP_LOG(INFO, "Stopping CPP component...");
  bool ret = true;

  BOOST_FOREACH(CPPPipeline* p_pipeline, pipelines_) {
      if (nullptr == p_pipeline ||
          kCppOK != p_pipeline->Stop()) {
        CPP_LOG(ERROR, "CPP pipeline cannot be stopped!");
        ret = false;  // Need to stop all pipelines
      }
    }

  return ret;
}

}   // namespace cpp

}   // namespace xtreme

ext: cc


text:
///////////////////////////////////////////////////////////////////////////////
// statistics::survival::data::algorithm::mean_events_by_covariate.hpp       //
//                                                                           //
//  Copyright 2009 Erwann Rogard. 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_STATISTICS_SURVIVAL_DATA_ALGORITHM_MEAN_EVENTS_BY_COVARIATE_HPP_ER_2009
#define BOOST_STATISTICS_SURVIVAL_DATA_ALGORITHM_MEAN_EVENTS_BY_COVARIATE_HPP_ER_2009
#include <vector>
#include <boost/foreach.hpp>
#include <boost/utility.hpp>
#include <boost/iterator/zip_iterator.hpp>
#include <boost/statistics/survival/data/data/mean_event.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/functional/find.hpp>
#include <boost/binary_op/functional/match_accumulator.hpp>
#include <boost/binary_op/algorithm/for_each.hpp>
#include <boost/binary_op/algorithm/heads.hpp>

namespace boost{
namespace statistics{
namespace survival{
namespace data{

    // Updates a collection of mean_events, one for each covariate value.
    //
    // Requirements
    // Let [b_x1,e_x1) denote a sequence of covariate values.
    // i = f(b_x1,e_x1,x) must be in [b_x1,e_x1].
    //
    // If i == e_x1, x is put at the end to [b_x1,e_x1)
    //
    // Another valid choice for F is nn1::find
    template<typename T,typename X,typename F = functional::find>
    class mean_events_by_covariate{
        public:
        typedef mean_event<T> mean_event_;
        typedef tuple<X,mean_event_> tuple_;
        typedef std::vector<tuple_> tuples_type;

        // Construct
        mean_events_by_covariate();
        template<typename Rx> mean_events_by_covariate(const Rx&);
        template<typename Rx> mean_events_by_covariate(const Rx&,const F& f);
        mean_events_by_covariate(const mean_events_by_covariate&);
        mean_events_by_covariate& operator=(const mean_events_by_covariate&);

        // Update
        template<typename ItX,typename ItE>
        void operator()(ItX b_x, ItX e_x, ItE b_e);

        // Acces
        const tuples_type& tuples()const;
        template<typename It> It tails(It out); // copies the mean_events

        private:
        F finder_;
        tuples_type tuples_;
        template<typename Rx>
        void set_covs(const Rx& rx);
    };

    // Implementation //

    template<typename T,typename X,typename F>
    mean_events_by_covariate<T,X,F>::mean_events_by_covariate(){}

    template<typename T,typename X,typename F>
    template<typename Rx>
    mean_events_by_covariate<T,X,F>::mean_events_by_covariate(const Rx& rx)
    :finder_(){
        this->set_covs(rx);
    }

    template<typename T,typename X,typename F>
    template<typename Rx>
    mean_events_by_covariate<T,X,F>::mean_events_by_covariate(
        const Rx& rx,const F& f)
    :finder_(f){
        this->set_covs(rx);
    }

    template<typename T,typename X,typename F>
    template<typename Rx>
    void mean_events_by_covariate<T,X,F>::set_covs(const Rx& rx){
        typedef typename range_value<Rx>::type x_;
        mean_event_ me;
        BOOST_FOREACH(const x_& x,rx){
            tuple_ t(x,me);
            tuples_.push_back( t );
        }
    }

    template<typename T,typename X,typename F>
    template<typename ItX,typename ItE>
    void mean_events_by_covariate<T,X,F>::operator()(ItX b_x,ItX e_x,ItE b_e)
    {
        typedef binary_op::match_accumulator<tuples_type&,F> functor_;
        std::for_each(
            make_zip_iterator( make_tuple( b_x, b_e ) ),
            make_zip_iterator(
                make_tuple(
                    e_x,
                    boost::next(
                        b_e,
                        std::distance(b_x,e_x)
                    )
                )
            ),
            functor_(this->tuples_)
        );
    }

    // Access
    template<typename T,typename X,typename F>
    const typename mean_events_by_covariate<T,X,F>::tuples_type&
    mean_events_by_covariate<T,X,F>::tuples()const{
        return (this->tuples_);
    }

    template<typename T,typename X,typename F>
    template<typename It>
    It mean_events_by_covariate<T,X,F>::tails(It out){
        return binary_op::tails(
            boost::begin(this->tuples()),
            boost::end(this->tuples()),
            out
        );
    }

}// data
}// survival
}// statistics
}// boost

#endif

ext: hpp


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

#ifndef OOX_HELPER_HELPER_HXX
#define OOX_HELPER_HELPER_HXX

#include <algorithm>
#include <limits>
#include <boost/static_assert.hpp>
#include <osl/endian.h>
#include <rtl/math.hxx>
#include <rtl/string.hxx>
#include <rtl/ustring.hxx>
#include <string.h>

namespace oox {

// Helper macros ==============================================================

/** Expands to the number of elements in a STATIC data array. */
#define STATIC_ARRAY_SIZE( array ) \
    (sizeof(array)/sizeof(*(array)))

/** Expands to a pointer behind the last element of a STATIC data array (like
    STL end()). */
#define STATIC_ARRAY_END( array ) \
    ((array)+STATIC_ARRAY_SIZE(array))

/** Expands to the 'index'-th element of a STATIC data array, or to 'def', if
    'index' is out of the array limits. */
#define STATIC_ARRAY_SELECT( array, index, def ) \
    ((static_cast<size_t>(index) < STATIC_ARRAY_SIZE(array)) ? ((array)[static_cast<size_t>(index)]) : (def))

/** Expands to a temporary ::rtl::OString, created from a literal(!) character
    array. */
#define CREATE_OSTRING( ascii ) \
    ::rtl::OString( RTL_CONSTASCII_STRINGPARAM( ascii ) )

/** Expands to a temporary ::rtl::OUString, created from a literal(!) ASCII(!)
    character array. */
#define CREATE_OUSTRING( ascii ) \
    ::rtl::OUString::intern( RTL_CONSTASCII_USTRINGPARAM( ascii ) )

/** Convert an OUString to an ASCII C string. Use for debug purposes only. */
#define OUSTRING_TO_CSTR( str ) \
    ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US ).getStr()

// Common constants ===========================================================

const sal_uInt8 WINDOWS_CHARSET_ANSI        = 0;
const sal_uInt8 WINDOWS_CHARSET_DEFAULT     = 1;
const sal_uInt8 WINDOWS_CHARSET_SYMBOL      = 2;
const sal_uInt8 WINDOWS_CHARSET_APPLE_ROMAN = 77;
const sal_uInt8 WINDOWS_CHARSET_SHIFTJIS    = 128;
const sal_uInt8 WINDOWS_CHARSET_HANGEUL     = 129;
const sal_uInt8 WINDOWS_CHARSET_JOHAB       = 130;
const sal_uInt8 WINDOWS_CHARSET_GB2312      = 134;
const sal_uInt8 WINDOWS_CHARSET_BIG5        = 136;
const sal_uInt8 WINDOWS_CHARSET_GREEK       = 161;
const sal_uInt8 WINDOWS_CHARSET_TURKISH     = 162;
const sal_uInt8 WINDOWS_CHARSET_VIETNAMESE  = 163;
const sal_uInt8 WINDOWS_CHARSET_HEBREW      = 177;
const sal_uInt8 WINDOWS_CHARSET_ARABIC      = 178;
const sal_uInt8 WINDOWS_CHARSET_BALTIC      = 186;
const sal_uInt8 WINDOWS_CHARSET_RUSSIAN     = 204;
const sal_uInt8 WINDOWS_CHARSET_THAI        = 222;
const sal_uInt8 WINDOWS_CHARSET_EASTERN     = 238;
const sal_uInt8 WINDOWS_CHARSET_OEM         = 255;

// ----------------------------------------------------------------------------

const sal_Int32 API_RGB_TRANSPARENT         = -1;       /// Transparent color for API calls.
const sal_Int32 API_RGB_BLACK               = 0x00000;  /// Black color for API calls.
const sal_Int32 API_RGB_WHITE               = 0xFFFFF;  /// White color for API calls.

const sal_Int16 API_LINE_NONE               = 0;
const sal_Int16 API_LINE_HAIR               = 2;
const sal_Int16 API_LINE_THIN               = 35;
const sal_Int16 API_LINE_MEDIUM             = 88;
const sal_Int16 API_LINE_THICK              = 141;

const sal_Int16 API_ESCAPE_NONE             = 0;        /// No escapement.
const sal_Int16 API_ESCAPE_SUPERSCRIPT      = 101;      /// Superscript: raise characters automatically (magic value 101).
const sal_Int16 API_ESCAPE_SUBSCRIPT        = -101;     /// Subscript: lower characters automatically (magic value -101).

const sal_Int8 API_ESCAPEHEIGHT_NONE        = 100;      /// Relative character height if not escaped.
const sal_Int8 API_ESCAPEHEIGHT_DEFAULT     = 58;       /// Relative character height if escaped.

// ============================================================================

// Limitate values ------------------------------------------------------------

template< typename ReturnType, typename Type >
inline ReturnType getLimitedValue( Type nValue, Type nMin, Type nMax )
{
    return static_cast< ReturnType >( ::std::min( ::std::max( nValue, nMin ), nMax ) );
}

template< typename ReturnType, typename Type >
inline ReturnType getIntervalValue( Type nValue, Type nBegin, Type nEnd )
{
//    this BOOST_STATIC_ASSERT fails with suncc
//    BOOST_STATIC_ASSERT( ::std::numeric_limits< Type >::is_integer );
    Type nInterval = nEnd - nBegin;
    Type nCount = (nValue < nBegin) ? -((nBegin - nValue - 1) / nInterval + 1) : ((nValue - nBegin) / nInterval);
    return static_cast< ReturnType >( nValue - nCount * nInterval );
}

template< typename ReturnType >
inline ReturnType getDoubleIntervalValue( double fValue, double fBegin, double fEnd )
{
    double fInterval = fEnd - fBegin;
    double fCount = (fValue < fBegin) ? -(::rtl::math::approxFloor( (fBegin - fValue - 1.0) / fInterval ) + 1.0) : ::rtl::math::approxFloor( (fValue - fBegin) / fInterval );
    return static_cast< ReturnType >( fValue - fCount * fInterval );
}

// Read from bitfields --------------------------------------------------------

/** Returns true, if at least one of the bits set in nMask is set in nBitField. */
template< typename Type >
inline bool getFlag( Type nBitField, Type nMask )
{
    return (nBitField & nMask) != 0;
}

/** Returns nSet, if at least one bit of nMask is set in nBitField, otherwise nUnset. */
template< typename ReturnType, typename Type >
inline ReturnType getFlagValue( Type nBitField, Type nMask, ReturnType nSet, ReturnType nUnset )
{
    return getFlag( nBitField, nMask ) ? nSet : nUnset;
}

/** Extracts a value from a bit field.

    Returns the data fragment from nBitField, that starts at bit nStartBit
    (0-based, bit 0 is rightmost) with the width of nBitCount. The returned
    value will be right-aligned (normalized).
    For instance: extractValue<T>(0x4321,8,4) returns 3 (value in bits 8-11).
 */
template< typename ReturnType, typename Type >
inline ReturnType extractValue( Type nBitField, sal_uInt8 nStartBit, sal_uInt8 nBitCount )
{
    sal_uInt64 nMask = 1; nMask <<= nBitCount; --nMask;
    return static_cast< ReturnType >( nMask & (nBitField >> nStartBit) );
}

// Write to bitfields ---------------------------------------------------------

/** Sets or clears (according to bSet) all set bits of nMask in ornBitField. */
template< typename Type >
inline void setFlag( Type& ornBitField, Type nMask, bool bSet = true )
{
    if( bSet ) ornBitField |= nMask; else ornBitField &= ~nMask;
}

/** Inserts a value into a bitfield.

    Inserts the lower nBitCount bits of nValue into ornBitField, starting
    there at bit nStartBit. Other contents of ornBitField keep unchanged.
 */
template< typename Type, typename InsertType >
void insertValue( Type& ornBitField, InsertType nValue, sal_uInt8 nStartBit, sal_uInt8 nBitCount )
{
    sal_uInt64 nMask = 1; nMask <<= nBitCount; --nMask;
    Type nNewValue = static_cast< Type >( nValue & nMask );
    (ornBitField &= ~(nMask << nStartBit)) |= (nNewValue << nStartBit);
}

// ============================================================================

/** Optional value, similar to ::boost::optional<>, with convenience accessors.
 */
template< typename Type >
class OptValue
{
public:
    inline explicit     OptValue() : maValue(), mbHasValue( false ) {}
    inline explicit     OptValue( const Type& rValue ) : maValue( rValue ), mbHasValue( true ) {}
    inline explicit     OptValue( bool bHasValue, const Type& rValue ) : maValue( rValue ), mbHasValue( bHasValue ) {}

    inline bool         has() const { return mbHasValue; }
    inline bool         operator!() const { return !mbHasValue; }
    inline bool         differsFrom( const Type& rValue ) const { return mbHasValue && (maValue != rValue); }

    inline const Type&  get() const { return maValue; }
    inline const Type&  get( const Type& rDefValue ) const { return mbHasValue ? maValue : rDefValue; }

    inline void         reset() { mbHasValue = false; }
    inline void         set( const Type& rValue ) { maValue = rValue; mbHasValue = true; }
    inline Type&        use() { mbHasValue = true; return maValue; }

    inline OptValue&    operator=( const Type& rValue ) { set( rValue ); return *this; }
    inline void         assignIfUsed( const OptValue& rValue ) { if( rValue.mbHasValue ) set( rValue.maValue ); }

private:
    Type                maValue;
    bool                mbHasValue;
};

// ============================================================================

/** Provides platform independent functions to convert from or to little-endian
    byte order, e.g. for reading data from or writing data to memory or a
    binary stream.

    On big-endian platforms, the byte order in the passed values is swapped,
    this can be used for converting big-endian to and from little-endian data.

    On little-endian platforms, the conversion functions are implemented empty,
    thus compilers should completely optimize away the function call.
 */
class ByteOrderConverter
{
public:
#ifdef OSL_BIGENDIAN
    inline static void  convertLittleEndian( sal_Int8& ) {}     // present for usage in templates
    inline static void  convertLittleEndian( sal_uInt8& ) {}    // present for usage in templates
    inline static void  convertLittleEndian( sal_Int16& rnValue )  { swap2( reinterpret_cast< sal_uInt8* >( &rnValue ) ); }
    inline static void  convertLittleEndian( sal_uInt16& rnValue ) { swap2( reinterpret_cast< sal_uInt8* >( &rnValue ) ); }
    inline static void  convertLittleEndian( sal_Int32& rnValue )  { swap4( reinterpret_cast< sal_uInt8* >( &rnValue ) ); }
    inline static void  convertLittleEndian( sal_uInt32& rnValue ) { swap4( reinterpret_cast< sal_uInt8* >( &rnValue ) ); }
    inline static void  convertLittleEndian( sal_Int64& rnValue )  { swap8( reinterpret_cast< sal_uInt8* >( &rnValue ) ); }
    inline static void  convertLittleEndian( sal_uInt64& rnValue ) { swap8( reinterpret_cast< sal_uInt8* >( &rnValue ) ); }
    inline static void  convertLittleEndian( float& rfValue )      { swap4( reinterpret_cast< sal_uInt8* >( &rfValue ) ); }
    inline static void  convertLittleEndian( double& rfValue )     { swap8( reinterpret_cast< sal_uInt8* >( &rfValue ) ); }

    template< typename Type >
    inline static void  convertLittleEndianArray( Type* pnArray, size_t nElemCount );

    inline static void  convertLittleEndianArray( sal_Int8*, size_t ) {}
    inline static void  convertLittleEndianArray( sal_uInt8*, size_t ) {}

#else
    template< typename Type >
    inline static void  convertLittleEndian( Type& ) {}

    template< typename Type >
    inline static void  convertLittleEndianArray( Type*, size_t ) {}

#endif

    /** Reads a value from memory, assuming memory buffer in little-endian.
        @param ornValue  (out-parameter) Contains the value read from memory.
        @param pSrcBuffer  The memory buffer to read the value from.
     */
    template< typename Type >
    inline static void  readLittleEndian( Type& ornValue, const void* pSrcBuffer );

    /** Writes a value to memory, while converting it to little-endian.
        @param pDstBuffer  The memory buffer to write the value to.
        @param nValue  The value to be written to memory in little-endian.
     */
    template< typename Type >
    inline static void  writeLittleEndian( void* pDstBuffer, Type nValue );

#ifdef OSL_BIGENDIAN
private:
    inline static void  swap2( sal_uInt8* pnData );
    inline static void  swap4( sal_uInt8* pnData );
    inline static void  swap8( sal_uInt8* pnData );
#endif
};

// ----------------------------------------------------------------------------

template< typename Type >
inline void ByteOrderConverter::readLittleEndian( Type& ornValue, const void* pSrcBuffer )
{
    memcpy( &ornValue, pSrcBuffer, sizeof( Type ) );
    convertLittleEndian( ornValue );
}

template< typename Type >
inline void ByteOrderConverter::writeLittleEndian( void* pDstBuffer, Type nValue )
{
    convertLittleEndian( nValue );
    memcpy( pDstBuffer, &nValue, sizeof( Type ) );
}

#ifdef OSL_BIGENDIAN
template< typename Type >
inline void ByteOrderConverter::convertLittleEndianArray( Type* pnArray, size_t nElemCount )
{
    for( Type* pnArrayEnd = pnArray + nElemCount; pnArray != pnArrayEnd; ++pnArray )
        convertLittleEndian( *pnArray );
}

inline void ByteOrderConverter::swap2( sal_uInt8* pnData )
{
    ::std::swap( pnData[ 0 ], pnData[ 1 ] );
}

inline void ByteOrderConverter::swap4( sal_uInt8* pnData )
{
    ::std::swap( pnData[ 0 ], pnData[ 3 ] );
    ::std::swap( pnData[ 1 ], pnData[ 2 ] );
}

inline void ByteOrderConverter::swap8( sal_uInt8* pnData )
{
    ::std::swap( pnData[ 0 ], pnData[ 7 ] );
    ::std::swap( pnData[ 1 ], pnData[ 6 ] );
    ::std::swap( pnData[ 2 ], pnData[ 5 ] );
    ::std::swap( pnData[ 3 ], pnData[ 4 ] );
}
#endif

// ============================================================================

} // namespace oox

#endif

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
/*
 * Copyright (c) 2018 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#include "exception_internal.hpp"
#include "item_list_gen2_keyitemimpl.hpp"

#include <pkmn/database/item_entry.hpp>
#include <pkmn/exception.hpp>

#include <boost/thread/lock_guard.hpp>

#include <cstdio>
#include <cstring>
#include <stdexcept>

namespace pkmn {

    item_list_gen2_keyitemimpl::item_list_gen2_keyitemimpl(
        int item_list_id,
        int game_id,
        const struct pksav_gen2_key_item_pocket* p_pksav_list
    ): item_list_impl(item_list_id, game_id)
    {
        if(p_pksav_list != nullptr)
        {
            _pksav_list = *p_pksav_list;
        }
        else
        {
            std::memset(&_pksav_list, 0, sizeof(_pksav_list));
            _pksav_list.terminator = 0xFF;
        }

        _from_native();

        _p_native = &_pksav_list;
    }

    void item_list_gen2_keyitemimpl::add(
        pkmn::e_item item,
        int amount
    )
    {
        if(amount != 1)
        {
            throw std::out_of_range("Amount: valid value 1");
        }

        pkmn::database::item_entry entry(item, get_game());
        if(entry.get_pocket() != get_name())
        {
            throw std::invalid_argument("This item is not valid for this list.");
        }

        boost::lock_guard<item_list_gen2_keyitemimpl> lock(*this);

        /*
         * Check if this item is already in the list. If so, it cannot
         * be added. If not, see if there's room to add another
         * item.
         */
        for(int item_index = 0; item_index < _num_items; ++item_index)
        {
            if(_item_slots[item_index].item == item)
            {
                throw std::invalid_argument("This item is already in this pocket.");
            }
        }

        if(_num_items < _capacity)
        {
            _item_slots[_num_items].item = item;
            _item_slots[_num_items].amount = amount;
            _to_native(_num_items++);
        }
        else
        {
            throw std::runtime_error("Cannot add any more items.");
        }
    }

    void item_list_gen2_keyitemimpl::remove(
        pkmn::e_item item,
        int amount
    )
    {
        if(amount != 1)
        {
            throw std::out_of_range("Amount: valid value 1");
        }

        pkmn::database::item_entry entry(item, get_game());
        if(entry.get_pocket() != get_name())
        {
            throw std::invalid_argument("This item is not valid for this list.");
        }

        boost::lock_guard<item_list_gen2_keyitemimpl> lock(*this);

        /*
         * Check if this item is in the list. If so, remove that amount,
         * and if there are no more, remove the item from the list and
         * shift everything over.
         */
        for(int item_index = 0; item_index < _num_items; ++item_index)
        {
            if(_item_slots[item_index].item == item)
            {
                _item_slots.erase(_item_slots.begin()+item_index);
                _item_slots.resize(_capacity);
                --_num_items;
                _to_native(item_index);

                break;
            }
        }
    }

    void item_list_gen2_keyitemimpl::set_item(
        int position,
        pkmn::e_item item,
        int amount
    )
    {
        // Input validation.
        int end_boundary = std::min<int>(_num_items, _capacity-1);
        pkmn::enforce_bounds("Position", position, 0, end_boundary);

        boost::lock_guard<item_list_gen2_keyitemimpl> lock(*this);

        if(item == pkmn::e_item::NONE)
        {
            if(amount != 0)
            {
                throw std::invalid_argument("\"None\" entries must have an amount of 0.");
            }
            else
            {
                pkmn::enforce_bounds("Amount", amount, 0, 99);
            }
        }
        else
        {
            pkmn::database::item_entry entry(item, get_game());
            if(entry.get_pocket() != get_name())
            {
                throw std::invalid_argument("This item does not belong in this pocket.");
            }

            if(amount != 1)
            {
                throw std::out_of_range("Amount: valid value 1");
            }

            for(int item_index = 0; item_index < _num_items; ++item_index)
            {
                if((_item_slots[item_index].item == item) && (item_index != position))
                {
                    // TODO: all error messages should have what slot item is in
                    std::string err_msg = "This item is already present in slot ";
                    err_msg.append(std::to_string(item_index));
                    err_msg.append(".");

                    throw std::invalid_argument(err_msg.c_str());
                }
            }
        }

        _item_slots[position].item = item;
        _item_slots[position].amount = amount;
        if((item == pkmn::e_item::NONE) && (position < end_boundary))
        {
            _item_slots.erase(_item_slots.begin()+position);
            _item_slots.emplace_back(pkmn::item_slot(pkmn::e_item::NONE, 0));
            --_num_items;
        }
        else
        {
            ++_num_items;
        }

        _to_native();
    }

    void item_list_gen2_keyitemimpl::_from_native(
        int index
    )
    {
        boost::lock_guard<item_list_gen2_keyitemimpl> lock(*this);

        if(index >= 0)
        {
            _item_slots[index].item = pkmn::database::item_entry(
                                          _pksav_list.item_indices[index],
                                          _game_id
                                      ).get_item();
            _item_slots[index].amount = (_pksav_list.item_indices[index] > 0) ? 1 : 0;
        }
        else
        {
            for(int item_index = 0; item_index < _capacity; ++item_index)
            {
                _item_slots[item_index].item = pkmn::database::item_entry(
                                                   _pksav_list.item_indices[item_index],
                                                   _game_id
                                               ).get_item();
                _item_slots[item_index].amount = (_pksav_list.item_indices[item_index] > 0) ? 1 : 0;
            }
        }

        _num_items = _pksav_list.count;
    }

    void item_list_gen2_keyitemimpl::_to_native(
        int index
    )
    {
        boost::lock_guard<item_list_gen2_keyitemimpl> lock(*this);

        if(index >= 0)
        {
            _pksav_list.item_indices[index] = uint8_t(pkmn::database::item_entry(
                                                          _item_slots[index].item,
                                                          get_game()
                                                      ).get_item_index());
        }
        else
        {
            for(int item_index = 0; item_index < _capacity; ++item_index)
            {
                _pksav_list.item_indices[item_index] = uint8_t(pkmn::database::item_entry(
                                                                   _item_slots[item_index].item,
                                                                   get_game()
                                                               ).get_item_index());
            }
        }

        _pksav_list.count = uint8_t(_num_items);
    }
}

max_stars_repo_name: ncorgan/libpkmn

max_issues_repo_name: PMArkive/libpkmn

max_forks_repo_name: PMArkive/libpkmn


text:
// Copyright (C) 2017  I. Bogoslavskyi, C. Stachniss, University of Bonn

// This program 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.

// This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

#include "projection_params.h"

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

#include <algorithm>
#include <fstream>
#include <string>
#include <vector>

namespace kamaz {

namespace hagen{

using std::vector;
using std::string;
using std::upper_bound;
using boost::algorithm::starts_with;

void ProjectionParams::SetSpan(const SpanParams& span_params,
                               const SpanParams::Direction& direction) {
  vector<SpanParams> params_vec = {{span_params}};
  this->SetSpan(params_vec, direction);
}

void ProjectionParams::SetSpan(const vector<SpanParams>& span_params,
                               const SpanParams::Direction& direction) {
  int num_beams = 0;
  for (const auto& span : span_params) {
    num_beams += span.num_beams();
  }
  switch (direction) {
    case SpanParams::Direction::HORIZONTAL:
      _h_span_params = SpanParams(span_params.front().start_angle(),
                                  span_params.back().end_angle(), num_beams);
      _col_angles = FillVector(span_params);
      break;
    case SpanParams::Direction::VERTICAL:
      _v_span_params = SpanParams(span_params.front().start_angle(),
                                  span_params.back().end_angle(), num_beams);
      _row_angles = FillVector(span_params);
      break;
  }
  FillCosSin();
}

vector<Radians> ProjectionParams::FillVector(const SpanParams& span_params) {
  vector<SpanParams> params_vec = {{span_params}};
  return this->FillVector(params_vec);
}

vector<Radians> ProjectionParams::FillVector(
    const vector<SpanParams>& span_params) {
  vector<Radians> res;
  for (const auto span_param : span_params) {
    Radians rad = span_param.start_angle();
    for (int i = 0; i < span_param.num_beams(); ++i) {
      res.push_back(rad);
      rad += span_param.step();
    }
  }
  return res;
}

double ProjectionParams::getMaxDistance(){
  return object_avoidance_zone;
}

bool ProjectionParams::valid() {
  bool all_params_valid = _v_span_params.valid() && _h_span_params.valid();
  bool arrays_empty = _row_angles.empty() && _col_angles.empty();
  bool cos_sin_empty = _row_angles_sines.empty() &&
                       _row_angles_cosines.empty() &&
                       _col_angles_sines.empty() && _col_angles_cosines.empty();
  if (!all_params_valid) {
    throw std::runtime_error("Projection parameters invalid.");
  }
  if (arrays_empty) {
    throw std::runtime_error("Projection parameters arrays not filled.");
  }
  if (cos_sin_empty) {
    throw std::runtime_error(
        "Projection parameters sin and cos arrays not filled.");
  }
  return true;
}

const Radians ProjectionParams::AngleFromRow(int row) const {
  if (row >= 0 && static_cast<size_t>(row) < _row_angles.size()) {
    return _row_angles[row];
  }
  fprintf(stderr, "ERROR: row %d is wrong\n", row);
  return 0.0_deg;
}

const Radians ProjectionParams::AngleFromCol(int col) const {
  int actual_col = col;
  if (col < 0) {
    actual_col = col + _col_angles.size();
  } else if (static_cast<size_t>(col) >= _col_angles.size()) {
    actual_col = col - _col_angles.size();
  }
  // everything is normal
  return _col_angles[actual_col];
}

size_t ProjectionParams::RowFromAngle(const Radians& angle) const {
  return FindClosest(_row_angles, angle);
}

size_t ProjectionParams::ColFromAngle(const Radians& angle) const {
  return FindClosest(_col_angles, angle);
}

size_t ProjectionParams::FindClosest(const vector<Radians>& vec,
                                     const Radians& val) {
  size_t found = 0;
  if (vec.front() < vec.back()) {
    found = upper_bound(vec.begin(), vec.end(), val) - vec.begin();
  } else {
    found = vec.rend() - upper_bound(vec.rbegin(), vec.rend(), val);
  }
  if (found == 0) {
    return found;
  }
  if (found == vec.size()) {
    return found - 1;
  }
  auto diff_next = Radians::Abs(vec[found] - val);
  auto diff_prev = Radians::Abs(val - vec[found - 1]);
  return diff_next < diff_prev ? found : found - 1;
}

std::unique_ptr<ProjectionParams> ProjectionParams::VLP_16(double object_avoidance_zone) {
  auto params = ProjectionParams();
  params.object_avoidance_zone = object_avoidance_zone;
  params.SetSpan(SpanParams(-180_deg, 180_deg, 870),
                 SpanParams::Direction::HORIZONTAL);
  params.SetSpan(SpanParams(15_deg, -15_deg, 16),
                 SpanParams::Direction::VERTICAL);
  params.FillCosSin();
  if (!params.valid()) {
    fprintf(stderr, "ERROR: params are not valid!\n");
    return nullptr;
  }
  return mem_utils::make_unique<ProjectionParams>(params);
}

std::unique_ptr<ProjectionParams> ProjectionParams::HDL_32(double object_avoidance_zone) {
  auto params = ProjectionParams();
  params.object_avoidance_zone = object_avoidance_zone;
  params.SetSpan(SpanParams(-180_deg, 180_deg, 870),
                 SpanParams::Direction::HORIZONTAL);
  params.SetSpan(SpanParams(10.0_deg, -30.0_deg, 32),
                 SpanParams::Direction::VERTICAL);
  params.FillCosSin();
  if (!params.valid()) {
    fprintf(stderr, "ERROR: params are not valid!\n");
    return nullptr;
  }
  return mem_utils::make_unique<ProjectionParams>(params);
}

std::unique_ptr<ProjectionParams> ProjectionParams::HDL_64(double object_avoidance_zone) {
  auto params = ProjectionParams();
  params.object_avoidance_zone = object_avoidance_zone;
  params.SetSpan(SpanParams(-180_deg, 180_deg, 870),
                 SpanParams::Direction::HORIZONTAL);
  SpanParams span_top(2.0_deg, -8.5_deg, 32);
  SpanParams span_bottom(-8.87_deg, -24.87_deg, 32);
  vector<SpanParams> spans = {{span_top, span_bottom}};
  params.SetSpan(spans, SpanParams::Direction::VERTICAL);
  params.FillCosSin();
  if (!params.valid()) {
    fprintf(stderr, "ERROR: params are not valid!\n");
    return nullptr;
  }
  return mem_utils::make_unique<ProjectionParams>(params);
}

const std::vector<float>& ProjectionParams::RowAngleCosines() const {
  return _row_angles_cosines;
}
const std::vector<float>& ProjectionParams::ColAngleCosines() const {
  return _col_angles_cosines;
}
const std::vector<float>& ProjectionParams::RowAngleSines() const {
  return _row_angles_sines;
}
const std::vector<float>& ProjectionParams::ColAngleSines() const {
  return _col_angles_sines;
}

void ProjectionParams::FillCosSin() {
  _row_angles_sines.clear();
  _row_angles_cosines.clear();
  for (const auto& angle : _row_angles) {
    _row_angles_sines.push_back(sin(angle.val()));
    _row_angles_cosines.push_back(cos(angle.val()));
  }
  _col_angles_sines.clear();
  _col_angles_cosines.clear();
  for (const auto& angle : _col_angles) {
    _col_angles_sines.push_back(sin(angle.val()));
    _col_angles_cosines.push_back(cos(angle.val()));
  }
}

}
}  // namespace kamaz

max_stars_repo_name: GPrathap/cmake

max_issues_repo_name: GPrathap/cmake

max_forks_repo_name: GPrathap/cmake


text:
#include "astar.cpp"
#include <Eigen/Dense>
#include "forward_kinematics.h"
#include <vector>
#include <stdio.h>
int main(int argc, char** argv )
{
  std::cout << "Start Program\n";

  Astar planner;

  configState start;

  start.theta[0] = 0;
  start.theta[1] = 0;
  start.theta[2] = 0;
  start.theta[3] = 0;
  start.theta[4] = 0;

  configState target;

  target.theta[0] = 0;
  target.theta[1] = 12;
  target.theta[2] = 12;
  target.theta[3] = 0;
  target.theta[4] = 0;

  wsState* actarget = fk(&target);

  std::cout << "Start Running\n";
  clock_t startTime = clock();
  std::vector<configState*> path = planner.run(&start, actarget);
  float secsElapsed = (float)(clock() - startTime)/CLOCKS_PER_SEC;
  printf("Runtime %f\n",secsElapsed);
  for(int i = 0; i < path.size(); i++){
    configstate_tostring(path.at(i));
  }
  return 0;
}


text:
#include <string>

#include <armadillo>

#ifndef GIBBS_SAMPLER_H
#define GIBBS_SAMPLER_H

namespace gibbs {

class GibbsSampler {

private:

    /// No units in each dim
    int _no_units;

    /// Coupling
    double _coupling;

    /// Bias
    double _bias;

public:

    /// Constructor
    GibbsSampler(int no_units, double coupling, double bias);

    /// Get random state of 0 or 1
    /// @return 2D state of random 0 or 1
    arma::imat get_random_state() const;

    /// Sample
    /// @param state_init Initital state
    /// @param no_steps No steps to sample
    /// @return Final state after sampling
    arma::imat sample(const arma::imat &state_init, int no_steps) const;
};

}

#endif

max_stars_repo_name: smrfeld/speed-up-python-with-carma

max_issues_repo_name: smrfeld/speed-up-python-with-carma

max_forks_repo_name: smrfeld/speed-up-python-with-carma


text:
/*
 * Copyright 2011 Nate Koenig
 *
 * 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.
 *
*/

#ifndef _QTESTFIXTURE_HH_
#define _QTESTFIXTURE_HH_

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

#include "gazebo/physics/physics.hh"
#include "gazebo/rendering/rendering.hh"
#include "gazebo/Server.hh"
#include "gazebo/gui/qt.h"
#include "gazebo/gui/qt_test.h"

#include "gazebo_config.h"
#include "test_config.h"

/// \brief Base class for all Gazebo GUI unit tests.
class QTestFixture : public QObject
{
  Q_OBJECT

  public: QTestFixture();

  /// \brief Load a world.
  /// \param[in] _worldFilename Name of the world to load.
  /// \param[in] _paused True to start the world paused.
  protected: void Load(const std::string &_worldFilename, bool _paused = false);

  /// \brief Pause or unpause the world.
  /// \param[in] _pause True to pause the world
  protected: void SetPause(bool _pause);

  /// \brief Get memory information about the current process.
  /// \param[out] _resident Resident size, in Kb.
  /// \param[out] _share Shared memory, in Kb.
  protected: void GetMemInfo(double &_resident, double &_share);

  /// \brief QT slot that is called automatically when the whole test case
  /// begins
  private slots: void initTestCase();

  /// \brief QT slot that is called automatically when each test begins
  private slots: void init();

  /// \brief QT slot that is called automatically when each test ends
  private slots: void cleanup();

  /// \brief QT slot that is called automatically when the whole test case ends
  private slots: void cleanupTestCase();

  /// \brief Run the Gazebo server in a thread.
  private: void RunServer(const std::string &_worldFilename, bool _paused);

  /// \brief The Gazebo server, which is run in a thread.
  protected: gazebo::Server *server;

  /// \brief Thread to run the Gazebo server.
  protected: boost::thread *serverThread;

  /// \brief Resident memory at test start
  private: double residentStart;

  /// \brief Shared memory at test start
  private: double shareStart;
};

#endif

ext: hh

max_stars_repo_name: thomas-moulard/gazebo-deb

max_issues_repo_name: thomas-moulard/gazebo-deb

max_forks_repo_name: thomas-moulard/gazebo-deb


text:
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab

#include "test/librados_test_stub/TestClassHandler.h"
#include "test/librados_test_stub/TestIoCtxImpl.h"
#include <boost/algorithm/string/predicate.hpp>
#include <dlfcn.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "common/debug.h"
#include "include/ceph_assert.h"

#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rados

namespace librados {

TestClassHandler::TestClassHandler() {
}

TestClassHandler::~TestClassHandler() {
  for (ClassHandles::iterator it = m_class_handles.begin();
      it != m_class_handles.end(); ++it) {
    dlclose(*it);
  }
}

void TestClassHandler::open_class(const std::string& name,
                                  const std::string& path) {
  void *handle = dlopen(path.c_str(), RTLD_NOW);
  if (handle == NULL) {
    std::cerr << "Failed to load class: " << name << " (" << path << "): "
              << dlerror() << std::endl;
    return;
  }

  // clear any existing error
  dlerror();

  // initialize
  void (*cls_init)() = reinterpret_cast<void (*)()>(
    dlsym(handle, "__cls_init"));

  char* error = nullptr;
  if ((error = dlerror()) != nullptr) {
    std::cerr << "Error locating initializer: " << error << std::endl;
  } else if (cls_init) {
    m_class_handles.push_back(handle);
    cls_init();
    return;
  }

  std::cerr << "Class: " << name << " (" << path << ") missing initializer"
            << std::endl;
  dlclose(handle);
}

void TestClassHandler::open_all_classes() {
  ceph_assert(m_class_handles.empty());

  const char* env = getenv("CEPH_LIB");
  std::string CEPH_LIB(env ? env : "lib");
  DIR *dir = ::opendir(CEPH_LIB.c_str());
  if (dir == NULL) {
    ceph_abort();;
  }

  std::set<std::string> names;
  struct dirent *pde = nullptr;
  while ((pde = ::readdir(dir))) {
    std::string name(pde->d_name);
    if (!boost::algorithm::starts_with(name, "libcls_") ||
        !boost::algorithm::ends_with(name, ".so")) {
      continue;
    }
    names.insert(name);
  }

  for (auto& name : names) {
    std::string class_name = name.substr(7, name.size() - 10);
    open_class(class_name, CEPH_LIB + "/" + name);
  }
  closedir(dir);
}

int TestClassHandler::create(const std::string &name, cls_handle_t *handle) {
  if (m_classes.find(name) != m_classes.end()) {
    std::cerr << "Class " << name << " already exists" << std::endl;
    return -EEXIST;
  }

  SharedClass cls(new Class());
  m_classes[name] = cls;
  *handle = reinterpret_cast<cls_handle_t>(cls.get());
  return 0;
}

int TestClassHandler::create_method(cls_handle_t hclass,
                                    const char *name,
                                    cls_method_cxx_call_t class_call,
                                    cls_method_handle_t *handle) {
  Class *cls = reinterpret_cast<Class*>(hclass);
  if (cls->methods.find(name) != cls->methods.end()) {
    std::cerr << "Class method " << hclass << ":" << name << " already exists"
              << std::endl;
    return -EEXIST;
  }

  SharedMethod method(new Method());
  method->class_call = class_call;
  cls->methods[name] = method;
  return 0;
}

cls_method_cxx_call_t TestClassHandler::get_method(const std::string &cls,
                                                   const std::string &method) {
  Classes::iterator c_it = m_classes.find(cls);
  if (c_it == m_classes.end()) {
    std::cerr << "Failed to located class " << cls << std::endl;
    return NULL;
  }

  SharedClass scls = c_it->second;
  Methods::iterator m_it = scls->methods.find(method);
  if (m_it == scls->methods.end()) {
    std::cerr << "Failed to located class method" << cls << "." << method
              << std::endl;
    return NULL;
  }
  return m_it->second->class_call;
}

TestClassHandler::SharedMethodContext TestClassHandler::get_method_context(
    TestIoCtxImpl *io_ctx_impl, const std::string &oid,
    const SnapContext &snapc) {
  SharedMethodContext ctx(new MethodContext());

  // clone to ioctx to provide a firewall for gmock expectations
  ctx->io_ctx_impl = io_ctx_impl->clone();
  ctx->oid = oid;
  ctx->snapc = snapc;
  return ctx;
}

int TestClassHandler::create_filter(cls_handle_t hclass,
				    const std::string& name,
				    cls_cxx_filter_factory_t fn)
{
  Class *cls = reinterpret_cast<Class*>(hclass);
  if (cls->filters.find(name) != cls->filters.end()) {
    return -EEXIST;
  }
  cls->filters[name] = fn;
  return 0;
}

TestClassHandler::MethodContext::~MethodContext() {
  io_ctx_impl->put();
}

} // namespace librados

max_stars_repo_name: rpratap-bot/ceph

max_issues_repo_name: rpratap-bot/ceph

max_forks_repo_name: rpratap-bot/ceph


text:
///////////////////////////////////////////////////////////////////////////////
// as_matcher.hpp
//
//  Copyright 2008 Eric Niebler. 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_XPRESSIVE_DETAIL_STATIC_TRANSFORMS_AS_MATCHER_HPP_EAN_04_01_2007
#define BOOST_XPRESSIVE_DETAIL_STATIC_TRANSFORMS_AS_MATCHER_HPP_EAN_04_01_2007

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

#include <boost/mpl/assert.hpp>
#include <boost/xpressive/detail/detail_fwd.hpp>
#include <boost/xpressive/detail/static/static.hpp>

namespace boost { namespace xpressive { namespace grammar_detail
{
    struct as_matcher : proto::callable
    {
        template<typename Sig> struct result {};

        template<typename This, typename Expr, typename State, typename Visitor>
        struct result<This(Expr, State, Visitor)>
        {
            typedef
                typename Visitor::template apply<
                    typename proto::result_of::arg<Expr>::type
                >::type
            type;
        };

        template<typename Expr, typename State, typename Visitor>
        typename result<void(Expr, State, Visitor)>::type
        operator ()(Expr const &expr, State const &, Visitor &visitor) const
        {
            return visitor.call(proto::arg(expr));
        }
    };

}}}

#endif

max_issues_repo_name: cpmech/vismatrix

max_forks_repo_name: cpmech/vismatrix


text:
/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#include "AliasedRegisters.h"

#include <algorithm>
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#endif
#include <boost/graph/adjacency_list.hpp>
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
#include <boost/optional.hpp>
#include <boost/range/iterator_range.hpp>
#include <limits>
#include <unordered_set>

// Implemented by an undirected graph where nodes are Registers and edges are an
// alias between them.
//
// An alias group is a fully connected clique of nodes.
// Every node in a group is aliased to every other node.
//
// Data structure invariant: The graph is a forest of cliques
// Corollary: There are no edges that are not part of a clique.
//
// The aliasing relation is an equivalence relation. An alias group is an
// equivalence class of this relation.
//   Reflexive : a node is trivially equivalent to itself
//   Symmetric : edges in the graph are undirected
//   Transitive: `AliasedRegisters::move` adds an edge to every node in the
//               group, creating a clique

// Move `moving` into the alias group of `group`
//
// Create an edge from `moving` to every vertex in the alias group of
// `group`.
//
// We want alias groups to be fully connected cliques.
// Here's an example to show why:
//
//   move v1, v2
//   move v0, v1 # (call `AliasedRegisters::move(v0, v1)` here)
//   const v1, 0
//
// At this point, v0 and v2 still hold the same value, but if we had just
// `make_aliased(v0, v1)`, then we would have lost this information.
void AliasedRegisters::move(const RegisterValue& moving,
                            const RegisterValue& group) {
  // Only need to do something if they're not already in same group
  if (!are_aliases(moving, group)) {
    // remove from the old group
    break_alias(moving);
    vertex_t mov = find_or_create(moving);
    vertex_t grp = find_or_create(group);
    // add edge to every node in new group
    for (vertex_t v : vertices_in_group(grp)) {
      boost::add_edge(mov, v, m_graph);
    }
  }
}

// This method is only public for testing reasons. Only use it if you know what
// you're doing. This method does not maintain transitive closure of the graph,
// You probably want to use `move`
void AliasedRegisters::make_aliased(const RegisterValue& r1, const RegisterValue& r2) {
  if (r1 != r2) {
    vertex_t v1 = find_or_create(r1);
    vertex_t v2 = find_or_create(r2);
    boost::add_edge(v1, v2, m_graph);
  }
}

// Remove r from its alias group
void AliasedRegisters::break_alias(const RegisterValue& r) {
  const auto& v = find(r);
  const auto& end = boost::vertices(m_graph).second;
  if (v != end) {
    // clear removes all edges incident to r
    boost::clear_vertex(*v, m_graph);
  }
}

// if there is an edge between r1 to r2, then they are aliases.
// We only need to check for single edge paths because `move` adds an edge to
// every node in the alias group, thus maintaining transitive closure of the
// graph
bool AliasedRegisters::are_aliases(const RegisterValue& r1, const RegisterValue& r2) {
  if (r1 == r2) {
    return true;
  }

  return has_edge_between(r1, r2);
}

// Return a representative for this register.
//
// Return the lowest numbered register that this value is an alias with.
boost::optional<Register> AliasedRegisters::get_representative(
    const RegisterValue& r) {

  // if r is not in the graph, then it has no representative
  const auto& v = find(r);
  const auto& end = boost::vertices(m_graph).second;
  if (v == end) {
    return boost::none;
  }

  // find the lowest numbered register in the same alias group as `v`
  Register result = std::numeric_limits<Register>::max();
  for (vertex_t candidate : vertices_in_group(*v)) {
    const RegisterValue& val = m_graph[candidate];
    if (val.kind == RegisterValue::Kind::REGISTER) {
      result = std::min<Register>(result, val.reg);
    }
  }
  if (result == std::numeric_limits<Register>::max()) {
    return boost::none;
  }
  return result;
}

// if `r` is in the graph, return the vertex holding it.
// if not, return the `end` iterator of the vertices
const boost::range_detail::integer_iterator<AliasedRegisters::vertex_t>
AliasedRegisters::find(const RegisterValue& r) const {
  const auto& iters = boost::vertices(m_graph);
  const auto& begin = iters.first;
  const auto& end = iters.second;
  for (auto it = begin; it != end; ++it) {
    if (m_graph[*it] == r) {
      return it;
    }
  }
  return end;
}

// returns the vertex holding `r` or creates a new (unconnected)
// vertex if `r` is not in m_graph
AliasedRegisters::vertex_t AliasedRegisters::find_or_create(const RegisterValue& r) {
  const auto& it = find(r);
  const auto& end = boost::vertices(m_graph).second;
  if (it != end) {
    return *it;
  } else {
    return boost::add_vertex(r, m_graph);
  }
}

// return true if there is a path of length exactly 1 from r1 to r2
bool AliasedRegisters::has_edge_between(const RegisterValue& r1,
                                        const RegisterValue& r2) const {
  // make sure we have both vertices
  const auto& search1 = find(r1);
  const auto& search2 = find(r2);
  const auto& end = boost::vertices(m_graph).second;
  if (search1 == end || search2 == end) {
    return false;
  }

  // and check that they have an edge between them
  const auto& adj = boost::adjacent_vertices(*search1, m_graph);
  const auto& adj_begin = adj.first;
  const auto& adj_end = adj.second;
  const auto& edge_search = std::find(adj_begin, adj_end, *search2);
  return edge_search != adj_end;
}

std::vector<AliasedRegisters::vertex_t> AliasedRegisters::vertices_in_group(
    vertex_t v) const {
  std::vector<vertex_t> result;
  result.push_back(v);
  const auto& adj = boost::adjacent_vertices(v, m_graph);
  const auto& adj_begin = adj.first;
  const auto& adj_end = adj.second;
  for (auto it = adj_begin; it != adj_end; ++it) {
    result.push_back(*it);
  }
  return result;
}

void AliasedRegisters::merge_groups_of(const RegisterValue& r1, const RegisterValue& r2) {
  vertex_t v1 = find_or_create(r1);
  vertex_t v2 = find_or_create(r2);

  for (vertex_t g1 : vertices_in_group(v1)) {
    for (vertex_t g2 : vertices_in_group(v2)) {
      boost::add_edge(g1, g2, m_graph);
    }
  }
}

// ---- extends AbstractValue ----

void AliasedRegisters::clear() {
  m_graph.clear();
}

AliasedRegisters::Kind AliasedRegisters::kind() const {
  return (boost::num_edges(m_graph) > 0) ? AliasedRegisters::Kind::Value
                                         : AliasedRegisters::Kind::Top;
}

// The lattice looks like this:
//
//             T (graphs with no edges)
//      graphs with 1 edge                  ^  join moves up (edge intersection)
//      graphs with 2 edges                 |
//            ...                           v  meet moves down (edge union)
//      graphs with n edges
//            ...
//            _|_
//
// So, leq is the superset relation on the edge set
bool AliasedRegisters::leq(const AliasedRegisters& other) const {
  if (boost::num_edges(m_graph) < boost::num_edges(other.m_graph)) {
    // this cannot be a superset of other if this has fewer edges
    return false;
  }

  // for all edges in other (the potential subset), make sure this contains that
  // edge.
  const auto& iters = boost::edges(other.m_graph);
  const auto& begin = iters.first;
  const auto& end = iters.second;
  for (auto it = begin; it != end; ++it) {
    const RegisterValue& r1 = other.m_graph[boost::source(*it, other.m_graph)];
    const RegisterValue& r2 = other.m_graph[boost::target(*it, other.m_graph)];
    if (!has_edge_between(r1, r2)) {
      return false;
    }
  }
  return true;
}

// returns true iff they have exactly the same edges between the same
// RegisterValues
bool AliasedRegisters::equals(const AliasedRegisters& other) const {
  return boost::num_edges(m_graph) == boost::num_edges(other.m_graph) &&
         leq(other);
}

// alias group union
AliasedRegisters::Kind AliasedRegisters::meet_with(
    const AliasedRegisters& other) {
  const auto& iters = boost::edges(other.m_graph);
  const auto& begin = iters.first;
  const auto& end = iters.second;
  for (auto it = begin; it != end; ++it) {
    const RegisterValue& r1 = other.m_graph[boost::source(*it, other.m_graph)];
    const RegisterValue& r2 = other.m_graph[boost::target(*it, other.m_graph)];
    if (!this->are_aliases(r1, r2)) {
      this->merge_groups_of(r1, r2);
    }
  }
  return AliasedRegisters::Kind::Value;
}

AliasedRegisters::Kind AliasedRegisters::narrow_with(
    const AliasedRegisters& other) {
  return join_with(other);
}

// edge intersection
AliasedRegisters::Kind AliasedRegisters::join_with(
    const AliasedRegisters& other) {

  // fill `deletes` with edges that aren't in `other`
  std::vector<std::pair<vertex_t, vertex_t>> deletes;
  const auto& iters = boost::edges(this->m_graph);
  const auto& begin = iters.first;
  const auto& end = iters.second;
  for (auto it = begin; it != end; ++it) {
    vertex_t v1 = boost::source(*it, this->m_graph);
    vertex_t v2 = boost::target(*it, this->m_graph);
    const RegisterValue& r1 = this->m_graph[v1];
    const RegisterValue& r2 = this->m_graph[v2];
    if (!other.has_edge_between(r1, r2)) {
      deletes.emplace_back(v1, v2);
    }
  }

  // This maintains a forest of cliques because any subset of nodes of a clique
  // is also a clique
  for (const auto& edge : deletes) {
    boost::remove_edge(edge.first, edge.second, this->m_graph);
  }

  return AliasedRegisters::Kind::Value;
}

AliasedRegisters::Kind AliasedRegisters::widen_with(
    const AliasedRegisters& other) {
  return meet_with(other);
}

max_stars_repo_name: arxan/redex

max_issues_repo_name: arxan/redex

max_forks_repo_name: arxan/redex


text:
#include "skinspage.h"
#include "ui_skinspage.h"
#include "util.h"
//#include "settings.h"

#include <QClipboard>
#include <QMessageBox>
#include <QMenu>
#include <QFileDialog>
#include <QProgressDialog>
#include <QTextStream>
#include <QDesktopServices>
#include <QUrl>
#include <QSettings>
#include <QSize>
#include <boost/filesystem.hpp>
#include <string>
#include <QMainWindow>
#include "ui_interface.h"
#include <QVector>
#include <QRegExp>
#include <QHeaderView>

#include <QDebug>
using namespace std;

SkinsPage::SkinsPage(QWidget *parent) : QWidget(parent), ui(new Ui::SkinsPage)
{

  networkTimer = new QTimer(this);
  networkTimer->setInterval(10000);
  connect(networkTimer, SIGNAL(timeout()), this, SLOT(networkTimeout()));
  ui->setupUi(this);
  resetButton = createButton(tr("&Reset to none"), SLOT(reset()));
  downloadButton = createButton(tr("&Download Themes"), SLOT(getlist()));

  QPixmap downloadPixmap(":/icons/gears");
  QIcon downloadButtonIcon(downloadPixmap);
  downloadButton->setIcon(downloadButtonIcon);
  QSettings settings("Bitcoin-sCrypt", "settings");
  inipath=GetDataDir().string().c_str();
  inipath=inipath+"/themes/";
  loadSettings();

  filesFoundLabel = new QLabel;
  statusLabel = new QLabel;

  createFilesTable();

  ui->mainLayout->setSizeConstraint(QLayout::SetNoConstraint);
  ui->mainLayout->addWidget(filesTable, 3, 0, 1, 3);
  ui->mainLayout->addWidget(filesFoundLabel, 4, 0, 1, 2);
  ui->mainLayout->addWidget(statusLabel, 5, 0, 1, 2);
  ui->mainLayout->addWidget(resetButton, 6, 2);
  ui->mainLayout->addWidget(downloadButton, 6, 0);

  //force find
  find();
}

void SkinsPage::reset()
{
	QApplication *app = (QApplication*)QApplication::instance();
	app->setStyleSheet(NULL);
	inifname = "";
	saveSettings();
}

void SkinsPage::find()
{
  filesTable->setRowCount(0);

  currentDir = QDir(inipath);
  QStringList files;
  files = currentDir.entryList(QStringList("*"),QDir::Files | QDir::NoSymLinks |QDir::Hidden);

  showFiles(files);
}

QStringList SkinsPage::findFiles(const QStringList &files, const QString &text)
{
  QProgressDialog progressDialog(this);
  progressDialog.setCancelButtonText(tr("&Cancel"));
  progressDialog.setRange(0, files.size());
  progressDialog.setWindowTitle(tr("Find Files"));

  QStringList foundFiles;
  for (int i = 0; i < files.size(); ++i)
  {
    progressDialog.setValue(i);
    progressDialog.setLabelText(tr("Searching file number %1 of %2...")
                                    .arg(i).arg(files.size()));
    qApp->processEvents();
    QFile file(currentDir.absoluteFilePath(files[i]));

    if (file.open(QIODevice::ReadOnly))
    {
      QString line;
      QTextStream in(&file);
      while (!in.atEnd())
      {
        if (progressDialog.wasCanceled())
          break;
        line = in.readLine();
        if (line.contains(text))
        {
          foundFiles << files[i];
          break;
        }
      }
    }
  }
  return foundFiles;
}

void SkinsPage::showFiles(const QStringList &files)
{
  inipath=currentDir.absolutePath();

  QString line="";// first line of file;
  QString desc="";// descrition goes here;
  QString vers="";// version info;
  int fcount=0;
  for (int i = 0; i < files.size(); ++i)
  {
    line="";
    desc="";
    vers="";
    QFile file(currentDir.absoluteFilePath(files[i]));

    QTableWidgetItem *fileNameItem = new QTableWidgetItem(files[i]);
    fileNameItem->setFlags(fileNameItem->flags() ^ Qt::ItemIsEditable);

// read first line of file to get desc, version
    QFile inputFile(currentDir.absoluteFilePath(files[i]));
    QFileInfo fi(inputFile);

    if(fi.suffix() == "qss")
    {
      if (inputFile.open(QIODevice::ReadOnly))
      {
        QTextStream in(&inputFile);
        if(!in.atEnd())
          line = in.readLine();
      }
      inputFile.close();

// parse line
    int x=line.indexOf("desc=");
    int e=0;
    if(x>0)
    {
      e=line.indexOf(QChar('"'),x);
      if(e>0) // if we found a "
      {
        x=e+1;
        e=line.indexOf(QChar('"'),x); //find the next "
        e=e-x;
        desc=line.mid(x,e);
      }
    }

    x=line.indexOf("vers=");
    e=0;
    if(x>0)
    {
      e=line.indexOf(QChar('"'),x);
      if(e>0) // if we found a "
      {
        x=e+1;
        e=line.indexOf(QChar('"'),x); //find the next "
        e=e-x;
        vers=line.mid(x,e);
      }
    }

    QTableWidgetItem *descriptionItem = new QTableWidgetItem(desc);
	descriptionItem->setFlags(descriptionItem->flags() ^ Qt::ItemIsEditable);
    QTableWidgetItem *versionItem = new QTableWidgetItem(vers);
	versionItem->setFlags(versionItem->flags() ^ Qt::ItemIsEditable);

    fcount++;
    int row = filesTable->rowCount();
    filesTable->insertRow(row);
    filesTable->setItem(row, 0, fileNameItem);
    filesTable->setItem(row, 1, descriptionItem);
    filesTable->setItem(row, 2, versionItem);
  }
    }
  filesFoundLabel->setText(tr("%1 file(s) found").arg(fcount) +
#if defined(Q_OS_SYMBIAN) || defined(Q_WS_MAEMO_5)
    (" (Select file to load it)"));
#else
    (" (Double click on a file to load it)"));
#endif
  filesFoundLabel->setWordWrap(true);
}

QPushButton *SkinsPage::createButton(const QString &text, const char *member)
{
  QPushButton *button = new QPushButton(text);
  connect(button, SIGNAL(clicked()), this, member);
  return button;
}

void SkinsPage::createFilesTable()
{
  filesTable = new QTableWidget(0, 3);
  filesTable->setSelectionBehavior(QAbstractItemView::SelectRows);

  QStringList labels;
  labels << tr("Filename") << tr("Description") << tr("Version");
  filesTable->setHorizontalHeaderLabels(labels);

  filesTable->setColumnWidth(0,160);// last column get resized automatically by qt
  filesTable->setColumnWidth(2,100);
  filesTable->setColumnWidth(1,250);
  filesTable->verticalHeader()->hide();
  filesTable->setShowGrid(false);

  connect(filesTable, SIGNAL(cellActivated(int,int)),
            this, SLOT(openFileOfItem(int,int)));
}

void SkinsPage::openFileOfItem(int row, int /* column */)
{
  QTableWidgetItem *item = filesTable->item(row, 0);

  inifname=item->text();
  saveSettings();
  loadSkin();
}

void SkinsPage::optionChanged()
{
  saveSettings();
  loadSettings(); // to resize the window
  loadSkin();
}

void SkinsPage::saveSettings()
{
  QSettings settings("Bitcoin-sCrypt", "settings");
  settings.setValue("filename", inifname);
}

void SkinsPage::loadSettings()
{
  QSettings settings("Bitcoin-sCrypt", "settings");
  inifname=settings.value("filename", "").toString();
}

void SkinsPage::loadSkin()
{
  QFile styleFile(inipath+"/"+inifname);
  styleFile.open(QFile::ReadOnly);
  QByteArray bytes = styleFile.readAll();
  QString newStyleSheet(bytes);
  newStyleSheet.replace("myimages",inipath+"/images"); // deal with relative path
  QApplication *app = (QApplication*)QApplication::instance();
  app->setStyleSheet(NULL);
  app->setStyleSheet(newStyleSheet);
}

void SkinsPage::resizeEvent(QResizeEvent* event)
{
  int ww=width();
  filesTable->setColumnWidth(1,ww-278);
}

void SkinsPage::getlist()
{
  // show a downloading message in status bar
  statusLabel->setText("<b>" + tr("Downloading themes from http://btcs.altcoinwarz.com...") + "</b>");
  latestNetError = "";

  // first, let's disable the download button (triple-clicks fanatics !)
  downloadButton->setEnabled(false);

  // create dir if not
  QDir imgdir(inipath + "/images");
  if (!imgdir.exists())
    imgdir.mkpath(".");

  connect(&manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(getListFinished(QNetworkReply*)));

  QNetworkRequest request;
  request.setUrl(QUrl("http://btcs.altcoinwarz.com/themes/list.txt"));
  request.setRawHeader("User-Agent", "Wallet theme request");

  networkTimer->start();
  manager.get(request);
}

bool SkinsPage::netHandleError(QNetworkReply* reply, QString urlDownload)
{
	networkTimer->stop();
	if (reply->error())
	{
		latestNetError = tr("Download of ") + urlDownload + tr(" failed: ") + reply->errorString();
	}
	else if (isHttpRedirect(reply))
	{
		latestNetError = tr("HTTP redirect while attempting download of ") + urlDownload;
	}
	else
	{

	// signal no errors here
		return(true);
	}

	// execute the same function, displaying latest occured error
	networkTimeout();
	return(false);
}

void SkinsPage::getListFinished(QNetworkReply* reply)
{
  if (netHandleError(reply, "http://btcs.altcoinwarz.com/themes/list.txt")) {
    disconnect(&manager, SIGNAL(finished(QNetworkReply*)), 0, 0);
    connect(&manager, SIGNAL(finished(QNetworkReply*)), SLOT(downloadFinished(QNetworkReply*)));
    QString pagelist=reply->readAll();
    QStringList list = pagelist.split('\n');
    QString line;

    for(int i=0;i<list.count();i++)
    {
      line=list.at(i).toLocal8Bit().constData();
      line.simplified(); // strip extra characters
      line.replace("\r",""); // this one too
      if(line.length())
      {
        download("http://btcs.altcoinwarz.com/themes/"+line);
      }
    }
  }
  else
  {
    reply->abort();
  }
}

void SkinsPage::download(const QUrl &filename)
{
  QNetworkRequest request;//(filename);
  request.setUrl(filename);
  request.setRawHeader("User-Agent", "Wallet theme request");
  networkTimer->start();
  reply = manager.get(request);
  currentDownloads.append(reply);
}

void SkinsPage::downloadFinished(QNetworkReply *reply)
{
  QUrl url = reply->url();
  if (netHandleError(reply, url.toEncoded()))
  {
    QString filename = inipath + url.path().replace("/themes/","/");
    if (!saveToDisk(filename, reply))
    {
      QString fError = tr("Could not open ") + filename + " for writing: " + latestFileError;
      emit error(tr("File Saving Error"), fError, false);
    }
    currentDownloads.removeAll(reply);
    reply->deleteLater();

    // when finish all, re-enable the download button and force a find
    if (currentDownloads.isEmpty())
    {
	  statusLabel->setText("");
      downloadButton->setEnabled(true);
      disconnect(&manager, SIGNAL(finished(QNetworkReply*)), 0, 0);
      find();
      emit information(tr("Themes Download"), tr("Themes were successfully downloaded and installed."));
    }
  }
}

bool SkinsPage::isHttpRedirect(QNetworkReply *reply)
{
    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    return statusCode == 301 || statusCode == 302 || statusCode == 303
           || statusCode == 305 || statusCode == 307 || statusCode == 308;
}

bool SkinsPage::saveToDisk(const QString &filename, QIODevice *data)
{
  QFile file(filename);
  if (!file.open(QIODevice::WriteOnly))
  {
    latestFileError = file.errorString();
    return false;
  }

  file.write(data->readAll());
  file.close();

  return true;
}

void SkinsPage::networkTimeout()
{
	// signal error and preset for next operation
	networkTimer->stop();
	if (!currentDownloads.isEmpty()) {
		QList<QNetworkReply *>::iterator i;
		for (i = currentDownloads.begin(); i != currentDownloads.end(); ++i)
		{
			(*i)->abort();		// abort here all and any pending reply, to avoid mess if anything comes back
		}
	}
	if (latestNetError == "")
	{
		latestNetError = tr("Network timeout. Please check your network and try again.");
	}
	statusLabel->setText("");
	downloadButton->setEnabled(true);
	disconnect(&manager, SIGNAL(finished(QNetworkReply*)), 0, 0);
	find();
	emit error(tr("Themes Download Error"), latestNetError, true);
}


text:
/*
 * File:   kanooth/number_bits.hpp
 * Author: Jan Marthedal Rasmussen
 *
 * Created 2009-12-19 09:18Z
 *
 * (C) Copyright Jan Marthedal Rasmussen 2009-2012
 * Use, modification and distribution are subject to 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 KANOOTH_NUMBER_BITS_HPP
#define KANOOTH_NUMBER_BITS_HPP

#ifdef KANOOTH_USE_BOOST
#include <boost/integer_traits.hpp>
#else
#include <limits>
#endif

namespace kanooth {

#ifdef KANOOTH_USE_BOOST

  template <typename T>
  struct number_bits {
      static const unsigned value = boost::integer_traits<T>::digits;
  };

#else

  template <typename T>
  struct number_bits {
      static const unsigned value = std::numeric_limits<T>::digits;
  };

#endif

} // namespace kanooth

#endif // KANOOTH_NUMBER_BITS_HPP

max_stars_repo_name: janmarthedal/kanooth-numbers

max_issues_repo_name: janmarthedal/kanooth-numbers

max_forks_repo_name: janmarthedal/kanooth-numbers


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
 * Copyright (c) 2014-2017,  Regents of the University of California,
 *                           Arizona Board of Regents,
 *                           Colorado State University,
 *                           University Pierre & Marie Curie, Sorbonne University,
 *                           Washington University in St. Louis,
 *                           Beijing Institute of Technology,
 *                           The University of Memphis.
 *
 * This file is part of NFD (Named Data Networking Forwarding Daemon).
 * See AUTHORS.md for complete list of NFD authors and contributors.
 *
 * NFD 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.
 *
 * NFD 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
 * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
 */

/** \file
 *  This test suite checks that forwarding can relay Interest and Data via ad hoc face.
 */

// Strategies that can forward Interest to an ad hoc face even if it's the downstream,
// sorted alphabetically.
#include "fw/asf-strategy.hpp"
#include "fw/best-route-strategy2.hpp"
#include "fw/multicast-strategy.hpp"

#include "tests/test-common.hpp"
#include "topology-tester.hpp"
#include <boost/mpl/vector.hpp>

namespace nfd {
namespace fw {
namespace tests {

using namespace nfd::tests;

template<typename S>
class AdHocForwardingFixture : public UnitTestTimeFixture
{
protected:
  AdHocForwardingFixture()
  {
    nodeA = topo.addForwarder("A");
    nodeB = topo.addForwarder("B");
    nodeC = topo.addForwarder("C");

    for (TopologyNode node : {nodeA, nodeB, nodeC}) {
      topo.setStrategy<S>(node);
    }

    auto wireless = topo.addLink("ABC", time::milliseconds(10), {nodeA, nodeB, nodeC},
                                 ndn::nfd::LINK_TYPE_AD_HOC);
    wireless->block(nodeA, nodeC);
    wireless->block(nodeC, nodeA);
    faceA = &wireless->getFace(nodeA);
    faceB = &wireless->getFace(nodeB);
    faceC = &wireless->getFace(nodeC);

    appA = topo.addAppFace("consumer", nodeA);
    topo.registerPrefix(nodeA, *faceA, "/P");
    appC = topo.addAppFace("producer", nodeC, "/P");
    topo.addEchoProducer(appC->getClientFace(), "/P");
  }

protected:
  TopologyTester topo;
  TopologyNode nodeA;
  TopologyNode nodeB;
  TopologyNode nodeC;
  Face* faceA;
  Face* faceB;
  Face* faceC;
  shared_ptr<TopologyAppLink> appA;
  shared_ptr<TopologyAppLink> appC;
};

BOOST_AUTO_TEST_SUITE(Fw)
BOOST_FIXTURE_TEST_SUITE(TestAdHocForwarding, BaseFixture)

using Strategies = boost::mpl::vector<
  AsfStrategy,
  BestRouteStrategy2,
  MulticastStrategy
>;

BOOST_FIXTURE_TEST_CASE_TEMPLATE(SingleNexthop, S, Strategies,
                                 AdHocForwardingFixture<S>)
{
  // +---+---+
  // A   B   C
  //
  // A is the consumer. C is the producer.
  // B should relay Interest/Data between A and C.

  this->topo.registerPrefix(this->nodeB, *this->faceB, "/P");
  this->topo.addIntervalConsumer(this->appA->getClientFace(), "/P", time::milliseconds(100), 10);
  this->advanceClocks(time::milliseconds(5), time::milliseconds(1200));

  // Consumer should receive Data, and B should be relaying.
  BOOST_CHECK_EQUAL(this->faceB->getCounters().nInInterests, 10);
  BOOST_CHECK_EQUAL(this->faceB->getCounters().nOutInterests, 10);
  BOOST_CHECK_EQUAL(this->appC->getForwarderFace().getCounters().nOutInterests, 10);
  BOOST_CHECK_EQUAL(this->faceB->getCounters().nInData, 10);
  BOOST_CHECK_EQUAL(this->faceB->getCounters().nOutData, 10);
  BOOST_CHECK_EQUAL(this->appA->getForwarderFace().getCounters().nOutData, 10);
}

BOOST_FIXTURE_TEST_CASE_TEMPLATE(SecondNexthop, S, Strategies,
                                 AdHocForwardingFixture<S>)
{
  // +---+---+
  // A   B   C
  //     |
  //     D
  //
  // A is the consumer. C is the producer.
  // B's first nexthop is D, but B-D link has failed, so B should relay Interest/Data between A and C.

  TopologyNode nodeD = this->topo.addForwarder("D");
  shared_ptr<TopologyLink> linkBD = this->topo.addLink("BD", time::milliseconds(5), {this->nodeB, nodeD});
  this->topo.registerPrefix(this->nodeB, linkBD->getFace(this->nodeB), "/P", 5);
  linkBD->fail();
  this->topo.registerPrefix(this->nodeB, *this->faceB, "/P", 10);

  // Two interval consumers are expressing Interests with same name 40ms apart,
  // so that Interests from the second interval consumer are considered retransmission.
  this->topo.addIntervalConsumer(this->appA->getClientFace(), "/P", time::milliseconds(100), 50, 1);
  this->advanceClocks(time::milliseconds(5), time::milliseconds(40));
  this->topo.addIntervalConsumer(this->appA->getClientFace(), "/P", time::milliseconds(100), 50, 1);
  this->advanceClocks(time::milliseconds(5), time::milliseconds(5400));

  // Consumer should receive Data, and B should be relaying at least some Interest/Data.
  BOOST_CHECK_GE(this->faceB->getCounters().nInInterests, 50);
  BOOST_CHECK_GE(this->faceB->getCounters().nOutInterests, 25);
  BOOST_CHECK_GE(this->appC->getForwarderFace().getCounters().nOutInterests, 25);
  BOOST_CHECK_GE(this->faceB->getCounters().nInData, 25);
  BOOST_CHECK_GE(this->faceB->getCounters().nOutData, 25);
  BOOST_CHECK_GE(this->appA->getForwarderFace().getCounters().nOutData, 25);
}

BOOST_AUTO_TEST_SUITE_END() // TestAdHocForwarding
BOOST_AUTO_TEST_SUITE_END() // Fw

} // namespace tests
} // namespace fw
} // namespace nfd

max_stars_repo_name: NDNLink/NDN-Chord

max_issues_repo_name: NDNLink/NDN-Chord

max_forks_repo_name: NDNLink/NDN-Chord


text:
#ifndef MELON_CLIENT_DESKTOP_CONFIG_HPP_
#define MELON_CLIENT_DESKTOP_CONFIG_HPP_

#include <yaml-cpp/yaml.h>

#include <QColor>
#include <QFont>
#include <QString>

#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>

namespace melon::client_desktop
{

class UserConfigSingletone
{
public:
    [[nodiscard]] static UserConfigSingletone& get_instance()
    {
        static UserConfigSingletone instance;
        return instance;
    }

    UserConfigSingletone(const UserConfigSingletone& root) = delete;
    UserConfigSingletone& operator=(const UserConfigSingletone&) = delete;
    UserConfigSingletone(UserConfigSingletone&& root) = delete;
    UserConfigSingletone& operator=(UserConfigSingletone&&) = delete;

    class Appearance
    {
    public:
        friend class UserConfigSingletone;

        struct FontParams
        {
            QString family;
            int size;
            int weight;
        };

        enum class FontSize
        {
            SMALL,
            STANDARD,
            BIG
        };

        // Getters

        [[nodiscard]] FontSize message_font_size() const;
        [[nodiscard]] const FontParams& sender_font_params() const;
        [[nodiscard]] const FontParams& message_text_font_params() const;
        [[nodiscard]] const FontParams& timestamp_font_params() const;

        [[nodiscard]] const QColor& receive_message_color() const;
        [[nodiscard]] const QColor& sended_message_color() const;

        [[nodiscard]] FontSize chatlist_font_size() const;
        [[nodiscard]] const FontParams& chat_name_font_params() const;
        [[nodiscard]] const FontParams& chat_timestamp_font_params() const;
        [[nodiscard]] const FontParams& last_message_font_params() const;
        [[nodiscard]] const FontParams& last_message_sender_font_params() const;
        [[nodiscard]] const FontParams& unread_counter_font_params() const;

        [[nodiscard]] QColor selected_chat_color() const;
        [[nodiscard]] QColor unread_background_color() const;

        [[nodiscard]] const QString& font_family() const;

        // Setters

        void set_message_font_size_var(FontSize size);
        void set_message_font_size(FontSize size);
        void set_sender_font_params(const FontParams& pm);
        void set_message_text_font_params(const FontParams& pm);
        void set_timestamp_font_params(const FontParams& pm);

        void set_receive_message_color(const QColor& c);
        void set_sended_message_color(const QColor& c);

        void set_chatlist_font_size_var(FontSize size);
        void set_chatlist_font_size(FontSize size);
        void set_chat_name_font_params(const FontParams& pm);
        void set_chat_timestamp_font_params(const FontParams& pm);
        void set_last_message_font_params(const FontParams& pm);
        void set_unread_counter_font_params(const FontParams& pm);
        void set_last_message_sender_font_params(const FontParams& pm);

        void set_selected_chat_color(const QColor& c);
        void set_unread_background_color(const QColor& c);

        void set_font_family_common(const QString& family);
        void set_font_family_var(const QString& family);

    private:
        Appearance() = default;

        QString m_font_family;
        FontSize m_message_font_size;
        FontSize m_chatlist_font_size;

        // for message item delegate
        FontParams m_sender_font_params;
        FontParams m_message_text_font_params;
        FontParams m_timestamp_font_params;

        QColor m_receive_message_color;
        QColor m_sended_message_color;

        // for chat item delegate
        FontParams m_chat_name_font_params;
        FontParams m_chat_timestamp_font_params;
        FontParams m_last_message_font_params;
        FontParams m_unread_counter_font_params;
        FontParams m_last_message_sender_font_params;

        QColor m_selected_chat_color;
        QColor m_unread_background_color;
    };

    class Behaviour
    {
    public:
        friend class UserConfigSingletone;

        // Getters

        [[nodiscard]] bool remove_whitespaces_around() const;
        [[nodiscard]] bool replace_hyphens() const;
        [[nodiscard]] bool send_message_by_enter() const;

        // Setters

        void set_remove_whitespaces_around(bool new_config);
        void set_replace_hyphens(bool new_config);
        void set_send_message_by_enter(bool new_config);

    private:
        Behaviour() = default;

        bool m_remove_whitespaces_around_message;
        bool m_replace_hyphens;
        bool m_send_message_by_enter;
    };

    [[nodiscard]] Appearance& appearance();
    [[nodiscard]] const Appearance& appearance() const;

    [[nodiscard]] Behaviour& behaviour();
    [[nodiscard]] const Behaviour& behaviour() const;

private:
    UserConfigSingletone() = default;

    Appearance m_appearance;
    Behaviour m_behaviour;
};

class DevelopConfigSingletone
{
public:
    [[nodiscard]] static DevelopConfigSingletone& get_instance()
    {
        static DevelopConfigSingletone instance;
        return instance;
    }

    DevelopConfigSingletone(const DevelopConfigSingletone& root) = delete;
    DevelopConfigSingletone& operator=(const DevelopConfigSingletone&) = delete;
    DevelopConfigSingletone(DevelopConfigSingletone&& root) = delete;
    DevelopConfigSingletone& operator=(DevelopConfigSingletone&&) = delete;

    class Appearance
    {
    public:
        friend class DevelopConfigSingletone;

        [[nodiscard]] const QColor& selected_message_color() const;
        [[nodiscard]] int min_message_width() const;
        [[nodiscard]] qreal scale_message_width() const;
        [[nodiscard]] int base_margin() const;
        [[nodiscard]] int icon_diameter() const;
        [[nodiscard]] int message_round_radius() const;
        [[nodiscard]] int chat_base_margin() const;
        [[nodiscard]] int chat_icon_radius() const;
        [[nodiscard]] int unread_indicator_round() const;
        [[nodiscard]] const QColor& item_under_mouse_color() const;

    private:
        Appearance() = default;

        // for message item delegate
        const QColor m_selected_message_color{/*r*/30, /*g*/30, /*b*/90, /*a*/50};
        const int m_min_message_width = 120;
        const qreal m_scale_message_width = 0.75;

        const int m_base_margin = 5;
        const int m_icon_diameter = 30;
        const int m_message_round_radius = 10;

        // for chat item delegate
        const int m_chat_base_margin = 6;
        const int m_chat_icon_radius = 20;
        const int m_unread_indicator_round = 10;
        const QColor m_item_under_mouse_color{/*r*/230, /*g*/230, /*b*/230};
    };

    [[nodiscard]] Appearance& appearance();
    [[nodiscard]] const Appearance& appearance() const;

private:
    DevelopConfigSingletone() = default;

    Appearance m_appearance;
};

void save_settings_to_yaml();
void set_standart_settings();
void parse_settings(const YAML::Node& conf_file);

}  // namespace melon::client_desktop

#include "config.ipp"

#endif  // MELON_CLIENT_DESKTOP_CONFIG_HPP_