text:
#pragma once
/**
 *  @file exception.hpp
 *  @brief Defines exception's used by fc
 */
#include <fc/log/logger.hpp>
#include <fc/optional.hpp>
#include <exception>
#include <functional>
#include <unordered_map>
#include <boost/core/typeinfo.hpp>
#include <boost/interprocess/exceptions.hpp>

namespace fc
{
   namespace detail { class exception_impl; }

   enum exception_code
   {
       /** for exceptions we threw that don't have an assigned code */
       unspecified_exception_code        = 0,
       unhandled_exception_code          = 1, ///< for unhandled 3rd party exceptions
       timeout_exception_code            = 2, ///< timeout exceptions
       file_not_found_exception_code     = 3,
       parse_error_exception_code        = 4,
       invalid_arg_exception_code        = 5,
       key_not_found_exception_code      = 6,
       bad_cast_exception_code           = 7,
       out_of_range_exception_code       = 8,
       canceled_exception_code           = 9,
       assert_exception_code             = 10,
       eof_exception_code                = 11,
       std_exception_code                = 13,
       invalid_operation_exception_code  = 14,
       unknown_host_exception_code       = 15,
       null_optional_code                = 16,
       udt_error_code                    = 17,
       aes_error_code                    = 18,
       overflow_code                     = 19,
       underflow_code                    = 20,
       divide_by_zero_code               = 21
   };

   /**
    *  @brief Used to generate a useful error report when an exception is thrown.
    *  @ingroup serializable
    *
    *  At each level in the stack where the exception is caught and rethrown a
    *  new log_message is added to the exception.
    *
    *  exception's are designed to be serialized to a variant and
    *  deserialized from an variant.
    *
    *  @see FC_THROW_EXCEPTION
    *  @see FC_RETHROW_EXCEPTION
    *  @see FC_RETHROW_EXCEPTIONS
    */
   class exception
   {
      public:
         enum code_enum
         {
            code_value = unspecified_exception_code
         };

         exception( int64_t code = unspecified_exception_code,
                    const std::string& name_value = "exception",
                    const std::string& what_value = "unspecified");
         exception( log_message&&, int64_t code = unspecified_exception_code,
                                   const std::string& name_value = "exception",
                                   const std::string& what_value = "unspecified");
         exception( log_messages&&, int64_t code = unspecified_exception_code,
                                    const std::string& name_value = "exception",
                                    const std::string& what_value = "unspecified");
         exception( const log_messages&,
                    int64_t code = unspecified_exception_code,
                    const std::string& name_value = "exception",
                    const std::string& what_value = "unspecified");
         exception( const exception& e );
         exception( exception&& e );
         virtual ~exception();

         const char*          name() const throw();
         int64_t              code() const throw();
         virtual const char*  what() const throw();
         const char*          strace()const throw();

         static void enable_detailed_strace(bool value = true);
         static bool is_detailed_strace();

         /**
          *   @return a reference to log messages that have
          *   been added to this log.
          */
         const log_messages&  get_log()const;
         void                 append_log( log_message m );

         /**
          *   Generates a detailed string including file, line, method,
          *   and other information that is generally only useful for
          *   developers.
          */
         std::string to_detail_string( log_level ll = log_level::all )const;

         /**
          *   Generates a user-friendly error report.
          */
         std::string to_string( log_level ll = log_level::info  )const;

         /**
          *   Generates a user-friendly error report.
          */
         std::string top_message( )const;

         /**
          *  Throw this exception as its most derived type.
          *
          *  @note does not return.
          */
         virtual NO_RETURN void     dynamic_rethrow_exception()const;

         /**
          *  This is equivalent to:
          *  @code
          *   try { throwAsDynamic_exception(); }
          *   catch( ... ) { return std::current_exception(); }
          *  @endcode
          */
          virtual std::shared_ptr<exception> dynamic_copy_exception()const;

         friend void to_variant( const exception& e, variant& v );
         friend void from_variant( const variant& e, exception& ll );

         exception& operator=( const exception& copy );
         exception& operator=( exception&& copy );
      protected:
         std::unique_ptr<detail::exception_impl> my;
   };

   void to_variant( const exception& e, variant& v );
   void from_variant( const variant& e, exception& ll );
   typedef std::shared_ptr<exception> exception_ptr;

   typedef optional<exception> oexception;

   /**
    *  @brief re-thrown whenever an unhandled exception is caught.
    *  @ingroup serializable
    *  Any exceptions thrown by 3rd party libraries that are not
    *  caught get wrapped in an unhandled_exception exception.
    *
    *  The original exception is captured as a std::exception_ptr
    *  which may be rethrown.  The std::exception_ptr does not
    *  propgate across process boundaries.
    */
   class unhandled_exception : public exception
   {
      public:
       enum code_enum {
          code_value = unhandled_exception_code,
       };
       unhandled_exception( log_message&& m, std::exception_ptr e = std::current_exception() );
       unhandled_exception( log_messages );
       unhandled_exception( const exception&  );

       std::exception_ptr get_inner_exception()const;

       virtual NO_RETURN void               dynamic_rethrow_exception()const;
       virtual std::shared_ptr<exception>   dynamic_copy_exception()const;
      private:
       std::exception_ptr _inner;
   };

   template<typename T>
   fc::exception_ptr copy_exception( T&& e )
   {
#if defined(_MSC_VER) && (_MSC_VER < 1700)
     return std::make_shared<unhandled_exception>( log_message(),
                                                   std::copy_exception(fc::forward<T>(e)) );
#else
     return std::make_shared<unhandled_exception>( log_message(),
                                                   std::make_exception_ptr(fc::forward<T>(e)) );
#endif
   }

   class exception_factory
   {
      public:
        struct base_exception_builder
        {
           virtual NO_RETURN void rethrow( const exception& e )const = 0;
        };

        template<typename T>
        struct exception_builder : public base_exception_builder
        {
           virtual NO_RETURN void rethrow( const exception& e )const override
           {
              throw T( e );
           }
        };

        template<typename T>
        void register_exception()
        {
           static exception_builder<T> builder;
           auto itr = _registered_exceptions.find( T::code_value );
           assert( itr == _registered_exceptions.end() );
           (void)itr; // in release builds this hides warnings
           _registered_exceptions[T::code_value] = &builder;
        }

        void NO_RETURN rethrow( const exception& e )const;

        static exception_factory& instance()
        {
           static exception_factory once;
           return once;
        }

      private:
        std::unordered_map<int64_t,base_exception_builder*> _registered_exceptions;
   };
#define FC_REGISTER_EXCEPTION(r, unused, base) \
   fc::exception_factory::instance().register_exception<base>();

#define FC_REGISTER_EXCEPTIONS( SEQ )\
     \
   static bool exception_init = []()->bool{ \
    BOOST_PP_SEQ_FOR_EACH( FC_REGISTER_EXCEPTION, v, SEQ )  \
      return true; \
   }();  \

#define FC_DECLARE_DERIVED_EXCEPTION( TYPE, BASE, CODE, WHAT ) \
   class TYPE : public BASE  \
   { \
      public: \
       enum code_enum { \
          code_value = CODE, \
       }; \
       explicit TYPE( int64_t code, const std::string& name_value, const std::string& what_value ) \
       :BASE( code, name_value, what_value ){} \
       explicit TYPE( fc::log_message&& m, int64_t code, const std::string& name_value, const std::string& what_value ) \
       :BASE( std::move(m), code, name_value, what_value ){} \
       explicit TYPE( fc::log_messages&& m, int64_t code, const std::string& name_value, const std::string& what_value )\
       :BASE( std::move(m), code, name_value, what_value ){}\
       explicit TYPE( const fc::log_messages& m, int64_t code, const std::string& name_value, const std::string& what_value )\
       :BASE( m, code, name_value, what_value ){}\
       TYPE( const std::string& what_value, const fc::log_messages& m ) \
       :BASE( m, CODE, BOOST_PP_STRINGIZE(TYPE), what_value ){} \
       TYPE( fc::log_message&& m ) \
       :BASE( fc::move(m), CODE, BOOST_PP_STRINGIZE(TYPE), WHAT ){}\
       TYPE( fc::log_messages msgs ) \
       :BASE( fc::move( msgs ), CODE, BOOST_PP_STRINGIZE(TYPE), WHAT ) {} \
       TYPE( const TYPE& c ) \
       :BASE(c){} \
       TYPE( const BASE& c ) \
       :BASE(c){} \
       TYPE():BASE(CODE, BOOST_PP_STRINGIZE(TYPE), WHAT){}\
       \
       virtual std::shared_ptr<fc::exception> dynamic_copy_exception()const\
       { return std::make_shared<TYPE>( *this ); } \
       virtual NO_RETURN void     dynamic_rethrow_exception()const \
       { if( code() == CODE ) throw *this;\
         else fc::exception::dynamic_rethrow_exception(); \
       } \
   };

  #define FC_DECLARE_EXCEPTION( TYPE, CODE, WHAT ) \
      FC_DECLARE_DERIVED_EXCEPTION( TYPE, fc::exception, CODE, WHAT )

  FC_DECLARE_EXCEPTION( timeout_exception, timeout_exception_code, "Timeout" );
  FC_DECLARE_EXCEPTION( file_not_found_exception, file_not_found_exception_code, "File Not Found" );
  /**
   * @brief report's parse errors
   */
  FC_DECLARE_EXCEPTION( parse_error_exception, parse_error_exception_code, "Parse Error" );
  FC_DECLARE_EXCEPTION( invalid_arg_exception, invalid_arg_exception_code, "Invalid Argument" );
  /**
   * @brief reports when a key, guid, or other item is not found.
   */
  FC_DECLARE_EXCEPTION( key_not_found_exception, key_not_found_exception_code, "Key Not Found" );
  FC_DECLARE_EXCEPTION( bad_cast_exception, bad_cast_exception_code, "Bad Cast" );
  FC_DECLARE_EXCEPTION( out_of_range_exception, out_of_range_exception_code, "Out of Range" );

  /** @brief if an operation is unsupported or not valid this may be thrown */
  FC_DECLARE_EXCEPTION( invalid_operation_exception,
                        invalid_operation_exception_code,
                        "Invalid Operation" );
  /** @brief if an host name can not be resolved this may be thrown */
  FC_DECLARE_EXCEPTION( unknown_host_exception,
                         unknown_host_exception_code,
                         "Unknown Host" );

  /**
   *  @brief used to report a canceled Operation
   */
  FC_DECLARE_EXCEPTION( canceled_exception, canceled_exception_code, "Canceled" );
  /**
   *  @brief used inplace of assert() to report violations of pre conditions.
   */
  FC_DECLARE_EXCEPTION( assert_exception, assert_exception_code, "Assert Exception" );
  FC_DECLARE_EXCEPTION( eof_exception, eof_exception_code, "End Of File" );
  FC_DECLARE_EXCEPTION( null_optional, null_optional_code, "null optional" );
  FC_DECLARE_EXCEPTION( udt_exception, udt_error_code, "UDT error" );
  FC_DECLARE_EXCEPTION( aes_exception, aes_error_code, "AES error" );
  FC_DECLARE_EXCEPTION( overflow_exception, overflow_code, "Integer Overflow" );
  FC_DECLARE_EXCEPTION( underflow_exception, underflow_code, "Integer Underflow" );
  FC_DECLARE_EXCEPTION( divide_by_zero_exception, divide_by_zero_code, "Integer Divide By Zero" );

  std::string except_str();

  void record_assert_trip(
     const char* filename,
     uint32_t lineno,
     const char* expr
     );

  extern bool enable_record_assert_trip;
} // namespace fc

#if __APPLE__
    #define LIKELY(x)    __builtin_expect((long)!!(x), 1L)
    #define UNLIKELY(x)  __builtin_expect((long)!!(x), 0L)
#else
    #define LIKELY(x)   (x)
    #define UNLIKELY(x) (x)
#endif

/**
 *@brief: Workaround for varying preprocessing behavior between MSVC and gcc
 */
#define FC_EXPAND_MACRO( x ) x
/**
 *  @brief Checks a condition and throws an assert_exception if the test is FALSE
 */
#define FC_ASSERT( TEST, ... ) \
  FC_EXPAND_MACRO( \
    FC_MULTILINE_MACRO_BEGIN \
      if( UNLIKELY(!(TEST)) ) \
      {                                                                      \
        if( fc::enable_record_assert_trip )                                  \
           fc::record_assert_trip( __FILE__, __LINE__, #TEST );              \
        FC_THROW_EXCEPTION( fc::assert_exception, #TEST ": "  __VA_ARGS__ ); \
      }                                                                      \
    FC_MULTILINE_MACRO_END \
  )

#define FC_CAPTURE_AND_THROW( EXCEPTION_TYPE, ... ) \
  FC_MULTILINE_MACRO_BEGIN \
    throw EXCEPTION_TYPE( FC_LOG_MESSAGE( error, "", FC_FORMAT_ARG_PARAMS(__VA_ARGS__) ) ); \
  FC_MULTILINE_MACRO_END

//#define FC_THROW( FORMAT, ... )
// FC_INDIRECT_EXPAND workas around a bug in Visual C++ variadic macro processing that prevents it
// from separating __VA_ARGS__ into separate tokens
#define FC_INDIRECT_EXPAND(MACRO, ARGS) MACRO ARGS
#define FC_THROW(  ... ) \
  FC_MULTILINE_MACRO_BEGIN \
    throw fc::exception( FC_INDIRECT_EXPAND(FC_LOG_MESSAGE, ( error, __VA_ARGS__ )) );  \
  FC_MULTILINE_MACRO_END

#define FC_EXCEPTION( EXCEPTION_TYPE, FORMAT, ... ) \
    EXCEPTION_TYPE( FC_LOG_MESSAGE( error, FORMAT, __VA_ARGS__ ) )
/**
 *  @def FC_THROW_EXCEPTION( EXCEPTION, FORMAT, ... )
 *  @param EXCEPTION a class in the Phoenix::Athena::API namespace that inherits
 *  @param format - a const char* string with "${keys}"
 */
#define FC_THROW_EXCEPTION( EXCEPTION, FORMAT, ... ) \
  FC_MULTILINE_MACRO_BEGIN \
    throw EXCEPTION( FC_LOG_MESSAGE( error, FORMAT, __VA_ARGS__ ) ); \
  FC_MULTILINE_MACRO_END

/**
 *  @def FC_RETHROW_EXCEPTION(ER,LOG_LEVEL,FORMAT,...)
 *  @brief Appends a log_message to the exception ER and rethrows it.
 */
#define FC_RETHROW_EXCEPTION( ER, LOG_LEVEL, FORMAT, ... ) \
  FC_MULTILINE_MACRO_BEGIN \
    ER.append_log( FC_LOG_MESSAGE( LOG_LEVEL, FORMAT, __VA_ARGS__ ) ); \
    throw; \
  FC_MULTILINE_MACRO_END

#define FC_LOG_AND_RETHROW( )  \
   catch( const boost::interprocess::bad_alloc& ) {\
      throw;\
   } catch( fc::exception& er ) { \
      wlog( "${details}", ("details",er.to_detail_string()) ); \
      FC_RETHROW_EXCEPTION( er, warn, "rethrow" ); \
   } catch( const std::exception& e ) {  \
      fc::exception fce( \
                FC_LOG_MESSAGE( warn, "rethrow ${what}: ", ("what",e.what())), \
                fc::std_exception_code,\
                BOOST_CORE_TYPEID(e).name(), \
                e.what() ) ; \
      wlog( "${details}", ("details",fce.to_detail_string()) ); \
      throw fce;\
   } catch( ... ) {  \
      fc::unhandled_exception e( \
                FC_LOG_MESSAGE( warn, "rethrow"), \
                std::current_exception() ); \
      wlog( "${details}", ("details",e.to_detail_string()) ); \
      throw e; \
   }

#define FC_CAPTURE_LOG_AND_RETHROW( ... )  \
   catch( const boost::interprocess::bad_alloc& ) {\
      throw;\
   } catch( fc::exception& er ) { \
      wlog( "${details}", ("details",er.to_detail_string()) ); \
      wdump( __VA_ARGS__ ); \
      FC_RETHROW_EXCEPTION( er, warn, "rethrow", FC_FORMAT_ARG_PARAMS(__VA_ARGS__) ); \
   } catch( const std::exception& e ) {  \
      fc::exception fce( \
                FC_LOG_MESSAGE( warn, "rethrow ${what}: ", FC_FORMAT_ARG_PARAMS( __VA_ARGS__ )("what",e.what())), \
                fc::std_exception_code,\
                BOOST_CORE_TYPEID(e).name(), \
                e.what() ) ; \
      wlog( "${details}", ("details",fce.to_detail_string()) ); \
      wdump( __VA_ARGS__ ); \
      throw fce;\
   } catch( ... ) {  \
      fc::unhandled_exception e( \
                FC_LOG_MESSAGE( warn, "rethrow", FC_FORMAT_ARG_PARAMS( __VA_ARGS__) ), \
                std::current_exception() ); \
      wlog( "${details}", ("details",e.to_detail_string()) ); \
      wdump( __VA_ARGS__ ); \
      throw e; \
   }

#define FC_CAPTURE_AND_LOG( ... )  \
   catch( const boost::interprocess::bad_alloc& ) {\
      throw;\
   } catch( fc::exception& er ) { \
      wlog( "${details}", ("details",er.to_detail_string()) ); \
      wdump( __VA_ARGS__ ); \
   } catch( const std::exception& e ) {  \
      fc::exception fce( \
                FC_LOG_MESSAGE( warn, "rethrow ${what}: ",FC_FORMAT_ARG_PARAMS( __VA_ARGS__  )("what",e.what()) ), \
                fc::std_exception_code,\
                BOOST_CORE_TYPEID(e).name(), \
                e.what() ) ; \
      wlog( "${details}", ("details",fce.to_detail_string()) ); \
      wdump( __VA_ARGS__ ); \
   } catch( ... ) {  \
      fc::unhandled_exception e( \
                FC_LOG_MESSAGE( warn, "rethrow", FC_FORMAT_ARG_PARAMS( __VA_ARGS__) ), \
                std::current_exception() ); \
      wlog( "${details}", ("details",e.to_detail_string()) ); \
      wdump( __VA_ARGS__ ); \
   }

#define FC_LOG_AND_DROP( ... )  \
   catch( const boost::interprocess::bad_alloc& ) {\
      throw;\
   } catch( fc::exception& er ) { \
      wlog( "${details}", ("details",er.to_detail_string()) ); \
   } catch( const std::exception& e ) {  \
      fc::exception fce( \
                FC_LOG_MESSAGE( warn, "rethrow ${what}: ",FC_FORMAT_ARG_PARAMS( __VA_ARGS__  )("what",e.what()) ), \
                fc::std_exception_code,\
                BOOST_CORE_TYPEID(e).name(), \
                e.what() ) ; \
      wlog( "${details}", ("details",fce.to_detail_string()) ); \
   } catch( ... ) {  \
      fc::unhandled_exception e( \
                FC_LOG_MESSAGE( warn, "rethrow", FC_FORMAT_ARG_PARAMS( __VA_ARGS__) ), \
                std::current_exception() ); \
      wlog( "${details}", ("details",e.to_detail_string()) ); \
   }

/**
 *  @def FC_RETHROW_EXCEPTIONS(LOG_LEVEL,FORMAT,...)
 *  @brief  Catchs all exception's, std::exceptions, and ... and rethrows them after
 *   appending the provided log message.
 */
#define FC_RETHROW_EXCEPTIONS( LOG_LEVEL, FORMAT, ... ) \
   catch( const boost::interprocess::bad_alloc& ) {\
      throw;\
   } catch( fc::exception& er ) { \
      FC_RETHROW_EXCEPTION( er, LOG_LEVEL, FORMAT, __VA_ARGS__ ); \
   } catch( const std::exception& e ) {  \
      fc::exception fce( \
                FC_LOG_MESSAGE( LOG_LEVEL, "${what}: " FORMAT,__VA_ARGS__("what",e.what())), \
                fc::std_exception_code,\
                BOOST_CORE_TYPEID(e).name(), \
                e.what() ) ; throw fce;\
   } catch( ... ) {  \
      throw fc::unhandled_exception( \
                FC_LOG_MESSAGE( LOG_LEVEL, FORMAT,__VA_ARGS__), \
                std::current_exception() ); \
   }

#define FC_CAPTURE_AND_RETHROW( ... ) \
   catch( const boost::interprocess::bad_alloc& ) {\
      throw;\
   } catch( fc::exception& er ) { \
      FC_RETHROW_EXCEPTION( er, warn, "", FC_FORMAT_ARG_PARAMS(__VA_ARGS__) ); \
   } catch( const std::exception& e ) {  \
      fc::exception fce( \
                FC_LOG_MESSAGE( warn, "${what}: ",FC_FORMAT_ARG_PARAMS(__VA_ARGS__)("what",e.what())), \
                fc::std_exception_code,\
                BOOST_CORE_TYPEID(decltype(e)).name(), \
                e.what() ) ; throw fce;\
   } catch( ... ) {  \
      throw fc::unhandled_exception( \
                FC_LOG_MESSAGE( warn, "",FC_FORMAT_ARG_PARAMS(__VA_ARGS__)), \
                std::current_exception() ); \
   }


text:
#include <iostream>
#include <map>
#include <cstring>
#include <fstream>
#include <queue>
#include <boost/algorithm/string.hpp>
#include <list>
#include <algorithm>
using namespace std;

bool check_palindrome(std::string s)
{
    std::size_t i = 0;
    std::size_t j = s.length() - 1;
    while (i < j)
    {
        if (s[i++] != s[j--])
        {
            return false;
        }
    }

    return true;
}

std::list<string> GetPalindrome()
{
	string filename;
	cout << "What file do you want to use for input? ";
	getline(cin, filename);
	ifstream fin;
	fin.open(filename.c_str());
	string str;
	char * token;

	std::list<string>List_Palindrome;

	while (fin >> str)
	{
		char *fileName = (char*)str.c_str();
		token = strtok (fileName," ,.-!;:\|'}{][)(");
		while (token != NULL)
		{
			boost::algorithm::to_lower(token);
			//mymap[token]++;
			if(check_palindrome(token))
			{
				List_Palindrome.push_back(str);
			}

			token = strtok (NULL, " ,.-!;:\|'}{][)(");

		}
	}
	fin.close();
	return List_Palindrome;
}

void print (std::list<string> myMap)
{
	for (std::list<string>::iterator it=myMap.begin(); it!=myMap.end(); ++it)
	{
		std::cout << *it<< endl;
	}
}

int print_freq_sorted(std::map<std::string, int> myMap)
{
	int total=0;

	std::priority_queue<std::pair<int, std::string> > pq;
	for (std::map<string,int>::iterator it=myMap.begin(); it!=myMap.end(); ++it)
	{
		pq.push(std::make_pair(it->second, it->first)); ///push into heap
		total=total+it->second;
	}
	int size=myMap.size();
	for(int i=1; i<=size;i++)
	{
		std::cout << pq.top().first << ", " << pq.top().second << std::endl;
		pq.pop();
	}
	cout<<"Total Number of words"<<":"<<total<<endl;
	return total;
}

void print_freq(std::map<std::string,int> mymap)
{

	for (std::map<std::string,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
		std::cout << it->first << " => " << it->second << '\n';

}

std::map<string, int> GetFreq(std::list<string>list)
{
	std::map<std::string, int> Frequency;
	for(std::list<string>::iterator it=list.begin();it!=list.end();++it)
		Frequency[*it]++;
	return Frequency;
}

int main()
{
	std::list<string>Palindromes=GetPalindrome(); /// get the palindromes
	print(Palindromes);				/// print the palindromes
	std::map<string, int> Frequency=GetFreq(Palindromes); //// get the frequency of the palindromes
	print_freq(Frequency);
	print_freq_sorted(Frequency);  ///print the frequency in sorted order

}
// It has a linear time complexity.
// The palindrome checker is O(m/2)~O(m) where m is the size of each string.
// Then I used a hashmap to get the frequency. And then used a priority queue to sort them and print in order
// Thus, worst case is O(n).

ext: cpp

max_stars_repo_name: anishacharya/Search-Engine-From-Scratch

max_issues_repo_name: anishacharya/Search-Engine-From-Scratch

max_forks_repo_name: anishacharya/Search-Engine-From-Scratch


text:
#include "../mutation_annotated_tree.hpp"
#include "src/matOptimize/tree_rearrangement_internal.hpp"
#include "transpose_vcf.hpp"
#include <algorithm>
#include <boost/program_options.hpp>
#include <boost/program_options/value_semantic.hpp>
#include <climits>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <fstream>
#include <iostream>
#include <iterator>
#include <mutex>
#include <string>
#include <tbb/blocked_range.h>
#include <tbb/concurrent_vector.h>
#include <tbb/enumerable_thread_specific.h>
#include <tbb/parallel_for.h>
#include <tbb/pipeline.h>
#include <tbb/task_scheduler_init.h>
#include <unistd.h>
#include <unordered_map>
#include <utility>
#include <vector>
#include <zlib.h>
std::string chrom;
std::string ref;
struct Pos_Mut {
    int position;
    uint8_t mut;
    Pos_Mut(int position, uint8_t mut) : position(position), mut(mut) {}
    bool operator<(const Pos_Mut &other) const {
        return position < other.position;
    }
};

struct Sample_Pos_Mut {
    std::string name;
    std::vector<Pos_Mut> not_Ns;
    std::vector<std::pair<int, int>> Ns;
    Sample_Pos_Mut(std::string &&name) : name(std::move(name)) {}
};
struct Sample_Pos_Mut_Printer {
    std::vector<Pos_Mut>::const_iterator not_Ns_iter;
    const std::vector<Pos_Mut>::const_iterator not_Ns_end;
    std::vector<std::pair<int, int>>::const_iterator Ns_iter;
    const std::vector<std::pair<int, int>>::const_iterator Ns_end;
    Sample_Pos_Mut_Printer(const Sample_Pos_Mut &in)
        : not_Ns_iter(in.not_Ns.begin()), not_Ns_end(in.not_Ns.end()),
          Ns_iter(in.Ns.begin()), Ns_end(in.Ns.end()) {}
    int print(uint8_t *out) {
        int end;
        if (not_Ns_iter == not_Ns_end ||
                (Ns_iter != Ns_end && Ns_iter->first < not_Ns_iter->position)) {
            memset(out, 'N', Ns_iter->second - Ns_iter->first + 1);
            end = Ns_iter->second;
            Ns_iter++;
        } else {
            *out = Mutation_Annotated_Tree::get_nuc(not_Ns_iter->mut);
            end = not_Ns_iter->position;
            not_Ns_iter++;
        }
        assert(not_Ns_iter<=not_Ns_end&&Ns_iter<=Ns_end);
        return end;
    }
    int next_pos() const {
        auto next_pos=std::min(not_Ns_end == not_Ns_iter ? INT_MAX
                               : not_Ns_iter->position,
                               Ns_end == Ns_iter ? INT_MAX : Ns_iter->first);
        assert(next_pos!=INT_MAX);
        return (next_pos);
    }
    operator bool() const {
        return (Ns_iter != Ns_end) || (not_Ns_iter != not_Ns_end);
    }
};

struct Sample_Pos_Mut_Wrap {
    Sample_Pos_Mut &content;
    void add_Not_N(int position, uint8_t allele) {
        content.not_Ns.emplace_back(position-1, allele);
    }
    void add_N(int first, int second) {
        content.Ns.emplace_back(first-1, second-1);
    }
};

typedef tbb::enumerable_thread_specific<std::vector<Sample_Pos_Mut>>
        sample_pos_mut_local_t;
sample_pos_mut_local_t sample_pos_mut_local;
struct All_Sample_Appender {
    Sample_Pos_Mut_Wrap set_name(std::string &&name) {
        sample_pos_mut_local_t::reference my_sample_pos_mut_local =
            sample_pos_mut_local.local();
        my_sample_pos_mut_local.emplace_back(std::move(name));
        return Sample_Pos_Mut_Wrap{my_sample_pos_mut_local.back()};
    }
};
void load_reference(const char *ref_path, std::string &seq_name,
                    std::string &reference) {
    std::ifstream fasta_f(ref_path);
    std::string temp;
    std::getline(fasta_f, temp);
    seq_name = temp.substr(1, 50);
    while (fasta_f) {
        std::getline(fasta_f, temp);
        reference += temp;
    }
}
namespace po = boost::program_options;
size_t write_sample(uint8_t *out, const Sample_Pos_Mut &in,
                    const std::string &seq) {
    out[0] = '>';
    memcpy(out + 1, in.name.c_str(), in.name.size());
    out[1 + in.name.size()] = '\n';
    auto start_offset = 2 + in.name.size();
    int last_print = 0;
    Sample_Pos_Mut_Printer printer(in);
    while (printer) {
        auto next = printer.next_pos();
        assert(next<seq.size());
        auto ref_print_siz = next - last_print;
        memcpy(out + last_print + start_offset, seq.data() + last_print,
               ref_print_siz);
        last_print = printer.print(out + next + start_offset) + 1;
        assert(last_print<seq.size());
    }
    memcpy(out + last_print + start_offset, seq.data() + last_print,
           seq.size() - last_print);
    out[start_offset + seq.size()] = '\n';
    return start_offset + seq.size() + 1;
}
#define OUT_BUF_SIZ 0x100000
struct Batch_Printer {
    const std::vector<Sample_Pos_Mut> ∈
    const std::string &seq;
    const size_t inbuf_siz;
    const int fd;
    std::mutex& out_mutex;
    mutable z_stream stream;
    mutable uint8_t *inbuf;
    mutable uint8_t *outbuf;
    Batch_Printer(const std::vector<Sample_Pos_Mut> &in, const std::string &seq,
                  size_t inbuf_siz,int fd,std::mutex& out_mutex)
        : in(in), seq(seq), inbuf_siz(inbuf_siz),fd(fd),out_mutex(out_mutex), inbuf(nullptr),
          outbuf(nullptr) {
        stream.opaque = nullptr;
        stream.zalloc = nullptr;
        stream.zfree = nullptr;
    }
    Batch_Printer(const Batch_Printer &other)
        : in(other.in), seq(other.seq), inbuf_siz(other.inbuf_siz),fd(other.fd), out_mutex(other.out_mutex),inbuf(nullptr),
          outbuf(nullptr) {
        stream.opaque = nullptr;
        stream.zalloc = nullptr;
        stream.zfree = nullptr;
    }
    void init() const {
        if (!inbuf) {
            inbuf=(uint8_t*) malloc(inbuf_siz);
            outbuf=(uint8_t*) malloc(OUT_BUF_SIZ);
            //auto err =
            deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
                         15 | 16, 9, Z_DEFAULT_STRATEGY);
            //assert(err==Z_OK);
        } else {
            //auto err=
            deflateReset(&stream);
            //assert(err==Z_OK);
        }
        stream.avail_out=OUT_BUF_SIZ;
        stream.next_out=outbuf;
    }
    void output()const {
        if (stream.avail_out<OUT_BUF_SIZ/2) {
            //auto err =
            deflate(&stream, Z_FINISH);
            //assert(err==Z_STREAM_END);
            out_mutex.lock();
            auto out=write(fd,outbuf,stream.next_out-outbuf);
            if (out!=stream.next_out-outbuf) {
                fprintf(stderr, "Couldn't output\n");
                exit(EXIT_FAILURE);
            }
            out_mutex.unlock();
            deflateReset(&stream);
            stream.avail_out=OUT_BUF_SIZ;
            stream.next_out=outbuf;
        }
    }
    void operator()(tbb::blocked_range<size_t> range) const {
        //fprintf(stderr, "%zu ",range.size());
        init();
        stream.avail_out = OUT_BUF_SIZ;
        stream.next_out = outbuf;
        for (size_t samp_idx = range.begin(); samp_idx < range.end();
                samp_idx++) {
            auto bytes_written=write_sample(inbuf, in[samp_idx], seq);
            stream.next_in=inbuf;
            stream.avail_in=bytes_written;
            auto err = deflate(&stream, Z_NO_FLUSH);
            assert(stream.avail_out);
            if (err!=Z_OK) {
                fprintf(stderr, "%d\n",err);
            }
            assert(err==Z_OK);
            output();
        }
        //auto err =
        deflate(&stream, Z_FINISH);
        //assert(err==Z_STREAM_END);
        out_mutex.lock();
        auto written_bytes=write(fd, outbuf, stream.next_out-outbuf);
        if (written_bytes!=stream.next_out-outbuf) {
            fprintf(stderr, "Couldn't output\n");
            exit(EXIT_FAILURE);
        }
        out_mutex.unlock();
    }
    ~Batch_Printer() {
        if (inbuf) {
            free(inbuf);
            free(outbuf);
            deflateEnd(&stream);
        }
    }
};
int main(int argc, char **argv) {
    po::options_description desc{"Options"};
    uint32_t num_cores = tbb::task_scheduler_init::default_num_threads();
    std::string output_fa_file;
    std::string input_path;
    std::string rename_file;
    uint32_t num_threads;
    std::string reference;
    std::string num_threads_message = "Number of threads to use when possible "
                                      "[DEFAULT uses all available cores, " +
                                      std::to_string(num_cores) +
                                      " detected on this machine]";
    desc.add_options()(
        "fa,o", po::value<std::string>(&output_fa_file)->required(),
        "Output FASTA file (in uncompressed or gzip-compressed .gz format) ")(
            "threads,T",
            po::value<uint32_t>(&num_threads)->default_value(num_cores),
            num_threads_message
            .c_str())("reference,r",
                      po::value<std::string>(&reference)->required(),
                      "Reference file")("samples,s",
                                        po::value<std::string>(&rename_file),
                                        "rename file")("output_path,i",
                                                po::value<std::string>(
                                                        &input_path)
                                                ->required(),
                                                "Load transposed VCF");
    po::options_description all_options;
    all_options.add(desc);
    po::variables_map vm;
    try {
        po::store(
            po::command_line_parser(argc, argv).options(all_options).run(), vm);
        po::notify(vm);
    } catch (std::exception &e) {
        std::cerr << desc << std::endl;
        // Return with error code 1 unless the user specifies help
        if (vm.count("help"))
            return 0;
        else
            return 1;
    }
    std::unordered_map<std::string, std::string> rename_mapping;
    if (rename_file != "") {
        parse_rename_file(rename_file, rename_mapping);
    }
    tbb::task_scheduler_init init(num_threads);
    load_reference(reference.c_str(), chrom, ref);
    All_Sample_Appender appender;
    load_mutations(input_path.c_str(), 80, appender);
    std::vector<Sample_Pos_Mut> all_samples;
    if (rename_mapping.empty()) {
        for (auto &sample_block : sample_pos_mut_local) {
            all_samples.insert(all_samples.end(),
                               std::make_move_iterator(sample_block.begin()),
                               std::make_move_iterator(sample_block.end()));
        }
    } else {
        all_samples.reserve(rename_mapping.size());
        for (auto &sample_block : sample_pos_mut_local) {
            for (const auto &sample : sample_block) {
                auto iter = rename_mapping.find(sample.name);
                if (iter != rename_mapping.end()) {
                    all_samples.push_back(std::move(sample));
                    all_samples.back().name = iter->second;
                    rename_mapping.erase(iter);
                }
            }
            sample_block.clear();
        }
    }
    for (const auto &name : rename_mapping) {
        fprintf(stderr, "sample %s not found \n", name.first.c_str());
    }
    size_t max_name_len=0;
    for(const auto& samp:all_samples) {
        max_name_len=std::max(max_name_len,samp.name.size());
    }
    auto inbuf_size=max_name_len+ref.size()+8;
    auto out_fd=open(output_fa_file.c_str(),O_WRONLY|O_CREAT|O_TRUNC,S_IRWXU|S_IRWXG|S_IRWXO);
    std::mutex f_mutex;
    tbb::parallel_for(tbb::blocked_range<size_t>(0,all_samples.size(),all_samples.size()/num_threads), Batch_Printer{all_samples,ref,inbuf_size,out_fd,f_mutex});
    close(out_fd);
}

max_stars_repo_name: abschneider/usher

max_issues_repo_name: abschneider/usher

max_forks_repo_name: abschneider/usher


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_SDK_DSL_IS_COMPARISON_EXPRESSION_HPP_INCLUDED
#define BOOST_SIMD_SDK_DSL_IS_COMPARISON_EXPRESSION_HPP_INCLUDED

////////////////////////////////////////////////////////////////////////////////
// Check if a given proto expression has a tag of a comaprison operator
////////////////////////////////////////////////////////////////////////////////
#include <boost/mpl/bool.hpp>
#include <boost/proto/tags.hpp>
#include <boost/proto/matches.hpp>

namespace boost { namespace simd {  namespace details
{
  struct compare_cases
  {
    template<class Tag> struct case_ : boost::proto::not_< boost::proto::_ > {};
  };

  template<>
  struct  compare_cases::case_< boost::proto::tag::equal_to >
        : boost::proto::_ {};

  template<>
  struct  compare_cases::case_< boost::proto::tag::not_equal_to >
        : boost::proto::_ {};

  template<>
  struct  compare_cases::case_< boost::proto::tag::less >
        : boost::proto::_ {};

  template<>
  struct  compare_cases::case_< boost::proto::tag::greater >
        : boost::proto::_ {};

  template<>
  struct  compare_cases::case_< boost::proto::tag::less_equal >
        : boost::proto::_ {};

  template<>
  struct  compare_cases::case_< boost::proto::tag::greater_equal >
        : boost::proto::_ {};
} } }

namespace boost { namespace simd {  namespace meta
{
  struct  comparison_operators
        : boost::proto::switch_< details::compare_cases>
  {};

  template<class Expr>
  struct  is_comparison_expression
        : boost::proto::matches < Expr
                                , comparison_operators
                                >
  {};
} } }

#endif

ext: hpp


text:
//          Copyright Carl Philipp Reh 2009 - 2016.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#include <fcppt/make_int_range_count.hpp>
#include <fcppt/no_init.hpp>
#include <fcppt/cast/size.hpp>
#include <fcppt/container/grid/object.hpp>
#include <fcppt/container/grid/resize_preserve_init.hpp>
#include <fcppt/container/grid/size_type.hpp>
#include <fcppt/math/dim/comparison.hpp>
#include <fcppt/math/dim/output.hpp>
#include <fcppt/preprocessor/disable_gcc_warning.hpp>
#include <fcppt/preprocessor/pop_warning.hpp>
#include <fcppt/preprocessor/push_warning.hpp>
#include <fcppt/config/external_begin.hpp>
#include <boost/test/unit_test.hpp>
#include <utility>
#include <fcppt/config/external_end.hpp>

FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)

BOOST_AUTO_TEST_CASE(
	container_grid_resize_preverse_init
)
{
FCPPT_PP_POP_WARNING

	typedef
	fcppt::container::grid::object<
		std::pair<
			fcppt::container::grid::size_type,
			fcppt::container::grid::size_type
		>,
		2
	>
	sz_pair_grid;

	sz_pair_grid test(
		sz_pair_grid::dim(
			5u,
			10u
		),
		fcppt::no_init{}
	);

	for(
		auto const y
		:
		fcppt::make_int_range_count(
			test.size()[1]
		)
	)
		for(
			auto const x
			:
			fcppt::make_int_range_count(
				test.size()[0]
			)
		)
			test[
				sz_pair_grid::pos(
					x,
					y
				)
			] =
				std::make_pair(
					x,
					y
				);

	fcppt::container::grid::resize_preserve_init(
		test,
		sz_pair_grid::dim(
			10u,
			15u
		),
		sz_pair_grid::value_type(
			10u,
			20u
		)
	);

	BOOST_CHECK_EQUAL(
		test.size(),
		sz_pair_grid::dim(
			10u,
			15u
		)
	);

	for(
		auto const y
		:
		fcppt::make_int_range_count(
			test.size()[1]
		)
	)
		for(
			auto const x
			:
			fcppt::make_int_range_count(
				test.size()[0]
			)
		)
		{
			if(
				x < 5 && y < 10
			)
				BOOST_CHECK(
					test[
						sz_pair_grid::pos(
							x,
							y
						)
					]
					==
					std::make_pair(
						fcppt::cast::size<
							fcppt::container::grid::size_type
						>(
							x
						),
						fcppt::cast::size<
							fcppt::container::grid::size_type
						>(
							y
						)
					)
				);
			else
				BOOST_CHECK(
					test[
						sz_pair_grid::pos(
							x,
							y
						)
					]
					==
					sz_pair_grid::value_type(
						10u,
						20u
					)
				);
		}
}

max_stars_repo_name: vinzenz/fcppt

max_issues_repo_name: vinzenz/fcppt

max_forks_repo_name: vinzenz/fcppt


text:
/// @file  dist.hpp
/// @brief Declarations for embedding methods using pairwise distances

#pragma once
#ifndef OGT_EMBED_DIST_HPP
#define OGT_EMBED_DIST_HPP

#include <ogt/config.hpp>
#include <Eigen/Dense>

namespace OGT_NAMESPACE {
namespace embed {

/// Produce an embedding of the specified dimensionality from the given
/// Euclidean distance matrix.
///
/// Uses Classical MDS, as described in:
/// [1] I. Borg & P. Groenen (1997): Modern multidimensional scaling: theory
///     and applications. Springer.
Eigen::MatrixXd embedDistWithDims(const Eigen::MatrixXd& dist, size_t nDim);

/// Produce an embedding from the given Euclidean distance matrix.
/// The natural dimensionality is estimated, using all eigenvalues greater than
/// or equal to the (non-negative) threshold lambda.
///
/// Uses Classical MDS, as described in:
/// [1] I. Borg & P. Groenen (1997): Modern multidimensional scaling: theory
///     and applications. Springer.
Eigen::MatrixXd embedDist(const Eigen::MatrixXd& dist,
	double lambda = 1e-12);

/// Produce an embedding using Euclidean distances to a subset of the set.
/// The matrix dist must be a n x (d+1) Euclidean distance matrix, where each
/// column represents the distance to some reference vertex.
/// The reference vertices must be the first (d+1) rows.
/// The produced embedding will be in R^maxDim, or in fewer dimensions if the
/// distances between reference vertices are not large enough to justify the
/// full dimensionality.
///
/// Implements:
/// [1]	M. J. Sippl and H. A. Scheraga, "Solution of the embedding problem and
///     decomposition of symmetric matrices.," Proceedings of the National
///     Academy of Sciences, Apr. 1985.
Eigen::MatrixXd embedDistWithCMReference(const Eigen::MatrixXd& dist,
	size_t maxDim);

/// Produce an embedding into the target dimensionality, attempting to preserve
/// the total ordering of pairwise distances.
/// An ordinal matrix is produced from the given distance matrix, and an
/// eigendecomposition is used to embed the points.
///
/// Implements method from:
/// [1] Dattorro, Jon, "Convex Optimization and Euclidean Distance Geometry,"
///     Meboo Publishing, 2016.
Eigen::MatrixXd embedDistWithOrdEig(const Eigen::MatrixXd& dist, size_t nDim);

} // end namespace embed
} // end namespace OGT_NAMESPACE
#endif /* OGT_EMBED_DIST_HPP */

max_stars_repo_name: jesand/lloe

max_issues_repo_name: jesand/lloe

max_forks_repo_name: jesand/lloe


text:
#include <bunsan/process/error.hpp>

#include <bunsan/process/context.hpp>

#include <boost/io/detail/quoted_manip.hpp>

#include <sstream>

namespace boost {
std::string to_string(const bunsan::process::error::context &context) {
  std::ostringstream sout;
  sout << '[' << bunsan::error::info_name(context) << "] = ";
  sout << to_string(context.value()) << '\n';
  return sout.str();
}

std::string to_string(const bunsan::process::error::arguments &arguments) {
  std::ostringstream sout;
  sout << '[' << bunsan::error::info_name(arguments) << "] = ";
  bool first = true;
  for (const std::string &argument : arguments.value()) {
    if (!first) {
      sout << ", ";
    }
    sout << argument;
    first = false;
  }
  sout << '\n';
  return sout.str();
}
}  // namespace boost


text:
// Copyright (C) by Josh Blum. See LICENSE.txt for licensing information.

#include <gras/factory.hpp>
#include <boost/format.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <stdexcept>
#include <iostream>
#include <map>

using namespace gras;

FactoryRegistryEntry::FactoryRegistryEntry(void)
{
    //NOP
}

FactoryRegistryEntry::~FactoryRegistryEntry(void)
{
    //NOP
}

void FactoryRegistryEntry::arg_check(const PMCList &args, const size_t nargs)
{
    if (args.size() != nargs) throw std::runtime_error(str(boost::format(
        "factory expected %u arguments but got %u") % nargs % args.size()));
}

typedef std::map<std::string, boost::shared_ptr<FactoryRegistryEntry> > FactoryRegistryType;

static FactoryRegistryType &get_factory_registry(void)
{
    static FactoryRegistryType r;
    return r;
}

static boost::mutex mutex;

void gras::_register_factory(const std::string &path, void *entry)
{
    boost::mutex::scoped_lock l(mutex);
    if (get_factory_registry().count(path) != 0)
    {
        std::cerr << "Warning: Factory - function already registered for path: " + path << std::endl;
    }
    get_factory_registry()[path].reset(reinterpret_cast<FactoryRegistryEntry *>(entry));
}

Element *gras::_handle_make(const std::string &path, const PMCC &args)
{
    boost::mutex::scoped_lock l(mutex);
    if (get_factory_registry().count(path) == 0)
    {
        throw std::invalid_argument("Factory - no function registered for path: " + path);
    }
    return get_factory_registry()[path]->make(args);
}

max_stars_repo_name: guruofquality/gras

max_issues_repo_name: guruofquality/gras

max_forks_repo_name: guruofquality/gras


text:
//! \file
//! \brief script object class
//!
//! Primary Author:  Dylan Leeman
//! Contributing Author:  Aaron Weeden

#include <boost/integer_traits.hpp>

#include <autonomy/script_object.hpp>
#include <autonomy/command_registry.hpp>
#include <autonomy/script_instruction.hpp>
#include <autonomy/instruction_list.hpp>

#include <autonomy/script_commands.hpp>

#include <autonomy/compiler/parse.hpp>
#include <autonomy/compiler/symbol_table.hpp>
#include <autonomy/compiler/translator_functors.hpp>
#include <autonomy/compiler/parser_translator_map.hpp>

namespace autonomy
{
    script_object_id_t script_object::_next_id =
        boost::integer_traits< script_object_id_t >::const_min;

    boost::mutex script_object::_next_id_mutex;

    instruction_list translate(
        compiler::parse_tree_match_t::tree_iterator root,
        compiler::parse_tree_match_t::tree_iterator parent,
        const instruction_list & il,
        compiler::symbol_table & st,
        compiler::parser_translator_map & pt_map,
        const command_registry & cr );

    std::string script_object::compile()
    {
        compiler::symbol_table st;
        compiler::parse::program the_program;
        compiler::parse::skipper skip_p;
        compiler::parse_node_attributes empty;

        compiler::parser_translator_map pt_map;

        // Populate translator map, no help for this
        pt_map.register_translator< compiler::parse::DECL_ID, compiler::decl_translator >( );
        pt_map.register_translator< compiler::parse::ASGN_ID, compiler::asgn_translator >();
        pt_map.register_translator< compiler::parse::BASE_ID, compiler::base_translator >();
        pt_map.register_translator< compiler::parse::FACTORCONT_ID,
            compiler::factorcont_translator >();
        pt_map.register_translator< compiler::parse::TERMCONT_ID, compiler::termcont_translator >();
        pt_map.register_translator< compiler::parse::EXPRCONT_ID, compiler::exprcont_translator >();
        pt_map.register_translator< compiler::parse::RELCONT_ID, compiler::relcont_translator >();
        pt_map.register_translator< compiler::parse::LLIT_ID, compiler::llit_translator >();
        pt_map.register_translator< compiler::parse::CONJCONT_ID, compiler::conjcont_translator >();
        pt_map.register_translator< compiler::parse::BEXPRCONT_ID,
            compiler::bexprcont_translator >();
        pt_map.register_translator< compiler::parse::CMD_ID, compiler::cmd_translator >();
        pt_map.register_translator< compiler::parse::COND_ID, compiler::cond_translator >();
        pt_map.register_translator< compiler::parse::WHILE_ID, compiler::while_translator >();
        pt_map.register_translator< compiler::parse::CONDCONT_ID, compiler::condcont_translator >();
        pt_map.register_translator< compiler::parse::PROG_ID, compiler::prog_translator >();
        pt_map.register_translator< compiler::parse::STMT_ID, compiler::stmt_translator >();

        command_registry cr;
        // Populate Command registry, will be done dynamically in future
        boost::shared_ptr<script_instruction>
            move_ptr(static_cast<script_instruction*>(new move));
        cr.add_command("move", move_ptr);

        boost::shared_ptr<script_instruction>
            get_x_ptr(static_cast<script_instruction*>(new get_x));
        cr.add_command("get_x", get_x_ptr);
        boost::shared_ptr<script_instruction>
            get_y_ptr(static_cast<script_instruction*>(new get_y));
        cr.add_command("get_y", get_y_ptr);

        boost::shared_ptr<script_instruction>
            scan_ptr(static_cast<script_instruction*>(new scan));
        cr.add_command("scan", scan_ptr);

        boost::shared_ptr<script_instruction>
            is_drone_ptr(static_cast<script_instruction*>(new is_drone));
        cr.add_command("is_drone", is_drone_ptr);
        boost::shared_ptr<script_instruction>
            is_asteroid_ptr(static_cast<script_instruction*>(new is_asteroid));
        cr.add_command("is_asteroid", is_asteroid_ptr);
        boost::shared_ptr<script_instruction>
            is_base_ptr(static_cast<script_instruction*>(new is_base));
        cr.add_command("is_base", is_base_ptr);

        boost::shared_ptr<script_instruction>
            rand_dir_ptr(static_cast<script_instruction*>(new rand_dir));
        cr.add_command("rand_dir", rand_dir_ptr);

        boost::shared_ptr<script_instruction>
            mine_ptr(static_cast<script_instruction*>(new mine));
        cr.add_command("mine", mine_ptr);

        boost::shared_ptr<script_instruction>
            unload_ptr(static_cast<script_instruction*>(new unload));
        cr.add_command("unload", unload_ptr);

        // done populating command registry

        compiler::parse_input_iterator_t begin(_raw_form.begin(), _raw_form.end());
        compiler::parse_input_iterator_t end;

        boost::spirit::tree_parse_info
            < compiler::parse_input_iterator_t,
              compiler::parse_tree_node_factory_t >
                parsed = boost::spirit::pt_parse< compiler::parse_tree_node_factory_t >
                            ( begin, end, the_program, skip_p );

        // clear the internal compiled form, if there are no entities with references
        // to the script, it will be destructed, otherwise they will retain their
        // reference
        _compiled_form = boost::shared_ptr<instruction_list>();

        if ( !parsed.full )
        {
            return std::string("Parse error.");
        }

        try
        {
            _compiled_form
                = boost::shared_ptr< instruction_list >(new instruction_list(
                            translate(parsed.trees.begin(),
                                      compiler::parse_tree_match_t::tree_iterator(),
                                      instruction_list(),
                                      st, pt_map, cr)));
        }
        catch ( compiler::translator_exception error )
        {
            return std::string(error.what());
        }
        // no compiler errors
        return std::string();
    }

    void script_object::set_raw( const std::string & raw_text )
    {
        _compiled_form = boost::shared_ptr< instruction_list >();
        _raw_form = raw_text;
    }

    std::istream & operator>> ( std::istream & is, script_object & so )
    {
        so._compiled_form = boost::shared_ptr < instruction_list >();
        std::string line;
        while ( is.good() )
        {
            getline( is, line, '\n' );
            so._raw_form += line + '\n';
        }
        return is;
    }

    //! \function translate
    //! \brief    Translates a parsed subtree to Autonomy instruction lists
    instruction_list translate(
        compiler::parse_tree_match_t::tree_iterator root,
        compiler::parse_tree_match_t::tree_iterator parent,
        const instruction_list & il,
        compiler::symbol_table & st,
        compiler::parser_translator_map & pt_map,
        const command_registry & cr )
    {
        instruction_list ins;
        std::pair < bool, instruction_list > status;

        compiler::construct_translator_ptr trans_constructor
        = pt_map.translator(root->value.id().to_long());

        std::auto_ptr< compiler::translator_base > translator
        = (*trans_constructor)(root->value.id().to_long(),
                               root->value.value(), st, cr);

        if (parent == compiler::parse_tree_match_t::tree_iterator())
        {
            // this node has no parent, call it's translator's
            // operator() with the appropriate parameters
            compiler::parse_node_attributes nil;
            status = (*translator)(il, compiler::NIL_ID, nil);
        }
        else
        {
            // call this node's translator with the parent node as the
            // node just processed
            status = (*translator)(il,
                                   parent->value.id().to_long(),
                                   parent->value.value());
        }
        root->value.value(translator->attributes());

        compiler::parse_tree_match_t::tree_iterator child(root->children.begin());
        while (child != root->children.end() && status.first)
        {
            ins = translate(child, root, status.second, st, pt_map, cr);
            status = (*translator)(ins,
                                   child->value.id().to_long(),
                                   child->value.value());
            root->value.value(translator->attributes());

            ++child;
        }

        return status.second;
    }

}

max_stars_repo_name: medlefsen/autonomy

max_issues_repo_name: medlefsen/autonomy

max_forks_repo_name: medlefsen/autonomy


text:
/*! \file demo_1d_x_external.cpp
  \brief 1D plot from two vectors of doubles, showing axis label variation.
  \author Jacob Voytko and Paul A. Bristow
  \date 2009
*/

// Copyright Jacob Voytko 2007
// Copyright Paul A. Bristow 2009

// Distributed under the Boost Software License, Version 1.0.
// For more information, see http://www.boost.org

#include <boost/svg_plot/svg_1d_plot.hpp>
#include <vector>

using std::vector;
using namespace boost::svg;

//enum x_axis_intersect
//{ //! \enum x_axis_intersect If and how the X axes intersects Y axis.
//  bottom = -1, //!< X-axis free below bottom of end of Y-axis (case of all Y definitely < 0).
//  x_intersects_y = 0, //!< x_intersects_y when Y values include zero, so X intersects the Y axis.
//  top = +1 //!< X-axis free above top of X-axis (case of all Y definitely > 0).
//  };

int main()
{
//[demo_1d_x_external_1

/*`Following previous examples, we set up two containers for two data series.
*/
  vector<double> dan_times;
  vector<double> elaine_times;

  dan_times.push_back(3.1);
  dan_times.push_back(4.2);
  elaine_times.push_back(2.1);
  elaine_times.push_back(7.8);

  svg_1d_plot my_plot;

  // Adding some generic settings.
  my_plot.background_border_color(black)
         .legend_on(true)
         .plot_window_on(true)
         .title("Race Times")
         .x_range(-1, 10);

/*`We add tastelessly color the grids for both major and minor ticks, and switch both grids on.
*/
  my_plot.x_major_grid_color(pink)
         .x_minor_grid_color(lightgray);

  my_plot.x_major_grid_on(true)
         .x_minor_grid_on(true);

/*`Also we specify the position of the labelling of the X-axis.
It can be controlled using values in the `enum x_axis_intersect`.
``
  enum x_axis_intersect
  { //! \enum x_axis_intersect
    bottom = -1, // On the bottom of the plot window.
    x_intersects_y = 0, // On the Y axis (in the middle of the plot window).
    top = +1 // On the top of the plot window.
  };
``
For this example, we choose to show the X axis and tick value labels at the top of the plot window.
*/
  my_plot.x_ticks_on_window_or_axis(top); // on top, not on axis.

  // Write to plot.
  my_plot.plot(dan_times, "Dan").stroke_color(blue);
  my_plot.plot(elaine_times, "Elaine").stroke_color(orange);

  // Write to file.
  my_plot.write("./demo_1d_x_external.svg");
  return 0;
} // int main()
//] [/demo_1d_x_external_1]

/*
Output:

Compiling...
demo_1d_x_external.cpp
Linking...
Embedding manifest...
Autorun "j:\Cpp\SVG\debug\demo_1d_x_external.exe"
*/


text:
//
// Created by arssivka on 11/9/15.
//

#include <rd/network/RPCServer.h>
#include <xmlrpc-c/server_abyss.hpp>
#include <boost/make_shared.hpp>

using namespace rd;
using namespace std;
using namespace boost;

RPCServer::RPCServer(int port) : port(port) { }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int RPCServer::getPort() const {
    return port;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void RPCServer::setPort(int port) {
    this->port = port;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void RPCServer::addModule(shared_ptr<RemoteModule> module) {
    this->modules_container.push_back(module);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

bool RPCServer::removeModule(std::string name) {
    vector<boost::shared_ptr<RemoteModule> >::iterator it;
    for (it = this->modules_container.begin();
         it != this->modules_container.end(); ++it) {
        if (name == it->get()->getName()) break;
    }

    if (it != this->modules_container.end()) {
        this->modules_container.erase(it);
        return true;
    } else {
        return false;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

const vector<shared_ptr<RemoteModule> > &RPCServer::getModules() const {
    return this->modules_container;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void RPCServer::addMethod(shared_ptr<RemoteMethod> func) {
    this->func_container.push_back(func);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

bool RPCServer::removeMethod(const string &name) {
    vector<shared_ptr<RemoteMethod> >::iterator it;
    for (it = this->func_container.begin(); it != this->func_container.end(); ++it) {
        if (name == it->get()->getName()) break;
    }

    if (it != this->func_container.end()) {
        this->func_container.erase(it);
        return true;
    } else {
        return false;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

const vector<shared_ptr<RemoteMethod> > &RPCServer::getMethods() const {
    return this->func_container;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void RPCServer::run() {
    vector<shared_ptr<RemoteMethod> > methods(this->func_container);
    {
        vector<shared_ptr<RemoteModule> >::iterator it;
        for (it = this->modules_container.begin(); it != this->modules_container.end(); ++it) {
            const vector<shared_ptr<RemoteMethod> > &m = (*it)->getMethods();
            methods.insert(methods.end(), m.begin(), m.end());
        }
    }

    xmlrpc_c::registry reg;
    {
        vector<shared_ptr<RemoteMethod> >::iterator it;
        for (it = methods.begin(); it != methods.end(); ++it) {
            RemoteMethod *method = it->get();
            reg.addMethod(method->getName(), method);
        }
    }

    xmlrpc_c::serverAbyss srv(xmlrpc_c::serverAbyss::constrOpt()
                                      .registryP(&reg)
                                      .portNumber(this->port));
    srv.run();
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

RPCServer::~RPCServer() { }

max_stars_repo_name: arssivka/naomech

max_issues_repo_name: arssivka/naomech

max_forks_repo_name: arssivka/naomech


text:
/* (c) Copyright 2012 Felipe Magno de Almeida
 *
 * Distributed under the Boost Software License, Version 1.0. (See
 * accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 */

#ifndef MORBID_IDL_PARSER_TYPEDEF_DEF_HPP
#define MORBID_IDL_PARSER_TYPEDEF_DEF_HPP

#include <morbid/idl_parser/type_spec.hpp>

#include <boost/fusion/include/adapt_struct.hpp>

#include <ostream>
#include <string>

namespace morbid { namespace idl_parser {

template <typename Iterator>
struct typedef_def
{
  type_spec<Iterator> alias;
  std::string name;
};

template <typename Iterator>
std::ostream& operator<<(std::ostream& os, typedef_def<Iterator> d)
{
  return os << "[typedef_def name: " << d.name
            << " alias: " << d.alias
            << "]";
}

} }

BOOST_FUSION_ADAPT_TPL_STRUCT((Iterator)
                              , (::morbid::idl_parser::typedef_def) (Iterator)
                              , (::morbid::idl_parser::type_spec<Iterator>, alias)
                              (std::string, name));

#endif

max_stars_repo_name: felipealmeida/mORBid

max_issues_repo_name: felipealmeida/mORBid

max_forks_repo_name: felipealmeida/mORBid


text: #include <boost/fusion/support/is_segmented.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*****************************************************************************
*
* Rokko: Integrated Interface for libraries of eigenvalue decomposition
*
* Copyright (C) 2013-2015 Rokko Developers https://github.com/t-sakashita/rokko
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*****************************************************************************/

#include <rokko/rokko.hpp>
#include <rokko/utility/helmert_matrix.hpp>
#include <boost/foreach.hpp>
#define BOOST_TEST_MODULE test_solver
#ifndef BOOST_TEST_DYN_LINK
#include <boost/test/included/unit_test.hpp>
#else
#include <boost/test/unit_test.hpp>
#endif

BOOST_AUTO_TEST_CASE(test_solver) {
  int provided;
  MPI_Init_thread(&boost::unit_test::framework::master_test_suite().argc,
                  &boost::unit_test::framework::master_test_suite().argv,
                  MPI_THREAD_MULTIPLE, &provided);

  MPI_Comm comm = MPI_COMM_WORLD;
  const int dim = 100;
  rokko::localized_vector<double> diag(dim);
  diag.setLinSpaced(diag.size(), 1, diag.size()); // diag = [1, 2, 3, ..., dim]

  std::vector<std::string> names;
  int argc = boost::unit_test::framework::master_test_suite().argc;
  if (argc == 1) {
    names = rokko::parallel_dense_solver::solvers();
  } else {
    for (int num=1; num < argc; ++num) {
      names.push_back(boost::unit_test::framework::master_test_suite().argv[num]);
    }
  }

  BOOST_FOREACH(std::string name, names) {
    std::cout << "solver=" << name << std::endl;
    rokko::parallel_dense_solver solver(name);
    if (solver.is_available_grid_major(rokko::grid_col_major)) {
      solver.initialize(boost::unit_test::framework::master_test_suite().argc,
                        boost::unit_test::framework::master_test_suite().argv);
      rokko::grid g(comm, rokko::grid_col_major);
      rokko::distributed_matrix<double, rokko::matrix_col_major> mat(dim, dim, g, solver);
      rokko::helmert_matrix::generate_for_given_eigenvalues(mat, diag);
      rokko::localized_vector<double> w(dim);
      rokko::distributed_matrix<double, rokko::matrix_col_major> Z(dim, dim, g, solver);

      solver.diagonalize(mat, w, Z);

      BOOST_CHECK_CLOSE(w.sum(), diag.sum(), 10e-5);

      solver.finalize();
    }
  }

  BOOST_FOREACH(std::string name, names) {
    std::cout << "solver=" << name << std::endl;
    rokko::parallel_dense_solver solver(name);
    if (solver.is_available_grid_major(rokko::grid_row_major)) {
      solver.initialize(boost::unit_test::framework::master_test_suite().argc,
                        boost::unit_test::framework::master_test_suite().argv);
      rokko::grid g(comm, rokko::grid_row_major);
      rokko::distributed_matrix<double, rokko::matrix_col_major> mat(dim, dim, g, solver);
      rokko::helmert_matrix::generate_for_given_eigenvalues(mat, diag);
      rokko::localized_vector<double> w(dim);
      rokko::distributed_matrix<double, rokko::matrix_col_major> Z(dim, dim, g, solver);

      solver.diagonalize(mat, w, Z);

      BOOST_CHECK_CLOSE(w.sum(), diag.sum(), 10e-5);

      solver.finalize();
    }
  }
  MPI_Finalize();
}

max_stars_repo_name: wistaria/rokko

max_issues_repo_name: wistaria/rokko

max_forks_repo_name: wistaria/rokko


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

#include "Test.h"

#include <sstream>
#include <fstream>

#include <rapidjson/rapidjson.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>

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

#include "../lib/RapidJsonDefs.h"

namespace TestsCommon {

namespace fs = boost::filesystem;

namespace {

std::string ToString(JsonSchemaValidator::JsonValue const &value) {
	using namespace rapidjson;
	GenericStringBuffer<UTF8<> > buffer;
	Writer<GenericStringBuffer<UTF8<> > > writer(buffer);
	value.Accept(writer);

	std::string string = buffer.GetString();
	return buffer.GetString();
}

std::vector<fs::path> GetTestFiles()
{
	fs::directory_iterator it("../thirdparty/json_schema_test_suite/tests/draft3"), endIt;
	std::vector<fs::path> test_files;
	std::copy_if(it, endIt, std::back_inserter(test_files), [](fs::directory_entry const &entry) -> bool {
		return fs::is_regular_file(entry) &&
		       boost::algorithm::ends_with(entry.path().string(), ".json") &&
		       entry.path().filename().string() != "ref.json";
	});
	return test_files;
}

void LoadTestCases(fs::path const &path_to_file, JsonSchemaValidator::JsonDocument &test_case) {
	std::ifstream test_file(path_to_file.string());
	std::istreambuf_iterator<char> it(test_file), endIt;
	std::string test_file_content(it, endIt);

	test_case.Parse<0>(test_file_content.c_str());
}

std::string GetStringTestData(JsonSchemaValidator::JsonValue const &test_data) {
	std::stringstream ss;
	ss << std::boolalpha << std::fixed << "{\"data\": ";
	if (test_data.IsObject() || test_data.IsArray()) ss << ToString(test_data);
	else if (test_data.IsString()) ss << "\"" << test_data.GetString() << "\"";
	else if (test_data.IsDouble()) ss << test_data.GetDouble();
	else if (test_data.IsNumber()) ss << test_data.GetInt64();
	else if (test_data.IsBool()) ss << test_data.GetBool();
	else if (test_data.IsNull()) ss << "null";
	ss << "}";
	return ss.str();
}

} // namespace

///////////////////////////////////////////////////////////////////////////////////////////////////
Test::Test(std::string const &name, std::string const &schema,
           std::string const &inspected_document, bool expect_result)
	: name_(name)
	, schema_(schema)
	, inspected_document_(inspected_document)
	, expect_result_(expect_result) {
}

std::string Test::GetName() const {
	return name_;
}

std::string Test::GetSchema() const {
	return schema_;
}

std::string Test::GetInspectedDocument() const {
	return inspected_document_;
}

bool Test::GetExpectResult() const {
	return expect_result_;
}

Tests Test::GetTests() {
	Tests result;
	using namespace JsonSchemaValidator;
	for (auto const &file : GetTestFiles()) {
		JsonDocument test_cases;
		LoadTestCases(file, test_cases);
		assert(!test_cases.HasParseError());
		assert(test_cases.IsArray());

		for (JsonSizeType case_index = 0; case_index < test_cases.Size(); ++case_index) {
			JsonValue const &test_case(test_cases[case_index]);
			assert(test_case.HasMember("description"));
			assert(test_case.HasMember("schema"));
			assert(test_case.HasMember("tests"));
			assert(test_case["description"].IsString());
			assert(test_case["tests"].IsArray());

			std::string schema = ToString(test_case["schema"]);
			std::string description = test_case["description"].GetString();
			JsonValue const &tests(test_case["tests"]);
			for (JsonSizeType test_index = 0; test_index < tests.Size(); ++test_index) {
				JsonValue const &test(tests[test_index]);
				assert(test.HasMember("description"));
				assert(test.HasMember("data"));
				assert(test.HasMember("valid"));
				assert(test["description"].IsString());
				assert(test["valid"].IsBool());

				std::string test_name = file.filename().string() + "/" + description +
				                        "/" + test["description"].GetString();
				result.emplace_back(test_name, schema, GetStringTestData(test["data"]),
				                    test["valid"].GetBool());
			}
		}
	}
	return result;
}

} // namespace TestsCommon

ext: cc

max_stars_repo_name: lyobzik/jsvor

max_issues_repo_name: lyobzik/jsvor

max_forks_repo_name: lyobzik/jsvor


text:
#include <geometry.h>
#include <tiny.h>

#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>

BOOST_AUTO_TEST_SUITE(geometry);

BOOST_AUTO_TEST_CASE(interval)
{
  typedef tiny::MathTypes<float> MT;
  typedef MT::value_traits       VT;
  typedef MT::real_type          T;

  {
    geometry::Interval<T> I;

    BOOST_CHECK_EQUAL( I.lower(), VT::highest() );
    BOOST_CHECK_EQUAL( I.upper(), VT::lowest() );
    BOOST_CHECK( geometry::is_valid(I) == false );
  }

  // No overlap
  {
    geometry::Interval<T> A;
    geometry::Interval<T> B;

    A.lower() = -2.0f;
    A.upper() = -1.0f;
    B.lower() =  1.0f;
    B.upper() =  2.0f;

    BOOST_CHECK_EQUAL( A.lower(), -2.0f );
    BOOST_CHECK_EQUAL( A.upper(), -1.0f );
    BOOST_CHECK_EQUAL( B.lower(),  1.0f );
    BOOST_CHECK_EQUAL( B.upper(),  2.0f );

    BOOST_CHECK( geometry::is_valid(A) == true );
    BOOST_CHECK( geometry::is_valid(B) == true );

    BOOST_CHECK( geometry::overlap_interval_interval(A,B) == false);
    BOOST_CHECK( geometry::overlap_interval_interval(B,A) == false);
  }

  // Deep overlap
  {
    geometry::Interval<T> A;
    geometry::Interval<T> B;

    A.lower() = -2.0f;
    A.upper() =  1.0f;
    B.lower() = -1.0f;
    B.upper() =  2.0f;

    BOOST_CHECK_EQUAL( A.lower(), -2.0f );
    BOOST_CHECK_EQUAL( A.upper(),  1.0f );
    BOOST_CHECK_EQUAL( B.lower(), -1.0f );
    BOOST_CHECK_EQUAL( B.upper(),  2.0f );

    BOOST_CHECK( geometry::overlap_interval_interval(A,B) == true);
    BOOST_CHECK( geometry::overlap_interval_interval(B,A) == true);
  }

  // Touching case
  {
    geometry::Interval<T> A;
    geometry::Interval<T> B;

    A.lower() = -2.0f;
    A.upper() =  0.0f;
    B.lower() =  0.0f;
    B.upper() =  2.0f;

    BOOST_CHECK_EQUAL( A.lower(), -2.0f );
    BOOST_CHECK_EQUAL( A.upper(),  0.0f );
    BOOST_CHECK_EQUAL( B.lower(),  0.0f );
    BOOST_CHECK_EQUAL( B.upper(),  2.0f );

    BOOST_CHECK( geometry::overlap_interval_interval(A,B) == true);
    BOOST_CHECK( geometry::overlap_interval_interval(B,A) == true);
  }

  // Indentical case
  {
    geometry::Interval<T> A;
    geometry::Interval<T> B;

    A.lower() = -2.0f;
    A.upper() =  0.0f;
    B.lower() = -2.0f;
    B.upper() =  0.0f;

    BOOST_CHECK_EQUAL( A.lower(), -2.0f );
    BOOST_CHECK_EQUAL( A.upper(),  0.0f );
    BOOST_CHECK_EQUAL( B.lower(), -2.0f );
    BOOST_CHECK_EQUAL( B.upper(),  0.0f );

    BOOST_CHECK( geometry::overlap_interval_interval(A,B) == true);
    BOOST_CHECK( geometry::overlap_interval_interval(B,A) == true);
  }

  // Zero sized interval case
  {
    geometry::Interval<T> A;
    geometry::Interval<T> B;

    A.lower() = -2.0f;
    A.upper() = -2.0f;
    B.lower() = -2.0f;
    B.upper() =  0.0f;

    BOOST_CHECK_EQUAL( A.lower(), -2.0f );
    BOOST_CHECK_EQUAL( A.upper(), -2.0f );
    BOOST_CHECK_EQUAL( B.lower(), -2.0f );
    BOOST_CHECK_EQUAL( B.upper(),  0.0f );

    BOOST_CHECK( geometry::overlap_interval_interval(A,B) == true);
    BOOST_CHECK( geometry::overlap_interval_interval(B,A) == true);

    BOOST_CHECK( geometry::is_valid(A) == true );

  }

}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: diku-dk/PROX

max_issues_repo_name: erleben/matchstick

max_forks_repo_name: erleben/matchstick


text:
#include "trajopt/common.hpp"
#include "json_marshal.hpp"
#include <boost/function.hpp>

namespace sco{struct OptResults;}

namespace trajopt {

using namespace json_marshal;
using namespace Json;
typedef Json::Value TrajOptRequest;
typedef Json::Value TrajOptResponse;
using std::string;

class CostInfo;
typedef boost::shared_ptr<CostInfo> CostInfoPtr;
class CntInfo;
typedef boost::shared_ptr<CntInfo> CntInfoPtr;
class TrajOptProb;
typedef boost::shared_ptr<TrajOptProb> TrajOptProbPtr;
class ProblemConstructionInfo;
class TrajOptResult;
typedef boost::shared_ptr<TrajOptResult> TrajOptResultPtr;

TrajOptProbPtr TRAJOPT_API ConstructProblem(const ProblemConstructionInfo&);
TrajOptProbPtr TRAJOPT_API ConstructProblem(const Json::Value&, OpenRAVE::EnvironmentBasePtr env);
TrajOptResultPtr TRAJOPT_API OptimizeProblem(TrajOptProbPtr, bool plot);
Eigen::VectorXd TRAJOPT_API SimulateAndReplan(const Json::Value& root, OpenRAVE::EnvironmentBasePtr env, bool sigma_pts_scale, bool interactive);

/**
 * Holds all the data for a trajectory optimization problem
 * so you can modify it programmatically, e.g. add your own costs
 */
class TRAJOPT_API TrajOptProb : public OptProb {
public:
	TrajOptProb();
	TrajOptProb(int n_steps, BeliefRobotAndDOFPtr rad);
	~TrajOptProb() {}
	VarVector GetVarRow(int i) {
		return m_traj_vars.row(i);
	}
	VarArray& GetVars() {
		return m_traj_vars;
	}
	int GetNumSteps() {return m_traj_vars.rows();}
	int GetNumDOF() {return m_traj_vars.cols();}
	BeliefRobotAndDOFPtr GetRAD() {return m_rad;}
	OR::EnvironmentBasePtr GetEnv() {return m_rad->GetRobot()->GetEnv();}

	void SetInitTraj(const TrajArray& x) {m_init_traj = x;}
	TrajArray GetInitTraj() {return m_init_traj;}

	friend TrajOptProbPtr ConstructProblem(const ProblemConstructionInfo&);

	bool belief_space;
private:
	VarArray m_traj_vars;
	BeliefRobotAndDOFPtr m_rad;
	TrajArray m_init_traj;
	typedef std::pair<string,string> StringPair;
};

struct TRAJOPT_API TrajOptResult {
	vector<string> cost_names, cnt_names;
	vector<double> cost_vals, cnt_viols;
	TrajArray traj;
	TrajOptResult(OptResults& opt, TrajOptProb& prob);
};

struct BasicInfo  {
	bool start_fixed;
	int n_steps;
	string manip;
	string robot; // optional
	IntVec dofs_fixed; // optional
	bool belief_space; // optional
	void fromJson(const Json::Value& v);
};

/**
Initialization info read from json
*/
struct InitInfo {
	enum Type {
		STATIONARY,
		GIVEN_TRAJ,
	};
	Type type;
	TrajArray data;
	void fromJson(const Json::Value& v);
};

/**
When cost element of JSON doc is read, one of these guys gets constructed to hold the parameters.
Then it later gets converted to a Cost object by the hatch method
*/
struct TRAJOPT_API CostInfo  {

	string name;
	virtual void fromJson(const Json::Value& v)=0;

	static CostInfoPtr fromName(const string& type);
	virtual void hatch(TrajOptProb& prob) = 0;
	typedef CostInfoPtr (*MakerFunc)();

	/**
	 * Registers a user-defined CostInfo so you can use your own cost
	 * see function RegisterMakers.cpp
	 */
	static void RegisterMaker(const std::string& type, MakerFunc);

	virtual ~CostInfo() {}
private:
	static std::map<string, MakerFunc> name2maker;
};

/**
See CostInfo
*/
struct TRAJOPT_API CntInfo  {
	string name;
	virtual void fromJson(const Json::Value& v) = 0;

	static CntInfoPtr fromName(const string& type);
	virtual void hatch(TrajOptProb& prob) = 0;
	typedef CntInfoPtr (*MakerFunc)();

	static void RegisterMaker(const std::string& type, MakerFunc);

	virtual ~CntInfo() {}
private:
	static std::map<string, MakerFunc> name2maker;
};

void fromJson(const Json::Value& v, CostInfoPtr&);
void fromJson(const Json::Value& v, CntInfoPtr&);

/**
This object holds all the data that's read from the JSON document
*/
struct TRAJOPT_API ProblemConstructionInfo {
public:
	BasicInfo basic_info;
	vector<CostInfoPtr> cost_infos;
	vector<CntInfoPtr> cnt_infos;
	InitInfo init_info;

	OR::EnvironmentBasePtr env;
	BeliefRobotAndDOFPtr rad;

	ProblemConstructionInfo(OR::EnvironmentBasePtr _env) : env(_env) {}
	void fromJson(const Value& v);

};

/**
 \brief pose error

 See trajopt::PoseCntInfo
 */
struct PoseCostInfo : public CostInfo {
	int timestep;
	Vector3d xyz;
	Vector4d wxyz;
	Vector3d pos_coeffs, rot_coeffs;
	double coeff;
	KinBody::LinkPtr link;
	void fromJson(const Value& v);
	void hatch(TrajOptProb& prob);
	static CostInfoPtr create();
};

/**
  \brief Joint space position cost

  \f{align*}{
  \sum_i c_i (x_i - xtarg_i)^2
  \f}
  where \f$i\f$ indexes over dof and \f$c_i\f$ are coeffs
 */
struct JointPosCostInfo : public CostInfo {
	DblVec vals, coeffs;
	int timestep;
	void fromJson(const Value& v);
	void hatch(TrajOptProb& prob);
	static CostInfoPtr create();
};

/**
  \brief Pose constraint

  let \f$T_{err} = T_{targ}^{-1} * T_{cur}\f$.
  Let xerr  be the  translation of \f$T_{err}\f$
  and roterr be the rotation part of the quaternion.
  Then the error vector is [xerr, roterr], scaled by
  pos_coeffs and rot_coeffs, respectively
 */
struct PoseCntInfo : public CntInfo {
	int timestep;
	Vector3d xyz;
	Vector4d wxyz;
	Vector3d pos_coeffs, rot_coeffs;
	double coeff;
	KinBody::LinkPtr link;
	void fromJson(const Value& v);
	void hatch(TrajOptProb& prob);
	static CntInfoPtr create();
};

/**
 \brief Motion constraint on link

 Constrains the change in position of the link in each timestep to be less than distance_limit
 */
struct CartVelCntInfo : public CntInfo {
	int first_step, last_step;
	KinBody::LinkPtr link;
	double distance_limit;
	void fromJson(const Value& v);
	void hatch(TrajOptProb& prob);
	static CntInfoPtr create();
};

/**
\brief Joint-space velocity squared

\f{align*}{
  cost = \sum_{t=0}^{T-2} \sum_j c_j (x_{t+1,j} - x_{t,j})^2
\f}
where j indexes over DOF, and \f$c_j\f$ are the coeffs.
 */
struct JointVelCostInfo : public CostInfo {
	DblVec coeffs;
	void fromJson(const Value& v);
	void hatch(TrajOptProb& prob);
	static CostInfoPtr create();
};
/**
\brief %Collision penalty

\f{align*}{
  cost = \sum_{t=0}^{T-1} \sum_{A, B} | distpen_t - sd(A,B) |^+
\f}
 */
struct CollisionCostInfo : public CostInfo {
	/// coeffs.size() = num_timesteps
	DblVec coeffs;
	/// safety margin: contacts with distance < dist_pen are penalized
	DblVec dist_pen;
	/// belief space version with sigma points?
	bool belief_space;
	void fromJson(const Value& v);
	void hatch(TrajOptProb& prob);
	static CostInfoPtr create();
};
/**
\brief continuous-time collision penalty

\f{align*}{
  cost = \sum_{t=firststep}^{laststep} \sum_{A \in robot,B} | distpen_t - sd(hull(A(t), A(t+1)),B) |^+
\f}
 */
struct ContinuousCollisionCostInfo : public CostInfo {
	/// first_step and last_step are inclusive
	int first_step, last_step;
	/// coeffs.size() = last_step - first_step - 1
	DblVec coeffs;
	/// see CollisionCostInfo::dist_pen
	DblVec dist_pen;
	void fromJson(const Value& v);
	void hatch(TrajOptProb& prob);
	static CostInfoPtr create();
};
/**
\brief %Collision constraint
*/
struct CollisionCntInfo : public CntInfo {
	/// coeffs.size() = num_timesteps
	DblVec coeffs;
	/// safety margin: contacts with distance < dist_pen are penalized
	DblVec dist_pen;
	/// belief space version with sigma points?
	bool belief_space;
	void fromJson(const Value& v);
	void hatch(TrajOptProb& prob);
	static CntInfoPtr create();
};
/**
\brief continuous-time collision constraint
 */
struct ContinuousCollisionCntInfo : public CntInfo {
	/// first_step and last_step are inclusive
	int first_step, last_step;
	/// coeffs.size() = last_step - first_step - 1
	DblVec coeffs;
	/// see CollisionCostInfo::dist_pen
	DblVec dist_pen;
	void fromJson(const Value& v);
	void hatch(TrajOptProb& prob);
	static CntInfoPtr create();
};
/**
joint-space position constraint
 */
struct JointConstraintInfo : public CntInfo {
	/// joint values. list of length 1 automatically gets expanded to list of length n_dof
	DblVec vals;
	/// which timestep. default = n_timesteps - 1
	int timestep;
	void fromJson(const Value& v);
	void hatch(TrajOptProb& prob);
	static CntInfoPtr create();
};

struct ControlCostInfo : public CostInfo {
	bool belief_space;
	DblVec coeffs;
	void fromJson(const Value& v);
	void hatch(TrajOptProb& prob);
	static CostInfoPtr create();
};
struct ControlCntInfo : public CntInfo {
	bool belief_space;
	double u_min;
	double u_max;
	void fromJson(const Value& v);
	void hatch(TrajOptProb& prob);
	static CntInfoPtr create();
};
/**
\brief trace of covariance

\f{align*}{
  cost = \sum_{t=0}^{T-1} \Tr(Q \Sigma)
\f}
where Q and \Sigma are DOF by DOF matrices.
 */
struct CovarianceCostInfo : public CostInfo {
	bool belief_space;
	Eigen::MatrixXd Q;
	void fromJson(const Value& v);
	void hatch(TrajOptProb& prob);
	static CostInfoPtr create();
};

}

max_stars_repo_name: alexlee-gk/trajopt

max_issues_repo_name: alexlee-gk/trajopt

max_forks_repo_name: alexlee-gk/trajopt


text:
#include <iostream>
#include <boost/test/included/unit_test.hpp>
#include <macgyver/StringConversion.h>
#include <macgyver/TypeName.h>
#include "DataSetIndex.h"

using namespace boost::unit_test;

test_suite* init_unit_test_suite(int argc, char* argv[])
{
  const char* name = "DataSetIndex tester";
  unit_test_log.set_threshold_level(log_messages);
  framework::master_test_suite().p_name.value = name;
  BOOST_TEST_MESSAGE("");
  BOOST_TEST_MESSAGE(name);
  BOOST_TEST_MESSAGE(std::string(std::strlen(name), '='));
  return NULL;
}

namespace
{

const std::string test_dir = "/home/pavenis/smartmet/plugins/smartmet-plugin-wfs";

boost::shared_ptr<libconfig::Config> create_config()
{
  using libconfig::Setting;
  boost::shared_ptr<libconfig::Config> config(new libconfig::Config);
  auto& root = config->getRoot();
  root.add("name", Setting::TypeString) = "Test1";
  root.add("dir", Setting::TypeString) = test_dir;
  root.add("file_regex", Setting::TypeString) = ".*";
  root.add("origin_time_extract", Setting::TypeString) = "^\\d{12}_";
  auto& transl = root.add("origin_time_translate", Setting::TypeArray);
  transl.add(Setting::TypeString) = "^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})_";
  transl.add(Setting::TypeString) = "\\1-\\2-\\3T\\4:\\5Z";
  auto& levels = root.add("levels", Setting::TypeArray);
  levels.add(Setting::TypeInt) = 1;
  levels.add(Setting::TypeInt) = 5;
  levels.add(Setting::TypeInt) = 151;
  levels.add(Setting::TypeInt) = 167;
  auto& bbox = root.add("bbox", Setting::TypeArray);
  bbox.add(Setting::TypeFloat) = 22.0;
  bbox.add(Setting::TypeFloat) = 60.0;
  bbox.add(Setting::TypeFloat) = 24.0;
  bbox.add(Setting::TypeFloat) = 62.0;
  auto& params = root.add("params", Setting::TypeArray);
  params.add(Setting::TypeString) = "TemperatUre";
  params.add(Setting::TypeString) = "SnowDepth";
  params.add(Setting::TypeString) = "Pressure";
  return config;
}
}

using SmartMet::Spine::ConfigBase;
using SmartMet::Plugin::WFS::DataSetDefinition;
namespace bg = boost::gregorian;
namespace pt = boost::posix_time;
using namespace boost::filesystem;
using boost::date_time::neg_infin;
using boost::date_time::pos_infin;

BOOST_AUTO_TEST_CASE(test_parse_config)
{
  BOOST_TEST_MESSAGE("+ [Testing parsing DataSetDefinition from libconfig::Setting]");
  auto raw_config = create_config();
  ConfigBase config(raw_config, "Test");
  try
  {
    auto ds_def = DataSetDefinition::create(config, raw_config->getRoot());
    BOOST_CHECK_EQUAL(std::string("Test1"), ds_def->get_name());
    BOOST_CHECK_EQUAL(std::string(test_dir), ds_def->get_dir().string());
  }
  catch (const std::exception& err)
  {
    std::cerr << "\nC++ exception of type '" << Fmi::current_exception_type() << "': " << err.what()
              << std::endl;
    BOOST_REQUIRE(false);
  }
}

BOOST_AUTO_TEST_CASE(test_time_extract)
{
  BOOST_TEST_MESSAGE("+ [Testing time extraction from file name]");
  auto raw_config = create_config();
  ConfigBase config(raw_config, "Test");
  auto ds_def = DataSetDefinition::create(config, raw_config->getRoot());
  try
  {
    pt::ptime t;
    t = ds_def->extract_origintime(path("foo/201209151234_pal_scandinavia_pinta_sqd"));
    BOOST_CHECK_EQUAL(std::string("2012-09-15T12:34:00"), Fmi::to_iso_extended_string(t));
  }
  catch (const std::exception& err)
  {
    std::cerr << "\nC++ exception of type '" << Fmi::current_exception_type() << "': " << err.what()
              << std::endl;
    BOOST_CHECK(false);
  }
}

namespace
{
inline DataSetDefinition::box_t mkbox(double x1, double y1, double x2, double y2)
{
  typedef DataSetDefinition::point_t point_t;
  return DataSetDefinition::box_t(point_t(x1, y1), point_t(x2, y2));
}
}

BOOST_AUTO_TEST_CASE(test_query_files)
{
  BOOST_TEST_MESSAGE("+ [Testing quering files by time interval]");
  auto raw_config = create_config();
  ConfigBase config(raw_config, "Test");
  auto ds_def = DataSetDefinition::create(config, raw_config->getRoot());
  std::vector<path> files;

  try
  {
    files = ds_def->query_files();
    BOOST_CHECK_EQUAL(2, (int)files.size());
  }
  catch (const std::exception& err)
  {
    std::cerr << "\nC++ exception of type '" << Fmi::current_exception_type() << "': " << err.what()
              << std::endl;
    BOOST_CHECK(false);
  }

  try
  {
    files = ds_def->query_files(pt::ptime(bg::date(2008, 8, 5), pt::time_duration(8, 0, 0, 0)));
    BOOST_CHECK_EQUAL(1, (int)files.size());
    BOOST_CHECK_EQUAL(std::string("200808050933_pal_skandinavia_pinta.sqd"),
                      files.at(0).filename().string());
  }
  catch (const std::exception& err)
  {
    std::cerr << "\nC++ exception of type '" << Fmi::current_exception_type() << "': " << err.what()
              << std::endl;
    BOOST_CHECK(false);
  }
}

BOOST_AUTO_TEST_CASE(test_bbox_intersection)
{
  //typedef DataSetDefinition::point_t point_t;
  typedef DataSetDefinition::box_t box_t;

  BOOST_TEST_MESSAGE("+ [Testing area intersection]");
  auto raw_config = create_config();
  ConfigBase config(raw_config, "Test");
  auto ds_def = DataSetDefinition::create(config, raw_config->getRoot());

  const box_t& bbox = ds_def->get_bbox();
  BOOST_CHECK_EQUAL(22.0, bbox.min_corner().x());
  BOOST_CHECK_EQUAL(60.0, bbox.min_corner().y());
  BOOST_CHECK_EQUAL(24.0, bbox.max_corner().x());
  BOOST_CHECK_EQUAL(62.0, bbox.max_corner().y());

  BOOST_CHECK(ds_def->intersects(mkbox(22.5, 60.5, 22.6, 60.6)));
  BOOST_CHECK(not ds_def->intersects(mkbox(19.0, 60.5, 19.2, 60.6)));
  BOOST_CHECK(ds_def->intersects(mkbox(19.0, 57.0, 22.5, 60.5)));
}

max_stars_repo_name: nakkim/smartmet-plugin-wfs

max_issues_repo_name: nakkim/smartmet-plugin-wfs

max_forks_repo_name: nakkim/smartmet-plugin-wfs


text:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

    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)
==============================================================================*/
#if !defined(FUSION_REPLACE_IF_08182005_0939)
#define FUSION_REPLACE_IF_08182005_0939

#include <boost/fusion/view/transform_view/transform_view.hpp>
#include <boost/fusion/algorithm/transformation/detail/replace_if.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_same.hpp>

namespace boost { namespace fusion
{
    namespace result_of
    {
        template <typename Sequence, typename F, typename T>
        struct replace_if
        {
            typedef transform_view<Sequence, detail::replacer_if<F, T> > type;
        };
    }

    template <typename Sequence, typename F, typename T>
    inline typename result_of::replace_if<Sequence const, F, T>::type
    replace_if(Sequence const& seq, F pred, T const& new_value)
    {
        typedef typename result_of::replace_if<Sequence const, F, T>::type result;
        detail::replacer_if<F, T> f(pred, new_value);
        return result(seq, f);
    }
}}

#endif