text:
/*
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#ifndef WIN32
#include <grp.h>
#include <netdb.h>
#include <sys/socket.h>
#endif

#include <signal.h>

#if !defined(__FreeBSD__) && !defined(WIN32)
#include <sys/syscall.h>
#include <uuid/uuid.h>
#endif

#ifdef WIN32
#include <WinSock2.h>
#endif

#include <ctime>
#include <sstream>

#include <boost/algorithm/string/trim.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#include <osquery/core.h>
#include <osquery/database.h>
#include <osquery/filesystem.h>
#include <osquery/flags.h>
#include <osquery/logger.h>
#include <osquery/sql.h>
#include <osquery/system.h>

#ifdef WIN32
#include "osquery/core/windows/wmi.h"
#endif
#include "osquery/core/conversions.h"
#include "osquery/core/process.h"
#include "osquery/core/utils.h"

namespace fs = boost::filesystem;

namespace osquery {

DECLARE_uint64(alarm_timeout);

/// The path to the pidfile for osqueryd
CLI_FLAG(string,
         pidfile,
         OSQUERY_PIDFILE "osqueryd.pidfile",
         "Path to the daemon pidfile mutex");

/// Should the daemon force unload previously-running osqueryd daemons.
CLI_FLAG(bool,
         force,
         false,
         "Force osqueryd to kill previously-running daemons");

FLAG(string,
     host_identifier,
     "hostname",
     "Field used to identify the host running osquery (hostname, uuid, "
     "instance, ephemeral, specified)");

// Only used when host_identifier=specified
FLAG(string,
     specified_identifier,
     "",
     "Field used to specify the host_identifier when set to \"specified\"");

FLAG(bool, utc, true, "Convert all UNIX times to UTC");

#ifdef WIN32
struct tm* gmtime_r(time_t* t, struct tm* result) {
  _gmtime64_s(result, t);
  return result;
}

struct tm* localtime_r(time_t* t, struct tm* result) {
  _localtime64_s(result, t);
  return result;
}
#endif

std::string getHostname() {
  long max_path = 256;
  long size = 0;
#ifndef WIN32
  static long max_hostname = sysconf(_SC_HOST_NAME_MAX);
  size = (max_hostname > max_path - 1) ? max_hostname + 1 : max_path;
#endif
  if (isPlatform(PlatformType::TYPE_WINDOWS)) {
    size = max_path;
  }

  std::vector<char> hostname(size, 0x0);
  std::string hostname_string;
  if (hostname.data() != nullptr) {
    gethostname(hostname.data(), size - 1);
    hostname_string = std::string(hostname.data());
  }
  boost::algorithm::trim(hostname_string);
  return hostname_string;
}

std::string getFqdn() {
  if (!isPlatform(PlatformType::TYPE_WINDOWS)) {
    std::string fqdn_string = getHostname();

#ifndef WIN32
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_flags = AI_CANONNAME;

    struct addrinfo* res = nullptr;
    if (getaddrinfo(fqdn_string.c_str(), nullptr, &hints, &res) == 0) {
      if (res->ai_canonname != nullptr) {
        fqdn_string = res->ai_canonname;
      }
    }
    if (res != nullptr) {
      freeaddrinfo(res);
    }
#endif
    return fqdn_string;
  } else {
    unsigned long size = 256;
    std::vector<char> fqdn(size, 0x0);
#ifdef WIN32
    GetComputerNameEx(ComputerNameDnsFullyQualified, fqdn.data(), &size);
#endif
    return fqdn.data();
  }
}

std::string generateNewUUID() {
  boost::uuids::uuid uuid = boost::uuids::random_generator()();
  return boost::uuids::to_string(uuid);
}

std::string generateHostUUID() {
  std::string hardware_uuid;
#ifdef __APPLE__
  // Use the hardware UUID available on OSX to identify this machine
  uuid_t id;
  // wait at most 5 seconds for gethostuuid to return
  const timespec wait = {5, 0};
  if (gethostuuid(id, &wait) == 0) {
    char out[128] = {0};
    uuid_unparse(id, out);
    hardware_uuid = std::string(out);
  }
#elif WIN32
  WmiRequest wmiUUIDReq("Select UUID from Win32_ComputerSystemProduct");
  std::vector<WmiResultItem>& wmiUUIDResults = wmiUUIDReq.results();
  if (wmiUUIDResults.size() != 0) {
    wmiUUIDResults[0].GetString("UUID", hardware_uuid);
  }
#else
  readFile("/sys/class/dmi/id/product_uuid", hardware_uuid);
#endif

  // We know at least Linux will append a newline.
  hardware_uuid.erase(
      std::remove(hardware_uuid.begin(), hardware_uuid.end(), '\n'),
      hardware_uuid.end());
  boost::algorithm::trim(hardware_uuid);
  if (!hardware_uuid.empty()) {
    // Construct a new string to remove trailing nulls.
    return std::string(hardware_uuid.c_str());
  }

  // Unable to get the hardware UUID, just return a new UUID
  return generateNewUUID();
}

Status getInstanceUUID(std::string& ident) {
  // Lookup the instance identifier (UUID) previously generated and stored.
  auto status =
      getDatabaseValue(kPersistentSettings, "instance_uuid_v1", ident);
  if (ident.size() == 0) {
    // There was no UUID stored in the database, generate one and store it.
    ident = osquery::generateNewUUID();
    return setDatabaseValue(kPersistentSettings, "instance_uuid_v1", ident);
  }

  return status;
}

Status getEphemeralUUID(std::string& ident) {
  if (ident.size() == 0) {
    ident = osquery::generateNewUUID();
  }
  return Status(0, "OK");
}

Status getHostUUID(std::string& ident) {
  // Lookup the host identifier (UUID) previously generated and stored.
  auto status = getDatabaseValue(kPersistentSettings, "host_uuid_v3", ident);
  if (ident.size() == 0) {
    // There was no UUID stored in the database, generate one and store it.
    ident = osquery::generateHostUUID();
    return setDatabaseValue(kPersistentSettings, "host_uuid_v3", ident);
  }
  return status;
}

Status getSpecifiedUUID(std::string& ident) {
  if (FLAGS_specified_identifier.empty()) {
    return Status(1, "No specified identifier for host");
  }
  ident = FLAGS_specified_identifier;
  return Status(0, "OK");
}

std::string getHostIdentifier() {
  static std::string ident;

  Status result(2);
  if (ident.size() == 0) {
    // The identifier has not been set yet.
    if (FLAGS_host_identifier == "uuid") {
      result = getHostUUID(ident);
    } else if (FLAGS_host_identifier == "instance") {
      result = getInstanceUUID(ident);
    } else if (FLAGS_host_identifier == "ephemeral") {
      result = getEphemeralUUID(ident);
    } else if (FLAGS_host_identifier == "specified") {
      result = getSpecifiedUUID(ident);
    }

    if (!result.ok()) {
      // assuming the default of "hostname" as the machine identifier
      // intentionally not set to `ident` because the hostname may change
      // throughout the life of the process and we always want to be using the
      // most current hostname
      return osquery::getHostname();
    } else {
      VLOG(1) << "Using host identifier: " << ident;
    }
  }
  return ident;
}

std::string toAsciiTime(const struct tm* tm_time) {
  if (tm_time == nullptr) {
    return "";
  }

  auto time_str = platformAsctime(tm_time);
  boost::algorithm::trim(time_str);
  return time_str + " UTC";
}

std::string toAsciiTimeUTC(const struct tm* tm_time) {
  size_t epoch = toUnixTime(tm_time);
  struct tm tptr;

  memset(&tptr, 0, sizeof(tptr));

  if (epoch == (size_t)-1) {
    return "";
  }

  gmtime_r((time_t*)&epoch, &tptr);
  return toAsciiTime(&tptr);
}

std::string getAsciiTime() {
  auto result = std::time(nullptr);

  struct tm now;
  gmtime_r(&result, &now);

  return toAsciiTime(&now);
}

size_t toUnixTime(const struct tm* tm_time) {
  struct tm result;
  memset(&result, 0, sizeof(result));

  memcpy(&result, tm_time, sizeof(result));
  return mktime(&result);
}

size_t getUnixTime() {
  std::time_t ut = std::time(nullptr);
  return ut < 0 ? 0 : ut;
}

Status checkStalePid(const std::string& content) {
  int pid;
  try {
    pid = boost::lexical_cast<int>(content);
  } catch (const boost::bad_lexical_cast& /* e */) {
    return Status(0, "Could not parse pid from existing pidfile");
  }

  PlatformProcess target(pid);
  int status = 0;

  // The pid is running, check if it is an osqueryd process by name.
  std::stringstream query_text;

  query_text << "SELECT name FROM processes WHERE pid = " << pid
             << " AND name LIKE 'osqueryd%';";

  SQL q(query_text.str());
  if (!q.ok()) {
    return Status(1, "Error querying processes: " + q.getMessageString());
  }

  if (q.rows().size() > 0) {
    // If the process really is osqueryd, return an "error" status.
    if (FLAGS_force) {
      // The caller may choose to abort the existing daemon with --force.
      // Do not use SIGQUIT as it will cause a crash on OS X.
      status = target.kill() ? 0 : -1;
      sleepFor(1000);

      return Status(status, "Tried to force remove the existing osqueryd");
    }

    return Status(1, "osqueryd (" + content + ") is already running");
  } else {
    VLOG(1) << "Found stale process for osqueryd (" << content << ")";
  }

  return Status(0, "OK");
}

Status createPidFile() {
  // check if pidfile exists
  auto pidfile_path = fs::path(FLAGS_pidfile).make_preferred();

  if (pathExists(pidfile_path).ok()) {
    // if it exists, check if that pid is running.
    std::string content;
    auto read_status = readFile(pidfile_path, content, true);
    if (!read_status.ok()) {
      return Status(1, "Could not read pidfile: " + read_status.toString());
    }

    auto stale_status = checkStalePid(content);
    if (!stale_status.ok()) {
      return stale_status;
    }
  }

  // Now the pidfile is either the wrong pid or the pid is not running.
  if (!removePath(pidfile_path)) {
    // Unable to remove old pidfile.
    LOG(WARNING) << "Unable to remove the osqueryd pidfile";
  }

  // If no pidfile exists or the existing pid was stale, write, log, and run.
  auto pid = boost::lexical_cast<std::string>(
      PlatformProcess::getCurrentProcess()->pid());
  VLOG(1) << "Writing osqueryd pid (" << pid << ") to "
          << pidfile_path.string();
  auto status = writeTextFile(pidfile_path, pid, 0644);
  return status;
}

bool PlatformProcess::cleanup() const {
  if (!isValid()) {
    return false;
  }

  size_t delay = 0;
  size_t timeout = (FLAGS_alarm_timeout + 1) * 1000;
  while (delay < timeout) {
    int status = 0;
    if (checkStatus(status) == PROCESS_EXITED) {
      return true;
    }

    sleepFor(200);
    delay += 200;
  }
  // The requested process did not exit.
  return false;
}

#ifndef WIN32

static inline bool ownerFromResult(const Row& row, long& uid, long& gid) {
  if (!safeStrtol(row.at("uid"), 10, uid) ||
      !safeStrtol(row.at("gid"), 10, gid)) {
    return false;
  }
  return true;
}

bool DropPrivileges::dropToParent(const fs::path& path) {
  auto parent = path.parent_path().string();
  auto result = SQL::selectAllFrom("file", "path", EQUALS, parent);
  if (result.empty()) {
    return false;
  }

  if (result.front().at("symlink") == "1") {
    // The file is a symlink, inspect the owner of the link.
    struct stat link_stat;
    if (lstat(parent.c_str(), &link_stat) != 0) {
      return false;
    }

    return dropTo(link_stat.st_uid, link_stat.st_gid);
  }

  long uid = 0;
  long gid = 0;
  if (!ownerFromResult(result.front(), uid, gid)) {
    return false;
  }

  return dropTo(static_cast<uid_t>(uid), static_cast<gid_t>(gid));
}

bool DropPrivileges::dropTo(const std::string& user) {
  auto result = SQL::selectAllFrom("users", "username", EQUALS, user);
  if (result.empty()) {
    return false;
  }

  long uid = 0;
  long gid = 0;
  if (!ownerFromResult(result.front(), uid, gid)) {
    return false;
  }

  return dropTo(static_cast<uid_t>(uid), static_cast<gid_t>(gid));
}

bool setThreadEffective(uid_t uid, gid_t gid) {
#if defined(__APPLE__)
  return (pthread_setugid_np(uid, gid) == 0);
#elif defined(__linux__)
  return (syscall(SYS_setresgid, -1, gid, -1) == 0 &&
          syscall(SYS_setresuid, -1, uid, -1) == 0);
#endif
  return 0;
}

bool DropPrivileges::dropTo(const std::string& uid, const std::string& gid) {
  unsigned long int _uid = 0;
  unsigned long int _gid = 0;
  if (!safeStrtoul(uid, 10, _uid).ok() || !safeStrtoul(gid, 10, _gid).ok() ||
      !dropTo(static_cast<uid_t>(_uid), static_cast<gid_t>(_gid))) {
    return false;
  }
  return true;
}

bool DropPrivileges::dropTo(uid_t uid, gid_t gid) {
  if (uid == geteuid() && gid == getegid()) {
    // Privileges do not need to be dropped.
    return true;
  } else if (dropped() && uid == to_user_ && gid == to_group_) {
    // Privileges are already dropped to the requested user and group.
    return true;
  } else if (dropped()) {
    return false;
  }

  /// Drop process groups.
  if (original_groups_ != nullptr) {
    restoreGroups();
  }

  group_size_ = getgroups(0, nullptr);
  if (group_size_ > 0) {
    original_groups_ = (gid_t*)malloc(group_size_ * sizeof(gid_t));
    group_size_ = getgroups(group_size_, original_groups_);
  }
  setgroups(1, &gid);

  if (!setThreadEffective(uid, gid)) {
    (void)setegid(getgid());
    return false;
  }

  // Privileges are now dropped to the requested user/group.
  to_user_ = uid;
  to_group_ = gid;
  dropped_ = true;
  return true;
}

void DropPrivileges::restoreGroups() {
  if (group_size_ > 0) {
    setgroups(group_size_, original_groups_);
    group_size_ = 0;
    free(original_groups_);
  }
  original_groups_ = nullptr;
}

DropPrivileges::~DropPrivileges() {
  // We are elevating privileges, there is no security vulnerability if
  // either privilege change fails.
  if (dropped_) {
#ifdef __APPLE__
    setThreadEffective(KAUTH_UID_NONE, KAUTH_GID_NONE);
#else
    setThreadEffective(getuid(), getgid());
#endif
    dropped_ = false;
  }

  if (original_groups_ != nullptr) {
    restoreGroups();
  }
}
#endif
}

max_stars_repo_name: msekletar/osquery

max_issues_repo_name: msekletar/osquery


text: #include <boost/mpl/front_fwd.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**
 * Copyright Soramitsu Co., Ltd. 2018 All Rights Reserved.
 * http://soramitsu.co.jp
 *
 * 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.
 */

#ifndef IROHA_CONTAINER_VALIDATOR_HPP
#define IROHA_CONTAINER_VALIDATOR_HPP

#include <boost/format.hpp>
#include "datetime/time.hpp"
#include "interfaces/common_objects/types.hpp"
#include "interfaces/iroha_internal/block.hpp"
#include "validators/answer.hpp"

// TODO 22/01/2018 x3medima17: write stateless validator IR-837

namespace shared_model {
  namespace validation {

    /**
     * Class that validates blocks and proposal common fields
     */
    template <typename Iface,
              typename FieldValidator,
              typename TransactionValidator,
              typename TransactionsCollectionValidator>
    class ContainerValidator {
     protected:
      void validateTransaction(
          ReasonsGroupType &reason,
          const interface::Transaction &transaction) const {
        auto answer = transaction_validator_.validate(transaction);
        if (answer.hasErrors()) {
          auto message = (boost::format("Tx: %s") % answer.reason()).str();
          reason.second.push_back(message);
        }
      }
      void validateTransactions(
          ReasonsGroupType &reason,
          const interface::types::TransactionsCollectionType &transactions)
          const {
        auto answer = transactions_collection_validator_.validate(transactions);
        if (answer.hasErrors()) {
          reason.second.push_back(answer.reason());
        }
      }

     public:
      explicit ContainerValidator(
          const FieldValidator &field_validator = FieldValidator(),
          const TransactionsCollectionValidator
              &transactions_collection_validator =
                  TransactionsCollectionValidator(),
          const TransactionValidator &transaction_validator =
              TransactionValidator())
          : transactions_collection_validator_(
                transactions_collection_validator),
            transaction_validator_(transaction_validator),
            field_validator_(field_validator) {}

      Answer validate(const Iface &cont, std::string reason_name) const {
        Answer answer;
        ReasonsGroupType reason;
        reason.first = reason_name;
        field_validator_.validateCreatedTime(reason, cont.createdTime());
        field_validator_.validateHeight(reason, cont.height());
        validateTransactions(reason, cont.transactions());
        if (not reason.second.empty()) {
          answer.addReason(std::move(reason));
        }
        return answer;
      }

     private:
      TransactionsCollectionValidator transactions_collection_validator_;
      TransactionValidator transaction_validator_;

     protected:
      FieldValidator field_validator_;
    };

  }  // namespace validation
}  // namespace shared_model

#endif  // IROHA_CONTAINER_VALIDATOR_HPP

max_stars_repo_name: truongnmt/iroha

max_issues_repo_name: truongnmt/iroha

max_forks_repo_name: truongnmt/iroha


text:
//
// Created by System Administrator on 2019-07-29.
//

#include <tins/tins.h>
#include <unordered_map>
#include <unordered_set>
#include <boost/functional/hash.hpp>

#include <maths/stopping_points_t.hpp>
#include <node_t.hpp>

using namespace Tins;

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

    uint8_t max_ttl = 8;

    // Edges
    using edges_t = std::unordered_set<std::pair<uint32_t , uint32_t >, boost::hash<std::pair<uint32_t , uint32_t >>>;

    // In memory structure for the MDA. Tree structure with probabilities of each node to get reached.
    using probability_tree_t = std::vector<std::unordered_map<uint32_t, node_t>>;
    probability_tree_t probability_tree(max_ttl);

    PacketSender sender{NetworkInterface::default_interface()};

    for (uint8_t ttl = 2; ttl < max_ttl; ++ttl){
        // BFS into the tree.
        bool is_ttl_done = false;
        while(!is_ttl_done){
            // Dispatch the probes into different prefixes according to the distribution
            std::vector<IP> probes;

            for (const auto & reply_ip_routing_table : probability_tree[ttl]){

                // Each prefix of the routing table is considered as a possible source of multiple paths.
                // As far as new paths are found within a prefix, we split the prefix in smaller prefixes.
                // The stopping condition occurs when a prefix reach some statistical guarantees?
                const auto & routing_table_distribution = reply_ip_routing_table.second.routing_table_distribution;
                for (const auto & prefix_tracenodes : routing_table_distribution){
                    // Extract number of successors
                    const auto & tracenodes = prefix_tracenodes.second;
                    std::unordered_set<uint32_t> successors;
                    std::transform(tracenodes.begin(), tracenodes.end(), std::inserter(successors, successors.begin()), [](const auto & tracenode){
                        return tracenode.reply_ip;
                    });

                    auto n_successors = successors.size();
                    if (tracenodes.size() < mda_maths::nks95[])

                }

            }

            // Update the graph routing table after receiving the answers.

        }

    }

}

ext: cpp

max_stars_repo_name: dioptra-io/diamond-miner-cpp

max_issues_repo_name: dioptra-io/diamond-miner-cpp

max_forks_repo_name: dioptra-io/diamond-miner-cpp


text:
#pragma once

#include <Eigen/Core>

namespace ipc::rigid {

//-------------------------------------------------------------------------
// Signed Distances (useful for CCD)
//-------------------------------------------------------------------------

/// Compute the signed distance between a point and a line
/// WARNING: Produces the same sign as euclidean distance but may be
/// different scales.
template <typename T>
inline T point_line_signed_distance(
    const Vector2<T>& point,
    const Vector2<T>& line_point0,
    const Vector2<T>& line_point1);

/// Compute the signed distance between two lines
/// WARNING: Produces the same sign as euclidean distance but may be
/// different scales.
/// WARNING: Parallel edges results in zero distance
template <typename T>
inline T line_line_signed_distance(
    const Vector3<T>& line0_point0,
    const Vector3<T>& line0_point1,
    const Vector3<T>& line1_point0,
    const Vector3<T>& line1_point1);

/// Compute the distance between a point and a plane.
/// Normal is assumed to be unit length.
/// WARNING: Produces the same sign as euclidean distance but may be
/// different scales.
template <typename T>
inline T point_plane_signed_distance(
    const Vector3<T>& point,
    const Vector3<T>& triangle_vertex0,
    const Vector3<T>& triangle_vertex1,
    const Vector3<T>& triangle_vertex2);

} // namespace ipc::rigid

#include "distance.tpp"

max_stars_repo_name: ipc-sim/rigid-ipc

max_issues_repo_name: ipc-sim/rigid-ipc

max_forks_repo_name: ipc-sim/rigid-ipc


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

#include <nt2/elliptic/functions/am.hpp>
#include <boost/dispatch/attributes.hpp>
#include <nt2/elliptic/functions/generic/details/am_kernel.hpp>
#include <nt2/include/constants/half.hpp>
#include <nt2/include/constants/one.hpp>
#include <nt2/include/constants/pio_2.hpp>
#include <nt2/include/constants/two.hpp>
#include <nt2/include/functions/simd/abs.hpp>
#include <nt2/include/functions/simd/atan.hpp>
#include <nt2/include/functions/simd/exp.hpp>
#include <nt2/include/functions/simd/if_else.hpp>
#include <nt2/include/functions/simd/is_equal.hpp>
#include <nt2/include/functions/simd/minus.hpp>
#include <nt2/include/functions/simd/multiplies.hpp>

namespace nt2 { namespace ext
{

   BOOST_DISPATCH_IMPLEMENT  (am_, tag::cpu_,
                              (A0)(A1)(A2)(X),
                              ((simd_<floating_<A0>,X >))
                              ((simd_<floating_<A1>,X >))
                              (scalar_<floating_<A2> >)
                             )
   {
     typedef A0 result_type;

     BOOST_FORCEINLINE result_type operator()(const A0 & u, const A1 & x,
                                             const A2 & tol) const
    {
      result_type xx = nt2::abs(x);
      result_type k = if_else(eq(xx, One<A0>()), Half<A0>(), xx);
      return  if_else(eq(xx, One<A0>()),
                      Two<A0>()*atan(exp(u))-Pio_2<A0>(),
                      details::am_kernel(u, k, tol));
    }
  };

} }
#endif


text:
#include <cetty/zurg/slave/SlaveServiceImpl.h>

#include <boost/weak_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <cetty/util/SmallFile.h>
#include <cetty/config/ConfigCenter.h>
#include <cetty/logging/LoggerHelper.h>
#include <cetty/channel/EventLoopPool.h>

#include <cetty/zurg/Util.h>
#include <cetty/zurg/slave/Process.h>
#include <cetty/zurg/slave/ApplicationManager.h>
#include <cetty/zurg/slave/ProcessManager.h>
#include <cetty/zurg/slave/GetHardwareTask.h>

namespace cetty {
namespace zurg {
namespace slave {

using namespace cetty::zurg;
using namespace cetty::util;
using namespace cetty::channel;
using namespace cetty::config;

SlaveServiceImpl::SlaveServiceImpl(const EventLoopPtr& loop) {
    ConfigCenter::instance().configure(&config_);
    processManager_.reset(new ProcessManager(loop));
    applicationManager_.reset(new ApplicationManager(*processManager_));

    // start all configured applications
    init();
}

SlaveServiceImpl::~SlaveServiceImpl() {

}

void SlaveServiceImpl::getHardware(const ConstGetHardwareRequestPtr& request,
                                   const GetHardwareResponsePtr& response,
                                   const DoneCallback& done) {

    LOG_INFO << "SlaveServiceImpl::getHardware - lshw = "
             << request->lshw();

    GetHardwareTaskPtr task(new GetHardwareTask(request, response, done, *this));
}

void SlaveServiceImpl::getFileContent(const ConstGetFileContentRequestPtr& request,
                                      const GetFileContentResponsePtr& response,
                                      const DoneCallback& done) {

    LOG_INFO << "SlaveServiceImpl::getFileContent - " << request->file_name()
             << " maxSize = " << request->max_size();

    int64_t file_size = 0;
    int64_t modify_time = 0;
    int64_t create_time = 0;
    int err = SmallFile::readFile(request->file_name(),
                                  request->max_size(),
                                  response->mutable_content(),
                                  &file_size,
                                  &modify_time,
                                  &create_time);
    response->set_error_code(err);
    response->set_file_size(file_size);
    response->set_modify_time(modify_time);
    response->set_create_time(create_time);

    LOG_DEBUG << "SlaveServiceImpl::getFileContent - err " << err;
    done(response);
}

void SlaveServiceImpl::getFileChecksum(const ConstGetFileChecksumRequestPtr& request,
                                       const GetFileChecksumResponsePtr& response,
                                       const DoneCallback& done) {

    DLOG_DEBUG ;

    if (request->files_size() > 0) {
        RunCommandRequestPtr runCommandReq(new RunCommandRequest);
        runCommandReq->set_command("md5sum");

        for (int i = 0; i < request->files_size(); ++i) {
            assert(request->files(i).find('\n') == std::string::npos);
            runCommandReq->add_args(request->files(i));
        }

        runCommand(
            runCommandReq,
            NULL,
            boost::bind(&SlaveServiceImpl::getFileChecksumDone,
                        this, request, _1, done)
        );
    }
    else {
        GetFileChecksumResponse response;
        done(&response);
    }
}

void SlaveServiceImpl::getFileChecksumDone(const ConstGetFileChecksumRequestPtr& request,
        const google::protobuf::Message* message,
        const DoneCallback& done) {

    const RunCommandResponse* runCommandResp =
        google::protobuf::down_cast<const RunCommandResponse*>(message);

    const std::string& lines = runCommandResp->std_output();
    std::map<StringPiece, StringPiece> md5sums;
    parseMd5sum(lines, &md5sums);

    GetFileChecksumResponse response;

    for (int i = 0; i < request->files_size(); ++i) {
        md5sums[request->files(i)].copy_to(response.add_md5sums());
    }

    done(&response);
}

void SlaveServiceImpl::runCommand(const ConstRunCommandRequestPtr& request,
                                  const RunCommandResponsePtr& response,
                                  const DoneCallback& done) {

    LOG_INFO << "SlaveServiceImpl::runCommand - " << request->command();

    ProcessPtr process(new Process(request, response, done, true, true,
                                   config_.slaveName,
                                   config_.prefix));

    int err = 12; // ENOMEM;

    try {
        err = process->start();
    }
    catch (...) {}

    if (err) {
        response->set_error_code(err);
        done(response);
    }
    else {
        processManager_->runAtExit(
            process->pid(),  // bind strong ptr
            boost::bind(&Process::onCommandExit,
                        process, _1, _2)
        );

        EventLoopPtr elp = EventLoopPool::current();
        assert(elp);
        boost::weak_ptr<Process> weakProcessPtr(process);
        TimeoutPtr timerId = elp->runAfter(
                                 request->timeout(),
                                 boost::bind(&Process::onTimeoutWeak, weakProcessPtr)
                             );

        process->setTimerId(timerId);
    }
}

void SlaveServiceImpl::runScript(const ConstRunScriptRequestPtr& request,
                                 const RunCommandResponsePtr& response,
                                 const DoneCallback& done) {

    /*
    RunCommandRequestPtr runCommandReq(new RunCommandRequest);
    std::string scriptFile = writeTempFile(ZurgSlave::instance().getName(), request->script());

    if (!scriptFile.empty()) {
        LOG_INFO << "runScript - write to " << scriptFile;

        // FIXME: interpreter
        runCommandReq->set_command(scriptFile);

        // FIXME: others
        runCommand(runCommandReq, NULL, done);
    }else {
        LOG_ERROR << "runScript - failed to write script file";
        // FIXME: done
    }
    */
}

void SlaveServiceImpl::listProcesses(const ConstListProcessesRequestPtr& request,
                                     const ListProcessesResponsePtr& response,
                                     const DoneCallback& done) {

}

void SlaveServiceImpl::addApplication(const ConstAddApplicationRequestPtr& request,
                                      const AddApplicationResponsePtr& response,
                                      const DoneCallback& done) {
    applicationManager_->add(request, response, done);
}

void SlaveServiceImpl::startApplications(const ConstStartApplicationsRequestPtr& request,
        const StartApplicationsResponsePtr& response,
        const DoneCallback& done) {
    applicationManager_->start(request, response, done);
}

void SlaveServiceImpl::stopApplications(const ConstStopApplicationRequestPtr& request,
                                        const StopApplicationResponsePtr& response,
                                        const DoneCallback& done) {
    applicationManager_->stop(request, response, done);
}

void SlaveServiceImpl::listApplications(const ConstListApplicationsRequestPtr& request,
                                        const ListApplicationsResponsePtr& response,
                                        const DoneCallback& done) {
    applicationManager_->list(request, response, done);
}

void SlaveServiceImpl::removeApplications(const ConstRemoveApplicationsRequestPtr& request,
        const RemoveApplicationsResponsePtr& response,
        const DoneCallback& done) {
    applicationManager_->remove(request, response, done);
}

void SlaveServiceImpl::init() {
    for (size_t i = 0; i < config_.applications.size(); ++i) {
        SlaveServiceConfig::Application* application = config_.applications[i];
        addApplicationFromConfig(application);

        if (application->autoStart) {
            startApplication(application->name);
        }
    }
}

void SlaveServiceImpl::addApplicationFromConfig(SlaveServiceConfig::Application* application) {
    std::string name = application->name;
    boost::scoped_ptr<AddApplicationRequest> request(new AddApplicationRequest);

    request->set_name(name);
    request->set_binary(application->binary);
    request->set_cwd(application->cwd);

    request->set_redirect_stdout(application->redirectStdout);
    request->set_redirect_stderr(application->redirectStderr);
    request->set_auto_recover(application->autoRecover);
    request->set_log_file(application->logFile);

    std::string args;

    for (std::size_t j; j < application->args.size(); ++ j) {
        request->add_args(application->args[j]);
        args += application->args[j];
        args += " ";
    }

    for (std::size_t j = 0; j < application->envs.size(); ++j) {
        request->add_envs(application->envs.at(j));
    }

    boost::scoped_ptr<AddApplicationResponse> response(new AddApplicationResponse);
    addApplication(request.get(),
                   response.get(),
                   DoneCallback());
    LOG_INFO << "add application: " << name
             << " bin: " << application->binary
             << " cwd: " << application->cwd
             << " args: " << args;
}

void SlaveServiceImpl::startApplication(const std::string& name) {
    boost::scoped_ptr<StartApplicationsRequest> request(new StartApplicationsRequest);
    boost::scoped_ptr<StartApplicationsResponse> response(new StartApplicationsResponse);

    request->add_names()->assign(name);
    startApplications(request.get(),
                      response.get(),
                      DoneCallback());

    if (response->status(0).state() == kError) {
        LOG_ERROR << "start application " << name << " failed";
        removeApplication(name);
    }
    else {
        LOG_INFO << "application [" << name << "] "
                 << response->status(0).message();
    }
}

void SlaveServiceImpl::removeApplication(const std::string& name) {
    boost::scoped_ptr<RemoveApplicationsRequest> request(new RemoveApplicationsRequest);
    boost::scoped_ptr<RemoveApplicationsResponse> response(new RemoveApplicationsResponse);
    request->add_name(name);

    removeApplications(request.get(),
                       response.get(),
                       DoneCallback());
}

}
}
}


text:
//
// Created by breiker on 6/26/17.
//

#include "benchmark_integer_class.hpp"

#include <fstream>

#include "utils.hpp"

#if TEST_SIZE_BOOST
#include <boost/serialization/serialization.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>

#include <boost/serialization/vector.hpp>
using oarchive = boost::archive::binary_oarchive;
using iarchive = boost::archive::binary_iarchive;
#elif TEST_SIZE_CEREAL_BINARY
#include "cereal/cereal.hpp"
#include "cereal/archives/binary.hpp"

#include "cereal/types/vector.hpp"
using oarchive = cereal::BinaryOutputArchive;
using iarchive = cereal::BinaryInputArchive;
#elif TEST_SIZE_CEREAL_EXTENDABLE
#include "cereal/cereal.hpp"
#include "cereal/archives/extendable_binary.hpp"

#include "cereal/types/vector.hpp"
using oarchive = cereal::ExtendableBinaryOutputArchive;
using iarchive = cereal::ExtendableBinaryInputArchive;
#elif TEST_SIZE_PROTOBUF
#include "IntegerClass.pb.h"
#include "benchmark_integer_class_protobuf.hpp"
using oarchive = IntegerOProtobuf;
using iarchive = IntegerIProtobuf;

using oarchive_vect = IntegerVectOProtobuf;
using iarchive_vect = IntegerVectIProtobuf;
#else
#error "unknown test"
#endif

#ifndef TEST_SIZE_PROTOBUF
using oarchive_vect = oarchive;
using iarchive_vect = iarchive;
#endif

template<class OArchive>
void save()
{
  std::ofstream os("test_int.bin", std::ios::binary);
  IntegerClass c;
  InitWithRandomWholeRange(c);
  oarchive ar(os);
  ar << c;
}

template<class IArchive>
void load()
{
  std::ifstream is("test_int.bin", std::ios::binary);
  IntegerClass c;
  iarchive ar(is);
  ar >> c;
}

template<class OArchive>
void save_vect()
{
  std::ofstream os("test_vect.bin", std::ios::binary);
  IntegerClassVect c;
  RandomInit(100, InitWithRandomWholeRange, c);
  oarchive_vect ar(os);
  ar << c;
}

template<class IArchive>
void load_vect()
{
  std::ifstream is("test_vect.bin", std::ios::binary);
  IntegerClassVect c;
  iarchive_vect ar(is);
  ar >> c;
}

int main()
{
  save<oarchive>();
  load<iarchive>();
  save_vect<oarchive_vect>();
  load_vect<iarchive_vect>();
}


text:
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//————————————————————————————————————————————————————————————————————————————————————————————————————————————————
/*
    此文件是Rippled的一部分：https://github.com/ripple/rippled
    版权所有（c）2012，2013 Ripple Labs Inc.

    使用、复制、修改和/或分发本软件的权限
    特此授予免费或不收费的目的，前提是
    版权声明和本许可声明出现在所有副本中。

    本软件按“原样”提供，作者不作任何保证。
    关于本软件，包括
    适销性和适用性。在任何情况下，作者都不对
    任何特殊、直接、间接或后果性损害或任何损害
    因使用、数据或利润损失而导致的任何情况，无论是在
    合同行为、疏忽或其他侵权行为
    或与本软件的使用或性能有关。
**/

//==============================================================

#include <ripple/app/paths/Credit.h>
#include <ripple/app/paths/impl/StepChecks.h>
#include <ripple/app/paths/impl/Steps.h>
#include <ripple/basics/Log.h>
#include <ripple/ledger/PaymentSandbox.h>
#include <ripple/protocol/IOUAmount.h>
#include <ripple/protocol/Quality.h>

#include <boost/container/flat_set.hpp>

#include <numeric>
#include <sstream>

namespace ripple {

template <class TDerived>
class DirectStepI : public StepImp<IOUAmount, IOUAmount, DirectStepI<TDerived>>
{
protected:
    AccountID src_;
    AccountID dst_;
    Currency currency_;

//上一步赎回时收取过户费
    Step const* const prevStep_ = nullptr;
    bool const isLast_;
    beast::Journal j_;

    struct Cache
    {
        IOUAmount in;
        IOUAmount srcToDst;
        IOUAmount out;
        bool srcRedeems;

        Cache (
            IOUAmount const& in_,
            IOUAmount const& srcToDst_,
            IOUAmount const& out_,
            bool srcRedeems_)
            : in(in_)
            , srcToDst(srcToDst_)
            , out(out_)
            , srcRedeems(srcRedeems_)
        {}
    };

    boost::optional<Cache> cache_;

//计算可从SRC->DST AT流出的最大值
//最好的质量。
//返回：第一个元素是可以流动的最大量，
//其次，如果DST持有SRC的IOU，则为真。
    std::pair<IOUAmount, bool>
    maxPaymentFlow (
        ReadView const& sb) const;

//返回srcqout，dstqin
    std::pair <std::uint32_t, std::uint32_t>
    qualities (
        ReadView const& sb,
        bool srcRedeems,
        bool fwd) const;

public:
    DirectStepI (
        StrandContext const& ctx,
        AccountID const& src,
        AccountID const& dst,
        Currency const& c)
            : src_(src)
            , dst_(dst)
            , currency_ (c)
            , prevStep_ (ctx.prevStep)
            , isLast_ (ctx.isLast)
            , j_ (ctx.j)
    {}

    AccountID const& src () const
    {
        return src_;
    }
    AccountID const& dst () const
    {
        return dst_;
    }
    Currency const& currency () const
    {
        return currency_;
    }

    boost::optional<EitherAmount> cachedIn () const override
    {
        if (!cache_)
            return boost::none;
        return EitherAmount (cache_->in);
    }

    boost::optional<EitherAmount>
    cachedOut () const override
    {
        if (!cache_)
            return boost::none;
        return EitherAmount (cache_->out);
    }

    boost::optional<AccountID>
    directStepSrcAcct () const override
    {
        return src_;
    }

    boost::optional<std::pair<AccountID,AccountID>>
    directStepAccts () const override
    {
        return std::make_pair(src_, dst_);
    }

    bool
    redeems (ReadView const& sb, bool fwd) const override;

    std::uint32_t
    lineQualityIn (ReadView const& v) const override;

    boost::optional<Quality>
    qualityUpperBound(ReadView const& v, bool& redeems) const override;

    std::pair<IOUAmount, IOUAmount>
    revImp (
        PaymentSandbox& sb,
        ApplyView& afView,
        boost::container::flat_set<uint256>& ofrsToRm,
        IOUAmount const& out);

    std::pair<IOUAmount, IOUAmount>
    fwdImp (
        PaymentSandbox& sb,
        ApplyView& afView,
        boost::container::flat_set<uint256>& ofrsToRm,
        IOUAmount const& in);

    std::pair<bool, EitherAmount>
    validFwd (
        PaymentSandbox& sb,
        ApplyView& afView,
        EitherAmount const& in) override;

//检查错误、现有流动性和违反授权/冻结的行为
//约束条件。
    TER check (StrandContext const& ctx) const;

    void setCacheLimiting (
        IOUAmount const& fwdIn,
        IOUAmount const& fwdSrcToDst,
        IOUAmount const& fwdOut,
        bool srcRedeems);

    friend bool operator==(DirectStepI const& lhs, DirectStepI const& rhs)
    {
        return lhs.src_ == rhs.src_ &&
            lhs.dst_ == rhs.dst_ &&
            lhs.currency_ == rhs.currency_;
    }

    friend bool operator!=(DirectStepI const& lhs, DirectStepI const& rhs)
    {
        return ! (lhs == rhs);
    }

protected:
    std::string logStringImpl (char const* name) const
    {
        std::ostringstream ostr;
        ostr <<
            name << ": " <<
            "\nSrc: " << src_ <<
            "\nDst: " << dst_;
        return ostr.str ();
    }

private:
    bool equal (Step const& rhs) const override
    {
        if (auto ds = dynamic_cast<DirectStepI const*> (&rhs))
        {
            return *this == *ds;
        }
        return false;
    }
};

//————————————————————————————————————————————————————————————————————————————————————————————————————————————————

//在两种不同的情况下，流动用于转移资金：
//付款，以及
//o提供交叉路口。
//在这两种情况下，处理资金的规则几乎是，但不是
//完全一样。

//付款直接步骤类（不提供交叉）。
class DirectIPaymentStep : public DirectStepI<DirectIPaymentStep>
{
public:
    explicit DirectIPaymentStep() = default;

    using DirectStepI<DirectIPaymentStep>::DirectStepI;
    using DirectStepI<DirectIPaymentStep>::check;

    bool verifyPrevStepRedeems (bool) const
    {
//付款不关心是否提前赎回。
        return true;
    }

    bool verifyDstQualityIn (std::uint32_t dstQIn) const
    {
//付款对dstchin的未来没有特别的期望。
        return true;
    }

    std::uint32_t
    quality (ReadView const& sb,
//输入为真，输出为假
        bool qin) const;

//计算可从SRC->DST AT流出的最大值
//最好的质量。
//返回：第一个元素是可以流动的最大量，
//其次，如果DST持有SRC的IOU，则为真。
    std::pair<IOUAmount, bool>
    maxFlow (ReadView const& sb, IOUAmount const& desired) const;

//验证步骤的一致性。这些支票是特定于
//付款并假设已执行一般检查。
    TER
    check (StrandContext const& ctx,
        std::shared_ptr<const SLE> const& sleSrc) const;

    std::string logString () const override
    {
        return logStringImpl ("DirectIPaymentStep");
    }
};

//提供交叉DirectStep类（不是付款）。
class DirectIOfferCrossingStep : public DirectStepI<DirectIOfferCrossingStep>
{
public:
    explicit DirectIOfferCrossingStep() = default;

    using DirectStepI<DirectIOfferCrossingStep>::DirectStepI;
    using DirectStepI<DirectIOfferCrossingStep>::check;

    bool verifyPrevStepRedeems (bool prevStepRedeems) const
    {
//在报价交叉过程中，我们依赖的事实是
//将永远是错误的。那是因为：
//o如果有预告步骤u，它将永远是一个预定步骤。
//o bookstep:：redeems（）aways在提供交叉时返回false。
//基于此返回值的断言将告诉我们
//行为改变。
        return !prevStepRedeems;
    }

    bool verifyDstQualityIn (std::uint32_t dstQIn) const
    {
//由于以下几个因素，DSTCIN始终是
//提供交叉路口。如果这改变了，我们需要知道。
        return dstQIn == QUALITY_ONE;
    }

    std::uint32_t
    quality (ReadView const& sb,
//输入为真，输出为假
        bool qin) const;

//计算可从SRC->DST AT流出的最大值
//最好的质量。
//返回：第一个元素是可以流动的最大量，
//其次，如果DST持有SRC的IOU，则为真。
    std::pair<IOUAmount, bool>
    maxFlow (ReadView const& sb, IOUAmount const& desired) const;

//验证步骤的一致性。这些支票是特定于
//提供交叉口，并假设已执行一般检查。
    TER
    check (StrandContext const& ctx,
        std::shared_ptr<const SLE> const& sleSrc) const;

    std::string logString () const override
    {
        return logStringImpl ("DirectIOfferCrossingStep");
    }
};

//————————————————————————————————————————————————————————————————————————————————————————————————————————————————

std::uint32_t
DirectIPaymentStep::quality (ReadView const& sb,
//输入为真，输出为假
    bool qin) const
{
    if (src_ == dst_)
        return QUALITY_ONE;

    auto const sle = sb.read (keylet::line (dst_, src_, currency_));

    if (!sle)
        return QUALITY_ONE;

    auto const& field = [this, qin]() -> SF_U32 const&
    {
        if (qin)
        {
//计算DST质量
            if (this->dst_ < this->src_)
                return sfLowQualityIn;
            else
                return sfHighQualityIn;
        }
        else
        {
//计算SRC质量输出
            if (this->src_ < this->dst_)
                return sfLowQualityOut;
            else
                return sfHighQualityOut;
        }
    }();

    if (! sle->isFieldPresent (field))
        return QUALITY_ONE;

    auto const q = (*sle)[field];
    if (!q)
        return QUALITY_ONE;
    return q;
}

std::uint32_t
DirectIOfferCrossingStep::quality (ReadView const&,
//输入为真，输出为假
    bool) const
{
//如果提供交叉，则忽略信任线质量字段。这个
//保持着悠久的传统。
    return QUALITY_ONE;
}

std::pair<IOUAmount, bool>
DirectIPaymentStep::maxFlow (ReadView const& sb, IOUAmount const&) const
{
    return maxPaymentFlow (sb);
}

std::pair<IOUAmount, bool>
DirectIOfferCrossingStep::maxFlow (
    ReadView const& sb, IOUAmount const& desired) const
{
//当islast和offer交叉时，则忽略信任线限制。要约
//交叉具有超过信任线设置的限制的能力。
//我们假定，如果有人提出报价，那么他们打算
//尽可能多地填写报价单，即使报价超过
//信任线设置的限制。
//
//关于使用“out”作为MaxFlow所需参数的说明。在一些
//在付款过程中，我们最终需要一个大于
//“out”表示“maxsrctodst”。但到目前为止（2016年6月），这种情况从未发生过
//报价交叉时。这是因为，由于一些因素，
//“dstqin”始终是优质的“offer crossing”。

    if (isLast_)
        return {desired, false};

    return maxPaymentFlow (sb);
}

TER
DirectIPaymentStep::check (
    StrandContext const& ctx, std::shared_ptr<const SLE> const& sleSrc) const
{
//因为这是一笔付款，所以必须存在一个信托额度。全部执行
//与信任行相关的检查。
    {
        auto const sleLine = ctx.view.read (keylet::line (src_, dst_, currency_));
        if (!sleLine)
        {
            JLOG (j_.trace()) << "DirectStepI: No credit line. " << *this;
            return terNO_LINE;
        }

        auto const authField = (src_ > dst_) ? lsfHighAuth : lsfLowAuth;

        if (((*sleSrc)[sfFlags] & lsfRequireAuth) &&
            !((*sleLine)[sfFlags] & authField) &&
            (*sleLine)[sfBalance] == beast::zero)
        {
            JLOG (j_.warn())
                << "DirectStepI: can't receive IOUs from issuer without auth."
                << " src: " << src_;
            return terNO_AUTH;
        }

        if (ctx.prevStep &&
            fix1449(ctx.view.info().parentCloseTime))
        {
            if (ctx.prevStep->bookStepBook())
            {
                auto const noRippleSrcToDst =
                    ((*sleLine)[sfFlags] &
                     ((src_ > dst_) ? lsfHighNoRipple : lsfLowNoRipple));
                if (noRippleSrcToDst)
                    return terNO_RIPPLE;
            }
        }
    }

    {
        auto const owed = creditBalance (ctx.view, dst_, src_, currency_);
        if (owed <= beast::zero)
        {
            auto const limit = creditLimit (ctx.view, dst_, src_, currency_);
            if (-owed >= limit)
            {
                JLOG (j_.debug())
                    << "DirectStepI: dry: owed: " << owed << " limit: " << limit;
                return tecPATH_DRY;
            }
        }
    }
    return tesSUCCESS;
}

TER
DirectIOfferCrossingStep::check (
    StrandContext const&, std::shared_ptr<const SLE> const&) const
{
//标准支票是我们能做的，因为剩下的支票
//需要建立信任关系。报价交叉不能
//需要预先存在的信任线。
    return tesSUCCESS;
}

//————————————————————————————————————————————————————————————————————————————————————————————————————————————————

template <class TDerived>
std::pair<IOUAmount, bool>
DirectStepI<TDerived>::maxPaymentFlow (ReadView const& sb) const
{
    auto const srcOwed = toAmount<IOUAmount> (
        accountHolds (sb, src_, currency_, dst_, fhIGNORE_FREEZE, j_));

    if (srcOwed.signum () > 0)
        return {srcOwed, true};

//srcouded为负或零
    return {creditLimit2 (sb, dst_, src_, currency_) + srcOwed, false};
}

template <class TDerived>
bool
DirectStepI<TDerived>::redeems (ReadView const& sb, bool fwd) const
{
    if (fwd && cache_)
        return cache_->srcRedeems;

    auto const srcOwed = accountHolds (
        sb, src_, currency_, dst_, fhIGNORE_FREEZE, j_);
    return srcOwed.signum () > 0;
}

template <class TDerived>
std::pair<IOUAmount, IOUAmount>
DirectStepI<TDerived>::revImp (
    PaymentSandbox& sb,
    /*lyview和/*afview*/，
    Boost：：container：：flat_set<uint256>&/*ofrstor*/,

    IOUAmount const& out)
{
    cache_.reset ();

    bool srcRedeems;
    IOUAmount maxSrcToDst;

    std::tie (maxSrcToDst, srcRedeems) =
        static_cast<TDerived const*>(this)->maxFlow (sb, out);

    std::uint32_t srcQOut, dstQIn;
    std::tie (srcQOut, dstQIn) = qualities (sb, srcRedeems, false);
    assert (static_cast<TDerived const*>(this)->verifyDstQualityIn (dstQIn));

    Issue const srcToDstIss (currency_, srcRedeems ? dst_ : src_);

    JLOG (j_.trace()) <<
        "DirectStepI::rev" <<
        " srcRedeems: " << srcRedeems <<
        " outReq: " << to_string (out) <<
        " maxSrcToDst: " << to_string (maxSrcToDst) <<
        " srcQOut: " << srcQOut <<
        " dstQIn: " << dstQIn;

    if (maxSrcToDst.signum () <= 0)
    {
        JLOG (j_.trace()) << "DirectStepI::rev: dry";
        cache_.emplace (
            IOUAmount (beast::zero),
            IOUAmount (beast::zero),
            IOUAmount (beast::zero),
            srcRedeems);
        return {beast::zero, beast::zero};
    }

    IOUAmount const srcToDst = mulRatio (
        /*，Quality_One，Dstqin，/*Roundup*/true）；

    if（srctodst<=maxsrctodst）
    {
        iouamount const in=multratio（
            srctodst、srcqout、quality_one、/*roundu*/ true);

        cache_.emplace (in, srcToDst, out, srcRedeems);
        rippleCredit (sb,
                      src_, dst_, toSTAmount (srcToDst, srcToDstIss),
                      /*heckissuer*/true，j_uu）；
        jLog（j_.trace（））<<
            “directstepi:：rev:non-limiting”<<
            “srcredems：”<<srcredems<<
            “in：”<<to_string（in）<<
            “srctodst：”<<to_string（srctodst）<<
            “out：”<<to_string（out）；
        返回输入，输出
    }

    //限制节点
    iouamount const in=multratio（
        Maxsrctodst、srcqout、Quality_One、/*Roundu*/ true);

    IOUAmount const actualOut = mulRatio (
        /*srctodst，dstchin，quality_one，/*roundup*/false）；
    缓存模板（in，maxsrctodst，actualout，srcreems）；
    RippleCredit（某人，
                  SRC_uuu，DST_u，Tostamount（最大SRCTodst，SRCTodstiss）
                  检查问题*/ true, j_);

    JLOG (j_.trace()) <<
        "DirectStepI::rev: Limiting" <<
        " srcRedeems: " << srcRedeems <<
        " in: " << to_string (in) <<
        " srcToDst: " << to_string (maxSrcToDst) <<
        " out: " << to_string (out);
    return {in, actualOut};
}

//远期信用证的流动性永远不应超过反向信用证的流动性。
//通过。但有时四舍五入的差异会导致向前传球
//提供更多的流动性。使用反向传递中的缓存值
//为了防止这种情况。
template <class TDerived>
void
DirectStepI<TDerived>::setCacheLimiting (
    IOUAmount const& fwdIn,
    IOUAmount const& fwdSrcToDst,
    IOUAmount const& fwdOut,
    bool srcRedeems)
{
    if (cache_->in < fwdIn)
    {
        IOUAmount const smallDiff(1, -9);
        auto const diff = fwdIn - cache_->in;
        if (diff > smallDiff)
        {
            if (fwdIn.exponent () != cache_->in.exponent () ||
                !cache_->in.mantissa () ||
                (double(fwdIn.mantissa ()) /
                    double(cache_->in.mantissa ())) > 1.01)
            {
//在向前通过时检测大的差异，以便进行调查
                JLOG (j_.warn())
                    << "DirectStepI::fwd: setCacheLimiting"
                    << " fwdIn: " << to_string (fwdIn)
                    << " cacheIn: " << to_string (cache_->in)
                    << " fwdSrcToDst: " << to_string (fwdSrcToDst)
                    << " cacheSrcToDst: " << to_string (cache_->srcToDst)
                    << " fwdOut: " << to_string (fwdOut)
                    << " cacheOut: " << to_string (cache_->out);
                cache_.emplace (fwdIn, fwdSrcToDst, fwdOut, srcRedeems);
                return;
            }
        }
    }
    cache_->in = fwdIn;
    if (fwdSrcToDst < cache_->srcToDst)
        cache_->srcToDst = fwdSrcToDst;
    if (fwdOut < cache_->out)
        cache_->out = fwdOut;
    cache_->srcRedeems = srcRedeems;
};

template <class TDerived>
std::pair<IOUAmount, IOUAmount>
DirectStepI<TDerived>::fwdImp (
    PaymentSandbox& sb,
    /*lyview和/*afview*/，
    Boost：：container：：flat_set<uint256>&/*ofrstor*/,

    IOUAmount const& in)
{
    assert (cache_);

    bool srcRedeems;
    IOUAmount maxSrcToDst;
    std::tie (maxSrcToDst, srcRedeems) =
        static_cast<TDerived const*>(this)->maxFlow (sb, cache_->srcToDst);

    std::uint32_t srcQOut, dstQIn;
    std::tie (srcQOut, dstQIn) = qualities (sb, srcRedeems, true);

    Issue const srcToDstIss (currency_, srcRedeems ? dst_ : src_);

    JLOG (j_.trace()) <<
            "DirectStepI::fwd" <<
            " srcRedeems: " << srcRedeems <<
            " inReq: " << to_string (in) <<
            " maxSrcToDst: " << to_string (maxSrcToDst) <<
            " srcQOut: " << srcQOut <<
            " dstQIn: " << dstQIn;

    if (maxSrcToDst.signum () <= 0)
    {
        JLOG (j_.trace()) << "DirectStepI::fwd: dry";
        cache_.emplace (
            IOUAmount (beast::zero),
            IOUAmount (beast::zero),
            IOUAmount (beast::zero),
            srcRedeems);
        return {beast::zero, beast::zero};
    }

    IOUAmount const srcToDst = mulRatio (
        /*Quality_One，srcqout，/*Roundup*/false）；

    if（srctodst<=maxsrctodst）
    {
        iouamount const out=多比率（
            srctodst、dstchin、quality_one、/*roundu*/ false);

        setCacheLimiting (in, srcToDst, out, srcRedeems);
        rippleCredit (sb,
            src_, dst_, toSTAmount (cache_->srcToDst, srcToDstIss),
            /*heckissuer*/true，j_uu）；
        jLog（j_.trace（））<<
                “directstepi:：fwd:非限制”<<
                “srcredems：”<<srcredems<<
                “in：”<<to_string（in）<<
                “srctodst：”<<to_string（srctodst）<<
                “out：”<<to_string（out）；
    }
    其他的
    {
        //限制节点
        iouamount const actuann=multratio（
            Maxsrctodst、srcqout、Quality_One、/*Roundu*/ true);

        IOUAmount const out = mulRatio (
            /*srctodst，dstchin，quality_one，/*roundup*/false）；
        setcachelimiting（actuann、maxsrctodst、out、srcreems）；
        RippleCredit（某人，
            SRC_uuu，DST_u，Tostamount（高速缓存->srctodst，srctodstiss）
            检查问题*/ true, j_);

        JLOG (j_.trace()) <<
                "DirectStepI::rev: Limiting" <<
                " srcRedeems: " << srcRedeems <<
                " in: " << to_string (actualIn) <<
                " srcToDst: " << to_string (srcToDst) <<
                " out: " << to_string (out);
    }
    return {cache_->in, cache_->out};
}

template <class TDerived>
std::pair<bool, EitherAmount>
DirectStepI<TDerived>::validFwd (
    PaymentSandbox& sb,
    ApplyView& afView,
    EitherAmount const& in)
{
    if (!cache_)
    {
        JLOG (j_.trace()) << "Expected valid cache in validFwd";
        return {false, EitherAmount (IOUAmount (beast::zero))};
    }

    auto const savCache = *cache_;

    assert (!in.native);

    bool srcRedeems;
    IOUAmount maxSrcToDst;
    std::tie (maxSrcToDst, srcRedeems) =
        static_cast<TDerived const*>(this)->maxFlow (sb, cache_->srcToDst);

    try
    {
        boost::container::flat_set<uint256> dummy;
fwdImp (sb, afView, dummy, in.iou);  //更改缓存
    }
    catch (FlowException const&)
    {
        return {false, EitherAmount (IOUAmount (beast::zero))};
    }

    if (maxSrcToDst < cache_->srcToDst)
    {
        JLOG (j_.error()) <<
            "DirectStepI: Strand re-execute check failed." <<
            " Exceeded max src->dst limit" <<
            " max src->dst: " << to_string (maxSrcToDst) <<
            " actual src->dst: " << to_string (cache_->srcToDst);
        return {false, EitherAmount(cache_->out)};
    }

    if (!(checkNear (savCache.in, cache_->in) &&
          checkNear (savCache.out, cache_->out)))
    {
        JLOG (j_.error()) <<
            "DirectStepI: Strand re-execute check failed." <<
            " ExpectedIn: " << to_string (savCache.in) <<
            " CachedIn: " << to_string (cache_->in) <<
            " ExpectedOut: " << to_string (savCache.out) <<
            " CachedOut: " << to_string (cache_->out);
        return {false, EitherAmount (cache_->out)};
    }
    return {true, EitherAmount (cache_->out)};
}

//返回srcqout，dstqin
template <class TDerived>
std::pair<std::uint32_t, std::uint32_t>
DirectStepI<TDerived>::qualities (
    ReadView const& sb,
    bool srcRedeems,
    bool fwd) const
{
    if (srcRedeems)
    {
        if (!prevStep_)
            return {QUALITY_ONE, QUALITY_ONE};

        auto const prevStepQIn = prevStep_->lineQualityIn (sb);
        auto srcQOut = static_cast<TDerived const*>(this)->quality (
            /*/*SRC质量输出*/错误）；

        如果（prevstepqin>srcqout）
            srcqout=prevstepqin；
        退货srcqout，质量一
    }
    其他的
    {
        //在发行和上一步赎回时收取转移率
        auto const prevstep redeems=prevstep&&prevstep->redeems（sb，fwd）；
        断言（static_cast<tderived const*>（this）->verifyPrevStepRedeems（
            PrevStepRedems））；

        标准：：uint32常数srcqout=
            预防措施？传输率（sb，src_uu）。值：质量_1；
        auto dstqin=static_cast<tderived const*>（this）->质量（
            SB，/*DST质量输入*/ true);

        if (isLast_ && dstQIn > QUALITY_ONE)
            dstQIn = QUALITY_ONE;
        return {srcQOut, dstQIn};
    }
}

template <class TDerived>
std::uint32_t
DirectStepI<TDerived>::lineQualityIn (ReadView const& v) const
{
//DST质量
    return static_cast<TDerived const*>(this)->quality (
        /*/*DST质量为*/真）；
}

template<class tderived>
boost：：可选<quality>
directstepi<tderive>：质量上界（readview const&v，bool&redeems）const
{
    auto const prevredems=赎回；
    redeems=this->redeems（v，true）；
    标准：：uint32常数srcqout=
        （预防和&！赎回）？传输率（V，SRC_uu）。值：质量_1；
    auto dstqin=static_cast<tderived const*>（this）->质量（
        V，/*DST质量输入*/ true);

    if (isLast_ && dstQIn > QUALITY_ONE)
        dstQIn = QUALITY_ONE;
    Issue const iss{currency_, src_};
    return Quality(getRate(STAmount(iss, srcQOut), STAmount(iss, dstQIn)));
}

template <class TDerived>
TER DirectStepI<TDerived>::check (StrandContext const& ctx) const
{
//以下支票既适用于付款，也适用于报价交叉。
    if (!src_ || !dst_)
    {
        JLOG (j_.debug()) << "DirectStepI: specified bad account.";
        return temBAD_PATH;
    }

    if (src_ == dst_)
    {
        JLOG (j_.debug()) << "DirectStepI: same src and dst.";
        return temBAD_PATH;
    }

    auto const sleSrc = ctx.view.read (keylet::account (src_));
    if (!sleSrc)
    {
        JLOG (j_.warn())
            << "DirectStepI: can't receive IOUs from non-existent issuer: "
            << src_;
        return terNO_ACCOUNT;
    }

//纯发行/兑换不能冻结
    if (!(ctx.isLast && ctx.isFirst))
    {
        auto const ter = checkFreeze(ctx.view, src_, dst_, currency_);
        if (ter != tesSUCCESS)
            return ter;
    }

//如果前一步是直接步骤，那么我们需要检查
//没有波纹标志。
    if (ctx.prevStep)
    {
        if (auto prevSrc = ctx.prevStep->directStepSrcAcct())
        {
            auto const ter = checkNoRipple(
                ctx.view, *prevSrc, src_, dst_, currency_, j_);
            if (ter != tesSUCCESS)
                return ter;
        }
    }
    {
        Issue const srcIssue{currency_, src_};
        Issue const dstIssue{currency_, dst_};

        if (ctx.seenBookOuts.count (srcIssue))
        {
            if (!ctx.prevStep)
            {
assert(0); //上一个看到的书没有上一步！？！
                return temBAD_PATH_LOOP;
            }

//如果上一步是输出此问题的书籍步骤，则可以执行此操作。
            if (auto book = ctx.prevStep->bookStepBook())
            {
                if (book->out != srcIssue)
                    return temBAD_PATH_LOOP;
            }
        }

        if (!ctx.seenDirectIssues[0].insert (srcIssue).second ||
            !ctx.seenDirectIssues[1].insert (dstIssue).second)
        {
            JLOG (j_.debug ())
                << "DirectStepI: loop detected: Index: " << ctx.strandSize
                << ' ' << *this;
            return temBAD_PATH_LOOP;
        }
    }

    return static_cast<TDerived const*>(this)->check (ctx, sleSrc);
}

//————————————————————————————————————————————————————————————————————————————————————————————————————————————————

namespace test
{
//测试所需
bool directStepEqual (Step const& step,
    AccountID const& src,
    AccountID const& dst,
    Currency const& currency)
{
    if (auto ds =
        dynamic_cast<DirectStepI<DirectIPaymentStep> const*> (&step))
    {
        return ds->src () == src && ds->dst () == dst &&
            ds->currency () == currency;
    }
    return false;
}
}  //测试

//————————————————————————————————————————————————————————————————————————————————————————————————————————————————

std::pair<TER, std::unique_ptr<Step>>
make_DirectStepI (
    StrandContext const& ctx,
    AccountID const& src,
    AccountID const& dst,
    Currency const& c)
{
    TER ter = tefINTERNAL;
    std::unique_ptr<Step> r;
    if (ctx.offerCrossing)
    {
        auto offerCrossingStep =
            std::make_unique<DirectIOfferCrossingStep> (ctx, src, dst, c);
        ter = offerCrossingStep->check (ctx);
        r = std::move (offerCrossingStep);
    }
else //付款
    {
        auto paymentStep =
            std::make_unique<DirectIPaymentStep> (ctx, src, dst, c);
        ter = paymentStep->check (ctx);
        r = std::move (paymentStep);
    }
    if (ter != tesSUCCESS)
        return {ter, nullptr};

    return {tesSUCCESS, std::move (r)};
}

} //涟漪

max_stars_repo_name: yinchengtsinghua/RippleCPPChinese

max_issues_repo_name: yinchengtsinghua/RippleCPPChinese

max_forks_repo_name: yinchengtsinghua/RippleCPPChinese


text:
#pragma once

/// \defgroup order-book Order book management
///
/// Order book management provides support for reconstructing and
/// querying per-asset order book state such as top and depth of book bid
/// and ask price and size.

//#include <boost/multi_index/ordered_index.hpp>
//#include <boost/multi_index/hashed_index.hpp>
//#include <boost/multi_index_container.hpp>
//#include <boost/multi_index/member.hpp>

#include <unordered_map>
#include <cstdint>
#include <utility>
#include <memory>
#include <string>
#include <list>
#include <map>

namespace hm {

    /// \addtogroup order-book
    /// @{

    /// \brief Order side.
    enum class side_type : uint8_t {
        /// Buy order
        buy = 1,
        /// Sell order
        sell = 2,
    };

    /// \brief Trading state.
    enum class trading_state : uint8_t {
        /// Trading state is unknown.
        unknown,
        /// Trading is halted.
        halted,
        /// Trading is paused.
        paused,
        /// Quotation only period.
        quotation_only,
        /// Trading is ongoing.
        trading,
        /// Auction period.
        auction,
    };

    struct price_level;

    /// \brief Order is a request to buy or sell quantity of asset at a
    /// specified price.
    struct order final {
        price_level* level;
        uint64_t     id;
        uint64_t     price;
        uint64_t     quantity;
        side_type    side;
        uint64_t     timestamp;

        order(uint64_t id, uint64_t price, uint64_t quantity, side_type side, uint64_t timestamp)
            : level{ nullptr }
            , id{ id }
            , price{ price }
            , quantity{ quantity }
            , side{ side }
            , timestamp{ timestamp }
        {}
    };

    /// \brief Price level is a time-prioritized list of orders with the same price.
    struct price_level {
        explicit price_level(uint64_t price_)
            : price(price_)
            , size(0)
        { }

        uint64_t price;
        uint64_t size;
    };

    /// \brief Order execution details.
    struct execution {
        //! The price order was executed with.
        uint64_t price;
        //! The side of the liquidity taker of the trade.
        side_type side;
        //! The number of remaining quantity on the traded price level.
        uint64_t remaining;

        execution(uint64_t price, side_type side, uint64_t remaining);
    };

    /// \brief Order book is a price-time prioritized list of buy and sell
    /// orders.
    class order_book {

    //     using order_set = boost::multi_index::multi_index_container<
    //         order,
    //         boost::multi_index::indexed_by<
    //         boost::multi_index::hashed_unique<
    //         boost::multi_index::member<order, uint64_t, &order::id>
    //         >
    //         >
    //     >;
    //     using iterator = order_set::iterator;

        std::string _symbol;
        uint64_t _timestamp;
        trading_state _state;
        // order_set _orders;
        std::map<uint64_t, price_level, std::greater<uint64_t>> _bids;
        std::map<uint64_t, price_level, std::less   <uint64_t>> _asks;
    public:
        order_book(std::string symbol, uint64_t timestamp, size_t max_orders = 0);

        const std::string& symbol() const {
            return _symbol;
        }

        void set_timestamp(uint64_t timestamp) {
            _timestamp = timestamp;
        }

        uint64_t timestamp() const {
            return _timestamp;
        }

        void set_state(trading_state state) {
            _state = state;
        }

        trading_state state() const {
            return _state;
        }

        void add(order order);
        void replace(uint64_t order_id, order order);
        void cancel(uint64_t order_id, uint64_t quantity);
        execution execute(uint64_t order_id, uint64_t quantity);
        void remove(uint64_t order_id);
        side_type side(uint64_t order_id) const;

        size_t bid_levels() const;
        size_t ask_levels() const;
        size_t order_count() const;

        uint64_t bid_price(size_t level) const;
        uint64_t bid_size(size_t level) const;
        uint64_t ask_price(size_t level) const;
        uint64_t ask_size(size_t level) const;
        uint64_t midprice(size_t level) const;

    private:
        // void remove(iterator& iter);

        template<typename T>
        void remove(const order& o, T& levels);

        template<typename T>
        price_level& lookup_or_create(T& levels, uint64_t price);
    };
}

ext: hh

max_stars_repo_name: cegrell/hermes

max_issues_repo_name: cegrell/hermes

max_forks_repo_name: cegrell/hermes


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

////////////////////////////////////////////////////////////////////////////////
// unaligned_store for AVX SIMD types
////////////////////////////////////////////////////////////////////////////////

//==============================================================================
// TODO : Documentation for simd unaligned_store
// TODO : Make them work properly with ContiguousRandomAccessIterator
//==============================================================================
#include <boost/simd/toolbox/operator/functions/unaligned_store.hpp>
#include <boost/simd/sdk/memory/iterator.hpp>
#include <boost/dispatch/functor/preprocessor/call.hpp>

//==============================================================================
// unaligned_load vector of double
//==============================================================================
namespace boost { namespace simd { namespace ext
{
  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::unaligned_store_ , boost::simd::tag::avx_
                            , (A0)(A1)(A2)
                            , ((simd_< double_<A0>, boost::simd::tag::avx_ >))
                              (iterator_< scalar_< double_<A1> > >)
                              (scalar_< integer_<A2> >)
                            )
  {
    typedef A0 result_type;

    BOOST_SIMD_FUNCTOR_CALL(3)
    {
      _mm256_storeu_pd(a1+a2,a0);
      return a0;
    }
  };
} } }

namespace boost { namespace simd { namespace ext
{
  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::unaligned_store_ , boost::simd::tag::avx_
                            , (A0)(A1)
                            , ((simd_< double_<A0>, boost::simd::tag::avx_ >))
                              (iterator_< scalar_< double_<A1> > >)
                            )
  {
    typedef A0 result_type;

    BOOST_SIMD_FUNCTOR_CALL(2)
    {
      _mm256_storeu_pd(a1,a0);
      return a0;
    }
  };
} } }

//==============================================================================
// unaligned_load vector of float
//==============================================================================
namespace boost { namespace simd { namespace ext
{
  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::unaligned_store_ , boost::simd::tag::avx_
                            , (A0)(A1)(A2)
                            , ((simd_< single_<A0>, boost::simd::tag::avx_ >))
                              (iterator_< scalar_< single_<A1> > >)
                              (scalar_< integer_<A2> >)
                            )
  {
    typedef A0 result_type;

    BOOST_SIMD_FUNCTOR_CALL(3)
    {
      _mm256_storeu_ps(a1+a2,a0);
      return a0;
    }
  };
} } }

namespace boost { namespace simd { namespace ext
{
  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::unaligned_store_ , boost::simd::tag::avx_
                            , (A0)(A1)
                            , ((simd_< single_<A0>, boost::simd::tag::avx_ >))
                              (iterator_< scalar_< single_<A1> > >)
                            )
  {
    typedef A0 result_type;

    BOOST_SIMD_FUNCTOR_CALL(2)
    {
      _mm256_storeu_ps(a1,a0);
      return a0;
    }
  };
} } }

//==============================================================================
// unaligned_load vector of integer
//==============================================================================
namespace boost { namespace simd { namespace ext
{
  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::unaligned_store_ , boost::simd::tag::avx_
                            , (A0)(A1)(A2)
                            , ((simd_< integer_<A0>, boost::simd::tag::avx_ >))
                              (iterator_< scalar_< integer_<A1> > >)
                              (scalar_< integer_<A2> >)
                            )
  {
    typedef A0 result_type;

    BOOST_SIMD_FUNCTOR_CALL(3)
    {
      _mm256_storeu_si256(reinterpret_cast<__m256i*>(a1+a2), a0);
      return a0;
    }
  };
} } }

namespace boost { namespace simd { namespace ext
{
  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::unaligned_store_ , boost::simd::tag::avx_
                            , (A0)(A1)
                            , ((simd_< integer_<A0>, boost::simd::tag::avx_ >))
                              (iterator_< scalar_< integer_<A1> > >)
                            )
  {
    typedef A0 result_type;

    BOOST_SIMD_FUNCTOR_CALL(2)
    {
      _mm256_storeu_si256(reinterpret_cast<__m256i*>(a1), a0);
      return a0;
    }
  };
} } }

#endif
#endif


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Alejandro Cabrera 2011.
// 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/bloom_filter for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <boost/bloom_filter/basic_bloom_filter.hpp>
#include <boost/bloom_filter/dynamic_bloom_filter.hpp>
#include <boost/bloom_filter/counting_bloom_filter.hpp>
#include <boost/unordered_set.hpp>
#include <set>
using boost::bloom_filters::basic_bloom_filter;
using boost::bloom_filters::dynamic_bloom_filter;
using boost::bloom_filters::counting_bloom_filter;
using boost::unordered_set;

typedef basic_bloom_filter<int, 1000> basic_bloom;
typedef dynamic_bloom_filter<int> basic_dynamic_bloom;
typedef counting_bloom_filter<int, 1000> counting_bloom;

int main()
{
  basic_bloom basic;
  basic_dynamic_bloom dynamic(1000);
  counting_bloom counting;
  boost::unordered_set<int> hash_set;
  std::set<int> set;

  std::cout << "\n============== Static size comparison ==============\n";

  std::cout << "Basic Bloom filter static size: " << sizeof(basic_bloom) << "\n"
            << "Basic dynamic Bloom filter static size: " << sizeof(basic_dynamic_bloom) << "\n"
            << "Counting Bloom filter static size: " << sizeof(counting_bloom) << "\n"
            << "Unordered set static size: " << sizeof(boost::unordered_set<int>) << "\n"
            << "Set static size: " << sizeof(std::set<int>) << std::endl;

  for (size_t i = 0; i < 1000; ++i) {
    basic.insert(i);
    dynamic.insert(i);
    counting.insert(i);
    hash_set.insert(i);
    set.insert(i);
  }

  std::cout << "\n============== Run-time size comparison ==============\n";

  std::cout << "Basic Bloom filter run-time size: " << 0 << "\n"
            << "Basic dynamic Bloom filter run-time size: " << dynamic.bit_capacity() << "\n"
            << "Counting Bloom filter run-time size: " << 0 << "\n"
            << "Unordered set run-time size: " << sizeof(int) * hash_set.size() << " + X\n"
            << "Set run-time size: " << sizeof(int) * set.size() << " + X"  << std::endl;

  std::cout << "\n============== Total size comparison ==============\n";

  std::cout << "Basic Bloom filter total size: " << sizeof(basic_bloom) + 0 << "\n"
            << "Basic dynamic Bloom filter total size: " << sizeof(basic_dynamic_bloom) + dynamic.bit_capacity() << "\n"
            << "Counting Bloom filter total size: " << sizeof(counting_bloom) + 0 << "\n"
            << "Unordered set total size: " << sizeof(boost::unordered_set<int>) + sizeof(int) * hash_set.size() << " + X\n"
            << "Set total size: " << sizeof(std::set<int>) + sizeof(int) * set.size() << " + X"  << std::endl;

  return 0;
}

max_stars_repo_name: tetzank/boost-bloom-filters

max_issues_repo_name: tetzank/boost-bloom-filters

max_forks_repo_name: tetzank/boost-bloom-filters


text:
#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
#include "index/PersistentElementStore.hpp"

#include <boost/test/unit_test.hpp>
#include "test_utils/DependencyProvider.hpp"
#include "test_utils/ElementUtils.hpp"

#include <boost/filesystem/operations.hpp>
#include <cstdio>

using namespace utymap;
using namespace utymap::entities;
using namespace utymap::index;
using namespace utymap::mapcss;

namespace {
    const std::string TestZoomDirectory = "1";

    const std::string stylesheet = "node|z1[any], way|z1[any], area|z1[any], relation|z1[any] { clip: false; }";

    struct Index_PersistentElementStoreFixture
    {
        Index_PersistentElementStoreFixture() :
            dependencyProvider(),
            elementStore("", *dependencyProvider.getStringTable())
        {
            boost::filesystem::create_directory(TestZoomDirectory);
        }

        ~Index_PersistentElementStoreFixture()
        {
            elementStore.commit();

            boost::filesystem::path dir(TestZoomDirectory);
            for (boost::filesystem::directory_iterator dirEnd, it(dir); it != dirEnd; ++it) {
                boost::filesystem::remove_all(it->path());
            }
            boost::filesystem::remove(TestZoomDirectory);
        }

        DependencyProvider dependencyProvider;
        PersistentElementStore elementStore;
    };

    struct ElementCounter : public ElementVisitor
    {
        int times = 0;
        std::shared_ptr<Element> element;

        void visitNode(const Node& node) override
        {
            ++times;
            element = std::make_shared<Node>(node);
        }

        void visitWay(const Way& way) override
        {
            ++times;
            element = std::make_shared<Way>(way);
        }
        void visitArea(const Area& area) override
        {
            ++times;
            element = std::make_shared<Area>(area);
        }
        void visitRelation(const Relation& relation) override
        {
            ++times;
            element = std::make_shared<Relation>(relation);
        }
    };

    void assertGeometry(const GeoCoordinate& expected, const GeoCoordinate& actual)
    {
        BOOST_CHECK_EQUAL(expected.latitude, actual.latitude);
        BOOST_CHECK_EQUAL(expected.longitude, actual.longitude);
    }

    void assertGeometry(const std::vector<GeoCoordinate>& expected, const std::vector<GeoCoordinate>& actual)
    {
        BOOST_CHECK_EQUAL(expected.size(), actual.size());

        for (std::size_t i = 0; i < expected.size(); ++i) {
            assertGeometry(expected[i], actual[i]);
        }
    }

    void assertElement(const Element& expected, const Element& actual)
    {
        BOOST_CHECK_EQUAL(expected.id, actual.id);
        BOOST_CHECK_EQUAL(expected.tags.size(), actual.tags.size());
    }

    void assertNode(const Node& expected, const Node& actual)
    {
        assertElement(expected, actual);
        assertGeometry(expected.coordinate, actual.coordinate);
    }

    template<typename T>
    void assertWayOrArea(const T& expected, const T& actual)
    {
        assertElement(expected, actual);
        assertGeometry(expected.coordinates, actual.coordinates);
    }
}

BOOST_FIXTURE_TEST_SUITE(Index_PersistentElementStore, Index_PersistentElementStoreFixture)

BOOST_AUTO_TEST_CASE(GivenNode_WhenStoreAndSearch_ThenItIsStoredAndReadBack)
{
    LodRange range(1, 2);
    QuadKey quadKey(1, 0, 0);
    auto styleProvider = dependencyProvider.getStyleProvider(stylesheet);
    Node node = ElementUtils::createElement<Node>(*dependencyProvider.getStringTable(), 7, { { "any", "true" } });
    node.coordinate = { 5, -5 };
    ElementCounter counter;

    elementStore.store(node, range, *styleProvider);
    elementStore.commit();
    elementStore.search(quadKey, counter);

    assertNode(node, *std::dynamic_pointer_cast<Node>(counter.element));
}

BOOST_AUTO_TEST_CASE(GivenWay_WhenStoreAndSearch_ThenItIsStoredAndReadBack)
{
    LodRange range(1, 2);
    QuadKey quadKey(1, 0, 0);
    auto styleProvider = dependencyProvider.getStyleProvider(stylesheet);
    Way way = ElementUtils::createElement<Way>(*dependencyProvider.getStringTable(), 7, { { "any", "true" } }, { { 1, -1 }, {5, -5} });
    ElementCounter counter;

    elementStore.store(way, range, *styleProvider);
    elementStore.commit();
    elementStore.search(quadKey, counter);

    assertWayOrArea(way, *std::dynamic_pointer_cast<Way>(counter.element));
}

BOOST_AUTO_TEST_CASE(GivenArea_WhenStoreAndSearch_ThenItIsStoredAndReadBack)
{
    LodRange range(1, 2);
    QuadKey quadKey(1, 0, 0);
    auto styleProvider = dependencyProvider.getStyleProvider(stylesheet);
    Area area = ElementUtils::createElement<Area>(*dependencyProvider.getStringTable(), 7, { { "any", "true" } }, { { 1, -1 }, { 5, -5 }, { 10, -10 } });
    ElementCounter counter;

    elementStore.store(area, range, *styleProvider);
    elementStore.commit();
    elementStore.search(quadKey, counter);

    assertWayOrArea(area, *std::dynamic_pointer_cast<Area>(counter.element));
}

BOOST_AUTO_TEST_CASE(GivenRelationWithDifferentElements_WhenStoreAndSearch_ThenItIsStoredAndReadBack)
{
    LodRange range(1, 2);
    QuadKey quadKey(1, 0, 0);
    auto styleProvider = dependencyProvider.getStyleProvider(stylesheet);
    Node node = ElementUtils::createElement<Node>(*dependencyProvider.getStringTable(), 1, { { "n", "1" } });
    node.coordinate = { 0.5, -0.5 };
    Way way = ElementUtils::createElement<Way>(*dependencyProvider.getStringTable(), 2, { { "w", "2" } }, { { 1, -1 }, { 2, -2 } });
    Area area = ElementUtils::createElement<Area>(*dependencyProvider.getStringTable(), 3, { { "a", "3" } }, { { 3, -3 }, { 4, -4 }, { 5, -5 } });
    Relation relation = ElementUtils::createElement<Relation>(*dependencyProvider.getStringTable(), 4, { { "any", "true" } });
    relation.elements.push_back(std::make_shared<Node>(node));
    relation.elements.push_back(std::make_shared<Way>(way));
    relation.elements.push_back(std::make_shared<Area>(area));
    ElementCounter counter;

    elementStore.store(relation, range, *styleProvider);
    elementStore.commit();
    elementStore.search(quadKey, counter);

    BOOST_CHECK_EQUAL(counter.times, 1);
    Relation result = *std::dynamic_pointer_cast<Relation>(counter.element);
    assertElement(relation, result);
}

BOOST_AUTO_TEST_CASE(GivenTwoAreas_WhenStoreAndSearchOnce_ThenTheyStoredTwiceAndSecondReturnedLast)
{
    LodRange range(1, 2);
    QuadKey quadKey(1, 0, 0);
    auto styleProvider = dependencyProvider.getStyleProvider(stylesheet);
    Area area1 = ElementUtils::createElement<Area>(*dependencyProvider.getStringTable(), 1, { { "any", "true" } }, { { 4, -4 }, { 5, -5 }, { 6, -6 } });
    Area area2 = ElementUtils::createElement<Area>(*dependencyProvider.getStringTable(), 2, { { "any", "true"} }, { { 1, -1 }, { 2, -2 }, { 3, -3 } });
    ElementCounter counter;

    elementStore.store(area1, range, *styleProvider);
    elementStore.store(area2, range, *styleProvider);
    elementStore.commit();
    elementStore.search(quadKey, counter);

    BOOST_CHECK_EQUAL(counter.times, 2);
    assertWayOrArea(area2, *std::dynamic_pointer_cast<Area>(counter.element));
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: lonnibesancon/utymap

max_issues_repo_name: daeilkim/utymap

max_forks_repo_name: daeilkim/utymap


text:
/**
 ** Copyright (c) 2014 Illumina, Inc.
 **
 ** This file is part of Illumina's Enhanced Artificial Genome Engine (EAGLE),
 ** covered by the "BSD 2-Clause License" (see accompanying LICENSE file)
 **
 ** \description Time display.
 **
 ** \author Mauricio Varea
 **/

#include <fstream>
#include <algorithm>
#include <boost/format.hpp>

#include "common/Logger.hh"
#include "common/FileSystem.hh"

namespace eagle
{
namespace common
{

/*
 * \brief Non-recursive GLOB operation
 */
std::vector<boost::filesystem::path> Glob::glob( const boost::filesystem::path& dir ) const
{
    std::vector<boost::filesystem::path> files;
    if (boost::filesystem::is_directory(dir))
    {
        for( boost::filesystem::directory_iterator it(dir), end;
             it != end;
             ++it)
        {
            boost::smatch match;
            if (boost::regex_match( it->path().leaf().string(), match, pattern_ ))
            {
                EAGLE_DEBUG(4, "... " << it->path().leaf() );
                files.push_back( it->path() );
            }
        }
    } else {
        boost::smatch match;
        if (boost::regex_match( dir.leaf().string(), match, pattern_ ))
        {
            EAGLE_DEBUG(4, "... " << dir.leaf() );
            // ... return vector with only one element
            files.push_back( dir );
        }
    }
    if (files.empty())
    {
        EAGLE_WARNING( (boost::format("Regex \"%s\" did not match any files in %s") % pattern_ % dir ).str() );
    } else {
        std::stable_sort(files.begin(),files.end());
    }
    return files;
}

} // namespace common
} // namespace eagle

max_stars_repo_name: sequencing/EAGLE

max_issues_repo_name: sequencing/EAGLE

max_forks_repo_name: sequencing/EAGLE