text:
// Copyright 2018 Grass Valley, A Belden Brand

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "stdafx.h"

#include "obj_pool.h"

#include <process.h>
#include "Z:\kernel\Shared\Utils\WinScopedHandleDef.h"
#include <iostream>
#include <boost/format.hpp>

typedef void            tReturn;
typedef int&            tParam0;
typedef short           tParam1;
typedef const float&    tParam2;
typedef volatile char*  tParam3;

struct FuncClass
{
  int mVal;
  FuncClass(int val) : mVal(val) {std::cout << "FuncClass::FuncClass() mVal: " << mVal << "\n";}
  ~FuncClass() {std::cout << "FuncClass::~FuncClass() mVal: " << mVal << "\n";}
  int                 FuncC0       (                                  )  const          { std::cout << boost::format("FuncClass::FuncC0       (             )\n")               ; return mVal;}
  tReturn             FuncV1       (tParam0 p0                        )  volatile       { std::cout << boost::format("FuncClass::FuncV1       (%1%          )\n") % p0          ; }
  tReturn             FuncCV2      (tParam0 p0, tParam1 p1            )  const volatile { std::cout << boost::format("FuncClass::FuncCV2      (%1%, %2%     )\n") % p0 % p1     ; }
  tReturn             Func3        (tParam0 p0, tParam1 p1, tParam2 p2)                 { std::cout << boost::format("FuncClass::Func3        (%1%, %2%, %3%)\n") % p0 % p1 % p2; }
  tReturn __stdcall   StdCallFunc1 (tParam0 p0                        )                 { std::cout << boost::format("FuncClass::StdCallFunc1 (%1%          )\n") % p0          ; }
  tReturn __fastcall  FastCallFunc2(tParam0 p0, tParam1 p1            )                 { std::cout << boost::format("FuncClass::FastCallFunc2(%1%, %2%     )\n") % p0 % p1     ; }
  int     __fastcall  FastCallFunc3(tParam0 p0, tParam1 p1, tParam2 p2)                 { std::cout << boost::format("FuncClass::FastCallFunc3(%1%, %2%, %3%)\n") % p0 % p1 % p2; return mVal; }
  static tReturn      StaticFunc3  (tParam0 p0, tParam1 p1, tParam2 p2)                 { std::cout << boost::format("FuncClass::StaticFunc3  (%1%, %2%, %3%)\n") % p0 % p1 % p2; }
};

typedef obj_pool<boost::shared_ptr, FuncClass, on_empty_return_null, single_thread_safe, int> obj_pool_st_null_t;
typedef obj_pool<boost::shared_ptr, FuncClass, on_empty_wait, single_thread_safe, int> obj_pool_st_block_t;
typedef obj_pool<boost::shared_ptr, FuncClass, on_empty_create, single_thread_safe, int> obj_pool_st_create_t;

typedef obj_pool<boost::shared_ptr, FuncClass, on_empty_return_null, multi_thread_safe, int> obj_pool_mt_null_t;
typedef obj_pool<boost::shared_ptr, FuncClass, on_empty_wait, multi_thread_safe, int> obj_pool_mt_block_t;
typedef obj_pool<boost::shared_ptr, FuncClass, on_empty_create, multi_thread_safe, int> obj_pool_mt_create_t;

template<class T, int n>
void Test()
{
  T objPool(n, 7);
  objPool.get();
  objPool.get();
}

unsigned __stdcall ThreadProc(void* param)
{
  obj_pool_mt_block_t* pool = (obj_pool_mt_block_t*) param;
  obj_pool_mt_block_t::ele_type ele = pool->get();
  Sleep(2000);
  std::cout << GetTickCount() << " : Return an obj\n";
  pool->put(ele);
  return 1;
}

template<int n>
void TestMt()
{
  obj_pool_mt_block_t objPool(n, 7);
  unsigned threadId;
  tKernelHandle threadHandle((HANDLE)_beginthreadex(NULL, 0, ThreadProc, &objPool, 0, &threadId));
  Sleep(200);
  std::cout << GetTickCount() << " : Get first obj\n";
  objPool.get();
  std::cout << GetTickCount() << " : Waiting for returned obj\n";
  objPool.get();
}

void TestObjPool()
{
  Test<obj_pool_st_null_t, 2>();
  //Test<obj_pool_st_block_t, 1>();
  Test<obj_pool_st_create_t, 1>();

  Test<obj_pool_mt_null_t, 2>();
  Test<obj_pool_mt_create_t, 1>();
  TestMt<2>();

}

max_stars_repo_name: rodrigomr/VFS

max_issues_repo_name: rodrigomr/VFS

max_forks_repo_name: rodrigomr/VFS


text:
// ROS
#include <ros/ros.h>
#include <ros/package.h>
#include <ros/console.h>
#include <rosbag/bag.h>
#include <rosbag/view.h>

// OpenCv
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <cv_bridge/cv_bridge.h>

#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>

#include <sensor_msgs/CompressedImage.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/CameraInfo.h>

#include "extract_zed_data/DepthProcessor.hpp"
#include <camera_calibration_parsers/parse.h>

using namespace std;

DepthProcessor zed_depth;
bool save_depth_pfm;

/*
 *  Reads a bag file comprising of zed camera data and saves the file
 *  contents
 *
 *  Params:
 *      bag_filename:     type: string    description: file path to bag file
 *      out_foldername:   type: string    description: output path to save bag contents
 *      image_ns:         type: string    description: image namespace
 */
void loadBag(const std::string &bag_filename, const std::string &out_foldername = "", const std::string &image_ns = "/zed")
{
  rosbag::Bag bag;
  // Open the bag file
  bag.open(bag_filename, rosbag::bagmode::Read);
  ROS_INFO("Opened %s", bag_filename.c_str());

  std::string l_cam = image_ns + "/left";
  std::string r_cam = image_ns + "/right";
  std::string d_cam = image_ns + "/depth";
  // sensor_msgs/Image topic names
  std::string l_cam_image = l_cam + "/image_rect_color/compressed";
  std::string r_cam_image = r_cam + "/image_rect_color/compressed";
  std::string d_cam_image = d_cam + "/depth_registered";
  // sensor_msgs/camea_info topic names
  std::string l_cam_info = l_cam + "/camera_info";
  std::string r_cam_info = r_cam + "/camera_info";
  std::string d_cam_info = d_cam + "/camera_info";

  // Image topics to load
  std::vector<std::string> topics;
  topics.push_back(l_cam_image);
  topics.push_back(r_cam_image);
  topics.push_back(d_cam_image);
  topics.push_back(l_cam_info);
  topics.push_back(r_cam_info);
  topics.push_back(d_cam_info);

  rosbag::View view(bag, rosbag::TopicQuery(topics));

  uint32_t  bag_size = view.size();
  ROS_INFO("Bagfile loaded. Size: %d", bag_size);

  // Load all messages into our zed camera dataset
  uint32_t frame = 0, msg_num = 0;
  std::string frame_name;
  BOOST_FOREACH(rosbag::MessageInstance const m, view)
  {
      // topics.size()+1 since right_caminfo published at twice the rate in bagfile
      if (msg_num % (topics.size()+1) == 0)
      {
        frame ++;
        ROS_INFO("Processing timestamp: %05i ", frame);
        std::stringstream frame_stream;
        frame_stream << std::setw(6) << std::setfill('0') << frame;
        frame_name = std::string(frame_stream.str().c_str());
      }

      // save CompressedImage published in message at "../left/image_rect_color/compressed"
      if (m.getTopic() == l_cam_image || ("/" + m.getTopic() == l_cam_image))
      {
        sensor_msgs::CompressedImage::ConstPtr l_img = m.instantiate<sensor_msgs::CompressedImage>();
        if (l_img != NULL)
        {
          cv_bridge::CvImagePtr left_img_ptr;
          try
          {
            ROS_INFO("Received Left Camera Image");
            left_img_ptr = cv_bridge::toCvCopy(l_img, "bgr8");
            cv::imwrite(out_foldername + "left_" + frame_name + ".jpg", left_img_ptr->image);
          }
          catch (cv_bridge::Exception& e)
          {
            ROS_ERROR("cv_bridge exception: %s", e.what());
          }
        }
      }

      // save CompressedImage published in message at "../right/image_rect_color/compressed"
      if (m.getTopic() == r_cam_image || ("/" + m.getTopic() == r_cam_image))
      {
        sensor_msgs::CompressedImage::ConstPtr r_img = m.instantiate<sensor_msgs::CompressedImage>();
        if (r_img != NULL)
        {
          cv_bridge::CvImagePtr right_img_ptr;
          try
          {
            ROS_INFO("Received Right Camera Image");
            right_img_ptr = cv_bridge::toCvCopy(r_img, "bgr8");
            cv::imwrite(out_foldername + "right_" + frame_name + ".jpg", right_img_ptr->image);
          }
          catch (cv_bridge::Exception& e)
          {
            ROS_ERROR("cv_bridge exception: %s", e.what());
          }
        }
      }

      // save Image published in message at "../depth/depth_registered"
      if (m.getTopic() == d_cam_image || ("/" + m.getTopic() == d_cam_image))
      {
        sensor_msgs::Image::ConstPtr d_img = m.instantiate<sensor_msgs::Image>();
        if (d_img != NULL)
        {
          cv_bridge::CvImagePtr depth_img_ptr;
          try
          {
            ROS_INFO("Depth Map Received");
            depth_img_ptr = cv_bridge::toCvCopy(d_img);
            zed_depth.processDepthData(depth_img_ptr);
            zed_depth.saveDepthData(out_foldername + "depth_" + frame_name, save_depth_pfm);
          }
          catch (cv_bridge::Exception& e)
          {
            ROS_ERROR("cv_bridge exception: %s", e.what());
          }
        }
      }

      // save left camera parameters into a YAML file
      if (m.getTopic() == l_cam_info || ("/" + m.getTopic() == l_cam_info))
      {
        sensor_msgs::CameraInfo::ConstPtr l_info = m.instantiate<sensor_msgs::CameraInfo>();
        if (l_info != NULL)
        {
            ROS_INFO("Left Camera Parameters Received");
            camera_calibration_parsers::writeCalibration(out_foldername + "zed_left_cam.yaml", "Zed Left Camera", *l_info);
        }
      }

      // save right camera parameters into a YAML file
      if (m.getTopic() == r_cam_info || ("/" + m.getTopic() == r_cam_info))
      {
        sensor_msgs::CameraInfo::ConstPtr r_info = m.instantiate<sensor_msgs::CameraInfo>();
        if (r_info != NULL)
        {
          ROS_INFO("Right Camera Parameters Received");
          camera_calibration_parsers::writeCalibration(out_foldername + "zed_right_cam.yaml", "Zed Right Camera", *r_info);
        }
      }

      // save depth camera parameters into a YAML file
      if (m.getTopic() == d_cam_info || ("/" + m.getTopic() == d_cam_info))
      {
        sensor_msgs::CameraInfo::ConstPtr d_info = m.instantiate<sensor_msgs::CameraInfo>();
        if (d_info != NULL)
        {
          ROS_INFO("Depth Camera Parameters Received");
          camera_calibration_parsers::writeCalibration(out_foldername + "zed_depth_cam.yaml", "Zed Depth Camera", *d_info);
        }
      }

      msg_num ++;
  }
  bag.close();
}

int main( int argc, char** argv )
{
  //Start ROS ----------------------------------------------------------------
  ros::init(argc, argv, "extract_rosbag_zed");
  ros::NodeHandle nh("~");

  // rosbag file
  std::string bag_filename, out_foldername;
  // read node paramters
  nh.param<std::string>("bag_filename", bag_filename, "/media/mayankm/Data/Fount_Landing/dataset/depth_sync_2017-11-21-10-51-39.bag");
  nh.param<std::string>("out_foldername", out_foldername, "/mnt/MM_Seagate_BUP/Fount_Landing/dataset/");
  nh.param<bool>("save_depth_pfm", save_depth_pfm, false);

  ROS_WARN("Reading Bag file: %s", bag_filename.c_str());
  ROS_WARN("Saving data to folder: %s", out_foldername.c_str());
  ROS_WARN("Saving depth pfm data: %d", save_depth_pfm);

  boost::filesystem::path dir(out_foldername);
	if(boost::filesystem::create_directory(dir))
  {
		ROS_INFO("Created folder %s to save data", out_foldername.c_str());
	}

  loadBag(bag_filename, out_foldername);

  ROS_INFO("Processing Complete");
  return 0;
}

ext: cpp


text:
/**
 * Copyright Soramitsu Co., Ltd. 2018 All Rights Reserved.
 * http://soramitsu.co.jp
 *
 * 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 IROHA_SHARED_MODEL_PROTO_PROPOSAL_HPP
#define IROHA_SHARED_MODEL_PROTO_PROPOSAL_HPP

#include "interfaces/iroha_internal/proposal.hpp"
#include "interfaces/transaction.hpp"

#include <boost/range/numeric.hpp>
#include "common_objects/trivial_proto.hpp"

#include "block.pb.h"
#include "interfaces/common_objects/types.hpp"
#include "proposal.pb.h"
#include "utils/lazy_initializer.hpp"

#include "transaction.hpp"
namespace shared_model {

  namespace proto {
    class Proposal final : public CopyableProto<interface::Proposal,
                                                iroha::protocol::Proposal,
                                                Proposal> {
      template <class T>
      using w = detail::PolymorphicWrapper<T>;
      using TransactionContainer = std::vector<w<interface::Transaction>>;

     public:
      template <class ProposalType>
      explicit Proposal(ProposalType &&proposal)
          : CopyableProto(std::forward<ProposalType>(proposal)) {}

      Proposal(const Proposal &o) : Proposal(o.proto_) {}

      Proposal(Proposal &&o) noexcept : Proposal(std::move(o.proto_)) {}

      const TransactionContainer &transactions() const override {
        return *transactions_;
      }

      interface::types::TimestampType createdTime() const override {
        return proto_->created_time();
      }

      interface::types::HeightType height() const override {
        return proto_->height();
      }

     private:
      // lazy
      template <typename T>
      using Lazy = detail::LazyInitializer<T>;

      const Lazy<TransactionContainer> transactions_{[this] {
        return boost::accumulate(proto_->transactions(),
                                 TransactionContainer{},
                                 [](auto &&vec, const auto &tx) {
                                   vec.emplace_back(new proto::Transaction(tx));
                                   return std::forward<decltype(vec)>(vec);
                                 });
      }};
    };
  }  // namespace proto
}  // namespace shared_model

#endif  // IROHA_PROPOSAL_HPP

ext: hpp

max_stars_repo_name: steephengeorge/iroha

max_issues_repo_name: steephengeorge/iroha

max_forks_repo_name: steephengeorge/iroha


text:
// Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.

#include "Generic/common/leak_detection.h"

#include "Generic/edt/AcronymMaker.h"
#include "Generic/edt/xx_AcronymMaker.h"
#include "Generic/common/WordConstants.h"
#include "Generic/common/ParamReader.h"

#include <boost/foreach.hpp>

GenericAcronymMaker::GenericAcronymMaker() {
	// to do: read reservedAcronyms from a data file.
	if (ParamReader::isParamTrue("simple_rule_name_link_distillation")) {
		std::vector<Symbol> united_states;
		std::vector<Symbol> united_nations;
		united_states.push_back(Symbol(L"united"));
		united_states.push_back(Symbol(L"states"));
		united_nations.push_back(Symbol(L"united"));
		united_nations.push_back(Symbol(L"nations"));
		reservedAcronyms[Symbol(L"us")].push_back(united_states);
		reservedAcronyms[Symbol(L"un")].push_back(united_nations);
	}
}

std::vector<Symbol> GenericAcronymMaker::generateAcronyms(const std::vector<Symbol>& words) {
	std::vector<Symbol> results;
	std::vector<Symbol> filteredWords;

	BOOST_FOREACH(Symbol word, words) {
		if (WordConstants::isAcronymStopWord(word))
			continue;
		filteredWords.push_back(word);
	}

	// No single-letter acronyms!
	if (filteredWords.size() < 2)
		return results;

	//concatenate the initials
	std::wstring acronym1; // without periods
	std::wstring acronym2; // with periods
	BOOST_FOREACH(Symbol word, filteredWords) {
		const wchar_t w = *word.to_string();
		acronym1 += w;
		acronym2 += w + std::wstring(L".");
	}
	//finally, the last period may be left off e.g. at end of sentence
	std::wstring acronym3(acronym2.begin(), acronym2.end()-1);

	// Check if this is a "reserved" acronym.  If so, then we only
	// keep it if it matches one of the names it's reserved for.
	ReservedAcronymTable::iterator it = reservedAcronyms.find(Symbol(acronym1.c_str()));
	if (it != reservedAcronyms.end()) {
		bool matches_reserved_acronym = false;
		BOOST_FOREACH(SymbolList reservedAcronym, (*it).second) {
			if (reservedAcronym == words)
				matches_reserved_acronym = true;
		}
		if (!matches_reserved_acronym)
			return results; // return empty result.
	}

	results.push_back(Symbol(acronym1.c_str()));
	results.push_back(Symbol(acronym2.c_str()));
	results.push_back(Symbol(acronym3.c_str()));

	return results;
}

max_stars_repo_name: BBN-E/serif

max_issues_repo_name: BBN-E/serif

max_forks_repo_name: BBN-E/serif


text:
/*
 * common.hpp
 *
 *  Created on: Nov 8, 2019
 *      Author: Edo Jelavic
 *      Institute: ETH Zurich, Robotic Systems Lab
 */

#pragma once

#include <pcl/common/common.h>
#include <ros/console.h>
#include <ros/package.h>
#include <Eigen/Core>
#include <grid_map_core/GridMap.hpp>
#include <grid_map_core/iterators/GridMapIterator.hpp>
#include <random>

namespace grid_map {

class GridMapPclLoader;

namespace grid_map_pcl_test {

using Point = pcl::PointXYZ;
using Pointcloud = pcl::PointCloud<Point>;

static const std::string layerName = "elevation";
static const bool savePointclouds = true;
extern std::mt19937 rndGenerator;

std::string getConfigFilePath();
std::string getTestDataFolderPath();
Pointcloud::Ptr concatenate(Pointcloud::Ptr cloud1, Pointcloud::Ptr cloud2);

std::vector<double> getNonNanElevationValues(const grid_map::GridMap& gridMap);
std::vector<Eigen::Vector3d> getNonNanElevationValuesWithCoordinates(const grid_map::GridMap& gridMap);

Pointcloud::Ptr createNormallyDistributedBlobOfPoints(unsigned int nPoints, double mean, double stdDev, std::mt19937* generator);
Pointcloud::Ptr createNoisyPlanePointcloud(unsigned int nPoints, double minXY, double maxXY, double meanZ, double stdDevZ,
                                           std::mt19937* generator);
Pointcloud::Ptr createPerfectPlane(unsigned int nPoints, double minXY, double maxXY, double desiredHeight, std::mt19937* generator);

void runGridMapPclLoaderOnInputCloud(Pointcloud::ConstPtr inputCloud, grid_map::GridMapPclLoader* gridMapPclLoader);
void runGridMapPclLoaderOnInputCloudAndSavePointCloud(Pointcloud::ConstPtr inputCloud, grid_map::GridMapPclLoader* gridMapPclLoader,
                                                      const std::string& filename);

Pointcloud::Ptr createStepTerrain(unsigned int nPoints, double minXY, double maxXY, double zHigh, double zLow, double stdDevZ,
                                  std::mt19937* generator, double* center);

void setVerbosityLevel(ros::console::levels::Level level);
std::string getTestPcdFilePath();

} /* namespace grid_map_pcl_test */
} /* namespace grid_map*/


text:
//ros头文件
#include <ros/ros.h>
#include <Eigen/Eigen>
#include <iostream>
#include <mission_utils.h>

//topic 头文件
#include <geometry_msgs/Point.h>
#include <prometheus_msgs/ControlCommand.h>
#include <prometheus_msgs/DroneState.h>
#include <prometheus_msgs/DetectionInfo.h>
#include <prometheus_msgs/PositionReference.h>
#include <nav_msgs/Odometry.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/TwistStamped.h>
#include <mavros_msgs/ActuatorControl.h>
#include <sensor_msgs/Imu.h>
#include <prometheus_msgs/DroneState.h>
#include <prometheus_msgs/AttitudeReference.h>
#include <prometheus_msgs/DroneState.h>
#include <nav_msgs/Path.h>
#include <std_msgs/Int8.h>
#include "message_utils.h"

using namespace std;

#define FIVE_STAR_SIZE 2.0
#define TRIANGLE_SIZE 2.0
#define T_SIZE 2.0
# define NODE_NAME "formation_flight"
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>全 局 变 量<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
geometry_msgs::Point leader;
geometry_msgs::Point relative_pos_to_leader1;
geometry_msgs::Point relative_pos_to_leader2;
geometry_msgs::Point relative_pos_to_leader3;
geometry_msgs::Point relative_pos_to_leader4;
geometry_msgs::Point relative_pos_to_leader5;

geometry_msgs::PoseStamped goal;
int flag_get_goal;

ros::Publisher leader_pub;
ros::Publisher formation_pub1;
ros::Publisher formation_pub2;
ros::Publisher formation_pub3;
ros::Publisher formation_pub4;
ros::Publisher formation_pub5;

float uav_number;
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>声 明 函 数<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
void five_star();
void triangle();
void T_shape();
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>回 调 函 数<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
void goal_cb(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
    goal = *msg;
    flag_get_goal = 1;
    cout << "Get a new goal from rviz!"<<endl;

    //高度打死
    leader.x = goal.pose.position.x;
    leader.y = goal.pose.position.y;
    leader.z = 1.0;
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>主 函 数<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
int main(int argc, char **argv)
{
    ros::init(argc, argv, "formation_flight");
    ros::NodeHandle nh("~");

    nh.param<float>("uav_number", uav_number, 5);

    //【订阅】目标点
    ros::Subscriber goal_sub = nh.subscribe<geometry_msgs::PoseStamped>("/prometheus/formation/goal", 10, goal_cb);

    // 【发布】用于地面站显示的提示消息
    ros::Publisher message_pub = nh.advertise<prometheus_msgs::Message>("/prometheus/message/main", 10);

    //【发布】阵型
    leader_pub     = nh.advertise<geometry_msgs::Point>("/prometheus/formation/leader_pos", 10);
    formation_pub1 = nh.advertise<geometry_msgs::Point>("/prometheus/formation/uav1", 10);
    formation_pub2 = nh.advertise<geometry_msgs::Point>("/prometheus/formation/uav2", 10);
    formation_pub3 = nh.advertise<geometry_msgs::Point>("/prometheus/formation/uav3", 10);
    formation_pub4 = nh.advertise<geometry_msgs::Point>("/prometheus/formation/uav4", 10);
    formation_pub5 = nh.advertise<geometry_msgs::Point>("/prometheus/formation/uav5", 10);

    //固定的浮点显示
    cout.setf(ios::fixed);
    //setprecision(n) 设显示小数精度为n位
    cout<<setprecision(4);
    //左对齐
    cout.setf(ios::left);
    // 强制显示小数点
    cout.setf(ios::showpoint);
    // 强制显示符号
    cout.setf(ios::showpos);

    // Waiting for input
    int start_flag = 0;

    ros::Duration(1.0).sleep();

    while(start_flag == 0)
    {
        cout << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Formation Flight Mission<<<<<<<<<<<<<<<<<<<<<<<<<<< "<< endl;
        cout << "Please enter 1 to takeoff all the UAVs."<<endl;
        cin >> start_flag;
        leader_pub.publish(leader);
    }

    float x_sp,y_sp;
    while (ros::ok())
    {
        cout << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Formation Flight Mission<<<<<<<<<<<<<<<<<<<<<<<<<<< "<< endl;
        cout << "Please choose the formation: 1 for five star, 2 for triangle, 3 for T shape..."<<endl;
        cin >> start_flag;
        cout << "Please enter the desired position (if x_sp = 999, use the position choosen in rviz):"<<endl;
        cout << "x_sp:"<<endl;
        cin >> x_sp;
        cout << "y_sp:"<<endl;
        cin >> y_sp;

        if(x_sp == 999)
        {
            ros::spinOnce();
        }else{
            //高度打死
            leader.x = x_sp;
            leader.y = y_sp;
            leader.z = 1.0;
        }

        //发布
        leader_pub.publish(leader);

        //选择阵型
        if (start_flag == 1)
        {
            five_star();
            pub_message(message_pub, prometheus_msgs::Message::NORMAL, NODE_NAME, "Switch to five_star formation.");
        }else if (start_flag == 2)
        {
            triangle();
        }else if (start_flag == 3)
        {
            T_shape();
        }

        cout << "Leader [X Y Z] : " << leader.x << " [ m ] "<< leader.y <<" [ m ] "<< leader.z <<" [ m ] "<<endl;

        ros::Duration(2.0).sleep();
    }

    return 0;

}

void five_star()
{
    relative_pos_to_leader1.x = FIVE_STAR_SIZE;
    relative_pos_to_leader1.y = 0.0;
    relative_pos_to_leader1.z = 0.0;
    formation_pub1.publish(relative_pos_to_leader1);

    relative_pos_to_leader2.x = 0.0;
    relative_pos_to_leader2.y = FIVE_STAR_SIZE;
    relative_pos_to_leader2.z = 0.0;
    formation_pub2.publish(relative_pos_to_leader2);

    relative_pos_to_leader3.x = -FIVE_STAR_SIZE;
    relative_pos_to_leader3.y = 0.5*FIVE_STAR_SIZE;
    relative_pos_to_leader3.z = 0.0;
    formation_pub3.publish(relative_pos_to_leader3);

    relative_pos_to_leader4.x = -FIVE_STAR_SIZE;
    relative_pos_to_leader4.y = -0.5*FIVE_STAR_SIZE;
    relative_pos_to_leader4.z = 0.0;
    formation_pub4.publish(relative_pos_to_leader4);

    relative_pos_to_leader5.x = 0.0;
    relative_pos_to_leader5.y = -FIVE_STAR_SIZE;
    relative_pos_to_leader5.z = 0.0;
    formation_pub5.publish(relative_pos_to_leader5);
}

void triangle()
{
    relative_pos_to_leader1.x = TRIANGLE_SIZE;
    relative_pos_to_leader1.y = TRIANGLE_SIZE;
    relative_pos_to_leader1.z = 0.0;
    formation_pub1.publish(relative_pos_to_leader1);

    relative_pos_to_leader2.x = 0.0;
    relative_pos_to_leader2.y = 2 * TRIANGLE_SIZE;
    relative_pos_to_leader2.z = 0.0;
    formation_pub2.publish(relative_pos_to_leader2);

    relative_pos_to_leader3.x = 0.0;
    relative_pos_to_leader3.y = - 2 * TRIANGLE_SIZE;
    relative_pos_to_leader3.z = 0.0;
    formation_pub3.publish(relative_pos_to_leader3);

    relative_pos_to_leader4.x = TRIANGLE_SIZE;
    relative_pos_to_leader4.y = -TRIANGLE_SIZE;
    relative_pos_to_leader4.z = 0.0;
    formation_pub4.publish(relative_pos_to_leader4);

    relative_pos_to_leader5.x = 2 * TRIANGLE_SIZE;
    relative_pos_to_leader5.y = 0.0;
    relative_pos_to_leader5.z = 0.0;
    formation_pub5.publish(relative_pos_to_leader5);
}

void T_shape()
{
    relative_pos_to_leader1.x = 2 * T_SIZE;
    relative_pos_to_leader1.y = - T_SIZE;
    relative_pos_to_leader1.z = 0.0;
    formation_pub1.publish(relative_pos_to_leader1);

    relative_pos_to_leader2.x = 2 * T_SIZE;
    relative_pos_to_leader2.y = 0.0;
    relative_pos_to_leader2.z = 0.0;
    formation_pub2.publish(relative_pos_to_leader2);

    relative_pos_to_leader3.x = 2 * T_SIZE;
    relative_pos_to_leader3.y = T_SIZE;
    relative_pos_to_leader3.z = 0.0;
    formation_pub3.publish(relative_pos_to_leader3);

    relative_pos_to_leader4.x = T_SIZE;
    relative_pos_to_leader4.y = 0.0;
    relative_pos_to_leader4.z = 0.0;
    formation_pub4.publish(relative_pos_to_leader4);

    relative_pos_to_leader5.x = 0.0;
    relative_pos_to_leader5.y = 0.0;
    relative_pos_to_leader5.z = 0.0;
    formation_pub5.publish(relative_pos_to_leader5);
}

max_stars_repo_name: zenglongGH/Prometheus

max_issues_repo_name: Fllying/Prometheus

max_forks_repo_name: Fllying/Prometheus


text: #include <boost/regex/pattern_except.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**
 * @file mgmpint.cpp This file contains the main class for unsigned big integers: ubint. Big
 * integers are represented as arrays of machine native unsigned integers. The
 * native integer type is supplied as a template parameter.  Currently
 * implementation based on uint32_t and uint64_t is
 * supported. a native double the base integer size is also needed.
 * @author  TPOC: palisade@njit.edu
 *
 * @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT)
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice, this
 * list of conditions and the following disclaimer in the documentation and/or other
 * materials provided with the distribution.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
 /*
 *
 * This file contains the C++ code for implementing the main class for
 * big integers: ubint. Big integers are represented as arrays of
 * native usigned integers. The native integer type is supplied as a
 * template parameter.  Currently implementation based on uint32_t is
 * supported. One needs a native integer 2x the size of the chosen type for
 * certain math operations.
 */

#define _SECURE_SCL 0 // to speed up VS

#include <iostream>
#include <fstream>
#include <sstream>

#include "../backend.h"

#if defined(__linux__) && MATHBACKEND == 6

#include "gmpint.h"
#include "mgmpint.h"

//#include <NTL/ZZ.h>
//#include <NTL/ZZ_limbs.h>

namespace NTL {

  //define the static vriables
  myZZ myZZ_p::m_OTM = 0;
  myZZ_p::OTMState myZZ_p::m_OTM_state = GARBAGE;

  // may have difficulty with not inintializing modulo first.
  // const myZZ_p myZZ_p::ZERO=myZZ_p(0L);
  // const myZZ_p myZZ_p::ONE=myZZ_p(1);
  // const myZZ_p myZZ_p::TWO=myZZ_p(2);
  // const myZZ_p myZZ_p::THREE=myZZ_p(3);
  // const myZZ_p myZZ_p::FOUR=myZZ_p(4);
  // const
  // myZZ_p myZZ_p::FIVE=myZZ_p(5);

  //constructors without moduli
  myZZ_p::myZZ_p():ZZ_p() {}
  myZZ_p::myZZ_p(int a): ZZ_p(a) {}
  myZZ_p::myZZ_p(long a): ZZ_p(a) {}
  myZZ_p::myZZ_p(unsigned long a): ZZ_p(a) {}
  myZZ_p::myZZ_p(const unsigned int a): ZZ_p(a) {}
  //myZZ_p::myZZ_p(const unsigned int &a): ZZ_p(a) {}
  //myZZ_p::myZZ_p(unsigned int &a): ZZ_p(a) {}
  myZZ_p::myZZ_p(std::string s): ZZ_p() {this->_ZZ_p__rep=conv<ZZ>(s.c_str());}
  myZZ_p::myZZ_p(const char *s): ZZ_p() {this->_ZZ_p__rep=conv<ZZ>(s);}
  //constructors with explicit myZZ moduli
  myZZ_p::myZZ_p(int a, myZZ&q): ZZ_p(a) {m_setOTM(q);}
  myZZ_p::myZZ_p(long a, myZZ&q): ZZ_p(a) {m_setOTM(q);}
  myZZ_p::myZZ_p(unsigned long a, myZZ&q): ZZ_p(a) {m_setOTM(q);}
  myZZ_p::myZZ_p(const unsigned int &a, myZZ&q): ZZ_p(a) {m_setOTM(q);}
  myZZ_p::myZZ_p(unsigned int &a, myZZ&q): ZZ_p(a) {m_setOTM(q);}
  myZZ_p::myZZ_p(std::string s, myZZ&q): ZZ_p() {this->_ZZ_p__rep=conv<ZZ>(s.c_str()); m_setOTM(q);}
  myZZ_p::myZZ_p(const char *s, myZZ&q): ZZ_p() {this->_ZZ_p__rep=conv<ZZ>(s); m_setOTM(q);}

  //constructors with explicit string moduli
  myZZ_p::myZZ_p(int a, const char *sq): ZZ_p(a) {m_setOTM(sq);}
  myZZ_p::myZZ_p(long a, const char *sq): ZZ_p(a) {m_setOTM(sq);}
  myZZ_p::myZZ_p(unsigned long a, const char *sq): ZZ_p(a) {m_setOTM(sq);}
  myZZ_p::myZZ_p(const unsigned int &a, const char *sq): ZZ_p(a) {m_setOTM(sq);}
  myZZ_p::myZZ_p(unsigned int &a, const char *sq): ZZ_p(a) {m_setOTM(sq);}
  myZZ_p::myZZ_p(std::string s, const char *sq): ZZ_p() {this->_ZZ_p__rep=conv<ZZ>(s.c_str());m_setOTM(sq);}
  myZZ_p::myZZ_p(const char *s, const char *sq): ZZ_p() {this->_ZZ_p__rep=conv<ZZ>(s); m_setOTM(sq);}

  //copy constructors
  myZZ_p::myZZ_p(NTL::ZZ &a): ZZ_p() {this->_ZZ_p__rep=a;}
  myZZ_p::myZZ_p(const NTL::ZZ &a): ZZ_p() {this->_ZZ_p__rep=a;}
  myZZ_p::myZZ_p(NTL::ZZ_p &a): ZZ_p(a) {}
  myZZ_p::myZZ_p(const NTL::ZZ_p &a): ZZ_p(a) {}
  // copy constructors with myZZ moduli
  myZZ_p::myZZ_p(NTL::ZZ &a, myZZ&q): ZZ_p() {this->_ZZ_p__rep=a; m_setOTM(q);}
  myZZ_p::myZZ_p(const NTL::ZZ &a, myZZ&q): ZZ_p() {this->_ZZ_p__rep=a; m_setOTM(q);}
  myZZ_p::myZZ_p(NTL::ZZ_p &a, myZZ&q): ZZ_p(a) { m_setOTM(q);}
  myZZ_p::myZZ_p(const NTL::ZZ_p &a, myZZ&q): ZZ_p(a) { m_setOTM(q);}
  // copy constructors with string constant moduli
  myZZ_p::myZZ_p(NTL::ZZ &a, const char *sq): ZZ_p() {this->_ZZ_p__rep=a; m_setOTM(sq);}
  myZZ_p::myZZ_p(const NTL::ZZ &a, const char *sq): ZZ_p() {this->_ZZ_p__rep=a; m_setOTM(sq);}
  myZZ_p::myZZ_p(NTL::ZZ_p &a, const char *sq): ZZ_p(a) { m_setOTM(sq);}
  myZZ_p::myZZ_p(const NTL::ZZ_p &a, const char *sq): ZZ_p(a) { m_setOTM(sq);}
  // copy constructors with unsigned int moduli
  myZZ_p::myZZ_p(NTL::ZZ &a, unsigned int q): ZZ_p() {this->_ZZ_p__rep=a; m_setOTM(q);}
  myZZ_p::myZZ_p(const NTL::ZZ &a, unsigned int q): ZZ_p() {this->_ZZ_p__rep=a; m_setOTM(q);}
  myZZ_p::myZZ_p(NTL::ZZ_p &a, unsigned int q): ZZ_p(a) { m_setOTM(q);}
  myZZ_p::myZZ_p(const NTL::ZZ_p &a, unsigned int q): ZZ_p(a) { m_setOTM(q);}

  //move copy constructors
  myZZ_p::myZZ_p(NTL::ZZ &&a) : ZZ_p() {this->_ZZ_p__rep.swap(a);}
  myZZ_p::myZZ_p(NTL::ZZ_p &&a) : ZZ_p() {this->swap(a);}

  myZZ_p  myZZ_p::MultiplyAndRound(const myZZ &p, const myZZ &q) const
  {
    myZZ ans(this->_ZZ_p__rep);
    ans *= p;
    ans = ans.DivideAndRound(q);
    return myZZ_p(ans);
  }

  myZZ_p myZZ_p::DivideAndRound(const myZZ &q) const
  {
    myZZ ans(this->_ZZ_p__rep);
     ans = ans.DivideAndRound(q);
    return myZZ_p(ans);
  }

  usint myZZ_p::GetMSB() const {
    //note: originally I did not worry about this, and just set the
    //MSB whenever this was called, but then that violated constness in the
    // various libraries that used this heavily
    //this->SetMSB(); //note no one needs to SetMSB()
    //return m_MSB;

    //SO INSTEAD I am just regenerating the MSB each time
    size_t sz = this->_ZZ_p__rep.size();
    usint MSB;
    //std::cout<<"size "<<sz <<" ";
    if (sz==0) { //special case for empty data
      MSB = 0;
      return(MSB);
    }
    MSB = (sz-1) * NTL_ZZ_NBITS; //figure out bit location of all but last limb
    const ZZ_limb_t *zlp = ZZ_limbs_get(this->_ZZ_p__rep);
    usint tmp = GetMSBLimb_t(zlp[sz-1]); //add the value of that last limb.
    MSB+=tmp;
    return(MSB);
  }

  void myZZ_p::SetMSB()
  {
    size_t sz = this->_ZZ_p__rep.size();
    //std::cout<<"size "<<sz <<" ";
    if (sz==0) { //special case for empty data
      m_MSB = 0;
      return;
    }

    m_MSB = (sz-1) * NTL_ZZ_NBITS; //figure out bit location of all but last limb
    //std::cout<<"msb starts with "<<m_MSB<< " ";
    //could also try
    //m_MSB = NumBytes(*this)*8;
    const ZZ_limb_t *zlp = ZZ_limbs_get(this->_ZZ_p__rep);
    //for (usint i = 0; i < sz; i++){
    //std::cout<< "limb["<<i<<"] = "<<zlp[i]<<std::endl;
    //}

    usint tmp = GetMSBLimb_t(zlp[sz-1]); //add the value of that last limb.
    //std::cout<< "tmp = "<<tmp<<std::endl;
    m_MSB+=tmp;
    //std::cout<<"msb ends with "<<m_MSB<< " " <<std::endl;
  }

 // inline static usint GetMSBLimb_t(ZZ_limb_t x){
  usint myZZ_p::GetMSBLimb_t( ZZ_limb_t x) const{
    const usint bval[] =
    {0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4};

    uint64_t r = 0;
    if (x & 0xFFFFFFFF00000000) { r += 32/1; x >>= 32/1; }
    if (x & 0x00000000FFFF0000) { r += 32/2; x >>= 32/2; }
    if (x & 0x000000000000FF00) { r += 32/4; x >>= 32/4; }
    if (x & 0x00000000000000F0) { r += 32/8; x >>= 32/8; }
    return r + bval[x];
  }

  void myZZ_p::m_setOTM(const myZZ &q)
  {
    //should test first but for now just set
    ZZ_p::init(q);
    m_OTM = q;
    m_OTM_state = INITIALIZED;
  }

  bool myZZ_p::m_checkOTM(const myZZ &q) const
  {
#ifdef WARN_BAD_MODULUS
    if (m_OTM_state == GARBAGE){
      //throw std::logic_error("myZZ_p::m_checkOTM() called with uninitialized OTM");
      std::cout<<"myZZ_p::m_checkOTM() called with uninitialized OTM"<<std::endl;
#ifdef PAUSE_BAD_MODULUS
      std::string foo;
      std::cin >> foo;
#endif

    }
#endif
    return (m_OTM == q);
  }

  myZZ& myZZ_p::m_getOTM(void) const
  {
#ifdef WARN_BAD_MODULUS
    if (m_OTM_state == GARBAGE){
      //std::logic_error("myZZ_p::m_getOTM() called with uninitialized OTM");
      std::cout<<"myZZ_p::m_getOTM() called with uninitialized OTM"<<std::endl;
#ifdef PAUSE_BAD_MODULUS
      std::string foo;
      std::cin >> foo;
#endif
    }
#endif
    return m_OTM;
  }

  //adapter kit
  //static const myZZ_p& myZZ_p::zero() {return const myZZ_p(0);}

  // //palisade conversion methods
  // usint myZZ_p::ConvertToUsint() const{
  //   bool dbg_flag = false;

  //   DEBUG("in myZZ_p::ConvertToUsint() this "<<*this);

  //   return (conv<usint>(*this));
  // }
  uint64_t myZZ_p::ConvertToInt() const{
   bool dbg_flag = false;

    DEBUG("in myZZ_p::ConvertToInt() this "<<*this);

    uint64_t result = conv<uint64_t>(*this);
    if (this->GetMSB() >= 64) {
      std::cerr<<"Warning myZZ_p::ConvertToInt() Loss of precision. "<<std::endl;
      std::cerr<<"input  "<< *this<<std::endl;
      std::cerr<<"result  "<< result<<std::endl;
    }
    return result;
  }
  // uint32_t myZZ_p::ConvertToUint32() const { return (conv<uint32_t>(*this));}

 // warning on some platforms usint64_t is implemented as an unsigned
  // long long which is not included in the conv functions in tools.h
  // in which case the following does not compile.

  uint64_t myZZ_p::ConvertToUint64() const{
    static_assert(sizeof(uint64_t) == sizeof(long),
		  "sizeof(uint64_t) != sizeof(long), edit myZZ ConvertToUint64()");
    uint64_t result = conv<uint64_t>(*this);
    if (this->GetMSB() >= 64) {
      std::cerr<<"Warning myZZ_p::ConvertToInt() Loss of precision. "<<std::endl;
      std::cerr<<"input  "<< *this<<std::endl;
      std::cerr<<"result  "<< result<<std::endl;
    }
    return result;
  }
  //float myZZ_p::ConvertToFloat() const{ return (conv<float>(this->_ZZ_p__rep));}
  double myZZ_p::ConvertToDouble() const{ return (conv<double>(this->_ZZ_p__rep));}
  //long double myZZ_p::ConvertToLongDouble() const {
  //  std::cerr<<"can't convert to long double"<<std::endl;
  //  return 0.0L;
  //}

  std::ostream& operator<<(std::ostream& os, const myZZ_p& ptr_obj){
    os << (ZZ_p)ptr_obj;
    return os;
  }

  const std::string myZZ_p::ToString() const
  {
    //todo Not sure if this string is safe, it may be ephemeral if not returned  by value.
    std::stringstream result("");
    result << *this;
    return result.str();
  }

  //optimized ceiling function after division by number of bits in the limb data type.
  usint myZZ_p::ceilIntByUInt( const ZZ_limb_t Number) const{
    //mask to perform bitwise AND
    static ZZ_limb_t mask = NTL_ZZ_NBITS-1;

    if(!Number)
      return 1;
    if((Number&mask)!=0)
      return (Number>>myZZ::m_log2LimbBitLength)+1;
    else
      return Number>>myZZ::m_log2LimbBitLength;
  }
#if 0
  // friend or inherit this? it is the same as gmpint
 //the following code is new serialize/deserialize code from

  // the array and the next
  // two functions convert a ubint in and out of a string of
  // characters the encoding is Base64-like: the first 5 6-bit
  // groupings are Base64 encoded, and the last 2 bits are A-D

  // Note this is, sadly, hardcoded for 32 bit integers and needs Some
  // Work to handle arbitrary sizes

  // precomputed shift amounts for each 6 bit chunk
  static const usint b64_shifts[] = { 0, 6, 12, 18, 24, 30 };
  static const usint B64MASK = 0x3F;

  // this for encoding...
  static char to_base64_char[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

  // and this for decoding...
  static inline unsigned int base64_to_value(char b64) {
    if( isupper(b64) )
      return b64 - 'A';
    else if( islower(b64) )
      return b64 - 'a' + 26;
    else if( isdigit(b64) )
      return b64 - '0' + 52;
    else if( b64 == '+' )
      return 62;
    else
      return 63;
  }

#endif
  // serialization of myZZ_p, calls myZZ.Serialize,
  const std::string myZZ_p::Serialize(const myZZ &modulus) const {
    bool dbg_flag = false;

    //note this does simple serialization, other libraries store small special values for 0 or  -1
    //we ignore this
    DEBUG("mgmp ser "<<*this);
    return (myZZ(this->_ZZ_p__rep)).Serialize();
  }

  // deserialization of myZZ_p, calls myZZ.Deserialize,
  // sets modulus to input  modulus.
  const char * myZZ_p::Deserialize(const char *cp, const myZZ &modulus){
    bool dbg_flag = false;
    const char *cpout;
    clear(*this);
    myZZ(repZZ); //new value store decode

    //DEBUG("cp before in mgminp "<<cp);
    cpout = repZZ.Deserialize(cp);    //cpout is rest of cp after decode
    //DEBUG("cp after in mgminp "<<cpout);
    //save
    *this=myZZ_p(repZZ);
    this->SetModulus(modulus);
    DEBUG("mgmp deser "<<*this);
    SetMSB();

    return cpout;
  }

} // namespace NTL ends

#endif


text:
#define BOOST_TEST_MODULE Resolver
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#define UDR_UNIT_TEST

#include <map>
#include <vector>
#include <utility>

#include <boost/test/unit_test.hpp>
#include <boost/optional.hpp>
#include <boost/variant/static_visitor.hpp>

#include "PackageSpec.hpp"
#include "Resolver.hpp"
#include "TestingPackage.hpp"

typedef UDRTest::TestingPackage PackageType;
typedef PackageType::NameType NameType;
typedef PackageType::VersionType VersionType;
typedef std::vector<NameType> UnsatisfiableType;
typedef std::vector<PackageType> QueryResultsType;
typedef std::vector<PackageType> ResolveResultsType;

class ShouldNotResolveVisitor : public boost::static_visitor<bool> {
private:
    std::vector<NameType> expected;

public:
    ShouldNotResolveVisitor(const std::vector<NameType>& e)
        : expected(e)
        , boost::static_visitor<bool>()
    {
    }
    ShouldNotResolveVisitor(std::vector<NameType>&& e, bool g)
        : expected(std::move(e))
        , boost::static_visitor<bool>()
    {
    }

    bool operator()(const std::vector<PackageType>& packages) const
    {
        BOOST_TEST_MESSAGE("Visited failed resolution");
        return false;
    }
    bool operator()(const std::vector<NameType>& names) const
    {
        if (names == expected) {
            BOOST_TEST_MESSAGE("Visited correct unsatisfiable names");
            return true;
        }
        else {
            BOOST_TEST_MESSAGE("Visited incorrect unsatisfiable names "
                    << names[0]);
            return false;
        }
    }
};

class ShouldResolveVisitor : public boost::static_visitor<bool> {
private:
    std::vector<PackageType> expected;

public:
    ShouldResolveVisitor(const std::vector<PackageType>& e)
        : expected(e)
        , boost::static_visitor<bool>()
    {
    }
    ShouldResolveVisitor(std::vector<PackageType>&& e)
        : expected(std::move(e))
        , boost::static_visitor<bool>()
    {
    }

    bool operator()(const std::vector<PackageType>& packages) const
    {
        if (packages == expected) {
            BOOST_TEST_MESSAGE("Visited correct packages");
            return true;
        }
        else {
            BOOST_TEST_MESSAGE("Visited incorrect packages " << packages[0].name);
            return false;
        }
    }
    bool operator()(const std::vector<NameType>& names) const
    {
        BOOST_TEST_MESSAGE("Visited failed resolution");
        return false;
    }
};

BOOST_AUTO_TEST_SUITE(NoDependencies)

class MapQuery
{
private:
    std::map<NameType, QueryResultsType> availablePackages;
public:
    MapQuery() = default;
    MapQuery(const MapQuery& other) = default;
    MapQuery(MapQuery&& other) = default;
    MapQuery& operator= (const MapQuery& other) {
        return *this = std::move(MapQuery(other));
    };
    MapQuery& operator= (MapQuery&& other) {
        this->availablePackages = std::move(other.availablePackages);
    }
    ~MapQuery() {}

    MapQuery(const std::map<NameType, QueryResultsType> & packages) :
        availablePackages(packages)
    {}

    MapQuery(std::map<NameType, QueryResultsType>&& packages) :
        availablePackages(std::move(packages))
    {}

    boost::optional<const std::vector<PackageType> &>
        operator ()(const NameType& n) {
            auto itr = availablePackages.find(n);
            if (itr == availablePackages.end()) {
                return boost::none;
            }
            else {
                return itr->second;
            }
    }
};

struct NoDependenciesFixture
{
    std::map<NameType, QueryResultsType> queryMap{
        { "a",
            { { "a", 25, "a_loc25" },
                { "a", 13, "a_loc13" } } },
        { "c",
            { { "c", 16, "c_loc16" } } }
    };
    MapQuery query{queryMap};
    std::vector<UDR::PackageSpec<PackageType> > request;
    UDR::Resolver<PackageType, MapQuery> resolve{query};
};

BOOST_FIXTURE_TEST_CASE(TestSimpleRetrieval, NoDependenciesFixture)
{
    request = { { "a" } };
    auto result = resolve(
            request);

    BOOST_CHECK(boost::apply_visitor(ShouldResolveVisitor{QueryResultsType{
                    { "a", 25, "a_loc25" }
                    }}, result));

    request = { { "c" } };
    result = resolve(request);
    BOOST_CHECK(boost::apply_visitor(ShouldResolveVisitor{
                    QueryResultsType{ { "c", 16, "c_loc16" } }
                    }, result));
}

BOOST_FIXTURE_TEST_CASE(TestSimpleUnsatisfiable, NoDependenciesFixture)
{
    request = { { "b" } };
    auto result = resolve(request);
    BOOST_CHECK(boost::apply_visitor(ShouldNotResolveVisitor{{
                    "b"
                    }},
                result));
}

BOOST_FIXTURE_TEST_CASE(TestSimpleAlreadyInstalled, NoDependenciesFixture)
{
    request = {
        { "a" },
        { "a" }
    };
    auto result = resolve(request);
    BOOST_CHECK(boost::apply_visitor(ShouldResolveVisitor{QueryResultsType{
                    { "a", 25, "a_loc25" }
                    }}, result));
}

BOOST_AUTO_TEST_SUITE_END()


text:
#include <unordered_map>

#include <boost/filesystem.hpp>
#include <g2o/types/slam3d/edge_se3.h>
#include <g2o/core/block_solver.h>
#include <g2o/solvers/csparse/linear_solver_csparse.h>
#include <g2o/solvers/pcg/linear_solver_pcg.h>
#include <g2o/core/optimization_algorithm_levenberg.h>

#include "GraphOptimizer/OptApp.h"
#include "GraphOptimizer/vertigo/vertex_switchLinear.h"
#include "GraphOptimizer/vertigo/edge_switchPrior.h"
#include "GraphOptimizer/vertigo/edge_se3Switchable.h"

typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>> SlamBlockSolver;
typedef g2o::LinearSolverCSparse<SlamBlockSolver::PoseMatrixType>
    SlamLinearCSparseSolver;
typedef g2o::LinearSolverPCG<SlamBlockSolver::PoseMatrixType>
    SlamLinearPCGSolver;
typedef std::unordered_map<int, g2o::HyperGraph::Vertex *> VertexIDMap;
typedef std::pair<int, g2o::HyperGraph::Vertex *> VertexIDPair;
typedef std::set<g2o::HyperGraph::Edge *> EdgeSet;

COptApp::COptApp(void) {}

COptApp::~COptApp(void) {}

bool COptApp::Init() {
    namespace fs = boost::filesystem;
    if (fs::exists(fs::path(odometry_log_file_))) {
        odometry_traj_.LoadFromFile(odometry_log_file_);
        if (fs::exists(fs::path(odometry_info_file_))) {
            odometry_info_.LoadFromFile(odometry_info_file_);
        }
    }
    if (fs::exists(fs::path(loop_log_file_))) {
        loop_traj_.LoadFromFile(loop_log_file_);
        if (fs::exists(fs::path(loop_info_file_))) {
            loop_info_.LoadFromFile(loop_info_file_);
        }
    }
    pose_traj_.data_.clear();
    pose_traj_.data_.push_back(
        FramedTransformation(0, 0, 1, Eigen::Matrix4d::Identity()));
    for (int i = 0; i < (int)odometry_traj_.data_.size(); i++) {
        pose_traj_.data_.push_back(
            FramedTransformation(i + 1, i + 1, i + 2,
                                 pose_traj_.data_[i].transformation_ *
                                     odometry_traj_.data_[i].transformation_));
    }
    return (odometry_traj_.data_.size() > 0);
}

void COptApp::OptimizeSwitchable() {
    struct SwitchableEdge {
      public:
        VertexSwitchLinear *v_;
        EdgeSwitchPrior *ep_;
        EdgeSE3Switchable *e_;
        FramedTransformation *t_;
    };

    g2o::SparseOptimizer *optimizer;
    optimizer = new g2o::SparseOptimizer();
    optimizer->setVerbose(true);
    SlamBlockSolver *solver = NULL;
    SlamLinearCSparseSolver *linearSolver = new SlamLinearCSparseSolver();
    linearSolver->setBlockOrdering(false);
    solver = new SlamBlockSolver(linearSolver);
    g2o::OptimizationAlgorithmLevenberg *algo =
        new g2o::OptimizationAlgorithmLevenberg(solver);
    optimizer->setAlgorithm(algo);

    std::vector<SwitchableEdge> switch_edge;

    Eigen::Matrix<double, 6, 6> default_information;
    default_information = Eigen::Matrix<double, 6, 6>::Identity();

    for (int i = 0; i < (int)pose_traj_.data_.size(); i++) {
        g2o::VertexSE3 *v = new g2o::VertexSE3();
        v->setId(i);
        v->setEstimate(Eigen2G2O(pose_traj_.data_[i].transformation_));
        if (i == 0) {
            v->setFixed(true);
        }
        optimizer->addVertex(v);

        if (i > 0) {
            g2o::EdgeSE3 *g2o_edge = new g2o::EdgeSE3();
            g2o_edge->vertices()[0] =
                dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(i - 1));
            g2o_edge->vertices()[1] =
                dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(i));
            g2o_edge->setMeasurement(g2o::internal::fromSE3Quat(
                Eigen2G2O(odometry_traj_.data_[i - 1].transformation_)));
            if (odometry_info_.data_.size() > 0) {
                g2o_edge->setInformation(
                    odometry_info_.data_[i - 1].information_);
            } else {
                g2o_edge->setInformation(default_information);
            }
            optimizer->addEdge(g2o_edge);
        }
    }

    for (int i = 0; i < (int)loop_traj_.data_.size(); i++) {
        FramedTransformation &t = loop_traj_.data_[i];

        SwitchableEdge edge;
        edge.t_ = &t;

        edge.v_ = new VertexSwitchLinear();
        edge.v_->setId(optimizer->vertices().size());
        edge.v_->setEstimate(1.0);
        optimizer->addVertex(edge.v_);

        edge.ep_ = new EdgeSwitchPrior();
        edge.ep_->vertices()[0] = edge.v_;
        edge.ep_->setMeasurement(1.0);
        edge.ep_->setInformation(Eigen::Matrix<double, 1, 1>::Identity() *
                                 weight_);
        optimizer->addEdge(edge.ep_);

        edge.e_ = new EdgeSE3Switchable();
        edge.e_->vertices()[0] =
            dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(t.id1_));
        edge.e_->vertices()[1] =
            dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(t.id2_));
        edge.e_->vertices()[2] = edge.v_;
        edge.e_->setMeasurement(
            g2o::internal::fromSE3Quat(Eigen2G2O(t.transformation_)));
        if (loop_info_.data_.size() > 0) {
            edge.e_->setInformation(loop_info_.data_[i].information_);
        } else {
            edge.e_->setInformation(default_information);
        }
        optimizer->addEdge(edge.e_);
        switch_edge.push_back(edge);
    }

    optimizer->initializeOptimization();
    optimizer->optimize(max_iteration_);

    for (int i = 0; i < (int)pose_traj_.data_.size(); i++) {
        g2o::VertexSE3 *v =
            dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(i));
        pose_traj_.data_[i].transformation_ =
            G2O2Matrix4d(v->estimateAsSE3Quat());
    }
    pose_traj_.SaveToFile(pose_log_file_);

    loop_remain_traj_.data_.clear();
    for (int i = 0; i < (int)switch_edge.size(); i++) {
        SwitchableEdge &edge = switch_edge[i];
        if (edge.v_->estimate() > 0.5) {
            loop_remain_traj_.data_.push_back(loop_traj_.data_[i]);
        }
    }
    loop_remain_traj_.SaveToFile(loop_remain_log_file_);

    refine_traj_.data_.clear();
    for (int i = 0; i < (int)odometry_traj_.data_.size(); i++) {
        refine_traj_.data_.push_back(odometry_traj_.data_[i]);
    }
    for (int i = 0; i < (int)switch_edge.size(); i++) {
        SwitchableEdge &edge = switch_edge[i];
        if (edge.v_->estimate() > 0.5 &&
            loop_traj_.data_[i].id1_ + 1 < loop_traj_.data_[i].id2_) {
            refine_traj_.data_.push_back(loop_traj_.data_[i]);
        }
    }
    refine_traj_.SaveToFile(refine_log_file_);
}

void COptApp::OptimizeEM() {
    struct SwitchableEdge {
      public:
        double weight_;
        g2o::EdgeSE3 *e_;
        FramedTransformation *t_;
    };

    g2o::SparseOptimizer *optimizer;
    optimizer = new g2o::SparseOptimizer();
    optimizer->setVerbose(true);
    SlamBlockSolver *solver = NULL;
    SlamLinearCSparseSolver *linearSolver = new SlamLinearCSparseSolver();
    linearSolver->setBlockOrdering(false);
    solver = new SlamBlockSolver(linearSolver);
    g2o::OptimizationAlgorithmLevenberg *algo =
        new g2o::OptimizationAlgorithmLevenberg(solver);
    optimizer->setAlgorithm(algo);

    std::vector<SwitchableEdge> switch_edge;

    Eigen::Matrix<double, 6, 6> default_information;
    default_information = Eigen::Matrix<double, 6, 6>::Identity();

    for (int i = 0; i < (int)pose_traj_.data_.size(); i++) {
        g2o::VertexSE3 *v = new g2o::VertexSE3();
        v->setId(i);
        v->setEstimate(Eigen2G2O(pose_traj_.data_[i].transformation_));
        if (i == 0) {
            v->setFixed(true);
        }
        optimizer->addVertex(v);

        if (i > 0) {
            g2o::EdgeSE3 *g2o_edge = new g2o::EdgeSE3();
            g2o_edge->vertices()[0] =
                dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(i - 1));
            g2o_edge->vertices()[1] =
                dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(i));
            g2o_edge->setMeasurement(g2o::internal::fromSE3Quat(
                Eigen2G2O(odometry_traj_.data_[i - 1].transformation_)));
            if (odometry_info_.data_.size() > 0) {
                g2o_edge->setInformation(
                    odometry_info_.data_[i - 1].information_);
            } else {
                g2o_edge->setInformation(default_information);
            }
            optimizer->addEdge(g2o_edge);
        }
    }

    for (int i = 0; i < (int)loop_traj_.data_.size(); i++) {
        FramedTransformation &t = loop_traj_.data_[i];
        SwitchableEdge edge;
        edge.t_ = &t;
        edge.weight_ = 0.0;

        edge.e_ = new g2o::EdgeSE3();
        edge.e_->vertices()[0] =
            dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(t.id1_));
        edge.e_->vertices()[1] =
            dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(t.id2_));
        edge.e_->setMeasurement(
            g2o::internal::fromSE3Quat(Eigen2G2O(t.transformation_)));
        if (loop_info_.data_.size() > 0) {
            edge.e_->setInformation(loop_info_.data_[i].information_);
        } else {
            edge.e_->setInformation(default_information);
        }
        optimizer->addEdge(edge.e_);
        switch_edge.push_back(edge);
    }

    for (int itr = 0; itr < max_iteration_; itr++) {
        // E step
        for (int i = 0; i < (int)switch_edge.size(); i++) {
            SwitchableEdge &edge = switch_edge[i];
            if (loop_info_.data_.size() > 0) {
                edge.e_->setInformation(loop_info_.data_[i].information_);
            } else {
                edge.e_->setInformation(default_information);
            }
            edge.e_->computeError();
            edge.weight_ = (weight_ * weight_) /
                           (weight_ * weight_ + switch_edge[i].e_->chi2());

            if (loop_info_.data_.size() > 0) {
                edge.e_->setInformation(loop_info_.data_[i].information_ *
                                        sqrt(edge.weight_));
            } else {
                edge.e_->setInformation(default_information *
                                        sqrt(edge.weight_));
            }
        }

        // M step
        optimizer->initializeOptimization();
        optimizer->optimize(1);
    }

    for (int i = 0; i < (int)pose_traj_.data_.size(); i++) {
        g2o::VertexSE3 *v =
            dynamic_cast<g2o::VertexSE3 *>(optimizer->vertex(i));
        pose_traj_.data_[i].transformation_ =
            G2O2Matrix4d(v->estimateAsSE3Quat());
    }
    pose_traj_.SaveToFile(pose_log_file_);

    loop_remain_traj_.data_.clear();
    for (int i = 0; i < (int)switch_edge.size(); i++) {
        SwitchableEdge &edge = switch_edge[i];
        if (edge.weight_ > 0.25) {
            loop_remain_traj_.data_.push_back(loop_traj_.data_[i]);
        }
    }
    loop_remain_traj_.SaveToFile(loop_remain_log_file_);
}

max_stars_repo_name: yxlao/ElasticReconstruction

max_issues_repo_name: yxlao/ElasticReconstruction

max_forks_repo_name: yxlao/ElasticReconstruction


text:
/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

#include "oper/ifmap_dependency_manager.h"

#include <boost/bind.hpp>

#include "base/test/task_test_util.h"
#include "db/db.h"
#include "db/db_graph.h"
#include "db/db_table_partition.h"
#include "db/test/db_test_util.h"
#include "ifmap/ifmap_agent_table.h"
#include "ifmap/ifmap_table.h"
#include "ifmap/test/ifmap_test_util.h"
#include "schema/vnc_cfg_types.h"
#include "testing/gunit.h"

class TestEntry : public DBEntry {
  public:
    class TestEntryKey : public DBRequestKey {
      public:
        TestEntryKey(const std::string &name)
                : name_(name) {
        }
        virtual ~TestEntryKey() {
        }
        const std::string &name() const { return name_; }
      private:
        std::string name_;
    };

    TestEntry() : node_(NULL) {
    }

    virtual std::string ToString() const {
        std::stringstream ss;
        ss << "test-entry:" << name_;
        return ss.str();
    }

    virtual KeyPtr GetDBRequestKey() const {
        KeyPtr key(new TestEntryKey(name_));
        return key;
    }

    virtual void SetKey(const DBRequestKey *key) {
        const TestEntryKey *test_key = static_cast<const TestEntryKey *>(key);
        name_ = test_key->name();
    }

    virtual bool IsLess(const DBEntry &rhs) const {
        const TestEntry &entry = static_cast<const TestEntry &>(rhs);
        return name_ < entry.name_;
    }

    const std::string  &name() const { return name_; }

    IFMapNode *node() { return node_; }
    void set_node(IFMapNode *node) { node_ = node; }
    void reset_node() { node_ = NULL; }

  private:
    std::string name_;
    IFMapNode *node_;
};

class TestTable : public DBTable {
  public:
    TestTable(DB *db, const std::string &name)
            : DBTable(db, name) {
    }
    virtual std::auto_ptr<DBEntry> AllocEntry(const DBRequestKey *key) const {
        std::auto_ptr<DBEntry> entry(new TestEntry());
        entry->SetKey(key);
        return entry;
    }
    static DBTableBase *CreateTable(DB *db, const std::string &name) {
        TestTable *table = new TestTable(db, name);
        table->Init();
        return table;
    }
};

class IFMapDependencyManagerTest : public ::testing::Test {
  protected:
    IFMapDependencyManagerTest()
            : manager_(new IFMapDependencyManager(&database_, &graph_)),
              test_table_(NULL) {
    }

    virtual void SetUp() {
        DB::RegisterFactory("db.test.0", &TestTable::CreateTable);
        test_table_ = static_cast<TestTable *>(
            database_.CreateTable("db.test.0"));
        IFMapAgentLinkTable_Init(&database_, &graph_);
        vnc_cfg_Agent_ModuleInit(&database_, &graph_);
        manager_->Initialize();
    }

    virtual void TearDown() {
        RemoveAllObjects();

        manager_->Terminate();
        IFMapLinkTable *link_table = static_cast<IFMapLinkTable *>(
            database_.FindTable(IFMAP_AGENT_LINK_DB_NAME));
        assert(link_table);
        link_table->Clear();
        db_util::Clear(&database_);
    }

    void AddObject(const std::string &id_name) {
        DBRequest request;
        request.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
        request.key.reset(new TestEntry::TestEntryKey(id_name));
        test_table_->Enqueue(&request);
    }

    void CreateObject(const std::string &id_typename,
                      const std::string &id_name) {
        IFMapTable *table = IFMapTable::FindTable(&database_, id_typename);
        IFMapNode *node = table->FindNode(id_name);
        ASSERT_TRUE(node != NULL);
        AddObject(id_name);
        task_util::WaitForIdle();
        TestEntry::TestEntryKey key(id_name);
        DBEntry *entry = test_table_->Find(&key);
        ASSERT_TRUE(entry != NULL);
        TestEntry *test_entry = static_cast<TestEntry *>(entry);
        manager_->SetObject(node, entry);
        test_entry->set_node(node);
    }

    void RemoveAllObjects() {
        DBTablePartition *tslice = static_cast<DBTablePartition *>(
            test_table_->GetTablePartition(0));
        typedef std::vector<std::string> IdList;
        IdList list;

        for (DBEntry *entry = tslice->GetFirst(); entry;
             entry = tslice->GetNext(entry)) {
            TestEntry *test_entry = static_cast<TestEntry *>(entry);
            manager_->ResetObject(test_entry->node());
            test_entry->reset_node();
            list.push_back(test_entry->name());
        }

        for (IdList::iterator iter = list.begin(); iter != list.end(); ++iter) {
            DBRequest request;
            request.oper = DBRequest::DB_ENTRY_DELETE;
            request.key.reset(new TestEntry::TestEntryKey(*iter));
            test_table_->Enqueue(&request);
        }
    }

    void ChangeEventHandler(DBEntry *entry) {
        change_list_.push_back(entry);
    }

    DB database_;
    DBGraph graph_;
    std::auto_ptr<IFMapDependencyManager> manager_;
    std::vector<DBEntry *> change_list_;
    TestTable *test_table_;
};

TEST_F(IFMapDependencyManagerTest, VirtualMachineEvent) {
    typedef IFMapDependencyManagerTest_VirtualMachineEvent_Test TestClass;
    manager_->Register(
        "service-instance",
        boost::bind(&TestClass::ChangeEventHandler, this, _1));

    ifmap_test_util::IFMapMsgNodeAdd(&database_, "service-instance", "id-1");
    task_util::WaitForIdle();
    CreateObject("service-instance", "id-1");

    ifmap_test_util::IFMapMsgNodeAdd(&database_, "virtual-machine", "id-1");
    ifmap_test_util::IFMapMsgLink(&database_, "service-instance", "id-1",
                                  "virtual-machine", "id-1",
                                  "virtual-machine-service-instance");
    task_util::WaitForIdle();
    ASSERT_EQ(1, change_list_.size());
    TestEntry *entry = static_cast<TestEntry *>(change_list_.at(0));
    EXPECT_EQ("id-1", entry->name());
}

TEST_F(IFMapDependencyManagerTest, TemplateEvent) {
    typedef IFMapDependencyManagerTest_TemplateEvent_Test TestClass;
    manager_->Register(
        "service-instance",
        boost::bind(&TestClass::ChangeEventHandler, this, _1));

    ifmap_test_util::IFMapMsgNodeAdd(&database_, "service-instance", "id-1");
    task_util::WaitForIdle();
    CreateObject("service-instance", "id-1");

    ifmap_test_util::IFMapMsgNodeAdd(&database_, "service-template", "id-1");
    ifmap_test_util::IFMapMsgLink(&database_, "service-instance", "id-1",
                                  "service-template", "id-1",
                                  "service-instance-service-template");
    task_util::WaitForIdle();
    ASSERT_EQ(1, change_list_.size());
    TestEntry *entry = static_cast<TestEntry *>(change_list_.at(0));
    EXPECT_EQ("id-1", entry->name());
}

TEST_F(IFMapDependencyManagerTest, VMIEvent) {
    typedef IFMapDependencyManagerTest_VMIEvent_Test TestClass;
    manager_->Register(
        "service-instance",
        boost::bind(&TestClass::ChangeEventHandler, this, _1));

    ifmap_test_util::IFMapMsgNodeAdd(&database_, "service-instance", "id-1");
    task_util::WaitForIdle();
    CreateObject("service-instance", "id-1");

    ifmap_test_util::IFMapMsgNodeAdd(&database_, "service-instance", "id-2");
    task_util::WaitForIdle();
    CreateObject("service-instance", "id-2");

    ifmap_test_util::IFMapMsgNodeAdd(&database_, "virtual-machine", "id-1");
    ifmap_test_util::IFMapMsgLink(&database_, "service-instance", "id-1",
                                  "virtual-machine", "id-1",
                                  "virtual-machine-service-instance");

    ifmap_test_util::IFMapMsgNodeAdd(&database_,
                                     "virtual-machine-interface",
                                     "id-1-left");
    ifmap_test_util::IFMapMsgLink(
        &database_,
        "virtual-machine-interface", "id-1-left",
        "virtual-machine", "id-1",
        "virtual-machine-interface-virtual-machine");

    task_util::WaitForIdle();
    ASSERT_LE(1, change_list_.size());
    for (uint32_t i = 0; i < change_list_.size(); ++i) {
        TestEntry *entry = static_cast<TestEntry *>(change_list_.at(i));
        EXPECT_EQ("id-1", entry->name());
    }
    change_list_.clear();

    ifmap_test_util::IFMapMsgNodeAdd(&database_, "virtual-machine", "id-1");
    ifmap_test_util::IFMapMsgLink(&database_, "service-instance", "id-1",
                                  "virtual-machine", "id-1",
                                  "virtual-machine-service-instance");

    ifmap_test_util::IFMapMsgNodeAdd(&database_,
                                     "virtual-machine-interface",
                                     "id-1-right");
    ifmap_test_util::IFMapMsgLink(
        &database_,
        "virtual-machine-interface", "id-1-right",
        "virtual-machine", "id-1",
        "virtual-machine-interface-virtual-machine");

    task_util::WaitForIdle();
    ASSERT_LE(1, change_list_.size());
    for (uint32_t i = 0; i < change_list_.size(); ++i) {
        TestEntry *entry = static_cast<TestEntry *>(change_list_.at(i));
        EXPECT_EQ("id-1", entry->name());
    }
    change_list_.clear();

    ifmap_test_util::IFMapMsgNodeAdd(&database_, "virtual-machine", "id-2");
    ifmap_test_util::IFMapMsgLink(&database_, "service-instance", "id-2",
                                  "virtual-machine", "id-2",
                                  "virtual-machine-service-instance");

    ifmap_test_util::IFMapMsgNodeAdd(&database_,
                                     "virtual-machine-interface",
                                     "id-2-left");
    ifmap_test_util::IFMapMsgLink(
        &database_,
        "virtual-machine-interface", "id-2-left",
        "virtual-machine", "id-2",
        "virtual-machine-interface-virtual-machine");

    task_util::WaitForIdle();
    ASSERT_LE(1, change_list_.size());
    for (uint32_t i = 0; i < change_list_.size(); ++i) {
        TestEntry *entry = static_cast<TestEntry *>(change_list_.at(i));
        EXPECT_EQ("id-2", entry->name());
    }
    change_list_.clear();
}

static void SetUp() {
}

static void TearDown() {
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    SetUp();
    int result = RUN_ALL_TESTS();
    TearDown();
    return result;
}

ext: cc


text:
#include <iostream>
#include <cmath>
#include <vector>
#include <array>
#include <math.h>
#include "heatEquation.hpp"
#include "TriDiagMatrix.hpp"
#include "MassMatrix.hpp"
#include "StiffnessMatrix.hpp"
#include <fstream>
#include <string>
#include <boost/math/quadrature/gauss.hpp>
using namespace std;
using namespace boost::math::quadrature;

void printQuadrature();
double f( double x);
double g (double x);
double h (double x);
const double M_PI = 2*acos(0);

int main(int argc, char* argv[])
{

SpaceMesh smesh;
//smesh.GenerateDefaultSpaceMesh();
//smesh.GloballyBisectSpaceMesh();
smesh.GenerateSpaceMesh({0, 0.15, 0.25, 0.5, 1});

//smesh.GloballyBisectSpaceMesh();
//smesh.GloballyBisectSpaceMesh();

TimeMesh tmesh;
tmesh.GenerateUniformTimeMesh(pow(smesh.meshsize(), 2), 1.0);

HeatEquation heat;
heat.SetSpaceTimeMesh( smesh, tmesh, "soultion1.txt");
heat.Solve();

smesh.PrintSpaceNodes();
heat.PrintSolution();

}

max_stars_repo_path: Simple Heat Equation solver class/Driver for simple heat equation classes.cpp

max_stars_repo_name: thabomiles/FEMHeatEquation

max_issues_repo_name: thabomiles/FEMHeatEquation

max_forks_repo_name: thabomiles/FEMHeatEquation


text:
#pragma once

#include <mutex>

#include <boost/config.hpp>

#include <boost/asio.hpp>
#include <boost/bimap/bimap.hpp>
#include <boost/bimap/multiset_of.hpp>

#include "Radio.hpp"

#include "rc-fshare/rtp.hpp"

/**
 * @brief Interface for the radio over regular network interface
 *
 * TODO(Kyle): Clean this up by removing dual-radio support.
 */
class NetworkRadio : public Radio {
public:
    NetworkRadio(int server_port);

    virtual bool isOpen() const override;

    // This `send` method actually sends separate control packets to all robots
    // to maintain backwards compatibility with the old radio API.
    // TODO(Kyle) Rearchitect radio code to avoid needing to do this.
    virtual void send(Packet::RadioTx& packet) override;

    virtual void receive() override;

    virtual void switchTeam(bool) override;

protected:
    // Bidrectional mapping from IP address <-> robot ID
    // TODO(Kyle): Add a timeout to remove robots from this once they're no
    // longer communicating with soccer
    using RobotIpMap = boost::bimaps::bimap<
        boost::bimaps::multiset_of<int>,
        boost::bimaps::set_of<boost::asio::ip::udp::endpoint>>;
    RobotIpMap _robot_ip_map;

    bool open();
    void receivePacket(const boost::system::error_code& error,
                       std::size_t num_bytes);

    void startReceive();

    void registerRobot(int robot, boost::asio::ip::udp::endpoint ip);

    boost::asio::io_service _context;
    boost::asio::ip::udp::socket _socket;

    // Written by `async_receive_from`.
    std::array<char, rtp::ReverseSize> _recv_buffer;
    boost::asio::ip::udp::endpoint _robot_endpoint;

    // Read from by `async_send_to`
    std::vector<
        std::array<uint8_t, rtp::HeaderSize + sizeof(rtp::RobotTxMessage)>>
        _send_buffers;
};


text:
// Copyright 2018 Peter Dimov
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt

#include <boost/core/lightweight_test.hpp>
#include <string.h>

int main( int ac, char const* av[] )
{
    BOOST_TEST_EQ( ac, 2 );

    if( ac >= 2 )
    {
        BOOST_TEST_CSTR_EQ( av[1], "pumpkin" );
    }

    return boost::report_errors();
}

max_issues_repo_name: qingkouwei/mediaones

max_forks_repo_name: qingkouwei/mediaones


text:
#include <boost/test/unit_test.hpp>
#include "algorithms/data_structures/string/reverse_words_in_string.hpp"

BOOST_AUTO_TEST_SUITE(ReverseWordsInString)

BOOST_AUTO_TEST_CASE(empty_string)
{
    {
        std::string str = "";
        Algo::DS::String::ReverseWords::ReverseWordsOrder(str);
        BOOST_CHECK("" == str);
    }

    {
        std::string str = " ";
        Algo::DS::String::ReverseWords::ReverseWordsOrder(str);
        BOOST_CHECK("" == str);
    }

    {
        std::string str = "     ";
        Algo::DS::String::ReverseWords::ReverseWordsOrder(str);
        BOOST_CHECK("" == str);
    }

    {
        std::string str = "";
        Algo::DS::String::ReverseWords::ReverseLettersInWords(str);
        BOOST_CHECK("" == str);
    }
}

BOOST_AUTO_TEST_CASE(one_word)
{
    {
        std::string str = "a";
        Algo::DS::String::ReverseWords::ReverseWordsOrder(str);
        BOOST_CHECK("a" == str);
    }

    {
        std::string str = "a    ", expected = "a";
        Algo::DS::String::ReverseWords::ReverseWordsOrder(str);
        BOOST_CHECK("a" == str);
    }

    {
        std::string str = "    a", expected = "a";
        Algo::DS::String::ReverseWords::ReverseWordsOrder(str);
        BOOST_CHECK("a" == str);
    }

    {
        std::string str = "    a   ", expected = "a";
        Algo::DS::String::ReverseWords::ReverseWordsOrder(str);
        BOOST_CHECK("a" == str);
    }

    {
        std::string str = " ab   ", expected = "ab";
        Algo::DS::String::ReverseWords::ReverseWordsOrder(str);
        BOOST_CHECK("ab" == str);
    }

    {
        std::string str = "a";
        Algo::DS::String::ReverseWords::ReverseLettersInWords(str);
        BOOST_CHECK("a" == str);
    }

    {
        std::string str = "ab";
        Algo::DS::String::ReverseWords::ReverseLettersInWords(str);
        BOOST_CHECK("ba" == str);
    }
}

BOOST_AUTO_TEST_CASE(several_words)
{
    {
        std::string str = "ab cd";
        Algo::DS::String::ReverseWords::ReverseWordsOrder(str);
        BOOST_CHECK("cd ab" == str);
    }

    {
        std::string str = "  the  sky is   blue   ";
        Algo::DS::String::ReverseWords::ReverseWordsOrder(str);
        BOOST_CHECK("blue is sky the" == str);
    }

    {
        std::string str = "ab cd";
        Algo::DS::String::ReverseWords::ReverseLettersInWords(str);
        BOOST_CHECK("ba dc" == str);
    }

    {
        std::string str = "the sky is blue";
        Algo::DS::String::ReverseWords::ReverseLettersInWords(str);
        BOOST_CHECK("eht yks si eulb" == str);
    }

    {
        std::string str = "Let's take LeetCode contest";
        Algo::DS::String::ReverseWords::ReverseLettersInWords(str);
        BOOST_CHECK("s'teL ekat edoCteeL tsetnoc" == str);
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: iamantony/CppNotes

max_issues_repo_name: iamantony/CppNotes

max_forks_repo_name: iamantony/CppNotes


text:
/* --------------------------------------------------------------------------
*
* (C) Copyright …
*
* ---------------------------------------------------------------------------
*/

/*!
 * @file GuiTestReconstruction3D.cpp
 * @date 28/03/2018
 * @author Alessandro Bianco
 */

/*!
 * @addtogroup GuiTests
 *
 * Implementation of the GuiTestReconstruction3D class.
 *
 *
 * @{
 */

/* --------------------------------------------------------------------------
 *
 * Includes
 *
 * --------------------------------------------------------------------------
 */
#include "GuiTestReconstruction3D.hpp"
#include <boost/algorithm/string.hpp>

using namespace FrameWrapper;
using namespace Converters;
using namespace PoseWrapper;
using namespace PointCloudWrapper;

/* --------------------------------------------------------------------------
 *
 * Public Member Functions
 *
 * --------------------------------------------------------------------------
 */
GuiTestReconstruction3D::GuiTestReconstruction3D(const std::string& configurationFilePath, const std::string& imageFilesFolder, const std::string& imagesListFileName, ImageFilesType imageFilesType) :
	configurationFilePath(configurationFilePath),
	imageFilesFolder(imageFilesFolder)
	{
	this->imageFilesType = imageFilesType;

	LoadImagesList(imagesListFileName);
	}

GuiTestReconstruction3D::~GuiTestReconstruction3D()
	{

	}

void GuiTestReconstruction3D::Run(CDFF::DFPC::Reconstruction3DInterface& reconstructor3d)
	{
	reconstructor3d.setConfigurationFile(configurationFilePath);
	reconstructor3d.setup();

	FrameConstPtr leftImage, rightImage;
	while( LoadNextImages(leftImage, rightImage) )
		{
		PRINT_TO_LOG("run", "");
		reconstructor3d.leftImageInput(*leftImage);
		reconstructor3d.rightImageInput(*rightImage);
		reconstructor3d.run();
		PRINT_TO_LOG("run", "after");
		reconstructor3d.pointCloudOutput();
		PRINT_TO_LOG("run", "load");
		delete(leftImage);
		delete(rightImage);
		}
	}

/* --------------------------------------------------------------------------
 *
 * Private Member Functions
 *
 * --------------------------------------------------------------------------
 */
void GuiTestReconstruction3D::LoadImagesList(const std::string& imagesListFileName)
	{
	std::stringstream imagesListFilePath;
	imagesListFilePath << imageFilesFolder << "/" << imagesListFileName;
	std::ifstream listFile( imagesListFilePath.str().c_str() );

	ASSERT(listFile.good(), "Error, could not open images list file");

	std::string line;

	std::getline(listFile, line);
	std::getline(listFile, line);
	std::getline(listFile, line);

	while (std::getline(listFile, line))
		{
		std::vector<std::string> stringsList;
		boost::split(stringsList, line, boost::is_any_of(" "));
		imageFileNamesList.push_back( stringsList.at(1) );
		PRINT_TO_LOG("", stringsList.at(1));

		if (imageFilesType == STEREO_CAMERA_TWO_FILES)
			{
			secondImageFileNamesList.push_back( stringsList.at(2) );
			}
		}

	listFile.close();
	}

bool GuiTestReconstruction3D::LoadNextImages(FrameConstPtr& leftImage, FrameConstPtr& rightImage)
	{
	static unsigned time = 0;
	if (time >= imageFileNamesList.size() )
		{
		return false;
		}

	std::stringstream nextImageFileName;
	nextImageFileName << imageFilesFolder << "/" << imageFileNamesList.at(time);
	cv::Mat cvLeftImage, cvRightImage;

	std::stringstream inputStream;
	inputStream << (time+1) << "/" << imageFileNamesList.size();
	std::string inputString = inputStream.str();
	PRINT_TO_LOG("input", inputString);

	if (imageFilesType == MONO_CAMERA)
		{
		cvLeftImage = cv::imread(nextImageFileName.str(), cv::IMREAD_COLOR);
		cvRightImage = cvLeftImage.clone();
		}
	else if (imageFilesType == STEREO_CAMERA_ONE_FILE)
		{
		cv::Mat cvImage = cv::imread(nextImageFileName.str(), cv::IMREAD_COLOR);
		cvLeftImage = cvImage( cv::Rect(0, 0, cvImage.cols/2, cvImage.rows) );
		cvRightImage = cvImage( cv::Rect(cvImage.cols/2, 0, cvImage.cols/2, cvImage.rows) );
		}
	else if (imageFilesType == STEREO_CAMERA_TWO_FILES)
		{
		std::stringstream secondImageFileName;
		secondImageFileName << imageFilesFolder << "/" << secondImageFileNamesList.at(time);

		cvLeftImage = cv::imread(nextImageFileName.str(), cv::IMREAD_COLOR);
		cvRightImage = cv::imread(secondImageFileName.str(), cv::IMREAD_COLOR);
		}
	else
		{
		ASSERT(false, "Unhandled image file type");
		}

	leftImage = frameConverter.Convert(cvLeftImage);
	rightImage = frameConverter.Convert(cvRightImage);

	time++;
	return true;
	}

/** @} */


text:
#ifndef BOOST_CERTIFY_TLS_DETAIL_KEYSTORE_WINDOWS
#define BOOST_CERTIFY_TLS_DETAIL_KEYSTORE_WINDOWS

#include <boost/asio/ssl/verify_context.hpp>
#include <boost/smart_ptr/make_unique.hpp>

#include <sstream>
#include <wincrypt.h>

namespace boost
{
namespace certify
{
namespace detail
{
struct cert_context_deleter
{
    void operator()(::CERT_CONTEXT const* ctx)
    {
        ::CertFreeCertificateContext(ctx);
    }
};

struct cert_chain_deleter
{
    void operator()(::CERT_CHAIN_CONTEXT const* ctx)
    {
        ::CertFreeCertificateChain(ctx);
    }
};

struct cert_store_deleter
{
    using pointer = HCERTSTORE;

    void operator()(HCERTSTORE store)
    {
        CertCloseStore(store, 0);
    }
};

BOOST_CERTIFY_DECL std::unique_ptr<::CERT_CHAIN_CONTEXT const, cert_chain_deleter>
get_cert_chain_context(::CERT_CONTEXT const* cert_ctx, CERT_CHAIN_PARA* params)
{
    ::CERT_CHAIN_CONTEXT const* ctx = nullptr;
    auto const success =
      ::CertGetCertificateChain(nullptr,
                                cert_ctx,
                                nullptr,
                                cert_ctx->hCertStore,
                                params,
                                CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY,
                                nullptr,
                                &ctx);

    std::unique_ptr<::CERT_CHAIN_CONTEXT const, cert_chain_deleter> ret{ctx};
    if (!success)
    {
        return nullptr;
    }

    return ret;
}

BOOST_CERTIFY_DECL bool
dump_cert(X509* cert, std::vector<std::uint8_t>& buffer)
{
    auto cert_len = ::i2d_X509(cert, nullptr);
    if (cert_len < 0)
        return false;
    buffer.resize(cert_len);
    auto* buf_ptr = buffer.data();
    auto cert_len2 = ::i2d_X509(cert, &buf_ptr);
    if (cert_len != cert_len2)
        return false;
    return true;
}

BOOST_CERTIFY_DECL std::unique_ptr<::CERT_CONTEXT const, cert_context_deleter>
  create_cert_ctx(STACK_OF(X509) * chain)
{
    std::unique_ptr<HCERTSTORE, cert_store_deleter> store{
      CertOpenStore(CERT_STORE_PROV_MEMORY,
                    0,
                    NULL,
                    CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG,
                    nullptr)};

    std::vector<std::uint8_t> buffer;

    PCCERT_CONTEXT leaf_cert = nullptr;

    if (!dump_cert(sk_X509_value(chain, 0), buffer))
        return nullptr;

    if (!CertAddEncodedCertificateToStore(store.get(),
                                          X509_ASN_ENCODING,
                                          buffer.data(),
                                          static_cast<DWORD>(buffer.size()),
                                          CERT_STORE_ADD_ALWAYS,
                                          &leaf_cert))
        return nullptr;

    std::unique_ptr<::CERT_CONTEXT const, cert_context_deleter> ret{leaf_cert};
    for (int i = 1; i < sk_X509_num(chain); ++i)
    {
        if (!dump_cert(sk_X509_value(chain, i), buffer))
            return nullptr;

        if (!CertAddEncodedCertificateToStore(store.get(),
                                              X509_ASN_ENCODING,
                                              buffer.data(),
                                              static_cast<DWORD>(buffer.size()),
                                              CERT_STORE_ADD_ALWAYS,
                                              nullptr))
            return nullptr;
    }

    return ret;
}

BOOST_CERTIFY_DECL bool
verify_certificate_chain(::X509_STORE_CTX* ctx)
{
    auto* const chain = ::X509_STORE_CTX_get_chain(ctx);
    if (sk_X509_num(chain) <= 0)
        return false;

    auto cert_ctx = create_cert_ctx(chain);
    if (cert_ctx == nullptr)
        return false;

    char oidPkixKpServerAuth[] = szOID_PKIX_KP_SERVER_AUTH;
    char oidServerGatedCrypto[] = szOID_SERVER_GATED_CRYPTO;
    char oidSgcNetscape[] = szOID_SGC_NETSCAPE;
    std::array<char*, 3> chain_usage = {
      oidPkixKpServerAuth,
      oidServerGatedCrypto,
      oidSgcNetscape,
    };

    ::CERT_CHAIN_PARA chain_params = {sizeof(chain_params)};
    chain_params.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR;
    chain_params.RequestedUsage.Usage.cUsageIdentifier =
      static_cast<DWORD>(chain_usage.size());
    chain_params.RequestedUsage.Usage.rgpszUsageIdentifier = chain_usage.data();
    auto const cert_chain_context =
      get_cert_chain_context(cert_ctx.get(), &chain_params);
    if (cert_chain_context == nullptr ||
        cert_chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR)
        return false;

    ::HTTPSPolicyCallbackData policyData = {
      {sizeof(policyData)},
      AUTHTYPE_SERVER,
      0,
      nullptr,
    };
    ::CERT_CHAIN_POLICY_PARA policy_params = {sizeof(policy_params)};
    policy_params.pvExtraPolicyPara = &policyData;
    ::CERT_CHAIN_POLICY_STATUS policy_status = {sizeof(policy_status)};

    return ::CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
                                              cert_chain_context.get(),
                                              &policy_params,
                                              &policy_status) &&
           policy_status.dwError == 0;
}

} // namespace detail
} // namespace certify
} // namespace boost

#endif // BOOST_CERTIFY_TLS_DETAIL_KEYSTORE_WINDOWS

ext: ipp


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

#pragma once

#include <boost/filesystem.hpp>

#include <nil/actor/core/future.hh>
#include <nil/actor/core/file.hh>
#include <nil/actor/core/thread.hh>

#include <nil/actor/detail/defer.hh>

namespace nil {
    namespace actor {

        const boost::filesystem::path &default_tmpdir();
        void set_default_tmpdir(boost::filesystem::path);

        class tmp_file {
            boost::filesystem::path _path;
            file _file;
            bool _is_open = false;

            static_assert(std::is_nothrow_constructible<boost::filesystem::path>::value,
                          "filesystem::path's constructor must not throw");
            static_assert(std::is_nothrow_move_constructible<boost::filesystem::path>::value,
                          "filesystem::path's move constructor must not throw");

        public:
            tmp_file() noexcept = default;
            tmp_file(const tmp_file &) = delete;
            tmp_file(tmp_file &&x) noexcept;

            tmp_file &operator=(tmp_file &&) noexcept = default;

            ~tmp_file();

            future<> open(boost::filesystem::path path_template = default_tmpdir(),
                          open_flags oflags = open_flags::rw,
                          file_open_options options = {}) noexcept;
            future<> close() noexcept;
            future<> remove() noexcept;

            template<typename Func>
            static future<> do_with(boost::filesystem::path path_template, Func &&func,
                                    open_flags oflags = open_flags::rw, file_open_options options = {}) noexcept {
                static_assert(std::is_nothrow_move_constructible<Func>::value,
                              "Func's move constructor must not throw");
                return nil::actor::do_with(tmp_file(), [func = std::move(func),
                                                        path_template = std::move(path_template), oflags,
                                                        options = std::move(options)](tmp_file &t) mutable {
                    return t.open(std::move(path_template), oflags, std::move(options))
                        .then([&t, func = std::move(func)]() mutable { return func(t); })
                        .finally([&t] { return t.close().finally([&t] { return t.remove(); }); });
                });
            }

            template<typename Func>
            static future<> do_with(Func &&func) noexcept {
                return do_with(default_tmpdir(), std::move(func));
            }

            bool has_path() const {
                return !_path.empty();
            }

            bool is_open() const {
                return _is_open;
            }

            const boost::filesystem::path &get_path() const {
                return _path;
            }

            file &get_file() {
                return _file;
            }
        };

        /// Returns a future for an opened tmp_file exclusively created by the function.
        ///
        /// \param path_template - path where the file is to be created,
        ///                        optionally including a template for the file name.
        /// \param oflags - optional \ref open_flags (open_flags::create | open_flags::exclusive are added to those by
        /// default) \param options - additional \ref file_open_options, e.g. for setting the created file permission.
        ///
        /// \note
        ///    path_template may optionally include a filename template in the last component of the path.
        ///    The template is indicated by two or more consecutive XX's.
        ///    Those will be replaced in the result path by a unique string.
        ///
        ///    If no filename template is found, then path_template is assumed to refer to the directory where
        ///    the temporary file is to be created at (a.k.a. the parent directory) and `default_tmp_name_template`
        ///    is appended to the path as the filename template.
        ///
        ///    The parent directory must exist and be writable to the current process.
        ///
        future<tmp_file> make_tmp_file(boost::filesystem::path path_template = default_tmpdir(),
                                       open_flags oflags = open_flags::rw, file_open_options options = {}) noexcept;

        class tmp_dir {
            boost::filesystem::path _path;

        public:
            tmp_dir() = default;
            tmp_dir(const tmp_dir &) = delete;
            tmp_dir(tmp_dir &&x) = default;

            tmp_dir &operator=(tmp_dir &&) noexcept = default;

            ~tmp_dir();

            future<> create(boost::filesystem::path path_template = default_tmpdir(),
                            file_permissions create_permissions = file_permissions::default_dir_permissions) noexcept;
            future<> remove() noexcept;

            template<typename Func>
#ifdef BOOST_HAS_CONCEPTS
            requires std::is_nothrow_move_constructible<Func>::value
#endif
                static future<>
                do_with(boost::filesystem::path path_template, Func &&func,
                        file_permissions create_permissions = file_permissions::default_dir_permissions) noexcept {
                static_assert(std::is_nothrow_move_constructible_v<Func>, "Func's move constructor must not throw");
                return nil::actor::do_with(tmp_dir(), [func = std::move(func), path_template = std::move(path_template),
                                                       create_permissions](tmp_dir &t) mutable {
                    return t.create(std::move(path_template), create_permissions)
                        .then([&t, func = std::move(func)]() mutable { return func(t); })
                        .finally([&t] { return t.remove(); });
                });
            }

            template<typename Func>
            static future<> do_with(Func &&func) noexcept {
                return do_with(default_tmpdir(), std::move(func));
            }

            template<typename Func>
#ifdef BOOST_HAS_CONCEPTS
            requires std::is_nothrow_move_constructible<Func>::value
#endif
                static future<>
                do_with_thread(Func &&func) noexcept {
                static_assert(std::is_nothrow_move_constructible_v<Func>, "Func's move constructor must not throw");
                return async([func = std::move(func)]() mutable {
                    auto t = tmp_dir();
                    t.create().get();
                    futurize_invoke(func, t).finally([&t] { return t.remove(); }).get();
                });
            }

            bool has_path() const {
                return !_path.empty();
            }

            const boost::filesystem::path &get_path() const {
                return _path;
            }
        };

        /// Returns a future for a tmp_dir exclusively created by the function.
        ///
        /// \param path_template - path where the file is to be created,
        ///                        optionally including a template for the file name.
        /// \param create_permissions - optional permissions for the newly created directory.
        ///
        /// \note
        ///    path_template may optionally include a name template in the last component of the path.
        ///    The template is indicated by two or more consecutive XX's.
        ///    Those will be replaced in the result path by a unique string.
        ///
        ///    If no name template is found, then path_template is assumed to refer to the directory where
        ///    the temporary dir is to be created at (a.k.a. the parent directory) and `default_tmp_name_template`
        ///    is appended to the path as the name template for the to-be-created directory.
        ///
        ///    The parent directory must exist and be writable to the current process.
        ///
        future<tmp_dir>
            make_tmp_dir(boost::filesystem::path path_template = default_tmpdir(),
                         file_permissions create_permissions = file_permissions::default_dir_permissions) noexcept;

    }    // namespace actor
}    // namespace nil

ext: hh

max_stars_repo_name: NilFoundation/actor-core

max_issues_repo_name: NilFoundation/actor-core

max_forks_repo_name: NilFoundation/actor-core


text:
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Zen Gaem Engine Framework
//
// Copyright (C) 2001 - 2016 Raymond A. Richards
//
//  This software is provided 'as-is', without any express or implied
//  warranty.  In no event will the authors be held liable for any damages
//  arising from the use of this software.
//
//  Permission is granted to anyone to use this software for any purpose,
//  including commercial applications, and to alter it and redistribute it
//  freely, subject to the following restrictions:
//
//  1. The origin of this software must not be misrepresented; you must not
//     claim that you wrote the original software. If you use this software
//     in a product, an acknowledgment in the product documentation would be
//     appreciated but is not required.
//  2. Altered source versions must be plainly marked as such, and must not be
//     misrepresented as being the original software.
//  3. This notice may not be removed or altered from any source distribution.
//
//  Tony Richards trichards@indiezen.com
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#include "LuaType.hpp"
#include "LuaModule.hpp"
#include "LuaMethod.hpp"
#include "LuaEngine.hpp"

#include <Zen/Core/Scripting/I_ObjectReference.hpp>

#include <sstream>

#include <stddef.h>

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

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen {
namespace ZLua {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
LuaType::LuaType(LuaModule* _pModule, const std::string& _name, const std::string& _docString, unsigned long _rawSize)
:   m_pModule(_pModule)
,   m_name(_name)
,   m_docString(_docString)
{
    std::ostringstream fullName;
    fullName << m_pModule->getName() << "." << m_name;
    m_fullName = fullName.str();
}

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
LuaType::~LuaType()
{
}

void
LuaType::openlib (lua_State *L, const char *libname, int nup)
{
  if (libname) {
    int size = (int)m_methods.size();
    /* check whether lib already exists */
    luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);
    lua_getfield(L, -1, libname);  /* get _LOADED[libname] */
    if (!lua_istable(L, -1)) {  /* not found? */
      lua_pop(L, 1);  /* remove previous result */
      /* try global variable (and create one if it does not exist) */
      if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != NULL)
        luaL_error(L, "name conflict for module " LUA_QS, libname);
      lua_pushvalue(L, -1);
      lua_setfield(L, -3, libname);  /* _LOADED[libname] = new table */
    }
    lua_remove(L, -2);  /* remove _LOADED table */
    lua_insert(L, -(nup+1));  /* move library table to below upvalues */
  }

  // Iterate through the methods
  for(methods_type::iterator iter = m_methods.begin(); iter != m_methods.end(); iter++)
  {
    int i;
    for (i=0; i<nup; i++)  /* copy upvalues to the top */
      lua_pushvalue(L, -nup);
    lua_pushcclosure(L, (*iter)->m_pCFunction, nup);
    lua_setfield(L, -(nup+2), (*iter)->m_name.c_str());
  }
  lua_pop(L, nup);  /* remove upvalues */
}

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
void
LuaType::activate()
{
    lua_State* const L = getModule().getEngine().getState();

    luaL_newmetatable(L, m_fullName.c_str());

    // __index = the meta table
    lua_pushstring(L, "__index");
    lua_pushvalue(L, -2);
    lua_settable(L, -3);

    // __gc = the garbage collector
    lua_pushstring(L, "__gc");
    lua_pushcfunction(L, *(lua_CFunction*)&boost::bind(&LuaType::gc, this, _1));
    lua_settable(L, -3);

    //luaL_openlib(L, NULL, arraylib_m, 0);

    // Add the methods to this __index
    openlib(L, NULL, 0);

    // Add the static methods
    //luaL_openlib(L, m_name.c_str(), arraylib_f, 0);

    // And pop the table off the stack
    lua_pop(L, 1);
}

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
LuaType::pScriptModule_type
LuaType::getScriptModule()
{
    return getModule().getSelfReference().lock();
}

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
const std::string&
LuaType::getTypeName()
{
    return m_name;
}

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
const std::string&
LuaType::getDocumentation()
{
    return m_docString;
}

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
int
LuaType::gc(lua_State* L)
{
    std::cout << "DEBUG: Lua garbage collector called for " << m_name << std::endl;
    /// TODO Determine how to 'clean up' a LuaObject correctly such that it
    /// either deletes an allocated object or decrements the use count of
    /// an associated managed pointer.
    return 0;
}

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
}   // namespace ZLua
}   // namespace Zen
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~

max_stars_repo_name: indie-zen-plugins/ZLua

max_issues_repo_name: indie-zen-plugins/ZLua

max_forks_repo_name: indie-zen-plugins/ZLua