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

#include <mayaUsd/fileio/primWriter.h>
#include <mayaUsd/fileio/primWriterRegistry.h>
#include <mayaUsd/fileio/registryHelper.h>
#include <mayaUsd/fileio/shaderWriter.h>
#include <mayaUsd/fileio/shaderWriterRegistry.h>
#include <mayaUsd/fileio/shading/symmetricShaderWriter.h>

#include <pxr/base/tf/pyEnum.h>
#include <pxr/base/tf/pyPolymorphic.h>

#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/make_constructor.hpp>
#include <boost/python/return_internal_reference.hpp>
#include <boost/python/wrapper.hpp>

PXR_NAMESPACE_USING_DIRECTIVE

//----------------------------------------------------------------------------------------------------------------------
/// \brief  boost python binding for the UsdMayaPrimWriter
//----------------------------------------------------------------------------------------------------------------------
template <typename T = UsdMayaPrimWriter>
class PrimWriterWrapper
    : public T
    , public TfPyPolymorphic<UsdMayaPrimWriter>
{
public:
    typedef PrimWriterWrapper This;
    typedef T                 base_t;

    PrimWriterWrapper(
        const MFnDependencyNode& depNodeFn,
        const SdfPath&           usdPath,
        UsdMayaWriteJobContext&  jobCtx)
        : T(depNodeFn, usdPath, jobCtx)
    {
    }

    static std::shared_ptr<This> New(uintptr_t createdWrapper)
    {
        return *((std::shared_ptr<This>*)createdWrapper);
    }

    virtual ~PrimWriterWrapper() = default;

    const UsdStage& GetUsdStage() const { return *get_pointer(base_t::GetUsdStage()); }

    // This is the pattern inspired from USD/pxr/base/tf/wrapTestTfPython.cpp
    // It would have been simpler to call 'this->CallVirtual<>("Write",
    // &base_t::default_Write)(usdTime);' But it is not allowed Instead of having to create a
    // function 'default_Write(...)' to call the base class when there is no Python implementation.
    void default_Write(const UsdTimeCode& usdTime) { base_t::Write(usdTime); }
    void Write(const UsdTimeCode& usdTime) override
    {
        this->template CallVirtual<>("Write", &This::default_Write)(usdTime);
    }

    void default_PostExport() { base_t::PostExport(); }
    void PostExport() override
    {
        this->template CallVirtual<>("PostExport", &This::default_PostExport)();
    }

    bool default_ExportsGprims() const { return base_t::ExportsGprims(); }
    bool ExportsGprims() const override
    {
        return this->template CallVirtual<bool>("ExportsGprims", &This::default_ExportsGprims)();
    }

    bool default_ShouldPruneChildren() const { return base_t::ShouldPruneChildren(); };
    bool ShouldPruneChildren() const override
    {
        return this->template CallVirtual<bool>(
            "ShouldPruneChildren", &This::default_ShouldPruneChildren)();
    }

    bool default__HasAnimCurves() const { return base_t::_HasAnimCurves(); };
    bool _HasAnimCurves() const override
    {
        return this->template CallVirtual<bool>("_HasAnimCurves", &This::default__HasAnimCurves)();
    }

    void _SetUsdPrim(const UsdPrim& usdPrim) { base_t::_SetUsdPrim(usdPrim); }

    const UsdMayaJobExportArgs& _GetExportArgs() const { return base_t::_GetExportArgs(); }
    boost::python::object       _GetSparseValueWriter()
    {
        return boost::python::object(base_t::_GetSparseValueWriter());
    }

    const SdfPathVector& default_GetModelPaths() const { return base_t::GetModelPaths(); }
    const SdfPathVector& GetModelPaths() const override
    {
        if (Override o = GetOverride("GetModelPaths")) {
            auto res = std::function<boost::python::object()>(TfPyCall<boost::python::object>(o))();
            if (res) {
                const_cast<SdfPathVector*>(&_modelPaths)->clear();
                TfPyLock pyLock;

                boost::python::list keys(res);
                for (int i = 0; i < len(keys); ++i) {
                    boost::python::extract<SdfPath> extractedKey(keys[i]);
                    if (!extractedKey.check()) {
                        TF_CODING_ERROR(
                            "PrimWriterWrapper.GetModelPaths: SdfPath key expected, not "
                            "found!");
                        return _modelPaths;
                    }

                    SdfPath path = extractedKey;
                    const_cast<SdfPathVector*>(&_modelPaths)->push_back(path);
                }
                return _modelPaths;
            }
        }
        return This::default_GetModelPaths();
    }

    const UsdMayaUtil::MDagPathMap<SdfPath>& default_GetDagToUsdPathMapping() const
    {
        return base_t::GetDagToUsdPathMapping();
    }
    const UsdMayaUtil::MDagPathMap<SdfPath>& GetDagToUsdPathMapping() const override
    {
        if (Override o = GetOverride("GetDagToUsdPathMapping")) {
            auto res = std::function<boost::python::object()>(TfPyCall<boost::python::object>(o))();
            if (res) {
                const_cast<UsdMayaUtil::MDagPathMap<SdfPath>*>(&_dagPathMap)->clear();
                TfPyLock pyLock;

                boost::python::list tuples(res);
                for (int i = 0; i < len(tuples); ++i) {
                    boost::python::tuple t(tuples[i]);
                    if (boost::python::len(t) != 2) {
                        TF_CODING_ERROR("PrimWriterWrapper.GetDagToUsdPathMapping: list<tuples> "
                                        "key expected, not "
                                        "found!");
                        return _dagPathMap;
                    }
                    boost::python::extract<MDagPath> extractedDagPath(t[0]);
                    if (!extractedDagPath.check()) {
                        TF_CODING_ERROR(
                            "PrimWriterWrapper.GetDagToUsdPathMapping: MDagPath key expected, not "
                            "found!");
                        return _dagPathMap;
                    }
                    boost::python::extract<SdfPath> extractedSdfPath(t[1]);
                    if (!extractedSdfPath.check()) {
                        TF_CODING_ERROR(
                            "PrimWriterWrapper.GetDagToUsdPathMapping: SdfPath key expected, not "
                            "found!");
                        return _dagPathMap;
                    }

                    MDagPath dagPath = extractedDagPath;
                    SdfPath  path = extractedSdfPath;
                    const_cast<UsdMayaUtil::MDagPathMap<SdfPath>*>(&_dagPathMap)
                        ->
                        operator[](dagPath)
                        = path;
                }
                return _dagPathMap;
            }
        }
        return This::default_GetDagToUsdPathMapping();
    }

    static void Register(boost::python::object cl, const std::string& mayaTypeName)
    {
        UsdMayaPrimWriterRegistry::Register(
            mayaTypeName,
            [=](const MFnDependencyNode& depNodeFn,
                const SdfPath&           usdPath,
                UsdMayaWriteJobContext&  jobCtx) {
                auto                  sptr = std::make_shared<This>(depNodeFn, usdPath, jobCtx);
                TfPyLock              pyLock;
                boost::python::object instance = cl((uintptr_t)&sptr);
                boost::python::incref(instance.ptr());
                initialize_wrapper(instance.ptr(), sptr.get());
                return sptr;
            },
            true);
    }

private:
    SdfPathVector                     _modelPaths;
    UsdMayaUtil::MDagPathMap<SdfPath> _dagPathMap;
};

//----------------------------------------------------------------------------------------------------------------------
/// \brief  boost python binding for the UsdMayaShaderWriter
//----------------------------------------------------------------------------------------------------------------------
class ShaderWriterWrapper : public PrimWriterWrapper<UsdMayaShaderWriter>
{
public:
    typedef ShaderWriterWrapper This;
    typedef UsdMayaShaderWriter base_t;

    ShaderWriterWrapper(
        const MFnDependencyNode& depNodeFn,
        const SdfPath&           usdPath,
        UsdMayaWriteJobContext&  jobCtx)
        : PrimWriterWrapper<UsdMayaShaderWriter>(depNodeFn, usdPath, jobCtx)
    {
    }

    static std::shared_ptr<This> New(uintptr_t createdWrapper)
    {
        return *((std::shared_ptr<This>*)createdWrapper);
    }

    virtual ~ShaderWriterWrapper() { }

    TfToken default_GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName)
    {
        return base_t::GetShadingAttributeNameForMayaAttrName(mayaAttrName);
    }
    TfToken GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName) override
    {
        return this->CallVirtual<TfToken>(
            "GetShadingAttributeNameForMayaAttrName",
            &This::default_GetShadingAttributeNameForMayaAttrName)(mayaAttrName);
    }

    UsdAttribute default_GetShadingAttributeForMayaAttrName(
        const TfToken&          mayaAttrName,
        const SdfValueTypeName& typeName)
    {
        return base_t::GetShadingAttributeForMayaAttrName(mayaAttrName, typeName);
    }
    UsdAttribute GetShadingAttributeForMayaAttrName(
        const TfToken&          mayaAttrName,
        const SdfValueTypeName& typeName) override
    {
        return this->CallVirtual<UsdAttribute>(
            "GetShadingAttributeForMayaAttrName",
            &This::default_GetShadingAttributeForMayaAttrName)(mayaAttrName, typeName);
    }

    static void Register(boost::python::object cl, const TfToken& mayaNodeTypeName)
    {
        UsdMayaShaderWriterRegistry::Register(
            mayaNodeTypeName,
            [=](const UsdMayaJobExportArgs& exportArgs) {
                TfPyLock              pyLock;
                boost::python::object CanExport = cl.attr("CanExport");
                PyObject*             callable = CanExport.ptr();
                auto                  res = boost::python::call<int>(callable, exportArgs);
                return UsdMayaShaderWriter::ContextSupport(res);
            },
            [=](const MFnDependencyNode& depNodeFn,
                const SdfPath&           usdPath,
                UsdMayaWriteJobContext&  jobCtx) {
                auto                  sptr = std::make_shared<This>(depNodeFn, usdPath, jobCtx);
                TfPyLock              pyLock;
                boost::python::object instance = cl((uintptr_t)&sptr);
                boost::python::incref(instance.ptr());
                initialize_wrapper(instance.ptr(), sptr.get());
                return sptr;
            },
            true);
    }

    static void RegisterSymmetric(
        boost::python::object cl,
        const TfToken&        mayaNodeTypeName,
        const TfToken&        usdShaderId,
        const TfToken&        materialConversionName)
    {
        UsdMayaSymmetricShaderWriter::RegisterWriter(
            mayaNodeTypeName, usdShaderId, materialConversionName, true);
    }
};

namespace {
std::vector<std::string> getChaserNames(UsdMayaJobExportArgs& self) { return self.chaserNames; }

boost::python::object getChaserArgs(UsdMayaJobExportArgs& self, const std::string& chaser)
{
    boost::python::dict editDict;

    std::map<std::string, std::string> myArgs;
    TfMapLookup(self.allChaserArgs, chaser, &myArgs);

    for (const auto& item : myArgs) {
        editDict[item.first] = item.second;
    }
    return boost::python::object(editDict);
}
} // namespace
//----------------------------------------------------------------------------------------------------------------------
void wrapJobExportArgs()
{
    boost::python::class_<UsdMayaJobExportArgs>("JobExportArgs", boost::python::no_init)
        .def("getChaserNames", &::getChaserNames)
        .def("getChaserArgs", &::getChaserArgs)
        .def("GetResolvedFileName", &UsdMayaJobExportArgs::GetResolvedFileName);
}

void wrapPrimWriter()
{
    boost::python::class_<PrimWriterWrapper<>, boost::noncopyable>(
        "PrimWriter", boost::python::no_init)
        .def("__init__", make_constructor(&PrimWriterWrapper<>::New))
        .def(
            "PostExport",
            &PrimWriterWrapper<>::PostExport,
            &PrimWriterWrapper<>::default_PostExport)
        .def("Write", &PrimWriterWrapper<>::Write, &PrimWriterWrapper<>::default_Write)

        .def("GetExportVisibility", &PrimWriterWrapper<>::GetExportVisibility)
        .def("SetExportVisibility", &PrimWriterWrapper<>::SetExportVisibility)
        .def(
            "GetMayaObject",
            &PrimWriterWrapper<>::GetMayaObject,
            boost::python::return_value_policy<boost::python::return_by_value>())
        .def(
            "GetUsdPrim",
            &PrimWriterWrapper<>::GetUsdPrim,
            boost::python::return_internal_reference<>())
        .def("_SetUsdPrim", &PrimWriterWrapper<>::_SetUsdPrim)
        .def(
            "MakeSingleSamplesStatic",
            static_cast<void (PrimWriterWrapper<>::*)()>(
                &PrimWriterWrapper<>::MakeSingleSamplesStatic))
        .def(
            "MakeSingleSamplesStatic",
            static_cast<void (PrimWriterWrapper<>::*)(UsdAttribute attr)>(
                &PrimWriterWrapper<>::MakeSingleSamplesStatic))

        .def(
            "_HasAnimCurves",
            &PrimWriterWrapper<>::_HasAnimCurves,
            &PrimWriterWrapper<>::default__HasAnimCurves)
        .def(
            "_GetExportArgs",
            &PrimWriterWrapper<>::_GetExportArgs,
            boost::python::return_internal_reference<>())
        .def("_GetSparseValueWriter", &PrimWriterWrapper<>::_GetSparseValueWriter)

        .def(
            "GetDagPath",
            &PrimWriterWrapper<>::GetDagPath,
            boost::python::return_value_policy<boost::python::return_by_value>())
        .def(
            "GetUsdStage",
            &UsdMayaPrimWriter::GetUsdStage,
            boost::python::return_value_policy<boost::python::return_by_value>())
        .def(
            "GetUsdPath",
            &UsdMayaPrimWriter::GetUsdPath,
            boost::python::return_value_policy<boost::python::return_by_value>())

        .def("Register", &PrimWriterWrapper<>::Register)
        .staticmethod("Register");
}

TF_REGISTRY_FUNCTION(TfEnum)
{
    TF_ADD_ENUM_NAME(UsdMayaShaderWriter::ContextSupport::Supported, "Supported");
    TF_ADD_ENUM_NAME(UsdMayaShaderWriter::ContextSupport::Fallback, "Fallback");
    TF_ADD_ENUM_NAME(UsdMayaShaderWriter::ContextSupport::Unsupported, "Unsupported");
}

//----------------------------------------------------------------------------------------------------------------------
void wrapShaderWriter()
{
    boost::python::
        class_<ShaderWriterWrapper, boost::python::bases<PrimWriterWrapper<>>, boost::noncopyable>
            c("ShaderWriter", boost::python::no_init);

    boost::python::scope s(c);

    TfPyWrapEnum<UsdMayaShaderWriter::ContextSupport>();

    c.def("__init__", make_constructor(&ShaderWriterWrapper::New))
        .def(
            "GetShadingAttributeNameForMayaAttrName",
            &ShaderWriterWrapper::GetShadingAttributeNameForMayaAttrName,
            &ShaderWriterWrapper::default_GetShadingAttributeNameForMayaAttrName)
        .def(
            "GetShadingAttributeForMayaAttrName",
            &ShaderWriterWrapper::GetShadingAttributeForMayaAttrName,
            &ShaderWriterWrapper::default_GetShadingAttributeForMayaAttrName)

        .def("Register", &ShaderWriterWrapper::Register)
        .staticmethod("Register")
        .def("RegisterSymmetric", &ShaderWriterWrapper::RegisterSymmetric)
        .staticmethod("RegisterSymmetric");
}

max_stars_repo_name: dgovil/maya-usd

max_issues_repo_name: dgovil/maya-usd

max_forks_repo_name: dgovil/maya-usd


text:
//
//  Configuration.cpp
//  Helios
//
//  Created by James Hurley on 1/25/13.
//  Copyright (c) 2013 James Hurley. All rights reserved.
//

#include <World/Configuration.h>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include <iostream>

namespace helios
{
    Configuration::Configuration(const std::string file)
    {
        boost::property_tree::ptree pt;

        try
        {
            boost::property_tree::read_json(file, pt);
        }
        catch(boost::property_tree::json_parser::json_parser_error &je)
        {
            std::cout << "Error parsing: " << je.filename() << " on line: " << je.line() << std::endl;
            std::cout << je.message() << std::endl;
        }

        BOOST_FOREACH(const boost::property_tree::ptree::value_type &v, pt.get_child("keybinding"))
        {

            short key = v.second.get_value<int>() ;
            std::string value = v.first.data() ;

            std::cout << "Found (" << v.first.data() << "," << v.second.get_value<int>() << ")" << std::endl ;

            mKeybindings[key] = value ;

        }
    }
    Configuration::~Configuration()
    {

    }
}

ext: cpp


text:
#include <boost/range/adaptor/indexed.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/assign.hpp>
#include <algorithm>
#include <iostream>
#include <vector>

template<typename Iterator>
void display_element_and_index(Iterator first, Iterator last)
{
    for (Iterator it = first; it != last; ++it)
    {
        std::cout << "Element = " << *it
                  << " Index = " << it.index() << std::endl;
    }
}

template<typename SinglePassRange>
void display_element_and_index(const SinglePassRange& rng)
{
    display_element_and_index(boost::begin(rng), boost::end(rng));
}

int main(int argc, const char* argv[])
{
    using namespace boost::assign;
    using namespace boost::adaptors;

    std::vector<int> input;
    input += 10,20,30,40,50,60,70,80,90;

    display_element_and_index( input | indexed(0) );

    return 0;
]

max_stars_repo_name: zyiacas/boost-doc-zh

max_issues_repo_name: sdfict/boost-doc-zh

max_forks_repo_name: sdfict/boost-doc-zh


text:
extern "C"  {
        #include "postgres.h"
        #include "catalog/pg_type.h"
        #include "fmgr.h"
}
#include "random.h"
#include "../array.h"

#include <boost/random.hpp>

template<class D> static Datum _gen_rand(PG_FUNCTION_ARGS, D& dist, int dim_arr_idx = 0) {
  typedef typename D::result_type T;
  ArrayType* arr = PG_GETARG_ARRAYTYPE_P_COPY(dim_arr_idx);

  if (ARR_NDIM(arr) == 0 ) {
     PG_RETURN_POINTER(construct_empty_array(oid_type<double>()));
  } else if (ARR_NDIM(arr) != 1 ) {
     elog(ERROR, "GEN_RAND: Size specification can only be 1-dimension array");
     PG_RETURN_NULL();
  } else if (ARR_DIMS(arr)[0] >= 4 ) {
     elog(ERROR, "GEN_RAND: Maximum of 4 dimensions in array generation.");
     PG_RETURN_NULL();
  }

  //compute number of dimensions
  ArrDims rd = extract_shape(arr);
  Datum* r = (Datum*)palloc(rd.n * sizeof(Datum));
  for (size_t i = 0; i < rd.n; ++i ) {
     r[i] = _ret<T>(dist(rgen));
  }

  ArrayType* res = construct_md_array(r,
                                      NULL,
                                      rd.ndims,
                                      rd.dims,
                                      rd.lbs,
                                      oid_type<T>(),
                                      sizeof(T),
                                      true,
                                      oid_align<T>());
  PG_RETURN_POINTER(res);
}

#define RAND_FUNCTION(NAME) \
	extern "C" { PG_FUNCTION_INFO_V1(NAME); Datum NAME(PG_FUNCTION_ARGS); } \
        Datum NAME(PG_FUNCTION_ARGS)

RAND_FUNCTION(gen_rand) {
  std::uniform_real_distribution<double> dist{0.0, 1.0};
  return _gen_rand(fcinfo, dist);
}

RAND_FUNCTION(gen_randn) {
  //for soem reason can't determine "std' variant is producing warnings.
  std::normal_distribution<double> dist{0.0, 1.0};
  return _gen_rand(fcinfo, dist);
}

RAND_FUNCTION(gen_randint) {
  long low = get_param<long>(fcinfo, 0);
  long high = get_param<long>(fcinfo, 1);
  if (high <= low ){
     elog(ERROR, "GEN_RANDINT: Cannot have high bound lower then low bound");
     PG_RETURN_NULL();
  } else {
     std::uniform_int_distribution<> dist(low, high);
     return _gen_rand(fcinfo, dist, 2);
  }
}

RAND_FUNCTION(gen_beta) {
  float alpha = get_param<double>(fcinfo, 0);
  float beta  = get_param<double>(fcinfo, 1);
  if (alpha < 0 || beta < 0){
     elog(ERROR, "BETA: Can't have negative alpha/beta parameters");
     PG_RETURN_NULL();
  } else {
     boost::random::beta_distribution<double> dist(alpha, beta);
     return _gen_rand(fcinfo, dist, 2);
  }
}

RAND_FUNCTION(gen_binomial) {
  int t = get_param<int>(fcinfo, 0);
  float p  = get_param<double>(fcinfo, 1);
  if (t < 0 || p < 0 || p > 1){
     elog(ERROR, "BINOMIAL: Input parameters outside of range");
     PG_RETURN_NULL();
  } else {
     boost::random::binomial_distribution<int> dist(t,p);
     return _gen_rand(fcinfo, dist, 2);
  }
}

max_stars_repo_name: tarkmeper/numpgsql

max_issues_repo_name: tarkmeper/numpgsql

max_forks_repo_name: tarkmeper/numpgsql


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_PREDICATES_FUNCTIONS_SIMD_SSE_SSE2_IS_EQZ_HPP_INCLUDED
#define BOOST_SIMD_PREDICATES_FUNCTIONS_SIMD_SSE_SSE2_IS_EQZ_HPP_INCLUDED
#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT
#include <boost/simd/predicates/functions/is_eqz.hpp>
#include <boost/simd/include/functions/simd/is_equal.hpp>
#include <boost/simd/include/constants/zero.hpp>
#include <boost/simd/include/functions/simd/bitwise_and.hpp>
#include <boost/simd/sdk/meta/as_logical.hpp>
#include <boost/simd/swar/functions/details/shuffle.hpp>
#include <boost/dispatch/meta/downgrade.hpp>

namespace boost { namespace simd { namespace ext
{
  BOOST_DISPATCH_IMPLEMENT          ( is_eqz_
                                    , boost::simd::tag::sse2_
                                    , (A0)
                                    , ((simd_ < int64_<A0>
                                              , boost::simd::tag::sse_
                                              >
                                      ))
                                    )
  {
    typedef typename meta::as_logical<A0>::type result_type;

    BOOST_SIMD_FUNCTOR_CALL(1)
    {
      typedef typename dispatch::meta::downgrade<A0>::type          base;

      const base tmp1 = boost::simd::bitwise_cast<base>(is_eqz(boost::simd::bitwise_cast<base>(a0)));
      const base tmp2 = details::shuffle<1,0,3,2>(tmp1);
      return boost::simd::bitwise_cast<result_type>(b_and(tmp1, tmp2));
    }
  };
} } }

#endif
#endif

ext: hpp


text:
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.

/* value_description.cc                                            -*- C++ -*-
   Jeremy Barnes, 29 March 2013
   Copyright (c) 2013 mldb.ai inc.  All rights reserved.

   Code for description and introspection of values and structures.  Used
   to allow for automated formatters and parsers to be built.
*/

#include <mutex>
#include "mldb/base/exc_assert.h"
#include "value_description.h"
#include "structure_description.h"
#include <boost/lexical_cast.hpp>

using namespace std;

namespace MLDB {

std::ostream & operator << (std::ostream & stream, ValueKind kind)
{
    switch (kind) {
    case ValueKind::ATOM: return stream << "ATOM";
    case ValueKind::INTEGER: return stream << "INTEGER";
    case ValueKind::FLOAT: return stream << "FLOAT";
    case ValueKind::BOOLEAN: return stream << "BOOLEAN";
    case ValueKind::STRING: return stream << "STRING";
    case ValueKind::ENUM: return stream << "ENUM";
    case ValueKind::OPTIONAL: return stream << "OPTIONAL";
    case ValueKind::ARRAY: return stream << "ARRAY";
    case ValueKind::STRUCTURE: return stream << "STRUCTURE";
    case ValueKind::TUPLE: return stream << "TUPLE";
    case ValueKind::VARIANT: return stream << "VARIANT";
    case ValueKind::MAP: return stream << "MAP";
    case ValueKind::ANY: return stream << "ANY";
    default:
        return stream << "ValueKind(" << std::to_string((int)kind) << ")";
    }
}

/*****************************************************************************/
/* VALUE DESCRIPTION                                                         */
/*****************************************************************************/

ValueDescription::
ValueDescription(ValueKind kind,
                 const std::type_info * type,
                 const std::string & typeName)
    : kind(kind),
      type(type),
      typeName(typeName.empty() ? demangle(type->name()) : typeName),
      jsConverters(nullptr),
      jsConvertersInitialized(false)
{
}

ValueDescription::
~ValueDescription()
{
}

void
ValueDescription::
setTypeName(const std::string & newName)
{
    this->typeName = newName;
}

Json::Value
ValueDescription::
printJsonStructured(const void * val) const
{
    Json::Value result;
    StructuredJsonPrintingContext context(result);
    printJson(val, context);
    return result;
}

Utf8String
ValueDescription::
printJsonString(const void * val) const
{
    Utf8String result;
    Utf8StringJsonPrintingContext context(result);
    printJson(val, context);
    return result;
}

void *
ValueDescription::
optionalMakeValue(void * val) const
{
    throw MLDB::Exception("type is not optional");
}

const void *
ValueDescription::
optionalGetValue(const void * val) const
{
    throw MLDB::Exception("type is not optional");
}

size_t
ValueDescription::
getArrayLength(void * val) const
{
    throw MLDB::Exception("type is not an array");
}

void *
ValueDescription::
getArrayElement(void * val, uint32_t element) const
{
    throw MLDB::Exception("type is not an array");
}

std::vector<std::shared_ptr<const ValueDescription> >
ValueDescription::
getTupleElementDescriptions() const
{
    throw MLDB::Exception("type '" + typeName + "' is not a tuple " + MLDB::type_name(*this));
}

size_t
ValueDescription::
getTupleLength() const
{
    throw MLDB::Exception("type '" + typeName + "' is not a tuple " + MLDB::type_name(*this));
}

const void *
ValueDescription::
getArrayElement(const void * val, uint32_t element) const
{
    throw MLDB::Exception("type is not an array");
}

/** Return the value description for the nth array element.  This is
    necessary for tuple types, which don't have the same type for each
    element.
*/
const ValueDescription &
ValueDescription::
getArrayElementDescription(const void * val, uint32_t element) const
{
    return contained();
}

void
ValueDescription::
setArrayLength(void * val, size_t newLength) const
{
    throw MLDB::Exception("type is not an array");
}

const ValueDescription &
ValueDescription::
getKeyValueDescription() const
{
    throw MLDB::Exception("type '" + typeName + "' has no key");
}

const ValueDescription &
ValueDescription::
contained() const
{
    throw MLDB::Exception("type '" + typeName + "' does not contain another");
}

std::shared_ptr<const ValueDescription>
ValueDescription::
containedPtr() const
{
    throw MLDB::Exception("type '" + typeName + "' does not contain another");
}

OwnershipModel
ValueDescription::
getOwnershipModel() const
{
    throw MLDB::Exception("type '" + typeName + "' does not define an ownership type");
}

void*
ValueDescription::
getLink(void* obj) const
{
    throw MLDB::Exception("type '" + typeName + "' is not a link");
}

void
ValueDescription::
set(void* obj, void* value, const ValueDescription* valueDesc) const
{
    throw MLDB::Exception("type '" + typeName + "' can't be written to");
}

size_t
ValueDescription::
getFieldCount(const void * val) const
{
    throw MLDB::Exception("type '" + typeName + "' doesn't support fields");
}

const ValueDescription::FieldDescription *
ValueDescription::
hasField(const void * val, const std::string & name) const
{
    throw MLDB::Exception("type '" + typeName + "' doesn't support fields");
}

const ValueDescription::FieldDescription *
ValueDescription::
getFieldDescription(const void * val, const void * field) const
{
    throw MLDB::Exception("type '" + typeName + "' doesn't support fields");
}

void
ValueDescription::
forEachField(const void * val,
             const std::function<void (const FieldDescription &)> & onField) const
{
    throw MLDB::Exception("type '" + typeName + "' doesn't support fields");
}

const ValueDescription::FieldDescription &
ValueDescription::
getField(const std::string & field) const
{
    throw MLDB::Exception("type '" + typeName + "' doesn't support fields");
}

const ValueDescription::FieldDescription &
ValueDescription::
getFieldByNumber(int fieldNum) const
{
    throw MLDB::Exception("type '" + typeName + "' doesn't support fields");
}

const std::vector<std::string>
ValueDescription::
getEnumKeys() const
{
    throw MLDB::Exception("type '" + typeName + "' is not an enum");
}

std::vector<std::tuple<int, std::string, std::string> >
ValueDescription::
getEnumValues() const
{
    throw MLDB::Exception("type '" + typeName + "' is not an enum");
}

int
ValueDescription::
getVersion() const
{
    return -1;
}

bool
ValueDescription::
isSame(const ValueDescription* other) const
{
    return type == other->type;
}

void
ValueDescription::
checkSame(const ValueDescription* other) const
{
    ExcCheck(isSame(other),
             "Wrong object type: "
             "expected <" + typeName + "> got <" + other->typeName + ">");
}

bool
ValueDescription::
isChildOf(const ValueDescription* base) const
{
    if (isSame(base)) return true;

    for (const auto& parent : parents)
        if (parent->isChildOf(base))
            return true;

    return false;
}

void
ValueDescription::
checkChildOf(const ValueDescription* base) const
{
    ExcCheck(isChildOf(base),
             "value of type " + typeName +
             " is not convertible to type " + typeName);
}

void
ValueDescription::
initialize()
{
    // Most values aren't recursive, so don't need an initialize() method.
}

namespace {

std::recursive_mutex registryMutex;
std::unordered_map<std::string, std::shared_ptr<const ValueDescription> > & registry()
{
    static std::unordered_map<std::string, std::shared_ptr<const ValueDescription> > result;
    return result;
}

} // file scope

std::shared_ptr<const ValueDescription>
ValueDescription::
get(std::string const & name)
{
    std::unique_lock<std::recursive_mutex> guard(registryMutex);
    auto i = registry().find(name);
    return registry().end() != i ? i->second : nullptr;
}

std::shared_ptr<const ValueDescription>
ValueDescription::
get(const std::type_info & type)
{
    return get(type.name());
}

void registerValueDescription(const std::type_info & type,
                              std::function<ValueDescription * ()> fn,
                              bool isDefault)
{
    registerValueDescription(type, fn, [] (ValueDescription &) {}, isDefault);
}

void
registerValueDescription(const std::type_info & type,
                         std::function<ValueDescription * ()> createFn,
                         std::function<void (ValueDescription &)> initFn,
                         bool isDefault)
{
    std::unique_lock<std::recursive_mutex> guard(registryMutex);

    std::shared_ptr<ValueDescription> desc(createFn());
    ExcAssert(desc);
    registry()[desc->typeName] = desc;
    registry()[type.name()] = desc;
    registry()[demangle(type.name())] = desc;
    initFn(*desc);
#if 0
    cerr << "type " << demangle(type.name())
         << " has description "
         << MLDB::type_name(*desc) << " default " << isDefault << endl;

    if (registry().count(type.name()))
        throw MLDB::Exception("attempt to double register "
                            + demangle(type.name()));
#endif
}

void
ValueDescription::
convertAndCopy(const void * from,
               const ValueDescription & fromDesc,
               void * to) const
{
    Json::Value val;
    StructuredJsonPrintingContext context(val);
    fromDesc.printJson(from, context);

    StructuredJsonParsingContext context2(val);
    parseJson(to, context2);
}

/*****************************************************************************/
/* STRUCTURE DESCRIPTION BASE                                                */
/*****************************************************************************/

StructureDescriptionBase::
StructureDescriptionBase(const std::type_info * type,
                         ValueDescription * owner,
                         const std::string & structName,
                         bool nullAccepted)
    : type(type),
      structName(structName.empty() ? demangle(type->name()) : structName),
      nullAccepted(nullAccepted),
      owner(owner)
{
}

void
StructureDescriptionBase::
operator = (const StructureDescriptionBase & other)
{
    type = other.type;
    structName = other.structName;
    nullAccepted = other.nullAccepted;

    fieldNames.clear();
    orderedFields.clear();
    fields.clear();
    fieldNames.reserve(other.fields.size());

    // Don't set owner
    for (auto & f: other.orderedFields) {
        const char * s = f->first;
        fieldNames.emplace_back(::strdup(s));
        auto it = fields.insert(make_pair(fieldNames.back().get(), f->second))
            .first;
        orderedFields.push_back(it);
    }
}

void
StructureDescriptionBase::
operator = (StructureDescriptionBase && other)
{
    type = std::move(other.type);
    structName = std::move(other.structName);
    nullAccepted = std::move(other.nullAccepted);
    fields = std::move(other.fields);
    fieldNames = std::move(other.fieldNames);
    orderedFields = std::move(other.orderedFields);
    // don't set owner
}

StructureDescriptionBase::Exception::
Exception(JsonParsingContext & context,
          const std::string & message)
    : MLDB::Exception("at " + context.printPath() + ": " + message)
{
}

StructureDescriptionBase::Exception::
~Exception() throw ()
{
}

void
StructureDescriptionBase::
parseJson(void * output, JsonParsingContext & context) const
{
    try {

        if (!onEntry(output, context)) return;

        if (nullAccepted && context.isNull()) {
            context.expectNull();
            return;
        }

        if (!context.isObject()) {
            std::string typeName;
            if (context.isNumber())
                typeName = "number";
            else if (context.isBool())
                typeName = "boolean";
            else if (context.isString())
                typeName = "string";
            else if (context.isNull())
                typeName = "null";
            else if (context.isArray())
                typeName = "array";
            else typeName = "<<unknown type>>";

            std::string msg
                = "expected object of type "
                + structName + ", but instead a "
                + typeName + " was provided";

            if (context.isString())
                msg += ".  Did you accidentally JSON encode your object into a string?";

            context.exception(msg);
        }

        auto onMember = [&] ()
            {
                try {
                    auto n = context.fieldNamePtr();

                    auto it = fields.find(n);
                    if (it == fields.end()) {
                        context.onUnknownField(owner);
                    }
                    else {
                        it->second.description
                        ->parseJson(addOffset(output,
                                              it->second.offset),
                                    context);
                    }
                }
                catch (const Exception & exc) {
                    throw;
                }
                catch (const std::exception & exc) {
                    throw Exception(context, exc.what());
                }
                catch (...) {
                    throw;
                }
            };

        context.forEachMember(onMember);

        onExit(output, context);
    }
    catch (const Exception & exc) {
        throw;
    }
    catch (const std::exception & exc) {
        throw Exception(context, exc.what());
    }
    catch (...) {
        throw;
    }
}

void
StructureDescriptionBase::
printJson(const void * input, JsonPrintingContext & context) const
{
    context.startObject();

    for (const auto & it: orderedFields) {
        auto & fd = it->second;

        const void * mbr = addOffset(input, fd.offset);
        if (fd.description->isDefault(mbr))
            continue;
        context.startMember(it->first);
        fd.description->printJson(mbr, context);
    }

    context.endObject();
}

/*****************************************************************************/
/* BRIDGED VALUE DESCRIPTION                                                 */
/*****************************************************************************/

BridgedValueDescription::
BridgedValueDescription(std::shared_ptr<const ValueDescription> impl)
    : ValueDescription(impl->kind, impl->type, impl->typeName),
      impl(std::move(impl))
{
    this->documentationUri = this->impl->documentationUri;
}

BridgedValueDescription::
~BridgedValueDescription()
{
}

void
BridgedValueDescription::
parseJson(void * val, JsonParsingContext & context) const
{
    ExcAssert(impl);
    impl->parseJson(val, context);
}

void
BridgedValueDescription::
printJson(const void * val, JsonPrintingContext & context) const
{
    ExcAssert(impl);
    impl->printJson(val, context);
}

bool
BridgedValueDescription::
isDefault(const void * val) const
{
    ExcAssert(impl);
    return impl->isDefault(val);
}

void
BridgedValueDescription::
setDefault(void * val) const
{
    ExcAssert(impl);
    impl->setDefault(val);
}

void
BridgedValueDescription::
copyValue(const void * from, void * to) const
{
    ExcAssert(impl);
    impl->copyValue(from, to);
}

void
BridgedValueDescription::
moveValue(void * from, void * to) const
{
    ExcAssert(impl);
    impl->moveValue(from, to);
}

void
BridgedValueDescription::
swapValues(void * from, void * to) const
{
    ExcAssert(impl);
    swapValues(from, to);
}

void *
BridgedValueDescription::
constructDefault() const
{
    ExcAssert(impl);
    return impl->constructDefault();
}

void *
BridgedValueDescription::
constructCopy(const void * from) const
{
    ExcAssert(impl);
    return impl->constructCopy(from);
}

void *
BridgedValueDescription::
constructMove(void * from) const
{
    ExcAssert(impl);
    return impl->constructMove(from);
}

void
BridgedValueDescription::
destroy(void * val) const
{
    ExcAssert(impl);
    impl->destroy(val);
}

void *
BridgedValueDescription::
optionalMakeValue(void * val) const
{
    ExcAssert(impl);
    return impl->optionalMakeValue(val);
}

const void *
BridgedValueDescription::
optionalGetValue(const void * val) const
{
    ExcAssert(impl);
    return impl->optionalGetValue(val);
}

size_t
BridgedValueDescription::
getArrayLength(void * val) const
{
    ExcAssert(impl);
    return impl->getArrayLength(val);
}

void *
BridgedValueDescription::
getArrayElement(void * val, uint32_t element) const
{
    ExcAssert(impl);
    return impl->getArrayElement(val, element);
}

const void *
BridgedValueDescription::
getArrayElement(const void * val, uint32_t element) const
{
    ExcAssert(impl);
    return impl->getArrayElement(val, element);
}

const ValueDescription &
BridgedValueDescription::
getArrayElementDescription(const void * val, uint32_t element) const
{
    ExcAssert(impl);
    return impl->getArrayElementDescription(val, element);
}

size_t
BridgedValueDescription::
getTupleLength() const
{
    ExcAssert(impl);
    return impl->getTupleLength();
}

std::vector<std::shared_ptr<const ValueDescription> >
BridgedValueDescription::
getTupleElementDescriptions() const
{
    ExcAssert(impl);
    return impl->getTupleElementDescriptions();
}

void
BridgedValueDescription::
setArrayLength(void * val, size_t newLength) const
{
    ExcAssert(impl);
    impl->setArrayLength(val, newLength);
}

const ValueDescription &
BridgedValueDescription::
getKeyValueDescription() const
{
    ExcAssert(impl);
    return impl->getKeyValueDescription();
}

const ValueDescription &
BridgedValueDescription::
contained() const
{
    ExcAssert(impl);
    return impl->contained();
}

OwnershipModel
BridgedValueDescription::
getOwnershipModel() const
{
    ExcAssert(impl);
    return impl->getOwnershipModel();
}

void*
BridgedValueDescription::
getLink(void* obj) const
{
    ExcAssert(impl);
    return impl->getLink(obj);
}

void
BridgedValueDescription::
set(void* obj, void* value, const ValueDescription* valueDesc) const
{
    ExcAssert(impl);
    impl->set(obj, value, valueDesc);
}

void
BridgedValueDescription::
convertAndCopy(const void * from,
               const ValueDescription & fromDesc,
               void * to) const
{
    ExcAssert(impl);
    impl->convertAndCopy(from, fromDesc, to);
}

size_t
BridgedValueDescription::
getFieldCount(const void * val) const
{
    ExcAssert(impl);
    return impl->getFieldCount(val);
}

const ValueDescription::FieldDescription *
BridgedValueDescription::
hasField(const void * val, const std::string & name) const
{
    ExcAssert(impl);
    return impl->hasField(val, name);
}

void
BridgedValueDescription::
forEachField(const void * val,
             const std::function<void (const FieldDescription &)> & onField) const
{
    ExcAssert(impl);
    impl->forEachField(val, onField);
}

const ValueDescription::FieldDescription &
BridgedValueDescription::
getField(const std::string & field) const
{
    ExcAssert(impl);
    return impl->getField(field);
}

const std::vector<std::string>
BridgedValueDescription::
getEnumKeys() const
{
    ExcAssert(impl);
    return impl->getEnumKeys();
}

std::vector<std::tuple<int, std::string, std::string> >
BridgedValueDescription::
getEnumValues() const
{
    ExcAssert(impl);
    return impl->getEnumValues();
}

bool
BridgedValueDescription::
isSame(const ValueDescription* other) const
{
    ExcAssert(impl);
    return impl->isSame(other);
}

bool
BridgedValueDescription::
isChildOf(const ValueDescription* base) const
{
    ExcAssert(impl);
    return impl->isChildOf(base);
}

void
BridgedValueDescription::
initialize()
{
    // Impl should be initialized already...
}

/*****************************************************************************/
/* UTILITY FUNCTIONS                                                         */
/*****************************************************************************/

short int stringToKey(const std::string & str, short int *)
{
    return boost::lexical_cast<short int>(str);
}

unsigned short int stringToKey(const std::string & str, unsigned short int *)
{
    return boost::lexical_cast<unsigned short int>(str);
}

int stringToKey(const std::string & str, int *)
{
    return boost::lexical_cast<int>(str);
}

unsigned int stringToKey(const std::string & str, unsigned int *)
{
    return boost::lexical_cast<unsigned int>(str);
}

long int stringToKey(const std::string & str, long int *)
{
    return boost::lexical_cast<long int>(str);
}

unsigned long int stringToKey(const std::string & str, unsigned long int *)
{
    return boost::lexical_cast<unsigned long int>(str);
}

long long int stringToKey(const std::string & str, long long int *)
{
    return boost::lexical_cast<long long int>(str);
}

unsigned long long int stringToKey(const std::string & str, unsigned long long int *)
{
    return boost::lexical_cast<unsigned long long int>(str);
}

} // namespace MLDB

ext: cc

max_stars_repo_name: tomzhang/mldb

max_issues_repo_name: tomzhang/mldb

max_forks_repo_name: tomzhang/mldb


text:
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Copyright (c) 2016 Frank Hein, maxence business consulting gmbh

Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(MXC_QITOO_DIRECTIVE_PROBE)
#define MXC_QITOO_DIRECTIVE_PROBE

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/spirit/home/qi/meta_compiler.hpp>
#include <boost/spirit/home/qi/skip_over.hpp>
#include <boost/spirit/home/qi/parser.hpp>
#include <boost/spirit/home/support/attributes.hpp>
#include <boost/spirit/home/support/info.hpp>
#include <boost/spirit/home/support/common_terminals.hpp>
#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/support/has_semantic_action.hpp>

namespace mxc { namespace qitoo {
    BOOST_SPIRIT_TERMINAL(probe);
}}

namespace boost { namespace spirit
{
    ///////////////////////////////////////////////////////////////////////////
    // Enablers
    ///////////////////////////////////////////////////////////////////////////
    template <>
    struct use_directive<qi::domain, mxc::qitoo::tag::probe> // enable probe[]
        : mpl::true_ {};
}}

namespace mxc { namespace qitoo {

    namespace spirit    = boost::spirit;
    namespace qi        = spirit::qi;

    template <typename Subject>
    struct probe_directive : qi::unary_parser<probe_directive<Subject> >
    {
        using subject_type = Subject;

        probe_directive(Subject const& subject_) : subject(subject_) {}

        template <typename Context, typename Iterator>
        struct attribute
        {
            using type = typename spirit::traits::attribute_of<subject_type, Context, Iterator>::type;
        };

        template <typename Iterator, typename Context, typename Skipper, typename Attribute>
            bool parse(Iterator& first, Iterator const& last
                , Context& context, Skipper const& skipper, Attribute& attr_) const
        {
            Iterator save = first;
            if (subject.parse(first, last, context, skipper, qi::unused))
            {
                first = save;
                return subject.parse(first, last, context, skipper, attr_);
            }
            return false;
        }

        template <typename Context>
        qi::info what(Context& context) const
        {
            return qi::info("probe", subject.what(context));
        }

        Subject subject;
    };

}}

namespace boost {  namespace spirit {
    namespace qi
    {
        ///////////////////////////////////////////////////////////////////////////
        // Parser generators: make_xxx function (objects)
        ///////////////////////////////////////////////////////////////////////////
        template <typename Subject, typename Modifiers>
        struct make_directive<mxc::qitoo::tag::probe, Subject, Modifiers>
        {
            using result_type = mxc::qitoo::probe_directive<Subject>;
            result_type operator()(unused_type, Subject const& subject, unused_type) const
            {
                return result_type(subject);
            }
        };
    }
    namespace traits
    {
        ///////////////////////////////////////////////////////////////////////////
        template <typename Subject>
        struct has_semantic_action<mxc::qitoo::probe_directive<Subject> >
            : unary_has_semantic_action<Subject> {};
        ///////////////////////////////////////////////////////////////////////////
        template <typename Subject, typename Attribute, typename Context, typename Iterator>
        struct handles_container<mxc::qitoo::probe_directive<Subject>, Attribute, Context, Iterator>
            : unary_handles_container<Subject, Attribute, Context, Iterator> {};
    }
}}

#endif

max_stars_repo_name: mxc-commons/MxcQitoo

max_issues_repo_name: mxc-commons/MxcQitoo

max_forks_repo_name: mxc-commons/MxcQitoo


text:
// Copyright © 2017-2019 Trust.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.

#include "../ARK/Address.h"
#include "../ARK/Signer.h"
#include "../ARK/Transaction.h"
#include "../proto/ARK.pb.h"
#include "../uint256.h"
#include <TrustWalletCore/TWARKSigner.h>
#include <boost/multiprecision/cpp_int.hpp>

using namespace TW;
using namespace TW::ARK;

TW_ARK_Proto_SigningOutput TWARKSignerSign(TW_ARK_Proto_SigningInput data) {
    Proto::SigningInput input;
    input.ParseFromArray(TWDataBytes(data), static_cast<int>(TWDataSize(data)));

    auto key = PrivateKey(Data(input.private_key().begin(), input.private_key().end()));
    auto pubKey = key.getPublicKey(TWPublicKeyTypeSECP256k1);
    auto to = Address(input.to_address());

    auto tx = Transaction(
        /* type */ static_cast<uint8_t>(input.type()),
        /* amount */ input.amount(),
        /* fee */ input.fee(),
        /* timestamp */ input.timestamp(),
        /* to */ to,
        /* publicKey*/ pubKey.bytes
    );

    auto output = Signer::sign(key, tx);

    auto serialized = output.SerializeAsString();
    return TWDataCreateWithBytes(reinterpret_cast<const uint8_t *>(serialized.data()),
                                 serialized.size());
}


text:
//
// Licensed to Green Energy Corp (www.greenenergycorp.com) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Green Enery Corp licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//

#include "StartupTeardownTest.h"

#include <DNP3/MasterStack.h>
#include <APL/PhysicalLayerAsyncTCPClient.h>
#include <APL/LogToStdio.h>

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

using namespace apl;
using namespace apl::dnp;

StartupTeardownTest::StartupTeardownTest(FilterLevel aLevel, bool aImmediate) :
	log(),
	manager(log.GetLogger(aLevel, "mgr"))
{
	if(aImmediate) log.AddLogSubscriber(LogToStdio::Inst());
}

void StartupTeardownTest::CreatePort(const std::string& arName, FilterLevel aLevel)
{
	std::string name = arName + " router";
	PhysLayerSettings s(aLevel, 1000);
	manager.AddTCPClient(arName, s, "127.0.0.1", 30000);
}

void StartupTeardownTest::AddMaster(const std::string& arStackName, const std::string& arPortName, boost::uint16_t aLocalAddress, FilterLevel aLevel)
{
	MasterStackConfig cfg;
	cfg.link.LocalAddr = aLocalAddress;
	manager.AddMaster(arPortName, arStackName, aLevel, &fdo, cfg);
}


text:
/*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.

// All rights reserved.

// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/

#ifndef STAPL_CONTAINERS_DISTRIBUTION_OPERATIONS_APPLYABLE_HPP
#define STAPL_CONTAINERS_DISTRIBUTION_OPERATIONS_APPLYABLE_HPP

#include <stapl/containers/type_traits/distribution_traits.hpp>
#include <stapl/views/view_packing.hpp>
#include <utility>
#include <type_traits>
#include <boost/utility/result_of.hpp>

namespace stapl {

namespace operations {

//////////////////////////////////////////////////////////////////////
/// @brief Operations class for container distributions that provides
///        @ref apply_set() and @ref apply_get().
///
/// Uses the CRTP pattern. Requires that the base container manager has
/// contains(), contains_apply_set() and contains_apply_get() functions method
/// that take a GID and an arbitrary function object.
///
/// @tparam Derived Most derived distribution class
////////////////////////////////////////////////////////////////////////
template<typename Derived>
class applyable
{
private:
  typedef Derived derived_type;

public:
  STAPL_IMPORT_TYPE(typename distribution_traits<derived_type>, gid_type)
  STAPL_IMPORT_TYPE(typename distribution_traits<derived_type>, value_type)

private:
  //////////////////////////////////////////////////////////////////////
  /// @brief Helper class to call @ref applyable::apply_set_impl().
  ////////////////////////////////////////////////////////////////////////
  template<typename Functor>
  struct apply_set_wf
    : private Functor
  {
    typedef void result_type;

    explicit apply_set_wf(Functor const& f)
      : Functor(f)
    { }

    void operator()(p_object& d, gid_type const& gid) const
    {
      down_cast<derived_type&>(d).apply_set_impl(
        gid, static_cast<Functor const&>(*this));
    }

    void define_type(typer& t)
    {
      t.base<Functor>(*this);
    }
  };

  //////////////////////////////////////////////////////////////////////
  /// @brief Helper class to call @ref applyable::apply_get_impl().
  ////////////////////////////////////////////////////////////////////////
  template<typename Functor>
  struct apply_get_wf
    : private Functor
  {
    typedef void result_type;

    typedef typename boost::result_of<Functor(value_type&)>::type f_result_type;
    typedef typename boost::result_of<
       transporter_packager(f_result_type)
    >::type                                                       transfer_type;
    typedef promise<transfer_type>                                promise_type;

    mutable promise_type m_p;

    explicit apply_get_wf(Functor const& f, promise_type p)
      : Functor(f), m_p(std::move(p))
    { }

    void operator()(p_object& d, gid_type const& gid) const
    {
      applyable& a = down_cast<derived_type&>(d);

      auto f = [&]() {
        a.apply_get_impl(
          gid, static_cast<Functor const&>(*this),
          [&](f_result_type&& v)
            { m_p.set_value(std::move(transporter_packager()(v))); });
      };

      constexpr bool b_wrap =
        !std::is_same<f_result_type, transfer_type>::value;

      if (b_wrap)
      {
        gang g;
        f();
        rmi_fence();
        return;
      }

      // else
      f();
    }

    void define_type(typer& t)
    {
      t.base<Functor>(*this);
      t.member(m_p);
    }
  };

  //////////////////////////////////////////////////////////////////////
  /// @brief Cast this object to its most derived class. Used for CRTP.
  //////////////////////////////////////////////////////////////////////
  derived_type& derived(void)
  {
    return static_cast<derived_type&>(*this);
  }

  //////////////////////////////////////////////////////////////////////
  /// @brief Cast this object to its most derived class. Used for CRTP.
  /// @todo Propagate constness through applyable methods.
  //////////////////////////////////////////////////////////////////////
  derived_type /*const*/& derived(void) const
  {
    return static_cast<derived_type&>(const_cast<applyable&>(*this));
  }

public:
  //////////////////////////////////////////////////////////////////////
  /// @brief Apply a function object to the element with the given GID.
  ///
  /// @param gid GID of the element for which we want to apply the function
  ///            object.
  /// @param f   Function object to apply to the element.
  ///
  /// @warning The function operator of @p f has to be @c const qualified.
  //////////////////////////////////////////////////////////////////////
  template<typename Functor>
  void apply_set(gid_type const& gid, Functor const& f)
  {
    if (derived().container_manager().contains_apply_set(gid, f))
      return;

    // else
    derived().directory().invoke_where(apply_set_wf<Functor>(f), gid);
  }

  //////////////////////////////////////////////////////////////////////
  /// @brief Apply a function object to the element with the given GID,
  ///        disregarding RMI causal ordering.
  ///
  /// @param gid GID of the element for which we want to apply the function
  ///            object.
  /// @param f   Function object to apply to the element.
  ///
  /// @warning The function operator of @p f has to be @c const qualified.
  //////////////////////////////////////////////////////////////////////
  template<typename Functor>
  void unordered_apply_set(gid_type const& gid, Functor&& f)
  {
    if (derived().container_manager().contains_apply_set(gid, f))
      return;

    // else
    derived().directory().unordered_invoke_where(
      apply_set_wf<Functor>(std::forward<Functor>(f)), gid);
  }

  //////////////////////////////////////////////////////////////////////
  /// @brief Apply a function object to the element with the given GID and
  ///        return the result.
  ///
  /// @param gid GID of the element for which we want to apply the function
  ///            object and return the result.
  /// @param f   Function object to apply to the element.
  ///
  /// @return The result of applying @p f to the element.
  ///
  /// @warning This function assumes that the @p Functor reflects a public type
  ///          @c result_type and that the invocation of its function operator
  ///          returns a value that is convertible to result_type. The function
  ///          operator of @p f has to be @c const qualified.
  //////////////////////////////////////////////////////////////////////
  template<typename Functor>
  typename boost::result_of<Functor(value_type&)>::type
  apply_get(gid_type const& gid, Functor const& f)
  {
    auto ret_val =
      derived().container_manager().contains_apply_get(gid, f);

    if (ret_val)
      return std::move(*ret_val);

    // else
    using wf_type       = apply_get_wf<Functor>;
    using transfer_type = typename wf_type::transfer_type;

    promise<transfer_type> p;
    auto ft = p.get_future();

    derived().directory().invoke_where(wf_type{f, std::move(p)}, gid);

    transfer_type package = ft.get(); // sync_rmi() equivalent

    return transporter_unpackager()(package);
  }

  //////////////////////////////////////////////////////////////////////
  /// @brief Apply a function object to the element with the given GID and
  ///        return the result.
  ///
  /// @param gid GID of the element for which we want to apply the function
  ///            object and return the result.
  /// @param f   Function object to apply to the element.
  ///
  /// @return The result of applying @p f to the element.
  ///
  /// @warning This function assumes that the @p Functor reflects a public type
  ///          @c result_type and that the invocation of its function operator
  ///          returns a value that is convertible to result_type. The function
  ///          operator of @p f has to be @c const qualified.
  /// @todo Having a pointer to member variant with variadic argument list maybe
  /// more convenient and stress the compiler less.  Investigate.
  //////////////////////////////////////////////////////////////////////
  template<typename Functor>
  typename boost::result_of<Functor(value_type&)>::type
  apply_get(gid_type const& gid, Functor const& f) const
  {
    auto ret_val = derived().container_manager().contains_apply_get(gid, f);

    if (ret_val)
      return std::move(*ret_val);

    // else
    using wf_type       = apply_get_wf<Functor>;
    using transfer_type = typename wf_type::transfer_type;

    promise<transfer_type> p;
    auto ft = p.get_future();

    derived().directory().invoke_where(wf_type{f, std::move(p)}, gid);

    transfer_type package = ft.get(); // sync_rmi() equivalent

    return transporter_unpackager()(package);
  }

private:
  //////////////////////////////////////////////////////////////////////
  /// @brief Apply a function object to an element at a specific GID, with
  /// the assumption that the element is local. Used by @ref apply_set.
  /// @param gid The GID associated with the element for which we want to apply
  /// the functor.
  /// @param f The functor to apply to the element
  /// @see apply_set
  //////////////////////////////////////////////////////////////////////
  template<typename Functor>
  void apply_set_impl(gid_type const& gid, Functor const& f)
  {
    stapl_assert(derived().container_manager().contains(gid),
                 "called on non-local gid");
    derived().container_manager().apply_set(gid, f);
  }

  //////////////////////////////////////////////////////////////////////
  /// @brief Invoke visitor functor with the value returned by invoking an
  /// arbitrary functor on an element at a specific GID with the assumption
  /// that the element is local.
  /// @param gid The GID associated with the element for which we want to apply
  /// the functor and read the result.
  /// @param visitor Visitor functor that wraps setting of promise on another
  ///   location.
  /// @param f The functor to apply to the element
  /// @see apply_get
  //////////////////////////////////////////////////////////////////////
  template<typename Functor, typename Visitor>
  void apply_get_impl(gid_type const& gid,
                      Functor const& f,
                      Visitor const& visitor)
  {
    stapl_assert(derived().container_manager().contains(gid),
                 "called on non-local gid");

    visitor(derived().container_manager().apply_get(gid, f));
  }
}; // class applyable

} // namespace operations

} // namespace stapl

#endif // STAPL_CONTAINERS_DISTRIBUTION_OPERATIONS_APPLYABLE_HPP


text:
/*
 * latlonrad.cc
 *
 *  Created on: 22/05/2014
 *      Author: pablin
 */
#include <boost/lexical_cast.hpp>
#include <rtbkit/core/agent_configuration/latlonrad.h>
#include <boost/algorithm/string.hpp>
#include <boost/range/algorithm/remove_if.hpp>
#include <stdlib.h>
#include "jml/arch/exception.h"

using namespace RTBKIT;

LatLonRad::LatLonRad(float la, float lo, float r)
: lat(la), lon(lo), radius(r){ }

LatLonRad::LatLonRad()
: lat(0), lon(0), radius(-1){ }

LatLonRad
LatLonRad::createFromJson(const Json::Value & val) {

    LatLonRad llr;

    if (val.isMember("lat") && val.isMember("long") && val.isMember("radius")){
        llr.lat = val["lat"].asDouble();
        llr.lon = val["long"].asDouble();
        llr.radius = val["radius"].asDouble();
    } else {
        throw ML::Exception("Error parsing LatLonRad. It should have lat, "
                            "long and radius. There was given: %s",
                            val.asCString());
    }

    return llr;
}

void LatLonRad::fromJson(const Json::Value & val) {
    *this = createFromJson(val);
}

Json::Value LatLonRad::toJson() const {
    Json::Value result;
    result["lat"] = lat;
    result["long"] = lon;
    result["radius"] = radius;
    return result;
}

bool LatLonRad::empty() const {
    return radius == 0; // as no point could be inside a 0 radius circle/square
}

LatLonRadList
LatLonRadList::createFromJson(const Json::Value & val) {

    LatLonRadList llrl;

    for (auto jt = val.begin(), jend = val.end();  jt != jend;  ++jt) {
        LatLonRad llr = LatLonRad::createFromJson(*jt);
        llrl.latlonrads.push_back(llr);
    }

    return llrl;
}

void LatLonRadList::fromJson(const Json::Value & val) {
    *this = createFromJson(val);
}

Json::Value LatLonRadList::toJson() const {
    Json::Value result;
    for (unsigned i = 0;  i < latlonrads.size();  ++i)
        result[i] = latlonrads[i].toJson();
    return result;
}

bool LatLonRadList::empty() const {
    return latlonrads.empty();
}

max_stars_repo_name: etnrlz/rtbkit

max_issues_repo_name: TuanTranEngineer/rtbkit

max_forks_repo_name: TuanTranEngineer/rtbkit


text:
//
// Copyright © 2017 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include <common/include/CommandHandlerRegistry.hpp>
#include <server/include/basePipeServer/ConnectionHandler.hpp>
#include <DirectoryCaptureCommandHandler.hpp>
#include <GatordMockService.hpp>
#include <LabelsAndEventClasses.hpp>
#include <ProfilingService.hpp>
#include <TimelinePacketWriterFactory.hpp>

#include <armnn/utility/NumericCast.hpp>

#include <server/include/timelineDecoder/TimelineDirectoryCaptureCommandHandler.hpp>
#include <server/include/timelineDecoder/TimelineDecoder.hpp>

#include <Runtime.hpp>

#include <MockBackend.hpp>

#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test_suite.hpp>

BOOST_AUTO_TEST_SUITE(GatordMockTests)

using namespace armnn;
using namespace std::this_thread;
using namespace std::chrono_literals;

BOOST_AUTO_TEST_CASE(CounterCaptureHandlingTest)
{
    arm::pipe::PacketVersionResolver packetVersionResolver;

    // Data with timestamp, counter idx & counter values
    std::vector<std::pair<uint16_t, uint32_t>> indexValuePairs;
    indexValuePairs.reserve(5);
    indexValuePairs.emplace_back(std::make_pair<uint16_t, uint32_t>(0, 100));
    indexValuePairs.emplace_back(std::make_pair<uint16_t, uint32_t>(1, 200));
    indexValuePairs.emplace_back(std::make_pair<uint16_t, uint32_t>(2, 300));
    indexValuePairs.emplace_back(std::make_pair<uint16_t, uint32_t>(3, 400));
    indexValuePairs.emplace_back(std::make_pair<uint16_t, uint32_t>(4, 500));

    // ((uint16_t (2 bytes) + uint32_t (4 bytes)) * 5) + word1 + word2
    uint32_t dataLength = 38;

    // Simulate two different packets incoming 500 ms apart
    uint64_t time = static_cast<uint64_t>(
        std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now().time_since_epoch())
            .count());

    uint64_t time2 = time + 5000;

    // UniqueData required for Packet class
    std::unique_ptr<unsigned char[]> uniqueData1 = std::make_unique<unsigned char[]>(dataLength);
    unsigned char* data1                         = reinterpret_cast<unsigned char*>(uniqueData1.get());

    std::unique_ptr<unsigned char[]> uniqueData2 = std::make_unique<unsigned char[]>(dataLength);
    unsigned char* data2                         = reinterpret_cast<unsigned char*>(uniqueData2.get());

    uint32_t sizeOfUint64 = armnn::numeric_cast<uint32_t>(sizeof(uint64_t));
    uint32_t sizeOfUint32 = armnn::numeric_cast<uint32_t>(sizeof(uint32_t));
    uint32_t sizeOfUint16 = armnn::numeric_cast<uint32_t>(sizeof(uint16_t));
    // Offset index to point to mem address
    uint32_t offset = 0;

    profiling::WriteUint64(data1, offset, time);
    offset += sizeOfUint64;
    for (const auto& pair : indexValuePairs)
    {
        profiling::WriteUint16(data1, offset, pair.first);
        offset += sizeOfUint16;
        profiling::WriteUint32(data1, offset, pair.second);
        offset += sizeOfUint32;
    }

    offset = 0;

    profiling::WriteUint64(data2, offset, time2);
    offset += sizeOfUint64;
    for (const auto& pair : indexValuePairs)
    {
        profiling::WriteUint16(data2, offset, pair.first);
        offset += sizeOfUint16;
        profiling::WriteUint32(data2, offset, pair.second);
        offset += sizeOfUint32;
    }

    uint32_t headerWord1 = packetVersionResolver.ResolvePacketVersion(0, 4).GetEncodedValue();
    // Create packet to send through to the command functor
    arm::pipe::Packet packet1(headerWord1, dataLength, uniqueData1);
    arm::pipe::Packet packet2(headerWord1, dataLength, uniqueData2);

    gatordmock::PeriodicCounterCaptureCommandHandler commandHandler(0, 4, headerWord1, true);

    // Simulate two separate packets coming in to calculate period
    commandHandler(packet1);
    commandHandler(packet2);

    ARMNN_ASSERT(commandHandler.m_CurrentPeriodValue == 5000);

    for (size_t i = 0; i < commandHandler.m_CounterCaptureValues.m_Uids.size(); ++i)
    {
        ARMNN_ASSERT(commandHandler.m_CounterCaptureValues.m_Uids[i] == i);
    }
}

void WaitFor(std::function<bool()> predicate, std::string errorMsg, uint32_t timeout = 2000, uint32_t sleepTime = 50)
{
    uint32_t timeSlept = 0;
    while (!predicate())
    {
        if (timeSlept >= timeout)
        {
            BOOST_FAIL("Timeout: " + errorMsg);
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
        timeSlept += sleepTime;
    }
}

void CheckTimelineDirectory(arm::pipe::TimelineDirectoryCaptureCommandHandler& commandHandler)
{
    uint32_t uint8_t_size  = sizeof(uint8_t);
    uint32_t uint32_t_size = sizeof(uint32_t);
    uint32_t uint64_t_size = sizeof(uint64_t);
    uint32_t threadId_size = sizeof(int);

    profiling::BufferManager bufferManager(5);
    profiling::TimelinePacketWriterFactory timelinePacketWriterFactory(bufferManager);

    std::unique_ptr<profiling::ISendTimelinePacket> sendTimelinePacket =
            timelinePacketWriterFactory.GetSendTimelinePacket();

    sendTimelinePacket->SendTimelineMessageDirectoryPackage();
    sendTimelinePacket->Commit();

    std::vector<arm::pipe::SwTraceMessage> swTraceBufferMessages;

    unsigned int offset = uint32_t_size * 2;

    std::unique_ptr<profiling::IPacketBuffer> packetBuffer = bufferManager.GetReadableBuffer();

    uint8_t readStreamVersion = ReadUint8(packetBuffer, offset);
    BOOST_CHECK(readStreamVersion == 4);
    offset += uint8_t_size;
    uint8_t readPointerBytes = ReadUint8(packetBuffer, offset);
    BOOST_CHECK(readPointerBytes == uint64_t_size);
    offset += uint8_t_size;
    uint8_t readThreadIdBytes = ReadUint8(packetBuffer, offset);
    BOOST_CHECK(readThreadIdBytes == threadId_size);
    offset += uint8_t_size;

    uint32_t declarationSize = profiling::ReadUint32(packetBuffer, offset);
    offset += uint32_t_size;
    for(uint32_t i = 0; i < declarationSize; ++i)
    {
        swTraceBufferMessages.push_back(arm::pipe::ReadSwTraceMessage(packetBuffer->GetReadableData(),
                                                                      offset,
                                                                      packetBuffer->GetSize()));
    }

    for(uint32_t index = 0; index < declarationSize; ++index)
    {
        arm::pipe::SwTraceMessage& bufferMessage = swTraceBufferMessages[index];
        arm::pipe::SwTraceMessage& handlerMessage = commandHandler.m_SwTraceMessages[index];

        BOOST_CHECK(bufferMessage.m_Name == handlerMessage.m_Name);
        BOOST_CHECK(bufferMessage.m_UiName == handlerMessage.m_UiName);
        BOOST_CHECK(bufferMessage.m_Id == handlerMessage.m_Id);

        BOOST_CHECK(bufferMessage.m_ArgTypes.size() == handlerMessage.m_ArgTypes.size());
        for(uint32_t i = 0; i < bufferMessage.m_ArgTypes.size(); ++i)
        {
            BOOST_CHECK(bufferMessage.m_ArgTypes[i] == handlerMessage.m_ArgTypes[i]);
        }

        BOOST_CHECK(bufferMessage.m_ArgNames.size() == handlerMessage.m_ArgNames.size());
        for(uint32_t i = 0; i < bufferMessage.m_ArgNames.size(); ++i)
        {
            BOOST_CHECK(bufferMessage.m_ArgNames[i] == handlerMessage.m_ArgNames[i]);
        }
    }
}

void CheckTimelinePackets(arm::pipe::TimelineDecoder& timelineDecoder)
{
    unsigned int i = 0; // Use a postfix increment to avoid changing indexes each time the packet gets updated.
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i].m_Guid == profiling::LabelsAndEventClasses::NAME_GUID);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i++].m_Name == profiling::LabelsAndEventClasses::NAME_LABEL);

    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i].m_Guid == profiling::LabelsAndEventClasses::TYPE_GUID);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i++].m_Name == profiling::LabelsAndEventClasses::TYPE_LABEL);

    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i].m_Guid == profiling::LabelsAndEventClasses::INDEX_GUID);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i++].m_Name == profiling::LabelsAndEventClasses::INDEX_LABEL);

    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i].m_Guid == profiling::LabelsAndEventClasses::BACKENDID_GUID);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i++].m_Name == profiling::LabelsAndEventClasses::BACKENDID_LABEL);

    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i].m_Guid == profiling::LabelsAndEventClasses::CHILD_GUID);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i++].m_Name == profiling::LabelsAndEventClasses::CHILD_LABEL);

    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i].m_Guid == profiling::LabelsAndEventClasses::EXECUTION_OF_GUID);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i++].m_Name ==
                profiling::LabelsAndEventClasses::EXECUTION_OF_LABEL);

    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i].m_Guid == profiling::LabelsAndEventClasses::PROCESS_ID_GUID);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i++].m_Name ==
                profiling::LabelsAndEventClasses::PROCESS_ID_LABEL);

    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i].m_Guid == profiling::LabelsAndEventClasses::LAYER_GUID);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i++].m_Name == profiling::LabelsAndEventClasses::LAYER);

    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i].m_Guid == profiling::LabelsAndEventClasses::WORKLOAD_GUID);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i++].m_Name == profiling::LabelsAndEventClasses::WORKLOAD);

    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i].m_Guid == profiling::LabelsAndEventClasses::NETWORK_GUID);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i++].m_Name == profiling::LabelsAndEventClasses::NETWORK);

    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i].m_Guid == profiling::LabelsAndEventClasses::CONNECTION_GUID);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i++].m_Name == profiling::LabelsAndEventClasses::CONNECTION);

    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i].m_Guid == profiling::LabelsAndEventClasses::INFERENCE_GUID);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i++].m_Name == profiling::LabelsAndEventClasses::INFERENCE);

    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i].m_Guid ==
                profiling::LabelsAndEventClasses::WORKLOAD_EXECUTION_GUID);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels[i++].m_Name ==
                profiling::LabelsAndEventClasses::WORKLOAD_EXECUTION);

    BOOST_CHECK(timelineDecoder.GetModel().m_EventClasses[0].m_Guid ==
                profiling::LabelsAndEventClasses::ARMNN_PROFILING_SOL_EVENT_CLASS);
    BOOST_CHECK(timelineDecoder.GetModel().m_EventClasses[1].m_Guid ==
                profiling::LabelsAndEventClasses::ARMNN_PROFILING_EOL_EVENT_CLASS);
}

BOOST_AUTO_TEST_CASE(GatorDMockEndToEnd)
{
    // The purpose of this test is to setup both sides of the profiling service and get to the point of receiving
    // performance data.

    // Setup the mock service to bind to the UDS.
    std::string udsNamespace = "gatord_namespace";

    BOOST_CHECK_NO_THROW(arm::pipe::ConnectionHandler connectionHandler(udsNamespace, false));

    arm::pipe::ConnectionHandler connectionHandler(udsNamespace, false);

    // Enable the profiling service.
    armnn::IRuntime::CreationOptions::ExternalProfilingOptions options;
    options.m_EnableProfiling = true;
    options.m_TimelineEnabled = true;

    armnn::profiling::ProfilingService profilingService;
    profilingService.ResetExternalProfilingOptions(options, true);

    // Bring the profiling service to the "WaitingForAck" state
    BOOST_CHECK(profilingService.GetCurrentState() == profiling::ProfilingState::Uninitialised);
    profilingService.Update();
    BOOST_CHECK(profilingService.GetCurrentState() == profiling::ProfilingState::NotConnected);
    profilingService.Update();

    // Connect the profiling service
    auto basePipeServer = connectionHandler.GetNewBasePipeServer(false);

    // Connect the profiling service to the mock Gatord.
    gatordmock::GatordMockService mockService(std::move(basePipeServer), false);

    arm::pipe::TimelineDecoder& timelineDecoder = mockService.GetTimelineDecoder();
    profiling::DirectoryCaptureCommandHandler& directoryCaptureCommandHandler =
         mockService.GetDirectoryCaptureCommandHandler();

    // Give the profiling service sending thread time start executing and send the stream metadata.
    WaitFor([&](){return profilingService.GetCurrentState() == profiling::ProfilingState::WaitingForAck;},
            "Profiling service did not switch to WaitingForAck state");

    profilingService.Update();
    // Read the stream metadata on the mock side.
    if (!mockService.WaitForStreamMetaData())
    {
        BOOST_FAIL("Failed to receive StreamMetaData");
    }
    // Send Ack from GatorD
    mockService.SendConnectionAck();
    // And start to listen for packets
    mockService.LaunchReceivingThread();

    WaitFor([&](){return profilingService.GetCurrentState() == profiling::ProfilingState::Active;},
            "Profiling service did not switch to Active state");

    // As part of the default startup of the profiling service a counter directory packet will be sent.
    WaitFor([&](){return directoryCaptureCommandHandler.ParsedCounterDirectory();},
            "MockGatord did not receive counter directory packet");

    // Following that we will receive a collection of well known timeline labels and event classes
    WaitFor([&](){return timelineDecoder.GetModel().m_EventClasses.size() >= 2;},
            "MockGatord did not receive well known timeline labels and event classes");

    CheckTimelineDirectory(mockService.GetTimelineDirectoryCaptureCommandHandler());
    // Verify the commonly used timeline packets sent when the profiling service enters the active state
    CheckTimelinePackets(timelineDecoder);

    const profiling::ICounterDirectory& serviceCounterDirectory  = profilingService.GetCounterDirectory();
    const profiling::ICounterDirectory& receivedCounterDirectory = directoryCaptureCommandHandler.GetCounterDirectory();

    // Compare the basics of the counter directory from the service and the one we received over the wire.
    BOOST_CHECK(serviceCounterDirectory.GetDeviceCount() == receivedCounterDirectory.GetDeviceCount());
    BOOST_CHECK(serviceCounterDirectory.GetCounterSetCount() == receivedCounterDirectory.GetCounterSetCount());
    BOOST_CHECK(serviceCounterDirectory.GetCategoryCount() == receivedCounterDirectory.GetCategoryCount());
    BOOST_CHECK(serviceCounterDirectory.GetCounterCount() == receivedCounterDirectory.GetCounterCount());

    receivedCounterDirectory.GetDeviceCount();
    serviceCounterDirectory.GetDeviceCount();

    const profiling::Devices& serviceDevices = serviceCounterDirectory.GetDevices();
    for (auto& device : serviceDevices)
    {
        // Find the same device in the received counter directory.
        auto foundDevice = receivedCounterDirectory.GetDevices().find(device.second->m_Uid);
        BOOST_CHECK(foundDevice != receivedCounterDirectory.GetDevices().end());
        BOOST_CHECK(device.second->m_Name.compare((*foundDevice).second->m_Name) == 0);
        BOOST_CHECK(device.second->m_Cores == (*foundDevice).second->m_Cores);
    }

    const profiling::CounterSets& serviceCounterSets = serviceCounterDirectory.GetCounterSets();
    for (auto& counterSet : serviceCounterSets)
    {
        // Find the same counter set in the received counter directory.
        auto foundCounterSet = receivedCounterDirectory.GetCounterSets().find(counterSet.second->m_Uid);
        BOOST_CHECK(foundCounterSet != receivedCounterDirectory.GetCounterSets().end());
        BOOST_CHECK(counterSet.second->m_Name.compare((*foundCounterSet).second->m_Name) == 0);
        BOOST_CHECK(counterSet.second->m_Count == (*foundCounterSet).second->m_Count);
    }

    const profiling::Categories& serviceCategories = serviceCounterDirectory.GetCategories();
    for (auto& category : serviceCategories)
    {
        for (auto& receivedCategory : receivedCounterDirectory.GetCategories())
        {
            if (receivedCategory->m_Name.compare(category->m_Name) == 0)
            {
                // We've found the matching category.
                // Now look at the interiors of the counters. Start by sorting them.
                std::sort(category->m_Counters.begin(), category->m_Counters.end());
                std::sort(receivedCategory->m_Counters.begin(), receivedCategory->m_Counters.end());
                // When comparing uid's here we need to translate them.
                std::function<bool(const uint16_t&, const uint16_t&)> comparator =
                    [&directoryCaptureCommandHandler](const uint16_t& first, const uint16_t& second) {
                        uint16_t translated = directoryCaptureCommandHandler.TranslateUIDCopyToOriginal(second);
                        if (translated == first)
                        {
                            return true;
                        }
                        return false;
                    };
                // Then let vector == do the work.
                BOOST_CHECK(std::equal(category->m_Counters.begin(), category->m_Counters.end(),
                                       receivedCategory->m_Counters.begin(), comparator));
                break;
            }
        }
    }

    // Finally check the content of the counters.
    const profiling::Counters& receivedCounters = receivedCounterDirectory.GetCounters();
    for (auto& receivedCounter : receivedCounters)
    {
        // Translate the Uid and find the corresponding counter in the original counter directory.
        // Note we can't check m_MaxCounterUid here as it will likely differ between the two counter directories.
        uint16_t translated = directoryCaptureCommandHandler.TranslateUIDCopyToOriginal(receivedCounter.first);
        const profiling::Counter* serviceCounter = serviceCounterDirectory.GetCounter(translated);
        BOOST_CHECK(serviceCounter->m_DeviceUid == receivedCounter.second->m_DeviceUid);
        BOOST_CHECK(serviceCounter->m_Name.compare(receivedCounter.second->m_Name) == 0);
        BOOST_CHECK(serviceCounter->m_CounterSetUid == receivedCounter.second->m_CounterSetUid);
        BOOST_CHECK(serviceCounter->m_Multiplier == receivedCounter.second->m_Multiplier);
        BOOST_CHECK(serviceCounter->m_Interpolation == receivedCounter.second->m_Interpolation);
        BOOST_CHECK(serviceCounter->m_Class == receivedCounter.second->m_Class);
        BOOST_CHECK(serviceCounter->m_Units.compare(receivedCounter.second->m_Units) == 0);
        BOOST_CHECK(serviceCounter->m_Description.compare(receivedCounter.second->m_Description) == 0);
    }

    mockService.WaitForReceivingThread();
    options.m_EnableProfiling = false;
    profilingService.ResetExternalProfilingOptions(options, true);
    // Future tests here will add counters to the ProfilingService, increment values and examine
    // PeriodicCounterCapture data received. These are yet to be integrated.
}

BOOST_AUTO_TEST_CASE(GatorDMockTimeLineActivation)
{
    // This test requires the CpuRef backend to be enabled
    if(!BackendRegistryInstance().IsBackendRegistered("CpuRef"))
    {
        return;
    }
    armnn::MockBackendInitialiser initialiser;
    // Setup the mock service to bind to the UDS.
    std::string udsNamespace = "gatord_namespace";

    arm::pipe::ConnectionHandler connectionHandler(udsNamespace, false);

    armnn::IRuntime::CreationOptions options;
    options.m_ProfilingOptions.m_EnableProfiling = true;
    options.m_ProfilingOptions.m_TimelineEnabled = true;
    armnn::Runtime runtime(options);

    auto basePipeServer = connectionHandler.GetNewBasePipeServer(false);
    gatordmock::GatordMockService mockService(std::move(basePipeServer), false);

    // Read the stream metadata on the mock side.
    if (!mockService.WaitForStreamMetaData())
    {
        BOOST_FAIL("Failed to receive StreamMetaData");
    }

    armnn::MockBackendProfilingService mockProfilingService = armnn::MockBackendProfilingService::Instance();
    armnn::MockBackendProfilingContext *mockBackEndProfilingContext = mockProfilingService.GetContext();

    // Send Ack from GatorD
    mockService.SendConnectionAck();
    // And start to listen for packets
    mockService.LaunchReceivingThread();

    // Build and optimize a simple network while we wait
    INetworkPtr net(INetwork::Create());

    IConnectableLayer* input = net->AddInputLayer(0, "input");

    NormalizationDescriptor descriptor;
    IConnectableLayer* normalize = net->AddNormalizationLayer(descriptor, "normalization");

    IConnectableLayer* output = net->AddOutputLayer(0, "output");

    input->GetOutputSlot(0).Connect(normalize->GetInputSlot(0));
    normalize->GetOutputSlot(0).Connect(output->GetInputSlot(0));

    input->GetOutputSlot(0).SetTensorInfo(TensorInfo({ 1, 1, 4, 4 }, DataType::Float32));
    normalize->GetOutputSlot(0).SetTensorInfo(TensorInfo({ 1, 1, 4, 4 }, DataType::Float32));

    std::vector<armnn::BackendId> backends = { armnn::Compute::CpuRef };
    IOptimizedNetworkPtr optNet = Optimize(*net, backends, runtime.GetDeviceSpec());

    WaitFor([&](){return mockService.GetDirectoryCaptureCommandHandler().ParsedCounterDirectory();},
            "MockGatord did not receive counter directory packet");

    arm::pipe::TimelineDecoder& timelineDecoder = mockService.GetTimelineDecoder();

    WaitFor([&](){return timelineDecoder.GetModel().m_EventClasses.size() >= 2;},
            "MockGatord did not receive well known timeline labels");

    WaitFor([&](){return timelineDecoder.GetModel().m_Entities.size() >= 1;},
            "MockGatord did not receive mock backend test entity");

    // Packets we expect from SendWellKnownLabelsAndEventClassesTest
    BOOST_CHECK(timelineDecoder.GetModel().m_Entities.size() == 1);
    BOOST_CHECK(timelineDecoder.GetModel().m_EventClasses.size()  == 2);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels.size()  == 15);
    BOOST_CHECK(timelineDecoder.GetModel().m_Relationships.size()  == 0);
    BOOST_CHECK(timelineDecoder.GetModel().m_Events.size()  == 0);

    mockService.SendDeactivateTimelinePacket();

    WaitFor([&](){return !mockBackEndProfilingContext->TimelineReportingEnabled();},
            "Timeline packets were not deactivated");

    // Load the network into runtime now that timeline reporting is disabled
    armnn::NetworkId netId;
    runtime.LoadNetwork(netId, std::move(optNet));

    // Now activate timeline packets
    mockService.SendActivateTimelinePacket();

    WaitFor([&](){return mockBackEndProfilingContext->TimelineReportingEnabled();},
            "Timeline packets were not activated");

    // Once TimelineReporting is Enabled additional activateTimelinePackets should be ignored
    mockService.SendActivateTimelinePacket();
    mockService.SendActivateTimelinePacket();

    // Once timeline packets have been reactivated the ActivateTimelineReportingCommandHandler will resend the
    // SendWellKnownLabelsAndEventClasses and then send the structure of any loaded networks
    WaitFor([&](){return timelineDecoder.GetModel().m_Labels.size() >= 24;},
            "MockGatord did not receive well known timeline labels");

    // Packets we expect from SendWellKnownLabelsAndEventClassesTest * 2 + network above (input, norm, backend, output)
    BOOST_CHECK(timelineDecoder.GetModel().m_Entities.size() == 6);
    BOOST_CHECK(timelineDecoder.GetModel().m_EventClasses.size()  == 4);
    BOOST_CHECK(timelineDecoder.GetModel().m_Labels.size()  == 34);
    BOOST_CHECK(timelineDecoder.GetModel().m_Relationships.size()  == 15);
    BOOST_CHECK(timelineDecoder.GetModel().m_Events.size()  == 0);

    mockService.WaitForReceivingThread();
    GetProfilingService(&runtime).Disconnect();
}

BOOST_AUTO_TEST_SUITE_END()


text:
// Copyright (C) 2008-2018 Lorenzo Caminiti
// Distributed under the Boost Software License, Version 1.0 (see accompanying
// file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
// See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html

// Test free function contracts.

#include "../detail/oteststream.hpp"
#include "../detail/counter.hpp"
#include <boost/contract/function.hpp>
#include <boost/contract/old.hpp>
#include <boost/contract/assert.hpp>
#include <boost/contract/check.hpp>
#include <boost/preprocessor/control/iif.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <sstream>

boost::contract::test::detail::oteststream out;

struct x_tag; typedef boost::contract::test::detail::counter<x_tag, int> x_type;
struct y_tag; typedef boost::contract::test::detail::counter<y_tag, int> y_type;

bool swap(x_type& x, y_type& y) {
    bool result;
    boost::contract::old_ptr<x_type> old_x =
            BOOST_CONTRACT_OLDOF(x_type::eval(x));
    boost::contract::old_ptr<y_type> old_y;
    boost::contract::check c = boost::contract::function()
        .precondition([&] {
            out << "swap::pre" << std::endl;
            BOOST_CONTRACT_ASSERT(x.value != y.value);
        })
        .old([&] {
            out << "swap::old" << std::endl;
            old_y = BOOST_CONTRACT_OLDOF(y_type::eval(y));
        })
        .postcondition([&] {
            out << "swap::post" << std::endl;
            BOOST_CONTRACT_ASSERT(x.value == old_y->value);
            BOOST_CONTRACT_ASSERT(y.value == old_x->value);
            BOOST_CONTRACT_ASSERT(result == (old_x->value != old_y->value));
        })
    ;

    out << "swap::body" << std::endl;
    if(x.value == y.value) return result = false;
    int save_x = x.value;
    x.value = y.value;
    y.value = save_x;
    return result = true;
}

int main() {
    std::ostringstream ok;

    {
        x_type x; x.value = 123;
        y_type y; y.value = 456;

        out.str("");
        bool r = swap(x, y);
        ok.str(""); ok
            #ifndef BOOST_CONTRACT_NO_PRECONDITIONS
                << "swap::pre" << std::endl
            #endif
            #ifndef BOOST_CONTRACT_NO_OLDS
                << "swap::old" << std::endl
            #endif
            << "swap::body" << std::endl
            #ifndef BOOST_CONTRACT_NO_POSTCONDITIONS
                << "swap::post" << std::endl
            #endif
        ;
        BOOST_TEST(out.eq(ok.str()));

        BOOST_TEST(r);
        BOOST_TEST_EQ(x.value, 456);
        BOOST_TEST_EQ(y.value, 123);
    }

    #ifndef BOOST_CONTRACT_NO_OLDS
        #define BOOST_CONTRACT_TEST_old 1u
    #else
        #define BOOST_CONTRACT_TEST_old 0u
    #endif

    BOOST_TEST_EQ(x_type::copies(), BOOST_CONTRACT_TEST_old);
    BOOST_TEST_EQ(x_type::evals(), BOOST_CONTRACT_TEST_old);
    BOOST_TEST_EQ(x_type::ctors(), x_type::dtors()); // No leak.

    BOOST_TEST_EQ(y_type::copies(), BOOST_CONTRACT_TEST_old);
    BOOST_TEST_EQ(y_type::evals(), BOOST_CONTRACT_TEST_old);
    BOOST_TEST_EQ(y_type::ctors(), y_type::dtors()); // No leak.

    #undef BOOST_CONTRACT_TEST_old
    return boost::report_errors();
}


text:
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once

#include <armnn/Tensor.hpp>
#include <armnn/utility/Assert.hpp>
#include <armnnUtils/FloatingPointComparison.hpp>

#include <QuantizeHelper.hpp>

#include <boost/multi_array.hpp>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/test/unit_test.hpp>

#include <array>
#include <cmath>
#include <vector>

constexpr float g_FloatCloseToZeroTolerance = 1.0e-6f;

template<typename T, bool isQuantized = true>
struct SelectiveComparer
{
    static bool Compare(T a, T b)
    {
        return (std::max(a, b) - std::min(a, b)) <= 1;
    }

};

template<typename T>
struct SelectiveComparer<T, false>
{
    static bool Compare(T a, T b)
    {
        // If a or b is zero, percent_tolerance does an exact match, so compare to a small, constant tolerance instead.
        if (a == 0.0f || b == 0.0f)
        {
            return std::abs(a - b) <= g_FloatCloseToZeroTolerance;
        }

        if (std::isinf(a) && a == b)
        {
            return true;
        }

        if (std::isnan(a) && std::isnan(b))
        {
            return true;
        }

        // For unquantized floats we use a tolerance of 1%.
        return armnnUtils::within_percentage_tolerance(a, b);
    }
};

template<typename T>
bool SelectiveCompare(T a, T b)
{
    return SelectiveComparer<T, armnn::IsQuantizedType<T>()>::Compare(a, b);
};

template<typename T>
bool SelectiveCompareBoolean(T a, T b)
{
    return (((a == 0) && (b == 0)) || ((a != 0) && (b != 0)));
};

template <typename T, std::size_t n>
boost::test_tools::predicate_result CompareTensors(const boost::multi_array<T, n>& a,
                                                   const boost::multi_array<T, n>& b,
                                                   bool compareBoolean = false,
                                                   bool isDynamic = false)
{
    if (!isDynamic)
    {
        // Checks they are same shape.
        for (unsigned int i = 0;
             i < n;
             i++)
        {
            if (a.shape()[i] != b.shape()[i])
            {
                boost::test_tools::predicate_result res(false);
                res.message() << "Different shapes ["
                              << a.shape()[i]
                              << "!="
                              << b.shape()[i]
                              << "]";
                return res;
            }
        }
    }

    // Now compares element-wise.

    // Fun iteration over n dimensions.
    std::array<unsigned int, n> indices;
    for (unsigned int i = 0; i < n; i++)
    {
        indices[i] = 0;
    }

    std::stringstream errorString;
    int numFailedElements = 0;
    constexpr int maxReportedDifferences = 3;

    while (true)
    {
        bool comparison;
        // As true for uint8_t is non-zero (1-255) we must have a dedicated compare for Booleans.
        if(compareBoolean)
        {
            comparison = SelectiveCompareBoolean(a(indices), b(indices));
        }
        else
        {
            comparison = SelectiveCompare(a(indices), b(indices));
        }

        if (!comparison)
        {
            ++numFailedElements;

            if (numFailedElements <= maxReportedDifferences)
            {
                if (numFailedElements >= 2)
                {
                    errorString << ", ";
                }
                errorString << "[";
                for (unsigned int i = 0; i < n; ++i)
                {
                    errorString << indices[i];
                    if (i != n - 1)
                    {
                        errorString << ",";
                    }
                }
                errorString << "]";

                errorString << " (" << +a(indices) << " != " << +b(indices) << ")";
            }
        }

        ++indices[n - 1];
        for (unsigned int i=n-1; i>0; i--)
        {
            if (indices[i] == a.shape()[i])
            {
                indices[i] = 0;
                ++indices[i - 1];
            }
        }

        if (indices[0] == a.shape()[0])
        {
            break;
        }
    }

    boost::test_tools::predicate_result comparisonResult(true);
    if (numFailedElements > 0)
    {
        comparisonResult = false;
        comparisonResult.message() << numFailedElements << " different values at: ";
        if (numFailedElements > maxReportedDifferences)
        {
            errorString << ", ... (and " << (numFailedElements - maxReportedDifferences) << " other differences)";
        }
        comparisonResult.message() << errorString.str();
    }

    return comparisonResult;
}

// Creates a boost::multi_array with the shape defined by the given TensorInfo.
template <typename T, std::size_t n>
boost::multi_array<T, n> MakeTensor(const armnn::TensorInfo& tensorInfo)
{
    std::array<unsigned int, n> shape;

    for (unsigned int i = 0; i < n; i++)
    {
        shape[i] = tensorInfo.GetShape()[i];
    }

    return boost::multi_array<T, n>(shape);
}

// Creates a boost::multi_array with the shape defined by the given TensorInfo and contents defined by the given vector.
template <typename T, std::size_t n>
boost::multi_array<T, n> MakeTensor(
    const armnn::TensorInfo& tensorInfo, const std::vector<T>& flat, bool isDynamic = false)
{
    if (!isDynamic)
    {
        ARMNN_ASSERT_MSG(flat.size() == tensorInfo.GetNumElements(), "Wrong number of components supplied to tensor");
    }

    std::array<unsigned int, n> shape;

    // NOTE: tensorInfo.GetNumDimensions() might be different from n
    const unsigned int returnDimensions = static_cast<unsigned int>(n);
    const unsigned int actualDimensions = tensorInfo.GetNumDimensions();

    const unsigned int paddedDimensions =
        returnDimensions > actualDimensions ? returnDimensions - actualDimensions : 0u;

    for (unsigned int i = 0u; i < returnDimensions; i++)
    {
        if (i < paddedDimensions)
        {
            shape[i] = 1u;
        }
        else
        {
            shape[i] = tensorInfo.GetShape()[i - paddedDimensions];
        }
    }

    boost::const_multi_array_ref<T, n> arrayRef(&flat[0], shape);
    return boost::multi_array<T, n>(arrayRef);
}

template <typename T, std::size_t n>
boost::multi_array<T, n> MakeRandomTensor(const armnn::TensorInfo& tensorInfo,
                                          unsigned int seed,
                                          float        min = -10.0f,
                                          float        max = 10.0f)
{
    boost::random::mt19937                          gen(seed);
    boost::random::uniform_real_distribution<float> dist(min, max);

    std::vector<float> init(tensorInfo.GetNumElements());
    for (unsigned int i = 0; i < init.size(); i++)
    {
        init[i] = dist(gen);
    }

    const float   qScale  = tensorInfo.GetQuantizationScale();
    const int32_t qOffset = tensorInfo.GetQuantizationOffset();

    return MakeTensor<T, n>(tensorInfo, armnnUtils::QuantizedVector<T>(init, qScale, qOffset));
}