text:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman
    Copyright (c) 2007 Dan Marsden
    Copyright (c) 2009 Christopher Schmidt

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

#include <boost/mpl/apply.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/lambda.hpp>
#include <boost/mpl/or.hpp>
#include <boost/fusion/iterator/advance.hpp>
#include <boost/fusion/iterator/distance.hpp>
#include <boost/fusion/iterator/equal_to.hpp>
#include <boost/fusion/iterator/next.hpp>
#include <boost/fusion/sequence/intrinsic/begin.hpp>
#include <boost/fusion/sequence/intrinsic/end.hpp>
#include <boost/fusion/support/category_of.hpp>

namespace boost { namespace fusion {
    struct random_access_traversal_tag;
namespace detail
{
    template <typename Iterator, typename Pred>
    struct apply_filter
    {
        typedef typename mpl::apply1<
            Pred, Iterator>::type type;
        BOOST_STATIC_CONSTANT(int, value = type::value);
    };

    template <typename First, typename Last, typename Pred>
    struct main_find_if;

    template <typename First, typename Last, typename Pred>
    struct recursive_find_if
    {
        typedef typename
            main_find_if<
                typename result_of::next<First>::type, Last, Pred
            >::type
        type;
    };

    template <typename First, typename Last, typename Pred>
    struct main_find_if
    {
        typedef mpl::or_<
            result_of::equal_to<First, Last>
          , apply_filter<First, Pred> >
        filter;

        typedef typename
            mpl::eval_if<
                filter
              , mpl::identity<First>
              , recursive_find_if<First, Last, Pred>
            >::type
        type;
    };

    template<
        typename First, typename Last,
        typename Pred, bool>
    struct choose_find_if;

    template<typename First, typename Last, typename Pred>
    struct choose_find_if<First, Last, Pred, false>
        : main_find_if<First, Last, Pred>
    {};

    template<typename Iter, typename Pred, int n, int unrolling>
    struct unroll_again;

    template <typename Iter, typename Pred, int offset>
    struct apply_offset_filter
    {
        typedef typename result_of::advance_c<Iter, offset>::type Shifted;
        typedef typename
            mpl::apply1<
                Pred
              , Shifted
            >::type
        type;
        BOOST_STATIC_CONSTANT(int, value = type::value);
    };

    template<typename Iter, typename Pred, int n>
    struct unrolled_find_if
    {
        typedef typename mpl::eval_if<
            apply_filter<Iter, Pred>,
            mpl::identity<Iter>,
            mpl::eval_if<
              apply_offset_filter<Iter, Pred, 1>,
              result_of::advance_c<Iter, 1>,
              mpl::eval_if<
                apply_offset_filter<Iter, Pred, 2>,
                result_of::advance_c<Iter, 2>,
                mpl::eval_if<
                  apply_offset_filter<Iter, Pred, 3>,
                  result_of::advance_c<Iter, 3>,
                  unroll_again<
                    Iter,
                    Pred,
                    n,
                    4> > > > >::type type;
    };

    template<typename Iter, typename Pred>
    struct unrolled_find_if<Iter, Pred, 3>
    {
        typedef typename mpl::eval_if<
            apply_filter<Iter, Pred>,
            mpl::identity<Iter>,
            mpl::eval_if<
              apply_offset_filter<Iter, Pred, 1>,
              result_of::advance_c<Iter, 1>,
              mpl::eval_if<
                apply_offset_filter<Iter, Pred, 2>,
                result_of::advance_c<Iter, 2>,
                result_of::advance_c<Iter, 3> > > >::type type;
    };

    template<typename Iter, typename Pred>
    struct unrolled_find_if<Iter, Pred, 2>
    {
        typedef typename mpl::eval_if<
            apply_filter<Iter, Pred>,
            mpl::identity<Iter>,
            mpl::eval_if<
              apply_offset_filter<Iter, Pred, 1>,
              result_of::advance_c<Iter, 1>,
              result_of::advance_c<Iter, 2> > >::type type;
    };

    template<typename Iter, typename Pred>
    struct unrolled_find_if<Iter, Pred, 1>
    {
        typedef typename mpl::eval_if<
            apply_filter<Iter, Pred>,
            mpl::identity<Iter>,
            result_of::advance_c<Iter, 1> >::type type;
    };

    template<typename Iter, typename Pred, int n, int unrolling>
    struct unroll_again
    {
        typedef typename unrolled_find_if<
            typename result_of::advance_c<Iter, unrolling>::type,
            Pred,
            n-unrolling>::type type;
    };

    template<typename Iter, typename Pred>
    struct unrolled_find_if<Iter, Pred, 0>
    {
        typedef Iter type;
    };

    template<typename First, typename Last, typename Pred>
    struct choose_find_if<First, Last, Pred, true>
    {
        typedef typename result_of::distance<First, Last>::type N;
        typedef typename unrolled_find_if<First, Pred, N::value>::type type;
    };

    template <typename First, typename Last, typename Pred>
    struct static_find_if
    {
        typedef typename
            choose_find_if<
                First
              , Last
              , typename mpl::lambda<Pred>::type
              , is_base_of<random_access_traversal_tag, typename traits::category_of<First>::type>::value
            >::type
        type;

        template <typename Iterator>
        static type
        recursive_call(Iterator const& iter, mpl::true_)
        {
            return iter;
        }

        template <typename Iterator>
        static type
        recursive_call(Iterator const& iter, mpl::false_)
        {
            return recursive_call(fusion::next(iter));
        }

        template <typename Iterator>
        static type
        recursive_call(Iterator const& iter)
        {
            typedef result_of::equal_to<Iterator, type> found;
            return recursive_call(iter, found());
        }

        template <typename Iterator, typename Tag>
        static type
        choose_call(Iterator const& iter, Tag)
        {
            return recursive_call(iter);
        }

        template <typename Iterator>
        static type
        choose_call(Iterator const& iter, random_access_traversal_tag)
        {
            typedef typename result_of::distance<Iterator, type>::type N;
            return fusion::advance<N>(iter);
        }

        template <typename Iterator>
        static type
        iter_call(Iterator const& iter)
        {
            return choose_call(iter, typename traits::category_of<Iterator>::type());
        }

        template <typename Sequence>
        static type
        call(Sequence& seq)
        {
            return iter_call(fusion::begin(seq));
        }
    };

    template <typename Sequence, typename Pred>
    struct result_of_find_if
    {
        typedef
            static_find_if<
                typename result_of::begin<Sequence>::type
              , typename result_of::end<Sequence>::type
              , Pred
            >
        filter;

        typedef typename filter::type type;
    };
}}}

#endif

max_stars_repo_name: PXLVision/opengv

max_issues_repo_name: isuhao/klib

max_forks_repo_name: isuhao/klib


text:
/*
 * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The OpenAirInterface Software Alliance licenses this file to You under
 * the OAI Public License, Version 1.1  (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.openairinterface.org/?page_id=698
 *
 * 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.
 *-------------------------------------------------------------------------------
 * For more information about the OpenAirInterface (OAI) Software Alliance:
 *      contact@openairinterface.org
 */

/*! \file nssf_http2-server.h
 \brief
 \author  Rohan Kharade
 \company Openairinterface Software Allianse
 \date 2021
 \email: rohan.kharade@openairinterface.org
 */

#ifndef FILE_NSSF_APP_HPP_SEEN
#define FILE_NSSF_APP_HPP_SEEN

#include "common_root_types.h"

#include <boost/atomic.hpp>

#include <map>
#include <memory>
#include <set>
#include <string>
#include <thread>

#include "3gpp_29.500.h"
#include "AuthorizedNetworkSliceInfo.h"
#include "PatchItem.h"
#include "PlmnId.h"
#include "ProblemDetails.h"
#include "SliceInfoForPDUSession.h"
#include "SliceInfoForRegistration.h"
#include "SliceInfoForUEConfigurationUpdate.h"
#include "Tai.h"

namespace nssf {

using namespace oai::nssf_server::model;

class nssf_app {
 private:
  std::thread::id thread_id;
  std::thread thread;

 public:
  explicit nssf_app(const std::string& config_file);
  nssf_app(nssf_app const&) = delete;
  void operator=(nssf_app const&) = delete;

  virtual ~nssf_app();

  /*
   * Handle a Register NF Instance request
   * @param [const std::string &] nf_instance_id: Instance ID
   * @param [NFProfile &] nf_profile: NF profile
   * @param [int &] http_code: HTTP code used to return to the consumer
   * @param [const uint8_t] http_version: HTTP version
   * @param [ProblemDetails &] problem_details: Store details of the error
   * @return void
   */

  void handle_slice_info_for_registration(
      const SliceInfoForRegistration& slice_info, const Tai& tai,
      const PlmnId& home_plmnid, const std::string& features, int& http_code,
      const uint8_t http_version, const ProblemDetails& problem_details);

  void handle_slice_info_for_pdu_session(
      const SliceInfoForPDUSession& slice_info, const Tai& tai,
      const PlmnId& home_plmnid, const std::string& features, int& http_code,
      const uint8_t http_version, const ProblemDetails& problem_details,
      AuthorizedNetworkSliceInfo& auth_slice_info);

  void handle_slice_info_for_ue_cu(
      const SliceInfoForUEConfigurationUpdate& slice_info, const Tai& tai,
      const PlmnId& home_plmnid, const std::string& features, int& http_code,
      const uint8_t http_version, const ProblemDetails& problem_details);
};
}  // namespace nssf
#endif /* FILE_NSSF_APP_HPP_SEEN */

ext: hpp


text:
// Copyright (c) 2019 Baidu, Inc. All Rights Reserved.
//
// 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.

/**
 * @file baikal_client_logic_db.cpp
 * @author liuhuicong(com@baidu.com)
 * @date 2015/11/16 11:25:18
 * @brief
 *
 **/

#include "baikal_client_logic_db.h"
#include <boost/algorithm/string.hpp>
#ifdef BAIDU_INTERNAL
#include "com_log.h"
#endif
#include "shard_operator_mgr.h"

using std::vector;
using std::string;

namespace baikal {
namespace client {
LogicDB::LogicDB(const string& logic_db_name) :
        _name(logic_db_name) {}

int LogicDB::get_table_id(
            const string& table_name,
            uint32_t partition_key,
            bool* split_table,
            int* table_id) {
    vector<TableSplit>::iterator iter = _table_infos.begin();
    for (; iter != _table_infos.end(); ++iter) {
        if (iter->table_name == table_name) {
            if (iter->table_split_function.empty()) {
                *split_table = false;
                *table_id = 0;
                return SUCCESS;
            }
            ShardOperatorMgr* mgr = ShardOperatorMgr::get_s_instance();
            uint32_t id = 0;
            int ret = mgr->evaluate(iter->table_split_function, partition_key, &id);
            if (ret < 0) {
                CLIENT_WARNING("table id compute fail, table_name:%s", table_name.c_str());
                return ret;
            }
            *table_id = id;
            *split_table = true;
            return SUCCESS;
        }
    }
    //table_name表在配置文件中未配置，说明不分表
    *split_table = false;
    *table_id = 0;
    return SUCCESS;
}

string LogicDB::get_name() const {
    return _name;
}

int LogicDB::add_table_split(
        const string& table_name,
        const vector<string>& table_split_function,
        int table_split_count) {
    if (table_name.empty()
            || table_split_count <= 0
            || (table_split_count != 1 && table_split_function.empty())) {
        CLIENT_WARNING("table split configure is not right");
        return CONFPARAM_ERROR;
    }
    vector<string> names;
    boost::split(names, table_name, boost::is_any_of("|"), boost::token_compress_on);
    vector<string>::iterator it = names.begin();
    for (; it != names.end(); ++it) {
        string name(*it);
        boost::trim(name);
        TableSplit table_split(name, table_split_count, table_split_function);
        _table_infos.push_back(table_split);
    }
    return SUCCESS;
}

vector<TableSplit> LogicDB::get_table_infos() const {
    return _table_infos;
}
}
}

/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */

ext: cpp

max_stars_repo_name: lvxinup/BaikalDB

max_issues_repo_name: lvxinup/BaikalDB

max_forks_repo_name: lvxinup/BaikalDB


text:
#define BOOST_TEST_MODULE Sort
#include <boost/thread.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/reductor.hpp>
#include "context_setup.hpp"

BOOST_AUTO_TEST_CASE(threads)
{
    const size_t n = 1024 * 1024;

    auto run = [n](vex::backend::command_queue queue, cl_long *s) {
        std::vector<vex::backend::command_queue> q(1, queue);
        vex::vector<int> x(q, n);
        x = 1;
        vex::Reductor<cl_long, vex::SUM> sum(q);
        *s = sum(x);
    };

    boost::ptr_vector< boost::thread > threads;
    std::vector< cl_long       > results(ctx.size(), 0);

    for(unsigned d = 0; d < ctx.size(); ++d) {
        threads.push_back( new boost::thread(run, ctx.queue(d), &results[d]) );
    }

    cl_long sum = 0;
    for(unsigned d = 0; d < ctx.size(); ++d) {
        threads[d].join();
        sum += results[d];
    }

    BOOST_CHECK_EQUAL(sum, n * ctx.size());
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: lkusch/Kratos

max_issues_repo_name: lkusch/Kratos

max_forks_repo_name: lkusch/Kratos


text:
#ifndef MDL_PAILLER_HPP
#define MDL_PAILLER_HPP
#include <NTL/ZZ.h>
#include <memory>
#include <vector>
namespace MDL {
namespace Paillier {
struct Encryption {};
//forward declaration
class Ctxt;
typedef std::vector<NTL::ZZ> PrimeSet;

class PubKey {
public:
    explicit PubKey(const NTL::ZZ &n);
    PubKey(const PubKey &oth);
    PubKey& operator=(const PubKey &oth) = delete;
    bool operator==(const PubKey &oth) const;
    ~PubKey() {}
    void Encrypt(Ctxt &ctxt, const NTL::ZZ &plain) const;
    void Encrypt(Ctxt &ctxt, const long plain) const;
    void Pack(Ctxt &ctxt, const std::vector<long> &slots, int bits) const;
    void Pack(Ctxt &ctxt, long m, int bits) const;
    const NTL::ZZ& GetN() const;
    const NTL::ZZ& GetG() const;
    const NTL::ZZ& GetN2() const;
    const PrimeSet& GetPrimes() const;
    PrimeSet GetPrimes(long bits) const;
    long bits_per_prime() const;
    long bits_all_prime() const;
private:
    class PubKeyImp;
    std::shared_ptr<PubKeyImp> imp = nullptr;
};

class SecKey {
public:
    explicit SecKey(const NTL::ZZ &p, const NTL::ZZ &q, const PubKey &pk);
    SecKey(const SecKey &oth);
    SecKey& operator=(const SecKey &oth) = delete;
    bool operator==(const SecKey &oth) const;
    ~SecKey() {}
    void Encrypt(Ctxt &ctxt, const NTL::ZZ &plain) const;
    void Encrypt(Ctxt &ctxt, const long plain) const;
    void Decrypt(NTL::ZZ &plain, const Ctxt &ctxt) const;
    void Decrypt(long &plain, const Ctxt &ctxt) const;
    void Unpack(std::vector<NTL::ZZ> &slots, const Ctxt &ctxt, int bits) const;
    const PubKey &GetPk() const;
private:
    class SecKeyImp; // implementation
    std::shared_ptr<SecKeyImp> imp = nullptr;
};

class Ctxt {
public:
    explicit Ctxt(const PubKey &pk);
    Ctxt(const Ctxt &oth);
    Ctxt& operator=(const Ctxt &oth) = delete;
    Ctxt& operator+=(const Ctxt &oth);
    Ctxt& operator+=(long v);
    Ctxt& operator+=(const NTL::ZZ &v);
    Ctxt& operator-=(const Ctxt &oth);
    Ctxt& operator-=(long v);
    Ctxt& operator-=(const NTL::ZZ &v);
    Ctxt& operator*=(long v);
    Ctxt& operator*=(const NTL::ZZ &v);
    Ctxt& negate();
    ~Ctxt() {}
    void SetCtxt(const NTL::ZZ &number);
    void SetCtxt(const long number);
    const PubKey& GetPk() const;
    const NTL::ZZ& GetValue() const;
private:
    class CtxtImp;
    std::shared_ptr<CtxtImp> imp = nullptr;
};

std::pair<SecKey, PubKey> GenKey(long bits);
}// namespace Paillier
}// namespace MDL
#endif // MDL_PAILLER_HPP

max_stars_repo_name: fionser/MDLHElib

max_issues_repo_name: fionser/MDLHElib

max_forks_repo_name: fionser/MDLHElib


text:
//////////////////////////////////////////////////////////////////////////////////////
// distribution::toolkit::distributions::::distributions::exponential::include.hpp   //
//                                                                                //
//  (C) Copyright 2009 Erwann Rogard                                                //
//  Use, modification and distribution are subject to the                           //
//  Boost Software License, Version 1.0. (See accompanying file                     //
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)                //
//////////////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_EXPONENTIAL_INCLUDE_HPP_ER_2009
#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_EXPONENTIAL_INCLUDE_HPP_ER_2009

#include <boost/math/distributions/exponential.hpp>
#include <boost/statistics/detail/distribution_toolkit/distributions/exponential/description.hpp>
#include <boost/statistics/detail/distribution_toolkit/distributions/exponential/derivative_log_unnormalized_pdf.hpp>
#include <boost/statistics/detail/distribution_toolkit/distributions/exponential/is_math_distribution.hpp>
#include <boost/statistics/detail/distribution_toolkit/distributions/exponential/log_unnormalized_pdf.hpp>
#include <boost/statistics/detail/distribution_toolkit/distributions/exponential/random.hpp>
#include <boost/statistics/detail/distribution_toolkit/distributions/exponential/os.hpp>

#endif


text:
#include "ndnrtc-wrapper.hpp"

#include <android/log.h>

#include <algorithm>
#include <boost/make_shared.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread.hpp>
#include <ndn-cpp/security/key-chain.hpp>
#include <ndn-cpp/security/identity/memory-private-key-storage.hpp>
#include <ndn-cpp/security/identity/memory-identity-storage.hpp>
#include <ndn-cpp/security/policy/no-verify-policy-manager.hpp>
#include <ndn-cpp/threadsafe-face.hpp>

#include <ndnrtc/params.hpp>
#include <ndnrtc/remote-stream.hpp>
#include <ndnrtc/local-stream.hpp>
#include <ndnrtc/simple-log.hpp>

#include <string.h>
#include <jni.h>

#define CLIENT_PRODUCER
// #define CLIENT_CONSUMER

static std::map<std::string, std::string> g_params;
static int g_run_time_sec = 5;

// the function below was taken from here: https://github.com/named-data-mobile/NFD-android/blob/master/app/src/main/jni/nfd-wrapper.cpp
std::map<std::string, std::string>
getParams(JNIEnv* env, jobject jParams)
{
  std::map<std::string, std::string> params;

  jclass jcMap = env->GetObjectClass(jParams);
  jclass jcSet = env->FindClass("java/util/Set");
  jclass jcIterator = env->FindClass("java/util/Iterator");
  jclass jcMapEntry = env->FindClass("java/util/Map$Entry");

  jmethodID jcMapEntrySet      = env->GetMethodID(jcMap,      "entrySet", "()Ljava/util/Set;");
  jmethodID jcSetIterator      = env->GetMethodID(jcSet,      "iterator", "()Ljava/util/Iterator;");
  jmethodID jcIteratorHasNext  = env->GetMethodID(jcIterator, "hasNext",  "()Z");
  jmethodID jcIteratorNext     = env->GetMethodID(jcIterator, "next",     "()Ljava/lang/Object;");
  jmethodID jcMapEntryGetKey   = env->GetMethodID(jcMapEntry, "getKey",   "()Ljava/lang/Object;");
  jmethodID jcMapEntryGetValue = env->GetMethodID(jcMapEntry, "getValue", "()Ljava/lang/Object;");

  jobject jParamsEntrySet = env->CallObjectMethod(jParams, jcMapEntrySet);
  jobject jParamsIterator = env->CallObjectMethod(jParamsEntrySet, jcSetIterator);
  jboolean bHasNext = env->CallBooleanMethod(jParamsIterator, jcIteratorHasNext);

  while (bHasNext) {
    jobject entry = env->CallObjectMethod(jParamsIterator, jcIteratorNext);

    jstring jKey = (jstring)env->CallObjectMethod(entry, jcMapEntryGetKey);
    jstring jValue = (jstring)env->CallObjectMethod(entry, jcMapEntryGetValue);

    const char* cKey = env->GetStringUTFChars(jKey, nullptr);
    const char* cValue = env->GetStringUTFChars(jValue, nullptr);

    params.insert(std::make_pair(cKey, cValue));

    env->ReleaseStringUTFChars(jKey, cKey);
    env->ReleaseStringUTFChars(jValue, cValue);

    bHasNext = env->CallBooleanMethod(jParamsIterator, jcIteratorHasNext);
  }

  return params;
}

// the function below was adapted from here: https://github.com/remap/ndnrtc/blob/4b2eb4001072ec00b96ab3d0c366149c9a536ac9/cpp/client/src/client.cpp
void runProcessLoop(boost::asio::io_service &io, int runTimeSec)
{
  boost::asio::deadline_timer runTimer(io);
  runTimer.expires_from_now(boost::posix_time::seconds(runTimeSec));
  runTimer.wait();
}

JNIEXPORT void JNICALL
Java_com_example_nrtpttv2_MainActivity_startNdnRtc(JNIEnv* env, jclass, jobject jParams) {

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Got to the beginning of the startNdnRtc function.");

  int err = 0;

  g_params = getParams(env, jParams);
  ::setenv("HOME", g_params["homePath"].c_str(), true);

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Finished setting the HOME variable: %s.", g_params["homePath"].c_str());
  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Got the directory of the application cache: %s.", g_params["cachePath"].c_str());

  ndnlog::new_api::Logger::initAsyncLogging();
  ndnlog::new_api::Logger::getLogger(g_params["cachePath"] + "/log.txt").setLogLevel(ndnlog::NdnLoggerDetailLevelAll);

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Finished creating the logger object and setting up logging.");

  boost::asio::io_service io;
  std::shared_ptr<boost::asio::io_service::work> work(std::make_shared<boost::asio::io_service::work>(io));
  boost::thread t([&io, &err]() {
      try
  	{
  	  io.run();
  	}
      catch (std::exception &e)
  	{
  	  __android_log_print(ANDROID_LOG_ERROR, "NDNRTC-WRAPPER", "Client caught exception while running: %s\n", e.what());
  	  err = 1;
  	}
    });

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Finished adding work to and running the io object.");

  auto keyChain = std::make_shared<ndn::KeyChain>();
  auto defaultIdentity = keyChain->createIdentityV2(ndn::Name("/default/identity"));
  keyChain->setDefaultIdentity(*defaultIdentity);

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Default identity of keychain object: %s.",
		      keyChain->getDefaultIdentity().toUri().c_str());

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Finished creating the keychain object.");

  std::shared_ptr<ndn::Face> face(std::make_shared<ndn::ThreadsafeFace>(io));
  face->setCommandSigningInfo(*keyChain, keyChain->getDefaultCertificateName());

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Finished creating the face object.");

#ifdef CLIENT_CONSUMER

  ndnrtc::RemoteAudioStream remoteStream(io,
  					 face,
  					 keyChain,
  					 "/ndnrtc",
  					 "nrtpttv2");
  remoteStream.setLogger(ndnlog::new_api::Logger::getLoggerPtr(g_params["cachePath"] + "/log.txt"));

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Finished creating the remote audio stream object.");

  remoteStream.start("pcmu");

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Finished starting the remote audio stream object.");

  runProcessLoop(io, g_run_time_sec);

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Process loop finished running.");

  remoteStream.stop();

#endif

#ifdef CLIENT_PRODUCER

  face->registerPrefix(ndn::Name("/ndnrtc"),
		       [](const std::shared_ptr<const ndn::Name> &prefix,
			  const std::shared_ptr<const ndn::Interest> &interest,
			  ndn::Face &face, uint64_t, const std::shared_ptr<const ndn::InterestFilter> &) {
			 __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Unexpected incoming interest %s.", interest->getName().toUri().c_str());
		       },
		       [](const std::shared_ptr<const ndn::Name> &p) {
			 __android_log_print(ANDROID_LOG_ERROR, "NDNRTC-WRAPPER", "Failed to register prefix %s.", p->toUri().c_str());
		       },
		       [](const std::shared_ptr<const ndn::Name> &p, uint64_t) {
			 __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Successfully registered prefix %s.", p->toUri().c_str());
		       });

  ndnrtc::MediaStreamParams params;
  params.streamName_ = "nrtpttv2";
  params.synchronizedStreamName_ = "";
  params.captureDevice_.deviceId_ = 0;
  params.type_ = ndnrtc::MediaStreamParams::MediaStreamType::MediaStreamTypeAudio;
  params.producerParams_.segmentSize_ = 1000;

  ndnrtc::MediaStreamSettings settings(io, params);
  settings.face_ = face.get();
  settings.keyChain_ = keyChain.get();
  settings.params_.addMediaThread(ndnrtc::AudioThreadParams("sound"));

  ndnrtc::LocalAudioStream localStream("/ndnrtc", settings);
  localStream.setLogger(ndnlog::new_api::Logger::getLoggerPtr(g_params["cachePath"] + "/log.txt"));

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Finished creating the local audio stream object.");

  localStream.start();

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Finished starting the local audio stream object.");

  runProcessLoop(io, g_run_time_sec);

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Process loop finished running.");

  localStream.stop();

#endif

  face->shutdown();
  face.reset();
  work.reset();
  t.join();
  io.stop();

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Clean up finished.");

  __android_log_print(ANDROID_LOG_DEBUG, "NDNRTC-WRAPPER", "Got to the end of the startNdnRtc function.");

}


text:
#pragma once

#ifndef GOSSIP_SEED_HPP
#define GOSSIP_SEED_HPP

#include <string>

#include <boost/asio/ip/tcp.hpp>

namespace es {
namespace tcp {

class gossip_seed
{
public:
	explicit gossip_seed(
		boost::asio::ip::tcp::endpoint const& endpoint,
		std::string const& host_header = ""
	)
		: endpoint_(endpoint), host_header_(host_header)
	{}

	boost::asio::ip::tcp::endpoint const& endpoint() const { return endpoint_; }
	std::string const& host_header() const { return host_header_; }

private:
	boost::asio::ip::tcp::endpoint endpoint_;
	std::string host_header_;
};

} // tcp
} // es

#endif // GOSSIP_SEED_HPP


text:
/* $Id: test_serialization.cpp 48153 2011-01-01 15:57:50Z mordante $ */
/*
   Copyright (C) 2009 - 2011 by Karol Nowak <grywacz@gmail.com>
   Part of the Battle for Wesnoth Project http://www.wesnoth.org/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

#define GETTEXT_DOMAIN "wesnoth-test"

#include <vector>
#include <string>
#include "serialization/string_utils.hpp"
#include <boost/test/auto_unit_test.hpp>

BOOST_AUTO_TEST_CASE( utils_join_test )
{
	std::vector<std::string> fruit;

	BOOST_CHECK( utils::join(fruit) == "" );

	fruit.push_back("apples");

	BOOST_CHECK( utils::join(fruit) == "apples" );

	fruit.push_back("oranges");
	fruit.push_back("lemons");

	BOOST_CHECK( utils::join(fruit) == "apples,oranges,lemons" );
}

max_stars_repo_name: blackberry/Wesnoth

max_issues_repo_name: blackberry/Wesnoth

max_forks_repo_name: blackberry/Wesnoth


text:
#include <iostream>
#include <fstream>
#include <vector>
#include <Eigen/Dense>

using namespace std;
using namespace Eigen;

// lee la matriz desde el archivo de texto path. Números separados por espacios
MatrixXd load_matrix(string path) {
	vector <double> raw_data;
	ifstream file(path);
	string line, element;
	stringstream ss;
	int rows=0,cols=0;

	while ( getline(file,line) ) { // leer línea del archivo
		ss = stringstream(line); // convertir la línea en un stream
		while( ss >> element ) { // leer cada elemento de la línea, separado por espacios
			raw_data.push_back(stod(element)); // convertir a double y echar al vector
		}
		rows++; // por cada fila terminada se aumenta el número de filas
	}
	file.close();
	cols = raw_data.size()/rows;
	return Map<Matrix<double, Dynamic, Dynamic, RowMajor>>(raw_data.data(),rows,cols);
}

// guarda la matriz como un archivo de texto en path. Números separados por espacios
void save_matrix(string path, MatrixXd matrix) {
	ofstream file(path);
	file << matrix; // echar matriz al archivo
	file.close();
}

// retorna una copia de la matriz M sin la fila dada por el índice
MatrixXd remove_row(MatrixXd M, int remove_index) {
	int rows = M.rows()-1;
	int cols = M.cols();
	M.block(remove_index,0,rows-remove_index,cols) = M.bottomRows(rows-remove_index);
	M.conservativeResize(rows,cols);
	return M;
}
// retorna una copia de la matriz M sin la columna dada por el índice
MatrixXd remove_col(MatrixXd M, int remove_index) {
	int rows = M.rows();
	int cols = M.cols()-1;
	M.block(0,remove_index,rows,cols-remove_index) = M.rightCols(cols-remove_index);
	M.conservativeResize(rows,cols);
	return M;
}
// retorna una copia de la matriz M sin la columna J y sin la fila I
MatrixXd minor_matrix(MatrixXd M, int I, int J) {
	return remove_col(remove_row(M,I),J);
}

// calcula el determinante de una matriz cuadrada M
double det(MatrixXd M){
	int rows = M.rows();
	int cols = M.cols();

	double d = 0.0;

	if (rows != cols) {
		cerr << "cannot take det of non-square matrix:" << endl << M << endl;
		abort();
	}
	else if (rows == 1 && cols == 1) {
		d = M(0,0);
	} else {
		for(int j=0; j<cols; j++){
			d += pow((-1.0),j) * M(0,j) * det(minor_matrix(M,0,j));
		}
	}
	return d;
}

// retorna el cofactor i,j de la matriz M
double cofactor(MatrixXd M, int i, int j){
	return pow(-1.0,i+j)*det(minor_matrix(M,i,j));
}

MatrixXd cramer_inverse(MatrixXd M) {
	double M_det = det(M);
	if (M_det == 0) {
		cout << "cannot take inverse of singular matrix:" << endl << M << endl;
		abort();
	}
	MatrixXd Adj(M); // Adjugate matrix
	int n = M.rows();

	for (int i=0; i<n; i++) {
		for (int j=0; j<n; j++) {
			Adj(i,j) = cofactor(M,j,i); // note j,i, the transpose of the cofactor matrix
		}
	}

	return Adj/M_det;
}

// matriz elemental nxn para cambiar la fila i por la j
MatrixXd elemental_swap(int i, int j, int n){
	MatrixXd E = MatrixXd::Identity(n,n);
	E(i,i) = 0.;
	E(j,j) = 0.;
	E(i,j) = 1.;
	E(j,i) = 1.;
	return E;
}
// matriz elemental nxn para multiplicar la fila i por la constante k
MatrixXd elemental_multiplication(double k, int i, int n){
	MatrixXd E = MatrixXd::Identity(n,n);
	E(i,i) = k;
	return E;
}
// matriz elemental nxn para sumar k veces la fila j a la fila i
MatrixXd elemental_addition(double k, int i, int j, int n){
	MatrixXd E = MatrixXd::Identity(n,n);
	E(i,j) = k;
	return E;
}

MatrixXd gauss_jordan_inverse(MatrixXd M) {
	if (det(M) == 0) {
		cout << "cannot take inverse of singular matrix:" << endl << M << endl;
		abort();
	}
	int n = M.rows();
	int k;
	MatrixXd E = MatrixXd::Identity(n,n);
	MatrixXd E_new;

	// grant pivots
	for (int i=0; i<n; i++) {
		// k is the first row that is nonzero on column i
		k = i;
		while (M(k,i) == 0.0) { k++;}
		E_new = elemental_swap(k,i,n);
		E = E_new * E;
		M = E_new * M;
	}
	// put in triangular form
	for (int j=0; j<n; j++) {
		for (int i=j+1; i<n; i++) {
			if (M(i,j) != 0.0) {
				E_new = elemental_addition(-M(i,j)/M(j,j),i,j,n);
				E = E_new * E;
				M = E_new * M;
			}
		}
	}
	// force ones in diagonal
	for (int i=0; i<n; i++) {
		E_new = elemental_multiplication(1/M(i,i),i,n);
		E = E_new * E;
		M = E_new * M;
	}
	// backsubstitute
	for (int j=n-1; j>=0; j--) {
		for (int i=0; i<j; i++) {
			//cout << i << " " << j << endl;
			E_new = elemental_addition(-M(i,j),i,j,n);
			E = E_new * E;
			M = E_new * M;
		}
	}

	return E;
}

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

	string input_filename;

	if (argc == 2) {
		input_filename = (string)argv[1];
	} else {
		cout << "Insert filename for input matrix: ";
		cin >> input_filename;
	}

	MatrixXd m = load_matrix(input_filename);

	save_matrix("eigen.dat",m.inverse());
	save_matrix("gauss_jordan.dat",gauss_jordan_inverse(m));
	save_matrix("cramer.dat",cramer_inverse(m));
}


text:
#include "sparta/kernel/MemoryProfiler.hpp"
#include "sparta/trigger/ExpressionTrigger.hpp"
#include "sparta/app/Simulation.hpp"
#include "sparta/parsers/YAMLTreeEventHandler.hpp"
#include "sparta/utils/ValidValue.hpp"

#include <gperftools/malloc_extension.h>

#include <map>
#include <set>
#include <stack>

#include <boost/filesystem.hpp>

namespace sparta {

class ProfilerConfig {
public:
    std::string report_name;
    std::string dest_file;
    std::set<MemoryProfiler::Phase> phases;
    std::string update_type;
    std::string update_expression;

    ProfilerConfig(const std::string & report_name,
                   const std::string & dest_file,
                   const std::set<MemoryProfiler::Phase> & phases,
                   const std::string & update_type,
                   const std::string & update_expression) :
        report_name(report_name),
        dest_file(dest_file),
        phases(phases),
        update_type(update_type),
        update_expression(update_expression)
    {}
};

typedef std::vector<ProfilerConfig> ProfilerConfigurations;

class MemoryProfilerConfigFileParserYAML
{
    class MemoryProfilerConfigFileEventHandlerYAML :
        public sparta::YAMLTreeEventHandler
    {
    private:
        std::stack<bool> in_report_stack_;
        std::string report_name_;
        std::string dest_file_;
        std::set<MemoryProfiler::Phase> phases_;
        std::string update_type_;
        std::string update_expression_;
        ProfilerConfigurations configs_;

        /*!
         * \brief Reserved keywords for this parser's dictionary
         */
        static constexpr char KEY_CONTENT[]         = "content";
        static constexpr char KEY_MEM_REPORT[]      = "memory-report";
        static constexpr char KEY_NAME[]            = "name";
        static constexpr char KEY_DEST_FILE[]       = "dest_file";
        static constexpr char KEY_PHASES[]          = "phases";
        static constexpr char KEY_UPDATE_COUNT[]    = "update-count";
        static constexpr char KEY_UPDATE_CYCLE[]    = "update-cycles";
        static constexpr char KEY_UPDATE_TIME[]     = "update-time";
        static constexpr char KEY_UPDATE_WHENEVER[] = "update-whenever";

        virtual bool handleEnterMap_(
            const std::string & key,
            NavVector & context) override final
        {
            (void) context;

            if (key == KEY_CONTENT) {
                return false;
            }

            if (key == KEY_MEM_REPORT) {
                if (!in_report_stack_.empty()) {
                    throw SpartaException(
                        "Nested memory report definitions are not supported");
                }
                prepareForNextConfig_();
                in_report_stack_.push(true);
                return false;
            }

            if (!key.empty()) {
                throw SpartaException(
                    "Unrecognized key found in memory profile definition file: ") << key;
            }

            return false;
        }

        virtual void handleLeafScalar_(
            TreeNode * n,
            const std::string & value,
            const std::string & assoc_key,
            const std::vector<std::string> & captures,
            node_uid_t uid) override final
        {
            (void) n;
            (void) captures;
            (void) uid;

            if (assoc_key == KEY_NAME) {
                report_name_ = value;
            } else if (assoc_key == KEY_DEST_FILE) {
                dest_file_ = value;
            } else if (assoc_key == KEY_PHASES) {
                std::string no_whitespace(value);
                boost::erase_all(no_whitespace, " ");
                std::vector<std::string> phases;
                boost::split(phases, no_whitespace, boost::is_any_of(","));

                bool all_phases = false;
                for (const auto & phase : phases) {
                    if (phase == "build") {
                        phases_.insert(MemoryProfiler::Phase::Build);
                    } else if (phase == "configure") {
                        phases_.insert(MemoryProfiler::Phase::Configure);
                    } else if (phase == "bind") {
                        phases_.insert(MemoryProfiler::Phase::Bind);
                    } else if (phase == "simulate") {
                        phases_.insert(MemoryProfiler::Phase::Simulate);
                    } else if (phase == "all") {
                        all_phases = true;
                    } else {
                        throw SpartaException("Invalid memory profile phase specified: ") << phase;
                    }
                }

                if (all_phases) {
                    if (phases.size() > 1) {
                        std::cerr << "The following memory profiler phases were specified: \n"
                                  << "\t" << value << "\n"
                                  << "Note that the 'all' keyword has forced every simulation "
                                  << "phase to be included in the profile." << std::endl;
                    }
                    phases_.clear();
                }
            } else {
                sparta_assert(assoc_key == KEY_UPDATE_COUNT ||
                            assoc_key == KEY_UPDATE_CYCLE ||
                            assoc_key == KEY_UPDATE_TIME  ||
                            assoc_key == KEY_UPDATE_WHENEVER);
                update_type_ = assoc_key;
                update_expression_ = value;
            }
        }

        virtual bool handleExitMap_(
            const std::string & key,
            const NavVector & context) override final
        {
            (void) context;

            if (key == KEY_MEM_REPORT) {
                sparta_assert(!report_name_.empty());
                sparta_assert(!dest_file_.empty());
                sparta_assert(!update_type_.empty());
                sparta_assert(!update_expression_.empty());

                in_report_stack_.pop();

                configs_.emplace_back(
                    report_name_,
                    dest_file_,
                    phases_,
                    update_type_,
                    update_expression_);
            }

            return false;
        }

        virtual bool isReservedKey_(
            const std::string & key) const override final
        {
            return (key == KEY_CONTENT           ||
                    key == KEY_MEM_REPORT        ||
                    key == KEY_NAME              ||
                    key == KEY_DEST_FILE         ||
                    key == KEY_PHASES            ||
                    key == KEY_UPDATE_COUNT      ||
                    key == KEY_UPDATE_CYCLE      ||
                    key == KEY_UPDATE_TIME       ||
                    key == KEY_UPDATE_WHENEVER);
        }

        void prepareForNextConfig_() {
            report_name_ = "Memory usage statistics";
            dest_file_ = "mem-stats.csv";
            update_type_ = "update-cycles";
            update_expression_ = "10k";
        }

    public:
        MemoryProfilerConfigFileEventHandlerYAML(
            const std::string & def_file,
            NavVector device_trees) :
                sparta::YAMLTreeEventHandler(def_file, device_trees, false)
        {
        }

        const ProfilerConfigurations & getConfigs() const
        {
            return configs_;
        }
    };

    std::unique_ptr<MemoryProfilerConfigFileEventHandlerYAML> handler_;

public:
    explicit MemoryProfilerConfigFileParserYAML(const std::string & def_file) :
        fin_(),
        parser_(),
        def_file_(def_file)
    {
        sparta_assert(boost::filesystem::exists(def_file_),
                   ("File '" + def_file + "' cannot be found"));
        fin_.open(def_file.c_str(), std::ios::in);
        sparta_assert(fin_.is_open());
        parser_.reset(new YP::Parser(fin_));
    }

    explicit MemoryProfilerConfigFileParserYAML(std::istream & content) :
        fin_(),
        parser_(new YP::Parser(content)),
        def_file_("<istream>")
    {
    }

    const ProfilerConfigurations & parseConfigurations(sparta::TreeNode * context)
    {
        std::shared_ptr<sparta::YAMLTreeEventHandler::NavNode> scope(
            new sparta::YAMLTreeEventHandler::NavNode({
                nullptr, context, {}, 0}));

        handler_.reset(new MemoryProfilerConfigFileEventHandlerYAML(def_file_, {scope}));

        while(parser_->HandleNextDocument(*((YP::EventHandler*)handler_.get()))) {}

        return handler_->getConfigs();
    }

private:
    std::ifstream fin_;
    std::unique_ptr<YP::Parser> parser_;
    std::string def_file_;
};

constexpr char MemoryProfilerConfigFileParserYAML::
    MemoryProfilerConfigFileEventHandlerYAML::KEY_CONTENT[];

constexpr char MemoryProfilerConfigFileParserYAML::
    MemoryProfilerConfigFileEventHandlerYAML::KEY_MEM_REPORT[];

constexpr char MemoryProfilerConfigFileParserYAML::
    MemoryProfilerConfigFileEventHandlerYAML::KEY_NAME[];

constexpr char MemoryProfilerConfigFileParserYAML::
    MemoryProfilerConfigFileEventHandlerYAML::KEY_DEST_FILE[];

constexpr char MemoryProfilerConfigFileParserYAML::
    MemoryProfilerConfigFileEventHandlerYAML::KEY_PHASES[];

constexpr char MemoryProfilerConfigFileParserYAML::
    MemoryProfilerConfigFileEventHandlerYAML::KEY_UPDATE_COUNT[];

constexpr char MemoryProfilerConfigFileParserYAML::
    MemoryProfilerConfigFileEventHandlerYAML::KEY_UPDATE_CYCLE[];

constexpr char MemoryProfilerConfigFileParserYAML::
    MemoryProfilerConfigFileEventHandlerYAML::KEY_UPDATE_TIME[];

constexpr char MemoryProfilerConfigFileParserYAML::
    MemoryProfilerConfigFileEventHandlerYAML::KEY_UPDATE_WHENEVER[];

class MemoryProfiler::Impl
{
public:
    Impl(const std::string & def_file,
         TreeNode * context,
         app::Simulation * sim)
    {
        if (def_file == "@") {
            setDefaults_(context, sim);
        } else if (def_file == "1") {
            setDefaultsForStdoutDump_(context, sim);
        } else {
            MemoryProfilerConfigFileParserYAML parser(def_file);
            auto & cfgs = parser.parseConfigurations(context);
            prepareProfiler_(cfgs, context, sim);
        }
    }

    void enteringPhase(const MemoryProfiler::Phase phase)
    {
        for (auto & prof : profilers_) {
            prof.enteringPhase(phase);
        }
    }

    void exitingPhase(const MemoryProfiler::Phase phase)
    {
        for (auto & prof : profilers_) {
            prof.exitingPhase(phase);
        }
    }

    void saveReport()
    {
        for (auto & prof : profilers_) {
            prof.saveReport();
        }
    }

    void saveReportToStream(std::ostream & os)
    {
        for (auto & prof : profilers_) {
            prof.saveReportToStream(os);
        }
    }

private:
    class ProfileRuntime
    {
    public:
        ProfileRuntime(const ProfilerConfig & cfg,
                       TreeNode * context,
                       app::Simulation * sim) :
            report_name_(cfg.report_name),
            dest_file_(cfg.dest_file),
            phases_(cfg.phases),
            update_type_(cfg.update_type),
            update_expression_(cfg.update_expression),
            context_(context),
            sim_(sim)
        {
            if (!dest_file_.empty() && dest_file_ != "1" &&
                boost::filesystem::extension(dest_file_) != ".csv") {
                throw SpartaException("Memory statistics must be saved to a *.csv file, "
                                    "not '") << dest_file_ << "' (bad file extension)";
            }
        }

        void enteringPhase(const MemoryProfiler::Phase phase)
        {
            if (!tracking_(phase)) {
                return;
            }
            if (phase == MemoryProfiler::Phase::Simulate) {
                startUpdateTrigger_();
            }
            current_phase_ = phase;
        }

        void exitingPhase(const MemoryProfiler::Phase phase)
        {
            if (!tracking_(phase)) {
                return;
            }
            if (phase == MemoryProfiler::Phase::Simulate) {
                stopUpdateTrigger_();
            }
            takeSnapshot_();
            current_phase_.clearValid();
        }

        void saveReport()
        {
            if (dest_file_.empty() || dest_file_ == "1") {
                writeUnformattedMemStatsToStream_(std::cout);
            } else {
                saveReportToFile_();
            }
        }

        void saveReportToStream(std::ostream & os)
        {
            writeUnformattedMemStatsToStream_(os);
        }

        void saveReportToFile_() {
            std::ofstream fout(dest_file_);

            if (!fout) {
                throw SpartaException("Unable to open output file for "
                                    "writing: '") << dest_file_ << "'";
            }

            /*
             * Memory usage reports are formatted as follows (heap
             * allocation values are in bytes):
             *
             *      # <report name>
             *      # <update type>:<update expression>
             *      # Phase,     Current,     Max
             *        Build,       12345,   12345
             *        Configure,   12675,   12675
             *        Bind,        12981,   12981
             *        Simulate,    13405,   13405
             *                     12987,   13405
             *                     14992,   14992
             *                     14560,   14992
             *                      ...      ...
             */

            //First write header information to the CSV report
            fout << "# " << report_name_ << "\n";
            fout << "# " << update_type_ << ":" << update_expression_ << "\n";
            fout << "Phase,Current,Max\n";

            for (auto & snapshots_by_phase : snapshots_by_phase_) {
                switch (snapshots_by_phase.first) {
                    case MemoryProfiler::Phase::Build: {
                        fout << "Build,";
                        break;
                    }
                    case MemoryProfiler::Phase::Configure: {
                        fout << "Configure,";
                        break;
                    }
                    case MemoryProfiler::Phase::Bind: {
                        fout << "Bind,";
                        break;
                    }
                    case MemoryProfiler::Phase::Simulate: {
                        fout << "Simulate,";
                        break;
                    }
                    default:
                        sparta_assert("Unreachable");
                        break;
                }

                bool pad_csv_cell = false;
                while (!snapshots_by_phase.second.empty()) {
                    if (pad_csv_cell) {
                        fout << ",";
                    }
                    pad_csv_cell = true;

                    const auto & snapshot = snapshots_by_phase.second.front();
                    fout << snapshot.first << "," << snapshot.second << "\n";
                    snapshots_by_phase.second.pop();
                }
            }

            std::cout << "  [profile] Wrote memory usage report to \"" << dest_file_ << "\"\n";
        }

        void writeUnformattedMemStatsToStream_(std::ostream & os) {
            /*
             * Memory usage reports are formatted as follows (heap
             * allocation values are in bytes):
             *
             *      # <report name>
             *      # <update type>:<update expression>
             *      # Phase       Current   Max
             *        Build       12345     12345
             *        Configure   12675     12675
             *        Bind        12981     12981
             *        Simulate    13405     13405
             *                    12987     13405
             *                    14992     14992
             *                    14560     14992
             *                     ...       ...
             */

            //First write header information to the console
            os << "# " << report_name_ << "\n";
            os << "# " << update_type_ << ":" << update_expression_ << "\n";
            os << "# Phase          Current     Max\n";

            for (auto & snapshots_by_phase : snapshots_by_phase_) {
                os << std::left << std::setfill(' ') << std::setw(17);
                switch (snapshots_by_phase.first) {
                    case MemoryProfiler::Phase::Build: {
                        os << "  Build        ";
                        break;
                    }
                    case MemoryProfiler::Phase::Configure: {
                        os << "  Configure    ";
                        break;
                    }
                    case MemoryProfiler::Phase::Bind: {
                        os << "  Bind         ";
                        break;
                    }
                    case MemoryProfiler::Phase::Simulate: {
                        os << "  Simulate     ";
                        break;
                    }
                    default:
                        sparta_assert("Unreachable");
                        break;
                }

                bool pad_whitespace = false;
                while (!snapshots_by_phase.second.empty()) {
                    if (pad_whitespace) {
                        os << "                 ";
                    }
                    pad_whitespace = true;

                    const auto & snapshot = snapshots_by_phase.second.front();
                    os << std::left << std::setfill(' ') << std::setw(12);
                    os << snapshot.first;
                    os << std::left << std::setfill(' ') << std::setw(12);
                    os << snapshot.second << "\n";
                    snapshots_by_phase.second.pop();
                }
            }
        }

    private:
        void startUpdateTrigger_() {
            auto configure = [&](TreeNode * context) {
                auto cb = CREATE_SPARTA_HANDLER(ProfileRuntime, takeSnapshot_);
                action_on_update_ = RescheduleActionOnUpdate::Reschedule;

                if (update_type_ == "update-count") {
                    update_trigger_.reset(new trigger::ExpressionCounterTrigger(
                        "MemorySnapshot", cb, update_expression_, 0, context));
                }

                else if (update_type_ == "update-cycles") {
                    update_trigger_.reset(new trigger::ExpressionCycleTrigger(
                        "MemorySnapshot", cb, update_expression_, context));
                }

                else if (update_type_ == "update-time") {
                    update_trigger_.reset(new trigger::ExpressionTimeTrigger(
                        "MemorySnapshot", cb, update_expression_, context));
                }

                else if (update_type_ == "update-whenever") {
                    update_trigger_.reset(new trigger::ExpressionTrigger(
                        "MemorySnapshot", cb, update_expression_, context, nullptr));

                    const auto & internals = update_trigger_->getInternals();
                    if (internals.num_counter_triggers_ > 0 ||
                        internals.num_cycle_triggers_ > 0 ||
                        internals.num_time_triggers_ > 0) {
                        throw SpartaException(
                            "Only 'notif.*' triggers are allowed in 'update-whenever' expressions");
                    }

                    action_on_update_ = RescheduleActionOnUpdate::StayActive;
                }

                else {
                    throw SpartaException("Unrecognized memory profile update type "
                                        "found: '") << update_type_ << "'";
                }
            };

            try {
                configure(context_);
            } catch (...) {
                configure(sim_->getRoot()->getSearchScope());
            }
        }

        void stopUpdateTrigger_() {
            update_trigger_.reset();
        }

        inline bool tracking_(const MemoryProfiler::Phase phase) const {
            return (phases_.empty() || phases_.find(phase) != phases_.end());
        }

        void takeSnapshot_() {
            //Use gperftools malloc extension to request the current allocated bytes
            static const char CURRENT_ALLOC[] = "generic.current_allocated_bytes";

            size_t allocated_bytes = 0;
            MallocExtension::instance()->GetNumericProperty(CURRENT_ALLOC, &allocated_bytes);

            //For each snapshot, keep track of the current allocated bytes, as well as the
            //maximum allocated bytes (running max over all snapshots)
            if (!max_heap_bytes_.isValid()) {
                max_heap_bytes_ = allocated_bytes;
            } else {
                max_heap_bytes_ = std::max(max_heap_bytes_.getValue(), allocated_bytes);
            }

            //Separate snapshots by simulation phase so the report stays organized and clear
            snapshots_by_phase_[current_phase_].push(
                std::make_pair(allocated_bytes, max_heap_bytes_.getValue()));

            if (update_trigger_ == nullptr) {
                return;
            }

            //Reschedule the update trigger to keep getting calls to this 'takeSnapshot_()'
            //method. This will continue to get hit over and over until the end of the simulate
            //phase.
            if (action_on_update_ == RescheduleActionOnUpdate::Reschedule) {
                update_trigger_->reschedule();
            } else if (action_on_update_ == RescheduleActionOnUpdate::StayActive) {
                update_trigger_->stayActive();
                update_trigger_->awaken();
            }
        }

        std::string report_name_;
        std::string dest_file_;
        std::set<MemoryProfiler::Phase> phases_;
        utils::ValidValue<MemoryProfiler::Phase> current_phase_;

        std::string update_type_;
        std::string update_expression_;
        std::unique_ptr<trigger::ExpressionTrigger> update_trigger_;
        TreeNode * context_ = nullptr;
        app::Simulation * sim_ = nullptr;

        enum class RescheduleActionOnUpdate {
            Reschedule,
            StayActive
        };
        utils::ValidValue<RescheduleActionOnUpdate> action_on_update_;

        typedef std::pair<size_t, size_t> HeapUsageSnapshot;
        utils::ValidValue<size_t> max_heap_bytes_;
        std::map<MemoryProfiler::Phase, std::queue<HeapUsageSnapshot>> snapshots_by_phase_;
    };

    void setDefaults_(TreeNode * context, app::Simulation * sim) {
        ProfilerConfig cfg(
            "Memory usage statistics", "mem-stats.csv", {},
            "update-cycles", "10k");
        prepareProfiler_({cfg}, context, sim);
    }

    void setDefaultsForStdoutDump_(TreeNode * context, app::Simulation * sim) {
        ProfilerConfig cfg(
            "Memory usage statistics", "", {},
            "update-cycles", "10k");
        prepareProfiler_({cfg}, context, sim);
    }

    void prepareProfiler_(const ProfilerConfigurations & configs,
                          TreeNode * context,
                          app::Simulation * sim) {
        for (const auto & cfg : configs) {
            profilers_.emplace_back(cfg, context, sim);
        }
    }

    std::vector<ProfileRuntime> profilers_;
};

MemoryProfiler::MemoryProfiler(const std::string & def_file,
                               TreeNode * context,
                               app::Simulation * sim) :
    impl_(new MemoryProfiler::Impl(def_file, context, sim))
{
}

void MemoryProfiler::enteringPhase(const Phase phase)
{
    impl_->enteringPhase(phase);
}

void MemoryProfiler::exitingPhase(const Phase phase)
{
    impl_->exitingPhase(phase);
}

void MemoryProfiler::saveReport()
{
    impl_->saveReport();
}

void MemoryProfiler::saveReportToStream(std::ostream & os)
{
    impl_->saveReportToStream(os);
}

}


text:
//
// Created by Przemek on 29.12.2019.
//
#include <boost/test/unit_test.hpp>
#include <memory>
#include "Field.h"
#include "Pieces/Pawn.h"
// #include "test.h"

const int row_1 = 1;
const int col_1 = 2;

BOOST_AUTO_TEST_SUITE(FieldTestSuite)

BOOST_AUTO_TEST_CASE(FieldTest1) {
    std::shared_ptr<Field> test_field_1 = std::make_shared<Field>(row_1, col_1);
    Position test_pos_1(row_1, col_1);
    BOOST_REQUIRE_EQUAL(test_pos_1.row, row_1);
    BOOST_REQUIRE_EQUAL(test_pos_1.col, col_1);
    BOOST_REQUIRE_EQUAL(test_pos_1.row, test_field_1->get_position().row);
    BOOST_REQUIRE_EQUAL(test_pos_1.col, test_field_1->get_position().col);

    Position tmp = test_field_1->get_position();
    BOOST_REQUIRE_EQUAL(test_pos_1.operator==(tmp), true);

    std::shared_ptr<Piece> test_pawn1 = std::make_shared<Pawn>(true);
    std::shared_ptr<Piece> test_pawn2 = std::make_shared<Pawn>(true);
    test_field_1->set_piece(test_pawn1);
    test_field_1->set_piece(test_pawn2);
    BOOST_CHECK_EQUAL(test_field_1->get_piece(), test_pawn2);
    test_field_1->set_piece(test_pawn1);
    BOOST_CHECK_EQUAL(test_field_1->get_piece(), test_pawn1);
    BOOST_CHECK(test_field_1->is_taken());

    std::shared_ptr<Pawn> test_pawn3 = std::make_shared<Pawn>(true);
    test_field_1->set_piece(test_pawn3);
    BOOST_CHECK(test_field_1->is_taken());
    BOOST_CHECK_EQUAL(test_field_1->get_piece(), test_pawn3);
}

BOOST_AUTO_TEST_SUITE_END()


text:
#include <Eigen/Core>
#include <Eigen/Dense>
#include <opencv2/opencv.hpp>
#include <opencv2/core/eigen.hpp>
#include <boost/filesystem.hpp>
#include <Open3D/Open3D.h>
#include <glog/logging.h>

#include "FileSystemTools.h"
#include "YamlFileIO.h"

// fitness threshold
double min_fitness_thresh = 0.05;

struct RegistrationResult{
    // transform matrix
    Eigen::Matrix4d T;
    // fitness score
    double fitness;
    // inlier rms
    double inlier_rms;
};

// create init extrinsic file
void createMultiLidarExtFile(const std::string& filename)
{
    // new backpack structural value
    Eigen::Matrix4d T_l0_l1_gt = Eigen::Matrix4d::Identity();
    Eigen::AngleAxisd l0_l1_vec1(-30 * M_PI / 180.0, Eigen::Vector3d(0, 0, 1));
    Eigen::AngleAxisd l0_l1_vec2(-73.5 * M_PI / 180.0, Eigen::Vector3d(0, 1, 0));
    Eigen::Matrix3d l0_l1_vec = l0_l1_vec1.matrix() * l0_l1_vec2.matrix();
    Eigen::Vector3d t_l0_l1(-0.31405, 0, -0.39803);
    T_l0_l1_gt.block<3, 3>(0, 0) = l0_l1_vec;
    T_l0_l1_gt.block<3, 1>(0, 3) = l0_l1_vec1.matrix() * t_l0_l1;
    std::cout << "T_l0_l1_gt:\n" << T_l0_l1_gt << "\n";

    common::saveExtFileOpencv(filename, T_l0_l1_gt);
}

bool alignTwoPointClouds(const std::string &src_pcl_file, const std::string &target_pcl_file, const Eigen::Matrix4d &T_init,
                RegistrationResult &result){
    std::string path, file_name;
    common::splitPathAndFilename(src_pcl_file, &path, &file_name);

    auto src_pcd_ptr = open3d::io::CreatePointCloudFromFile(src_pcl_file);
    auto target_pcd_ptr = open3d::io::CreatePointCloudFromFile(target_pcl_file);

    if( src_pcd_ptr == nullptr || src_pcd_ptr == nullptr){
        LOG(ERROR) << "Fail to load src and target pointcloud file!";
        return false;
    }

    auto src_pcd_down_ptr = src_pcd_ptr->VoxelDownSample(0.05);
    src_pcd_ptr->EstimateNormals(open3d::geometry::KDTreeSearchParamHybrid(0.1, 30));

    auto target_pcd_down_ptr = target_pcd_ptr->VoxelDownSample(0.05);
    target_pcd_ptr->EstimateNormals(open3d::geometry::KDTreeSearchParamHybrid(0.1, 30));

    src_pcd_ptr->Transform(T_init);
    src_pcd_down_ptr->Transform(T_init);

    open3d::registration::RegistrationResult icp_result;

    const double max_corresp_dis = 0.03; // meter
    open3d::registration::ICPConvergenceCriteria icp_criteria(1e-6, 1e-6, 100);
    // icp_result = open3d::registration::RegistrationICP(*src_pcd_ptr, *target_pcd_ptr, max_corresp_dis, Eigen::Matrix4d::Identity(),
    //                                                         open3d::registration::TransformationEstimationPointToPlane(), icp_criteria);
    icp_result = open3d::registration::RegistrationICP(*src_pcd_ptr, *target_pcd_ptr, max_corresp_dis, Eigen::Matrix4d::Identity(),
                                                    open3d::registration::TransformationEstimationPointToPoint(false), icp_criteria);

    // transform source pointcloud with icp_transformation
    Eigen::Matrix4d T_icp = icp_result.transformation_;

    LOG(INFO) << "#############" << path << " ################";
    result.fitness = icp_result.fitness_;
    LOG(INFO) << "icp_result.fitness: " << icp_result.fitness_;
    result.inlier_rms = icp_result.inlier_rmse_;
    LOG(INFO) << "icp_result.inlier_rmse_ : " << icp_result.inlier_rmse_;

    if(result.fitness < min_fitness_thresh){
        LOG(ERROR) << "fitness score < " << min_fitness_thresh;
        return false;
    }

    // final transformation between source pointcloud and target pointcloud
    result.T = T_icp * T_init;
    std::cout << "Final transformation:\n"
              << result.T << "\n";

    src_pcd_down_ptr->Transform(T_icp);

    std::string save_file_path;

    save_file_path = common::concatenateFolderAndFileName(path, "transformed_source_pointcloud.ply");
    open3d::io::WritePointCloudToPLY(save_file_path, *src_pcd_down_ptr, true);
    std::shared_ptr<open3d::geometry::PointCloud> merge_points(new open3d::geometry::PointCloud);
    *merge_points = *src_pcd_down_ptr + *target_pcd_down_ptr;

    save_file_path = common::concatenateFolderAndFileName(path, "merged_pointcloud.ply");
    open3d::io::WritePointCloudToPLY(save_file_path, *merge_points, true);

    return true;
}

void evaluateExtrinsics(const std::vector<RegistrationResult> & v_results, const Eigen::Matrix4d &T_baseline){
    assert(v_results.size() > 1);

    std::vector<double> v_inlier_rms = {v_results[0].inlier_rms};
    // rotation sigma
    std::vector<double> v_sigma_r;
    // translation sigma
    std::vector<double> v_sigma_t;

    int T_num = v_results.size();
    for(int i = 0; i < T_num; ++i){
        Eigen::Matrix4d T = v_results[i].T;
        Eigen::Matrix4d T_inv = T.inverse();

        Eigen::Matrix4d T_delt = T_inv * T_baseline;
        Eigen::AngleAxisd rot_vec(T_delt.block<3, 3>(0, 0));
        double delt_r = rot_vec.angle() * 180.0 / M_PI;
        Eigen::Vector3d t_delt = T_delt.block<3, 1>(0, 3);
        double delt_t = t_delt.norm() * 100;
        LOG(INFO) << "T_baseline and  T_" << i << " Rotation delta: "
                <<  delt_r << " °\n";
        LOG(INFO) << "T_baseline and  T_" << i << " Translation delta: " << delt_t
                << " cm\n";

        v_sigma_r.push_back(delt_r * delt_r);
        v_sigma_t.push_back(delt_t * delt_t);
        v_inlier_rms.push_back(v_results[i].inlier_rms);
    }

    double sigma_r = std::accumulate(v_sigma_r.begin(), v_sigma_r.end(), 0.0) / T_num;
    double sigma_t = std::accumulate(v_sigma_t.begin(), v_sigma_t.end(), 0.0) / T_num;
    LOG(INFO) << "Avg rotation sigma: " << sigma_r << ", Avg trans sigma: " << sigma_t;
    LOG(INFO) << "Final sigma_r" << std::sqrt(sigma_r) << ", sigma_t: " << std::sqrt(sigma_t);
    // LOG(INFO) << "Avg inlier rms: " << std::accumulate(v_inlier_rms.begin(), v_inlier_rms.end(), 0.0) / v_inlier_rms.size();

}

int main(int argc, char **argv){
    if (argc < 3){
        LOG(FATAL) << "Usage: test_lidar2lidar_calibration [T_l0_l1_init.yaml] [input_dataset_folder] [output_folder] [lidar0_id] [lidar1_id]";
        return -1;
    }

    std::string init_ext_filepath(argv[1]);
    // dataset folder e.g. /path/data0/lidar_lidar
    std::string dataset_folder(argv[2]);
    std::string output_folder(argv[3]);
    int lidar0_id = 0, lidar1_id = 1;
    if (argc == 6){
        lidar0_id = std::stoi (argv[4]);
        lidar1_id = std::stoi (argv[5]);
    }

    // if initial extrinsic isn't here, create it
    if(!common::fileExists(init_ext_filepath)){
        createMultiLidarExtFile(init_ext_filepath);
    }
    if(!common::pathExists(dataset_folder)){
        LOG(FATAL) << "Input folder doesnot exist!";
        return -1;
    }
    if(!common::pathExists(output_folder)){
        if(!common::createPath(output_folder)){
            LOG(FATAL) << "Fail to create " << output_folder;
            return -1;
        }
    }

    // Eigen::Matrix4d T_base_l0 = horizontal_lidar_ptr->extrinsics();
    // Eigen::Matrix4d T_base_l1 = vertical_lidar_ptr->extrinsics();
    // initial extrinsic between two lidar
    Eigen::Matrix4d T_l0_l1_init = Eigen::Matrix4d::Identity();
    if (!common::loadExtFileOpencv(init_ext_filepath, T_l0_l1_init)){
        LOG(FATAL) << "Fail to load " << init_ext_filepath;
        return -1;
    }

    std::vector<RegistrationResult> v_extrinsics;

    // for (const auto & entry : boost::filesystem::directory_iterator(dataset_folder)){
    //     if(!boost::filesystem::is_directory(entry))
    //         continue;

    //     std::string scan_folder_path = entry.path().string() + "/lidar_lidar";
        std::string lidar0_scan_folder = common::concatenateFolderAndFileName(dataset_folder, "lidar0");
        std::string lidar1_scan_folder = common::concatenateFolderAndFileName(dataset_folder, "lidar1");
        std::vector<std::string> v_lidar0_pcl_paths,  v_lidar1_pcl_paths;
        std::vector<std::string> paths = {lidar0_scan_folder};
        common::getFileLists(paths, true, "ply", &v_lidar0_pcl_paths);
        paths = {lidar1_scan_folder};
        common::getFileLists(paths, true, "ply", &v_lidar1_pcl_paths);

        if (v_lidar0_pcl_paths.empty() || v_lidar1_pcl_paths.empty()){
            LOG(ERROR) << "lidar scan folder is empty!\n";
            return -1;
        }
        // only choose 1 scan pair for calibration
        std::string src_pcl_file_path, target_pcl_file_path;
        {
            std::string file_path = v_lidar0_pcl_paths[0];
            std::string path, file_name;
            common::splitPathAndFilename(file_path, &path, &file_name);
            if(std::atoi(&file_name[0]) == lidar0_id)
                target_pcl_file_path = file_path;
        }
        {
            std::string file_path = v_lidar1_pcl_paths[0];
            std::string path, file_name;
            common::splitPathAndFilename(file_path, &path, &file_name);
            if(std::atoi(&file_name[0]) == lidar1_id)
                src_pcl_file_path = file_path;
        }

        RegistrationResult regist_result;
        bool sts = alignTwoPointClouds(src_pcl_file_path, target_pcl_file_path, T_l0_l1_init, regist_result);
        if(!sts){
            return -1;
        }

        std::string save_file_path = common::concatenateFolderAndFileName(output_folder, "lidar0_to_lidar1.yml");
        common::saveExtFileOpencv(save_file_path, regist_result.T);
        v_extrinsics.emplace_back(regist_result);
    // }

    // sort result by fitness
    // std::sort(v_extrinsics.begin(), v_extrinsics.end(), [&](RegistrationResult &res_a, RegistrationResult &res_b){
    //     return res_a.fitness > res_b.fitness;
    // });

    // evaluateExtrinsics(v_extrinsics, v_extrinsics[0].T);

    return 0;
}


text:
/*
 * simd_scalar.cpp
 *
 *  Description:
 *    Methods of the system component: scalar processor
 */

#include <boost/foreach.hpp>
#include "simd_sys_scalar.h"
#include "simd_conv_ptree.h"
#include "simd_assert.h"
#include "simd_report.h"

namespace simd {

SC_HAS_PROCESS( simd::simd_sys_scalar_c );
simd_sys_scalar_c::simd_sys_scalar_c(
      sc_core::sc_module_name nm )
   : sc_core::sc_module( nm )
   , clock_i( "clock_i" )
   , reset_i( "reset_i" )
   , event_i( "event_i" )
   , busw_o(  "busw_o"  )
   , busr_i(  "busr_i"  ) {

   // Process registrations
   SC_CTHREAD( exec_thrd, clock_i.pos() ); //  Synchronous thread for data processing
   reset_signal_is( reset_i, true );
} // simd_sys_scalar_c::simd_sys_scalar_c(

void simd_sys_scalar_c::wr_conf(
      const std::string& conf ) {
   boost_pt::ptree wr_pt;
   simd_sig_ptree_c wr;

   str2pt( conf, wr_pt );

   busw_o->write( wr.set( wr_pt ));
} // void simd_sys_scalar_c::wr_conf(

void simd_sys_scalar_c::evt_proc_clear(
      void ) {
   BOOST_FOREACH( evt_proc_data_t& evt_data, evt_proc ) {
      evt_data.evt = false;
   }
} // void simd_sys_scalar_c::evt_proc_clear(

simd_sys_scalar_c::evt_proc_t simd_sys_scalar_c::evt_proc_check(
      const boost_pt::ptree& event_pt ) {

   std::string src_name;
   std::string evt_name;

   try {
      src_name = event_pt.get<std::string>( "src" );
      evt_name = event_pt.get<std::string>( "event_id" );
   }
   catch( const boost_pt::ptree_error& err ) {
      SIMD_REPORT_ERROR( "simd::sys_scalar" ) << err.what();
   }
   catch( ... ) {
      SIMD_REPORT_ERROR( "simd::sys_scalar" ) << "Unexpected";
   }

   bool valid_all = true;
   bool valid_any = false;
   bool error_all = true;
   bool error_any = false;

   BOOST_FOREACH( evt_proc_data_t& evt_data, evt_proc ) {
      evt_data.evt |= ( evt_data.src_name == src_name &&
                        evt_data.evt_name == evt_name );

      if( evt_data.valid_all ) {
         valid_all &= evt_data.evt;
      }

      if( evt_data.valid_any ) {
         valid_any |= evt_data.evt;
      }

      if( evt_data.error_all ) {
         error_all &= evt_data.evt;
      }

      if( evt_data.error_any ) {
         error_any |= evt_data.evt;
      }
   }

   if(      error_all && error_all_present ) {
      return EVT_PROC_ERROR_ALL;
   }
   else if( error_any && error_any_present ) {
      return EVT_PROC_ERROR_ANY;
   }
   else if( valid_all && valid_all_present ) {
      return EVT_PROC_VALID_ALL;
   }
   else if( valid_any && valid_any_present ) {
      return EVT_PROC_VALID_ANY;
   }
   else {
      return EVT_PROC_NONE;
   }
} // simd_sys_scalar_c::evt_proc_t simd_sys_scalar_c::evt_proc_check(

void simd_sys_scalar_c::evt_proc_init(
      const std::string& evt_list ) {

   boost_pt::ptree evt_list_pt;

   str2pt(
         evt_list,
         evt_list_pt );

   // Parse
   boost::optional<const boost_pt::ptree &> valid_all_p( evt_list_pt.get_child_optional( "valid_all" ));
   boost::optional<const boost_pt::ptree &> valid_any_p( evt_list_pt.get_child_optional( "valid_any" ));
   boost::optional<const boost_pt::ptree &> error_all_p( evt_list_pt.get_child_optional( "error_all" ));
   boost::optional<const boost_pt::ptree &> error_any_p( evt_list_pt.get_child_optional( "error_any" ));

   if( valid_all_p == boost::none &&
       valid_any_p == boost::none &&
       error_any_p == boost::none &&
       error_all_p == boost::none ) {
      SIMD_REPORT_ERROR( "simd::sys_scalar" ) << " Initialization list is empty";
   }

   evt_proc.clear();

   evt_proc_data_t evt_proc_elem;

   if( valid_all_p != boost::none ) {
      evt_proc_elem.valid_all = true;
      evt_proc_elem.valid_any = false;
      evt_proc_elem.error_any = false;
      evt_proc_elem.error_all = false;
      evt_proc_elem.evt       = false;

      BOOST_FOREACH( const boost_pt::ptree::value_type& evt, valid_all_p.get() ) {
         if( !evt.first.empty()) {
            SIMD_REPORT_ERROR( "simd::sys_scalar" ) << "Incorrect format";
         }

         try {
            evt_proc_elem.src_name = evt.second.get<std::string>( "src" );
            evt_proc_elem.evt_name = evt.second.get<std::string>( "evt" );
         }
         catch( const boost_pt::ptree_error& err ) {
            SIMD_REPORT_ERROR( "simd::sys_scalar" ) << err.what();
         }
         catch( ... ) {
            SIMD_REPORT_ERROR( "simd::sys_scalar" ) << "Unexpected";
         }

         evt_proc.push_back( evt_proc_elem );

         valid_all_present = true;
      }
   } // if( valid_all_p != boost::none )

   if( valid_any_p != boost::none ) {
      evt_proc_elem.valid_all = false;
      evt_proc_elem.valid_any = true;
      evt_proc_elem.error_any = false;
      evt_proc_elem.error_all = false;
      evt_proc_elem.evt       = false;

      BOOST_FOREACH( const boost_pt::ptree::value_type& evt, valid_any_p.get() ) {
         if( !evt.first.empty()) {
            SIMD_REPORT_ERROR( "simd::sys_scalar" ) << "Incorrect format";
         }

         try {
            evt_proc_elem.src_name = evt.second.get<std::string>( "src" );
            evt_proc_elem.evt_name = evt.second.get<std::string>( "evt" );
         }
         catch( const boost_pt::ptree_error& err ) {
            SIMD_REPORT_ERROR( "simd::sys_scalar" ) << err.what();
         }
         catch( ... ) {
            SIMD_REPORT_ERROR( "simd::sys_scalar" ) << "Unexpected";
         }

         evt_proc.push_back( evt_proc_elem );

         valid_any_present = true;
      }
   } // if( valid_any_p != boost::none )

   if( error_any_p != boost::none ) {
      evt_proc_elem.valid_all = false;
      evt_proc_elem.valid_any = false;
      evt_proc_elem.error_any = true;
      evt_proc_elem.error_all = false;
      evt_proc_elem.evt       = false;

      BOOST_FOREACH( const boost_pt::ptree::value_type& evt, error_any_p.get() ) {
         if( !evt.first.empty()) {
            SIMD_REPORT_ERROR( "simd::sys_scalar" ) << "Incorrect format";
         }

         try {
            evt_proc_elem.src_name = evt.second.get<std::string>( "src" );
            evt_proc_elem.evt_name = evt.second.get<std::string>( "evt" );
         }
         catch( const boost_pt::ptree_error& err ) {
            SIMD_REPORT_ERROR( "simd::sys_scalar" ) << err.what();
         }
         catch( ... ) {
            SIMD_REPORT_ERROR( "simd::sys_scalar" ) << "Unexpected";
         }

         evt_proc.push_back( evt_proc_elem );

         error_any_present = true;
      }
   } // if( error_any_p != boost::none )

   if( error_all_p != boost::none ) {
      evt_proc_elem.valid_all = false;
      evt_proc_elem.valid_any = false;
      evt_proc_elem.error_any = false;
      evt_proc_elem.error_all = true;
      evt_proc_elem.evt       = false;

      BOOST_FOREACH( const boost_pt::ptree::value_type& evt, error_all_p.get() ) {
         if( !evt.first.empty()) {
            SIMD_REPORT_ERROR( "simd::sys_scalar" ) << "Incorrect format";
         }

         try {
            evt_proc_elem.src_name = evt.second.get<std::string>( "src" );
            evt_proc_elem.evt_name = evt.second.get<std::string>( "evt" );
         }
         catch( const boost_pt::ptree_error& err ) {
            SIMD_REPORT_ERROR( "simd::sys_scalar" ) << err.what();
         }
         catch( ... ) {
            SIMD_REPORT_ERROR( "simd::sys_scalar" ) << "Unexpected";
         }

         evt_proc.push_back( evt_proc_elem );

         error_all_present = true;
      }
   } // if( error_all_p != boost::none )
} // void simd_sys_scalar_c::evt_proc_init(

} // namespace simd

max_stars_repo_name: timurkelin/simsimd

max_issues_repo_name: timurkelin/simsimd

max_forks_repo_name: timurkelin/simsimd


text:
#include "SHA1Strategy.hpp"
#include "checksum.h"

#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <boost/algorithm/string/predicate.hpp>
#include <openssl/sha.h>

#include "base64.h"

namespace irods {

    const std::string SHA1_NAME( "sha1" );

    error
    SHA1Strategy::init( boost::any& _context ) const {
        _context = SHA_CTX();
        SHA1_Init( boost::any_cast<SHA_CTX>( &_context ) );
        return SUCCESS();
    }

    error
    SHA1Strategy::update( const std::string& data, boost::any& _context ) const {
        SHA1_Update( boost::any_cast<SHA_CTX>( &_context ), data.c_str(), data.size() );
        return SUCCESS();
    }

    error
    SHA1Strategy::digest( std::string& _messageDigest, boost::any& _context ) const {
        unsigned char final_buffer[SHA_DIGEST_LENGTH];
        SHA1_Final( final_buffer, boost::any_cast<SHA_CTX>( &_context ) );
        int len = strlen( SHA1_CHKSUM_PREFIX );
        unsigned long out_len = CHKSUM_LEN - len;

        unsigned char out_buffer[CHKSUM_LEN];
        base64_encode( final_buffer, SHA_DIGEST_LENGTH, out_buffer, &out_len );

        _messageDigest = SHA1_CHKSUM_PREFIX;
        _messageDigest += std::string( ( char* )out_buffer, out_len );

        return SUCCESS();
    }

    bool
    SHA1Strategy::isChecksum( const std::string& _chksum ) const {
        return boost::starts_with( _chksum, SHA1_CHKSUM_PREFIX );
    }
}; // namespace irods

max_stars_repo_name: JustinKyleJames/irods

max_issues_repo_name: JustinKyleJames/irods

max_forks_repo_name: JustinKyleJames/irods


text:
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_POLICIES_ASYNC_RESOLVER_20100622
#define BOOST_NETWORK_PROTOCOL_HTTP_POLICIES_ASYNC_RESOLVER_20100622

// Copyright Dean Michael Berris 2010.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <memory>
#include <unordered_map>
#include <cstdint>
#include <functional>
#include <boost/asio/placeholders.hpp>
#include <boost/asio/strand.hpp>
#include <boost/network/protocol/http/traits/resolver.hpp>
#include <boost/network/traits/string.hpp>
#include <boost/algorithm/string/case_conv.hpp>

namespace boost {
namespace network {
namespace http {
namespace policies {

template <class Tag>
struct async_resolver : std::enable_shared_from_this<async_resolver<Tag> > {
  typedef typename resolver<Tag>::type resolver_type;
  typedef typename resolver_type::iterator resolver_iterator;
  typedef typename resolver_type::query resolver_query;
  typedef std::pair<resolver_iterator, resolver_iterator>
      resolver_iterator_pair;
  typedef typename string<Tag>::type string_type;
  typedef std::unordered_map<string_type, resolver_iterator_pair>
      endpoint_cache;
  typedef std::function<void(boost::system::error_code const &, resolver_iterator_pair)>
      resolve_completion_function;
  typedef std::function<void(resolver_type &, string_type, std::uint16_t,
                             resolve_completion_function)> resolve_function;

 protected:
  bool cache_resolved_;
  endpoint_cache endpoint_cache_;
  std::shared_ptr<boost::asio::io_service> service_;
  std::shared_ptr<boost::asio::io_service::strand> resolver_strand_;

  explicit async_resolver(bool cache_resolved)
      : cache_resolved_(cache_resolved), endpoint_cache_() {}

  void resolve(resolver_type &resolver_, string_type const &host,
               std::uint16_t port, resolve_completion_function once_resolved) {
    if (cache_resolved_) {
      typename endpoint_cache::iterator iter =
          endpoint_cache_.find(boost::to_lower_copy(host));
      if (iter != endpoint_cache_.end()) {
        boost::system::error_code ignored;
        once_resolved(ignored, iter->second);
        return;
      }
    }

    typename resolver_type::query q(host, std::to_string(port));
    auto self = this->shared_from_this();
    resolver_.async_resolve(
        q, resolver_strand_->wrap([=](boost::system::error_code const &ec,
                                      resolver_iterator endpoint_iterator) {
          self->handle_resolve(boost::to_lower_copy(host), once_resolved, ec,
                               endpoint_iterator);
        }));
  }

  void handle_resolve(string_type /*unused*/ const &host,
                      resolve_completion_function once_resolved,
                      boost::system::error_code const &ec,
                      resolver_iterator endpoint_iterator) {
    typename endpoint_cache::iterator iter;
    bool inserted = false;
    if (!ec && cache_resolved_) {
      std::tie(iter, inserted) = endpoint_cache_.insert(std::make_pair(
          host, std::make_pair(endpoint_iterator, resolver_iterator())));
      once_resolved(ec, iter->second);
    } else {
      once_resolved(ec, std::make_pair(endpoint_iterator, resolver_iterator()));
    }
  }
};

}  // namespace policies
}  // namespace http
}  // namespace network
}  // namespace boost

#endif  // BOOST_NETWORK_PROTOCOL_HTTP_POLICIES_ASYNC_RESOLVER_20100622

max_stars_repo_name: yhager/cpp-netlib

max_issues_repo_name: yhager/cpp-netlib

max_forks_repo_name: yhager/cpp-netlib


text:
/*=============================================================================
    Copyright (c) 2003 Jonathan de Halleux (dehalleux@pelikhan.com)
    http://spirit.sourceforge.net/

    Use, modification and distribution is subject to the Boost Software
    License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef BOOST_SPIRIT_ACTOR_INSERT_AT_ACTOR_HPP
#define BOOST_SPIRIT_ACTOR_INSERT_AT_ACTOR_HPP

#include <boost/spirit/actor/ref_const_ref_value_actor.hpp>
#include <boost/spirit/actor/ref_const_ref_const_ref_a.hpp>

namespace boost { namespace spirit {

    ///////////////////////////////////////////////////////////////////////////
    //  Summary:
    //  A semantic action policy that insert data into an associative
    //  container using a const reference to a key.
    //  (This doc uses convention available in actors.hpp)
    //
    //  Actions (what it does):
    //      ref.insert( T::value_type(key_ref,value) );
    //      ref.insert( T::value_type(key_ref, T::mapped_type(first,last)));;
    //      ref.insert( T::value_type(key_ref,value_ref) );
    //
    //  Policy name:
    //      insert_at_action
    //
    //  Policy holder, corresponding helper method:
    //      ref_const_ref_value_actor, insert_at_a( ref, key_ref );
    //      ref_const_ref_const_ref_actor, insert_a( ref, key_ref, value_ref );
    //
    //  () operators: both
    //
    //  See also ref_const_ref_value_actor and ref_const_ref_const_ref_actor
    //  for more details.
    ///////////////////////////////////////////////////////////////////////////
    struct insert_at_action
    {
        template<
            typename T,
            typename ReferentT,
            typename ValueT
        >
        void act(
            T& ref_,
            ReferentT const& key_,
            ValueT const& value_
            ) const
        {
            typedef typename T::value_type value_type;
            ref_.insert( value_type(key_, value_) );
        }

        template<
            typename T,
            typename ReferentT,
            typename IteratorT
        >
        void act(
            T& ref_,
            ReferentT const& key_,
            IteratorT const& first_,
            IteratorT const& last_
            ) const
        {
            typedef typename T::mapped_type mapped_type;
            typedef typename T::value_type value_type;

            mapped_type value(first_,last_);
            value_type key_value(key_, value);
            ref_.insert( key_value );
        }
    };

    template<
        typename T,
        typename ReferentT
        >
    inline ref_const_ref_value_actor<T,ReferentT,insert_at_action>
    insert_at_a(
            T& ref_,
            ReferentT const& key_
        )
    {
        return ref_const_ref_value_actor<
            T,
            ReferentT,
            insert_at_action
            >(ref_,key_);
    }

    template<
        typename T,
        typename ReferentT,
        typename ValueT
    >
    inline ref_const_ref_const_ref_actor<T,ReferentT,ValueT,insert_at_action>
    insert_at_a(
                T& ref_,
                ReferentT const& key_,
                ValueT const& value_
            )
    {
        return ref_const_ref_const_ref_actor<
            T,
            ReferentT,
            ValueT,
            insert_at_action
            >(ref_,key_,value_);
    }

}}

#endif

max_stars_repo_name: schinmayee/nimbus

max_issues_repo_name: schinmayee/nimbus

max_forks_repo_name: schinmayee/nimbus


text:
// This code is forked from
//   boost_1_67_0/libs/beast/example/http/client/coro/http_client_coro.cpp
// and modified by xhawk18 to use promise-cpp for better async control.
// Copyright (c) 2018, xhawk18
// at gmail.com

// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/boostorg/beast
//

//------------------------------------------------------------------------------
//
// Example: HTTP client, asynchronous with promise-cpp
//
//------------------------------------------------------------------------------

#include <boost/version.hpp>
#if BOOST_VERSION < 106600
#   error "This program need boost 1.66.0 or higher!"
#endif
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include "promise.hpp"
#include "add_ons/asio/io.hpp"

using namespace promise;
namespace asio   = boost::asio;
using     tcp    = boost::asio::ip::tcp;
namespace http   = boost::beast::http;
namespace beast  = boost::beast;

                                        //------------------------------------------------------------------------------

// Performs an HTTP GET and prints the response
void do_session(
    std::string const& host,
    std::string const& port,
    std::string const& target,
    int version,
    asio::io_context& ioc) {

    struct Session {
        tcp::resolver resolver_;
        tcp::socket socket_;
        beast::flat_buffer buffer_;
        http::request<http::empty_body> req_;
        http::response<http::string_body> res_;

        explicit Session(asio::io_context& ioc)
            : resolver_(ioc)
            , socket_(ioc) {
        }
    };

    // (Must persist in io_context ioc)
    auto session = std::make_shared<Session>(ioc);

    // Set up an HTTP GET request message
    session->req_.version(version);
    session->req_.method(http::verb::get);
    session->req_.target(target);
    session->req_.set(http::field::host, host);
    session->req_.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);

    //<1> Resolve the host
    async_resolve(session->resolver_, host, port)

    .then([=](tcp::resolver::results_type &results) {
        //<2> Connect to the host
        return async_connect(session->socket_, results);

    }).then([=]() {
        //<3> Write the request
        return async_write(session->socket_, session->req_);

    }).then([=](size_t bytes_transferred) {
        boost::ignore_unused(bytes_transferred);
        //<4> Read the response
        return async_read(session->socket_, session->buffer_, session->res_);

    }).then([=](size_t bytes_transferred) {
        boost::ignore_unused(bytes_transferred);
        //<5> Write the message to standard out
        std::cout << session->res_ << std::endl;

    }).then([]() {
        //<6> success, return default error_code
        return boost::system::error_code();
    }, [](const boost::system::error_code err) {
        //<6> failed, return the error_code
        return err;

    }).then([=](boost::system::error_code &err) {
        //<7> Gracefully close the socket
        std::cout << "shutdown..." << std::endl;
        session->socket_.shutdown(tcp::socket::shutdown_both, err);
    });
}

//------------------------------------------------------------------------------

int main(int argc, char** argv)
{
    // Check command line arguments.
    if (argc != 4 && argc != 5)
    {
        std::cerr <<
            "Usage: http-client-async <host> <port> <target> [<HTTP version: 1.0 or 1.1(default)>]\n" <<
            "Example:\n" <<
            "    http-client-async www.example.com 80 /\n" <<
            "    http-client-async www.example.com 80 / 1.0\n";
        return EXIT_FAILURE;
    }
    auto const host = argv[1];
    auto const port = argv[2];
    auto const target = argv[3];
    int version = argc == 5 && !std::strcmp("1.0", argv[4]) ? 10 : 11;

    // The io_context is required for all I/O
    asio::io_context ioc;

    // Launch the asynchronous operation
    do_session(host, port, target, version, ioc);

    // Run the I/O service. The call will return when
    // the get operation is complete.
    ioc.run();

    return EXIT_SUCCESS;
}

max_stars_repo_name: ExternalRepositories/promise-cpp

max_issues_repo_name: ExternalRepositories/promise-cpp

max_forks_repo_name: ExternalRepositories/promise-cpp