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

/// \copyright Copyright 2021 Apex.AI, Inc.
/// All rights reserved.

#ifndef STATE_ESTIMATION_NODES__KALMAN_FILTER_WRAPPER_HPP_
#define STATE_ESTIMATION_NODES__KALMAN_FILTER_WRAPPER_HPP_

#include <common/types.hpp>
#include <measurement_conversion/measurement_typedefs.hpp>
#include <nav_msgs/msg/odometry.hpp>
#include <state_estimation/kalman_filter/kalman_filter.hpp>
#include <state_estimation_nodes/filter_typedefs.hpp>
#include <state_estimation_nodes/history.hpp>
#include <state_estimation_nodes/steady_time_grid.hpp>
#include <state_estimation_nodes/visibility_control.hpp>
#include <state_vector/common_states.hpp>

#include <Eigen/Core>
#include <Eigen/Geometry>

#include <chrono>
#include <cstdint>
#include <limits>
#include <memory>
#include <string>
#include <vector>

namespace autoware
{
namespace common
{
namespace state_estimation
{

///
/// @brief      This class provides a high level interface to the Kalman Filter allowing to predict
///             the state of the filter with time and observe it by receiving ROS messages.
///
/// @tparam     FilterT           Type of filter used internally.
///
template<typename FilterT>
class STATE_ESTIMATION_NODES_PUBLIC KalmanFilterWrapper
{
  using HistoryT = History<
    FilterT,
    PredictionEvent,
    ResetEvent<FilterT>,
    PoseMeasurementXYZ32,
    PoseMeasurementXYZRPY32>;

public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
  using State = typename FilterT::State;

  ///
  /// @brief      Create an EKF wrapper.
  ///
  /// @param[in]  motion_model              The motion model that is to be used.
  /// @param[in]  noise_model               The noise model that is to be used.
  /// @param[in]  initial_state_covariance  The initial covariances for the state. This is usually a
  ///                                       diagonal matrix with sigmas squared for each state
  ///                                       dimension on the diagonal.
  /// @param[in]  expected_dt               Expected time difference between updates of the filter.
  /// @param[in]  frame_id                  The frame id in which tracking takes place.
  /// @param[in]  history_duration          Length of the history of events.
  /// @param[in]  mahalanobis_threshold     The threshold on the Mahalanobis distance for outlier
  ///                                       rejection.
  ///
  KalmanFilterWrapper(
    const typename FilterT::MotionModel motion_model,
    const typename FilterT::NoiseModel noise_model,
    const typename FilterT::State::Matrix initial_state_covariance,
    const std::chrono::nanoseconds & expected_dt,
    const std::string & frame_id,
    const std::chrono::nanoseconds & history_duration = std::chrono::milliseconds{5000},
    common::types::float32_t mahalanobis_threshold =
    std::numeric_limits<common::types::float32_t>::max())
  : m_initial_covariance{initial_state_covariance},
    m_frame_id{frame_id},
    m_mahalanobis_threshold{mahalanobis_threshold},
    m_expected_prediction_period{expected_dt},
    m_filter{
      motion_model,
      noise_model,
      State{},
      initial_state_covariance,
    },
    m_history{
      m_filter,
      static_cast<std::size_t>(history_duration / expected_dt),
      m_mahalanobis_threshold} {}

  ///
  /// Reset the filter state using the default covariance and state derived from the measurement.
  ///
  /// @param[in]  measurement   The measurement from which we initialize the state.
  ///
  /// @tparam     MeasurementT  Type of measurement.
  ///
  template<typename MeasurementT>
  inline void add_reset_event_to_history(const MeasurementT & measurement)
  {
    add_reset_event_to_history(
      measurement.measurement.map_into(State{}),
      m_initial_covariance,
      measurement.timestamp);
  }

  ///
  /// Reset the filter state. This must be called at least once to start / tracking.
  ///
  /// @param[in]  state               The full state to set the system to.
  /// @param[in]  initial_covariance  The initial covariance.
  /// @param[in]  event_timestamp     The event timestamp. Ideally this should be in the same clock
  ///                                 as the one that timestamps the messages.
  ///
  inline void add_reset_event_to_history(
    const State & state,
    const typename State::Matrix & initial_covariance,
    const std::chrono::system_clock::time_point & event_timestamp)
  {
    m_history.emplace_event(event_timestamp, ResetEvent<FilterT>{state, initial_covariance});
    m_time_grid = SteadyTimeGrid{event_timestamp, m_expected_prediction_period};
  }

  ///
  /// Predict state of filter at the next timestep defined by the period of this node.
  ///
  /// @return     true if the update was successful and false otherwise. In case false is returned,
  ///             this update had no effect on the state of the filter.
  ///
  inline common::types::bool8_t add_next_temporal_update_to_history()
  {
    if (!is_initialized()) {return false;}
    const auto next_prediction_timestamp =
      m_time_grid.get_next_timestamp_after(m_history.get_last_timestamp());
    m_history.emplace_event(next_prediction_timestamp, PredictionEvent{});
    return true;
  }

  ///
  /// Update the filter state with a measurement.
  ///
  /// @param[in]  measurement            The measurement. It is expected to be a concrete
  ///                                    instantiation of the Measurement class.
  ///
  /// @tparam     MeasurementT           Measurement type that is a concrete template specialization
  ///                                    of the Measurement class.
  ///
  /// @return     true if the observation was successful, false otherwise. In case of an
  ///             unsuccessful update, the state of the underlying filter has not been changed.
  ///
  template<typename MeasurementT>
  common::types::bool8_t add_observation_to_history(const MeasurementT & measurement)
  {
    if (!is_initialized()) {return false;}
    m_history.emplace_event(measurement.timestamp, measurement.measurement);
    return true;
  }

  /// Check if the filter is is_initialized with a state.
  inline common::types::bool8_t is_initialized() const noexcept
  {
    return (!m_history.empty()) && m_time_grid.is_initialized();
  }

  /// Get the current state of the system as an odometry message.
  nav_msgs::msg::Odometry get_state() const;

private:
  /// Initial covariance of the filter.
  typename State::Matrix m_initial_covariance{};
  /// Time represented in a frame based on the last measurement timestamp.
  SteadyTimeGrid m_time_grid{};
  /// Frame in which the estimation happens, e.g. "odom".
  std::string m_frame_id{};
  /// The threshold on the Mahalanobis distance used to reject outliers.
  common::types::float32_t m_mahalanobis_threshold{};
  /// What duration passes between prediction events.
  std::chrono::nanoseconds m_expected_prediction_period{};
  /// Wrapper owns the filter implementation.
  FilterT m_filter{};
  /// History of all events is stored here.
  HistoryT m_history{};
};

using ConstantAccelerationFilterWrapperXY =
  KalmanFilterWrapper<ConstAccelerationKalmanFilterXY>;

using ConstantAccelerationFilterWrapperXYZRPY =
  KalmanFilterWrapper<ConstAccelerationKalmanFilterXYZRPY>;

}  // namespace state_estimation
}  // namespace common
}  // namespace autoware

#endif  // STATE_ESTIMATION_NODES__KALMAN_FILTER_WRAPPER_HPP_

ext: hpp

max_stars_repo_name: ruvus/auto

max_issues_repo_name: ruvus/auto

max_forks_repo_name: ruvus/auto


text:
/////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Olaf Krzikalla 2004-2006.
// (C) Copyright Ion Gaztanaga  2006-2014
//
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_INTRUSIVE_LINEAR_SLIST_ALGORITHMS_HPP
#define BOOST_INTRUSIVE_LINEAR_SLIST_ALGORITHMS_HPP

#include <boost/intrusive/detail/config_begin.hpp>
#include <boost/intrusive/intrusive_fwd.hpp>
#include <boost/intrusive/detail/common_slist_algorithms.hpp>
#include <boost/intrusive/detail/algo_type.hpp>
#include <cstddef>
#include <boost/intrusive/detail/minimal_pair_header.hpp>   //std::pair

#if defined(BOOST_HAS_PRAGMA_ONCE)
#  pragma once
#endif

namespace boost {
namespace intrusive {

//! linear_slist_algorithms provides basic algorithms to manipulate nodes
//! forming a linear singly linked list.
//!
//! linear_slist_algorithms is configured with a NodeTraits class, which encapsulates the
//! information about the node to be manipulated. NodeTraits must support the
//! following interface:
//!
//! Typedefs:
//!
//! <tt>node</tt>: The type of the node that forms the linear list
//!
//! <tt>node_ptr</tt>: A pointer to a node
//!
//! <tt>const_node_ptr</tt>: A pointer to a const node
//!
//! Static functions:
//!
//! <tt>static node_ptr get_next(const_node_ptr n);</tt>
//!
//! <tt>static void set_next(node_ptr n, node_ptr next);</tt>
template<class NodeTraits>
class linear_slist_algorithms
   /// @cond
   : public detail::common_slist_algorithms<NodeTraits>
   /// @endcond
{
   /// @cond
   typedef detail::common_slist_algorithms<NodeTraits> base_t;
   /// @endcond
   public:
   typedef typename NodeTraits::node            node;
   typedef typename NodeTraits::node_ptr        node_ptr;
   typedef typename NodeTraits::const_node_ptr  const_node_ptr;
   typedef NodeTraits                           node_traits;

   #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)

   //! Effects: Constructs an non-used list element, putting the next
   //!   pointer to null:
   //!  <tt>NodeTraits::get_next(this_node) == node_ptr()</tt>
   //!
   //! Complexity: Constant
   //!
   //! Throws: Nothing.
   static void init(const node_ptr & this_node);

   //! Requires: this_node must be in a circular list or be an empty circular list.
   //!
   //! Effects: Returns true is "this_node" is the only node of a circular list:
   //!  or it's a not inserted node:
   //!  <tt>return node_ptr() == NodeTraits::get_next(this_node) || NodeTraits::get_next(this_node) == this_node</tt>
   //!
   //! Complexity: Constant
   //!
   //! Throws: Nothing.
   static bool unique(const_node_ptr this_node);

   //! Effects: Returns true is "this_node" has the same state as if
   //!  it was inited using "init(node_ptr)"
   //!
   //! Complexity: Constant
   //!
   //! Throws: Nothing.
   static bool inited(const_node_ptr this_node);

   //! Requires: prev_node must be in a circular list or be an empty circular list.
   //!
   //! Effects: Unlinks the next node of prev_node from the circular list.
   //!
   //! Complexity: Constant
   //!
   //! Throws: Nothing.
   static void unlink_after(const node_ptr & prev_node);

   //! Requires: prev_node and last_node must be in a circular list
   //!  or be an empty circular list.
   //!
   //! Effects: Unlinks the range (prev_node, last_node) from the linear list.
   //!
   //! Complexity: Constant
   //!
   //! Throws: Nothing.
   static void unlink_after(const node_ptr & prev_node, const node_ptr & last_node);

   //! Requires: prev_node must be a node of a linear list.
   //!
   //! Effects: Links this_node after prev_node in the linear list.
   //!
   //! Complexity: Constant
   //!
   //! Throws: Nothing.
   static void link_after(const node_ptr & prev_node, const node_ptr & this_node);

   //! Requires: b and e must be nodes of the same linear list or an empty range.
   //!   and p must be a node of a different linear list.
   //!
   //! Effects: Removes the nodes from (b, e] range from their linear list and inserts
   //!   them after p in p's linear list.
   //!
   //! Complexity: Constant
   //!
   //! Throws: Nothing.
   static void transfer_after(const node_ptr & p, const node_ptr & b, const node_ptr & e);

   #endif   //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)

   //! Effects: Constructs an empty list, making this_node the only
   //!   node of the circular list:
   //!  <tt>NodeTraits::get_next(this_node) == this_node</tt>.
   //!
   //! Complexity: Constant
   //!
   //! Throws: Nothing.
   static void init_header(const node_ptr & this_node)
   {  NodeTraits::set_next(this_node, node_ptr ());  }

   //! Requires: this_node and prev_init_node must be in the same linear list.
   //!
   //! Effects: Returns the previous node of this_node in the linear list starting.
   //!   the search from prev_init_node. The first node checked for equality
   //!   is NodeTraits::get_next(prev_init_node).
   //!
   //! Complexity: Linear to the number of elements between prev_init_node and this_node.
   //!
   //! Throws: Nothing.
   static node_ptr get_previous_node(const node_ptr & prev_init_node, const node_ptr & this_node)
   {  return base_t::get_previous_node(prev_init_node, this_node);   }

   //! Requires: this_node must be in a linear list or be an empty linear list.
   //!
   //! Effects: Returns the number of nodes in a linear list. If the linear list
   //!  is empty, returns 1.
   //!
   //! Complexity: Linear
   //!
   //! Throws: Nothing.
   static std::size_t count(const const_node_ptr & this_node)
   {
      std::size_t result = 0;
      const_node_ptr p = this_node;
      do{
         p = NodeTraits::get_next(p);
         ++result;
      } while (p);
      return result;
   }

   //! Requires: this_node and other_node must be nodes inserted
   //!  in linear lists or be empty linear lists.
   //!
   //! Effects: Moves all the nodes previously chained after this_node after other_node
   //!   and vice-versa.
   //!
   //! Complexity: Constant
   //!
   //! Throws: Nothing.
   static void swap_trailing_nodes(const node_ptr & this_node, const node_ptr & other_node)
   {
      node_ptr this_nxt    = NodeTraits::get_next(this_node);
      node_ptr other_nxt   = NodeTraits::get_next(other_node);
      NodeTraits::set_next(this_node, other_nxt);
      NodeTraits::set_next(other_node, this_nxt);
   }

   //! Effects: Reverses the order of elements in the list.
   //!
   //! Returns: The new first node of the list.
   //!
   //! Throws: Nothing.
   //!
   //! Complexity: This function is linear to the contained elements.
   static node_ptr reverse(const node_ptr & p)
   {
      if(!p) return node_ptr();
      node_ptr i = NodeTraits::get_next(p);
      node_ptr first(p);
      while(i){
         node_ptr nxti(NodeTraits::get_next(i));
         base_t::unlink_after(p);
         NodeTraits::set_next(i, first);
         first = i;
         i = nxti;
      }
      return first;
   }

   //! Effects: Moves the first n nodes starting at p to the end of the list.
   //!
   //! Returns: A pair containing the new first and last node of the list or
   //!   if there has been any movement, a null pair if n leads to no movement.
   //!
   //! Throws: Nothing.
   //!
   //! Complexity: Linear to the number of elements plus the number moved positions.
   static std::pair<node_ptr, node_ptr> move_first_n_backwards(const node_ptr & p, std::size_t n)
   {
      std::pair<node_ptr, node_ptr> ret;
      //Null shift, or count() == 0 or 1, nothing to do
      if(!n || !p || !NodeTraits::get_next(p)){
         return ret;
      }

      node_ptr first = p;
      bool end_found = false;
      node_ptr new_last = node_ptr();
      node_ptr old_last = node_ptr();

      //Now find the new last node according to the shift count.
      //If we find 0 before finding the new last node
      //unlink p, shortcut the search now that we know the size of the list
      //and continue.
      for(std::size_t i = 1; i <= n; ++i){
         new_last = first;
         first = NodeTraits::get_next(first);
         if(first == node_ptr()){
            //Shortcut the shift with the modulo of the size of the list
            n %= i;
            if(!n)   return ret;
            old_last = new_last;
            i = 0;
            //Unlink p and continue the new first node search
            first = p;
            //unlink_after(new_last);
            end_found = true;
         }
      }

      //If the p has not been found in the previous loop, find it
      //starting in the new first node and unlink it
      if(!end_found){
         old_last = base_t::get_previous_node(first, node_ptr());
      }

      //Now link p after the new last node
      NodeTraits::set_next(old_last, p);
      NodeTraits::set_next(new_last, node_ptr());
      ret.first   = first;
      ret.second  = new_last;
      return ret;
   }

   //! Effects: Moves the first n nodes starting at p to the beginning of the list.
   //!
   //! Returns: A pair containing the new first and last node of the list or
   //!   if there has been any movement, a null pair if n leads to no movement.
   //!
   //! Throws: Nothing.
   //!
   //! Complexity: Linear to the number of elements plus the number moved positions.
   static std::pair<node_ptr, node_ptr> move_first_n_forward(const node_ptr & p, std::size_t n)
   {
      std::pair<node_ptr, node_ptr> ret;
      //Null shift, or count() == 0 or 1, nothing to do
      if(!n || !p || !NodeTraits::get_next(p))
         return ret;

      node_ptr first  = p;

      //Iterate until p is found to know where the current last node is.
      //If the shift count is less than the size of the list, we can also obtain
      //the position of the new last node after the shift.
      node_ptr old_last(first), next_to_it, new_last(p);
      std::size_t distance = 1;
      while(!!(next_to_it = node_traits::get_next(old_last))){
         if(distance++ > n)
            new_last = node_traits::get_next(new_last);
         old_last = next_to_it;
      }
      //If the shift was bigger or equal than the size, obtain the equivalent
      //forward shifts and find the new last node.
      if(distance <= n){
         //Now find the equivalent forward shifts.
         //Shortcut the shift with the modulo of the size of the list
         std::size_t new_before_last_pos = (distance - (n % distance))% distance;
         //If the shift is a multiple of the size there is nothing to do
         if(!new_before_last_pos)
            return ret;

         for( new_last = p
            ; --new_before_last_pos
            ; new_last = node_traits::get_next(new_last)){
            //empty
         }
      }

      //Get the first new node
      node_ptr new_first(node_traits::get_next(new_last));
      //Now put the old beginning after the old end
      NodeTraits::set_next(old_last, p);
      NodeTraits::set_next(new_last, node_ptr());
      ret.first   = new_first;
      ret.second  = new_last;
      return ret;
   }
};

/// @cond

template<class NodeTraits>
struct get_algo<LinearSListAlgorithms, NodeTraits>
{
   typedef linear_slist_algorithms<NodeTraits> type;
};

/// @endcond

} //namespace intrusive
} //namespace boost

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

#endif //BOOST_INTRUSIVE_LINEAR_SLIST_ALGORITHMS_HPP

max_stars_repo_name: multi-os-engine/cinder-natj-binding

max_issues_repo_name: multi-os-engine/cinder-natj-binding

max_forks_repo_name: multi-os-engine/cinder-natj-binding


text:
#ifndef __TARGET_FIELD_HPP__
#define __TARGET_FIELD_HPP__ 1

#include <list>
#include <vector>
#include <Eigen/Dense>

class TargetField {
 public:
  const double ignore = -666.666;

  class Target {
   public:
    Target(
      const double p_value,
      const std::pair<double, double> p_coordinates
    );

    ~Target();

    double value() const;

    std::pair<double, double> coordinates() const;

   private:
    double value_;
    std::pair<double, double> coordinates_;
  };

  TargetField(
    const double p_x_size,
    const double p_y_size,
    const int p_num_cells
  );

  ~TargetField();

  TargetField& add_target(const Target& p_target);

  std::vector<Target> get_targets() const;

  Eigen::MatrixXd as_cells() const;

  std::pair<double, double> coordinates_of_cell(
    const int p_cell_x,
    const int p_cell_y
  ) const;

 private:
  int num_cells_;
  double x_size_;
  double y_size_;
  std::vector<Target> targets_;
};

#endif //__TARGET_FIELD_HPP__


text:
/*
*Author:GeneralSandman
*Code:https://github.com/GeneralSandman/TinyWeb
*E-mail:generalsandman@163.com
*Web:www.generalsandman.cn
*/

/*---XXX---
*
****************************************
*
*/

#include <tiny_core/timerqueue.h>
#include <tiny_core/timerid.h>
#include <tiny_core/eventloop.h>

#include <iostream>
#include <boost/bind.hpp>

using namespace std;

EventLoop *g_loop = nullptr;

int global_num1 = 0;
int global_num2 = 0;

TimerId timerid1, timerid2;

void fun1()
{
    cout << "[Timer1]:cout per second\n";
    global_num1++;
    if (global_num1 == 10)
    {
        cout << "[Timer1]:cancel Timer1\n";
        g_loop->cancelTimerId(timerid1);
    }
}

void fun2()
{
    cout << "[Timer2]:cout per two second\n";
    global_num2++;
    if (global_num2 == 5)
    {
        cout << "[Timer2]:cancel Timer2\n";
        g_loop->cancelTimerId(timerid2);
    }
}

void timeout()
{
    cout << "[Timer3]:13 seconds from main function started\n";
    cout << "[Timer3]:quit eventloop\n";
    g_loop->quit();
}

int main()
{
    g_loop = new EventLoop();
    timerid1 = g_loop->runEvery(1, boost::bind(fun1));
    timerid2 = g_loop->runEvery(2, boost::bind(fun2));

    if (timerid1.isVaild())
        std::cout << "timerid1 vaild\n";
    else
        std::cout << "timerid1 invaild\n";

    if (timerid2.isVaild())
        std::cout << "timerid2 vaild\n";
    else
        std::cout << "timerid2 invaild\n";

    std::cout << "after cancel timerid1 and timerid2\n";
    g_loop->cancelTimerId(timerid1);
    g_loop->cancelTimerId(timerid2);

    if (timerid1.isVaild())
        std::cout << "timerid1 vaild\n";
    else
        std::cout << "timerid1 invaild\n";

    if (timerid2.isVaild())
        std::cout << "timerid2 vaild\n";
    else
        std::cout << "timerid2 invaild\n";

    g_loop->runAfter(13, boost::bind(timeout));

    g_loop->loop();
    delete g_loop;
    return 0;
}

ext: cc


text:
#pragma once

#include <boost/detail/bitmask.hpp>
#include <comm/UWP/boost/path.hpp>

#if defined(_MSC_VER) // || (defined(__GLIBCXX__) && __GLIBCXX__ >= 20110325)
#  define BOOST_FILESYSTEM_STRICMP _stricmp
#else
#  define BOOST_FILESYSTEM_STRICMP strcmp
#endif

namespace mars_boost {}
namespace boost = mars_boost;
namespace mars_boost {
namespace filesystem {
enum file_type {
  status_error,
#   ifndef BOOST_FILESYSTEM_NO_DEPRECATED
  status_unknown = status_error,
#   endif
  file_not_found,
  regular_file,
  directory_file,
  // the following may not apply to some operating systems or file systems
  symlink_file,
  block_file,
  character_file,
  fifo_file,
  socket_file,
  reparse_file,  // Windows: FILE_ATTRIBUTE_REPARSE_POINT that is not a symlink
  type_unknown,  // file does exist, but isn't one of the above types or
  // we don't have strong enough permission to find its type

  _detail_directory_symlink  // internal use only; never exposed to users
};

enum perms {
  no_perms = 0,       // file_not_found is no_perms rather than perms_not_known

  // POSIX equivalent macros given in comments.
  // Values are from POSIX and are given in octal per the POSIX standard.

  // permission bits

  owner_read = 0400,  // S_IRUSR, Read permission, owner
  owner_write = 0200, // S_IWUSR, Write permission, owner
  owner_exe = 0100,   // S_IXUSR, Execute/search permission, owner
  owner_all = 0700,   // S_IRWXU, Read, write, execute/search by owner

  group_read = 040,   // S_IRGRP, Read permission, group
  group_write = 020,  // S_IWGRP, Write permission, group
  group_exe = 010,    // S_IXGRP, Execute/search permission, group
  group_all = 070,    // S_IRWXG, Read, write, execute/search by group

  others_read = 04,   // S_IROTH, Read permission, others
  others_write = 02,  // S_IWOTH, Write permission, others
  others_exe = 01,    // S_IXOTH, Execute/search permission, others
  others_all = 07,    // S_IRWXO, Read, write, execute/search by others

  all_all = 0777,     // owner_all|group_all|others_all

  // other POSIX bits

  set_uid_on_exe = 04000, // S_ISUID, Set-user-ID on execution
  set_gid_on_exe = 02000, // S_ISGID, Set-group-ID on execution
  sticky_bit = 01000, // S_ISVTX,
  // (POSIX XSI) On directories, restricted deletion flag
  // (V7) 'sticky bit': save swapped text even after use
  // (SunOS) On non-directories: don't cache this file
  // (SVID-v4.2) On directories: restricted deletion flag
  // Also see http://en.wikipedia.org/wiki/Sticky_bit

  perms_mask = 07777,     // all_all|set_uid_on_exe|set_gid_on_exe|sticky_bit

  perms_not_known = 0xFFFF, // present when directory_entry cache not loaded

  // options for permissions() function

  add_perms = 0x1000,     // adds the given permission bits to the current bits
  remove_perms = 0x2000,  // removes the given permission bits from the current bits;
  // choose add_perms or remove_perms, not both; if neither add_perms
  // nor remove_perms is given, replace the current bits with
  // the given bits.

  symlink_perms = 0x4000  // on POSIX, don't resolve symlinks; implied on Windows
};

BOOST_BITMASK(perms)

class file_status {
public:
  file_status() BOOST_NOEXCEPT
      : m_value(status_error), m_perms(perms_not_known) {}

  explicit file_status(file_type v) BOOST_NOEXCEPT
      : m_value(v), m_perms(perms_not_known) {}

  file_status(file_type v, perms prms) BOOST_NOEXCEPT
      : m_value(v), m_perms(prms) {}

  //  As of October 2015 the interaction between noexcept and =default is so troublesome
  //  for VC++, GCC, and probably other compilers, that =default is not used with noexcept
  //  functions. GCC is not even consistent for the same release on different platforms.

  file_status(const file_status& rhs) BOOST_NOEXCEPT
      : m_value(rhs.m_value), m_perms(rhs.m_perms) {}

  file_status& operator=(const file_status& rhs) BOOST_NOEXCEPT {
    m_value = rhs.m_value;
    m_perms = rhs.m_perms;
    return *this;
  }

  // observers
  file_type type() const BOOST_NOEXCEPT { return m_value; }

  perms permissions() const BOOST_NOEXCEPT { return m_perms; }

  // modifiers
  void type(file_type v) BOOST_NOEXCEPT { m_value = v; }

  void permissions(perms prms) BOOST_NOEXCEPT { m_perms = prms; }

  bool operator==(const file_status& rhs) const BOOST_NOEXCEPT {
    return type() == rhs.type() &&
           permissions() == rhs.permissions();
  }

  bool operator!=(const file_status& rhs) const BOOST_NOEXCEPT {
    return !(*this == rhs);
  }

private:
  file_type m_value;
  enum perms m_perms;
};

struct handle_wrapper {
  HANDLE handle;

  handle_wrapper(HANDLE h)
      : handle(h) {}

  ~handle_wrapper() {
    if (handle != INVALID_HANDLE_VALUE)
      CloseHandle(handle);
  }
};

inline
perms make_permissions(const path& p, DWORD attr) {
  perms prms = perms::owner_read | perms::group_read | perms::others_read;
  if ((attr & FILE_ATTRIBUTE_READONLY) == 0)
    prms |= perms::owner_write | perms::group_write | perms::others_write;
  if (BOOST_FILESYSTEM_STRICMP(p.extension().string().c_str(), ".exe") == 0
      || BOOST_FILESYSTEM_STRICMP(p.extension().string().c_str(), ".com") == 0
      || BOOST_FILESYSTEM_STRICMP(p.extension().string().c_str(), ".bat") == 0
      || BOOST_FILESYSTEM_STRICMP(p.extension().string().c_str(), ".cmd") == 0)
    prms |= perms::owner_exe | perms::group_exe | perms::others_exe;
  return prms;
}

inline
file_status status(const path& p) {
  std::wstring ws = p.wstring();
  WIN32_FILE_ATTRIBUTE_DATA fad;
  BOOL ret = GetFileAttributesExW(ws.c_str(), GetFileExInfoStandard, &fad);
  if (ret != TRUE) {
    return file_status(file_not_found, no_perms);
  }

  DWORD attr = fad.dwFileAttributes;
  if (attr == 0xFFFFFFFF) {
    return file_status(file_not_found, no_perms);
  }

  return (attr & FILE_ATTRIBUTE_DIRECTORY)
         ? file_status(directory_file, make_permissions(p, attr))
         : file_status(regular_file, make_permissions(p, attr));
}

inline
bool is_directory(const path& p) {
  file_status f = status(p);
  return f.type() == directory_file;
}

inline
bool is_directory(file_status f) {
  return f.type() == directory_file;
}

inline
bool is_regular_file(file_status f) {
  return f.type() == regular_file;
}

inline
bool exists(const path& p) {
  file_status f = status(p);
  return f.type() != status_error && f.type() != file_not_found;
}

inline
mars_boost::uintmax_t file_size(const path& p) {
  std::wstring ws = p.wstring();
  WIN32_FILE_ATTRIBUTE_DATA fad;
  BOOL ret = GetFileAttributesExW(ws.c_str(), GetFileExInfoStandard, &fad);
  if (ret != TRUE) {
    return static_cast<mars_boost::uintmax_t>(-1);
  }

  if (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
    return static_cast<mars_boost::uintmax_t>(-1);
  }

  return (static_cast<mars_boost::uintmax_t>(fad.nFileSizeHigh)
      << (sizeof(fad.nFileSizeLow) * 8)) + fad.nFileSizeLow;
}

inline
std::time_t to_time_t(const FILETIME& ft) {
  __int64 t = (static_cast<__int64>(ft.dwHighDateTime) << 32)
              + ft.dwLowDateTime;
#   if !defined(BOOST_MSVC) || BOOST_MSVC > 1300 // > VC++ 7.0
  t -= 116444736000000000LL;
#   else
  t -= 116444736000000000;
#   endif
  t /= 10000000;
  return static_cast<std::time_t>(t);
}

inline
std::time_t last_write_time(const path& p) {
  CREATEFILE2_EXTENDED_PARAMETERS para;
  para.dwFileAttributes = NULL;
  para.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS;
  para.dwSecurityQosFlags = SECURITY_ANONYMOUS; // for windows store app
  para.lpSecurityAttributes = NULL;
  para.hTemplateFile = NULL;

  std::wstring ws = p.wstring();

  handle_wrapper hw(
      CreateFile2(ws.c_str(), GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING,
                  &para));

  if (hw.handle == INVALID_HANDLE_VALUE) {
    return std::time_t(-1);
  }

  FILETIME lwt;
  BOOL ret = GetFileTime(hw.handle, 0, 0, &lwt);
  return ret == TRUE ? to_time_t(lwt) : std::time_t(-1);
}

inline
bool remove(const path& p) {
  bool isSucc = false;
  file_status f = status(p);
  if (f.type() == status_error || f.type() == file_not_found) {
    return isSucc;
  }

  std::wstring ws = p.wstring();
  if (f.type() == directory_file || f.type() == _detail_directory_symlink) {
    if (RemoveDirectoryW(ws.c_str()) == TRUE)
      isSucc = true;
  } else {
    if (DeleteFileW(ws.c_str()) == TRUE)
      isSucc = true;
  }

  return isSucc;
}

inline
bool create_directory(const path& p) {
  std::wstring ws = p.wstring();
  bool ret = CreateDirectoryW(ws.c_str(), NULL);
  return ret == TRUE ? true : false;
}

inline
bool create_directories(const path& p) {
  path filename(p.filename());
  if ((filename.native().size() == 1 && filename.native()[0] == '.')
      || (filename.native().size() == 2
          && filename.native()[0] == '.' && filename.native()[1] == '.'))
    return create_directories(p.parent_path());

  file_status p_status = status(p);
  if (p_status.type() == directory_file) {
    return false;
  }

  path parent = p.parent_path();
  if (!parent.empty()) {
    file_status parent_status = status(parent);
    if (parent_status.type() == file_not_found) {
      if (!create_directories(parent))
        return false;
    }
  }

  return create_directory(p);
}

inline
std::string wstring_to_string(const std::wstring& ws) {
  if (ws.empty())
    return std::string("");

  int size = WideCharToMultiByte(CP_ACP, 0, ws.c_str(), ws.length(), NULL, 0, NULL, NULL);
  if (size <= 0)
    return std::string("");

  char* pszDst = new char[size + 1];
  if (pszDst == NULL)
    return std::string("");

  memset(pszDst, 0, (size + 1) * sizeof(char));
  WideCharToMultiByte(CP_ACP, 0, ws.c_str(), ws.length(), pszDst, size, NULL, NULL);

  std::string str(pszDst);
  delete[] pszDst;

  return str;
}

inline
void dir_itr_close(void*& handle) {
  if (handle != 0) {
    FindClose(handle);
    handle = 0;
  }
}

class directory_entry {
public:

  directory_entry() {}

  explicit directory_entry(const mars_boost::filesystem::path& p)
      : m_path(p), m_status(file_status()), m_symlink_status(file_status()) {}

  directory_entry(const mars_boost::filesystem::path& p,
                  file_status st, file_status symlink_st = file_status())
      : m_path(p), m_status(st), m_symlink_status(symlink_st) {}

  directory_entry(const directory_entry& rhs)
      : m_path(rhs.m_path), m_status(rhs.m_status), m_symlink_status(rhs.m_symlink_status) {}

  directory_entry& operator=(const directory_entry& rhs) {
    m_path = rhs.m_path;
    m_status = rhs.m_status;
    m_symlink_status = rhs.m_symlink_status;
    return *this;
  }

  void assign(const mars_boost::filesystem::path& p,
              file_status st = file_status(), file_status symlink_st = file_status()) {
    m_path = p;
    m_status = st;
    m_symlink_status = symlink_st;
  }

  void replace_filename(const mars_boost::filesystem::path& p,
                        file_status st = file_status(), file_status symlink_st = file_status()) {
    m_path.remove_filename();
    m_path /= p;
    m_status = st;
    m_symlink_status = symlink_st;
  }

  const mars_boost::filesystem::path& path() const { return m_path; }

  operator const mars_boost::filesystem::path&() const { return m_path; }

  file_status status() const {
    m_status = mars_boost::filesystem::status(m_path);
    return m_status;
  }

  file_status symlink_status() const { return m_symlink_status; }

  bool operator==(const directory_entry& rhs) const { return m_path.string().compare(rhs.path().string()) == 0; }

  bool operator!=(const directory_entry& rhs) const { return m_path.string().compare(rhs.path().string()) != 0; }

private:
  mars_boost::filesystem::path m_path;
  mutable file_status m_status;
  mutable file_status m_symlink_status;
};

struct dir_itr_imp {
  directory_entry dir_entry;
  void* handle;

  dir_itr_imp() : handle(0) {}

  ~dir_itr_imp() {
    dir_itr_close(handle);
  }
};

class directory_iterator {
private:
  mars_boost::shared_ptr<dir_itr_imp> m_imp;

  bool dir_itr_first(void*& handle, const path& dir, std::string& target, file_status& sf, file_status& symlink_sf) {
    std::wstring dirpath(dir.wstring());
    dirpath += (dirpath.empty()
                || (dirpath[dirpath.size() - 1] != L'\\'
                    && dirpath[dirpath.size() - 1] != L'/'
                    && dirpath[dirpath.size() - 1] != L':')) ? L"\\*" : L"*";

    WIN32_FIND_DATAW data;
    if ((handle = FindFirstFileExW(dirpath.c_str(), FindExInfoStandard, &data, FindExSearchNameMatch, NULL, 0)) ==
        INVALID_HANDLE_VALUE) {
      handle = 0;  // signal eof
      return false;
    }
    target = wstring_to_string(data.cFileName);
    if (data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
      sf.type(status_error);
      symlink_sf.type(status_error);
      return false;
    } else {
      if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
        sf.type(directory_file);
        symlink_sf.type(directory_file);
      } else {
        sf.type(regular_file);
        symlink_sf.type(regular_file);
      }
      sf.permissions(make_permissions(target, data.dwFileAttributes));
      symlink_sf.permissions(sf.permissions());
    }
    return true;
  }

  bool dir_itr_increment(void*& handle, std::string& target, file_status& sf, file_status& symlink_sf) {
    WIN32_FIND_DATAW data;
    if (FindNextFileW(handle, &data) == 0)// fails
    {
      dir_itr_close(handle);
      return false;
    }
    target = wstring_to_string(data.cFileName);
    if (data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
      sf.type(status_error);
      symlink_sf.type(status_error);
      return false;
    } else {
      if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
        sf.type(directory_file);
        symlink_sf.type(directory_file);
      } else {
        sf.type(regular_file);
        symlink_sf.type(regular_file);
      }
      sf.permissions(make_permissions(target, data.dwFileAttributes));
      symlink_sf.permissions(sf.permissions());
    }
    return true;
  }

  void directory_iterator_construct(directory_iterator& it, const path& p) {
    if (p.empty())
      return;

    string_type filename;
    file_status file_stat, symlink_file_stat;
    bool result = dir_itr_first(it.m_imp->handle, p, filename, file_stat, symlink_file_stat);

    if (!result) {
      it.m_imp.reset();
      return;
    }

    if (it.m_imp->handle == 0)
      it.m_imp.reset(); // eof, so make end iterator
    else // not eof
    {
      mars_boost::filesystem::path np(p);
      np /= filename;
      it.m_imp->dir_entry.assign(np, file_stat, symlink_file_stat);
      if (filename[0] == '.' // dot or dot-dot
          && (filename.size() == 1
              || (filename[1] == '.'
                  && filename.size() == 2))) {
        directory_iterator_increment(it);
      }
    }
  }

  void directory_iterator_increment(directory_iterator& it) {
    if (!it.m_imp.get())
      return;

    if (it.m_imp->handle == 0) {
      m_imp.reset();
      return;
    }

    string_type filename;
    file_status file_stat, symlink_file_stat;
    bool result;

    for (;;) {
      result = dir_itr_increment(it.m_imp->handle, filename, file_stat, symlink_file_stat);

      if (!result)  // happens if filesystem is corrupt, such as on a damaged optical disc
      {
        mars_boost::filesystem::path error_path(it.m_imp->dir_entry.path().parent_path());  // fix ticket #5900
        it.m_imp.reset();
        return;
      }

      if (it.m_imp->handle == 0)  // eof, make end
      {
        it.m_imp.reset();
        return;
      }

      if (!(filename[0] == '.' // !(dot or dot-dot)
            && (filename.size() == 1
                || (filename[1] == '.'
                    && filename.size() == 2)))) {
        it.m_imp->dir_entry.replace_filename(
            filename, file_stat, symlink_file_stat);
        return;
      }
    }
  }

public:
  directory_iterator() {}

  explicit directory_iterator(const path& p) : m_imp(new dir_itr_imp) {
    directory_iterator_construct(*this, p);
  }

  ~directory_iterator() {
    if (m_imp.get())
      m_imp.reset();
  }

  directory_iterator* operator->() {
    return this;
  }

  directory_iterator& operator++() {
    directory_iterator_increment(*this);
    return *this;
  }

  bool operator==(const directory_iterator& other) const {
    if (m_imp.get() && other.m_imp.get()) {
      return m_imp->dir_entry == other.m_imp->dir_entry;
    } else if (!m_imp.get() && !other.m_imp.get()) {
      return true;
    } else {
      return false;
    }
  }

  bool operator!=(const directory_iterator& other) const {
    if (m_imp.get() && other.m_imp.get()) {
      return m_imp->dir_entry != other.m_imp->dir_entry;
    } else if (!m_imp.get() && !other.m_imp.get()) {
      return false;
    } else {
      return true;
    }
  }

  path path() {
    return m_imp.get() ? m_imp->dir_entry.path() : mars_boost::filesystem::path();
  }

  file_status status() {
    return m_imp.get() ? m_imp->dir_entry.status() : file_status();
  }
};
}
}

max_stars_repo_name: habbyge/mars

max_issues_repo_name: habbyge/mars

max_forks_repo_name: habbyge/mars


text:
/**
 * Copyright (c) 2018, University Osnabrück
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the University Osnabrück nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL University Osnabrück BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * ScanprojectIO.hpp
 *
 *  @date 01.11.2018
 *  @author Alexander Loehr (aloehr@uos.de)
 */

#ifndef LVR2_IO_SCANPROJECTIO_HPP
#define LVR2_IO_SCANPROJECTIO_HPP

#include <lvr2/io/BaseIO.hpp>
#include <lvr2/geometry/Matrix4.hpp>
#include <lvr2/geometry/BaseVector.hpp>

#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;

namespace lvr2
{

using Vec = BaseVector<float>;

/**
 * @brief A struct that holds information for an image
 */
struct ImageFile
{
    /// transformation matrix
    Matrix4<Vec> orientation_transform;
    /// transformation matrix
    Matrix4<Vec> extrinsic_transform;

    /// path to image
    fs::path image_file;

    /// intrinsic parameters in this order: fx, fy, Cx, Cy
    float intrinsic_params[4];

    /// distortion params in this order: k1, k2, k3, k4, p1, p2
    float distortion_params[6];
};

/**
 * @brief A struct that holds information for a scan position.
 */
struct ScanPosition
{
    /// file path for pointcloud data
    fs::path               scan_file;
    /// transformation  matrix from scan position space to scan project space
    Matrix4<Vec>           transform;
    /// a vector with image informations for this scanposition
    std::vector<ImageFile> images;
};

/**
 * @brief A struct that holds information for an UOS Scanproject
 */
struct Scanproject
{
    /// directory with calibration information
    fs::path calib_dir;
    /// directory with image data
    fs::path img_dir;
    /// directory with scan data
    fs::path scans_dir;
    /// A vector with ScanPositions that are part of this scan project
    std::vector<ScanPosition> scans;
};

/**
 * @brief Class for reading/writing and parsing a UOS Scanproject directory.
 */
class ScanprojectIO : public BaseIO
{
    public:

        /**
         * @brief Reads the giving directory as an UOS Scanproject directory and
         * return a ModelPtr with the read data.
         *
         * @param dir the path to the UOS Scanproject directory
         *
         * @return a ModelPtr with the data read from dir
         */
        ModelPtr read(std::string dir);

        /**
         * @brief Saving UOS Scanprojects is currently not supported.
         */
        void save(std::string dir);

        /**
         * @brief Parses a directory as an UOS Scanproject
         *
         * @param dir The directory path
         *
         * @param silent Suppresses any error messages while parsing the directory. This is usefull
         *               if you only want to figure out if the directory is a valid UOS Scanproject
         *               directory and aren't interested in any warnings if it isn't one.
         *
         * @return Returns true if it successfully parsed an UOS Scanproject and elsewise false.
         */
        bool parse_project(const std::string& dir, bool silent = false);

        /**
         * @brief Returns the parsed UOS Scanproject
         *
         * @return Returns the parsed UOS Scanproject in an Scanproject struct
         *         if parse_project(...) was executed before and returned true
         *         else it will return an empty Scanproject struct.
         */
        Scanproject& get_project();

    private:

        /// @cond internal
        template<typename ValueType>
        bool load_params_from_file(ValueType *buf, const fs::path &src, unsigned int count);
        bool exists_and_is_dir(const fs::path &dir, bool silent);
        fs::path project_dir;
        Scanproject project;
        /// @endcond internal
};

} // namespace lvr2

#endif


text:
#ifndef GENERATORS_BASE_H
#define GENERATORS_BASE_H

#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/karma_right_alignment.hpp>
#include <boost/spirit/include/karma_symbols.hpp>

//#include <boost/spirit/include/karma_int.hpp>
//#include <boost/spirit/include/phoenix_core.hpp>
//#include <boost/spirit/include/phoenix_operator.hpp>

#include <string>

namespace generators
{
    namespace karma = boost::spirit::karma;
    namespace spirit = boost::spirit;
    namespace ascii = boost::spirit::ascii;
    using spirit::long_;
    using spirit::float_;
    using spirit::right_align;

    bool long_to_string(std::string &str,long number);
    bool float_to_string(std::string &str,float number);
}

namespace gen = generators;

#endif


text:
/**
 * Cloud Manager API
 * This API allows access to Cloud Manager programs, pipelines, and environments by an authorized technical account created through the Adobe I/O Console. The base url for this API is https://cloudmanager.adobe.io, e.g. to get the list of programs for an organization, you would make a GET request to https://cloudmanager.adobe.io/api/programs (with the correct set of headers as described below). This swagger file can be downloaded from https://raw.githubusercontent.com/AdobeDocs/cloudmanager-api-docs/master/swagger-specs/api.yaml.
 *
 * The version of the OpenAPI document: 1.0.0
 * Contact: opensource@shinesolutions.com
 *
 * NOTE: This class is auto generated by OpenAPI-Generator 4.3.1-SNAPSHOT.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

#include "Environment__links.h"

#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree;
using boost::property_tree::read_json;
using boost::property_tree::write_json;

namespace org {
namespace openapitools {
namespace server {
namespace model {

Environment__links::Environment__links()
{
}

Environment__links::~Environment__links()
{
}

std::string Environment__links::toJsonString(bool prettyJson)
{
	std::stringstream ss;
	write_json(ss, this->toPropertyTree(), prettyJson);
	return ss.str();
}

void Environment__links::fromJsonString(std::string const& jsonString)
{
	std::stringstream ss(jsonString);
	ptree pt;
	read_json(ss,pt);
	this->fromPropertyTree(pt);
}

ptree Environment__links::toPropertyTree()
{
	ptree pt;
	ptree tmp_node;
	if (m_Http__ns_adobe_com_adobecloud_rel_program != nullptr) {
		pt.add_child("http://ns.adobe.com/adobecloud/rel/program", m_Http__ns_adobe_com_adobecloud_rel_program->toPropertyTree());
	}
	if (m_Http__ns_adobe_com_adobecloud_rel_pipeline != nullptr) {
		pt.add_child("http://ns.adobe.com/adobecloud/rel/pipeline", m_Http__ns_adobe_com_adobecloud_rel_pipeline->toPropertyTree());
	}
	if (m_Http__ns_adobe_com_adobecloud_rel_author != nullptr) {
		pt.add_child("http://ns.adobe.com/adobecloud/rel/author", m_Http__ns_adobe_com_adobecloud_rel_author->toPropertyTree());
	}
	if (m_Http__ns_adobe_com_adobecloud_rel_publish != nullptr) {
		pt.add_child("http://ns.adobe.com/adobecloud/rel/publish", m_Http__ns_adobe_com_adobecloud_rel_publish->toPropertyTree());
	}
	if (m_Http__ns_adobe_com_adobecloud_rel_developerConsole != nullptr) {
		pt.add_child("http://ns.adobe.com/adobecloud/rel/developerConsole", m_Http__ns_adobe_com_adobecloud_rel_developerConsole->toPropertyTree());
	}
	if (m_Http__ns_adobe_com_adobecloud_rel_logs != nullptr) {
		pt.add_child("http://ns.adobe.com/adobecloud/rel/logs", m_Http__ns_adobe_com_adobecloud_rel_logs->toPropertyTree());
	}
	if (m_Http__ns_adobe_com_adobecloud_rel_variables != nullptr) {
		pt.add_child("http://ns.adobe.com/adobecloud/rel/variables", m_Http__ns_adobe_com_adobecloud_rel_variables->toPropertyTree());
	}
	if (m_Self != nullptr) {
		pt.add_child("self", m_Self->toPropertyTree());
	}
	return pt;
}

void Environment__links::fromPropertyTree(ptree const &pt)
{
	ptree tmp_node;
	if (pt.get_child_optional("http://ns.adobe.com/adobecloud/rel/program")) {
		m_Http__ns_adobe_com_adobecloud_rel_program = std::make_shared<HalLink>();
		m_Http__ns_adobe_com_adobecloud_rel_program->fromPropertyTree(pt.get_child("http://ns.adobe.com/adobecloud/rel/program"));
	}
	if (pt.get_child_optional("http://ns.adobe.com/adobecloud/rel/pipeline")) {
		m_Http__ns_adobe_com_adobecloud_rel_pipeline = std::make_shared<HalLink>();
		m_Http__ns_adobe_com_adobecloud_rel_pipeline->fromPropertyTree(pt.get_child("http://ns.adobe.com/adobecloud/rel/pipeline"));
	}
	if (pt.get_child_optional("http://ns.adobe.com/adobecloud/rel/author")) {
		m_Http__ns_adobe_com_adobecloud_rel_author = std::make_shared<HalLink>();
		m_Http__ns_adobe_com_adobecloud_rel_author->fromPropertyTree(pt.get_child("http://ns.adobe.com/adobecloud/rel/author"));
	}
	if (pt.get_child_optional("http://ns.adobe.com/adobecloud/rel/publish")) {
		m_Http__ns_adobe_com_adobecloud_rel_publish = std::make_shared<HalLink>();
		m_Http__ns_adobe_com_adobecloud_rel_publish->fromPropertyTree(pt.get_child("http://ns.adobe.com/adobecloud/rel/publish"));
	}
	if (pt.get_child_optional("http://ns.adobe.com/adobecloud/rel/developerConsole")) {
		m_Http__ns_adobe_com_adobecloud_rel_developerConsole = std::make_shared<HalLink>();
		m_Http__ns_adobe_com_adobecloud_rel_developerConsole->fromPropertyTree(pt.get_child("http://ns.adobe.com/adobecloud/rel/developerConsole"));
	}
	if (pt.get_child_optional("http://ns.adobe.com/adobecloud/rel/logs")) {
		m_Http__ns_adobe_com_adobecloud_rel_logs = std::make_shared<HalLink>();
		m_Http__ns_adobe_com_adobecloud_rel_logs->fromPropertyTree(pt.get_child("http://ns.adobe.com/adobecloud/rel/logs"));
	}
	if (pt.get_child_optional("http://ns.adobe.com/adobecloud/rel/variables")) {
		m_Http__ns_adobe_com_adobecloud_rel_variables = std::make_shared<HalLink>();
		m_Http__ns_adobe_com_adobecloud_rel_variables->fromPropertyTree(pt.get_child("http://ns.adobe.com/adobecloud/rel/variables"));
	}
	if (pt.get_child_optional("self")) {
		m_Self = std::make_shared<HalLink>();
		m_Self->fromPropertyTree(pt.get_child("self"));
	}
}

std::shared_ptr<HalLink> Environment__links::getHttpNsAdobeComAdobecloudRelProgram() const
{
    return m_Http__ns_adobe_com_adobecloud_rel_program;
}
void Environment__links::setHttpNsAdobeComAdobecloudRelProgram(std::shared_ptr<HalLink> value)
{
	m_Http__ns_adobe_com_adobecloud_rel_program = value;
}
std::shared_ptr<HalLink> Environment__links::getHttpNsAdobeComAdobecloudRelPipeline() const
{
    return m_Http__ns_adobe_com_adobecloud_rel_pipeline;
}
void Environment__links::setHttpNsAdobeComAdobecloudRelPipeline(std::shared_ptr<HalLink> value)
{
	m_Http__ns_adobe_com_adobecloud_rel_pipeline = value;
}
std::shared_ptr<HalLink> Environment__links::getHttpNsAdobeComAdobecloudRelAuthor() const
{
    return m_Http__ns_adobe_com_adobecloud_rel_author;
}
void Environment__links::setHttpNsAdobeComAdobecloudRelAuthor(std::shared_ptr<HalLink> value)
{
	m_Http__ns_adobe_com_adobecloud_rel_author = value;
}
std::shared_ptr<HalLink> Environment__links::getHttpNsAdobeComAdobecloudRelPublish() const
{
    return m_Http__ns_adobe_com_adobecloud_rel_publish;
}
void Environment__links::setHttpNsAdobeComAdobecloudRelPublish(std::shared_ptr<HalLink> value)
{
	m_Http__ns_adobe_com_adobecloud_rel_publish = value;
}
std::shared_ptr<HalLink> Environment__links::getHttpNsAdobeComAdobecloudRelDeveloperConsole() const
{
    return m_Http__ns_adobe_com_adobecloud_rel_developerConsole;
}
void Environment__links::setHttpNsAdobeComAdobecloudRelDeveloperConsole(std::shared_ptr<HalLink> value)
{
	m_Http__ns_adobe_com_adobecloud_rel_developerConsole = value;
}
std::shared_ptr<HalLink> Environment__links::getHttpNsAdobeComAdobecloudRelLogs() const
{
    return m_Http__ns_adobe_com_adobecloud_rel_logs;
}
void Environment__links::setHttpNsAdobeComAdobecloudRelLogs(std::shared_ptr<HalLink> value)
{
	m_Http__ns_adobe_com_adobecloud_rel_logs = value;
}
std::shared_ptr<HalLink> Environment__links::getHttpNsAdobeComAdobecloudRelVariables() const
{
    return m_Http__ns_adobe_com_adobecloud_rel_variables;
}
void Environment__links::setHttpNsAdobeComAdobecloudRelVariables(std::shared_ptr<HalLink> value)
{
	m_Http__ns_adobe_com_adobecloud_rel_variables = value;
}
std::shared_ptr<HalLink> Environment__links::getSelf() const
{
    return m_Self;
}
void Environment__links::setSelf(std::shared_ptr<HalLink> value)
{
	m_Self = value;
}

}
}
}
}

ext: cpp

max_stars_repo_name: shinesolutions/cloudmanager-api-clients

max_issues_repo_name: shinesolutions/cloudmanager-api-clients

max_forks_repo_name: shinesolutions/cloudmanager-api-clients


text:
#pragma once

#include <boost/asio.hpp>

#include "output_writer.hpp"
#include "params.hpp"

namespace metrics {

  class MetricsUDPSender;
  class StatsdTagger;

  /**
   * A StatsdOutputWriter accepts data from one or more ContainerReaders, then tags and forwards it
   * to an external statsd endpoint. The data may be buffered into chunks before being sent out --
   * statsd supports separating multiple metrics by newlines.
   * In practice, there is one singleton StatsdOutputWriter instance per mesos-slave.
   */
  class StatsdOutputWriter : public OutputWriter {
   public:
    /**
     * Default maximum time to wait before sending a pending chunk.
     * Statsd messages are time-sensitive so don't sit on them too long, at most a second or so.
     */
    const static size_t DEFAULT_CHUNK_TIMEOUT_MS = 1000;

    /**
     * Creates a StatsdOutputWriter which shares the provided io_service for async operations.
     * Additional arguments are exposed here to allow customization in unit tests.
     *
     * start() must be called before write()ing data, or else that data will be lost.
     */
    static output_writer_ptr_t create(
        std::shared_ptr<boost::asio::io_service> io_service,
        const mesos::Parameters& parameters);

    /**
     * Use create(). This is meant for access by tests.
     */
    StatsdOutputWriter(
        std::shared_ptr<boost::asio::io_service> io_service,
        const mesos::Parameters& parameters,
        std::shared_ptr<MetricsUDPSender> sender,
        size_t chunk_timeout_ms_for_tests = DEFAULT_CHUNK_TIMEOUT_MS);

    virtual ~StatsdOutputWriter();

    /**
     * Starts internal timers for flushing data and refreshing the host.
     */
    void start();

    /**
     * Outputs the provided statsd message associated with the given container information, or NULL
     * container information if none is available. The provided data should only be for a single
     * statsd message. Multiline payloads should be passed individually.
     */
    void write_container_statsd(
        const mesos::ContainerID* container_id, const mesos::ExecutorInfo* executor_info,
        const char* data, size_t size);

    void write_resource_usage(const process::Future<mesos::ResourceUsage>& usage);

   private:
    void start_chunk_flush_timer();
    void chunk_flush_cb(boost::system::error_code ec);

    void shutdown_cb();

    const bool chunking;
    const size_t chunk_capacity;
    const size_t chunk_timeout_ms;

    std::shared_ptr<boost::asio::io_service> io_service;
    boost::asio::deadline_timer flush_timer;
    char* output_buffer;
    size_t chunk_used;

    std::shared_ptr<MetricsUDPSender> sender;
    std::shared_ptr<StatsdTagger> tagger;
  };

}

max_stars_repo_name: samvantran/dcos-metrics

max_issues_repo_name: samvantran/dcos-metrics

max_forks_repo_name: samvantran/dcos-metrics


text:
/*****************************************************************************
Program: getJPEGimg.cpp reads a jpeg image using the boost library.
Compile:
g++ getJPEGimg.cpp -o getJPGimg -g -Wall -std=c++0x /usr/lib64/libjpeg.so.62
*****************************************************************************/
#include <iostream>
#include <boost/gil/extension/io/jpeg_io.hpp>
namespace gil = boost::gil;

int main() {
	gil::rgb8_image_t img;
	gil::jpeg_read_image("red.jpg", img);
	std::cout << "Read complete, got an image " << img.width() << "by" << img.height() << " pixels\n";

	return 0;
}


text:
/*
 * drakeUtil.cpp
 *
 *  Created on: Jun 19, 2013
 *      Author: russt
 */

#include "drakeUtil.h"
#include <string.h>
#include <string>
#include <math.h>
#include <limits>
#include <Eigen/Dense>

using namespace std;

bool isa(const mxArray* mxa, const char* class_str)
// mxIsClass seems to not be able to handle derived classes. so i'll implement what I need by calling back to matlab
{
  mxArray* plhs;
  mxArray* prhs[2];
  prhs[0] = const_cast<mxArray*>(mxa);
  prhs[1] = mxCreateString(class_str);
  mexCallMATLAB(1,&plhs,2,prhs,"isa");
  bool tf = *mxGetLogicals(plhs);
  mxDestroyArray(plhs);
  mxDestroyArray(prhs[1]);
  return tf;
}

bool mexCallMATLABsafe(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[], const char* filename)
{
  int i;
  mxArray* ex = mexCallMATLABWithTrap(nlhs,plhs,nrhs,prhs,filename);
  if (ex) {
    mexPrintf("DrakeSystem S-Function: error when calling ''%s'' with the following arguments:\n",filename);
    for (i=0; i<nrhs; i++)
      mexCallMATLAB(0,NULL,1,&prhs[i],"disp");
    mxArray *report;
    mexCallMATLAB(1,&report,1,&ex,"getReport");
    char *errmsg = mxArrayToString(report);
    mexPrintf(errmsg);
    mxFree(errmsg);
    mxDestroyArray(report);
    mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:CallbackError", "Error in MATLAB callback.\nSee additional debugging information above");
    mxDestroyArray(ex);
    return true;
  }
  for (i=0; i<nlhs; i++)
    if (!plhs[i]) {
      mexPrintf("Drake mexCallMATLABsafe: error when calling ''%s'' with the following arguments:\n", filename);
      for (i=0; i<nrhs; i++)
        mexCallMATLAB(0,NULL,1,&prhs[i],"disp");
      mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:NotEnoughOutputs","Asked for %d outputs, but function only returned %d\n",nrhs,i);
      return true;
    }
  return false;
}

/*
 * @param subclass_name (optional) if you want to call a class that derives from
 * DrakeMexPointer (e.g. so that you can refer to it as something more specific in
 * your matlab code), then you can pass in the alternative name here.  The constructor
 * for this class must take the same inputs as the DrakeMexPointer constructor.
 */
mxArray* createDrakeMexPointer(void* ptr, const char* name, int num_additional_inputs, mxArray* delete_fcn_additional_inputs[], const char* subclass_name)
{
	mxClassID cid;
	if (sizeof(ptr)==4) cid = mxUINT32_CLASS;
	else if (sizeof(ptr)==8) cid = mxUINT64_CLASS;
  else mexErrMsgIdAndTxt("Drake:constructDrakeMexPointer:PointerSize","Are you on a 32-bit machine or 64-bit machine??");

	int nrhs=3+num_additional_inputs;
	mxArray *plhs[1];
  mxArray **prhs;  prhs = new mxArray*[nrhs];

	prhs[0] = mxCreateNumericMatrix(1,1,cid,mxREAL);
  memcpy(mxGetData(prhs[0]),&ptr,sizeof(ptr));

	prhs[1] = mxCreateString(mexFunctionName());

  prhs[2] = mxCreateString(name);

  for (int i=0; i<num_additional_inputs; i++)
    prhs[3+i] = delete_fcn_additional_inputs[i];

//  mexPrintf("deleteMethod = %s\n name =%s\n", deleteMethod,name);

  // call matlab to construct mex pointer object
  if (subclass_name) {
    mexCallMATLABsafe(1,plhs,nrhs,prhs,subclass_name);
    if (!isa(plhs[0],"DrakeMexPointer")) {
      mxDestroyArray(plhs[0]);
      mexErrMsgIdAndTxt("Drake:createDrakeMexPointer:InvalidSubclass","subclass_name is not a valid subclass of DrakeMexPointer");
    }
  }
  else
    mexCallMATLABsafe(1,plhs,nrhs,prhs,"DrakeMexPointer");

  mexLock();

//  mexPrintf("incrementing lock count\n");

  delete[] prhs;
  return plhs[0];
}

void* getDrakeMexPointer(const mxArray* mx)
{
	void* ptr = NULL;

	// todo: optimize this by caching the pointer values, as described in
	// http://groups.csail.mit.edu/locomotion/bugs/show_bug.cgi?id=1590
	mxArray* ptrArray = mxGetProperty(mx,0,"ptr");
	if (!ptrArray)
		mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs","cannot retrieve 'ptr' field from this mxArray.  are you sure it's a valid DrakeMexPointer object?");

  if (!mxIsNumeric(ptrArray) || mxGetNumberOfElements(ptrArray)!=1)
    mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs","the ptr property of this DrakeMexPointer does not appear to contain a valid pointer");
  memcpy(&ptr,mxGetData(ptrArray),sizeof(ptr));     // note: could use a reinterpret_cast here instead

  return ptr;
}

double angleAverage(double theta1, double theta2) {
  // Computes the average between two angles by averaging points on the unit
  // circle and taking the arctan of the result.
  //   see: http://en.wikipedia.org/wiki/Mean_of_circular_quantities
  // theta1 is a scalar or column vector of angles (rad)
  // theta2 is a scalar or column vector of angles (rad)

  double x_mean = 0.5*(cos(theta1)+cos(theta2));
  double y_mean = 0.5*(sin(theta1)+sin(theta2));

  double angle_mean = atan2(y_mean,x_mean);

  return angle_mean;
}

std::pair<Eigen::Vector3d, double> resolveCenterOfPressure(Eigen::Vector3d torque, Eigen::Vector3d force, Eigen::Vector3d normal, Eigen::Vector3d point_on_contact_plane)
{
  // TODO: implement multi-column version
  using namespace Eigen;

  if (abs(normal.squaredNorm() - 1.0) > 1e-12) {
    mexErrMsgIdAndTxt("Drake:resolveCenterOfPressure:BadInputs", "normal should be a unit vector");
  }

  Vector3d cop;
  double normal_torque_at_cop;

  double fz = normal.dot(force);
  bool cop_exists = abs(fz) > 1e-12;

  if (cop_exists) {
    auto torque_at_point_on_contact_plane = torque - point_on_contact_plane.cross(force);
    double normal_torque_at_point_on_contact_plane = normal.dot(torque_at_point_on_contact_plane);
    auto tangential_torque = torque_at_point_on_contact_plane - normal * normal_torque_at_point_on_contact_plane;
    cop = normal.cross(tangential_torque) / fz + point_on_contact_plane;
    auto torque_at_cop = torque - cop.cross(force);
    normal_torque_at_cop = normal.dot(torque_at_cop);
  }
  else {
    cop.setConstant(std::numeric_limits<double>::quiet_NaN());
    normal_torque_at_cop = std::numeric_limits<double>::quiet_NaN();
  }
  return std::pair<Vector3d, double>(cop, normal_torque_at_cop);
}

max_stars_repo_name: andybarry/drake

max_issues_repo_name: andybarry/drake

max_forks_repo_name: andybarry/drake


text:
#include <fstream>
#include <boost/config.hpp>
#include <boost/version.hpp>

// CGAL headers
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Regular_triangulation_2.h>
#include <CGAL/IO/WKT.h>

#include <CGAL/point_generators_2.h>
// Qt headers
#include <QtGui>
#include <QString>
#include <QActionGroup>
#include <QFileDialog>
#include <QInputDialog>

// GraphicsView items and event filters (input classes)

#include "RegularTriangulationRemoveVertex.h"
#include <CGAL/Qt/GraphicsViewCircleInput.h>
#include <CGAL/Qt/RegularTriangulationGraphicsItem.h>
#include <CGAL/Qt/PowerdiagramGraphicsItem.h>

// for viewportsBbox
#include <CGAL/Qt/utility.h>
// the two base classes
#include "ui_Regular_triangulation_2.h"
#include <CGAL/Qt/DemosMainWindow.h>

typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef K::Point_2                                          Point_2;
typedef K::Weighted_point_2                                 Weighted_point_2;
typedef K::Point_2                                          Circle_2;
typedef K::Iso_rectangle_2                                  Iso_rectangle_2;

typedef CGAL::Regular_triangulation_2<K>                    Regular;

class MainWindow :
  public CGAL::Qt::DemosMainWindow,
  public Ui::Regular_triangulation_2
{
  Q_OBJECT

private:
  Regular dt;
  QGraphicsScene scene;

  CGAL::Qt::RegularTriangulationGraphicsItem<Regular> * dgi;
  CGAL::Qt::PowerdiagramGraphicsItem<Regular> * vgi;

  CGAL::Qt::RegularTriangulationRemoveVertex<Regular> * trv;
  CGAL::Qt::GraphicsViewCircleInput<K> * pi;
public:
  MainWindow();

public Q_SLOTS:

  void processInput(CGAL::Object o);

  void on_actionShowRegular_toggled(bool checked);

  void on_actionShowPowerdiagram_toggled(bool checked);

  void on_actionInsertPoint_toggled(bool checked);

  void on_actionInsertRandomPoints_triggered();

  void on_actionLoadPoints_triggered();

  void on_actionSavePoints_triggered();

  void on_actionClear_triggered();

  void on_actionRecenter_triggered();

Q_SIGNALS:
  void changed();
};

MainWindow::MainWindow()
  : DemosMainWindow()
{
  setupUi(this);

  // Add a GraphicItem for the regular triangulation
  dgi = new CGAL::Qt::RegularTriangulationGraphicsItem<Regular>(&dt);

  QObject::connect(this, SIGNAL(changed()),
                   dgi, SLOT(modelChanged()));

  dgi->setVerticesPen(QPen(Qt::red, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
  dgi->setEdgesPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
  scene.addItem(dgi);

  // Add a GraphicItem for the Powerdiagram diagram
  vgi = new CGAL::Qt::PowerdiagramGraphicsItem<Regular>(&dt);

  QObject::connect(this, SIGNAL(changed()),
                   vgi, SLOT(modelChanged()));

  vgi->setEdgesPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
  scene.addItem(vgi);
  vgi->hide();

  // Setup input handlers. They get events before the scene gets them
  // and the input they generate is passed to the triangulation with
  // the signal/slot mechanism
  pi = new CGAL::Qt::GraphicsViewCircleInput<K>(this, &scene, 1); // emits center/radius

  QObject::connect(pi, SIGNAL(generate(CGAL::Object)),
                   this, SLOT(processInput(CGAL::Object)));

  trv = new CGAL::Qt::RegularTriangulationRemoveVertex<Regular>(&dt, this);
  QObject::connect(trv, SIGNAL(modelChanged()),
                   this, SIGNAL(changed()));

  //
  // Manual handling of actions
  //
  QObject::connect(this->actionQuit, SIGNAL(triggered()),
                   this, SLOT(close()));

  // We put mutually exclusive actions in an QActionGroup
  QActionGroup* ag = new QActionGroup(this);
  ag->addAction(this->actionInsertPoint);

  // Check two actions
  this->actionInsertPoint->setChecked(true);
  this->actionShowRegular->setChecked(true);

  //
  // Setup the scene and the view
  //
  scene.setItemIndexMethod(QGraphicsScene::NoIndex);
  scene.setSceneRect(-100, -100, 100, 100);
  this->graphicsView->setScene(&scene);
  this->graphicsView->setMouseTracking(true);

  // Turn the vertical axis upside down
  this->graphicsView->transform().scale(1, -1);

  // The navigation adds zooming and translation functionality to the
  // QGraphicsView
  this->addNavigation(this->graphicsView);

  this->setupStatusBar();
  this->setupOptionsMenu();
  this->addAboutDemo(":/cgal/help/about_Regular_triangulation_2.html");
  this->addAboutCGAL();
}

void
MainWindow::processInput(CGAL::Object o)
{
  std::pair<Point_2, K::FT > center_sqr;
  if(CGAL::assign(center_sqr, o)){
    Regular::Point wp(center_sqr.first, center_sqr.second);
    dt.insert(wp);
  }

  Q_EMIT( changed());
}

/*
 *  Qt Automatic Connections
 *  https://doc.qt.io/qt-5/designer-using-a-ui-file.html#automatic-connections
 *
 *  setupUi(this) generates connections to the slots named
 *  "on_<action_name>_<signal_name>"
 */
void
MainWindow::on_actionInsertPoint_toggled(bool checked)
{
  if(checked){
    scene.installEventFilter(pi);
    scene.installEventFilter(trv);
  } else {
    scene.removeEventFilter(pi);
    scene.removeEventFilter(trv);
  }
}

void
MainWindow::on_actionShowRegular_toggled(bool checked)
{
  dgi->setVisibleEdges(checked);
}

void
MainWindow::on_actionShowPowerdiagram_toggled(bool checked)
{
  vgi->setVisible(checked);
}

void
MainWindow::on_actionClear_triggered()
{
  dt.clear();
  Q_EMIT( changed());
}

void
MainWindow::on_actionInsertRandomPoints_triggered()
{
  QRectF rect = CGAL::Qt::viewportsBbox(&scene);
  CGAL::Qt::Converter<K> convert;
  Iso_rectangle_2 isor = convert(rect);
  CGAL::Random_points_in_iso_rectangle_2<Point_2> pg((isor.min)(), (isor.max)());
  CGAL::Random rnd(CGAL::get_default_random());

  const int number_of_points =
    QInputDialog::getInt(this,
                             tr("Number of random points"),
                             tr("Enter number of random points"), 100, 0);

  // wait cursor
  QApplication::setOverrideCursor(Qt::WaitCursor);
  std::vector<Weighted_point_2> points;
  points.reserve(number_of_points);
  for(int i = 0; i < number_of_points; ++i){
    Weighted_point_2 wp(*pg++, rnd.get_double(0, 500));
    points.push_back(wp);
  }
  dt.insert(points.begin(), points.end());
  // default cursor
  QApplication::setOverrideCursor(Qt::ArrowCursor);
  Q_EMIT( changed());
}

void
MainWindow::on_actionLoadPoints_triggered()
{
  QString fileName = QFileDialog::getOpenFileName(this,
                                                  tr("Open Points file"),
                                                  ".",
                                                  tr("Weighted Points (*.wpts.cgal);;"
                                                     "WKT files (*.wkt *.WKT);;"
                                                     "All (*)"));

  if(! fileName.isEmpty()){
    std::ifstream ifs(qPrintable(fileName));
    std::vector<Weighted_point_2> points;
    if(fileName.endsWith(".wkt",Qt::CaseInsensitive))
    {
      std::vector<K::Point_3> points_3;
      CGAL::IO::read_multi_point_WKT(ifs, points_3);
      for(const K::Point_3& p : points_3)
      {
        points.push_back(Weighted_point_2(K::Point_2(p.x(), p.y()), p.z()));
      }
    }
    else
    {
      Weighted_point_2 p;
      while(ifs >> p) {
        points.push_back(p);
      }
    }
    dt.insert(points.begin(), points.end());

    actionRecenter->trigger();
    Q_EMIT( changed());
  }
}

void
MainWindow::on_actionSavePoints_triggered()
{
  QString fileName = QFileDialog::getSaveFileName(this,
                                                  tr("Save points"),
                                                  ".reg.cgal",
                                                  tr("Weighted Points (*.wpts.cgal);;"
                                                     "WKT files (*.wkt *.WKT);;"
                                                     "All (*)"));
  if(! fileName.isEmpty()){
    std::ofstream ofs(qPrintable(fileName));
    if(fileName.endsWith(".wkt",Qt::CaseInsensitive))
    {
      std::vector<K::Point_3> points_3;
      for(Regular::Finite_vertices_iterator
          vit = dt.finite_vertices_begin(),
          end = dt.finite_vertices_end();
          vit!= end; ++vit)
      {
        points_3.push_back(K::Point_3(vit->point().x(),
                                      vit->point().y(),
                                      vit->point().weight()));
      }
      CGAL::IO::write_multi_point_WKT(ofs, points_3);
    }
    else
    {
      for(Regular::Finite_vertices_iterator
          vit = dt.finite_vertices_begin(),
          end = dt.finite_vertices_end();
          vit!= end; ++vit)
      {
        ofs << vit->point() << std::endl;
      }
    }
  }
}

void
MainWindow::on_actionRecenter_triggered()
{
  this->graphicsView->setSceneRect(dgi->boundingRect());
  this->graphicsView->fitInView(dgi->boundingRect(), Qt::KeepAspectRatio);
}

#include "Regular_triangulation_2.moc"
#include <CGAL/Qt/resources.h>

int main(int argc, char **argv)
{
  QApplication app(argc, argv);

  app.setOrganizationDomain("geometryfactory.com");
  app.setOrganizationName("GeometryFactory");
  app.setApplicationName("Regular_triangulation_2 demo");

  // Import resources from libCGAL (Qt5).
  CGAL_QT_INIT_RESOURCES;

  MainWindow mainWindow;
  mainWindow.show();

  QStringList args = app.arguments();
  args.removeAt(0);
  Q_FOREACH(QString filename, args) {
    mainWindow.open(filename);
  }

  return app.exec();
}

max_stars_repo_name: ffteja/cgal

max_issues_repo_name: ffteja/cgal

max_forks_repo_name: ffteja/cgal