text:
#include <boost/interprocess/indexes/flat_map_index.hpp>
#include <boost/interprocess/indexes/map_index.hpp>
#include <boost/interprocess/indexes/null_index.hpp>
#include <boost/interprocess/indexes/unordered_map_index.hpp>
#include <boost/interprocess/indexes/iset_index.hpp>
#include <boost/interprocess/indexes/iunordered_set_index.hpp>

#include <boost/interprocess/mem_algo/simple_seq_fit.hpp>
#include <boost/interprocess/mem_algo/rbtree_best_fit.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/segment_manager.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/sync/mutex_family.hpp>
#include <boost/interprocess/exceptions.hpp>
#include "get_process_id_name.hpp"
#include <cstddef>
#include <new>
#include <cstring>

using namespace boost::interprocess;

template <class SegmentManager>
struct atomic_func_test
{
   SegmentManager &rsm;
   int *object;

   atomic_func_test(SegmentManager &sm)
      : rsm(sm), object()
   {}

   void operator()()
   {
      object = rsm.template find<int>("atomic_func_find_object").first;
   }
   private:
   atomic_func_test operator=(const atomic_func_test&);
   atomic_func_test(const atomic_func_test&);
};

template <class SegmentManager>
bool test_segment_manager()
{
   typedef typename SegmentManager::size_type size_type;
   const unsigned int ShmSizeSize = 1024*64u;
   std::string shmname(test::get_process_id_name());

   shared_memory_object::remove(shmname.c_str());
   shared_memory_object sh_mem( create_only, shmname.c_str(), read_write );
   sh_mem.truncate( ShmSizeSize );
   mapped_region mapping( sh_mem, read_write );

   SegmentManager* seg_mgr = new( mapping.get_address() ) SegmentManager( ShmSizeSize );
   std::size_t free_mem_before = seg_mgr->get_free_memory();
   std::size_t size_before = seg_mgr->get_size();

   if(size_before != ShmSizeSize)
      return false;
   if(!seg_mgr->all_memory_deallocated())
      return false;
   if(seg_mgr->get_min_size() >= ShmSizeSize)
      return false;

   {//test get_free_memory() / allocate()/deallocate()
      const size_type Size = ShmSizeSize/2;
      void *mem = seg_mgr->allocate(Size+1);
      const size_type free_mem = seg_mgr->get_free_memory();
      if(free_mem >= Size)
         return false;
      if(seg_mgr->all_memory_deallocated())
         return false;
      const size_type Size2 = free_mem/2;
      void *mem2 = seg_mgr->allocate(size_type(Size2+1), std::nothrow);
      if(seg_mgr->get_free_memory() >= Size2)
         return false;
      if(seg_mgr->size(mem) < (Size+1))
         return false;
      if(seg_mgr->size(mem2) < (Size2+1))
         return false;
      seg_mgr->deallocate(mem);
      seg_mgr->deallocate(mem2);
      if(!seg_mgr->all_memory_deallocated())
         return false;
      if(seg_mgr->get_free_memory() != free_mem_before)
         return false;
      try{  seg_mgr->allocate(ShmSizeSize*2);  }catch(interprocess_exception&){}
      if(seg_mgr->get_free_memory() != free_mem_before)
         return false;
      if(seg_mgr->allocate(ShmSizeSize*2, std::nothrow))
         return false;
      if(seg_mgr->get_free_memory() != free_mem_before)
         return false;
   }
   {//test allocate_aligned
      const std::size_t Alignment = 128u;
      void *mem = seg_mgr->allocate_aligned(ShmSizeSize/4, Alignment);
      if(seg_mgr->all_memory_deallocated())
         return false;
      std::size_t offset = static_cast<std::size_t>
         (static_cast<const char *>(mem) -  static_cast<const char *>(mapping.get_address()));
      if(offset & (Alignment-1))
         return false;
      void *mem2 = seg_mgr->allocate_aligned(ShmSizeSize/4, Alignment, std::nothrow);
      std::size_t offset2 = static_cast<std::size_t>
         (static_cast<const char *>(mem2) -  static_cast<const char *>(mapping.get_address()));
      if(offset2 & (Alignment-1))
         return false;
      seg_mgr->deallocate(mem);
      seg_mgr->deallocate(mem2);
      if(!seg_mgr->all_memory_deallocated())
         return false;
      if(seg_mgr->get_free_memory() != free_mem_before)
         return false;
      try{  seg_mgr->allocate_aligned(ShmSizeSize*2, Alignment);  }catch(interprocess_exception&){}
      if(seg_mgr->get_free_memory() != free_mem_before)
         return false;
      if(seg_mgr->allocate_aligned(ShmSizeSize*2, Alignment, std::nothrow))
         return false;
      if(seg_mgr->get_free_memory() != free_mem_before)
         return false;
   }
   {//test shrink_to_fit

      seg_mgr->shrink_to_fit();
      if(!seg_mgr->all_memory_deallocated())
         return false;
      std::size_t empty_shrunk_size     = seg_mgr->get_size();
      std::size_t empty_shrunk_free_mem = seg_mgr->get_free_memory();
      if(empty_shrunk_size >= size_before)
         return false;
      if(empty_shrunk_free_mem >= size_before)
         return false;
      seg_mgr->grow(size_type(size_before - empty_shrunk_size));
      if(seg_mgr->get_size() != size_before)
         return false;
      if(seg_mgr->get_free_memory() != free_mem_before)
         return false;
      if(!seg_mgr->all_memory_deallocated())
         return false;
   }
   {//test zero_free_memory
      const size_type Size(ShmSizeSize/2+1), Size2(ShmSizeSize/8);
      void *mem  = seg_mgr->allocate(Size);
      void *mem2 = seg_mgr->allocate(Size2);
      //Mark memory to non-zero
      std::memset(mem,  0xFF, Size);
      std::memset(mem2, 0xFF, Size2);
      //Deallocate and check still non-zero
      seg_mgr->deallocate(mem);
      seg_mgr->deallocate(mem2);
      {  //Use byte per byte comparison as "static unsigned char zerobuf[Size]"
         //seems to be problematic in some compilers
         unsigned char *const mem_uch_ptr  = static_cast<unsigned char *>(mem);
         unsigned char *const mem2_uch_ptr = static_cast<unsigned char *>(mem2);
         size_type zeroes = 0;
         for(size_type i = 0; i != Size; ++i){
            if(!mem_uch_ptr[i])
               ++zeroes;
         }
         if(zeroes == Size)
            return false;

         zeroes = 0;
         for(size_type i = 0; i != Size2; ++i){
            if(!mem2_uch_ptr[i])
               ++zeroes;
         }
         if(zeroes == Size2)
            return false;
      }
      //zero_free_memory and check it's zeroed
      seg_mgr->zero_free_memory();
      //TODO: some parts are not zeroed because they are used
      //as internal metadata, find a way to test this
      //if(std::memcmp(mem,  zerobuf, Size))
         //return false;
      //if(std::memcmp(mem2, zerobuf, Size2))
         //return false;
      if(seg_mgr->get_free_memory() != free_mem_before)
         return false;
      if(!seg_mgr->all_memory_deallocated())
         return false;
   }

   {//test anonymous object
      int *int_object  = seg_mgr->template construct<int>(anonymous_instance)();
      if(1 != seg_mgr->get_instance_length(int_object))
         return false;
      if(anonymous_type != seg_mgr->get_instance_type(int_object))
         return false;
      if(seg_mgr->get_instance_name(int_object))
         return false;
      seg_mgr->destroy_ptr(int_object);
      int const int_array_values[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
      int *int_array  = seg_mgr->template construct_it<int>(anonymous_instance, std::nothrow)[10](&int_array_values[0]);
      if(10 != seg_mgr->get_instance_length(int_object))
         return false;
      if(anonymous_type != seg_mgr->get_instance_type(int_array))
         return false;
      if(seg_mgr->get_instance_name(int_array))
         return false;
      seg_mgr->destroy_ptr(int_array);
      try{  seg_mgr->template construct<int>(anonymous_instance)[ShmSizeSize]();  }catch(interprocess_exception&){}
      if(seg_mgr->template construct<int>(anonymous_instance, std::nothrow)[ShmSizeSize]())
      try{  seg_mgr->template construct_it<int>(anonymous_instance)[ShmSizeSize](&int_array_values[0]);  }catch(interprocess_exception&){}
      if(seg_mgr->template construct_it<int>(anonymous_instance, std::nothrow)[ShmSizeSize](&int_array_values[0]))
         return false;
      if(seg_mgr->get_free_memory() != free_mem_before)
         return false;
      if(!seg_mgr->all_memory_deallocated())
         return false;
   }

   {//test named object
      const char *const object1_name = "object1";
      const char *const object2_name = "object2";
      int const int_array_values[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

      for(std::size_t i = 0; i != 1/*4*/; ++i){
         if(seg_mgr->template find<unsigned int>(object1_name).first)
            return false;
         //Single element construction
         unsigned int *uint_object = 0;
         switch(i){
            case 0:
               uint_object = seg_mgr->template construct<unsigned int>(object1_name)();
            break;
            case 1:
               uint_object = seg_mgr->template construct<unsigned int>(object1_name, std::nothrow)();
            break;
            case 2:
               uint_object = seg_mgr->template find_or_construct<unsigned int>(object1_name)();
            break;
            case 3:
               uint_object = seg_mgr->template find_or_construct<unsigned int>(object1_name, std::nothrow)();
            break;
         }
         std::pair<unsigned int*, std::size_t> find_ret = seg_mgr->template find<unsigned int>(object1_name);
         if(uint_object != find_ret.first)
            return false;
         if(1 != find_ret.second)
            return false;
         if(1 != seg_mgr->get_instance_length(uint_object))
            return false;
         if(named_type != seg_mgr->get_instance_type(uint_object))
            return false;
         if(std::strcmp(object1_name, seg_mgr->get_instance_name(uint_object)))
            return false;
         //Array construction
         if(seg_mgr->template find<int>(object2_name).first)
            return false;
         int *int_array = 0;
         switch(i){
            case 0:
               int_array = seg_mgr->template construct_it<int>(object2_name)[10](&int_array_values[0]);
            break;
            case 1:
               int_array = seg_mgr->template construct_it<int>(object2_name, std::nothrow)[10](&int_array_values[0]);
            break;
            case 2:
               int_array = seg_mgr->template find_or_construct_it<int>(object2_name)[10](&int_array_values[0]);
            break;
            case 3:
               int_array = seg_mgr->template find_or_construct_it<int>(object2_name, std::nothrow)[10](&int_array_values[0]);
            break;
         }
         std::pair<int*, std::size_t> find_ret2 = seg_mgr->template find<int>(object2_name);
         if(int_array != find_ret2.first)
            return false;
         if(10 != find_ret2.second)
            return false;
         if(10 != seg_mgr->get_instance_length(int_array))
            return false;
         if(named_type != seg_mgr->get_instance_type(int_array))
            return false;
         if(std::strcmp(object2_name, seg_mgr->get_instance_name(int_array)))
            return false;
         if(seg_mgr->get_num_named_objects() != 2)
            return false;
         typename SegmentManager::const_named_iterator nb(seg_mgr->named_begin());
         typename SegmentManager::const_named_iterator ne(seg_mgr->named_end());
         for(std::size_t i = 0, imax = seg_mgr->get_num_named_objects(); i != imax; ++i){ ++nb; }
         if(nb != ne)
            return false;
         seg_mgr->destroy_ptr(uint_object);
         seg_mgr->template destroy<int>(object2_name);
      }
      try{  seg_mgr->template construct<unsigned int>(object1_name)[ShmSizeSize]();  }catch(interprocess_exception&){}
      if(seg_mgr->template construct<int>(object2_name, std::nothrow)[ShmSizeSize]())
      try{  seg_mgr->template construct_it<unsigned int>(object1_name)[ShmSizeSize](&int_array_values[0]);  }catch(interprocess_exception&){}
      if(seg_mgr->template construct_it<int>(object2_name, std::nothrow)[ShmSizeSize](&int_array_values[0]))
         return false;
      seg_mgr->shrink_to_fit_indexes();
      if(seg_mgr->get_free_memory() != free_mem_before)
         return false;
      if(!seg_mgr->all_memory_deallocated())
         return false;
      seg_mgr->reserve_named_objects(1);
      //In indexes with no capacity() memory won't be allocated so don't check anything was allocated.
      //if(seg_mgr->all_memory_deallocated())  return false;
      seg_mgr->shrink_to_fit_indexes();
      if(!seg_mgr->all_memory_deallocated())
         return false;
   }

   {//test unique object
      int const int_array_values[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

      for(std::size_t i = 0; i != 4; ++i){
         if(seg_mgr->template find<unsigned int>(unique_instance).first)
            return false;
         //Single element construction
         unsigned int *uint_object = 0;
         switch(i){
            case 0:
               uint_object = seg_mgr->template construct<unsigned int>(unique_instance)();
            break;
            case 1:
               uint_object = seg_mgr->template construct<unsigned int>(unique_instance, std::nothrow)();
            break;
            case 2:
               uint_object = seg_mgr->template find_or_construct<unsigned int>(unique_instance)();
            break;
            case 3:
               uint_object = seg_mgr->template find_or_construct<unsigned int>(unique_instance, std::nothrow)();
            break;
         }
         std::pair<unsigned int*, std::size_t> find_ret = seg_mgr->template find<unsigned int>(unique_instance);
         if(uint_object != find_ret.first)
            return false;
         if(1 != find_ret.second)
            return false;
         if(1 != seg_mgr->get_instance_length(uint_object))
            return false;
         if(unique_type != seg_mgr->get_instance_type(uint_object))
            return false;
         if(std::strcmp(typeid(unsigned int).name(), seg_mgr->get_instance_name(uint_object)))
            return false;
         //Array construction
         if(seg_mgr->template find<int>(unique_instance).first)
            return false;
         int *int_array = 0;
         switch(i){
            case 0:
               int_array = seg_mgr->template construct_it<int>(unique_instance)[10](&int_array_values[0]);
            break;
            case 1:
               int_array = seg_mgr->template construct_it<int>(unique_instance, std::nothrow)[10](&int_array_values[0]);
            break;
            case 2:
               int_array = seg_mgr->template find_or_construct_it<int>(unique_instance)[10](&int_array_values[0]);
            break;
            case 3:
               int_array = seg_mgr->template find_or_construct_it<int>(unique_instance, std::nothrow)[10](&int_array_values[0]);
            break;
         }
         std::pair<int*, std::size_t> find_ret2 = seg_mgr->template find<int>(unique_instance);
         if(int_array != find_ret2.first)
            return false;
         if(10 != find_ret2.second)
            return false;
         if(10 != seg_mgr->get_instance_length(int_array))
            return false;
         if(unique_type != seg_mgr->get_instance_type(int_array))
            return false;
         if(std::strcmp(typeid(int).name(), seg_mgr->get_instance_name(int_array)))
            return false;
         if(seg_mgr->get_num_unique_objects() != 2)
            return false;
         typename SegmentManager::const_unique_iterator nb(seg_mgr->unique_begin());
         typename SegmentManager::const_unique_iterator ne(seg_mgr->unique_end());
         for(std::size_t i = 0, imax = seg_mgr->get_num_unique_objects(); i != imax; ++i){ ++nb; }
         if(nb != ne)
            return false;
         seg_mgr->destroy_ptr(uint_object);
         seg_mgr->template destroy<int>(unique_instance);
      }
      try{  seg_mgr->template construct<unsigned int>(unique_instance)[ShmSizeSize]();  }catch(interprocess_exception&){}
      if(seg_mgr->template construct<int>(unique_instance, std::nothrow)[ShmSizeSize]())
      try{  seg_mgr->template construct_it<unsigned int>(unique_instance)[ShmSizeSize](&int_array_values[0]);  }catch(interprocess_exception&){}
      if(seg_mgr->template construct_it<int>(unique_instance, std::nothrow)[ShmSizeSize](&int_array_values[0]))
         return false;
      seg_mgr->shrink_to_fit_indexes();
      if(seg_mgr->get_free_memory() != free_mem_before)
         return false;
      if(!seg_mgr->all_memory_deallocated())
         return false;
      seg_mgr->reserve_unique_objects(1);
      //In indexes with no capacity() memory won't be allocated so don't check anything was allocated.
      //if(seg_mgr->all_memory_deallocated())  return false;
      seg_mgr->shrink_to_fit_indexes();
      if(!seg_mgr->all_memory_deallocated())
         return false;
   }
   {//test allocator/deleter
      if(!seg_mgr->all_memory_deallocated())
         return false;
      typedef typename SegmentManager::template allocator<float>::type allocator_t;

      allocator_t alloc(seg_mgr->template get_allocator<float>());

      if(!seg_mgr->all_memory_deallocated())
         return false;
      offset_ptr<float> f = alloc.allocate(50);
      if(seg_mgr->all_memory_deallocated())
         return false;
      alloc.deallocate(f, 50);
      if(!seg_mgr->all_memory_deallocated())
         return false;
      typedef typename SegmentManager::template deleter<float>::type deleter_t;
      deleter_t delet(seg_mgr->template get_deleter<float>());
      delet(seg_mgr->template construct<float>(anonymous_instance)());
      if(!seg_mgr->all_memory_deallocated())
         return false;
   }
   {//test allocator/deleter
      if(!seg_mgr->all_memory_deallocated())
         return false;
      int *int_object  = seg_mgr->template construct<int>("atomic_func_find_object")();
      atomic_func_test<SegmentManager> func(*seg_mgr);
      seg_mgr->atomic_func(func);
      if(int_object != func.object)
         return 1;
      seg_mgr->destroy_ptr(int_object);
      seg_mgr->shrink_to_fit_indexes();
      if(!seg_mgr->all_memory_deallocated())
         return false;
   }
   return true;
}

template<class MemoryAlgorithm>
bool test_each_algo()
{
   {
      typedef segment_manager< char, MemoryAlgorithm, flat_map_index > segment_manager_t;
      if(!test_segment_manager<segment_manager_t>())
         return false;
   }
   {
      typedef segment_manager< char, MemoryAlgorithm, map_index > segment_manager_t;
      if(!test_segment_manager<segment_manager_t>())
         return false;
   }
   /*
   {
      typedef segment_manager< char, MemoryAlgorithm, null_index > segment_manager_t;
      if(!test_segment_manager<segment_manager_t>())
         return false;
   }*/
   /*
   {
      typedef segment_manager< char, MemoryAlgorithm, unordered_map_index > segment_manager_t;
      if(!test_segment_manager<segment_manager_t>())
         return false;
   }*/
   {
      typedef segment_manager< char, MemoryAlgorithm, iset_index > segment_manager_t;
      if(!test_segment_manager<segment_manager_t>())
         return false;
   }
   {
      typedef segment_manager< char, MemoryAlgorithm, iunordered_set_index > segment_manager_t;
      if(!test_segment_manager<segment_manager_t>())
         return false;
   }
   return true;
}

int main()
{
   if(!test_each_algo< simple_seq_fit< null_mutex_family > >())
      return 1;
   if(!test_each_algo< rbtree_best_fit< null_mutex_family > >())
      return 1;

   return 0;
}


text:
#include "metadata.h"
#include <opencv2/highgui/highgui.hpp>

#include <boost/version.hpp>

#if BOOST_VERSION >= 104500
	#ifndef BOOST_FILESYSTEM_VERSION
    	#define BOOST_FILESYSTEM_VERSION 3
	#endif
#else
	#ifndef BOOST_FILESYSTEM_VERSION
		#define BOOST_FILESYSTEM_VERSION 2
	#endif
	#error detected boost version is lower than 1.45, I think I will die.
#endif

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

namespace illumestimators {

Metadata::Metadata()
{

}

Metadata::Metadata(const std::string& filename) :
	m_filename(filename)
{

}

Metadata::~Metadata()
{

}

cv::Mat_<cv::Vec3d> Metadata::illuminantMap() const
{
	cv::Mat_<cv::Vec3d> illuminantMap = cv::imread(m_illuminantMapFilename);
	return illuminantMap;
}

cv::Mat_<unsigned char> Metadata::mask() const
{
	cv::Mat_<unsigned char> mask = cv::imread(m_maskFilename, 0);
	return mask;
}

cv::Mat_<unsigned char> Metadata::target() const
{
	cv::Mat_<unsigned char> target = cv::imread(m_targetFilename, 0);
	return target;
}

void Metadata::print() const
{
	std::cout << "Metadata:" << std::endl;
	std::cout << "filename           : " << m_filename << std::endl;
	std::cout << "database           : " << m_database << std::endl;
	std::cout << "scene              : " << m_scene << std::endl;
	std::cout << "colorspace         : " << m_colorspace << std::endl;
	std::cout << "light sources      : " << m_lightSources << std::endl;
		std::cout << "dominant illuminant: " << "r = " << m_dominantIlluminant.r << ", g = " << m_dominantIlluminant.g << ", b = " << m_dominantIlluminant.b << ", "<< std::endl;
	std::cout << "illuminant map     : " << m_illuminantMapFilename << std::endl;
	std::cout << "mask               : " << m_maskFilename << std::endl;
	std::cout << "target             : " << m_targetFilename << std::endl;
	std::cout << std::endl;
}

bool Metadata::parse(std::vector<std::string> labels, std::vector<std::string> values, const std::string& parentPath)
{
	if (labels.size() != values.size()) {
		return false;
	}

	for (unsigned int i = 0; i < labels.size(); i++) {
		std::string label = labels[i];
		std::string value = values[i];

		if (label.compare("filename") == 0) {
			m_filename = fixPath(value, parentPath);
		} else if (label.compare("database") == 0) {
			m_database = value;
		} else if (label.compare("scene") == 0) {
			m_scene = value;
		} else if (label.compare("colorspace") == 0) {
			m_colorspace = value;
		} else if (label.compare("lightsources") == 0) {
			m_lightSources = value;
		} else if (label.compare("r") == 0) {
			std::istringstream iss(value);
			iss >> m_dominantIlluminant.r;
		} else if (label.compare("g") == 0) {
			std::istringstream iss(value);
			iss >> m_dominantIlluminant.g;
		} else if (label.compare("b") == 0) {
			std::istringstream iss(value);
			iss >> m_dominantIlluminant.b;
		} else if (label.compare("illuminantmap") == 0) {
			m_illuminantMapFilename = fixPath(value, parentPath);
		} else if (label.compare("mask") == 0) {
			m_maskFilename = fixPath(value, parentPath);
		} else if (label.compare("target") == 0) {
			m_targetFilename = fixPath(value, parentPath);
		}
	}

	if (m_filename.size() == 0) {
		return false;
	}

	return true;
}

std::string Metadata::fixPath(const std::string& path, const std::string& parentPath) const
{
	std::string fixedPath;

	if (boost::filesystem::path(path).is_absolute()) {
		fixedPath = path;
	} else {
		fixedPath = parentPath + "/" + path;
	}

	/*char* actualpath = realpath(fixedPath.c_str(), NULL);
	if (!actualpath) {
		std::cerr << "The path \"" << path << "\" cannot be resolved!" << std::endl;
		return std::string();
	}
	fixedPath = actualpath;
	free(actualpath);*/

	return fixedPath;
}

} // namespace illumestimators

ext: cpp

max_stars_repo_name: rodrigobressan/PADify

max_issues_repo_name: rodrigobressan/PADify

max_forks_repo_name: rodrigobressan/PADify


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

#include "MissionEndedXML.h"
#include "MissionSpec.h"
#include "XMLParseException.h"

// STL:
#include <exception>
#include <iostream>

// Boost:
#include <boost/property_tree/xml_parser.hpp>

namespace malmo {

    MissionEndedXML::MissionEndedXML(std::string xml_text) {
        boost::property_tree::ptree xml;

        std::istringstream is(xml_text);
        boost::property_tree::read_xml(is, xml);

        schema_version = xml.get_optional<std::string>("MissionEnded.<xmlattr>.SchemaVersion");
        status = xml.get<std::string>("MissionEnded.Status");
        human_readable_status = xml.get<std::string>("MissionEnded.HumanReadableStatus");

        const auto& reward_element = xml.get_child_optional("MissionEnded.Reward");
        have_rewards = reward_element != boost::none;
        if (have_rewards) {
            reward.parse_rewards(reward_element.get());
            if (reward.size() == 0) {
                throw XMLParseException("Reward must have at least one value");
            }
        }

        for (boost::property_tree::ptree::value_type const& v : xml.get_child("MissionEnded.MissionDiagnostics")) {
            if (v.first == "VideoData") {
                VideoDataAttributes attributes;

                attributes.frame_type = v.second.get<std::string>("<xmlattr>.frameType");
                attributes.frames_sent = v.second.get<int>("<xmlattr>.framesSent");
                attributes.frames_received = v.second.get_optional<int>("<xmlattr>.framesReceived");
                attributes.frames_written = v.second.get_optional<int>("<xmlattr>.framesWritten");

                video_data_attributes.push_back(attributes);
            }
        }
    }

    std::string MissionEndedXML::toXml() const {
        std::ostringstream oss;

        boost::property_tree::ptree xml;

        xml.put("MissionEnded.<xmlattr>.xmlns", MissionSpec::MALMO_NAMESPACE);
        xml.put("MissionEnded.<xmlattr>.xmlns:xsi", MissionSpec::XMLNS_XSI);
        if (schema_version)
            xml.put("MissionEnded.<xmlattr>.SchemaVersion", schema_version);
        xml.put("MissionEnded.Status", status);
        xml.put("MissionEnded.HumanReadableStatus", human_readable_status);

        if (have_rewards)
            reward.add_rewards(xml.get_child("MissionEnded"));

        for (auto& d : video_data_attributes) {
            boost::property_tree::ptree videoData;
            videoData.put("<xmlattr>.frameType", d.frame_type);
            videoData.put("<xmlattr>.framesSent", d.frames_sent);
            xml.add_child("MissionEnded.MissionDiagnostics", videoData);
        }

        write_xml(oss, xml);

        std::string xml_str = oss.str();
        xml_str.erase(std::remove(xml_str.begin(), xml_str.end(), '\n'), xml_str.end());

        return xml_str;
    }
}

max_stars_repo_name: Diffblue-benchmarks/Microsoft-malmo

max_issues_repo_name: Diffblue-benchmarks/Microsoft-malmo

max_forks_repo_name: Diffblue-benchmarks/Microsoft-malmo


text:
//  boost/chrono/stopwatches/reporters/system_default_formatter.hpp
//  Copyright 2011 Vicente J. Botet Escriba
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or
//   copy at http://www.boost.org/LICENSE_1_0.txt)
//  See http://www.boost.org/libs/chrono/stopwatches for documentation.

#ifndef BOOST_CHRONO_STOPWATCHES_REPORTERS_SYSTEM_DEFAULT_FORMATTER_HPP
#define BOOST_CHRONO_STOPWATCHES_REPORTERS_SYSTEM_DEFAULT_FORMATTER_HPP

#include <boost/chrono/stopwatches/reporters/stopwatch_reporter_default_formatter.hpp>
#include <boost/chrono/stopwatches/reporters/clock_default_formatter.hpp>
#include <boost/chrono/stopwatches/formatters/elapsed_formatter.hpp>
#include <boost/chrono/system_clocks.hpp>

#endif

ext: hpp

max_stars_repo_name: EdwardPrentice/wrongo

max_issues_repo_name: wujf/mongo

max_forks_repo_name: wujf/mongo


text:
//======================================================================
/*! \file ObjectEcuEt.cpp
 *
 * \copydoc Copyright
 * \author Kai-Uwe von Deylen (kd)
 * \date Mar 14, 2014
 *///-------------------------------------------------------------------

#include <ibeosdk/datablocks/snippets/Measurement.hpp>
#include <ibeosdk/io.hpp>
#include <ibeosdk/Log.hpp>
#include <ibeosdk/Math.hpp>

#include <boost/scoped_array.hpp>

#include <sstream>

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

namespace ibeosdk {

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

Measurement::Measurement()
 :  m_key(0),
    m_data(0)
{}

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

std::streamsize Measurement::getSerializedSize() const
{
	std::streamsize result = std::streamsize(sizeof(UINT16)) // m_key
	                       + std::streamsize(sizeof(UINT8)); // m_measurementType

	switch (this->getMeasurementType()) {
	case TypeVoid:   return result;
	case TypeFloat:  return result + std::streamsize(sizeof(float));
	case TypeDouble: return result + std::streamsize(sizeof(double));
	case TypeINT8:
	case TypeUINT8:  return result + std::streamsize(sizeof(UINT8));
	case TypeINT16:
	case TypeUINT16: return result + std::streamsize(sizeof(UINT16));
	case TypeINT32:
	case TypeUINT32: return result + std::streamsize(sizeof(UINT32));
	case TypeINT64:
	case TypeUINT64: return result + std::streamsize(sizeof(UINT64));
	case TypeBool:   return result + std::streamsize(sizeof(UINT8));
	case TypeStdString:
		result += 4; // 4 bytes for the BLOB data length
		result += std::streamsize(boost::any_cast<std::string>(m_data).size()); // and the BLOB data itself
		break;
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch
	return result;
}

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

bool Measurement::deserialize(std::istream& is)
{
	const int64_t startPos = streamposToInt64(is.tellg());

	union allTypes {
		float flt;
		double dbl;
		int8_t int8;
		uint8_t uint8;
		int16_t int16;
		uint16_t uint16;
		int32_t int32;
		uint32_t uint32;
		int64_t int64;
		uint64_t uint64;
		bool boolean;
	};

	allTypes tmp;

	readBE(is, m_key);

	UINT8 type;
	readBE(is, type);

	switch (MeasurementType(type)) {
	case TypeVoid:   m_data = boost::any();                         break;
	case TypeFloat:  readBE(is, tmp.flt);     m_data = tmp.flt;     break;
	case TypeDouble: readBE(is, tmp.dbl);     m_data = tmp.dbl;     break;
	case TypeINT8:   readBE(is, tmp.int8);    m_data = tmp.int8;    break;
	case TypeUINT8:  readBE(is, tmp.uint8);   m_data = tmp.uint8;   break;
	case TypeINT16:  readBE(is, tmp.int16);   m_data = tmp.int16;   break;
	case TypeUINT16: readBE(is, tmp.uint16);  m_data = tmp.uint16;  break;
	case TypeINT32:  readBE(is, tmp.int32);   m_data = tmp.int32;   break;
	case TypeUINT32: readBE(is, tmp.uint32);  m_data = tmp.uint32;  break;
	case TypeINT64:  readBE(is, tmp.int64);   m_data = tmp.int64;   break;
	case TypeUINT64: readBE(is, tmp.uint64);  m_data = tmp.uint64;  break;
	case TypeBool:   readBE(is, tmp.boolean); m_data = tmp.boolean; break;
	case TypeStdString:
		{
			UINT32 strLen;
			readBE(is, strLen);
			boost::scoped_array<char> strBuf (new char[strLen]);
			is.read(strBuf.get(), strLen);
			m_data = std::string(strBuf.get(), strLen);
		}
		break;
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch

	return !is.fail() && ((streamposToInt64(is.tellg()) - startPos) == this->getSerializedSize());
}

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

bool Measurement::serialize(std::ostream& os) const
{
	const int64_t startPos = streamposToInt64(os.tellp());

	writeBE(os, m_key);

	const MeasurementType mt = this->getMeasurementType();
	const UINT8 type = UINT8(mt);
	writeBE(os, type);

	switch (mt) {
	case TypeVoid:   break;
	case TypeFloat:  writeBE(os, boost::any_cast<float>(m_data));  break;
	case TypeDouble: writeBE(os, boost::any_cast<double>(m_data)); break;
	case TypeINT8:   writeBE(os, boost::any_cast<INT8>(m_data));   break;
	case TypeUINT8:  writeBE(os, boost::any_cast<UINT8>(m_data));  break;
	case TypeINT16:  writeBE(os, boost::any_cast<INT16>(m_data));  break;
	case TypeUINT16: writeBE(os, boost::any_cast<UINT16>(m_data)); break;
	case TypeINT32:  writeBE(os, boost::any_cast<INT32>(m_data));  break;
	case TypeUINT32: writeBE(os, boost::any_cast<UINT32>(m_data)); break;
	case TypeINT64:  writeBE(os, boost::any_cast<INT64>(m_data));  break;
	case TypeUINT64: writeBE(os, boost::any_cast<UINT64>(m_data)); break;
	case TypeBool:   writeBE(os, boost::any_cast<bool>(m_data));   break;
	case TypeStdString:
		writeBE(os, UINT32(boost::any_cast<std::string>(m_data).size()));
		os.write(boost::any_cast<std::string>(m_data).c_str(), std::streamsize(boost::any_cast<std::string>(m_data).size()));
		break;
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch

	return !os.fail() && ((streamposToInt64(os.tellp()) - startPos) == this->getSerializedSize());
}

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

template<>
void Measurement::getAs<void>() const
{
	throw std::runtime_error("Not able to convert any type to void");

}

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

template<>
float Measurement::getAs<float>() const
{
	switch (this->getMeasurementType()) {
	case TypeVoid:
		throw std::runtime_error("Not able to convert from void to float");
	case TypeFloat:    return getData<float>();
	case TypeDouble:   return static_cast<float>(getData<double>());
	case TypeINT8:     return static_cast<float>(getData<INT8>());
	case TypeUINT8:    return static_cast<float>(getData<UINT8>());
	case TypeINT16:    return static_cast<float>(getData<INT16>());
	case TypeUINT16:   return static_cast<float>(getData<UINT16>());
	case TypeINT32:    return static_cast<float>(getData<INT32>());
	case TypeUINT32:   return static_cast<float>(getData<UINT32>());
	case TypeINT64:    return static_cast<float>(getData<INT64>());
	case TypeUINT64:   return static_cast<float>(getData<UINT64>());
	case TypeBool:     return static_cast<float>(getData<bool>());
	case TypeStdString:
		throw std::runtime_error("Not able to convert from std::str to float");
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch
}

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

template<>
double Measurement::getAs<double>() const
{
	switch (this->getMeasurementType()) {
	case TypeVoid:
		throw std::runtime_error("Not able to convert from void to double");
	case TypeFloat:    return static_cast<double>(getData<float>());
	case TypeDouble:   return getData<double>();
	case TypeINT8:     return static_cast<double>(getData<INT8>());
	case TypeUINT8:    return static_cast<double>(getData<UINT8>());
	case TypeINT16:    return static_cast<double>(getData<INT16>());
	case TypeUINT16:   return static_cast<double>(getData<UINT16>());
	case TypeINT32:    return static_cast<double>(getData<INT32>());
	case TypeUINT32:   return static_cast<double>(getData<UINT32>());
	case TypeINT64:    return static_cast<double>(getData<INT64>());
	case TypeUINT64:   return static_cast<double>(getData<UINT64>());
	case TypeBool:     return static_cast<double>(getData<bool>());
	case TypeStdString:
		throw std::runtime_error("Not able to convert from std::str to double");
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch
}

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

template<>
INT8 Measurement::getAs<INT8>() const
{
	switch (this->getMeasurementType()) {
	case TypeVoid:
		throw std::runtime_error("Not able to convert from void to INT8");
	case TypeFloat:    return static_cast<INT8>(getData<float>());
	case TypeDouble:   return static_cast<INT8> (getData<double>());
	case TypeINT8:     return (getData<INT8>());
	case TypeUINT8:    return static_cast<INT8>(getData<UINT8>());
	case TypeINT16:    return static_cast<INT8>(getData<INT16>());
	case TypeUINT16:   return static_cast<INT8>(getData<UINT16>());
	case TypeINT32:    return static_cast<INT8>(getData<INT32>());
	case TypeUINT32:   return static_cast<INT8>(getData<UINT32>());
	case TypeINT64:    return static_cast<INT8>(getData<INT64>());
	case TypeUINT64:   return static_cast<INT8>(getData<UINT64>());
	case TypeBool:     return static_cast<INT8>(getData<bool>());
	case TypeStdString:
		throw std::runtime_error("Not able to convert from std::str to INT8");
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch
}

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

template<>
UINT8 Measurement::getAs<UINT8>() const
{
	switch (this->getMeasurementType()) {
	case TypeVoid:
		throw std::runtime_error("Not able to convert from void to UINT8");
	case TypeFloat:    return static_cast<UINT8>(getData<float>());
	case TypeDouble:   return static_cast<UINT8>(getData<double>());
	case TypeINT8:     return static_cast<UINT8>(getData<INT8>());
	case TypeUINT8:    return (getData<UINT8>());
	case TypeINT16:    return static_cast<UINT8>(getData<INT16>());
	case TypeUINT16:   return static_cast<UINT8>(getData<UINT16>());
	case TypeINT32:    return static_cast<UINT8>(getData<INT32>());
	case TypeUINT32:   return static_cast<UINT8>(getData<UINT32>());
	case TypeINT64:    return static_cast<UINT8>(getData<INT64>());
	case TypeUINT64:   return static_cast<UINT8>(getData<UINT64>());
	case TypeBool:     return static_cast<UINT8>(getData<bool>());
	case TypeStdString:
		throw std::runtime_error("Not able to convert from std::str to UINT8");
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch
}

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

template<>
INT16 Measurement::getAs<INT16>() const
{
	switch (this->getMeasurementType()) {
	case TypeVoid:
		throw std::runtime_error("Not able to convert from void to INT16");
	case TypeFloat:    return static_cast<INT16>(getData<float>());
	case TypeDouble:   return static_cast<INT16>(getData<double>());
	case TypeINT8:     return static_cast<INT16>(getData<INT8>());
	case TypeUINT8:    return static_cast<INT16>(getData<UINT8>());
	case TypeINT16:    return (getData<INT16>());
	case TypeUINT16:   return static_cast<INT16>(getData<UINT16>());
	case TypeINT32:    return static_cast<INT16>(getData<INT32>());
	case TypeUINT32:   return static_cast<INT16>(getData<UINT32>());
	case TypeINT64:    return static_cast<INT16>(getData<INT64>());
	case TypeUINT64:   return static_cast<INT16>(getData<UINT64>());
	case TypeBool:     return static_cast<INT16>(getData<bool>());
	case TypeStdString:
		throw std::runtime_error("Not able to convert from std::str to INT16");
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch
}

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

template<>
UINT16 Measurement::getAs<UINT16>() const
{
	switch (this->getMeasurementType()) {
	case TypeVoid:
		throw std::runtime_error("Not able to convert from void to UINT16");
	case TypeFloat:    return static_cast<UINT16>(getData<float>());
	case TypeDouble:   return static_cast<UINT16>(getData<double>());
	case TypeINT8:     return static_cast<UINT16>(getData<INT8>());
	case TypeUINT8:    return static_cast<UINT16>(getData<UINT8>());
	case TypeINT16:    return static_cast<UINT16>(getData<INT16>());
	case TypeUINT16:   return (getData<UINT16>());
	case TypeINT32:    return static_cast<UINT16>(getData<INT32>());
	case TypeUINT32:   return static_cast<UINT16>(getData<UINT32>());
	case TypeINT64:    return static_cast<UINT16>(getData<INT64>());
	case TypeUINT64:   return static_cast<UINT16>(getData<UINT64>());
	case TypeBool:     return static_cast<UINT16>(getData<bool>());
	case TypeStdString:
		throw std::runtime_error("Not able to convert from std::str to UINT16");
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch
}

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

template<>
INT32 Measurement::getAs<INT32>() const
{
	switch (this->getMeasurementType()) {
	case TypeVoid:
		throw std::runtime_error("Not able to convert from void to INT32");
	case TypeFloat:    return static_cast<INT32>(getData<float>());
	case TypeDouble:   return static_cast<INT32>(getData<double>());
	case TypeINT8:     return static_cast<INT32>(getData<INT8>());
	case TypeUINT8:    return static_cast<INT32>(getData<UINT8>());
	case TypeINT16:    return static_cast<INT32>(getData<INT16>());
	case TypeUINT16:   return static_cast<INT32>(getData<UINT16>());
	case TypeINT32:    return (getData<INT32>());
	case TypeUINT32:   return static_cast<INT32>(getData<UINT32>());
	case TypeINT64:    return static_cast<INT32>(getData<INT64>());
	case TypeUINT64:   return static_cast<INT32>(getData<UINT64>());
	case TypeBool:     return static_cast<INT32>(getData<bool>());
	case TypeStdString:
		throw std::runtime_error("Not able to convert from std::str to INT32");
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch
}

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

template<>
UINT32 Measurement::getAs<UINT32>() const
{
	switch (this->getMeasurementType()) {
	case TypeVoid:
		throw std::runtime_error("Not able to convert from void to UINT32");
	case TypeFloat:    return static_cast<UINT32>(getData<float>());
	case TypeDouble:   return static_cast<UINT32>(getData<double>());
	case TypeINT8:     return static_cast<UINT32>(getData<INT8>());
	case TypeUINT8:    return static_cast<UINT32>(getData<UINT8>());
	case TypeINT16:    return static_cast<UINT32>(getData<INT16>());
	case TypeUINT16:   return static_cast<UINT32>(getData<UINT16>());
	case TypeINT32:    return static_cast<UINT32>(getData<INT32>());
	case TypeUINT32:   return (getData<UINT32>());
	case TypeINT64:    return static_cast<UINT32>(getData<INT64>());
	case TypeUINT64:   return static_cast<UINT32>(getData<UINT64>());
	case TypeBool:     return static_cast<UINT32>(getData<bool>());
	case TypeStdString:
		throw std::runtime_error("Not able to convert from std::str to UINT32");
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch
}

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

template<>
INT64 Measurement::getAs<INT64>() const
{
	switch (this->getMeasurementType()) {
	case TypeVoid:
		throw std::runtime_error("Not able to convert from void to INT64");
	case TypeFloat:    return static_cast<INT64>(getData<float>());
	case TypeDouble:   return static_cast<INT64>(getData<double>());
	case TypeINT8:     return static_cast<INT64>(getData<INT8>());
	case TypeUINT8:    return static_cast<INT64>(getData<UINT8>());
	case TypeINT16:    return static_cast<INT64>(getData<INT16>());
	case TypeUINT16:   return static_cast<INT64>(getData<UINT16>());
	case TypeINT32:    return static_cast<INT64>(getData<INT32>());
	case TypeUINT32:   return static_cast<INT64>(getData<UINT32>());
	case TypeINT64:    return (getData<INT64>());
	case TypeUINT64:   return static_cast<INT64>(getData<UINT64>());
	case TypeBool:     return static_cast<INT64>(getData<bool>());
	case TypeStdString:
		throw std::runtime_error("Not able to convert from std::str to INT64");
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch
}

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

template<>
UINT64 Measurement::getAs<UINT64>() const
{
	switch (this->getMeasurementType()) {
	case TypeVoid:
		throw std::runtime_error("Not able to convert from void to UINT64");
	case TypeFloat:    return static_cast<UINT64>(getData<float>());
	case TypeDouble:   return static_cast<UINT64>(getData<double>());
	case TypeINT8:     return static_cast<UINT64>(getData<INT8>());
	case TypeUINT8:    return static_cast<UINT64>(getData<UINT8>());
	case TypeINT16:    return static_cast<UINT64>(getData<INT16>());
	case TypeUINT16:   return static_cast<UINT64>(getData<UINT16>());
	case TypeINT32:    return static_cast<UINT64>(getData<INT32>());
	case TypeUINT32:   return static_cast<UINT64>(getData<UINT32>());
	case TypeINT64:    return static_cast<UINT64>(getData<INT64>());
	case TypeUINT64:   return (getData<UINT64>());
	case TypeBool:     return static_cast<UINT64>(getData<bool>());
	case TypeStdString:
		throw std::runtime_error("Not able to convert from std::str to UINT64");
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch
}

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

template<>
bool Measurement::getAs<bool>() const
{
	switch (this->getMeasurementType()) {
	case TypeVoid:
		throw std::runtime_error("Not able to convert from void to bool");
	case TypeFloat:    return (getData<float>() == 0.0f);
	case TypeDouble:   return (getData<double>() == 0.0);
	case TypeINT8:     return (getData<INT8>() == 0);
	case TypeUINT8:    return (getData<UINT8>() == 0U);
	case TypeINT16:    return (getData<INT16>() == 0);
	case TypeUINT16:   return (getData<UINT16>() == 0U);
	case TypeINT32:    return (getData<INT32>() == 0);
	case TypeUINT32:   return (getData<UINT32>() == 0U);
	case TypeINT64:    return (getData<INT64>() == 0);
	case TypeUINT64:   return (getData<UINT64>() == 0U);
	case TypeBool:     return (getData<bool>());
	case TypeStdString:
		throw std::runtime_error("Not able to convert from std::str to float");
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch
}

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

template<>
std::string Measurement::getAs<std::string>() const
{
	switch (this->getMeasurementType()) {
	case TypeVoid:
		throw std::runtime_error("Not able to convert from void to std::str");
	case TypeFloat:
		throw std::runtime_error("Not able to convert from float to std::str");
	case TypeDouble:
		throw std::runtime_error("Not able to convert from double to std::str");
	case TypeINT8:
		throw std::runtime_error("Not able to convert from INT8 to std::str");
	case TypeUINT8:
		throw std::runtime_error("Not able to convert from UINT8 to std::str");
	case TypeINT16:
		throw std::runtime_error("Not able to convert from INT16 to std::str");
	case TypeUINT16:
		throw std::runtime_error("Not able to convert from UINT16 to std::str");
	case TypeINT32:
		throw std::runtime_error("Not able to convert from INT32 to std::str");
	case TypeUINT32:
		throw std::runtime_error("Not able to convert from UINT32 to std::str");
	case TypeINT64:
		throw std::runtime_error("Not able to convert from INT64 to std::str");
	case TypeUINT64:
		throw std::runtime_error("Not able to convert from UINT64 to std::str");
	case TypeBool:
		throw std::runtime_error("Not able to convert from bool to std::str");
	case TypeStdString: return (getData<std::string>());
	default:
		throw std::runtime_error("Unknown MeasurementType in Measurement");
	} // switch
}

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

bool Measurement::isEqual(const Measurement& m) const
{
	if ((getKey() != m.getKey()) || (getMeasurementType() != m.getMeasurementType())) {
		return false;
	}

	// Same key, same type. Now check the actual value.
	const MeasurementType mtype = typeIdToType(getType());
	switch (mtype) {
	case TypeVoid:      return true;
	case TypeFloat:     return floatEqual(getData<float>(), m.getData<float>());
	case TypeDouble:    return doubleEqual(getData<double>(), m.getData<double>());
	case TypeINT8:      return getData<INT8>() == m.getData<INT8>();
	case TypeUINT8:     return getData<UINT8>() == m.getData<UINT8>();
	case TypeINT16:     return getData<INT16>() == m.getData<INT16>();
	case TypeUINT16:    return getData<UINT16>() == m.getData<UINT16>();
	case TypeINT32:     return getData<INT32>() == m.getData<INT32>();
	case TypeUINT32:    return getData<UINT32>() == m.getData<UINT32>();
	case TypeINT64:     return getData<INT64>() == m.getData<INT64>();
	case TypeUINT64:    return getData<UINT64>() == m.getData<UINT64>();
	case TypeBool:      return getData<bool>() == m.getData<bool>();
	case TypeStdString: return getData<std::string>() == m.getData<std::string>();
	default:
		throw boost::bad_any_cast();
	}
}

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

Measurement::MeasurementType Measurement::typeIdToType(const std::type_info& tinfo)
{
	if (tinfo == typeid(void)) return TypeVoid;
	else if (tinfo == typeid(float)) return TypeFloat;
	else if (tinfo == typeid(double)) return TypeDouble;
	else if (tinfo == typeid(INT8)) return TypeINT8;
	else if (tinfo == typeid(UINT8)) return TypeUINT8;
	else if (tinfo == typeid(INT16)) return TypeINT16;
	else if (tinfo == typeid(UINT16)) return TypeUINT16;
	else if (tinfo == typeid(INT32)) return TypeINT32;
	else if (tinfo == typeid(UINT32)) return TypeUINT32;
	else if (tinfo == typeid(INT64)) return TypeINT64;
	else if (tinfo == typeid(UINT64)) return TypeUINT64;
	else if (tinfo == typeid(bool)) return TypeBool;
	else if (tinfo == typeid(std::string)) return TypeStdString;
	else {
		logError << "Unknown type_info in Measurement: " << tinfo.name() << std::endl;
		throw std::runtime_error("Unknown type_info in Measurement");
		assert(false);
	}
	return TypeFloat; // To avoid compiler warnings
}

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

bool operator==(const Measurement& lhs, const Measurement& rhs)
{
	return lhs.isEqual(rhs);
}

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

bool operator!=(const Measurement& lhs, const Measurement& rhs)
{
	return !lhs.isEqual(rhs);
}

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

std::ostream& operator<<(std::ostream& oss, const Measurement& m)
{
	oss << "Key=" << m.getKey() << " type=" << m.getMeasurementType() << " ";

	switch(m.getMeasurementType()) {
	case Measurement::TypeFloat:     oss << "TypeFloat(" << m.getData<float>() << ")";           break;
	case Measurement::TypeDouble:    oss << "TypeDouble(" << m.getData<double>() << ")";         break;
	case Measurement::TypeINT8:      oss << "TypeINT8(" << int(m.getData<INT8>()) << ")";        break;
	case Measurement::TypeUINT8:     oss << "TypeUINT8(" << int(m.getData<UINT8>()) << ")";      break;
	case Measurement::TypeINT16:     oss << "TypeINT16(" << m.getData<INT16>() << ")";           break;
	case Measurement::TypeUINT16:    oss << "TypeUINT16(" << m.getData<UINT16>() << ")";         break;
	case Measurement::TypeINT32:     oss << "TypeINT32(" << m.getData<INT32>() << ")";           break;
	case Measurement::TypeUINT32:    oss << "TypeUINT32(" << m.getData<UINT32>() << ")";         break;
	case Measurement::TypeINT64:     oss << "TypeINT64(" << m.getData<INT64>() << ")";           break;
	case Measurement::TypeUINT64:    oss << "TypeUINT64(" << m.getData<UINT64>() << ")";         break;
	case Measurement::TypeBool:      oss << "TypeBool(" << m.getData<bool>() << ")";             break;
	case Measurement::TypeStdString: oss << "TypeStdString(" << m.getData<std::string>() << ")"; break;
	default:
		oss << "Undefined Type(..) ";
		break;
	}

	return oss;
}

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

} // namespace ibeosdk

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


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

#ifndef __tsid_python_contact_6d_hpp__
#define __tsid_python_contact_6d_hpp__

#include <pinocchio/fwd.hpp>
#include <boost/python.hpp>
#include <string>
#include <eigenpy/eigenpy.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

#include "tsid/contacts/contact-6d.hpp"
#include "tsid/robots/robot-wrapper.hpp"
#include "tsid/math/constraint-inequality.hpp"
#include "tsid/math/constraint-equality.hpp"
#include "tsid/math/constraint-base.hpp"
#include "tsid/tasks/task-se3-equality.hpp"

namespace tsid
{
  namespace python
  {
    namespace bp = boost::python;

    template<typename Contact6d>
    struct Contact6DPythonVisitor
    : public boost::python::def_visitor< Contact6DPythonVisitor<Contact6d> >
    {

      template<class PyClass>

      void visit(PyClass& cl) const
      {
        cl
        .def(bp::init<std::string, robots::RobotWrapper &, std::string, Eigen::MatrixXd, Eigen::VectorXd, double, double, double> ((bp::arg("name"), bp::arg("robot"), bp::arg("framename"), bp::arg("contactPoint"), bp::arg("contactNormal"), bp::arg("frictionCoeff"), bp::arg("minForce"), bp::arg("maxForce")), "Default Constructor"))
        .def(bp::init<std::string, robots::RobotWrapper &, std::string, Eigen::MatrixXd, Eigen::VectorXd, double, double, double, double> ((bp::arg("name"), bp::arg("robot"), bp::arg("framename"), bp::arg("contactPoint"), bp::arg("contactNormal"), bp::arg("frictionCoeff"), bp::arg("minForce"), bp::arg("maxForce"), bp::arg("wForceReg")), "Deprecated Constructor"))
        .add_property("n_motion", &Contact6d::n_motion, "return number of motion")
        .add_property("n_force", &Contact6d::n_force, "return number of force")
        .add_property("name", &Contact6DPythonVisitor::name, "return name")
        .def("computeMotionTask", &Contact6DPythonVisitor::computeMotionTask, bp::args("t", "q", "v", "data"))
        .def("computeForceTask", &Contact6DPythonVisitor::computeForceTask, bp::args("t", "q", "v", "data"))
        .def("computeForceRegularizationTask", &Contact6DPythonVisitor::computeForceRegularizationTask, bp::args("t", "q", "v", "data"))

        .add_property("getForceGeneratorMatrix", bp::make_function(&Contact6DPythonVisitor::getForceGeneratorMatrix, bp::return_value_policy<bp::copy_const_reference>()))

        .def("getNormalForce", &Contact6DPythonVisitor::getNormalForce, bp::arg("vec"))
        .add_property("getMinNormalForce", &Contact6d::getMinNormalForce)
        .add_property("getMaxNormalForce", &Contact6d::getMaxNormalForce)

        .add_property("Kp", bp::make_function(&Contact6DPythonVisitor::Kp, bp::return_value_policy<bp::copy_const_reference>()))
        .add_property("Kd", bp::make_function(&Contact6DPythonVisitor::Kd, bp::return_value_policy<bp::copy_const_reference>()))
        .def("setKp", &Contact6DPythonVisitor::setKp, bp::arg("Kp"))
        .def("setKd", &Contact6DPythonVisitor::setKd, bp::arg("Kd"))

        .def("setContactPoints", &Contact6DPythonVisitor::setContactPoints, bp::args("vec"))
        .def("setContactNormal", &Contact6DPythonVisitor::setContactNormal, bp::args("vec"))
        .def("setFrictionCoefficient", &Contact6DPythonVisitor::setFrictionCoefficient, bp::args("friction_coeff"))
        .def("setMinNormalForce", &Contact6DPythonVisitor::setMinNormalForce, bp::args("min_force"))
        .def("setMaxNormalForce", &Contact6DPythonVisitor::setMaxNormalForce, bp::args("max_force"))
        .def("setReference", &Contact6DPythonVisitor::setReference, bp::args("SE3"))
        .def("setForceReference", &Contact6DPythonVisitor::setForceReference, bp::args("f_vec"))
        .def("setRegularizationTaskWeightVector", &Contact6DPythonVisitor::setRegularizationTaskWeightVector, bp::args("w_vec"))
        ;
      }
      static std::string name(Contact6d & self){
        std::string name = self.name();
        return name;
      }

      static math::ConstraintEquality computeMotionTask(Contact6d & self, const double t, const Eigen::VectorXd & q, const Eigen::VectorXd & v, pinocchio::Data & data){
        self.computeMotionTask(t, q, v, data);
        math::ConstraintEquality cons(self.getMotionConstraint().name(), self.getMotionConstraint().matrix(), self.getMotionConstraint().vector());
        return cons;
      }
      static math::ConstraintInequality computeForceTask(Contact6d & self, const double t, const Eigen::VectorXd & q, const Eigen::VectorXd & v, const pinocchio::Data & data){
        self.computeForceTask(t, q, v, data);
        math::ConstraintInequality cons(self.getForceConstraint().name(), self.getForceConstraint().matrix(), self.getForceConstraint().lowerBound(), self.getForceConstraint().upperBound());
        return cons;
      }
      static math::ConstraintEquality computeForceRegularizationTask(Contact6d & self, const double t, const Eigen::VectorXd & q, const Eigen::VectorXd & v, const pinocchio::Data & data){
        self.computeForceRegularizationTask(t, q, v, data);
        math::ConstraintEquality cons(self.getForceRegularizationTask().name(), self.getForceRegularizationTask().matrix(), self.getForceRegularizationTask().vector());
        return cons;
      }

      static const Eigen::MatrixXd & getForceGeneratorMatrix(Contact6d & self){
        return self.getForceGeneratorMatrix();
      }
      static const Eigen::VectorXd & Kp (Contact6d & self){
        return self.Kp();
      }
      static const Eigen::VectorXd & Kd (Contact6d & self){
        return self.Kd();
      }
      static void setKp (Contact6d & self, const::Eigen::VectorXd Kp){
        return self.Kp(Kp);
      }
      static void setKd (Contact6d & self, const::Eigen::VectorXd Kd){
        return self.Kd(Kd);
      }
      static bool setContactPoints (Contact6d & self, const::Eigen::MatrixXd contactpoints){
        return self.setContactPoints(contactpoints);
      }
      static bool setContactNormal (Contact6d & self, const::Eigen::VectorXd contactNormal){
        return self.setContactNormal(contactNormal);
      }
      static bool setFrictionCoefficient (Contact6d & self, const double frictionCoefficient){
        return self.setFrictionCoefficient(frictionCoefficient);
      }
      static bool setMinNormalForce (Contact6d & self, const double minNormalForce){
        return self.setMinNormalForce(minNormalForce);
      }
      static bool setMaxNormalForce (Contact6d & self, const double maxNormalForce){
        return self.setMaxNormalForce(maxNormalForce);
      }
      static void setReference(Contact6d & self, const pinocchio::SE3 & ref){
        self.setReference(ref);
      }
      static void setForceReference(Contact6d & self, const::Eigen::VectorXd f_ref){
        self.setForceReference(f_ref);
      }
      static void setRegularizationTaskWeightVector(Contact6d & self, const::Eigen::VectorXd w){
        self.setRegularizationTaskWeightVector(w);
      }
      static double getNormalForce(Contact6d & self, Eigen::VectorXd f){
        return self.getNormalForce(f);
      }

      static void expose(const std::string & class_name)
      {
        std::string doc = "Contact6d info.";
        bp::class_<Contact6d>(class_name.c_str(),
                          doc.c_str(),
                          bp::no_init)
        .def(Contact6DPythonVisitor<Contact6d>());
      }
    };
  }
}

#endif // ifndef __tsid_python_contact_hpp__

max_stars_repo_name: NimaPng/tsid

max_issues_repo_name: NimaPng/tsid

max_forks_repo_name: NimaPng/tsid


text:
#include <boost/test/unit_test.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>

#include <iostream>
#include <sstream>

#include <3rdparty/zookeeper/ZooKeeper.hpp>
#include <3rdparty/zookeeper/ZooKeeperWatcher.hpp>
#include <3rdparty/zookeeper/ZooKeeperEvent.hpp>

using namespace std;
using namespace boost;
using namespace boost::lambda;
using namespace izenelib::zookeeper;

class WorkerSearch : public ZooKeeperEventHandler
{
public:
    virtual void onSessionConnected()
    {
    }

    virtual void onNodeCreated(const std::string& path)
    {
        cout << "[WorkerSearch] onNodeCreated " << path <<endl;
        path_ = path;
    }

    virtual void onNodeDeleted(const std::string& path)
    {
        cout << "[WorkerSearch] onNodeDeleted " << path <<endl;
    }

    virtual void onDataChanged(const std::string& path)
    {
        cout << "[WorkerSearch] onDataChanged " << path <<endl;
        path_ = path;
    }

    std::string path_;
};

class WorkerMining : public ZooKeeperEventHandler
{
public:
    virtual void onSessionConnected()
    {
    }

    virtual void onNodeCreated(const std::string& path)
    {
        cout << "[WorkerMining] onNodeCreated " << path <<endl;
    }

    virtual void onNodeDeleted(const std::string& path)
    {
        cout << "[WorkerMining] onNodeDeleted " << path <<endl;
    }

    virtual void onDataChanged(const std::string& path)
    {
        cout << "[WorkerMining] onDataChanged " << path <<endl;
    }
};

static const std::string gHosts = "localhost:2181"; //"127.16.0.161:2181,127.16.0.162:2181,127.16.0.163:2181";
//#define ENABLE_ZK_TEST

BOOST_AUTO_TEST_SUITE( t_zookeeper )

BOOST_AUTO_TEST_CASE( check_zookeeper_service )
{
    std::cout << "---> Note: start ZooKeeper Service firstly before test." << std::endl;
    std::cout << "     ZooKeeper Service: "<< gHosts << std::endl;
}

BOOST_AUTO_TEST_CASE( zookeeper_client_basic )
{
    std::cout << "---> Test ZooKeeper Client basic functions" << std::endl;

#ifndef ENABLE_ZK_TEST
    return;
#endif

    std::string hosts = gHosts;
    int recvTimeout = 3000;

    // Zookeeper Client
    ZooKeeper cli(hosts, recvTimeout);
    sleep(2);

    if (!cli.isConnected())
        return;

    // remove all
    cli.deleteZNode("/SF1", true);

    // create
    std::string path = "/SF1";
    std::string data = "distributed search";
    cli.createZNode(path, data, ZooKeeper::ZNODE_NORMAL);
    BOOST_CHECK_EQUAL(cli.isZNodeExists(path), true);
    BOOST_CHECK_EQUAL(cli.createZNode(path, data, ZooKeeper::ZNODE_NORMAL), false);

    // create ephemeral node
    if (false) // disable
    {
        ZooKeeper tmpCli(hosts, recvTimeout);
        tmpCli.createZNode("/SF1/ephemeral", "", ZooKeeper::ZNODE_EPHEMERAL);
        BOOST_CHECK_EQUAL(tmpCli.isZNodeExists("/SF1/ephemeral"), true);
    }
    //tmpCli exited...
    sleep(1);
    BOOST_CHECK_EQUAL(cli.isZNodeExists("/SF1/ephemeral"), false);

    // create sequence node
    cli.createZNode("/SF1/sequence", "", ZooKeeper::ZNODE_SEQUENCE);
    string s1 = cli.getLastCreatedNodePath();
    BOOST_CHECK_EQUAL(cli.isZNodeExists(s1), true);
    cli.createZNode("/SF1/sequence", "", ZooKeeper::ZNODE_SEQUENCE);
    string s2 = cli.getLastCreatedNodePath();
    BOOST_CHECK_EQUAL(cli.isZNodeExists(s2), true);
    cli.deleteZNode(s1);
    cli.deleteZNode(s2);

    // get
    std::string data_get;
    cli.getZNodeData(path, data_get);
    BOOST_CHECK_EQUAL(data_get, data);

    // set
    std::string data2 = "distributed search (sf1-kite)";
    BOOST_CHECK_EQUAL(cli.setZNodeData(path, data2), true);
    cli.getZNodeData(path, data_get);
    BOOST_CHECK_EQUAL(data_get, data2);

    // children
    std::string master = "/SF1/Master";
    std::string worker1 = "/SF1/Worker1";
    std::string worker2 = "/SF1/Worker2";
    BOOST_CHECK_EQUAL(cli.createZNode(master, "this is master node"), true);
    BOOST_CHECK_EQUAL(cli.createZNode(worker1, "remote worker1"), true);
    BOOST_CHECK_EQUAL(cli.createZNode(worker2, "remote worker2"), true);
    std::vector<std::string> children;
    cli.getZNodeChildren("/SF1", children);
    BOOST_CHECK_EQUAL(children.size(), 3);
    BOOST_CHECK_EQUAL(children[0], master);
    BOOST_CHECK_EQUAL(children[1], worker1);
    BOOST_CHECK_EQUAL(children[2], worker2);

    // display
    //cli.showZKNamespace("/SF1");
}

BOOST_AUTO_TEST_CASE( zookeeper_watch )
{
    std::cout << "---> Test ZooKeeper Watcher" << std::endl;

#ifndef ENABLE_ZK_TEST
    return;
#endif

    // Client
    std::string hosts = gHosts;
    int recvTimeout = 2000;
    ZooKeeper cli(hosts, recvTimeout);
    sleep(1);

    if (!cli.isConnected())
        return;

    // set event handlers for watcher
    WorkerSearch wkSearch;
    WorkerMining wkMining;
    cli.registerEventHandler(&wkSearch);
    cli.registerEventHandler(&wkMining);

    // 1. get and watch znode for changes
    std::string path = "/SF1/Master";
    std::string data_get;
    cli.getZNodeData(path, data_get, ZooKeeper::WATCH);
    BOOST_CHECK_EQUAL(data_get, "this is master node"); // set in former test case

    cli.setZNodeData(path, "master data changed!");
    sleep(1); //ensure watcher notified

    // master was notified by watcher on znode changed
    BOOST_CHECK_EQUAL(wkSearch.path_, path);
    cli.getZNodeData(wkSearch.path_, data_get);
    BOOST_CHECK_EQUAL(data_get, "master data changed!");

    // 2. check exists and watch znode for creation
    std::string path2 = "/NotExistedNode";
    cli.deleteZNode(path2, true);
    BOOST_CHECK_EQUAL(cli.isZNodeExists(path2, ZooKeeper::WATCH), false);

    cli.createZNode(path2, "nodata");
    sleep(1); //ensure watcher notified

    // master was notified by watcher on znode created
    BOOST_CHECK_EQUAL(wkSearch.path_, path2);
    cli.getZNodeData(wkSearch.path_, data_get);
    BOOST_CHECK_EQUAL(data_get, "nodata");

    // clear test data from zookeeper servers
    cli.deleteZNode(path2, true);
    cli.deleteZNode("/SF1", true);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: izenecloud/izenelib

max_issues_repo_name: izenecloud/izenelib

max_forks_repo_name: izenecloud/izenelib


text:
/*
 Copyright (C) 2016 Quaternion Risk Management Ltd
 All rights reserved.

 This file is part of ORE, a free-software/open-source library
 for transparent pricing and risk analysis - http://opensourcerisk.org

 ORE is free software: you can redistribute it and/or modify it
 under the terms of the Modified BSD License.  You should have received a
 copy of the license along with this program.
 The license is also available online at <http://opensourcerisk.org>

 This program is distributed on the basis that it will form a useful
 contribution to risk analytics and model standardisation, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/

#include <qle/termstructures/swaptionvolatilityconverter.hpp>
#include <qle/termstructures/swaptionvolcube2.hpp>
#include <qle/termstructures/swaptionvolcubewithatm.hpp>

#include <ql/exercise.hpp>
#include <ql/instruments/makevanillaswap.hpp>
#include <ql/instruments/swaption.hpp>
#include <ql/pricingengines/swap/discountingswapengine.hpp>
#include <ql/pricingengines/swaption/blackswaptionengine.hpp>
#include <ql/quotes/simplequote.hpp>
#include <ql/version.hpp>

#include <boost/make_shared.hpp>

namespace QuantExt {

const Volatility SwaptionVolatilityConverter::minVol_ = 1.0e-7;
const Volatility SwaptionVolatilityConverter::maxVol_ = 10.0;
const Real SwaptionVolatilityConverter::minVega_ = 1.0e-6;

SwaptionVolatilityConverter::SwaptionVolatilityConverter(
    const Date& asof, const boost::shared_ptr<SwaptionVolatilityStructure>& svsIn,
    const Handle<YieldTermStructure>& discount, const Handle<YieldTermStructure>& shortDiscount,
    const boost::shared_ptr<SwapConventions>& conventions, const boost::shared_ptr<SwapConventions>& shortConventions,
    const Period& conventionsTenor, const Period& shortConventionsTenor, const VolatilityType targetType,
    const Matrix& targetShifts)
    : asof_(asof), svsIn_(svsIn), discount_(discount), shortDiscount_(shortDiscount), conventions_(conventions),
      shortConventions_(shortConventions), conventionsTenor_(conventionsTenor),
      shortConventionsTenor_(shortConventionsTenor), targetType_(targetType), targetShifts_(targetShifts),
      accuracy_(1.0e-5), maxEvaluations_(100) {

    // Some checks
    checkInputs();
}

SwaptionVolatilityConverter::SwaptionVolatilityConverter(const Date& asof,
                                                         const boost::shared_ptr<SwaptionVolatilityStructure>& svsIn,
                                                         const boost::shared_ptr<SwapIndex>& swapIndex,
                                                         const boost::shared_ptr<SwapIndex>& shortSwapIndex,
                                                         const VolatilityType targetType, const Matrix& targetShifts)
    : asof_(asof), svsIn_(svsIn), discount_(swapIndex->discountingTermStructure()),
      shortDiscount_(shortSwapIndex->discountingTermStructure()),
      conventions_(boost::make_shared<SwapConventions>(swapIndex->fixingDays(), swapIndex->fixedLegTenor(),
                                                       swapIndex->fixingCalendar(), swapIndex->fixedLegConvention(),
                                                       swapIndex->dayCounter(), swapIndex->iborIndex())),
      shortConventions_(boost::make_shared<SwapConventions>(
          shortSwapIndex->fixingDays(), shortSwapIndex->fixedLegTenor(), shortSwapIndex->fixingCalendar(),
          shortSwapIndex->fixedLegConvention(), shortSwapIndex->dayCounter(), shortSwapIndex->iborIndex())),
      conventionsTenor_(swapIndex->tenor()), shortConventionsTenor_(shortSwapIndex->tenor()), targetType_(targetType),
      targetShifts_(targetShifts), accuracy_(1.0e-5), maxEvaluations_(100) {

    // Some checks
    if (discount_.empty())
        discount_ = swapIndex->iborIndex()->forwardingTermStructure();
    if (shortDiscount_.empty())
        shortDiscount_ = shortSwapIndex->iborIndex()->forwardingTermStructure();
    checkInputs();
}

void SwaptionVolatilityConverter::checkInputs() const {
    QL_REQUIRE(svsIn_->referenceDate() == asof_,
               "SwaptionVolatilityConverter requires the asof date and reference date to align");
    QL_REQUIRE(!discount_.empty() && discount_->referenceDate() == asof_,
               "SwaptionVolatilityConverter requires a valid discount curve with reference date equal to asof date");
    Handle<YieldTermStructure> forwardCurve = conventions_->floatIndex()->forwardingTermStructure();
    QL_REQUIRE(!forwardCurve.empty() && forwardCurve->referenceDate() == asof_,
               "SwaptionVolatilityConverter requires a valid forward curve with reference date equal to asof date");
}

boost::shared_ptr<SwaptionVolatilityStructure> SwaptionVolatilityConverter::convert() const {

    boost::shared_ptr<SwaptionVolatilityDiscrete> svDisc;

    // We expect either the wrapper adding ATM to a cube or a swaption vol discrete
    // instance (like a matrix, a regular cube).

    vector<Real> strikeSpreads(1, 0.0);
    boost::shared_ptr<SwapIndex> swapIndexBase, shortSwapIndexBase;
    boost::shared_ptr<SwaptionVolatilityCube> cube;
    if (boost::dynamic_pointer_cast<SwaptionVolCubeWithATM>(svsIn_)) {
        cube = boost::static_pointer_cast<SwaptionVolCubeWithATM>(svsIn_)->cube();
    }
    if (boost::dynamic_pointer_cast<SwaptionVolatilityCube>(svsIn_)) {
        cube = boost::static_pointer_cast<SwaptionVolatilityCube>(svsIn_);
    }
    if (cube) {
        svDisc = cube;
        strikeSpreads = cube->strikeSpreads();
        swapIndexBase = cube->swapIndexBase();
        shortSwapIndexBase = cube->shortSwapIndexBase();
    } else if (boost::dynamic_pointer_cast<SwaptionVolatilityDiscrete>(svsIn_)) {
        svDisc = boost::static_pointer_cast<SwaptionVolatilityDiscrete>(svsIn_);
    } else {
        QL_FAIL("SwaptionVolatilityConverter: unknown input volatility structure");
    }

    // Some aspects of original volatility structure that we will need
    DayCounter dayCounter = svDisc->dayCounter();
    bool extrapolation = svDisc->allowsExtrapolation();
    Calendar calendar = svDisc->calendar();
    BusinessDayConvention bdc = svDisc->businessDayConvention();

    const vector<Date>& optionDates = svDisc->optionDates();
    const vector<Period>& optionTenors = svDisc->optionTenors();
    const vector<Period>& swapTenors = svDisc->swapTenors();
    const vector<Time>& optionTimes = svDisc->optionTimes();
    const vector<Time>& swapLengths = svDisc->swapLengths();
    Size nOptionTimes = optionTimes.size();
    Size nSwapLengths = swapLengths.size();
    Size nStrikeSpreads = strikeSpreads.size();

    Real targetShift = 0.0;

    // If target type is ShiftedLognormal and shifts are provided, check size
    if (targetType_ == ShiftedLognormal && !targetShifts_.empty()) {
        QL_REQUIRE(targetShifts_.rows() == nOptionTimes,
                   "SwaptionVolatilityConverter: number of shift rows does not equal the number of option tenors");
        QL_REQUIRE(targetShifts_.columns() == nSwapLengths,
                   "SwaptionVolatilityConverter: number of shift columns does not equal the number of swap tenors");
    }

    // Calculate the converted ATM volatilities
    Matrix volatilities(nOptionTimes, nSwapLengths);
    for (Size i = 0; i < nOptionTimes; ++i) {
        for (Size j = 0; j < nSwapLengths; ++j) {
            if (!targetShifts_.empty())
                targetShift = targetShifts_[i][j];
            volatilities[i][j] = convert(optionDates[i], swapTenors[j], 0.0, dayCounter, targetType_, targetShift);
        }
    }

    // Build ATM matrix
    Handle<SwaptionVolatilityStructure> atmStructure;
    if (calendar.empty() || optionTenors.empty()) {
        // Original matrix was created with fixed option dates
        atmStructure = Handle<SwaptionVolatilityStructure>(boost::make_shared<SwaptionVolatilityMatrix>(
            asof_, optionDates, swapTenors, volatilities, Actual365Fixed(), extrapolation, targetType_, targetShifts_));
    } else {
        atmStructure = Handle<SwaptionVolatilityStructure>(boost::shared_ptr<SwaptionVolatilityMatrix>(
            new SwaptionVolatilityMatrix(asof_, calendar, bdc, optionTenors, swapTenors, volatilities, Actual365Fixed(),
                                         extrapolation, targetType_, targetShifts_)));
    }

    // no cube input => we are done
    if (!cube)
        return *atmStructure;

    // convert non-ATM volatilities, note that we use the ATM option tenors and swap tenors here!

    std::vector<std::vector<Handle<Quote> > > volSpreads(nOptionTimes * nSwapLengths,
                                                         std::vector<Handle<Quote> >(nStrikeSpreads));
    for (Size k = 0; k < nStrikeSpreads; ++k) {
        for (Size i = 0; i < nOptionTimes; ++i) {
            for (Size j = 0; j < nSwapLengths; ++j) {
                if (!targetShifts_.empty())
                    targetShift = targetShifts_[i][j];
                Real outVol =
                    convert(optionDates[i], swapTenors[j], strikeSpreads[k], dayCounter, targetType_, targetShift);
                volSpreads[i * nSwapLengths + j][k] = Handle<Quote>(boost::make_shared<SimpleQuote>(outVol));
            }
        }
    }

    // Build and return cube, note that we hardcode flat extrapolation
    boost::shared_ptr<SwaptionVolatilityCube> cubeOut = boost::shared_ptr<QuantExt::SwaptionVolCube2>(
        new QuantExt::SwaptionVolCube2(atmStructure, optionTenors, swapTenors, strikeSpreads, volSpreads, swapIndexBase,
                                       shortSwapIndexBase, false, true, false));
    cubeOut->enableExtrapolation(cube->allowsExtrapolation());
    return boost::make_shared<SwaptionVolCubeWithATM>(cubeOut);

} // namespace QuantExt

// Ignore "warning C4996: 'Quantlib::Swaption::impliedVolatility': was declared deprecated"
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable : 4996)
#endif
Real SwaptionVolatilityConverter::convert(const Date& expiry, const Period& swapTenor, Real strikeSpread,
                                          const DayCounter& volDayCounter, VolatilityType outType,
                                          Real outShift) const {

    const boost::shared_ptr<SwapConventions> tmpConv =
        swapTenor <= shortConventionsTenor_ ? shortConventions_ : conventions_;
    Handle<YieldTermStructure> tmpDiscount = swapTenor <= shortConventionsTenor_ ? shortDiscount_ : discount_;

    // Create the underlying swap with fixed rate = fair rate
    // We rely on the fact that MakeVanillaSwap sets the fixed rate to the fair rate if it is left null in the ctor
    Date effectiveDate = tmpConv->fixedCalendar().advance(expiry, tmpConv->settlementDays(), Days);
    boost::shared_ptr<PricingEngine> engine = boost::make_shared<DiscountingSwapEngine>(tmpDiscount);
    boost::shared_ptr<VanillaSwap> swap = MakeVanillaSwap(swapTenor, tmpConv->floatIndex())
                                              .withType(strikeSpread < 0.0 ? VanillaSwap::Receiver : VanillaSwap::Payer)
                                              .withEffectiveDate(effectiveDate)
                                              .withFixedLegCalendar(tmpConv->fixedCalendar())
                                              .withFixedLegDayCount(tmpConv->fixedDayCounter())
                                              .withFixedLegTenor(tmpConv->fixedTenor())
                                              .withFixedLegConvention(tmpConv->fixedConvention())
                                              .withFixedLegTerminationDateConvention(tmpConv->fixedConvention())
                                              .withFloatingLegSpread(0.0)
                                              .withPricingEngine(engine);
    // we need this also for non-atm swaps
    Rate atmRate = swap->fairRate(), strike;
    if (!close_enough(strikeSpread, 0.0)) {
        strike = atmRate + strikeSpread;
        swap = MakeVanillaSwap(swapTenor, tmpConv->floatIndex(), strike)
                   .withEffectiveDate(effectiveDate)
                   .withFixedLegTenor(tmpConv->fixedTenor())
                   .withFixedLegDayCount(tmpConv->fixedDayCounter())
                   .withFloatingLegSpread(0.0)
                   .withPricingEngine(engine);
    } else {
        strike = atmRate;
    }

    Real inShift = svsIn_->shift(expiry, swapTenor);
    VolatilityType inType = svsIn_->volatilityType();

    // if strike is invalid w.r.t. the given input or output vol types, return zero vol
    // (for a lognormal cube e.g. it is common that some effective strikes are negative)
    Real inMinStrike = inType == ShiftedLognormal ? -inShift : -QL_MAX_REAL;
    Real outMinStrike = outType == ShiftedLognormal ? -outShift : -QL_MAX_REAL;
    if (strike < inMinStrike || strike < outMinStrike)
        return 0.0;

    Real inVol = svsIn_->volatility(expiry, swapTenor, strike);

    // Create the swaption
    boost::shared_ptr<Exercise> exercise = boost::make_shared<EuropeanExercise>(expiry);
    boost::shared_ptr<Swaption> swaption = boost::make_shared<Swaption>(swap, exercise, Settlement::Physical);

    // Price the swaption with the input volatility
    boost::shared_ptr<PricingEngine> swaptionEngine;
    if (inType == ShiftedLognormal) {
        swaptionEngine = boost::make_shared<BlackSwaptionEngine>(discount_, inVol, volDayCounter, inShift);
    } else {
        swaptionEngine = boost::make_shared<BachelierSwaptionEngine>(discount_, inVol, volDayCounter);
    }
    swaption->setPricingEngine(swaptionEngine);

    // zero might be the actual implied vol (if we e.g. convert from LN to N with a strike near zero),
    // but the Swaption::impliedVolatility function will not find this, so we check for this case
    // explicitly here
    Real vega = swaption->result<Real>("vega");
    if (vega < minVega_)
        return 0.0;

    Volatility impliedVol = 0.0;
    try {
        Real npv = swaption->NPV();

        // Calculate guess for implied volatility solver
        Real guess = 0.0;
        if (outType == ShiftedLognormal) {
            QL_REQUIRE(atmRate + outShift > 0.0, "SwaptionVolatilityConverter: ATM rate + shift must be > 0.0");
            if (inType == Normal)
                guess = inVol / (atmRate + outShift);
            else
                guess = inVol * (atmRate + inShift) / (atmRate + outShift);
        } else {
            if (inType == Normal)
                guess = inVol;
            else
                guess = inVol * (atmRate + inShift);
        }

// Note: In implying the volatility the volatility day counter is hardcoded to Actual365Fixed
#if QL_HEX_VERSION < 0x011000f0
        impliedVol = swaption->impliedVolatility(npv, discount_, guess, accuracy_, maxEvaluations_, minVol_, maxVol_,
                                                 outShift, outType);
#else
        impliedVol = swaption->impliedVolatility(npv, discount_, guess, accuracy_, maxEvaluations_, minVol_, maxVol_,
                                                 outType, outShift);
#endif

    } catch (std::exception& e) {
        // couldn't find implied volatility
        QL_FAIL("SwaptionVolatilityConverter: volatility conversion failed while trying to convert volatility"
                " for expiry "
                << expiry << " and swap tenor " << swapTenor << ". Error: " << e.what());
    }

    return impliedVol;
}
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
} // namespace QuantExt

max_stars_repo_name: PiotrSiejda/Engine

max_issues_repo_name: PiotrSiejda/Engine

max_forks_repo_name: PiotrSiejda/Engine


text:
#ifndef _DLIB_FDETECT_AND_LANDMARK_HPP_
#define _DLIB_FDETECT_AND_LANDMARK_HPP_
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include <dlib/image_io.h>
#include <dlib/opencv.h>

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>

#include <iostream>
#include <fstream>
#include <string>

bool debug;

// Apply affine transform calculated using srcTri and dstTri to src
void applyAffineTransform(cv::Mat &warpImage, cv::Mat &src, std::vector<cv::Point2f> &srcTri, std::vector<cv::Point2f> &dstTri)
{
    // Given a pair of triangles, find the affine transform.
    cv::Mat warpMat = getAffineTransform( srcTri, dstTri );

    // Apply the Affine Transform just found to the src image
    cv::warpAffine( src, warpImage, warpMat, warpImage.size(), cv::INTER_LINEAR, cv::BORDER_REFLECT_101);
}

// Calculate Delaunay triangles for set of points
// Returns the vector of indices of 3 points for each triangle
static void calculateDelaunayTriangles(cv::Rect rect, std::vector<cv::Point2f> &points, std::vector< std::vector<int> > &delaunayTri){

    // Create an instance of Subdiv2D
    cv::Subdiv2D subdiv(rect);

    // Insert points into subdiv
    for( std::vector<cv::Point2f>::iterator it = points.begin(); it != points.end(); it++)
        subdiv.insert(*it);

    std::vector<cv::Vec6f> triangleList;
    subdiv.getTriangleList(triangleList);
    std::vector<cv::Point2f> pt(3);
    std::vector<int> ind(3);

    for( size_t i = 0; i < triangleList.size(); i++ )
    {
        cv::Vec6f t = triangleList[i];
        pt[0] = cv::Point2f(t[0], t[1]);
        pt[1] = cv::Point2f(t[2], t[3]);
        pt[2] = cv::Point2f(t[4], t[5]);

        if ( rect.contains(pt[0]) && rect.contains(pt[1]) && rect.contains(pt[2])){
            for(int j = 0; j < 3; j++)
                for(size_t k = 0; k < points.size(); k++)
                    if(abs(pt[j].x - points[k].x) < 1.0 && abs(pt[j].y - points[k].y) < 1)
                        ind[j] = k;

            delaunayTri.push_back(ind);
        }
    }
}

// Warps and alpha blends triangular regions from img1 and img2 to img
void warpTriangle(cv::Mat &img1, cv::Mat &img2, std::vector<cv::Point2f> &t1, std::vector<cv::Point2f> &t2)
{

    cv::Rect r1 = boundingRect(t1);
    cv::Rect r2 = boundingRect(t2);

    // Offset points by left top corner of the respective rectangles
    std::vector<cv::Point2f> t1Rect, t2Rect;
    std::vector<cv::Point> t2RectInt;
    for(int i = 0; i < 3; i++)
    {

        t1Rect.push_back( cv::Point2f( t1[i].x - r1.x, t1[i].y -  r1.y) );
        t2Rect.push_back( cv::Point2f( t2[i].x - r2.x, t2[i].y - r2.y) );
        t2RectInt.push_back( cv::Point(t2[i].x - r2.x, t2[i].y - r2.y) ); // for fillConvexPoly

    }

    // Get mask by filling triangle
    cv::Mat mask = cv::Mat::zeros(r2.height, r2.width, CV_32FC3);
    fillConvexPoly(mask, t2RectInt, cv::Scalar(1.0, 1.0, 1.0), 16, 0);

    // Apply warpImage to small rectangular patches
    cv::Mat img1Rect;
    img1(r1).copyTo(img1Rect);

    cv::Mat img2Rect = cv::Mat::zeros(r2.height, r2.width, img1Rect.type());

    applyAffineTransform(img2Rect, img1Rect, t1Rect, t2Rect);

    cv::multiply(img2Rect,mask, img2Rect);
    cv::multiply(img2(r2), cv::Scalar(1.0,1.0,1.0) - mask, img2(r2));
    img2(r2) = img2(r2) + img2Rect;

}

cv::Mat swap(cv::Mat img1, cv::Mat img2, std::vector<cv::Point2f> points1, std::vector<cv::Point2f> points2) {
    cv::Mat img1Warped = img2.clone();

    //convert Mat to float data type
    img1.convertTo(img1, CV_32F);
    img1Warped.convertTo(img1Warped, CV_32F);

    // Find convex hull
    std::vector<cv::Point2f> hull1;
    std::vector<cv::Point2f> hull2;
    std::vector<int> hullIndex;

    cv::convexHull(points2, hullIndex, false, false);

    for(int i = 0; i < hullIndex.size(); i++)
    {
        hull1.push_back(points1[hullIndex[i]]);
        hull2.push_back(points2[hullIndex[i]]);
    }

    // Find delaunay triangulation for points on the convex hull
    std::vector< std::vector<int> > dt;
    cv::Rect rect(0, 0, img1Warped.cols, img1Warped.rows);
    calculateDelaunayTriangles(rect, hull2, dt);

    // Apply affine transformation to Delaunay triangles
    for(size_t i = 0; i < dt.size(); i++)
    {
        std::vector<cv::Point2f> t1, t2;
        // Get points for img1, img2 corresponding to the triangles
        for(size_t j = 0; j < 3; j++)
        {
            t1.push_back(hull1[dt[i][j]]);
            t2.push_back(hull2[dt[i][j]]);
        }

        warpTriangle(img1, img1Warped, t1, t2);

    }

    // Calculate mask
    std::vector<cv::Point> hull8U;
    for(int i = 0; i < hull2.size(); i++)
    {
        cv::Point pt(hull2[i].x, hull2[i].y);
        hull8U.push_back(pt);
    }

    cv::Mat mask = cv::Mat::zeros(img2.rows, img2.cols, img2.depth());
    cv::fillConvexPoly(mask,&hull8U[0], hull8U.size(), cv::Scalar(255,255,255));

    // Clone seamlessly.
    cv::Rect r = boundingRect(hull2);
    cv::Point center = (r.tl() + r.br()) / 2;

    cv::Mat output;
    img1Warped.convertTo(img1Warped, CV_8UC3);
    cv::seamlessClone(img1Warped,img2, mask, center, output, cv::NORMAL_CLONE);
    return output;
}

std::vector<std::vector<cv::Point2f>> landmark_detection(dlib::cv_image<dlib::rgb_pixel> dlibIm, std::vector<dlib::rectangle> rects, dlib::shape_predictor sp) {
    std::vector<std::vector<cv::Point2f>> both_points;
    for (unsigned long j = 0; j < 2; ++j)
    {
        dlib::full_object_detection shape = sp(dlibIm, rects[j]);
        if (shape.num_parts() == 68){
            std::vector<cv::Point2f> points;
            for(int i = 0; i < 68; ++i){
                points.push_back(cv::Point2f((float)shape.part(i)(0),(float)shape.part(i)(1)));
                // std::cout << i << " " << shape.part(i)(0) << " " << shape.part(i)(1) << std::endl;
            }
            both_points.push_back(points);
        }
    }

    return both_points;
}

std::tuple<dlib::cv_image<dlib::rgb_pixel>,std::vector<dlib::rectangle>> detectFaceDlibHog(dlib::frontal_face_detector hogFaceDetector, cv::Mat& frameDlibHog, int inHeight=300, int inWidth=0)
{

    int frameHeight = frameDlibHog.rows;
    dlib::cv_image<dlib::rgb_pixel> dlibIm(frameDlibHog);

    // Detect faces in the image
    std::vector<dlib::rectangle> faceRects = hogFaceDetector(dlibIm);
    if(debug){
        for ( size_t i = 0; i < faceRects.size(); i++ )
        {
            int x1 = (int)(faceRects[i].left());
            int y1 = (int)(faceRects[i].top());
            int x2 = (int)(faceRects[i].right());
            int y2 = (int)(faceRects[i].bottom());
            cv::rectangle(frameDlibHog, cv::Point(x1, y1), cv::Point(x2, y2), cv::Scalar(0,255,0), (int)(frameHeight/150.0), 4);
        }
    }
    return std::make_tuple(dlibIm,faceRects);
}

#endif


text:
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <list>
#include <memory>
#include <string>

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

#include "tui.h"
#include "elftree.h"
#include "elfinfo.h"
#include "elfutil.h"

static void __print_usage()
{
  std::cout << "Usage : rpmtree {library name or file name}\n" << std::endl;
}

static bool __check_file_is_exists(std::string fileName)
{
  if ( boost::filesystem::exists(fileName) == false )
    return false;
  return true;
}

int main(int argc, char *argv[])
{
  if (argc != 2) {
    __print_usage();
    return -1;
  }

  std::string fileName = std::string(argv[1]);
  if (__check_file_is_exists(fileName) == false) {
    std::cout << "Please check file is exists" << std::endl;
    return -1;
  }

  TreeView* view = nullptr;
  try {
    view = ElfUtil::makeTreeView(fileName);
  } catch (const std::exception &e) {
    std::cerr << "Failed to make TreeView : " << e.what() << std::endl;
    exit(-1);
  }

  ElfTreeTUI tui;
  tui.initTerminal();
  tui.setMenuList(view);
  tui.run();
  tui.clearTerminal();

  return 0;
}

ext: cc

max_stars_repo_name: linuxias/rpmtree

max_issues_repo_name: linuxias/rpmtree

max_forks_repo_name: linuxias/rpmtree


text:
/*****************************************************************************
 * Copyright [2017] [taurus.ai]
 *
 * 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.
 *****************************************************************************/

/**
 * Journal Handler
 * @Author cjiang (changhao.jiang@taurus.ai)
 * @since   March, 2017
 * base class of Journal reader / writer
 */

#include "JournalHandler.h"
#include "PageProvider.h"
#include "Journal.h"
#include "Timer.h"
#include <sstream>
#include <boost/filesystem.hpp>

USING_YJJ_NAMESPACE

#define REDIS_DIRECT_USAGE

string JournalHandler::getDefaultName(const string& prefix)
{
    std::stringstream ss;
    ss << prefix << "_" << getNanoTime();
    return ss.str();
}

size_t JournalHandler::addJournal(const string& _dir, const string& jname)
{
    // TODO fix this with boost filesystem
    // directory should not contain '/' in the back
    string dir;
    if (_dir.back() == '/')
        dir = _dir.substr(0, _dir.length() - 1);
    else
        dir = _dir;

    boost::filesystem::path page_folder_path = _dir;
    if(!boost::filesystem::exists(page_folder_path)) {
        boost::filesystem::create_directories(page_folder_path);
    }

    // register this journal
    int service_idx = page_provider->register_journal(dir, jname);
    journals.push_back(Journal::create(dir, jname, service_idx, page_provider));
    return journals.size() - 1;
}

JournalHandler::~JournalHandler()
{
    page_provider->exit_client();
}

max_stars_repo_name: shenglinqian/kungfu

max_issues_repo_name: shenglinqian/kungfu

max_forks_repo_name: shenglinqian/kungfu