text:
#include <iostream>
#include <unistd.h>
#include <gtest/gtest.h>
#include "coroutine.h"
#include <boost/thread.hpp>
#include "gtest_exit.h"
using namespace std;
using namespace co;

TEST(Mutex, test_mutex)
{
//    co_sched.GetOptions().debug = dbg_switch;

    go []{
        std::cout << "start mutex test...\n" << std::endl;
    };
    WaitUntilNoTask();

    co_mutex m;

    go [&]()mutable {
        EXPECT_FALSE(m.is_lock());
        m.lock();
        EXPECT_TRUE(m.is_lock());
        m.unlock();
        EXPECT_FALSE(m.is_lock());

        EXPECT_TRUE(m.try_lock());
        EXPECT_FALSE(m.try_lock());
        m.unlock();
        EXPECT_FALSE(m.is_lock());
    };
    WaitUntilNoTask();

    int *pv = new int(0);
    std::vector<int> *vec = new std::vector<int>;
    vec->reserve(100 * 100);
    for (int i = 0; i < 100; ++i)
        go [&]()mutable {
            for (int i = 0; i < 100; ++i)
            {
                std::unique_lock<co_mutex> lock(m);
                vec->push_back(++*pv);
            }
        };
    WaitUntilNoTask();
    for (int i = 0; i < (int)vec->size(); ++i)
    {
        EXPECT_EQ(i + 1, vec->at(i));
    }
}

TEST(Mutex, test_rwmutex)
{
    co_rwmutex m;

    // reader view
    go [&]()mutable {
        EXPECT_FALSE(m.reader().is_lock());
        m.reader().lock();
        EXPECT_FALSE(m.reader().is_lock());
        m.reader().unlock();
        EXPECT_FALSE(m.reader().is_lock());

        EXPECT_TRUE(m.reader().try_lock());
        EXPECT_TRUE(m.reader().try_lock());
        EXPECT_TRUE(m.reader().try_lock());
        m.reader().unlock();
        m.reader().unlock();
        m.reader().unlock();
    };
    WaitUntilNoTask();

    // writer view
    go [&]()mutable {
        EXPECT_FALSE(m.writer().is_lock());
        m.writer().lock();
        EXPECT_TRUE(m.writer().is_lock());
        m.writer().unlock();
        EXPECT_FALSE(m.writer().is_lock());

        EXPECT_TRUE(m.writer().try_lock());
        EXPECT_FALSE(m.writer().try_lock());
        m.writer().unlock();
        EXPECT_FALSE(m.writer().is_lock());
    };
    WaitUntilNoTask();

    // cross two view
    go [&]()mutable {
        {
            std::unique_lock<co_wmutex> lock(m.writer());
            EXPECT_FALSE(m.reader().try_lock());
            EXPECT_FALSE(m.writer().try_lock());
        }

        {
            std::unique_lock<co_rmutex> lock(m.reader());
            EXPECT_TRUE(m.reader().try_lock());
            m.reader().unlock();
            EXPECT_FALSE(m.writer().try_lock());
            EXPECT_FALSE(m.writer().is_lock());
        }

        EXPECT_TRUE(m.writer().try_lock());
        EXPECT_TRUE(m.writer().is_lock());
        m.writer().unlock();
        EXPECT_FALSE(m.writer().is_lock());
    };
    WaitUntilNoTask();

    // multi threads
    int *v1 = new int(0);
    int *v2 = new int(0);

    go [&]()mutable {
        // write
        for (int i = 0; i < 10000; ++i)
        {
            std::unique_lock<co_wmutex> lock(m.writer());
            ++ *v1;
            ++ *v2;
        }
    };

    for (int i = 0; i < 100; ++i)
        go [&]()mutable {
            // read
            for (int i = 0; i < 10000; ++i)
            {
                std::unique_lock<co_rmutex> lock(m.reader());
                EXPECT_EQ(*v1, *v2);
            }
        };
    WaitUntilNoTask();
    EXPECT_EQ(*v1, 10000);
    EXPECT_EQ(*v2, 10000);
}

ext: cpp

max_stars_repo_name: chisuhua/costream

max_issues_repo_name: chisuhua/costream

max_forks_repo_name: chisuhua/costream


text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#include "integration/executor/executor_fixture.hpp"

#include <map>

#include <gtest/gtest.h>
#include <boost/format.hpp>
#include "backend/plain/account_detail_record_id.hpp"
#include "framework/common_constants.hpp"
#include "integration/executor/account_detail_checker.hpp"
#include "integration/executor/query_permission_test.hpp"
#include "interfaces/query_responses/account_detail_response.hpp"
#include "module/shared_model/mock_objects_factories/mock_command_factory.hpp"
#include "module/shared_model/mock_objects_factories/mock_query_factory.hpp"

using namespace common_constants;
using namespace executor_testing;
using namespace framework::expected;
using namespace shared_model::interface::types;

using iroha::ametsuchi::QueryExecutorResult;
using shared_model::interface::AccountDetailResponse;
using shared_model::interface::permissions::Grantable;
using shared_model::interface::permissions::Role;
using shared_model::plain::AccountDetailRecordId;

struct GetAccountDetailTest : public ExecutorTestBase {
  std::string makeAccountName(size_t i) const {
    return (boost::format("account_%02d") % i).str();
  }

  AccountIdType makeAccountId(size_t i) const {
    return makeAccountName(i) + "@" + kDomain;
  }

  std::string makeKey(size_t i) const {
    return (boost::format("key_%02d") % i).str();
  }

  std::string makeValue(size_t writer, size_t key) const {
    return (boost::format("value_w%02d_k%02d") % writer % key).str();
  }

  /**
   * Add details to kUserId.
   * @param num_accounts are created and each adds
   * @param num_keys_per_account detail pieces to kUserId.
   */
  void addDetails(const size_t num_accounts,
                  const size_t num_keys_per_account) {
    SCOPED_TRACE("addDetails");
    for (size_t acc = 0; acc < num_accounts; ++acc) {
      IROHA_ASSERT_RESULT_VALUE(
          getItf().createUserWithPerms(makeAccountName(acc),
                                       kDomain,
                                       kSameDomainUserKeypair.publicKey(),
                                       {}));
      IROHA_ASSERT_RESULT_VALUE(getItf().executeCommandAsAccount(
          *getItf().getMockCommandFactory()->constructGrantPermission(
              makeAccountId(acc), Grantable::kSetMyAccountDetail),
          kUserId,
          true));
      auto &added_writer = added_data_[makeAccountId(acc)];
      for (size_t key = 0; key < num_keys_per_account; ++key) {
        IROHA_ASSERT_RESULT_VALUE(getItf().executeCommandAsAccount(
            *getItf().getMockCommandFactory()->constructSetAccountDetail(
                kUserId, makeKey(key), makeValue(acc, key)),
            makeAccountId(acc),
            true));
        added_writer[makeKey(key)] = makeValue(acc, key);
      }
    }
  }

  std::unique_ptr<shared_model::interface::MockAccountDetailPaginationMeta>
  makePaginationMeta(
      TransactionsNumberType page_size,
      const boost::optional<AccountDetailRecordId> &requested_first_record_id) {
    boost::optional<const shared_model::interface::AccountDetailRecordId &>
        first_record_id;
    if (requested_first_record_id) {
      first_record_id = requested_first_record_id.value();
    }  // convert to boost::optional ctor?
    return getItf().getMockQueryFactory()->constructAccountDetailPaginationMeta(
        page_size, first_record_id);
  }

  /// Query account details.
  QueryExecutorResult queryPage(
      boost::optional<std::string> writer,
      boost::optional<std::string> key,
      boost::optional<AccountDetailRecordId> first_record_id,
      size_t page_size,
      const AccountIdType &command_issuer = kAdminId) {
    auto page_meta = makePaginationMeta(page_size, first_record_id);
    return getItf().executeQuery(
        *getItf().getMockQueryFactory()->constructGetAccountDetail(
            kUserId, std::move(key), std::move(writer), *page_meta),
        command_issuer);
  }

  void prepareState(const size_t num_accounts,
                    const size_t num_keys_per_account) {
    SCOPED_TRACE("prepareState");
    getItf().createDomain(kSecondDomain);
    IROHA_ASSERT_RESULT_VALUE(getItf().createUserWithPerms(
        kUser, kDomain, kUserKeypair.publicKey(), {Role::kSetMyAccountDetail}));
    addDetails(num_accounts, num_keys_per_account);
  }

  void validatePageResponse(
      const QueryExecutorResult &response,
      boost::optional<std::string> writer,
      boost::optional<std::string> key,
      boost::optional<shared_model::plain::AccountDetailRecordId>
          first_record_id,
      size_t page_size) {
    checkSuccessfulResult<shared_model::interface::AccountDetailResponse>(
        response, [&, this](const auto &response) {
          this->validatePageResponse(
              response, writer, key, first_record_id, page_size);
        });
  }

  /**
   * Query account assets and validate the response.
   */
  template <typename... Types>
  QueryExecutorResult queryPageAndValidateResponse(Types &&... args) {
    auto response = queryPage(args...);
    validatePageResponse(response, std::forward<Types>(args)...);
    return response;
  }

 protected:
  struct Response {
    size_t total_number{0};
    boost::optional<shared_model::plain::AccountDetailRecordId> next_record;
    DetailsByKeyByWriter details;
  };

  /**
   * Exhaustive check of the page response.
   * @param response the response of GetAccountDetail query
   * @param expected_response the reference to compare with
   */
  void validatePageResponse(const AccountDetailResponse &response,
                            const Response &expected_response) {
    EXPECT_EQ(response.totalNumber(), expected_response.total_number);
    if (expected_response.next_record) {
      if (not response.nextRecordId()) {
        ADD_FAILURE() << "nextRecordId not set!";
      } else {
        EXPECT_EQ(response.nextRecordId()->writer(),
                  expected_response.next_record->writer());
        EXPECT_EQ(response.nextRecordId()->key(),
                  expected_response.next_record->key());
      }
    } else {
      EXPECT_FALSE(response.nextRecordId());
    }
    checkJsonData(response.detail(), expected_response.details);
  }

  /**
   * Exhaustive check of the page response.
   * @param response the response of GetAccountDetail query
   * @param writer requested data writer
   * @param key requested data key
   * @param first_record_id requested first record id
   * @param page_size requested page size
   */
  void validatePageResponse(
      const AccountDetailResponse &response,
      boost::optional<std::string> writer,
      boost::optional<std::string> key,
      boost::optional<AccountDetailRecordId> first_record_id,
      size_t page_size) {
    Response expected_response = this->getExpectedResponse(
        writer, key, std::move(first_record_id), page_size);
    validatePageResponse(response, expected_response);
  }

  /**
   * @return an internal representation of expected correct response for the
   * given parameters.
   */
  Response getExpectedResponse(
      const boost::optional<std::string> &req_writer,
      const boost::optional<std::string> &req_key,
      const boost::optional<shared_model::plain::AccountDetailRecordId>
          &first_record_id,
      size_t page_size) {
    auto optional_match = [](const auto &opt, const auto &val) {
      return not opt or opt.value() == val;
    };

    Response expected_response;
    size_t expected_page_size = 0;
    bool page_started = false;
    bool page_ended = false;
    for (const auto &added_writer_and_data : this->added_data_) {
      const auto &writer = added_writer_and_data.first;
      const auto &added_data_by_writer = added_writer_and_data.second;

      // check if writer matches query
      if (optional_match(req_writer, writer)) {
        for (const auto &key_and_value : added_data_by_writer) {
          const auto &key = key_and_value.first;
          const auto &val = key_and_value.second;

          // check if key matches query
          if (optional_match(req_key, key)) {
            ++expected_response.total_number;
            page_started = page_started
                or optional_match(first_record_id,
                                  shared_model::plain::AccountDetailRecordId{
                                      writer, key});
            if (page_started) {
              if (page_ended) {
                if (not expected_response.next_record) {
                  expected_response.next_record =
                      shared_model::plain::AccountDetailRecordId{writer, key};
                }
              } else {
                expected_response.details[writer][key] = val;
                ++expected_page_size;
                page_ended |= expected_page_size >= page_size;
              }
            }
          }
        }
      }
    }
    return expected_response;
  }

  // added account details
  DetailsByKeyByWriter added_data_;
};

enum GetAccountDetailRecordIdVariant {
  kAllDetails,
  kDetailsByWriter,
  kDetailsByKey,
  kSingleDetail,
};

struct GetAccountDetailRecordIdTest
    : public GetAccountDetailTest,
      public ::testing::WithParamInterface<
          std::tuple<std::shared_ptr<ExecutorTestParam>,
                     GetAccountDetailRecordIdVariant>> {
  GetAccountDetailRecordIdTest()
      : backend_param_(std::get<0>(GetParam())),
        record_id_param_(std::get<1>(GetParam())) {}

  static std::string paramToString(testing::TestParamInfo<ParamType> param) {
    static const std::map<GetAccountDetailRecordIdVariant, std::string>
        record_id_param_names{{kAllDetails, "AllDetails"},
                              {kDetailsByWriter, "DetailsByWriter"},
                              {kDetailsByKey, "DetailsByKey"},
                              {kSingleDetail, "SingleDetail"}};
    return std::get<0>(param.param)->toString()
        + record_id_param_names.at(std::get<1>(param.param));
  }

  boost::optional<std::string> requestedWriter() const {
    if (record_id_param_ == kDetailsByWriter
        or record_id_param_ == kSingleDetail) {
      return makeAccountId(0);
    }
    return boost::none;
  }

  boost::optional<std::string> requestedKey() const {
    if (record_id_param_ == kDetailsByKey
        or record_id_param_ == kSingleDetail) {
      return makeKey(0);
    }
    return boost::none;
  }

  shared_model::plain::AccountDetailRecordId makeFirstRecordId(
      std::string writer, std::string key) {
    return shared_model::plain::AccountDetailRecordId{
        requestedWriter().value_or(std::move(writer)),
        requestedKey().value_or(std::move(key))};
  }

  QueryExecutorResult queryPage(
      boost::optional<shared_model::plain::AccountDetailRecordId>
          first_record_id,
      size_t page_size) {
    return GetAccountDetailTest::queryPage(requestedWriter(),
                                           requestedKey(),
                                           std::move(first_record_id),
                                           page_size);
  }

  QueryExecutorResult queryPage(size_t page_size) {
    return GetAccountDetailTest::queryPage(
        requestedWriter(), requestedKey(), boost::none, page_size);
  }

  void validatePageResponse(
      const QueryExecutorResult &response,
      boost::optional<shared_model::plain::AccountDetailRecordId>
          first_record_id,
      size_t page_size) {
    checkSuccessfulResult<shared_model::interface::AccountDetailResponse>(
        response, [&, this](const auto &response) {
          Response expected_response =
              this->getExpectedResponse(this->requestedWriter(),
                                        this->requestedKey(),
                                        std::move(first_record_id),
                                        page_size);
          this->validatePageResponse(response, expected_response);
        });
  }

  template <typename... Args>
  auto queryPageAndValidateResponse(Args... args)
      -> decltype(queryPage(std::declval<Args>()...)) {
    auto response = queryPage(args...);
    validatePageResponse(response, args...);
    return response;
  }

  template <typename... Args>
  auto validatePageResponse(Args &&... args)
      -> decltype(GetAccountDetailTest::validatePageResponse(args...)) {
    return GetAccountDetailTest::validatePageResponse(
        std::forward<Args>(args)...);
  }

 protected:
  virtual std::shared_ptr<ExecutorTestParam> getBackendParam() {
    return backend_param_;
  }

 private:
  const std::shared_ptr<ExecutorTestParam> &backend_param_;
  const GetAccountDetailRecordIdVariant record_id_param_;
};

/**
 * @given two users with all related permissions
 * @when GetAccountDetail is queried on the user with no details
 * @then there is an empty AccountDetailResponse
 */
TEST_P(GetAccountDetailRecordIdTest, NoDetail) {
  prepareState(0, 0);
  queryPageAndValidateResponse(makeFirstRecordId(makeAccountId(1), makeKey(1)),
                               1);
}

/**
 * @given a user with all related permissions
 * @when GetAccountDetail is queried on a nonexistent user
 * @then there is an error
 */
TEST_P(GetAccountDetailRecordIdTest, InvalidNoAccount) {
  checkQueryError<shared_model::interface::NoAccountDetailErrorResponse>(
      GetAccountDetailTest::queryPage(
          makeAccountId(1), makeKey(1), boost::none, 1),
      error_codes::kNoStatefulError);
}

/**
 * @given account with all related permissions
 * @when GetAccountDetail is queried without page metadata
 * @then all details are returned and are valid
 */
TEST_P(GetAccountDetailRecordIdTest, NoPageMetaData) {
  ASSERT_NO_FATAL_FAILURE(prepareState(3, 3));
  QueryExecutorResult response = getItf().executeQuery(
      *getItf().getMockQueryFactory()->constructGetAccountDetail(
          kUserId, requestedKey(), requestedWriter(), boost::none));
  validatePageResponse(response, boost::none, 9);
}

/**
 * @given account with all related permissions and 10 assets
 * @when queried assets page of size 5 starting from unknown asset
 * @then error response is returned
 */
TEST_P(GetAccountDetailRecordIdTest, NonexistentFirstRecordId) {
  ASSERT_NO_FATAL_FAILURE(prepareState(1, 1));
  auto response =
      queryPage(AccountDetailRecordId{makeAccountId(2), makeKey(2)}, 5);
  checkQueryError<shared_model::interface::StatefulFailedErrorResponse>(
      response, error_codes::kInvalidPagination);
}

/**
 * @given account with 9 details from 3 writers, 3 unique keys from each,
 * and all related permissions
 * @when queried account details with page size of 2 and first record unset
 * @then the appropriate detail records are returned and are valid
 */
TEST_P(GetAccountDetailRecordIdTest, FirstPage) {
  ASSERT_NO_FATAL_FAILURE(prepareState(3, 3));
  queryPageAndValidateResponse(boost::none, 2);
}

/**
 * @given account with 8 details from 4 writers, 2 unique keys from each,
 * and all related permissions
 * @when queried account details with page size of 3 and first record set to
 * the last key of the second writer
 * @then the appropriate detail records are returned and are valid
 */
TEST_P(GetAccountDetailRecordIdTest, MiddlePageAcrossWriters) {
  ASSERT_NO_FATAL_FAILURE(prepareState(4, 2));
  queryPageAndValidateResponse(makeFirstRecordId(makeAccountId(1), makeKey(1)),
                               3);
}

/**
 * @given account with 8 details from 2 writers, 4 unique keys from each,
 * and all related permissions
 * @when queried account details with page size of 2 and first record set to
 * the second key of the second writer
 * @then the appropriate detail records are returned and are valid
 */
TEST_P(GetAccountDetailRecordIdTest, MiddlePageAcrossKeys) {
  ASSERT_NO_FATAL_FAILURE(prepareState(2, 4));
  queryPageAndValidateResponse(makeFirstRecordId(makeAccountId(1), makeKey(1)),
                               3);
}
/**
 * @given account with 9 details from 3 writers, 3 unique keys from each,
 * and all related permissions
 * @when queried account details with page size of 2 and first record set to
 * the last key of the last writer
 * @then the appropriate detail records are returned and are valid
 */
TEST_P(GetAccountDetailRecordIdTest, LastPage) {
  ASSERT_NO_FATAL_FAILURE(prepareState(3, 3));
  queryPageAndValidateResponse(makeFirstRecordId(makeAccountId(2), makeKey(2)),
                               2);
}

INSTANTIATE_TEST_SUITE_P(
    Base,
    GetAccountDetailRecordIdTest,
    ::testing::Combine(executor_testing::getExecutorTestParams(),
                       ::testing::ValuesIn({kAllDetails,
                                            kDetailsByWriter,
                                            kDetailsByKey,
                                            kSingleDetail})),
    GetAccountDetailRecordIdTest::paramToString);

using GetAccountDetailPermissionTest =
    query_permission_test::QueryPermissionTest<GetAccountDetailTest>;

TEST_P(GetAccountDetailPermissionTest, QueryPermissionTest) {
  ASSERT_NO_FATAL_FAILURE(prepareState({Role::kSetMyAccountDetail}));
  addDetails(1, 1);
  checkResponse<shared_model::interface::AccountDetailResponse>(
      queryPage(makeAccountId(0), makeKey(0), boost::none, 1, getSpectator()),
      [this](const shared_model::interface::AccountDetailResponse &response) {
        this->validatePageResponse(
            response, makeAccountId(0), makeKey(0), boost::none, 1);
      });
}

INSTANTIATE_TEST_SUITE_P(
    Common,
    GetAccountDetailPermissionTest,
    query_permission_test::getParams({Role::kGetMyAccDetail},
                                     {Role::kGetDomainAccDetail},
                                     {Role::kGetAllAccDetail}),
    query_permission_test::paramToString);

max_stars_repo_name: e-ivkov/iroha

max_issues_repo_name: e-ivkov/iroha

max_forks_repo_name: e-ivkov/iroha


text:
//  (C) Copyright Nick Thompson 2020.
//  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)

#include <random>
#include <benchmark/benchmark.h>
#include <boost/math/special_functions/jacobi_theta.hpp>
#include <boost/multiprecision/float128.hpp>
#include <boost/multiprecision/mpfr.hpp>
#include <boost/multiprecision/cpp_bin_float.hpp>

using boost::multiprecision::number;
using boost::multiprecision::mpfr_float_backend;
using boost::multiprecision::float128;
using boost::multiprecision::cpp_bin_float_50;
using boost::multiprecision::cpp_bin_float_100;
using boost::math::jacobi_theta1;
using boost::math::jacobi_theta1tau;

template<class Real>
void JacobiTheta1(benchmark::State& state)
{
    std::random_device rd;
    std::mt19937_64 mt(rd());
    std::uniform_real_distribution<long double> unif(0,0.01);

    Real x = static_cast<Real>(unif(mt));
    Real q = static_cast<Real>(unif(mt));
    for (auto _ : state)
    {
        benchmark::DoNotOptimize(jacobi_theta1(x, q));
        x += std::numeric_limits<Real>::epsilon();
    }
}

BENCHMARK_TEMPLATE(JacobiTheta1, float);
BENCHMARK_TEMPLATE(JacobiTheta1, double);
BENCHMARK_TEMPLATE(JacobiTheta1, long double);
BENCHMARK_TEMPLATE(JacobiTheta1, float128);
BENCHMARK_TEMPLATE(JacobiTheta1, number<mpfr_float_backend<100>>);
BENCHMARK_TEMPLATE(JacobiTheta1, number<mpfr_float_backend<200>>);
BENCHMARK_TEMPLATE(JacobiTheta1, number<mpfr_float_backend<300>>);
BENCHMARK_TEMPLATE(JacobiTheta1, number<mpfr_float_backend<400>>);
BENCHMARK_TEMPLATE(JacobiTheta1, number<mpfr_float_backend<1000>>);
BENCHMARK_TEMPLATE(JacobiTheta1, cpp_bin_float_50);
BENCHMARK_TEMPLATE(JacobiTheta1, cpp_bin_float_100);

template<class Real>
void JacobiTheta1Tau(benchmark::State& state)
{
    std::random_device rd;
    std::mt19937_64 mt(rd());
    std::uniform_real_distribution<long double> unif(0,0.01);

    Real x = static_cast<Real>(unif(mt));
    Real q = static_cast<Real>(unif(mt));
    for (auto _ : state)
    {
        benchmark::DoNotOptimize(jacobi_theta1tau(x, q));
        x += std::numeric_limits<Real>::epsilon();
    }
}

BENCHMARK_TEMPLATE(JacobiTheta1Tau, float);
BENCHMARK_TEMPLATE(JacobiTheta1Tau, double);
BENCHMARK_TEMPLATE(JacobiTheta1Tau, long double);
BENCHMARK_TEMPLATE(JacobiTheta1Tau, float128);
BENCHMARK_TEMPLATE(JacobiTheta1Tau, number<mpfr_float_backend<100>>);
BENCHMARK_TEMPLATE(JacobiTheta1Tau, number<mpfr_float_backend<200>>);
BENCHMARK_TEMPLATE(JacobiTheta1Tau, number<mpfr_float_backend<300>>);
BENCHMARK_TEMPLATE(JacobiTheta1Tau, number<mpfr_float_backend<400>>);
BENCHMARK_TEMPLATE(JacobiTheta1Tau, number<mpfr_float_backend<1000>>);
BENCHMARK_TEMPLATE(JacobiTheta1Tau, cpp_bin_float_50);
BENCHMARK_TEMPLATE(JacobiTheta1Tau, cpp_bin_float_100);

BENCHMARK_MAIN();

max_stars_repo_name: oleg-alexandrov/math

max_issues_repo_name: oleg-alexandrov/math


text:
/*
   Simple echo server example
*/

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

const char SERVER_IP[] = "127.0.0.1";
const unsigned short PORT_NUMBER = 31400;

int main() {
  // io_service: 커널에서 발생한 I/O 이벤트를 디스 패치해주는 클래스
  // 접속 받기/하기, 데이터 받기/보내기 이벤트를 알 수 있다
  // socket과 같은 객체 생성 시 io_service를 인자로 넘겨줌
  boost::asio::io_service io_service;

  // endpoint: 네트워크 주소를 설정한다(이 주소로 클라이언트가 접속)
  //
  boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(),
                                          PORT_NUMBER);

  // acceptor: 클라이언트의 접속을 받아들임 (io_service와 endpoint를 인자로
  // 받음)
  boost::asio::ip::tcp::acceptor acceptor(io_service, endpoint);

  // socket: 접속한 클라이언트에 할당할 소켓
  // 클라이언트와 메세지를 주고 받으므로, io_service를 인자로 넣음
  boost::asio::ip::tcp::socket socket(io_service);

  // 클라이언트의 접속을 기다림 (동기방식)
  acceptor.accept(socket);
  std::cout << "클라이언트 접속"
            << "\n";

  for (;;) {
    std::array<char, 128> buf;
    buf.fill(0);
    boost::system::error_code error;

    // read_some(): 클라이언트가 보낸 데이터를 받는다
    size_t len = socket.read_some(boost::asio::buffer(buf), error);

    if (error) {
      // 에러 발생 시, 진짜 에러인지, 접속이 끊긴문제인지를 꼭 구분해야 한다
      if (error == boost::asio::error::eof) {
        std::cout << "클라이언트와 연결이 끊어졌습니다"
                  << "\n";
      } else {
        std::cout << "error No: " << error.value()
                  << " error Message: " << error.message() << "\n";
      }
      break;
    }

    std::cout << "클라이언트에서 받은 메세지: " << &buf[0] << std::endl;
    char szMessage[128] = {
        0,
    };
    snprintf(szMessage, 128 - 1, "Re: %s", &buf[0]);
    int nMsgLen = strnlen(szMessage, 128 - 1);

    boost::system::error_code ignored_error;

    // write_some() : 클라이언트에 메세지를 보냄
    // asio:buffer는 char 뿐 아니라,  array, vector, string 등 STL과 호환이 잘
    // 된다
    socket.write_some(boost::asio::buffer(szMessage, nMsgLen), ignored_error);
    std::cout << "클라이언트에 보낸 메세지: " << szMessage << std::endl;
  }
  getchar();

  return 0;
}


text:
#include <aslam/calibration/model/sensors/Imu.h>

#include <glog/logging.h>

#include <boost/make_shared.hpp>
#include <bsplines/NsecTimePolicy.hpp>
#include <bsplines/EuclideanBSpline.hpp>
#include <aslam/backend/QuadraticIntegralError.hpp>
#include <aslam/backend/Vector2RotationQuaternionExpressionAdapter.hpp>
#include <aslam/splines/OPTBSpline.hpp>

#include "aslam/calibration/calibrator/CalibratorI.h"
#include "aslam/calibration/data/AccelerometerMeasurement.h"
#include "aslam/calibration/data/GyroscopeMeasurement.h"
#include <aslam/calibration/DesignVariableReceiver.h>
#include <aslam/calibration/algo/splinesToFile.h>
#include <aslam/calibration/model/Model.h>
#include <aslam/calibration/model/fragments/TrajectoryCarrier.h>
#include <aslam/calibration/model/ModuleTools.h>
#include <aslam/calibration/calibrator/StateCarrier.h>
#include "aslam/calibration/error-terms/ErrorTermAccelerometer.h"
#include "aslam/calibration/error-terms/ErrorTermGyroscope.h"
#include "aslam/calibration/tools/ErrorTermStatisticsWithProblemAndPredictor.h"
#include "aslam/calibration/tools/SplineWriter.h"

namespace aslam {
namespace calibration {

Imu::Imu(Model& model, const std::string& name, sm::value_store::ValueStoreRef config) :
    Sensor(model, name, config),
    measurements_(std::make_shared<Measurements>()),
    useAcc_(getMyConfig().getBool("acc/used", true)),
    useGyro_(getMyConfig().getBool("gyro/used", true)),
    covAcc_{getMyConfig().getChild("acc/noise/cov"), 3, useAcc_},
    covGyro_{getMyConfig().getChild("gyro/noise/cov"), 3, useGyro_},
    enforceAccCovariance_(getMyConfig().getBool("acc/enforceCovariance", false)),
    enforceGyroCovariance_(getMyConfig().getBool("gyro/enforceCovariance", false)),
    accBias(*this, "accBias", getMyConfig().getChild("acc")),
    gyroBias(*this, "gyroBias", getMyConfig().getChild("gyro")),
    minimalMeasurementsPerBatch(getMyConfig().getInt("minimalMeasurementsPerBatch", 100)),
    inertiaFrame(getModel().getFrame(getMyConfig().getString("inertiaFrame")))
{
  if(isUsed()){
    SM_ASSERT_GE(std::runtime_error, minimalMeasurementsPerBatch, 0, "");
    if(useAcc_){
      accRandomWalk = getMyConfig().getDouble("acc/noise/biasRandomWalk");
    }
    if(useGyro_){
      gyroRandomWalk = getMyConfig().getDouble("gyro/noise/biasRandomWalk");
    }
  }

//TODO C support MESTIMATORS:  setMEstimator(boost::shared_ptr<aslam::backend::MEstimator>(new aslam::backend::CauchyMEstimator(10)));
}

void Imu::writeConfig(std::ostream& out) const {
  Sensor::writeConfig(out);

  MODULE_WRITE_PARAM(inertiaFrame);

  //TODO D write bias mode

  MODULE_WRITE_PARAM(useAcc_);
  if(useAcc_){
    MODULE_WRITE_PARAM(covAcc_);
    MODULE_WRITE_PARAM(enforceAccCovariance_);
    if(accBias.isUsed()){
      MODULE_WRITE_PARAM(accRandomWalk);
    }
  }
  MODULE_WRITE_PARAM(useGyro_);
  if(useGyro_){
    MODULE_WRITE_PARAM(covGyro_);
    MODULE_WRITE_PARAM(enforceGyroCovariance_);
    if(accBias.isUsed()){
      MODULE_WRITE_PARAM(gyroRandomWalk);
    }
  }

  MODULE_WRITE_PARAM(minimalMeasurementsPerBatch);
}

void Imu::registerWithModel() {
  Sensor::registerWithModel();
  if(useAcc_)
    accBias.registerCalibrationVariables(getModel());
  if(useGyro_)
    gyroBias.registerCalibrationVariables(getModel());
}

Imu::~Imu() = default;

typedef aslam::splines::OPTBSpline<typename bsplines::EuclideanBSpline<Eigen::Dynamic, 3, bsplines::NsecTimePolicy>::CONF>::BSpline BiasSpline;

class BiasBatchState : public BatchState {
 public:
  BiasBatchState(const TrajectoryCarrier & carrier, const std::string & name);
  void writeToFile(const CalibratorI & calib, const std::string & pathPrefix) const override;
  void addToProblem(DesignVariableReceiver & problem) const;

 private:
  std::string name_;
  BiasSpline biasSpline;
  friend Bias;
  friend Imu;
};

Bias::Bias(Module & m, const std::string & name, sm::value_store::ValueStoreRef config) :
    NamedMinimal(name)
{
  if (config.getBool("hasBias", true)) {
    biasVector = m.createCVIfUsed<EuclideanPointCv>(config.getChild("biasVector"), name);
    if (biasVector) {
      mode_ = Mode::Vector;
      biasVectorExpression = biasVector->toExpression();
    } else if (m.isUsed()) {
      mode_ = Mode::Spline;
      biasSplineCarrier.reset(new TrajectoryCarrier(config.getChild("biasSpline")));
    }
  } else {
    mode_ = Mode::None;
  }
}

void Bias::registerCalibrationVariables(Model& model) {
  if (biasVector) {
    model.addCalibrationVariables({biasVector});
  }
}

void Bias::initState(CalibratorI & calib){
  if (isUsingSpline()) {
    state_ = std::make_shared<BiasBatchState>(*biasSplineCarrier, getName());
    const auto & interval = calib.getCurrentEffectiveBatchInterval();
    const double elapsedTime = interval.getElapsedTime();
    const int numSegments = std::ceil(biasSplineCarrier->getKnotsPerSecond() * elapsedTime);
    LOG(INFO)<< "using IMU bias numSegments=" << numSegments << " for " << elapsedTime << " seconds";

    //TODO D make bias initial guess based on IMU measurements!

    state_->biasSpline.initConstantUniformSpline(interval.start, interval.end, numSegments, Eigen::Vector3d::Zero());
  }
}

void Bias::addToBatch(bool stateActive, BatchStateReceiver & batchStateReceiver, DesignVariableReceiver & problem) {
  if(state_){
    problem.addSplineDesignVariables(state_->biasSpline, stateActive);
    batchStateReceiver.addBatchState(*this, state_);
  }
}

bool Imu::initState(CalibratorI& calib) {
  if(isUsed()){
    accBias.initState(calib);
    gyroBias.initState(calib);
  }
  return true;
}
void Imu::addToBatch(const Activator & stateActivator, BatchStateReceiver & batchStateReceiver, DesignVariableReceiver & problem) {
  const bool stateActive = stateActivator.isActive(*this);
  if(useAcc_){
    accBias.setActive(stateActive);
    accBias.addToBatch(stateActive, batchStateReceiver, problem);
  }
  if(useGyro_){
    gyroBias.setActive(stateActive);
    gyroBias.addToBatch(stateActive, batchStateReceiver, problem);
  }
}

void Imu::setActive(bool spatial, bool temporal) {
  Sensor::setActive(spatial, temporal);
}

BiasBatchState::BiasBatchState(const TrajectoryCarrier & carrier, const std::string & name)
    : name_(name), biasSpline(carrier.getSplineOrder())
{
}

void BiasBatchState::writeToFile(const CalibratorI & calib, const std::string& pathPrefix) const {
  writeSpline(biasSpline, calib.getOptions().getSplineOutputSamplePeriod(), pathPrefix + name_);
}

void Imu::addAccelerometerMeasurement(CalibratorI & calib, const AccelerometerMeasurement& data, Timestamp timestamp) const {
  calib.addMeasurementTimestamp(timestamp, *this);
  measurements_->accelerometer.emplace_back(timestamp, data);
}

void Imu::addGyroscopeMeasurement(CalibratorI & calib, const GyroscopeMeasurement& data, Timestamp timestamp) const {
  calib.addMeasurementTimestamp(timestamp, *this);
  measurements_->gyroscope.emplace_back(timestamp, data);
}

void Imu::addInputTo(Timestamp t, const AccelerometerMeasurement& input, ModuleStorage&) const {
  measurements_->accelerometer.emplace_back(t, input);
}

void Imu::addInputTo(Timestamp t, const GyroscopeMeasurement& input, ModuleStorage&) const {
  measurements_->gyroscope.emplace_back(t, input);
}

void Imu::clearMeasurements() {
  measurements_->accelerometer.clear();
  measurements_->gyroscope.clear();
}

using namespace aslam::backend;

template<typename BSpline_>
struct BiasModelIntegrationErrorExpressionFactory {
  typedef BSpline_ BSplineT;
  typedef typename BSplineT::time_t TimeT;
  enum { PointSize = 3 };
  typedef VectorExpression<PointSize> value_expression_t;
  typedef Eigen::Matrix<double, 1, 1>  value_t;

  const BSplineT & _bspline;
  const Eigen::Matrix<double, PointSize, PointSize> _sqrtInvR;

  BiasModelIntegrationErrorExpressionFactory(const BSplineT & bspline, Eigen::Matrix<double, PointSize, PointSize> sqrtInvR) : _bspline(bspline), _sqrtInvR(sqrtInvR) {}

  inline value_expression_t operator()(TimeT time) const {
    return _bspline.template getExpressionFactoryAt<1>(time).getValueExpression(1);
  }
};

template <typename SplineT>
void addBiasModelErrorTerms(CalibratorI & calib, std::string name, ErrorTermReceiver & errorTermReceiver, const SplineT & spline, const Eigen::MatrixXd & sqrtInvR, bool observeOnly, int numberOfIntegrationPoints = -1){
  BiasModelIntegrationErrorExpressionFactory<SplineT> integrationFunctor(spline, sqrtInvR);
  if(numberOfIntegrationPoints < 0){
    numberOfIntegrationPoints = (spline.getAbsoluteNumberOfSegments() + spline.getSplineOrder()) * 2;
  }

  ErrorTermStatisticsWithProblemAndPredictor stat(calib, name + "Bias", errorTermReceiver, observeOnly);

  aslam::backend::integration::addQuadraticIntegralExpressionErrorTerms<aslam::backend::integration::DefaultAlgorithm>(stat, spline.getMinTime(), spline.getMaxTime(), numberOfIntegrationPoints, integrationFunctor, sqrtInvR);

  stat.printInto(LOG(INFO));
}

template <typename T, typename ErrorTermFactory>
void addImuErrorTerms(CalibratorI & calib, const Imu & imu, std::string name, const MeasurementsContainer<T>& measurements, ErrorTermFactory etFactory, ErrorTermReceiver & errorTermReceiver, bool observeOnly) {
  LOG(INFO) << "Adding " << measurements.size() << " " << name << " error terms";

  ErrorTermStatisticsWithProblemAndPredictor statWPAP(calib, name, errorTermReceiver, observeOnly);
  const Interval & interval = calib.getCurrentEffectiveBatchInterval();

  Timestamp minTime = interval.end, maxTime = interval.start;

  for (auto & m : measurements) {
    Timestamp timestamp = m.first;
    if (!interval.contains(timestamp, imu)){
      LOG(INFO) << name << " measurement out of spline range at " << calib.secsSinceStart(timestamp) << "s.";
      continue;
    }

    if(minTime > timestamp) minTime = timestamp;
    if(maxTime < timestamp) maxTime = timestamp;

    auto e = etFactory(timestamp, m.second);

    if(imu.getMEstimator()){
      e->setMEstimatorPolicy(imu.getMEstimator());
    }

    VLOG(2) << "Cost function " << name << " : " << e->evaluateError() << " count: " << statWPAP.getCounter() << " timestamp: " << calib.secsSinceStart(timestamp) << "s,";
    statWPAP.add(timestamp, e);
  }
  statWPAP.printInto(LOG(INFO)) << " Between " << calib.secsSinceStart(minTime) << "s and " << calib.secsSinceStart(maxTime) << "s.";
}

template <typename T>
bool isCovarianceAvailable(T&t){
  return t.cov(0,0) > 0.0;
}

void Imu::addMeasurementErrorTerms(CalibratorI & calib, const CalibrationConfI & /*ec*/, ErrorTermReceiver & errorTermReceiver, bool observeOnly) const {
  if(useAcc_){
    const std::string accelerometerName = getName() + "Accelerometer";
    if(accBias.isUsingSpline()){
      addBiasModelErrorTerms(calib, accelerometerName, errorTermReceiver, accBias.state_->biasSpline, Eigen::Matrix3d::Identity() / accRandomWalk, observeOnly);
    }

    //TODO C solve gravity vector problem. Each model has a gravity vector?
    auto g_m = calib.getModel().getGravity().getVectorExpression();
    Eigen::Matrix3d covarianceMatrix = covAcc_.getValue();
    ErrorTermGroupReference etgr(getName() + "Acc");
    addImuErrorTerms(
        calib, *this, accelerometerName, measurements_->accelerometer,
        [&, this](const Timestamp timestamp, const AccelerometerMeasurement & m){
          auto modelAt = calib.getModelAt(*this, timestamp, 2, {false});
          return boost::make_shared<ErrorTermAccelerometer>(
              modelAt.getAcceleration(getFrame(), inertiaFrame),
              getTransformationExpressionTo(modelAt, inertiaFrame).toRotationExpression().inverse(),
              g_m,
              accBias.getBiasExpression(timestamp),
              m.a,
              isCovarianceAvailable(m) && !enforceAccCovariance_ ? m.cov : covarianceMatrix,
              etgr);
        },
        errorTermReceiver,
        observeOnly
      );
  }
  if(useGyro_){
    const std::string gyroscopeName = getName() + "Gyroscope";
    if(gyroBias.isUsingSpline()){
      addBiasModelErrorTerms(calib, gyroscopeName, errorTermReceiver, gyroBias.state_->biasSpline, Eigen::Matrix3d::Identity() / gyroRandomWalk, observeOnly);
    }
    Eigen::Matrix3d covarianceMatrix = covGyro_.getValue();
    ErrorTermGroupReference etgr(getName() + "Gyro");
    addImuErrorTerms(
        calib, *this, gyroscopeName, measurements_->gyroscope,
        [&, this](const Timestamp timestamp, const GyroscopeMeasurement & m){
          auto modelAt = calib.getModelAt(*this,  timestamp, 1, {false});
          return boost::make_shared<ErrorTermGyroscope>(
              getTransformationExpressionTo(modelAt, inertiaFrame).toRotationExpression().inverse() * modelAt.getAngularVelocity(getReferenceFrame(), inertiaFrame),
              gyroBias.getBiasExpression(timestamp),
              m.w,
              isCovarianceAvailable(m) && !enforceGyroCovariance_ ? m.cov : covarianceMatrix,
              etgr
            );
        },
        errorTermReceiver,
        observeOnly
      );
  }
}

double Imu::getMaximalTimeGap() const {
  if(measurements_){
    Timestamp gGap(measurements_->gyroscope.getMaximalTimeGap());
    Timestamp aGap(measurements_->accelerometer.getMaximalTimeGap());
    return std::max(double(gGap), double(aGap));
  } else {
    return 0.0;
  }
}

bool Imu::hasTooFewMeasurements() const {
  return getGyroscopeMeasurements().size() < size_t(minimalMeasurementsPerBatch);
}

aslam::backend::EuclideanExpression Bias::getBiasExpression(Timestamp t) const {
  if(isUsingSpline()){
    SM_ASSERT_NOTNULL(std::runtime_error, state_, "");
    return state_->biasSpline.getExpressionFactoryAt<0>(t).getValueExpression();
  } else {
    return biasVectorExpression;
  }
}

void Imu::addPriorFactors(CalibratorI & calib, ErrorTermReceiver & errorTermReceiver, double priorFactor) const {
  const double invSigma = 1e-2 * priorFactor;
  Timestamp startTime = calib.getCurrentEffectiveBatchInterval().start;
  if(accBias.isUsingSpline()) errorTermReceiver.addErrorTerm(backend::toErrorTerm(accBias.getBiasExpression(startTime), Eigen::Matrix3d::Identity() * invSigma));
  if(gyroBias.isUsingSpline()) errorTermReceiver.addErrorTerm(backend::toErrorTerm(gyroBias.getBiasExpression(startTime), Eigen::Matrix3d::Identity() * invSigma));
}

} /* namespace calibration */
} /* namespace aslam */


text:
#ifndef CANARD_NET_OFP_V13_ERROR_CODE_HPP
#define CANARD_NET_OFP_V13_ERROR_CODE_HPP

#include <tuple>
#include <boost/fusion/container/map.hpp>
#include <boost/fusion/sequence/intrinsic/value_at_key.hpp>
#include <boost/fusion/support/pair.hpp>
#include <canard/net/ofp/v13/openflow.hpp>

namespace canard {
namespace net {
namespace ofp {
namespace v13 {

  namespace error_code_detail {

    template <class ErrorCode, protocol::error_type ErrorType>
    using pair = boost::fusion::pair<
      ErrorCode, std::integral_constant<protocol::error_type, ErrorType>
    >;

    using error_code_map = boost::fusion::map<
        pair<protocol::hello_failed_code, protocol::error_type::hello_failed>
      , pair<protocol::bad_request_code, protocol::error_type::bad_request>
      , pair<protocol::bad_action_code, protocol::error_type::bad_action>
      , pair<protocol::bad_instruction_code, protocol::error_type::bad_instruction>
      , pair<protocol::bad_match_code, protocol::error_type::bad_match>
      , pair<protocol::flow_mod_failed_code, protocol::error_type::flow_mod_failed>
      , pair<protocol::group_mod_failed_code, protocol::error_type::group_mod_failed>
      , pair<protocol::port_mod_failed_code, protocol::error_type::port_mod_failed>
      , pair<protocol::table_mod_failed_code, protocol::error_type::table_mod_failed>
      , pair<protocol::queue_op_failed_code, protocol::error_type::queue_op_failed>
      , pair<protocol::switch_config_failed_code, protocol::error_type::switch_config_failed>
      , pair<protocol::role_request_failed_code, protocol::error_type::role_request_failed>
      , pair<protocol::meter_mod_failed_code, protocol::error_type::meter_mod_failed>
      , pair<protocol::table_features_failed_code, protocol::error_type::table_features_failed>
    >;

    template <class ErrorCode>
    using error_type = typename boost::fusion::result_of::value_at_key<
      error_code_map, ErrorCode
    >::type;

  } // namespace error_code_detail

  template <class ErrorCodeType>
  struct error_code
  {
    using type = ErrorCodeType;
    static constexpr protocol::error_type error_type
      = error_code_detail::error_type<type>::value;
  };

  using default_error_code_list = std::tuple<
      error_code<protocol::hello_failed_code>
    , error_code<protocol::bad_request_code>
    , error_code<protocol::bad_action_code>
    , error_code<protocol::bad_instruction_code>
    , error_code<protocol::bad_match_code>
    , error_code<protocol::flow_mod_failed_code>
    , error_code<protocol::group_mod_failed_code>
    , error_code<protocol::port_mod_failed_code>
    , error_code<protocol::table_mod_failed_code>
    , error_code<protocol::queue_op_failed_code>
    , error_code<protocol::switch_config_failed_code>
    , error_code<protocol::role_request_failed_code>
    , error_code<protocol::meter_mod_failed_code>
    , error_code<protocol::table_features_failed_code>
  >;

} // namespace v13
} // namespace ofp
} // namespace net
} // namespace canard

#endif // CANARD_NET_OFP_V13_ERROR_CODE_HPP

ext: hpp


text:
//  bpp.cpp
//  PhyloAcc
//
//  Created by hzr on 3/8/16.
//  Copyright © 2016 hzr. All rights reserved.
//

#include "bpp.hpp"
#include <armadillo>
#include <sys/types.h>
#include <dirent.h>
#include<queue>

#include <cmath>
#include <cassert>

#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_cdf.h>

#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <ctype.h>

#include "newick.h"
#include "utils.h"
#include "bpp_c.hpp"

using namespace std;
using namespace arma;

// load the phylogenetic tree
void BPP::InitPhyloTree(PhyloTree & tree) //, double indel_pi), double indel, double indel2
{

    submat = tree.subs_rate;
    children    = new int[N][2];
    parent      = new int[N];
    distances   = new double[N];
    thetas   = new double[N];
    heights = vector<double>(N);
    move_br = vector<int>(N);

    for(int s=0; s<N; s++)
    {
        distances[s] = tree.distances[s];
        thetas[s] = tree.thetas[s];
        heights[s] = 0; // root
    }

    for(int i=0; i<N; i++)
    {
        children[i][0] = -1;
        children[i][1] = -1;
        parent[i] = N;
    }

    for(int i=0; i<N; i++)
    {
        int p = -1;
        for(int j=0; j<N; j++)
        {
            if (tree.dag[i][j])
            {
                p++;
                children[i][p] = j;
                parent[j] = i;
            }
        }
    }

    for(int i = N-2; i >= 0; i--)
    {
        heights[i] = heights[parent[i]] - distances[i]; //heights<=0. root=0. Distance: br length. +ve.
    }
}

// try to match the phylogenetic profile and tree
void BPP::MatchProfAndTree(PhyloProf & _prof, PhyloTree & _tree)
{
    // try to match the species
    bool success_match = true;
    int S = _tree.S;
    int S2 = _prof.S;
    vector<int> reorder(S);  //each species in the tree where is in prof
    for(int s1=0; s1<S; s1++)
    {
        bool has_same_species = false;
        string sname1 = _tree.species_names[s1];
        for(int s2=0; s2<S2; s2++)
        {
            string sname2 = _prof.species_names[s2];
            if (sname1 == sname2)
            {
                has_same_species = true;
                reorder[s1] = s2;
                break;
            }
        }
        if (!has_same_species)
        {
            cout << "No matrix species " << _prof.species_names[s1] << " found in tree." << endl;
            success_match = false;
            break;
        }
    }

    if (!success_match) // if cannot match literally
    {
        cout << endl << "The species in phylogenetic profile and tree cannot be matched literally:" << endl;
        cout << "The program will use the default mapping in data:" << endl;
        for(int s=0; s<S; s++)
            cout << "(" << _prof.species_names[s] << "\t=  " << _tree.species_names[s] << ")" << endl;
        cout << endl;
    }
    else                // if successully matched
    {
        cout << "The species in profile and tree match perfectly. Reorder the species in profile matrix by the tree." << endl << endl;
        vector<string> old_X = _prof.X;
        for(int s=0; s<S; s++)
        {
            int reorder_s = reorder[s];
            _prof.X[s] = old_X[reorder_s];
        }
        _prof.species_names = _tree.species_names;
    }

}

void BPP::InitMCMC(int _num_burn, int _num_mcmc, int _num_thin)
{
    // init parameters
    num_burn = _num_burn;

    num_mcmc = _num_mcmc;
    num_thin = _num_thin;

    last_time = time(NULL);

    // init MCMC sampling storage
    Max_Z = vector<vector < vector <int > >> (3,vector < vector <int >>  (C,vector <int > (N,0)));
    cur_Z = vector<vector < vector <int > >> (3,vector < vector <int >>  (C,vector <int > (N,0)));

    genetrees = vector<vector<string>>(3, vector<string>(C)); // for max gene tree

    log_liks_null = vector <double>(C,0);
    log_liks_null_L = vector <double>(C,0);
    log_liks_Z = vector<vector <double>>(3,vector <double>(C,0));
    log_liks_sgl = vector <double>(C,0);
    log_liks_resZ = vector <double>(C,0);
    log_liks_sgl_L = vector <double>(C,0);
    log_liks_resZ_L = vector <double>(C,0);
    log_liks_WL = vector< vector <double> > (3, vector <double>(C, 0));
    log_mle = vector<vector<double> > (3, vector<double> (C,0));

    log_liks_curZ = vector <double>(C,0);
    log_liks_propZ = vector <double>(C,0);
    MH_ratio_gain = vector <double>(C,0);
    MH_ratio_loss = vector <double>(C,0);

    cur_crate = vector <double>(C,ratio0);
    cur_nrate = vector <double>(C,ratio1);

    cur_lrate = vector <double>(C,ind_lrate);
    cur_lrate2 = vector <double>(C,ind_lrate2);
    cur_grate = vector <double>(C, ind_grate);

   //Han*: used to save mode of MCMC output, so one element one vector.
    cur_pi = vector<vector<vector<double>>>(3,vector<vector<double>> (C, vector<double>(4,0.25)));

}

void BPP::sample_proposal(int iter, double & lrate_prop, double & grate_prop, ofstream & output)
{
    lrate_prop =gsl_ran_beta(RNG, ind_lrate * vlr, (1 - ind_lrate) *vlr); // let vlr == vgr!!
    grate_prop =gsl_ran_beta(RNG, ind_grate * vgr, (1 - ind_grate - ind_lrate) *vgr); //gsl_ran_gamma(RNG, vgr, ind_grate/vgr);
    grate_prop = grate_prop * (1 - lrate_prop);

    output << iter << "\t"<< nprior_a<< "\t"<< nprior_b <<"\t"<< cprior_a << "\t"<< cprior_b << "\t"<< indel << "\t"<< indel2 << "\t"<<ind_grate<< "\t"<< ind_lrate <<endl;
}

vec BPP::getlogTM(double dist, double rate, mat & lam )
{
    mat tmp_diag  = exp(eigenval* dist * rate);
    mat x = eigenvec;
    x.each_col()%=tmp_diag;

    mat log_cache_TM = log(eigeninv * x) ; //transpose Q
    return(log_multi(log_cache_TM, lam.col(lam.n_cols -1)));
}

mat BPP::getlogTM(double dist, double rate) //Han: get log transition matrix.
{
    if(dist < 1e-8)
    {
        mat x(num_base, num_base);
        x.fill(-INFINITY);
        x.diag().zeros();
        return(x);
    }
    mat tmp_diag  = exp(eigenval* dist * rate);
    mat x = eigenvec;
    x.each_col()%=tmp_diag;

    return(log(eigeninv * x)) ; //transpose Q

}

//Han*: new function. to account for updated Q
//For each element, since eigen value/vec changed
mat BPP::getlogTMc(double dist, double rate, mat& c_eigenvec, mat& c_eigenval, mat& c_eigeninv)
{
    if(dist < 1e-8)
    {
        mat x(num_base, num_base);
        x.fill(-INFINITY);
        x.diag().zeros();
        return(x);
    }
    mat tmp_diag  = exp(c_eigenval* dist * rate);
    mat x = c_eigenvec;
    x.each_col()%=tmp_diag;

    return(log(c_eigeninv * x)) ; //transpose Q //element-wise log
}

mat BPP::getlogTM_len(double dist, mat& c_eigenvec, mat& c_eigenval, mat& c_eigeninv){
    if(dist < 1e-8){
        mat x(num_base, num_base);
        x.fill(-INFINITY);
        x.diag().zeros();
        return(x);
    }
    mat tmp_diag  = exp(c_eigenval* dist);
    mat x = c_eigenvec;
    x.each_col()%=tmp_diag;

    return(log(c_eigeninv * x)) ; //transpose Q
}

double BPP::log_lik(vector< vector<vec> > & lambda, double _indel, double _indel2, int start1, int end1, vector<unsigned int> & v, double p)
{
    // compute loglik
    double result =0;
    mat x(2,2);

    int rr = *subtree.rbegin();
    // 1. sending the lambda msg from leaves bottom up through the network
    for(vector<int>::iterator it = subtree.begin(); it!=subtree.end(); it++) //int s=S; s<N; s++)
    {
        int s = *it;
        if(s<S) continue;
        int* p = children[s];
        for(int it = start1; it < end1; it++)  lambda[v[it]][s].fill(0);

        for(int cc=0;cc<2;cc++)
        {
            int chi = p[cc];
            assert(chi != -1);
            if(distances[chi]>0 )
            {
                double tt = (1 - exp(-(_indel + _indel2) * distances[chi]))/(_indel + _indel2);
                x.at(1,0) = _indel * tt;
                x.at(0,0) = 1 - x.at(1,0);

                x.at(0,1) = _indel2 * tt;
                x.at(1,1) = 1 - x.at(0,1);

                //cout << x;
                x = log(x);

            }
            else{
                x.fill(-INFINITY); //83, root
                x.diag().fill(0);
            }

            #pragma omp parallel for schedule (guided)
            for(int it = start1; it < end1; it++)  lambda[v[it]][s] +=  BPP::log_multi(x,lambda[v[it]][chi]);
        }

    }

    // 2. processing the distribution of root species
    for(int it = start1; it < end1; it++)
    {

        lambda[v[it]][rr][0] += log(1-p); //N-1
        lambda[v[it]][rr][1] += log(p) ;
        result += BPP::log_exp_sum(lambda[v[it]][rr]);
    }

    return(result);
}

void BPP::sample_hyperparam(int iter, vector<int> & ids, ofstream & output) // recompute log_TM, double indel_prop, double indel2_prop,
{
    //indepent MH to sample hyperparam of rates
    double p=1,r = 1; //hyperparam for shape
    double q=0.1,s = 0.1; // hyperparam for scale

    double vna = 100, vnb = 100, vca = 100, vcb = 100;
    double nprior_a_prop =gsl_ran_gamma(RNG, vna, nprior_a/vna);
    double cprior_a_prop =gsl_ran_gamma(RNG, vca, cprior_a/vca);

    double nprior_b_prop =gsl_ran_gamma(RNG, vnb, nprior_b/vnb);
    double cprior_b_prop =gsl_ran_gamma(RNG, vcb, cprior_b/vcb);

    //MH proposal
    double sum_r = 0;
    double log_prod_r = 0;
    for(std::size_t i = 0; i < ids.size(); i++ )  // 0702
    {
        int c = ids[i];
        sum_r += cur_nrate[c];
        //var_r += pow(*it, 2);
        log_prod_r += log(cur_nrate[c]);
    }

    double M_ratio = (nprior_a_prop - 1) * (log(p) + log_prod_r) - (q + sum_r)/nprior_b_prop - (ids.size() + r)*lgamma(nprior_a_prop) - log(nprior_b_prop) * nprior_a_prop * (s + ids.size());
    M_ratio -= (nprior_a - 1) * (log(p) + log_prod_r) - (q + sum_r)/nprior_b - (ids.size() + r)*lgamma(nprior_a) - log(nprior_b) * nprior_a * (s + ids.size());

    double H_ratio = log(gsl_ran_gamma_pdf(nprior_a,vna,nprior_a_prop/vna)) - log(gsl_ran_gamma_pdf(nprior_a_prop,vna,nprior_a/vna)) + log(gsl_ran_gamma_pdf(nprior_b,vnb,nprior_b_prop/vnb)) - log(gsl_ran_gamma_pdf(nprior_b_prop,vnb,nprior_b/vnb));

    cout << "nrate_MH_ratio: " << M_ratio <<", " << H_ratio << ", " << nprior_a << ", " << nprior_a_prop << ", " << nprior_b << ", " << nprior_b_prop << endl;

    if(log(gsl_rng_uniform(RNG)) < M_ratio + H_ratio)
    {
        nprior_a = nprior_a_prop;
        nprior_b = nprior_b_prop;
    }

    sum_r = 0;
    log_prod_r = 0;
    //for(vector<double>::iterator it = cur_crate.begin(); it< cur_crate.end(); it++)
    for(std::size_t i = 0; i < ids.size(); i++ )  // 0702
    {
        int c = ids[i];
        sum_r += cur_crate[c];
        //var_r += pow(*it, 2);
        log_prod_r += log(cur_crate[c]);
    }

    M_ratio = (cprior_a_prop - 1) * (log(p) + log_prod_r) - (q + sum_r)/cprior_b_prop - (ids.size() + r)*lgamma(cprior_a_prop) - log(cprior_b_prop) * cprior_a_prop * (s + ids.size()) - ((cprior_a - 1) * (log(p) + log_prod_r) - (q + sum_r)/cprior_b - (ids.size() + r)*lgamma(cprior_a) - log(cprior_b) * cprior_a * (s + ids.size()));

    H_ratio = log(gsl_ran_gamma_pdf(cprior_a,vca,cprior_a_prop/vca)) - log(gsl_ran_gamma_pdf(cprior_a_prop,vca,cprior_a/vca)) + log(gsl_ran_gamma_pdf(cprior_b,vcb,cprior_b_prop/vcb)) - log(gsl_ran_gamma_pdf(cprior_b_prop,vcb,cprior_b/vcb));

    cout << "crate_MH_ratio: " << M_ratio + H_ratio << ", " << cprior_a << ", " << cprior_a_prop <<", " << cprior_b << ", " << cprior_b_prop << endl;

    if(log(gsl_rng_uniform(RNG)) < M_ratio + H_ratio)
    {
        cprior_a = cprior_a_prop;
        cprior_b = cprior_b_prop;
    }

  // sample hyperparameters of lrate and grate, exponential prior for prior_l_a and prior_l_b, prior_g_a and prior_g_b
    double u = gsl_rng_uniform(RNG)*(1.3 - 0.7) + 0.7; // generate uniform from (1/prop_n, prop_n);
    double prior_l_a_prop = prior_l_a *  u;

    u = gsl_rng_uniform(RNG)*(1.3 - 0.7) + 0.7; // generate uniform from (1/prop_n, prop_n);
    double prior_l_b_prop = prior_l_b *  u;
    double log_p = 0, log_pc = 0;
    for(std::size_t i = 0; i < ids.size(); i++ )  // 0702
    {
        int c = ids[i];
        log_p += log(cur_lrate[c]);
        log_pc += log(1 - cur_lrate[c]);
    }

    M_ratio = (prior_l_a_prop - prior_l_a) * (log_p - 1) + (prior_l_b_prop - prior_l_b) * (log_pc - 1);
    M_ratio += ids.size() * (gsl_sf_lnbeta(prior_l_a, prior_l_b) - gsl_sf_lnbeta(prior_l_a_prop, prior_l_b_prop));

    H_ratio = log(prior_l_a) - log(prior_l_a_prop) + log(prior_l_b) - log(prior_l_b_prop);

    cout << "lrate_MH_ratio: " << M_ratio + H_ratio << ", " << prior_l_a << ", " << prior_l_a_prop <<", " << prior_l_b << ", " << prior_l_b_prop  << endl;

    if(log(gsl_rng_uniform(RNG)) < M_ratio + H_ratio)
    {
        prior_l_a = prior_l_a_prop;
        prior_l_b = prior_l_b_prop;
    }

    // sample grate
    u = gsl_rng_uniform(RNG)*(1.3 - 0.7) + 0.7; // generate uniform from (1/prop_n, prop_n);
    double prior_g_a_prop = prior_g_a *  u;

    u = gsl_rng_uniform(RNG)*(1.3 - 0.7) + 0.7; // generate uniform from (1/prop_n, prop_n);
    double prior_g_b_prop = prior_g_b *  u;
    log_p = 0; log_pc = 0;
    for(std::size_t i = 0; i < ids.size(); i++ )  // 0702
    {
        int c = ids[i];
        log_p += log(cur_grate[c]);
        log_pc += log(1 - cur_grate[c]);
    }

    M_ratio = (prior_g_a_prop - prior_g_a) * (log_p - 1) + (prior_g_b_prop - prior_g_b) * (log_pc - 1);
    M_ratio += ids.size() * (gsl_sf_lnbeta(prior_g_a, prior_g_b) - gsl_sf_lnbeta(prior_g_a_prop, prior_g_b_prop));

    H_ratio = log(prior_g_a) - log(prior_g_a_prop) + log(prior_g_b) - log(prior_g_b_prop);

    cout << "grate_MH_ratio: " << M_ratio + H_ratio << ", " << prior_g_a << ", " << prior_g_a_prop <<", " << prior_g_b << ", " << prior_g_b_prop  << endl;

    if(log(gsl_rng_uniform(RNG)) < M_ratio + H_ratio)
    {
        prior_g_a = prior_g_a_prop;
        prior_g_b = prior_g_b_prop;
    }

    output << iter << "\t"<< nprior_a<< "\t"<< nprior_b <<"\t"<< cprior_a << "\t"<< cprior_b << "\t"<< prior_l_a << "\t"<< prior_l_b << "\t"<< prior_g_a << "\t"<< prior_g_b <<endl;
}

void BPP::getUppertree(int root, vector<int>& child, set<int> & visited_init)  // go to the root, include root!
{
    for(vector<int>::iterator it = child.begin(); it!=child.end(); it++)
    {
       int p = *it;
       while(p!=root)
       {
           visited_init.insert(p);
           p = parent[p];
       }
    }
    visited_init.insert(root);
}

void BPP::getSubtree(int root, vector<int> & visited_init)  // traverse from root to children, include root
{

    int j = root;

    //cout << nodes_names[j]<<"\t";

    if(children[j][0]!=-1)
    {
        for(int chi=0;chi<2;chi++)
        {
            getSubtree(children[j][chi], visited_init);
        }
    }
    visited_init.push_back(j);
}

void BPP::getSubtree(int root, set<int>& child, vector<int> & visited_init)  // traverse from root, stop at children, 74 & 64; do include 1-S!
{
    int j = root;

    //cout << nodes_names[j]<<"\t";
    if(child.find(j) != child.end())
    {
        visited_init.push_back(j);
        return;
    }

    if(children[j][0]!=-1)
    {
        for(int chi=0;chi<2;chi++)
        {
            getSubtree(children[j][chi], child, visited_init);
        }
    }
     visited_init.push_back(j);
}

void BPP::Output_init(PhyloProf & prof, string output_path, vector<int> & ids){

        string outpath_elem = output_path+ "_elem_lik.txt";
        ofstream out_lik(outpath_elem.c_str());
        out_lik.precision(8);

        //out_lik<<"No.\tID\tloglik_Null_W\tloglik_Acc_W\tloglik_Full_W\tlogBF1\tlogBF2\tlogPost_Max_M0\tlogPost_Max_M1\tlogPost_Max_M2\n";
        out_lik<<"No.\tID\tloglik_Null_W\tloglik_Acc_W\tloglik_Full_W\tlogBF1\tlogBF2"<<endl;
        for(vector<int>::iterator it = ids.begin(); it !=ids.end(); it++)
        {
            int cc = *it;
            out_lik <<cc << "\t" << prof.element_names[cc] << "\t" << log_liks_WL[0][cc] <<"\t"<< log_liks_WL[2][cc] <<"\t"<< log_liks_WL[1][cc] <<"\t";
            out_lik<<log_liks_WL[2][cc]-log_liks_WL[0][cc]<<"\t"<<log_liks_WL[2][cc]-log_liks_WL[1][cc]<<endl;
            //out_lik <<log_liks_Z[0][cc] << "\t" <<log_liks_Z[2][cc]<<"\t" <<log_liks_Z[1][cc]<<"\t";
            //out_lik<<log_mle[0][cc]<<"\t"<<log_mle[2][cc]<<"\t"<<log_mle[1][cc]<<"\t"<<log_mle[2][cc]-log_mle[0][cc]<<"\t"<<log_mle[2][cc]-log_mle[1][cc];
            //out_lik << endl;
        }

        out_lik.close();

    ofstream out_z;
    for(int r =0;r<3;r++)
    {
      if(r == 2)
      {
          outpath_elem = output_path+"_M" +to_string(1) + "_elem_Z.txt";
      }else if(r == 1)
      {
          outpath_elem = output_path+"_M" +to_string(2) + "_elem_Z.txt";
      }else{
          outpath_elem = output_path+"_M" +to_string(0) + "_elem_Z.txt";
      }

            out_z.open(outpath_elem.c_str());
            out_z<<"No.";
                for(int s =0 ;s<N;s++){  // header: species name
                    out_z<< "\t" << nodes_names[s];
                }
            out_z << "\tgenetree" <<endl;

            for(vector<int>::iterator it = ids.begin(); it !=ids.end(); it++)
            {
                int c = *it;
                out_z<<c;
                for(int s=0; s<N;s++)
                    out_z<<"\t" << Max_Z[r][c][s];
                out_z << "\t" << genetrees[r][c];
                out_z <<endl;
            }
        out_z.close();
    }

    ofstream out_pi;
    for(int r=0; r<3;r++){
        if(r==0){
            outpath_elem=output_path+"_M"+to_string(0)+"_Beta_Post_pi_mode.txt";
        }else if(r==2){
            outpath_elem=output_path+"_M"+to_string(1)+"_Beta_Post_pi_mode.txt";
        }else{
            outpath_elem=output_path+"_M"+to_string(2)+"_Beta_Post_pi_mode.txt";
        }
        out_pi.open(outpath_elem.c_str());

        for(vector<int>:: iterator it = ids.begin(); it !=ids.end(); it++)
        {
            int c=*it;
            out_pi << c;
            for(int b=0; b<4; b++) {//4 or num_base
                out_pi<<"\t"<<cur_pi[r][c][b];
            }
            out_pi <<endl;
        }
        out_pi.close();
    }

}

void BPP::Output_init0(PhyloProf & prof, ofstream& out_lik, vector<int> & ids){

    //for(int cc=0; cc<C;cc++)
    for(vector<int>::iterator it = ids.begin(); it !=ids.end(); it++)
    {
        int cc = *it;
        out_lik <<cc << "\t" << prof.element_names[cc] << "\t"  <<log_liks_sgl[cc]<< "\t"<<log_liks_Z[1][cc];
        out_lik << endl;
    }
}

/*** output simulated sequence ***/
void BPP::Output_simu(PhyloProf & prof, string outpath, int c){
    ofstream output;
    string outpath1 = outpath + ".fasta";
    string outpath2 = outpath + ".bed";
    string outpath3 = outpath +"_Z.txt";
    string outpath4 = outpath +"_pi.txt";
    output.open(outpath1.c_str());
    for(int s = 0; s< S; s++)
    {
        output << ">" << prof.species_names[s] << endl;
        output << prof.X[s].substr(0, element_start[c] + element_size[c])<< endl; //strutils::ToUpperCase(
    }
    output.close();

    output.open(outpath2.c_str());
    for(int i = 0; i < c; i++)
    {
        output << i << "\t" << element_start[i] << "\t" << element_start[i] + element_size[i]<< "\t";
        //Han*: add in output for pi
        output << i << "\t" << 1 << "\t" << cur_crate[i] << "\t" << cur_nrate[i] << "\t" << genetrees[0][i] << endl;
    }
    output.close();

    //Han*: output for Z
    output.open(outpath3.c_str());
    for(int s=0; s<N; s++){
        output<<"\t"<<nodes_names[s];
    }
    output<<endl;
    for(int s=0; s<N; s++){
        output<<"\t"<<cur_Z[0][0][s];
    }
    output<<endl;
    output.close();

    //Han*: output pi
    output.open(outpath4.c_str());
    for(int i=0; i<c; i++){
        output<<i<<"\t"<<cur_pi[0][i][0]<<endl; //only need to output pi_A (double-stranded)
    }
    output.close();
}

    void BPP::getTreeString(int rootN, std::stringstream & buffer)
    {
        if (children[rootN][0] == -1)
        {
            buffer << species_names[rootN] << ":"<< distances[rootN];
        }
        else
        {
            buffer << "(";
            for(int i =0;i <2; i++)
            {
                int child = children[rootN][i];

                getTreeString(child, buffer);
                if(i==0) buffer << ",";
            }

            if(parent[rootN] < N)
            {
                buffer << "):" << distances[rootN];
            }else{
                buffer << ");" ;
            }
        }
    }

max_stars_repo_name: gwct/PhyloAcc

max_issues_repo_name: gwct/PhyloAcc

max_forks_repo_name: gwct/PhyloAcc


text:
#include "platform/i_platform.h"
#include "network/server_system.h"
#include <boost/timer.hpp>
#include <portable_iarchive.hpp>
#include "my_name_message.h"
#include "client_system.h"
#include "engine/frame_counter_system.h"
#include "core/program_state.h"
#include "engine/connection_event.h"
#include "platform/settings.h"
namespace network {

ServerSystem::ServerSystem()
    : mAddress()
    , mServer( NULL )
    , mClientId( 0 )
    , mMessageHolder( MessageHolder::Get() )
    , mSentMessagesSize( 0 )
    , mRunning( false )
    , mThreaded( false )
{
    mOnPhaseChanged = EventServer<PhaseChangedEvent>::Get().Subscribe( boost::bind( &ServerSystem::OnPhaseChanged, this, _1 ) );
}

namespace {
class Timer_t
{
    boost::timer mMeasurer;
    double mPrevMeasurement;
public:
    void Log( std::string const& Str = std::string() )
    {
        double Now = mMeasurer.elapsed();
        L2( "Timer - %s: %f %f\n", Str.c_str(), Now, Now - mPrevMeasurement );
        mPrevMeasurement = Now;
    }
    Timer_t(): mMeasurer(), mPrevMeasurement( mMeasurer.elapsed() )
    {
        Log( "timer init" );
    }
} PerfTimer;

}

void ServerSystem::Init()
{
    if ( enet_initialize () != 0 )
    {
        L1 ( "An error occurred while initializing ENet.\n" );
    }
    atexit ( enet_deinitialize );
    mOnFrameCounterEvent = EventServer<engine::FrameCounterEvent>::Get().Subscribe( boost::bind( &ServerSystem::OnFrameCounterEvent, this, _1 ) );
    mOnClientIdChanged = EventServer<ClientIdChangedEvent>::Get().Subscribe( boost::bind( &ServerSystem::OnClientIdChanged, this, _1 ) );

    /* Bind the server to the default localhost.     */
    /* A specific host address can be specified by   */
    /* enet_address_set_host (& address, "x.x.x.x"); */
    mAddress.host = ENET_HOST_ANY;
    /* Bind the server to port 1234. */
    mAddress.port = 1234;
    mServer = enet_host_create ( & mAddress /* the address to bind the server host to */,
                                 32      /* allow up to 32 clients and/or outgoing connections */,
                                 2      /* allow up to 2 channels to be used, 0 and 1 */,
                                 0      /* assume any amount of incoming bandwidth */,
                                 0      /* assume any amount of outgoing bandwidth */ );
    if ( mServer == NULL )
    {
        L1 ( "An error occurred while trying to create an ENet server host.\n" );
    }
    mRunning = true;
    mThreaded = Settings::Get().GetBool( "network.threaded", true );
    if (mThreaded)
    {
        mThread = std::thread( boost::bind( &ServerSystem::UpdateThread, this ) );
    }
}

void ServerSystem::Update( double DeltaTime )
{
    PerfTimer.Log( "server update started" );

    if (mThreaded)
    {
        std::lock_guard<std::mutex> lck( mMessageHolder.GetOutgoingMessages().GetMutex() );
        mMessageHolder.GetOutgoingMessages().Publish();
        mMessageHolder.GetOutgoingMessages().GetCV().notify_all();
    }
    else
    {
        ReceiveMessages();
        mMessageHolder.GetOutgoingMessages().Publish();
        SendMessages();
    }

    PerfTimer.Log( "server update ended" );

}

void ServerSystem::Receive( ENetEvent& event )
{
    //     L1 ("A packet of length %u containing %s was received from %s on channel %u.\n",
    //         event.packet -> dataLength,
    //         event.packet -> data,
    //         event.peer -> data,
    //         event.channelID);
    std::istringstream iss( std::string( ( char* )( event.packet->data ), event.packet->dataLength ) );
    eos::portable_iarchive ia( iss );

    MessageList::Messages_t messages;
    ia >> messages;
    SetSenderId( messages, event );
    mMessageHolder.GetIncomingMessages().TransferFrom( messages );

    /* Clean up the packet now that we're done using it. */
    enet_packet_destroy ( event.packet );
}

void ServerSystem::SetSenderId( MessageList::Messages_t& messages, ENetEvent& event )
{
    const int senderId = *(static_cast<int*>(event.peer->data));
    for (auto& message : messages)
    {
        message.mSenderId = senderId;
    }
}

void ServerSystem::ClientConnect( ENetEvent& event )
{
//     L1 ( "A new client connected from %x:%u.\n",
//          event.peer -> address.host,
//          event.peer -> address.port );
    /* Store any relevant client information here. */
    std::lock_guard<std::mutex> lck( mClientsMutex );
    int32_t clientId = mClientId++;
    event.peer -> data = static_cast<void*>( new int32_t( clientId ) );
    mClients[clientId] = event.peer;
}

void ServerSystem::OnFrameCounterEvent( engine::FrameCounterEvent const& Evt )
{
    L1( "sent messages size (approx): %f\n", mSentMessagesSize / Evt.mDiff );
    mSentMessagesSize = 0;
}

void ServerSystem::ClientDisconnect( ENetEvent& event )
{
    std::lock_guard<std::mutex> lck( mClientsMutex );
    int32_t clientId = *static_cast<int32_t*>( event.peer -> data );
    Opt<core::ClientData> clientData( core::ProgramState::Get().FindClientDataByClientId( clientId ) );
//     L1 ( "client disconnected: %x:%u. client id: %d, name: %s\n",
//          event.peer -> address.host,
//          event.peer -> address.port,
//          clientId,
//          clientData.IsValid() ? clientData->mClientName.c_str() : "_no_name_" );
    /* Reset the peer's client information. */
    delete static_cast<int32_t*>( event.peer->data );
    event.peer -> data = NULL;
    if ( clientData.IsValid() )
    {
        // could be invalid if client tried to connect too early, and the system had it as connected
        clientData->mConnected = false;
    }
    mClients.erase( clientId );
    EventServer<engine::ConnectionEvent>::Get().SendEvent( engine::ConnectionEvent( clientId, engine::ConnectionEvent::Disconnected ) );
}

void ServerSystem::OnClientIdChanged( ClientIdChangedEvent const& Evt )
{
    std::lock_guard<std::mutex> lck( mClientsMutex );
    auto currPeer = mClients.find( Evt.mCurrClientId );
    if ( currPeer == mClients.end() )
    {
        // client connect should happen before client id change
        BOOST_ASSERT( currPeer != mClients.end() );
        return;
    }
    // client should be removed at this time (clientDisconnet should happen before client can reconnect)
    BOOST_ASSERT( mClients.find( Evt.mNewClientId ) == mClients.end() );
    delete static_cast<int32_t*>( currPeer->second->data );
    currPeer->second -> data = static_cast<void*>( new int32_t( Evt.mNewClientId ) );
    mClients[Evt.mNewClientId] = currPeer->second;
    mClients.erase( Evt.mCurrClientId );
}

void ServerSystem::UpdateThread()
{
    while (mRunning)
    {
        ReceiveMessages();
        SendMessages();
    }
}

void ServerSystem::SendMessages()
{
    MessageList::Messages_t messages;
    TransferOutgoingMessagesTo( messages );
    if (!messages.empty())
    {
        std::ostringstream oss;
        eos::portable_oarchive oa( oss );
        oa & messages;
        std::string astr( oss.str() );
        // L1("server sends - %s:\n",astr.c_str());
        ENetPacket* packet = enet_packet_create( astr.c_str(),
            astr.size(),
            ENET_PACKET_FLAG_RELIABLE );

        enet_host_broadcast( mServer, 0, packet );
        enet_host_flush( mServer );
    }
}

void ServerSystem::ReceiveMessages()
{
    ENetEvent event;
    while (enet_host_service( mServer, &event, 0 ) > 0)
    {
        switch (event.type)
        {
        case ENET_EVENT_TYPE_CONNECT:
            ClientConnect( event );
            break;
        case ENET_EVENT_TYPE_RECEIVE:
            Receive( event );
            break;

        case ENET_EVENT_TYPE_DISCONNECT:
            ClientDisconnect( event );
            break;
        }
    }
    PublishIncomingMessages();
}

void ServerSystem::TransferOutgoingMessagesTo( MessageList::Messages_t& messages )
{
    if (mThreaded)
    {
        static const int32_t mWaitMillisecs = Settings::Get().GetInt( "network.wait_millisec", 10 );
        std::unique_lock<std::mutex> ulck( mMessageHolder.GetOutgoingMessages().GetMutex() );
        if (!mMessageHolder.GetOutgoingMessages().HasPublishedMessages())
        {
            mMessageHolder.GetOutgoingMessages().GetCV().wait_for( ulck, std::chrono::milliseconds( mWaitMillisecs ) );
        }
        mMessageHolder.GetOutgoingMessages().TransferPublishedMessagesTo( messages );
    }
    else
    {
        mMessageHolder.GetOutgoingMessages().TransferPublishedMessagesTo( messages );
    }
}

void ServerSystem::PublishIncomingMessages()
{
    if (mThreaded)
    {
        std::lock_guard<std::mutex> lck( mMessageHolder.GetIncomingMessages().GetMutex() );
        mMessageHolder.GetIncomingMessages().Publish();
    }
    else
    {
        mMessageHolder.GetIncomingMessages().Publish();
    }
}

void ServerSystem::OnPhaseChanged( PhaseChangedEvent const& Evt )
{
    if (mThreaded && Evt.CurrentPhase == ProgramPhase::CloseSignal)
    {
        mRunning = false;
        mThread.join();
    }
}

} // namespace engine


text:
#include "drake/math/barycentric.h"

#include <algorithm>
#include <memory>
#include <set>
#include <utility>
#include <vector>

#include <Eigen/Dense>

#include "drake/common/drake_assert.h"

namespace drake {
namespace math {

template <typename T>
BarycentricMesh<T>::BarycentricMesh(MeshGrid input_grid)
    : input_grid_(std::move(input_grid)),
      stride_(input_grid_.size()),
      num_interpolants_{1} {
  DRAKE_DEMAND(input_grid_.size() > 0);
  for (int i = 0; i < get_input_size(); i++) {
    // Must define at least one mesh point per dimension.
    DRAKE_DEMAND(!input_grid_[i].empty());

    // Gain one interpolant for every non-singleton dimension.
    if (input_grid_[i].size() > 1) num_interpolants_++;

    stride_[i] = (i == 0) ? 1 : input_grid_[i - 1].size() * stride_[i - 1];
  }
}

template <typename T>
void BarycentricMesh<T>::get_mesh_point(int index,
                                        EigenPtr<Eigen::VectorXd> point) const {
  DRAKE_DEMAND(index >= 0);
  DRAKE_DEMAND(point != nullptr);
  point->resize(get_input_size());
  // Iterate through the input dimensions, assigning the value and reducing
  // the index to be relevant only to the remaining dimensions.
  for (int i = 0; i < get_input_size(); i++) {
    const auto& coords = input_grid_[i];
    const int dim_index = index % coords.size();
    (*point)[i] = *(std::next(input_grid_[i].begin(), dim_index));
    index /= coords.size();  // intentionally truncate to int.
  }
  DRAKE_DEMAND(index == 0);  // otherwise the index was out of range.
}

template <typename T>
VectorX<T> BarycentricMesh<T>::get_mesh_point(int index) const {
  VectorX<T> point(get_input_size());
  get_mesh_point(index, &point);
  return point;
}

template <typename T>
MatrixX<T> BarycentricMesh<T>::get_all_mesh_points() const {
  const int M = get_input_size();
  const int N = get_num_mesh_points();
  VectorX<T> point(M);
  MatrixX<T> points(M, N);
  for (int i = 0; i < N; i++) {
    get_mesh_point(i, &point);
    points.col(i) = point;
  }
  return points;
}

template <typename T>
void BarycentricMesh<T>::EvalBarycentricWeights(
    const Eigen::Ref<const VectorX<T>>& input,
    EigenPtr<Eigen::VectorXi> mesh_indices,
    EigenPtr<VectorX<T>> weights) const {
  DRAKE_DEMAND(input.size() == static_cast<int>(input_grid_.size()));
  DRAKE_DEMAND(mesh_indices != nullptr && weights != nullptr);

  // std::pair of fractional position [0,1] and dimension index (position first,
  // so that std::pair's default operator< works for us).
  // There is one relative position for every non-singleton input dimension.  In
  // the case of triangular meshes, there is one interpolant for every
  // non-singular dimension + one additional, so num_interpolants-1 is the size
  // we need.
  std::vector<std::pair<T, int>> relative_position(num_interpolants_ - 1);
  // Bounding box on the input grid containing the sample input.
  std::vector<bool> has_volume(get_input_size());

  int current_index = 0;

  // Loop through input dimensions and compute the relative positions and
  // indices.  Set current_index to the "top right" corner index.
  int count = 0;
  for (int i = 0; i < get_input_size(); i++) {
    const auto& coords = input_grid_[i];

    // Skip over singleton dimensions.
    if (coords.size() == 1) continue;

    // Tag the positions with the dimension index.
    relative_position[count].second = i;

    // Find the right side of the bounding box.
    // Recall that lower_bound returns the first grid element that is NOT less
    // than the sample.
    auto right_iter = coords.lower_bound(input[i]);
    int right_index = 0;

    if (right_iter == coords.end()) {
      // ... then input is off the right end of the grid;
      // move it to the right boundary.
      has_volume[i] = false;
      right_index = coords.size() - 1;
      relative_position[count].first = T(1.);
    } else if (right_iter == coords.begin()) {
      // ... then input is at the first element or left of it;
      // move it to the left boundary.
      has_volume[i] = false;
      right_index = 0;
      relative_position[count].first = T(1.);
    } else {
      // ... then input is inside the grid.
      has_volume[i] = true;
      right_index = std::distance(coords.begin(), right_iter);
      const T& right_value = *(right_iter);
      const T& left_value = *(std::prev(right_iter));
      relative_position[count].first =
          (input[i] - left_value) / (right_value - left_value);
    }

    current_index += stride_[i] * right_index;
    count++;
  }
  DRAKE_ASSERT(count == (num_interpolants_ - 1));

  // Sort the dimensions by their relative position.  We identify which triangle
  // of the mesh we are in by moving along the faces in order of their relative
  // position.
  std::sort(relative_position.begin(), relative_position.end());

  mesh_indices->resize(num_interpolants_);
  weights->resize(num_interpolants_);
  (*mesh_indices)[0] = current_index;
  (*weights)[0] = relative_position[0].first;

  for (int i = 1; i < num_interpolants_; i++) {
    int dim = relative_position[i - 1].second;
    if (has_volume[dim]) {
      current_index -= stride_[dim];
    }
    (*mesh_indices)[i] = current_index;
    if (i == (num_interpolants_ - 1)) {
      (*weights)[i] = 1.0 - relative_position[i - 1].first;
    } else {
      (*weights)[i] =
          relative_position[i].first - relative_position[i - 1].first;
    }
  }
}

template <typename T>
void BarycentricMesh<T>::Eval(const Eigen::Ref<const MatrixX<T>>& mesh_values,
                              const Eigen::Ref<const VectorX<T>>& input,
                              EigenPtr<VectorX<T>> output) const {
  EvalWithMixedScalars<T>(mesh_values, input, output);
}

template <typename T>
VectorX<T> BarycentricMesh<T>::Eval(
    const Eigen::Ref<const MatrixX<T>>& mesh_values,
    const Eigen::Ref<const VectorX<T>>& input) const {
  return EvalWithMixedScalars<T>(mesh_values, input);
}

template <typename T>
MatrixX<T> BarycentricMesh<T>::MeshValuesFrom(
    const std::function<VectorX<T>(const Eigen::Ref<const VectorX<T>>&)>&
        vector_func) const {
  VectorX<T> sample(get_input_size());
  const int N = get_num_mesh_points();

  // Call it once to determine the size of the output and initialize memory.
  get_mesh_point(0, &sample);
  VectorX<T> value = vector_func(sample);
  MatrixX<T> mesh_values(value.rows(), N);
  mesh_values.col(0) = value;

  // Now loop through all of the other points.
  for (int i = 1; i < N; i++) {
    get_mesh_point(i, &sample);
    mesh_values.col(i) = vector_func(sample);
  }

  return mesh_values;
}

}  // namespace math
}  // namespace drake

template class ::drake::math::BarycentricMesh<double>;

ext: cc


text:
/*
 *  Copyright 2011-2014 Maxim Milakov
 *
 *  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 "training_stat.h"

#include <boost/format.hpp>

namespace nnforge
{
	training_stat::training_stat()
	{
	}

	std::ostream& operator<< (std::ostream& out, const training_stat& val)
	{
		out << "Avg Abs weight updates";

		for(unsigned int layer_id = 0; layer_id < val.absolute_updates.size(); ++layer_id)
		{
			if (!val.absolute_updates[layer_id].empty())
			{
				out << " #" << layer_id << " (" << (boost::format("%|1$.5e|") % val.absolute_updates[layer_id][0]);
				for(int i = 1; i < val.absolute_updates[layer_id].size(); ++i)
					out << (boost::format(", %|1$.5e|") % val.absolute_updates[layer_id][i]);
				out << ")";
			}
		}

		return out;
	}
}

max_stars_repo_name: anshumang/nnForgeINST

max_issues_repo_name: yanshanjing/nnForge

max_forks_repo_name: yanshanjing/nnForge


text:
// Copyright 2015, 2017 Peter Dimov.
//
// 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 <boost/mp11/utility.hpp>
#include <boost/mp11/detail/config.hpp>
#include <boost/core/lightweight_test_trait.hpp>
#include <type_traits>

using boost::mp11::mp_invoke;

template<class...> struct X {};

template<template<class...> class F, class... T> using Y = X<F<T>...>;

template<class Q, class... T> using Z = X<mp_invoke<Q, T>...>;

template<class T, class U> struct P {};

template<class T, class U> using first = T;

int main()
{
    using boost::mp11::mp_identity_t;
    using boost::mp11::mp_quote;

    {
        using Q = mp_quote<mp_identity_t>;

        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_invoke<Q, void>, void>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_invoke<Q, int[]>, int[]>));
    }

    {
        using Q = mp_quote<mp_identity_t>;

#if !BOOST_MP11_WORKAROUND( BOOST_MP11_MSVC, <= 1800 )
        using R1 = Y<Q::fn, void, char, int>;
        BOOST_TEST_TRAIT_TRUE((std::is_same<R1, X<void, char, int>>));
#endif

#if !BOOST_MP11_WORKAROUND( BOOST_MP11_MSVC, < 1920 && BOOST_MP11_MSVC >= 1900 )
        using R2 = Z<Q, void, char, int>;
        BOOST_TEST_TRAIT_TRUE((std::is_same<R2, X<void, char, int>>));
#endif
    }

    {
        using Q = mp_quote<P>;

        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_invoke<Q, void, void>, P<void, void>>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_invoke<Q, char[], int[]>, P<char[], int[]>>));
    }

    {
        using Q = mp_quote<first>;

        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_invoke<Q, void, int>, void>));
        BOOST_TEST_TRAIT_TRUE((std::is_same<mp_invoke<Q, char[], int[]>, char[]>));
    }

    return boost::report_errors();
}

max_stars_repo_name: alexhenrie/poedit

max_issues_repo_name: alexhenrie/poedit

max_forks_repo_name: alexhenrie/poedit


text:
//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// Copyright (C) 2014 Vicente J. Botet Escriba
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// <boost/thread/future.hpp>

// future<tuple<>> when_all();

#include <boost/config.hpp>

#if ! defined  BOOST_NO_CXX11_DECLTYPE
#define BOOST_RESULT_OF_USE_DECLTYPE
#endif

#define BOOST_THREAD_VERSION 4

#include <boost/thread/future.hpp>
#include <boost/detail/lightweight_test.hpp>

int main()
{
#if defined BOOST_THREAD_PROVIDES_FUTURE_WHEN_ALL_WHEN_ANY

  {
    boost::future<boost::csbl::tuple<> > all = boost::when_all();
    BOOST_TEST(all.valid());
    BOOST_TEST(all.is_ready());
  }
#endif

  return boost::report_errors();
}


text:
#include <cstdlib>
#include <iostream>
#include <complex>
#include <type_traits>
#include <algorithm>
#define BOOST_UBLAS_NO_ELEMENT_PROXIES
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/banded.hpp>
#include <boost/numeric/ublas/hermitian.hpp>
#include <boost/numeric/bindings/ublas/vector.hpp>
#include <boost/numeric/bindings/ublas/banded.hpp>
#include <boost/numeric/bindings/ublas/hermitian.hpp>
#include <boost/numeric/bindings/blas/level2.hpp>
#include "print.hpp"
#include "random.hpp"

namespace ublas=boost::numeric::ublas;
namespace blas=boost::numeric::bindings::blas;

int main(int argc, char *argv[]) {
  {
    typedef std::complex<double> complex;
    typedef ublas::vector<complex> vector;
    typedef ublas::banded_matrix<complex, ublas::column_major> matrix;
    typedef typename std::make_signed<vector::size_type>::type size_type;
    rand_normal<complex>::reset();
    size_type n=8;
    matrix A(n, n, 2, 2);
    matrix A_u(n, n, 0, 2), A_l(n, n, 2, 0);
    for (size_type j=0; j<n; ++j) {
      A(j, j)=rand_normal<complex>::get().real();
      A_u(j, j)=A(j, j);
      A_l(j, j)=A(j, j);
      for (size_type i=std::max(size_type(0), j-2); i<j; ++i) {
	A(i, j)=rand_normal<complex>::get();
	A(j, i)=std::conj(A(i, j));
	A_u(i, j)=A(i, j);
	A_l(j, i)=A(j, i);
      }
    }
    ublas::hermitian_adaptor<matrix, ublas::upper> B_u(A_u);
    ublas::hermitian_adaptor<matrix, ublas::lower> B_l(A_l);
    vector x(n);
    for (size_type i=0; i<n; ++i)
      x(i)=rand_normal<complex>::get();
    vector y(n);
    for (size_type i=0; i<n; ++i)
      y(i)=rand_normal<complex>::get();
    complex alpha(rand_normal<complex>::get());
    complex beta(rand_normal<complex>::get());
    vector y1(alpha*ublas::prod(A, x)+beta*y);
    vector y2(y);
    blas::hbmv(alpha, B_l, x, beta, y2);
    vector y3(y);
    blas::hbmv(alpha, B_u, x, beta, y3);
    std::cout << "testing boost::ublas containers\n"
    	      << "using ublas       : " << print_vec(y1) << '\n'
	      << "using blas (lower): " << print_vec(y2) << '\n'
	      << "using blas (upper): " << print_vec(y3) << '\n'
    	      << '\n';
  }
  return EXIT_SUCCESS;
}


text:
//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//  Adaptation to Boost of the libcxx
//  Copyright 2010 Vicente J. Botet Escriba
//  Distributed under the Boost Software License, Version 1.0.
//  See http://www.boost.org/LICENSE_1_0.txt

#include <boost/chrono/duration.hpp>
#include <boost/detail/lightweight_test.hpp>

#include <libs/chrono/test/rep.h>

template <class D>
void check_max()
{
    typedef typename D::rep Rep;
    Rep max_rep = (boost::chrono::duration_values<Rep>::max)();
    BOOST_TEST((D::max)().count() == max_rep);
}

template <class D>
void check_min()
{
    typedef typename D::rep Rep;
    Rep min_rep = (boost::chrono::duration_values<Rep>::min)();
    BOOST_TEST((D::min)().count() == min_rep);
}

template <class D>
void check_zero()
{
    typedef typename D::rep Rep;
    Rep zero_rep = boost::chrono::duration_values<Rep>::zero();
    BOOST_TEST(D::zero().count() == zero_rep);
}

int main()
{
    check_max<boost::chrono::duration<int> >();
    check_max<boost::chrono::duration<Rep> >();
    check_min<boost::chrono::duration<int> >();
    check_min<boost::chrono::duration<Rep> >();
    check_zero<boost::chrono::duration<int> >();
    check_zero<boost::chrono::duration<Rep> >();
    return boost::report_errors();
}


text:
// (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2004-2007 Jonathan Turkanis
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)

// See http://www.boost.org/libs/iostreams for documentation.

#include <algorithm> // equal.
#include <fstream>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/detail/adapter/direct_adapter.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
#include "detail/sequence.hpp"
#include "detail/temp_file.hpp"
#include "detail/verification.hpp"

using namespace std;
using namespace boost::iostreams;
using namespace boost::iostreams::test;
using boost::unit_test::test_suite;

void direct_adapter_test()
{

    typedef boost::iostreams::detail::direct_adapter<array_source>
            indirect_array_source;
    typedef boost::iostreams::detail::direct_adapter<array_sink>
            indirect_array_sink;
    typedef boost::iostreams::detail::direct_adapter<boost::iostreams::array>
            indirect_array;
    typedef stream<indirect_array_source>
            indirect_array_istream;
    typedef stream<indirect_array_sink>
            indirect_array_ostream;
    typedef stream<indirect_array>
            indirect_array_stream;

    test_file        test;
    test_sequence<>  seq;

    //--------------indirect_array_istream------------------------------------//

    {
        indirect_array_istream  first(&seq[0], &seq[0] + seq.size());
        ifstream                second(test.name().c_str());
        BOOST_CHECK_MESSAGE(
            compare_streams_in_chars(first, second),
            "failed reading from indirect_array_istream in chars"
        );
    }

    {
        indirect_array_istream  first(&seq[0], &seq[0] + seq.size());
        ifstream                second(test.name().c_str());
        BOOST_CHECK_MESSAGE(
            compare_streams_in_chunks(first, second),
            "failed reading from indirect_array_istream in chunks"
        );
    }

    //--------------indirect_array_ostream------------------------------------//

    {
        vector<char>            dest(data_reps * data_length(), '?');
        indirect_array_ostream  out(&dest[0], &dest[0] + dest.size());
        write_data_in_chars(out);
        BOOST_CHECK_MESSAGE(
            std::equal(seq.begin(), seq.end(), dest.begin()),
            "failed writing to indirect_array_ostream in chunks"
        );
    }

    {
        vector<char>            dest(data_reps * data_length(), '?');
        indirect_array_ostream  out(&dest[0], &dest[0] + dest.size());
        write_data_in_chunks(out);
        BOOST_CHECK_MESSAGE(
            std::equal(seq.begin(), seq.end(), dest.begin()),
            "failed writing to indirect_array_ostream in chunks"
        );
    }

    //--------------indirect_array_stream-------------------------------------//

    {
        vector<char> test(data_reps * data_length(), '?');
        indirect_array_stream io(&test[0], &test[0] + test.size());
        BOOST_CHECK_MESSAGE(
            test_seekable_in_chars(io),
            "failed seeking within indirect_array_stream, in chars"
        );
    }

    {
        vector<char> test(data_reps * data_length(), '?');
        indirect_array_stream io(&test[0], &test[0] + test.size());
        BOOST_CHECK_MESSAGE(
            test_seekable_in_chunks(io),
            "failed seeking within indirect_array_stream, in chunks"
        );
    }
}

test_suite* init_unit_test_suite(int, char* [])
{
    test_suite* test = BOOST_TEST_SUITE("direct_adapter test");
    test->add(BOOST_TEST_CASE(&direct_adapter_test));
    return test;
}


text:
#include <boost/mpl/apply.hpp>
#include <boost/mpl/assert.hpp>
#include <nt2/sdk/meta/factory_of.hpp>
#include <boost/type_traits/is_same.hpp>

using namespace boost;
using namespace boost::mpl;

int main()
{
  typedef nt2::meta::factory_of<float>::type                  factory_of_float;

  BOOST_MPL_ASSERT(( is_same<double, apply<factory_of_float,double>::type > ));
}


text:
/*
 * This file is part of the Sequoia MSO Solver.
 *
 * Copyright 2012 Alexander Langer, Theoretical Computer Science,
 *                                  RWTH Aachen University
 *
 * 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.
 */
/**
 * @author Alexander Langer
 */
#include "apply_join_assignments.h"
#include "apply_game_join.h"
#include "lightweight_apply.h"
#include "pair_iterator_stl.h"

#include <algorithm>
#include <boost/scoped_ptr.hpp>
#ifdef HAVE_TBB
#include <tbb/parallel_do.h>
#endif

namespace sequoia {

template <typename Solver>
void
ApplyJoinAssignment<Solver>::operator()(const SequoiaTable::const_iterator::value_type &entry) {
    const Assignment_f *alpha = entry.first;
    const GameVoidPtrMap *left_inmap = entry.second;

    SequoiaTable *right_table = _solver->table(_child_right);
    SequoiaTable::const_iterator ralpha_it = right_table->find(alpha);
    if (ralpha_it == right_table->end()) {
	// no compatible entries in the right table, no need to iterate.
	return;
    }
    assert(*alpha == *ralpha_it->first);
    const GameVoidPtrMap *right_inmap = ralpha_it->second;
    ApplyGameJoin<Solver> apply(_solver, _node, alpha);
    apply.init();

    /*
     * Now we iterate over all games in a Cartesian manner and for each
     * pair we join the two games with each other.
     */
    typedef PairIteratorStl<GameVoidPtrMap::const_iterator, GameVoidPtrMap::const_iterator> PairIt;
    PairIt pit(left_inmap->begin(), left_inmap->end(),
	       right_inmap->begin(), right_inmap->end());
    PairIt pitend(left_inmap->end(), right_inmap->end());
    DPRINTLN("Start iterating over sets");
#ifdef HAVE_TBB
    tbb::parallel_do(pit, pitend, lightweight_apply(&apply));
#else
    std::for_each(pit, pitend, lightweight_apply(&apply));
#endif
    _solver->log_games_completed(apply.count());
}

} // namespace

max_stars_repo_name: sequoia-mso/sequoia-core

max_issues_repo_name: sequoia-mso/sequoia-core

max_forks_repo_name: sequoia-mso/sequoia-core


text:
//==================================================================================================
/*!
  @file

    @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_ATAN2D_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_ATAN2D_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-trigonometric
    This function object returns the atan2d function : atan2 in degrees.

    @par Header <boost/simd/function/atan2d.hpp>

    @par Note

      For every parameters of same floating type
      `atan2d(y, x)` is similar  to: `indeg(atan2(y, x))`

    @see atan2,  atan2pi

    @par Example:

      @snippet atan2d.cpp atan2d

    @par Possible output:

      @snippet atan2d.txt atan2d

  **/
  IEEEValue atan2d(IEEEValue const& y, IEEEValue const& x );
} }
#endif

#include <boost/simd/function/scalar/atan2d.hpp>
#include <boost/simd/function/simd/atan2d.hpp>

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
// Copyright (c) 2018, ZIH,
// Technische Universitaet Dresden,
// Federal Republic of Germany
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
//       this list of conditions and the following disclaimer in the documentation
//       and/or other materials provided with the distribution.
//     * Neither the name of metricq nor the names of its contributors
//       may be used to endorse or promote products derived from this software
//       without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../storage/file/file.hpp"
#include "../storage/file/metric.hpp"

#include <hta/ostream.hpp>

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

#include <cassert>

namespace po = boost::program_options;

namespace hta::storage::file
{
template <class T>
void dump_summary(const std::filesystem::path& path)
{
    File<Metric::Header, T> file{ FileOpenTag::Read(), path };
    if (file.size() > 0)
    {
        std::cout << "first timestamp: " << file.read(0).time << "\n";
        std::cout << "last timestamp " << file.read(file.size() - 1).time << "\n";
    }
    std::cout << file.size() << " entries\n";
}

void dump_header(const std::filesystem::path& path)
{
    File<Metric::Header, TimePoint> file{ FileOpenTag::Read(), path };
    auto header = file.header();
    std::cout << "HTA header of " << path << "\n";
    std::cout << "version: " << header.version << "\n";
    std::cout << "interval: " << header.interval << "\n";
    std::cout << "duration_period: " << header.duration_period.num << " / "
              << header.duration_period.den << "\n";
    std::cout << "interval_min: " << header.interval_min << "\n";
    std::cout << "interval_max: " << header.interval_max << "\n";
    std::cout << "interval_factor: " << header.interval_factor << "\n";
    if (header.interval == 0)
    {
        std::cout << "File contains raw TimeValue\n";
        dump_summary<TimeValue>(path);
    }
    else
    {
        std::cout << "File contains TimeAggregate\n";
        dump_summary<TimeAggregate>(path);
    }
}
} // namespace hta::storage::file

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        return -1;
    }
    hta::storage::file::dump_header(argv[1]);
}

max_stars_repo_name: metricq/hta

max_issues_repo_name: metricq/hta

max_forks_repo_name: metricq/hta