text:
#include <boost/cstdint.hpp>
#include <numpy_eigen/boost_python_headers.hpp>
#include <sm/timing/TimestampCorrector.hpp>

template <typename TIME_T>
void exportTimestampCorrector(const std::string& className) {
    using namespace boost::python;
    using namespace sm::timing;

    class_<TimestampCorrector<TIME_T> >(className.c_str(), init<>())
        .def("correctTimestamp", &TimestampCorrector<TIME_T>::correctTimestamp,
             "correctedEventLocalTime = correctTimestamp(eventRemoteTime, eventLocalTimes).\nNote: This function must "
             "be called with monotonically increasing remote timestamps.")
        .def("getLocalTime", &TimestampCorrector<TIME_T>::getLocalTime,
             "eventLocalTime = getLocalTime(eventRemoteTime)")
        .def("convexHullSize", &TimestampCorrector<TIME_T>::convexHullSize)
        .def("printHullPoints", &TimestampCorrector<TIME_T>::printHullPoints)
        .def("getSlope", &TimestampCorrector<TIME_T>::getSlope)
        .def("getOffset", &TimestampCorrector<TIME_T>::getOffset);
}

void exportTimestampCorrectors() {
    exportTimestampCorrector<double>("DoubleTimestampCorrector");
    exportTimestampCorrector<boost::int64_t>("LongTimestampCorrector");
}

max_stars_repo_name: chengfzy/kalibr

max_issues_repo_name: chengfzy/kalibr

max_forks_repo_name: chengfzy/kalibr


text:
/*
 * test_Parameter.cpp
 *
 *  Created on: 2013-2-28
 *      Author: fasiondog
 */

#ifdef TEST_ALL_IN_ONE
    #include <boost/test/unit_test.hpp>
#else
    #define BOOST_TEST_MODULE test_hikyuu_utilities
    #include <boost/test/unit_test.hpp>
#endif

#include <hikyuu/Log.h>
#include <hikyuu/utilities/Parameter.h>
#include <hikyuu/StockManager.h>

#if HKU_SUPPORT_SERIALIZATION
#include <fstream>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#endif

using namespace hku;

/**
 * @defgroup test_hikyuu_Parameter test_hikyuu_Parameter
 * @ingroup test_hikyuu_utilities
 * @{
 */

/** @par 检测点 */
BOOST_AUTO_TEST_CASE( test_Parameter ) {
    Parameter param;

    /** @arg 正常添加、读取、修改参数 */
    param.set<int>("n", 1);
    param.set<bool>("bool", true);
    param.set<double>("double", 10);
    param.set<string>("string", "test");
    BOOST_CHECK(param.get<int>("n") == 1);
    BOOST_CHECK(param.get<bool>("bool") == true);
    BOOST_CHECK(param.get<double>("double") == 10.0);
    BOOST_CHECK(param.get<string>("string") == "test");
    param.set<int>("n", 10);
    param.set<bool>("bool", false);
    param.set<double>("double", 10.01);
    param.set<string>("string", "test2");
    BOOST_CHECK(param.get<int>("n") == 10);
    BOOST_CHECK(param.get<bool>("bool") == false);
    BOOST_CHECK(param.get<double>("double") == 10.01);
    BOOST_CHECK(param.get<string>("string") == "test2");

    /** @arg 添加不支持的参数类型 */
    BOOST_CHECK_THROW(param.set<size_t>("n", 10), std::logic_error);
    BOOST_CHECK_THROW(param.set<float>("n", 10.0), std::logic_error);

    /** @arg 修改参数时，指定的类型和原有类型不符 */
    BOOST_CHECK_THROW(param.set<float>("n", 10.0), std::logic_error);
    BOOST_CHECK_THROW(param.set<float>("bool", 10.0), std::logic_error);
    BOOST_CHECK_THROW(param.set<float>("double", 10.0), std::logic_error);

    /** @arg 测试相等比较 */
    Parameter p1, p2;
    p1.set<string>("string", "test");
    p1.set<bool>("bool", true);
    p1.set<double>("double", 0.01);
    p1.set<string>("test", "test2");

    p2.set<double>("double", 0.01);
    p2.set<string>("test", "test2");
    p2.set<string>("string", "test");
    p2.set<bool>("bool", true);

    BOOST_CHECK(p1==p2);

    /** @arg 测试使用 Stock 做为参数 */
    Stock stk = getStock("sh600000");
    Parameter p;
    p.set<Stock>("stk", stk);
    Stock stk2 = p.get<Stock>("stk");
    BOOST_CHECK(stk == stk2);

    /** @arg 测试使用 KQuery 做为参数 */
    KQuery query(10, 20);
    p = Parameter();
    p.set<KQuery>("query", query);
    KQuery q2;
    q2 = p.get<KQuery>("query");
    BOOST_CHECK(query == q2);

    /** @arg 测试使用 KData 做为参数 */
    KData k = stk.getKData(query);
    p = Parameter();
    p.set<KData>("k", k);
    KData k2 = p.get<KData>("k");
    BOOST_CHECK(k.size() == k2.size());
    BOOST_CHECK(k.getStock() == k2.getStock());
    BOOST_CHECK(k.getQuery() == k2.getQuery());

    k = KData();
    p = Parameter();
    p.set<KData>("k", k);
    k2 = p.get<KData>("k");
    BOOST_CHECK(k.size() == k2.size());
    BOOST_CHECK(k.getStock() == k2.getStock());
    BOOST_CHECK(k.getQuery() == k2.getQuery());

    /** @arg 测试使用 PriceList 做为参数 */
    PriceList x;
    for (int i = 0; i < 10; i++) {
        x.push_back(i);
    }
    p = Parameter();
    p.set<PriceList>("x", x);
    PriceList x2 = p.get<PriceList>("x");
    BOOST_CHECK(x.size() == x2.size());
    for (int i = 0; i < 10; i++) {
        BOOST_CHECK(x[i] == x2[i]);
    }
}

#if HKU_SUPPORT_SERIALIZATION
/** @par 检测点 */
BOOST_AUTO_TEST_CASE( test_Parameter_serialize ) {
    string filename(StockManager::instance().tmpdir());
    filename += "/Parameter.xml";

    Parameter p1;
    p1.set<int>("n", 10);
    p1.set<bool>("bool", true);
    p1.set<double>("p", 0.101);
    p1.set<string>("string", "This is string!");
    Stock stk = getStock("sh600000");
    KQuery q = KQueryByDate(Datetime(200001041025), Datetime(200001041100), KQuery::MIN5);
    KData k = stk.getKData(q);
    p1.set<Stock>("stk", stk);
    p1.set<KQuery>("query", q);
    p1.set<KData>("kdata", k);

    PriceList x;
    for (int i = 0; i < 10; i++) {
        x.push_back(i);
    }
    p1.set<PriceList>("x", x);

    {
        std::ofstream ofs(filename);
        boost::archive::xml_oarchive oa(ofs);
        oa << BOOST_SERIALIZATION_NVP(p1);
    }

    Parameter p2;
    {
        std::ifstream ifs(filename);
        boost::archive::xml_iarchive ia(ifs);
        ia >> BOOST_SERIALIZATION_NVP(p2);
    }

    BOOST_CHECK(p2.get<int>("n") == 10);
    BOOST_CHECK(p2.get<bool>("bool") == true);
    BOOST_CHECK(p2.get<double>("p") == 0.101);
    BOOST_CHECK(p2.get<string>("string") == "This is string!");
    BOOST_CHECK(p2.get<Stock>("stk") == stk);
    BOOST_CHECK(p2.get<KQuery>("query") == q);
    KData k2 = p2.get<KData>("kdata");
    BOOST_CHECK(k.size() == k2.size());
    BOOST_CHECK(k.getStock() == k2.getStock());
    BOOST_CHECK(k.getQuery() == k2.getQuery());
    PriceList x2 = p2.get<PriceList>("x");
    BOOST_CHECK(x.size() == x2.size());
    for (int i = 0; i < 10; i++) {
        BOOST_CHECK(x[i] == x2[i]);
    }
}
#endif /* HKU_SUPPORT_SERIALIZATION */

/** @} */

ext: cpp

max_stars_repo_name: awesome-archive/hikyuu

max_forks_repo_name: archya/hikyuu


text:
// Boost.Bimap
//
// Copyright (c) 2006-2007 Matias Capeletto
//
// 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)

/// \file vector_of.hpp
/// \brief Include support for vector constrains for the bimap container

#ifndef BOOST_BIMAP_VECTOR_OF_HPP
#define BOOST_BIMAP_VECTOR_OF_HPP

#if defined(_MSC_VER) && (_MSC_VER>=1200)
#pragma once
#endif

#include <boost/config.hpp>

#include <boost/bimap/detail/user_interface_config.hpp>

#include <boost/mpl/bool.hpp>

#include <boost/concept_check.hpp>

#include <boost/bimap/detail/concept_tags.hpp>

#include <boost/bimap/tags/support/value_type_of.hpp>

#include <boost/bimap/detail/generate_index_binder.hpp>
#include <boost/bimap/detail/generate_view_binder.hpp>
#include <boost/bimap/detail/generate_relation_binder.hpp>

#include <boost/multi_index/random_access_index.hpp>

#include <boost/bimap/views/vector_map_view.hpp>
#include <boost/bimap/views/vector_set_view.hpp>

namespace boost {
namespace bimaps {

/// \brief Set Type Specification
/**
This struct is used to specify a set specification.
It is not a container, it is just a metaprogramming facility to
express the type of a set. Generally, this specification will
be used in other place to create a container.
It has the same syntax that an std::vector instantiation, except
that the allocator cannot be specified. The rationale behind
this difference is that the allocator is not part of the set
type specification, rather it is a container configuration
parameter.
The first parameter is the type of the objects in the set, and
the second one is a Functor that compares them.
Bimap binding metafunctions can be used with this class in
the following way:

\code
using namespace support;

BOOST_STATIC_ASSERT( is_set_type_of< vector_of<Type> >::value )

BOOST_STATIC_ASSERT
(
     is_same
     <
        vector_of<Type>::index_bind
        <
            KeyExtractor,
            Tag

        >::type,

        random_access< tag<Tag>, KeyExtractor >

    >::value
)

typedef bimap
<
    vector_of<Type>, RightKeyType

> bimap_with_left_type_as_vector;

BOOST_STATIC_ASSERT
(
    is_same
    <
        vector_of<Type>::map_view_bind
        <
            member_at::left,
            bimap_with_left_type_as_vector

        >::type,

        vector_map_view< member_at::left, bimap_with_left_type_as_vector >

    >::value
)

\endcode

See also vector_of_relation.
                                                                        **/

template< class Type >
struct vector_of : public ::boost::bimaps::detail::set_type_of_tag
{
    /// User type, can be tagged
    typedef Type user_type;

    /// Type of the object that will be stored in the vector
	typedef BOOST_DEDUCED_TYPENAME ::boost::bimaps::tags::support::
		value_type_of<user_type>::type value_type;

    struct lazy_concept_checked
    {
        BOOST_CLASS_REQUIRE ( value_type,
                              boost, AssignableConcept );

        typedef vector_of type;
    };

    BOOST_BIMAP_GENERATE_INDEX_BINDER_0CP_NO_EXTRACTOR(

        // binds to
        multi_index::random_access
    )

    BOOST_BIMAP_GENERATE_MAP_VIEW_BINDER(

        // binds to
        views::vector_map_view
    )

    BOOST_BIMAP_GENERATE_SET_VIEW_BINDER(

        // binds to
        views::vector_set_view
    )

    typedef mpl::bool_<true> mutable_key;
};

/// \brief Set Of Relation Specification
/**
This struct is similar to vector_of but it is bind logically to a
relation. It is used in the bimap instantiation to specify the
desired type of the main view. This struct implements internally
a metafunction named bind_to that manages the quite complicated
task of finding the right type of the set for the relation.

\code
template<class Relation>
struct bind_to
{
    typedef -unspecified- type;
};
\endcode

See also vector_of, is_set_type_of_relation.
                                                                **/

struct vector_of_relation : public ::boost::bimaps::detail::set_type_of_relation_tag
{
    BOOST_BIMAP_GENERATE_RELATION_BINDER_0CP(

        // binds to
        vector_of
    )

    typedef mpl::bool_<true>  left_mutable_key;
    typedef mpl::bool_<true> right_mutable_key;
};

} // namespace bimaps
} // namespace boost

#endif // BOOST_BIMAP_VECTOR_OF_HPP

ext: hpp


text:
// Copyright 2018 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/throw_exception.hpp>
#include <boost/core/lightweight_test.hpp>

#if defined(_MSC_VER)
# pragma warning(disable: 4702) // unreachable code
#endif

class my_exception: public std::exception
{
};

class my_exception2: public std::exception, public boost::exception
{
};

class my_exception3: public std::exception, public virtual boost::exception
{
};

int main()
{
    BOOST_TEST_THROWS( boost::throw_exception( my_exception() ), boost::exception );
    BOOST_TEST_THROWS( boost::throw_exception( my_exception2() ), boost::exception );
    BOOST_TEST_THROWS( boost::throw_exception( my_exception3() ), boost::exception );

    BOOST_TEST_THROWS( BOOST_THROW_EXCEPTION( my_exception() ), boost::exception );
    BOOST_TEST_THROWS( BOOST_THROW_EXCEPTION( my_exception2() ), boost::exception );
    BOOST_TEST_THROWS( BOOST_THROW_EXCEPTION( my_exception3() ), boost::exception );

    return boost::report_errors();
}

max_issues_repo_name: qingkouwei/mediaones

max_forks_repo_name: qingkouwei/mediaones


text:
/*
 * Copyright 2011 Nate Koenig & Andrew Howard
 *
 * 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 <msgs/msgs.h>

#include <boost/thread/recursive_mutex.hpp>
#include <sstream>
#include <limits>
#include <algorithm>

#include "common/KeyFrame.hh"
#include "common/Animation.hh"
#include "common/Plugin.hh"
#include "common/Events.hh"
#include "common/Exception.hh"
#include "common/Console.hh"
#include "common/CommonTypes.hh"
#include "common/MeshManager.hh"
#include "common/Mesh.hh"
#include "common/Skeleton.hh"
#include "common/SkeletonAnimation.hh"
#include "common/BVHLoader.hh"

#include "physics/World.hh"
#include "physics/Joint.hh"
#include "physics/Link.hh"
#include "physics/Model.hh"
#include "physics/PhysicsEngine.hh"
#include "physics/Actor.hh"

#include "transport/Node.hh"

using namespace gazebo;
using namespace physics;
using namespace common;

//////////////////////////////////////////////////
Actor::Actor(BasePtr _parent)
  : Model(_parent)
{
  this->AddType(ACTOR);
  this->mesh = NULL;
  this->skeleton = NULL;
}

//////////////////////////////////////////////////
Actor::~Actor()
{
  this->skelAnimation.clear();
  this->bonePosePub.reset();
}

//////////////////////////////////////////////////
void Actor::Load(sdf::ElementPtr _sdf)
{
  std::string name = _sdf->GetValueString("name");

  sdf::ElementPtr skinSdf = _sdf->GetOrCreateElement("skin");
  this->skinFile = skinSdf->GetValueString("filename");
  this->skinScale = skinSdf->GetValueDouble("scale");

  MeshManager::Instance()->Load(this->skinFile);
  std::string actorName = _sdf->GetValueString("name");

  if (MeshManager::Instance()->HasMesh(this->skinFile))
  {
    this->mesh = MeshManager::Instance()->GetMesh(this->skinFile);
    if (!this->mesh->HasSkeleton())
      gzthrow("Collada file does not contain skeletal animation.");
    this->skeleton = mesh->GetSkeleton();
    this->skeleton->Scale(this->skinScale);
    /// create the link sdfs for the model
    NodeMap nodes = this->skeleton->GetNodes();

    sdf::ElementPtr linkSdf;
    linkSdf = _sdf->GetOrCreateElement("link");
    linkSdf->GetAttribute("name")->Set(actorName + "_origin");
    linkSdf->GetAttribute("gravity")->Set(false);
    sdf::ElementPtr linkPose = linkSdf->GetOrCreateElement("origin");

    this->AddSphereInertia(linkSdf, math::Pose(), 1.0, 0.01);
    this->AddSphereCollision(linkSdf, actorName + "_origin_col",
                                             math::Pose(), 0.02);
    this->AddSphereVisual(linkSdf, actorName + "_origin_vis",
                    math::Pose(), 0.05, "Gazebo/White", Color::White);

    for (NodeMapIter iter = nodes.begin(); iter != nodes.end(); ++iter)
    {
      SkeletonNode* bone = iter->second;

      linkSdf = _sdf->AddElement("link");

      linkSdf->GetAttribute("name")->Set(bone->GetName());
      linkSdf->GetAttribute("gravity")->Set(false);
      linkPose = linkSdf->GetOrCreateElement("origin");
      math::Pose pose(bone->GetModelTransform().GetTranslation(),
                      bone->GetModelTransform().GetRotation());
      linkPose->GetAttribute("pose")->Set(pose);

      /// FIXME hardcoded inertia of a sphere with mass 1.0 and radius 0.01
      this->AddSphereInertia(linkSdf, math::Pose(), 1.0, 0.01);

      /// FIXME hardcoded collision to sphere with radius 0.02
      this->AddSphereCollision(linkSdf, bone->GetName() + "_collision",
                       math::Pose(), 0.02);

      /// FIXME hardcoded visual to red sphere with radius 0.02
      if (bone->IsRootNode())
      {
        this->AddSphereVisual(linkSdf, bone->GetName() + "_visual",
                            math::Pose(), 0.02, "Gazebo/Blue", Color::Blue);
        this->AddActorVisual(linkSdf, name + "_visual", pose.GetInverse());
        this->visualName = name + "::" + bone->GetName()
                             + "::" + name + "_visual";
      }
      else
        if (bone->GetChildCount() == 0)
        {
            this->AddSphereVisual(linkSdf, bone->GetName() + "_visual",
                            math::Pose(), 0.02, "Gazebo/Yellow", Color::Yellow);
        }
        else
          this->AddSphereVisual(linkSdf, bone->GetName() + "_visual",
                            math::Pose(), 0.02, "Gazebo/Red", Color::Red);

      for (unsigned int i = 0; i < bone->GetChildCount(); i++)
      {
        SkeletonNode *curChild = bone->GetChild(i);

        math::Vector3 r = curChild->GetTransform().GetTranslation();
        math::Vector3 linkPos = math::Vector3(r.x / 2.0, r.y / 2.0, r.z / 2.0);
        math::Vector3 dir = curChild->GetModelTransform().GetTranslation() -
            bone->GetModelTransform().GetTranslation();
        double length = dir.GetLength();
        double theta = atan2(dir.y, dir.x);
        double phi = acos(dir.z / length);

        math::Pose bonePose(linkPos, math::Quaternion(0.0, phi, theta));
        bonePose.rot = pose.rot.GetInverse() * bonePose.rot;

        this->AddBoxVisual(linkSdf, bone->GetName() + "_" + curChild->GetName()
          + "_link", bonePose, math::Vector3(0.02, 0.02, length),
          "Gazebo/Green", Color::Green);
      }
    }

    sdf::ElementPtr animSdf = _sdf->GetOrCreateElement("animation");

    while (animSdf)
    {
      this->LoadAnimation(animSdf);
      animSdf = animSdf->GetNextElement("animation");
    }

    this->LoadScript(_sdf->GetOrCreateElement("script"));

    /// we are ready to load the links
    Model::Load(_sdf);
    this->bonePosePub = this->node->Advertise<msgs::PoseAnimation>(
                                       "~/skeleton_pose/info", 10);
  }
}

//////////////////////////////////////////////////
void Actor::LoadScript(sdf::ElementPtr _sdf)
{
  this->loop = _sdf->GetValueBool("loop");
  this->startDelay = _sdf->GetValueDouble("delay_start");
  this->autoStart = _sdf->GetValueBool("auto_start");
  this->active = this->autoStart;

  sdf::ElementPtr trajSdf = _sdf->GetOrCreateElement("trajectory");
  while (trajSdf)
  {
    TrajectoryInfo tinfo;
    tinfo.id = trajSdf->GetValueInt("id");
    tinfo.type = trajSdf->GetValueString("type");
    std::vector<TrajectoryInfo>::iterator iter = this->trajInfo.begin();
    while (iter != this->trajInfo.end())
    {
      if (iter->id > tinfo.id)
        break;
      ++iter;
    }

    unsigned int idx = iter - this->trajInfo.begin();
    this->trajInfo.insert(iter, tinfo);

    std::map<double, math::Pose> points;

    sdf::ElementPtr wayptSdf = trajSdf->GetOrCreateElement("waypoint");
    while (wayptSdf)
    {
      points[wayptSdf->GetValueDouble("time")] = wayptSdf->GetValuePose("pose");
      wayptSdf = wayptSdf->GetNextElement("waypoint");
    }

    std::map<double, math::Pose>::reverse_iterator last = points.rbegin();
    std::stringstream animName;
    animName << tinfo.type << "_" << tinfo.id;
    common::PoseAnimation *anim = new common::PoseAnimation(animName.str(),
                                                          last->first, false);
    this->trajInfo[idx].duration = last->first;

    for (std::map<double, math::Pose>::iterator pIter = points.begin();
          pIter != points.end(); ++pIter)
    {
      common::PoseKeyFrame *key;
      if (pIter == points.begin() && !math::equal(pIter->first, 0.0))
      {
        key = anim->CreateKeyFrame(0.0);
        key->SetTranslation(pIter->second.pos);
        key->SetRotation(pIter->second.rot);
      }
      key = anim->CreateKeyFrame(pIter->first);
      key->SetTranslation(pIter->second.pos);
      key->SetRotation(pIter->second.rot);
    }

    this->trajectories.insert(this->trajectories.begin() + idx, anim);

    trajSdf = trajSdf->GetNextElement("trajectory");
  }
  double scriptTime = 0.0;
  for (unsigned int i = 0; i < this->trajInfo.size(); i++)
  {
    this->trajInfo[i].startTime = scriptTime;
    scriptTime += this->trajInfo[i].duration;
    this->trajInfo[i].endTime = scriptTime;
  }
  this->scriptLength = scriptTime;
}

//////////////////////////////////////////////////
void Actor::LoadAnimation(sdf::ElementPtr _sdf)
{
  std::string animName = _sdf->GetValueString("name");

  if (animName == "__default__")
  {
    this->skelAnimation[this->skinFile] =
        this->skeleton->GetAnimation(0);
    std::map<std::string, std::string> skelMap;
    for (unsigned int i = 0; i < this->skeleton->GetNumNodes(); i++)
      skelMap[this->skeleton->GetNodeByHandle(i)->GetName()] =
        this->skeleton->GetNodeByHandle(i)->GetName();
    this->skelNodesMap[this->skinFile] = skelMap;
    this->interpolateX[this->skinFile] = false;
  }
  else
  {
    std::string animFile = _sdf->GetValueString("filename");
    std::string extension = animFile.substr(animFile.rfind(".") + 1,
        animFile.size());
    double scale = _sdf->GetValueDouble("scale");
    Skeleton *skel = NULL;

    if (extension == "bvh")
    {
      BVHLoader loader;
      skel = loader.Load(animFile, scale);
    }
    else
      if (extension == "dae")
      {
        MeshManager::Instance()->Load(animFile);
        const Mesh *animMesh = NULL;
        if (MeshManager::Instance()->HasMesh(animFile))
          animMesh = MeshManager::Instance()->GetMesh(animFile);
        if (animMesh && animMesh->HasSkeleton())
        {
          skel = animMesh->GetSkeleton();
          skel->Scale(scale);
        }
      }

    if (!skel || skel->GetNumAnimations() == 0)
      gzerr << "Failed to load animation.";
    else
    {
      bool compatible = true;
      std::map<std::string, std::string> skelMap;
      if (this->skeleton->GetNumNodes() != skel->GetNumNodes())
        compatible = false;
      else
        for (unsigned int i = 0; i < this->skeleton->GetNumNodes(); i++)
        {
          SkeletonNode *skinNode = this->skeleton->GetNodeByHandle(i);
          SkeletonNode *animNode = skel->GetNodeByHandle(i);
          if (animNode->GetChildCount() != skinNode->GetChildCount())
          {
            compatible = false;
            break;
          }
          else
            skelMap[skinNode->GetName()] = animNode->GetName();
        }

      if (!compatible)
      {
        gzerr << "Skin and animation " << animName <<
              " skeletons are not compatible.\n";
      }
      else
      {
        this->skelAnimation[animName] =
            skel->GetAnimation(0);
        this->interpolateX[animName] = _sdf->GetValueBool("interpolate_x");
        this->skelNodesMap[animName] = skelMap;
      }
    }
  }
}

//////////////////////////////////////////////////
void Actor::Init()
{
  this->prevFrameTime = this->world->GetSimTime();
  if (this->autoStart)
    this->Play();
  this->mainLink = this->GetChildLink(this->GetName() + "_origin");
}

//////////////////////////////////////////////////
void Actor::Play()
{
  this->active = true;
  this->playStartTime = this->world->GetSimTime();
  this->lastScriptTime = std::numeric_limits<double>::max();
}

//////////////////////////////////////////////////
void Actor::Stop()
{
  this->active = false;
}

//////////////////////////////////////////////////
bool Actor::IsActive()
{
  return this->active;
}

///////////////////////////////////////////////////
void Actor::Update()
{
  if (!this->active)
    return;

  common::Time currentTime = this->world->GetSimTime();

  /// do not refresh animation more faster the 30 Hz sim time
  if ((currentTime - this->prevFrameTime).Double() < (1.0 / 30.0))
    return;

  double scriptTime = currentTime.Double() - this->startDelay -
            this->playStartTime.Double();

  /// waiting for delayed start
  if (scriptTime < 0)
    return;

  if (scriptTime >= this->scriptLength)
  {
    if (!this->loop)
      return;
    else
    {
      scriptTime = scriptTime - this->scriptLength;
      this->playStartTime = currentTime - scriptTime;
    }
  }

  /// at this point we are certain that a new frame will be animated
  this->prevFrameTime = currentTime;

  TrajectoryInfo tinfo;

  unsigned int tid = 0;

  for (unsigned int i = 0; i < this->trajInfo.size(); i++)
    if (this->trajInfo[i].startTime <= scriptTime &&
          this->trajInfo[i].endTime >= scriptTime)
    {
      tinfo = this->trajInfo[i];
      tid = i;
      break;
    }

  scriptTime = scriptTime - tinfo.startTime;

  SkeletonAnimation *skelAnim = this->skelAnimation[tinfo.type];
  std::map<std::string, std::string> skelMap = this->skelNodesMap[tinfo.type];

  common::PoseKeyFrame posFrame(0.0);
  this->trajectories[tid]->SetTime(scriptTime);
  this->trajectories[tid]->GetInterpolatedKeyFrame(posFrame);

  msgs::PoseAnimation msg;
  msg.set_model_name(this->visualName);

  std::map<std::string, math::Matrix4> frame;
  if (!this->interpolateX[tinfo.type])
    frame = skelAnim->GetPoseAt(scriptTime);
  else
  {
    common::PoseKeyFrame *frame0 = dynamic_cast<common::PoseKeyFrame*>
        (this->trajectories[tid]->GetKeyFrame(0));
    math::Vector3 framePos = posFrame.GetTranslation() -
        frame0->GetTranslation();
    frame = skelAnim->GetPoseAtX(framePos.GetLength(),
              skelMap[this->skeleton->GetRootNode()->GetName()]);
  }

  for (unsigned int i = 0; i < this->skeleton->GetNumNodes(); i++)
  {
    SkeletonNode *bone = this->skeleton->GetNodeByHandle(i);
    SkeletonNode *parentBone = bone->GetParent();
    math::Matrix4 transform(math::Matrix4::IDENTITY);
    if (frame.find(skelMap[bone->GetName()]) != frame.end())
      transform = frame[skelMap[bone->GetName()]];
    else
      transform = bone->GetTransform();

    LinkPtr currentLink = this->GetChildLink(bone->GetName());
    if (parentBone)
    {
      math::Pose bonePose;
      bonePose.pos = transform.GetTranslation();
      bonePose.rot = transform.GetRotation();
      if (!bonePose.IsFinite())
      {
        std::cerr << "ACTOR: " << currentTime << " " << bone->GetName()
                  << " " << bonePose << "\n";
        bonePose.Correct();
      }

      msgs::Pose *msg_pose = msg.add_pose();
      msg_pose->set_name(bone->GetName());
      msg_pose->mutable_position()->CopyFrom(msgs::Convert(bonePose.pos));
      msg_pose->mutable_orientation()->CopyFrom(msgs::Convert(bonePose.rot));

      LinkPtr parentLink = this->GetChildLink(
                              skelMap[parentBone->GetName()]);
      math::Pose parentPose = parentLink->GetWorldPose();
      math::Matrix4 parentTrans(math::Matrix4::IDENTITY);
      parentTrans = parentPose.rot.GetAsMatrix4();
      parentTrans.SetTranslate(parentPose.pos);
      transform = parentTrans * transform;
    }
    else
    {
      math::Pose modelPose;

      modelPose.pos = transform.GetTranslation();
      math::Vector3 yPos(0.0, modelPose.pos.y, 0.0);
      math::Vector3 zPos(0.0, 0.0, modelPose.pos.z);

      modelPose.pos = posFrame.GetTranslation() +
                        posFrame.GetRotation().RotateVector(yPos);
      modelPose.rot = posFrame.GetRotation();

      this->mainLink->SetWorldPose(modelPose);

      math::Matrix4 modelTrans(modelPose.rot.GetAsMatrix4());
      modelTrans.SetTranslate(modelPose.pos + zPos);
      transform.SetTranslate(math::Vector3(0, 0, 0));
      transform = modelTrans * transform;

      this->lastScriptTime = scriptTime;
    }
    currentLink->SetWorldPose(transform.GetAsPose());
  }

  msgs::Time *stamp = msg.add_time();
  stamp->CopyFrom(msgs::Convert(currentTime));

  if (this->bonePosePub && this->bonePosePub->HasConnections())
    this->bonePosePub->Publish(msg);
}

//////////////////////////////////////////////////
void Actor::Fini()
{
  Model::Fini();
}

//////////////////////////////////////////////////
void Actor::UpdateParameters(sdf::ElementPtr /*_sdf*/)
{
//  Model::UpdateParameters(_sdf);
}

//////////////////////////////////////////////////
const sdf::ElementPtr Actor::GetSDF()
{
  return Model::GetSDF();
}

//////////////////////////////////////////////////
void Actor::AddSphereInertia(sdf::ElementPtr linkSdf, math::Pose pose,
            double mass, double radius)
{
  double ixx = 2.0 * mass * radius * radius / 5.0;
  sdf::ElementPtr inertialSdf = linkSdf->GetOrCreateElement("inertial");
  sdf::ElementPtr inertialPoseSdf = inertialSdf->GetOrCreateElement("origin");
  inertialPoseSdf->GetAttribute("pose")->Set(pose);
  inertialSdf->GetAttribute("mass")->Set(mass);
  sdf::ElementPtr tensorSdf = inertialSdf->GetOrCreateElement("inertia");
  tensorSdf->GetAttribute("ixx")->Set(ixx);
  tensorSdf->GetAttribute("ixy")->Set(0.00);
  tensorSdf->GetAttribute("ixz")->Set(0.00);
  tensorSdf->GetAttribute("iyy")->Set(ixx);
  tensorSdf->GetAttribute("iyz")->Set(0.00);
  tensorSdf->GetAttribute("izz")->Set(ixx);
}

//////////////////////////////////////////////////
void Actor::AddSphereCollision(sdf::ElementPtr linkSdf, std::string name,
            math::Pose pose, double radius)
{
  sdf::ElementPtr collisionSdf = linkSdf->GetOrCreateElement("collision");
  collisionSdf->GetAttribute("name")->Set(name);
  sdf::ElementPtr collPoseSdf = collisionSdf->GetOrCreateElement("origin");
  collPoseSdf->GetAttribute("pose")->Set(pose);
  sdf::ElementPtr geomColSdf = collisionSdf->GetOrCreateElement("geometry");
  sdf::ElementPtr sphereColSdf = geomColSdf->GetOrCreateElement("sphere");
  sphereColSdf->GetAttribute("radius")->Set(radius);
}

//////////////////////////////////////////////////
void Actor::AddSphereVisual(sdf::ElementPtr linkSdf, std::string name,
            math::Pose pose, double radius, std::string material, Color ambient)
{
  sdf::ElementPtr visualSdf = linkSdf->GetOrCreateElement("visual");
  visualSdf->GetAttribute("name")->Set(name);
  sdf::ElementPtr visualPoseSdf = visualSdf->GetOrCreateElement("origin");
  visualPoseSdf->GetAttribute("pose")->Set(pose);
  sdf::ElementPtr geomVisSdf = visualSdf->GetOrCreateElement("geometry");
  sdf::ElementPtr sphereVisSdf = geomVisSdf->GetOrCreateElement("sphere");
  sphereVisSdf->GetAttribute("radius")->Set(radius);
  sdf::ElementPtr matSdf = visualSdf->GetOrCreateElement("material");
  matSdf->GetAttribute("script")->Set(material);
  sdf::ElementPtr colorSdf = matSdf->GetOrCreateElement("ambient");
  colorSdf->GetAttribute("rgba")->Set(ambient);
}

//////////////////////////////////////////////////
void Actor::AddBoxVisual(sdf::ElementPtr linkSdf, std::string name,
    math::Pose pose, math::Vector3 size, std::string material, Color ambient)
{
  sdf::ElementPtr visualSdf = linkSdf->AddElement("visual");
  visualSdf->GetAttribute("name")->Set(name);
  sdf::ElementPtr visualPoseSdf = visualSdf->GetOrCreateElement("origin");
  visualPoseSdf->GetAttribute("pose")->Set(pose);
  sdf::ElementPtr geomVisSdf = visualSdf->GetOrCreateElement("geometry");
  sdf::ElementPtr boxSdf = geomVisSdf->GetOrCreateElement("box");
  boxSdf->GetAttribute("size")->Set(size);
  sdf::ElementPtr matSdf = visualSdf->GetOrCreateElement("material");
  matSdf->GetAttribute("script")->Set(material);
  sdf::ElementPtr colorSdf = matSdf->GetOrCreateElement("ambient");
  colorSdf->GetAttribute("rgba")->Set(ambient);
}

//////////////////////////////////////////////////
void Actor::AddActorVisual(sdf::ElementPtr linkSdf, std::string name,
    math::Pose pose)
{
  sdf::ElementPtr visualSdf = linkSdf->AddElement("visual");
  visualSdf->GetAttribute("name")->Set(name);
  sdf::ElementPtr visualPoseSdf = visualSdf->GetOrCreateElement("origin");
  visualPoseSdf->GetAttribute("pose")->Set(pose);
  sdf::ElementPtr geomVisSdf = visualSdf->GetOrCreateElement("geometry");
  sdf::ElementPtr meshSdf = geomVisSdf->GetOrCreateElement("mesh");
  meshSdf->GetAttribute("filename")->Set(this->skinFile);
  meshSdf->GetAttribute("scale")->Set(math::Vector3(this->skinScale,
      this->skinScale, this->skinScale));

  /// use a material with shading for now
  sdf::ElementPtr matSdf = visualSdf->GetOrCreateElement("material");
  matSdf->GetAttribute("script")->Set("Gazebo/Blue");
  sdf::ElementPtr colorSdf = matSdf->GetOrCreateElement("ambient");
  colorSdf->GetAttribute("rgba")->Set(Color::Blue);
}

ext: cc

max_stars_repo_name: nherment/gazebo

max_issues_repo_name: nherment/gazebo

max_forks_repo_name: nherment/gazebo


text:
#include <nano/node/bootstrap/bootstrap.hpp>
#include <nano/node/bootstrap/bootstrap_attempt.hpp>
#include <nano/node/bootstrap/bootstrap_connections.hpp>
#include <nano/node/common.hpp>
#include <nano/node/node.hpp>
#include <nano/node/transport/tcp.hpp>

#include <boost/format.hpp>

constexpr double nano::bootstrap_limits::bootstrap_connection_scale_target_blocks;
constexpr double nano::bootstrap_limits::bootstrap_minimum_blocks_per_sec;
constexpr double nano::bootstrap_limits::bootstrap_minimum_termination_time_sec;
constexpr unsigned nano::bootstrap_limits::bootstrap_max_new_connections;
constexpr unsigned nano::bootstrap_limits::requeued_pulls_processed_blocks_factor;

nano::bootstrap_client::bootstrap_client (std::shared_ptr<nano::node> node_a, std::shared_ptr<nano::bootstrap_connections> connections_a, std::shared_ptr<nano::transport::channel_tcp> channel_a, std::shared_ptr<nano::socket> socket_a) :
node (node_a),
connections (connections_a),
channel (channel_a),
socket (socket_a),
receive_buffer (std::make_shared<std::vector<uint8_t>> ()),
start_time_m (std::chrono::steady_clock::now ())
{
	++connections->connections_count;
	receive_buffer->resize (256);
}

nano::bootstrap_client::~bootstrap_client ()
{
	--connections->connections_count;
}

double nano::bootstrap_client::sample_block_rate ()
{
	auto elapsed = std::max (elapsed_seconds (), nano::bootstrap_limits::bootstrap_minimum_elapsed_seconds_blockrate);
	block_rate = static_cast<double> (block_count.load ()) / elapsed;
	return block_rate;
}

void nano::bootstrap_client::set_start_time (std::chrono::steady_clock::time_point start_time_a)
{
	nano::lock_guard<std::mutex> guard (start_time_mutex);
	start_time_m = start_time_a;
}

double nano::bootstrap_client::elapsed_seconds () const
{
	nano::lock_guard<std::mutex> guard (start_time_mutex);
	return std::chrono::duration_cast<std::chrono::duration<double>> (std::chrono::steady_clock::now () - start_time_m).count ();
}

void nano::bootstrap_client::stop (bool force)
{
	pending_stop = true;
	if (force)
	{
		hard_stop = true;
	}
}

nano::bootstrap_connections::bootstrap_connections (nano::node & node_a) :
node (node_a)
{
}

std::shared_ptr<nano::bootstrap_client> nano::bootstrap_connections::connection (std::shared_ptr<nano::bootstrap_attempt> attempt_a, bool use_front_connection)
{
	nano::unique_lock<std::mutex> lock (mutex);
	condition.wait (lock, [& stopped = stopped, &idle = idle, &new_connections_empty = new_connections_empty] { return stopped || !idle.empty () || new_connections_empty; });
	std::shared_ptr<nano::bootstrap_client> result;
	if (!stopped && !idle.empty ())
	{
		if (!use_front_connection)
		{
			result = idle.back ();
			idle.pop_back ();
		}
		else
		{
			result = idle.front ();
			idle.pop_front ();
		}
	}
	if (result == nullptr && connections_count == 0 && new_connections_empty && attempt_a != nullptr)
	{
		node.logger.try_log (boost::str (boost::format ("Bootstrap attempt stopped because there are no peers")));
		lock.unlock ();
		attempt_a->stop ();
	}
	return result;
}

void nano::bootstrap_connections::pool_connection (std::shared_ptr<nano::bootstrap_client> client_a, bool new_client, bool push_front)
{
	nano::unique_lock<std::mutex> lock (mutex);
	if (!stopped && !client_a->pending_stop && !node.network.excluded_peers.check (client_a->channel->get_tcp_endpoint ()))
	{
		// Idle bootstrap client socket
		if (auto socket_l = client_a->channel->socket.lock ())
		{
			socket_l->start_timer (node.network_params.node.idle_timeout);
			// Push into idle deque
			if (!push_front)
			{
				idle.push_back (client_a);
			}
			else
			{
				idle.push_front (client_a);
			}
			if (new_client)
			{
				clients.push_back (client_a);
			}
		}
	}
	else
	{
		if (auto socket_l = client_a->channel->socket.lock ())
		{
			socket_l->close ();
		}
	}
	lock.unlock ();
	condition.notify_all ();
}

void nano::bootstrap_connections::add_connection (nano::endpoint const & endpoint_a)
{
	connect_client (nano::tcp_endpoint (endpoint_a.address (), endpoint_a.port ()), true);
}

std::shared_ptr<nano::bootstrap_client> nano::bootstrap_connections::find_connection (nano::tcp_endpoint const & endpoint_a)
{
	nano::lock_guard<std::mutex> lock (mutex);
	std::shared_ptr<nano::bootstrap_client> result;
	for (auto i (idle.begin ()), end (idle.end ()); i != end && !stopped; ++i)
	{
		if ((*i)->channel->get_tcp_endpoint () == endpoint_a)
		{
			result = *i;
			idle.erase (i);
			break;
		}
	}
	return result;
}

void nano::bootstrap_connections::connect_client (nano::tcp_endpoint const & endpoint_a, bool push_front)
{
	++connections_count;
	auto socket (std::make_shared<nano::socket> (node.shared ()));
	auto this_l (shared_from_this ());
	socket->async_connect (endpoint_a,
	[this_l, socket, endpoint_a, push_front](boost::system::error_code const & ec) {
		if (!ec)
		{
			if (this_l->node.config.logging.bulk_pull_logging ())
			{
				this_l->node.logger.try_log (boost::str (boost::format ("Connection established to %1%") % endpoint_a));
			}
			auto client (std::make_shared<nano::bootstrap_client> (this_l->node.shared (), this_l, std::make_shared<nano::transport::channel_tcp> (*this_l->node.shared (), socket), socket));
			this_l->pool_connection (client, true, push_front);
		}
		else
		{
			if (this_l->node.config.logging.network_logging ())
			{
				switch (ec.value ())
				{
					default:
						this_l->node.logger.try_log (boost::str (boost::format ("Error initiating bootstrap connection to %1%: %2%") % endpoint_a % ec.message ()));
						break;
					case boost::system::errc::connection_refused:
					case boost::system::errc::operation_canceled:
					case boost::system::errc::timed_out:
					case 995: //Windows The I/O operation has been aborted because of either a thread exit or an application request
					case 10061: //Windows No connection could be made because the target machine actively refused it
						break;
				}
			}
		}
		--this_l->connections_count;
	});
}

unsigned nano::bootstrap_connections::target_connections (size_t pulls_remaining, size_t attempts_count)
{
	unsigned attempts_factor = node.config.bootstrap_connections * attempts_count;
	if (attempts_factor >= node.config.bootstrap_connections_max)
	{
		return std::max (1U, node.config.bootstrap_connections_max);
	}

	// Only scale up to bootstrap_connections_max for large pulls.
	double step_scale = std::min (1.0, std::max (0.0, (double)pulls_remaining / nano::bootstrap_limits::bootstrap_connection_scale_target_blocks));
	double target = (double)attempts_factor + (double)(node.config.bootstrap_connections_max - attempts_factor) * step_scale;
	return std::max (1U, (unsigned)(target + 0.5f));
}

struct block_rate_cmp
{
	bool operator() (const std::shared_ptr<nano::bootstrap_client> & lhs, const std::shared_ptr<nano::bootstrap_client> & rhs) const
	{
		return lhs->block_rate > rhs->block_rate;
	}
};

void nano::bootstrap_connections::populate_connections (bool repeat)
{
	double rate_sum = 0.0;
	size_t num_pulls = 0;
	size_t attempts_count = node.bootstrap_initiator.attempts.size ();
	std::priority_queue<std::shared_ptr<nano::bootstrap_client>, std::vector<std::shared_ptr<nano::bootstrap_client>>, block_rate_cmp> sorted_connections;
	std::unordered_set<nano::tcp_endpoint> endpoints;
	{
		nano::unique_lock<std::mutex> lock (mutex);
		num_pulls = pulls.size ();
		std::deque<std::weak_ptr<nano::bootstrap_client>> new_clients;
		for (auto & c : clients)
		{
			if (auto client = c.lock ())
			{
				if (auto socket_l = client->channel->socket.lock ())
				{
					new_clients.push_back (client);
					endpoints.insert (socket_l->remote_endpoint ());
					double elapsed_sec = client->elapsed_seconds ();
					auto blocks_per_sec = client->sample_block_rate ();
					rate_sum += blocks_per_sec;
					if (client->elapsed_seconds () > nano::bootstrap_limits::bootstrap_connection_warmup_time_sec && client->block_count > 0)
					{
						sorted_connections.push (client);
					}
					// Force-stop the slowest peers, since they can take the whole bootstrap hostage by dribbling out blocks on the last remaining pull.
					// This is ~1.5kilobits/sec.
					if (elapsed_sec > nano::bootstrap_limits::bootstrap_minimum_termination_time_sec && blocks_per_sec < nano::bootstrap_limits::bootstrap_minimum_blocks_per_sec)
					{
						if (node.config.logging.bulk_pull_logging ())
						{
							node.logger.try_log (boost::str (boost::format ("Stopping slow peer %1% (elapsed sec %2%s > %3%s and %4% blocks per second < %5%)") % client->channel->to_string () % elapsed_sec % nano::bootstrap_limits::bootstrap_minimum_termination_time_sec % blocks_per_sec % nano::bootstrap_limits::bootstrap_minimum_blocks_per_sec));
						}

						client->stop (true);
						new_clients.pop_back ();
					}
				}
			}
		}
		// Cleanup expired clients
		clients.swap (new_clients);
	}

	auto target = target_connections (num_pulls, attempts_count);

	// We only want to drop slow peers when more than 2/3 are active. 2/3 because 1/2 is too aggressive, and 100% rarely happens.
	// Probably needs more tuning.
	if (sorted_connections.size () >= (target * 2) / 3 && target >= 4)
	{
		// 4 -> 1, 8 -> 2, 16 -> 4, arbitrary, but seems to work well.
		auto drop = (int)roundf (sqrtf ((float)target - 2.0f));

		if (node.config.logging.bulk_pull_logging ())
		{
			node.logger.try_log (boost::str (boost::format ("Dropping %1% bulk pull peers, target connections %2%") % drop % target));
		}

		for (int i = 0; i < drop; i++)
		{
			auto client = sorted_connections.top ();

			if (node.config.logging.bulk_pull_logging ())
			{
				node.logger.try_log (boost::str (boost::format ("Dropping peer with block rate %1%, block count %2% (%3%) ") % client->block_rate % client->block_count % client->channel->to_string ()));
			}

			client->stop (false);
			sorted_connections.pop ();
		}
	}

	if (node.config.logging.bulk_pull_logging ())
	{
		node.logger.try_log (boost::str (boost::format ("Bulk pull connections: %1%, rate: %2% blocks/sec, bootstrap attempts %3%, remaining pulls: %4%") % connections_count.load () % (int)rate_sum % attempts_count % num_pulls));
	}

	if (connections_count < target && (attempts_count != 0 || new_connections_empty) && !stopped)
	{
		auto delta = std::min ((target - connections_count) * 2, nano::bootstrap_limits::bootstrap_max_new_connections);
		// TODO - tune this better
		// Not many peers respond, need to try to make more connections than we need.
		for (auto i = 0u; i < delta; i++)
		{
			auto endpoint (node.network.bootstrap_peer (true));
			if (endpoint != nano::tcp_endpoint (boost::asio::ip::address_v6::any (), 0) && (node.flags.allow_bootstrap_peers_duplicates || endpoints.find (endpoint) == endpoints.end ()) && !node.network.excluded_peers.check (endpoint))
			{
				connect_client (endpoint);
				endpoints.insert (endpoint);
				nano::lock_guard<std::mutex> lock (mutex);
				new_connections_empty = false;
			}
			else if (connections_count == 0)
			{
				{
					nano::lock_guard<std::mutex> lock (mutex);
					new_connections_empty = true;
				}
				condition.notify_all ();
			}
		}
	}
	if (!stopped && repeat)
	{
		std::weak_ptr<nano::bootstrap_connections> this_w (shared_from_this ());
		node.alarm.add (std::chrono::steady_clock::now () + std::chrono::seconds (1), [this_w]() {
			if (auto this_l = this_w.lock ())
			{
				this_l->populate_connections ();
			}
		});
	}
}

void nano::bootstrap_connections::start_populate_connections ()
{
	if (!populate_connections_started.exchange (true))
	{
		populate_connections ();
	}
}

void nano::bootstrap_connections::add_pull (nano::pull_info const & pull_a)
{
	nano::pull_info pull (pull_a);
	node.bootstrap_initiator.cache.update_pull (pull);
	{
		nano::lock_guard<std::mutex> lock (mutex);
		pulls.push_back (pull);
	}
	condition.notify_all ();
}

void nano::bootstrap_connections::request_pull (nano::unique_lock<std::mutex> & lock_a)
{
	lock_a.unlock ();
	auto connection_l (connection ());
	lock_a.lock ();
	if (connection_l != nullptr && !pulls.empty ())
	{
		std::shared_ptr<nano::bootstrap_attempt> attempt_l;
		nano::pull_info pull;
		// Search pulls with existing attempts
		while (attempt_l == nullptr && !pulls.empty ())
		{
			pull = pulls.front ();
			pulls.pop_front ();
			attempt_l = node.bootstrap_initiator.attempts.find (pull.bootstrap_id);
			// Check if lazy pull is obsolete (head was processed or head is 0 for destinations requests)
			if (attempt_l != nullptr && attempt_l->mode == nano::bootstrap_mode::lazy && !pull.head.is_zero () && attempt_l->lazy_processed_or_exists (pull.head))
			{
				attempt_l->pull_finished ();
				attempt_l = nullptr;
			}
		}
		if (attempt_l != nullptr)
		{
			if (attempt_l->mode == nano::bootstrap_mode::legacy)
			{
				attempt_l->add_recent_pull (pull.head);
			}
			// The bulk_pull_client destructor attempt to requeue_pull which can cause a deadlock if this is the last reference
			// Dispatch request in an external thread in case it needs to be destroyed
			node.background ([connection_l, attempt_l, pull]() {
				auto client (std::make_shared<nano::bulk_pull_client> (connection_l, attempt_l, pull));
				client->request ();
			});
		}
	}
	else if (connection_l != nullptr)
	{
		// Reuse connection if pulls deque become empty
		lock_a.unlock ();
		pool_connection (connection_l);
		lock_a.lock ();
	}
}

void nano::bootstrap_connections::requeue_pull (nano::pull_info const & pull_a, bool network_error)
{
	auto pull (pull_a);
	if (!network_error)
	{
		++pull.attempts;
	}
	auto attempt_l (node.bootstrap_initiator.attempts.find (pull.bootstrap_id));
	if (attempt_l != nullptr)
	{
		++attempt_l->requeued_pulls;
		if (attempt_l->mode == nano::bootstrap_mode::legacy)
		{
			attempt_l->restart_condition ();
		}
		else if (attempt_l->mode == nano::bootstrap_mode::lazy)
		{
			pull.count = attempt_l->lazy_batch_size ();
		}
		if (attempt_l->mode == nano::bootstrap_mode::legacy && (pull.attempts < pull.retry_limit + (pull.processed / nano::bootstrap_limits::requeued_pulls_processed_blocks_factor)))
		{
			{
				nano::lock_guard<std::mutex> lock (mutex);
				pulls.push_front (pull);
			}
			attempt_l->pull_started ();
			condition.notify_all ();
		}
		else if (attempt_l->mode == nano::bootstrap_mode::lazy && (pull.retry_limit == std::numeric_limits<unsigned>::max () || pull.attempts <= pull.retry_limit + (pull.processed / node.network_params.bootstrap.lazy_max_pull_blocks)))
		{
			debug_assert (pull.account_or_head == pull.head);
			if (!attempt_l->lazy_processed_or_exists (pull.account_or_head))
			{
				{
					nano::lock_guard<std::mutex> lock (mutex);
					pulls.push_back (pull);
				}
				attempt_l->pull_started ();
				condition.notify_all ();
			}
		}
		else
		{
			if (node.config.logging.bulk_pull_logging ())
			{
				node.logger.try_log (boost::str (boost::format ("Failed to pull account %1% down to %2% after %3% attempts and %4% blocks processed") % pull.account_or_head.to_account () % pull.end.to_string () % pull.attempts % pull.processed));
			}
			node.stats.inc (nano::stat::type::bootstrap, nano::stat::detail::bulk_pull_failed_account, nano::stat::dir::in);

			if (attempt_l->mode == nano::bootstrap_mode::lazy && pull.processed > 0)
			{
				attempt_l->lazy_add (pull);
			}
			else if (attempt_l->mode == nano::bootstrap_mode::legacy)
			{
				node.bootstrap_initiator.cache.add (pull);
			}
		}
	}
}

void nano::bootstrap_connections::clear_pulls (uint64_t bootstrap_id_a)
{
	{
		nano::lock_guard<std::mutex> lock (mutex);
		auto i (pulls.begin ());
		while (i != pulls.end ())
		{
			if (i->bootstrap_id == bootstrap_id_a)
			{
				i = pulls.erase (i);
			}
			else
			{
				++i;
			}
		}
	}
	condition.notify_all ();
}

void nano::bootstrap_connections::run ()
{
	start_populate_connections ();
	nano::unique_lock<std::mutex> lock (mutex);
	while (!stopped)
	{
		if (!pulls.empty ())
		{
			request_pull (lock);
		}
		else
		{
			condition.wait (lock);
		}
	}
	stopped = true;
	lock.unlock ();
	condition.notify_all ();
}

void nano::bootstrap_connections::stop ()
{
	nano::unique_lock<std::mutex> lock (mutex);
	stopped = true;
	lock.unlock ();
	condition.notify_all ();
	lock.lock ();
	for (auto i : clients)
	{
		if (auto client = i.lock ())
		{
			client->socket->close ();
		}
	}
	clients.clear ();
	idle.clear ();
}

max_stars_repo_name: koczadly/nano-node


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://kylelutz.github.com/compute for more information.
//---------------------------------------------------------------------------//

#include <iostream>
#include <iterator>

#include <boost/compute/algorithm/max_element.hpp>
#include <boost/compute/container/vector.hpp>
#include <boost/compute/functional/geometry.hpp>
#include <boost/compute/iterator/transform_iterator.hpp>
#include <boost/compute/types/fundamental.hpp>

namespace compute = boost::compute;

// this example shows how to use the max_element() algorithm along with
// a transform_iterator and the length() function to find the longest
// 4-component vector in an array of vectors
int main()
{
    using compute::float4_;

    // vectors data
    float data[] = { 1.0f, 2.0f, 3.0f, 0.0f,
                     4.0f, 5.0f, 6.0f, 0.0f,
                     7.0f, 8.0f, 9.0f, 0.0f,
                     0.0f, 0.0f, 0.0f, 0.0f };

    // create device vector with the vector data
    compute::vector<float4_> vector(
        reinterpret_cast<float4_ *>(data),
        reinterpret_cast<float4_ *>(data) + 4
    );

    // find the longest vector
    compute::vector<float4_>::const_iterator iter =
        compute::max_element(
            compute::make_transform_iterator(
                vector.begin(), compute::length<float4_>()
            ),
            compute::make_transform_iterator(
                vector.end(), compute::length<float4_>()
            )
        ).base();

    // print the index of the longest vector
    std::cout << "longest vector index: "
              << std::distance(vector.begin(), iter)
              << std::endl;

    return 0;
}

max_stars_repo_name: skozilla/compute

max_issues_repo_name: junmuz/compute

max_forks_repo_name: junmuz/compute


text:
/*=============================================================================
    Copyright (c) 2007 Tobias Schwinger

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

#ifndef BOOST_FUSION_REPETITIVE_VIEW_ITERATOR_HPP_INCLUDED
#define BOOST_FUSION_REPETITIVE_VIEW_ITERATOR_HPP_INCLUDED

#include <boost/fusion/adapted/mpl/mpl_iterator.hpp>
#include <boost/fusion/iterator/mpl/convert_iterator.hpp>
#include <boost/fusion/sequence/intrinsic/begin.hpp>
#include <boost/fusion/sequence/intrinsic/end.hpp>
#include <boost/fusion/support/category_of.hpp>
#include <boost/fusion/support/config.hpp>
#include <boost/fusion/support/iterator_base.hpp>
#include <boost/fusion/view/repetitive_view/detail/deref_impl.hpp>
#include <boost/fusion/view/repetitive_view/detail/next_impl.hpp>
#include <boost/fusion/view/repetitive_view/detail/value_of_impl.hpp>

namespace boost {
namespace fusion {
struct repetitive_view_iterator_tag;

template <typename Sequence,
          typename Pos = typename result_of::begin<Sequence>::type>
struct repetitive_view_iterator
    : iterator_base<repetitive_view_iterator<Sequence, Pos>> {
  typedef repetitive_view_iterator_tag fusion_tag;

  typedef Sequence sequence_type;
  typedef typename convert_iterator<Pos>::type pos_type;
  typedef
      typename convert_iterator<typename result_of::begin<Sequence>::type>::type
          first_type;
  typedef
      typename convert_iterator<typename result_of::end<Sequence>::type>::type
          end_type;
  typedef single_pass_traversal_tag category;

  BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED explicit repetitive_view_iterator(
      Sequence &in_seq)
      : seq(in_seq), pos(begin(in_seq)) {}

  BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
  repetitive_view_iterator(Sequence &in_seq, pos_type const &in_pos)
      : seq(in_seq), pos(in_pos) {}

  Sequence &seq;
  pos_type pos;

private:
  // silence MSVC warning C4512: assignment operator could not be generated
  repetitive_view_iterator &operator=(repetitive_view_iterator const &);
};
} // namespace fusion
} // namespace boost

#ifdef BOOST_FUSION_WORKAROUND_FOR_LWG_2408
namespace std {
template <typename Sequence, typename Pos>
struct iterator_traits<
    ::boost::fusion::repetitive_view_iterator<Sequence, Pos>> {};
} // namespace std
#endif

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#ifndef _PATHFINDING_MAP_CREATOR_GLOBALS_HEADER__
#define _PATHFINDING_MAP_CREATOR_GLOBALS_HEADER__

#include <boost/filesystem.hpp>

#include <cpp-utils/Random.hpp>

namespace map_creator {

    using namespace cpp_utils;

    /**
     * @brief contains all the global variables
     *
     */
    class Globals {
    public:
        unsigned int randomSeed;
        boost::filesystem::path outputMainDirectory;
        std::string generatedMapPyString;
        std::string generationMethod;
        boost::filesystem::path baseMapPath;
        size_t width;
        size_t height;
        std::string untraversableCellPyString;

        Random randomGenerator;
    };

}

#endif

max_stars_repo_name: Koldar/pathfinding-map-creator

max_issues_repo_name: Koldar/pathfinding-map-creator

max_forks_repo_name: Koldar/pathfinding-map-creator


text:
#include <iostream>
#include "PDBCatalog.h"
#include <qunit.h>
#include <boost/filesystem.hpp>

class Tests {

  QUnit::UnitTest qunit;

  /**
   * This test tests a simple aggregation
   */
  void test() {

    // remove the catalog if it exists from a previous run
    boost::filesystem::remove("out.sqlite");

    // create a catalog
    pdb::PDBCatalog catalog("out.sqlite");

    std::string error;

    // create the databases
    QUNIT_IS_TRUE(catalog.registerDatabase(std::make_shared<pdb::PDBCatalogDatabase>("db1"), error));
    QUNIT_IS_TRUE(catalog.registerDatabase(std::make_shared<pdb::PDBCatalogDatabase>("db2"), error));

    // store the number of registred types
    auto numBefore = catalog.numRegisteredTypes();

    // create a type
    QUNIT_IS_TRUE(catalog.registerType(std::make_shared<pdb::PDBCatalogType>(8341, "built-in", "Type1", std::vector<char>()), error))
    QUNIT_IS_TRUE(catalog.registerType(std::make_shared<pdb::PDBCatalogType>(8342, "built-in", "Type2", std::vector<char>()), error));

    // check if we added two new types
    QUNIT_IS_EQUAL(catalog.numRegisteredTypes() - numBefore, 2);

    // create the set
    QUNIT_IS_TRUE(catalog.registerSet(std::make_shared<pdb::PDBCatalogSet>("set1", "db1", "Type1"), error));
    QUNIT_IS_TRUE(catalog.registerSet(std::make_shared<pdb::PDBCatalogSet>("set2", "db1", "Type1"), error));
    QUNIT_IS_TRUE(catalog.registerSet(std::make_shared<pdb::PDBCatalogSet>("set3", "db2", "Type2"), error));

    // create the nodes
    QUNIT_IS_TRUE(catalog.registerNode(std::make_shared<pdb::PDBCatalogNode>("localhost:8080", "localhost", 8080, "master"), error));
    QUNIT_IS_TRUE(catalog.registerNode(std::make_shared<pdb::PDBCatalogNode>("localhost:8081", "localhost", 8081, "worker"), error));
    QUNIT_IS_TRUE(catalog.registerNode(std::make_shared<pdb::PDBCatalogNode>("localhost:8082", "localhost", 8082, "worker"), error));

    // check the exists functions for databases
    QUNIT_IS_TRUE(catalog.databaseExists("db1"));
    QUNIT_IS_TRUE(catalog.databaseExists("db2"));

    // check the exists functions for sets
    QUNIT_IS_TRUE(catalog.setExists("db1", "set1"));
    QUNIT_IS_TRUE(catalog.setExists("db1", "set2"));
    QUNIT_IS_TRUE(catalog.setExists("db2", "set3"));

    QUNIT_IS_FALSE(catalog.setExists("db1", "set3"));
    QUNIT_IS_FALSE(catalog.setExists("db2", "set1"));
    QUNIT_IS_FALSE(catalog.setExists("db2", "set2"));

    // check if the types exist
    QUNIT_IS_TRUE(catalog.typeExists("Type1"));
    QUNIT_IS_TRUE(catalog.typeExists("Type2"));

    // check if the node exist
    QUNIT_IS_TRUE(catalog.nodeExists("localhost:8080"));
    QUNIT_IS_TRUE(catalog.nodeExists("localhost:8081"));
    QUNIT_IS_TRUE(catalog.nodeExists("localhost:8082"));

    // check the get method for the database
    auto db = catalog.getDatabase("db1");

    QUNIT_IS_EQUAL(db->name, "db1");
    QUNIT_IS_TRUE(db->createdOn > 0)

    db = catalog.getDatabase("db2");

    QUNIT_IS_EQUAL(db->name, "db2");
    QUNIT_IS_TRUE(db->createdOn > 0)

    // check the get method for the sets
    auto set = catalog.getSet("db1", "set1");

    QUNIT_IS_EQUAL(set->name, "set1")
    QUNIT_IS_EQUAL(set->setIdentifier, "db1:set1")
    QUNIT_IS_EQUAL(set->database, "db1")
    QUNIT_IS_EQUAL(*set->type, "Type1")

    set = catalog.getSet("db1", "set2");

    QUNIT_IS_EQUAL(set->name, "set2")
    QUNIT_IS_EQUAL(set->setIdentifier, "db1:set2")
    QUNIT_IS_EQUAL(set->database, "db1")
    QUNIT_IS_EQUAL(*set->type, "Type1")

    set = catalog.getSet("db2", "set3");

    QUNIT_IS_EQUAL(set->name, "set3")
    QUNIT_IS_EQUAL(set->setIdentifier, "db2:set3")
    QUNIT_IS_EQUAL(set->database, "db2")
    QUNIT_IS_EQUAL(*set->type, "Type2")

    set = catalog.getSet("db1", "set3");
    QUNIT_IS_TRUE(set == nullptr);

    // check the nodes
    auto node = catalog.getNode("localhost:8080");

    QUNIT_IS_EQUAL(node->nodeID, "localhost:8080");
    QUNIT_IS_EQUAL(node->nodeType, "master");
    QUNIT_IS_EQUAL(node->address, "localhost");
    QUNIT_IS_EQUAL(node->port, 8080);

    node = catalog.getNode("localhost:8081");

    QUNIT_IS_EQUAL(node->nodeID, "localhost:8081");
    QUNIT_IS_EQUAL(node->nodeType, "worker");
    QUNIT_IS_EQUAL(node->address, "localhost");
    QUNIT_IS_EQUAL(node->port, 8081);

    node = catalog.getNode("localhost:8082");

    QUNIT_IS_EQUAL(node->nodeID, "localhost:8082");
    QUNIT_IS_EQUAL(node->nodeType, "worker");
    QUNIT_IS_EQUAL(node->address, "localhost");
    QUNIT_IS_EQUAL(node->port, 8082);

    auto t1 = catalog.getTypeWithoutLibrary(8341);
    auto t2 = catalog.getTypeWithoutLibrary("Type1");

    QUNIT_IS_EQUAL(t1->name, t2->name)
    QUNIT_IS_EQUAL(t1->id, t2->id)
    QUNIT_IS_EQUAL(t1->typeCategory, t2->typeCategory)

    // print out the catalog
    std::cout << catalog.listNodesInCluster() << std::endl;
    std::cout << catalog.listRegisteredDatabases() << std::endl;
    std::cout << catalog.listUserDefinedTypes() << std::endl;

    // remove the database
    catalog.removeDatabase("db1", error);

    // check the get method for the sets
    QUNIT_IS_TRUE(!catalog.setExists("db1", "set1"));
    QUNIT_IS_TRUE(!catalog.setExists("db1", "set2"));
  }

 public:

  explicit Tests(std::ostream & out, int verboseLevel = QUnit::verbose): qunit(out, verboseLevel) {}

  /**
   * Runs the tests
   * @return if the tests succeeded
   */
  int run() {

    // run tests
    test();

    // return the errors
    return qunit.errors();
  }

};

int main() {
  return Tests(std::cerr).run();
}

max_stars_repo_name: dimitrijejankov/pdb

max_issues_repo_name: dimitrijejankov/pdb

max_forks_repo_name: dimitrijejankov/pdb


text:
// Copyright (C) 2014 Vicente Botet
//
//  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/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/thread.hpp>

using namespace boost::interprocess;

struct item
{
   int i;
};

struct queue
{
   void put( const item& item )
   {
      boost::unique_lock<boost::mutex> lock(mutex);
      while ( item_in )
         cond_full.wait(lock);

      item_ = item;
      item_in = true;
      cond_empty.notify_one();
   }

   void print()
   {
      boost::unique_lock<boost::mutex> lock(mutex);
      while ( !item_in )
         cond_empty.wait(lock);

      item_in = false;
      std::cout << item_.i << std::endl;
      cond_full.notify_one();
   }

private:
   //Mutex to protect access to the queue
   boost::mutex mutex;

   //Condition to wait when the queue is empty
   boost::condition_variable  cond_empty;

   //Condition to wait when the queue is full
   boost::condition_variable  cond_full;

   bool item_in;

   //Items to fill
   item item_;
};

void *addr;

void printThread()
{
   //Erase previous shared memory and schedule erasure on exit
   struct shm_remove
   {
      shm_remove() { shared_memory_object::remove("MySharedMemory"); }
      ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
   } remover;

   //Create a shared memory object.
   shared_memory_object shm(create_only,"MySharedMemory",read_write);

   try
   {
//      //Set size
//      shm.truncate(sizeof(queue));
//
//      //Map the whole shared memory in this process
//      mapped_region region(shm,read_write);
//
//      //Get the address of the mapped region
//      void *addr = region.get_address();

      //Construct the shared structure in memory
      queue *q = new (addr) queue;

      do
      {
         q->print();
      } while ( true );
   }
//   catch(interprocess_exception &ex)
//   {
//      std::cout << ex.what() << std::endl;
//   }
   catch(boost::thread_interrupted&)
   {
      std::cout << "interrupted" << std::endl;
   }
   catch(...)
   {
      std::cout << "exception" << std::endl;
   }
}

int main()
{
   addr = new queue();
   boost::thread t(printThread);

   // give the thread time to create the shm
   boost::this_thread::sleep( boost::posix_time::milliseconds( 1000 ) );

//   //Create a shared memory object.
//   shared_memory_object shm(open_only,"MySharedMemory",read_write);

   try
   {
//      //Map the whole shared memory in this process
//      mapped_region region(shm,read_write);
//
//      //Get the address of the mapped region
//      void *addr = region.get_address();

      //Obtain a pointer to the shared structure
      queue *q = static_cast<queue*>(addr);

      item i;
      i.i = 42;
      q->put( i );

      ++i.i;
      q->put( i );

      // give the printThread time to "process" the item
      boost::this_thread::sleep( boost::posix_time::milliseconds( 1000 ) );

      t.interrupt();
      t.join();
   }
   catch(...)
   {
      std::cout << "exception" << std::endl;
      return -1;
   }
}


text:
#ifndef SHIFT_SERIALIZATION2_COMPACT_OUTPUT_ARCHIVE_HPP
#define SHIFT_SERIALIZATION2_COMPACT_OUTPUT_ARCHIVE_HPP

#include <shift/core/boost_disable_warnings.hpp>
#include <boost/endian/conversion.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <shift/core/boost_restore_warnings.hpp>
#include "shift/serialization2/compressed.hpp"

namespace shift::serialization2
{
///
template <boost::endian::order Order>
class compact_output_archive final
{
public:
  /// Constructor.
  compact_output_archive(boost::iostreams::filtering_ostream& stream)
  : _stream(stream)
  {
    _stream.exceptions(boost::iostreams::filtering_ostream::failbit |
                       boost::iostreams::filtering_ostream::eofbit);
  }

  compact_output_archive(const compact_output_archive&) = default;
  compact_output_archive(compact_output_archive&&) noexcept = default;

  /// Destructor.
  ~compact_output_archive() = default;

  compact_output_archive& operator=(const compact_output_archive&) = default;
  compact_output_archive& operator=(compact_output_archive&&) noexcept =
    default;

  ///
  compact_output_archive& operator<<(begin_write /*value*/)
  {
    // NOP.
    return *this;
  }

  ///
  compact_output_archive& operator<<(end_write /*value*/)
  {
    // NOP.
    return *this;
  }

  ///
  compact_output_archive& operator<<(begin_field /*value*/)
  {
    // NOP.
    return *this;
  }

  ///
  compact_output_archive& operator<<(end_field /*value*/)
  {
    // NOP.
    return *this;
  }

  ///
  compact_output_archive& operator<<(begin_pair /*value*/)
  {
    // NOP.
    return *this;
  }

  ///
  compact_output_archive& operator<<(end_pair /*value*/)
  {
    // NOP.
    return *this;
  }

  ///
  compact_output_archive& operator<<(begin_tuple /*value*/)
  {
    // NOP.
    return *this;
  }

  ///
  compact_output_archive& operator<<(end_tuple /*value*/)
  {
    // NOP.
    return *this;
  }

  ///
  compact_output_archive& operator<<(begin_array /*value*/)
  {
    // NOP.
    return *this;
  }

  ///
  compact_output_archive& operator<<(end_array /*value*/)
  {
    // NOP.
    return *this;
  }

  ///
  compact_output_archive& operator<<(begin_vector value)
  {
    compressed<std::uint32_t> length = static_cast<std::uint32_t>(value.length);
    BOOST_ASSERT(length == value.length);
    (*this) << length;
    return *this;
  }

  ///
  compact_output_archive& operator<<(end_vector /*value*/)
  {
    // NOP.
    return *this;
  }

  ///
  compact_output_archive& operator<<(begin_list value)
  {
    *this << begin_vector{value.length};
    return *this;
  }

  ///
  compact_output_archive& operator<<(end_list /*value*/)
  {
    *this << end_vector{};
    return *this;
  }

  ///
  compact_output_archive& operator<<(begin_set value)
  {
    *this << begin_vector{value.length};
    return *this;
  }

  ///
  compact_output_archive& operator<<(end_set /*value*/)
  {
    *this << end_vector{};
    return *this;
  }

  ///
  compact_output_archive& operator<<(begin_map value)
  {
    *this << begin_vector{value.length};
    return *this;
  }

  ///
  compact_output_archive& operator<<(end_map /*value*/)
  {
    *this << end_vector{};
    return *this;
  }

  ///
  compact_output_archive& operator<<(begin_raw_pointer value)
  {
    (*this) << value.valid;
    return *this;
  }

  ///
  compact_output_archive& operator<<(end_raw_pointer /*value*/)
  {
    // NOP.
    return *this;
  }

  ///
  compact_output_archive& operator<<(begin_shared_pointer value)
  {
    (*this) << value.key;
    return *this;
  }

  ///
  compact_output_archive& operator<<(end_shared_pointer /*value*/)
  {
    // NOP.
    return *this;
  }

  ///
  compact_output_archive& operator<<(bool value)
  {
    write(reinterpret_cast<const char*>(&value), sizeof(value));
    return *this;
  }

  ///
  compact_output_archive& operator<<(char value)
  {
    using namespace boost::endian;
    auto target_value = conditional_reverse<order::native, Order>(value);
    write(reinterpret_cast<const char*>(&target_value), sizeof(value));
    return *this;
  }

  ///
  compact_output_archive& operator<<(char16_t value)
  {
    using namespace boost::endian;
    auto target_value = conditional_reverse<order::native, Order>(value);
    write(reinterpret_cast<const char*>(&target_value), sizeof(target_value));
    return *this;
  }

  ///
  compact_output_archive& operator<<(char32_t value)
  {
    using namespace boost::endian;
    auto target_value = conditional_reverse<order::native, Order>(value);
    write(reinterpret_cast<const char*>(&target_value), sizeof(value));
    return *this;
  }

  ///
  compact_output_archive& operator<<(std::uint8_t value)
  {
    using namespace boost::endian;
    auto target_value = conditional_reverse<order::native, Order>(value);
    write(reinterpret_cast<const char*>(&target_value), sizeof(value));
    return *this;
  }

  ///
  compact_output_archive& operator<<(std::int8_t value)
  {
    using namespace boost::endian;
    auto target_value = conditional_reverse<order::native, Order>(value);
    write(reinterpret_cast<const char*>(&target_value), sizeof(value));
    return *this;
  }

  ///
  compact_output_archive& operator<<(std::uint16_t value)
  {
    using namespace boost::endian;
    auto target_value = conditional_reverse<order::native, Order>(value);
    write(reinterpret_cast<const char*>(&target_value), sizeof(value));
    return *this;
  }

  ///
  compact_output_archive& operator<<(std::int16_t value)
  {
    using namespace boost::endian;
    auto target_value = conditional_reverse<order::native, Order>(value);
    write(reinterpret_cast<const char*>(&target_value), sizeof(value));
    return *this;
  }

  ///
  compact_output_archive& operator<<(std::uint32_t value)
  {
    using namespace boost::endian;
    auto target_value = conditional_reverse<order::native, Order>(value);
    write(reinterpret_cast<const char*>(&target_value), sizeof(value));
    return *this;
  }

  ///
  compact_output_archive& operator<<(std::int32_t value)
  {
    using namespace boost::endian;
    auto target_value = conditional_reverse<order::native, Order>(value);
    write(reinterpret_cast<const char*>(&target_value), sizeof(value));
    return *this;
  }

  ///
  compact_output_archive& operator<<(std::uint64_t value)
  {
    using namespace boost::endian;
    auto target_value = conditional_reverse<order::native, Order>(value);
    write(reinterpret_cast<const char*>(&target_value), sizeof(value));
    return *this;
  }

  ///
  compact_output_archive& operator<<(std::int64_t value)
  {
    using namespace boost::endian;
    auto target_value = conditional_reverse<order::native, Order>(value);
    write(reinterpret_cast<const char*>(&target_value), sizeof(value));
    return *this;
  }

  ///
  compact_output_archive& operator<<(float value)
  {
    ieee754_to_uint<float> temp;
    temp.foat_value = value;
    *this << temp.uint_value;
    return *this;
  }

  ///
  compact_output_archive& operator<<(double value)
  {
    ieee754_to_uint<double> temp;
    temp.foat_value = value;
    *this << temp.uint_value;
    return *this;
  }

  ///
  compact_output_archive& operator<<(std::string value)
  {
    compressed<std::uint32_t> length = static_cast<uint32_t>(value.size());
    BOOST_ASSERT(length == value.size());
    *this << length;
    write(value.c_str(), length);
    return *this;
  }

public:
  /// Write data to the underlying stream.
  void write(const char* source, std::size_t size)
  {
    _stream.write(source, static_cast<std::streamsize>(size));
  }

private:
  boost::iostreams::filtering_ostream& _stream;
};

///
template <boost::endian::order Order, typename U>
compact_output_archive<Order>& operator<<(
  compact_output_archive<Order>& archive, const compressed<U>& compressed_value)
{
  auto value = static_cast<U>(compressed_value);
  do
  {
    auto digit = static_cast<std::uint8_t>(value & 0x7F);
    if (value > 0x7F)
      digit |= 0x80;
    archive << digit;
    value >>= 7;
  } while (value > 0);
  return archive;
}
}

#endif

max_stars_repo_name: cspanier/shift

max_issues_repo_name: cspanier/shift

max_forks_repo_name: cspanier/shift


text:
#pragma once

#include <sophiatx/chain/sophiatx_object_types.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <sophiatx/chain/buffer_type.hpp>

namespace sophiatx {
namespace plugins {
namespace custom_tokens {

using namespace std;
using namespace sophiatx::chain;

//
// Plugins should #define their SPACE_ID's so plugins with
// conflicting SPACE_ID assignments can be compiled into the
// same binary (by simply re-assigning some of the conflicting #defined
// SPACE_ID's in a build script).
//
// Assignment of SPACE_ID's cannot be done at run-time because
// various template automagic depends on them being known at compile
// time.
//
#ifndef SOPHIATX_CUSTOM_TOKENS_SPACE_ID
#define SOPHIATX_CUSTOM_TOKENS_SPACE_ID 122
#endif

enum token_object_types {
   custom_token_object_type = (SOPHIATX_CUSTOM_TOKENS_SPACE_ID << 8),
   custom_token_account_object_type = (SOPHIATX_CUSTOM_TOKENS_SPACE_ID << 8) + 1,
   custom_token_operation_object_type = (SOPHIATX_CUSTOM_TOKENS_SPACE_ID << 8) + 2,
   custom_token_error_object_type = (SOPHIATX_CUSTOM_TOKENS_SPACE_ID << 8) + 3
};

class custom_token_object : public object<custom_token_object_type, custom_token_object> {
public:
   template<typename Constructor, typename Allocator>
   custom_token_object(Constructor &&c, allocator<Allocator> a) {
      c(*this);
   }

   id_type id;

   asset_symbol_type token_symbol;
   account_name_type owner_name;
   uint64_t total_supply;
   uint64_t max_supply = std::numeric_limits<uint64_t>::max();
   uint64_t burned = 0;
   bool paused = false;
};

class custom_token_account_object
      : public object<custom_token_account_object_type, custom_token_account_object> {
public:
   template<typename Constructor, typename Allocator>
   custom_token_account_object(Constructor &&c, allocator<Allocator> a) {
      c(*this);
   }

   id_type id;

   account_name_type account_name;
   asset_symbol_type token_symbol;
   uint64_t amount = 0;

   uint64_t token_sequence = 0;
   uint64_t account_sequence = 0;
};

class custom_token_operation_object
      : public object<custom_token_operation_object_type, custom_token_operation_object> {
public:
   template<typename Constructor, typename Allocator>
   custom_token_operation_object(Constructor &&c, allocator<Allocator> a) : serialized_op(a.get_segment_manager()) {
      c(*this);
   }

   id_type id;

   account_name_type account;
   asset_symbol_type token_symbol;
   uint32_t block = 0;
   buffer_type serialized_op;
   transaction_id_type trx_id;
   fc::time_point_sec timestamp;

   uint64_t token_sequence = 0;
   uint64_t account_sequence = 0;
};

class custom_token_error_object
      : public object<custom_token_error_object_type, custom_token_error_object> {
public:
   template<typename Constructor, typename Allocator>
   custom_token_error_object(Constructor &&c, allocator<Allocator> a) : error(a) {
      c(*this);
   }

   id_type id;
   transaction_id_type trx_id;
   asset_symbol_type token_symbol;
   shared_string error;
   std::chrono::system_clock::time_point time = std::chrono::system_clock::now();

   uint64_t token_sequence = 0;
};

typedef custom_token_object::id_type custom_token_id_type;
typedef custom_token_account_object::id_type custom_token_account_id_type;
typedef custom_token_operation_object::id_type custom_token_transfer_id_type;
typedef custom_token_error_object::id_type custom_token_error_object_id_type;

using namespace boost::multi_index;

struct by_token_symbol;
struct by_token_and_account;
struct by_tx_id;
struct by_time;

typedef multi_index_container<
      custom_token_object,
      indexed_by<
            ordered_unique<tag<by_id>, member<custom_token_object, custom_token_id_type, &custom_token_object::id> >,
            ordered_unique<tag<by_token_symbol>, member<custom_token_object, asset_symbol_type, &custom_token_object::token_symbol> >
      >,
      allocator<custom_token_object>
> token_index;

typedef multi_index_container<
      custom_token_account_object,
      indexed_by<
            ordered_unique<tag<by_id>, member<custom_token_account_object, custom_token_account_id_type, &custom_token_account_object::id> >,
            ordered_non_unique<tag<by_account>, composite_key<custom_token_account_object,
                  member<custom_token_account_object, account_name_type, &custom_token_account_object::account_name>,
                  member<custom_token_account_object, uint64_t, &custom_token_account_object::account_sequence> >,
                  composite_key_compare<std::less<account_name_type>, std::greater<uint64_t> > >,
            ordered_non_unique<tag<by_token_symbol>, composite_key<custom_token_account_object,
                  member<custom_token_account_object, asset_symbol_type, &custom_token_account_object::token_symbol>,
                  member<custom_token_account_object, uint64_t, &custom_token_account_object::token_sequence> >,
                  composite_key_compare<std::less<asset_symbol_type>, std::greater<uint64_t> > >,
            ordered_unique<tag<by_token_and_account>, composite_key<custom_token_account_object,
                  member<custom_token_account_object, asset_symbol_type, &custom_token_account_object::token_symbol>,
                  member<custom_token_account_object, account_name_type, &custom_token_account_object::account_name> >,
                  composite_key_compare< std::less< asset_symbol_type >, std::less< account_name_type > > >
      >,
      allocator<custom_token_account_object>
> token_accounts_index;

typedef multi_index_container<
      custom_token_operation_object,
      indexed_by<
            ordered_unique<tag<by_id>, member<custom_token_operation_object, custom_token_transfer_id_type, &custom_token_operation_object::id> >,
            ordered_non_unique<tag<by_account>, composite_key<custom_token_operation_object,
                  member<custom_token_operation_object, account_name_type, &custom_token_operation_object::account>,
                  member<custom_token_operation_object, uint64_t, &custom_token_operation_object::account_sequence> >,
                  composite_key_compare<std::less<account_name_type>, std::greater<uint64_t> > >,
            ordered_non_unique<tag<by_token_symbol>, composite_key<custom_token_operation_object,
                  member<custom_token_operation_object, asset_symbol_type, &custom_token_operation_object::token_symbol>,
                  member<custom_token_operation_object, uint64_t, &custom_token_operation_object::token_sequence> >,
                  composite_key_compare<std::less<asset_symbol_type>, std::greater<uint64_t> > >
      >,
      allocator<custom_token_operation_object>
> token_operation_index;

typedef multi_index_container<
      custom_token_error_object,
      indexed_by<
            ordered_unique<tag<by_id>, member<custom_token_error_object, custom_token_error_object_id_type, &custom_token_error_object::id> >,
            ordered_unique<tag<by_tx_id>, member<custom_token_error_object, transaction_id_type, &custom_token_error_object::trx_id> >,
            ordered_non_unique<tag<by_time>, member<custom_token_error_object, std::chrono::system_clock::time_point, &custom_token_error_object::time> >,
            ordered_non_unique<tag<by_token_symbol>, composite_key<custom_token_error_object,
                  member<custom_token_error_object, asset_symbol_type, &custom_token_error_object::token_symbol>,
                  member<custom_token_error_object, uint64_t, &custom_token_error_object::token_sequence> >,
                  composite_key_compare<std::less<asset_symbol_type>, std::greater<uint64_t> > >
      >,
      allocator<custom_token_error_object>
> token_error_index;

}
}
} // sophiatx::plugins::custom_tokens

FC_REFLECT(sophiatx::plugins::custom_tokens::custom_token_object,
           (id)(token_symbol)(owner_name)(total_supply)(max_supply)(burned)(paused))
FC_REFLECT(sophiatx::plugins::custom_tokens::custom_token_account_object,
           (id)(account_name)(token_symbol)(amount)(token_sequence)(account_sequence))
FC_REFLECT(sophiatx::plugins::custom_tokens::custom_token_operation_object,
           (id)(account)(token_symbol)(serialized_op)(block)(trx_id)(timestamp)(token_sequence)(account_sequence))
FC_REFLECT(sophiatx::plugins::custom_tokens::custom_token_error_object,
           (id)(trx_id)(time)(token_symbol)(error)(token_sequence))

CHAINBASE_SET_INDEX_TYPE(sophiatx::plugins::custom_tokens::custom_token_object,
                         sophiatx::plugins::custom_tokens::token_index)
CHAINBASE_SET_INDEX_TYPE(sophiatx::plugins::custom_tokens::custom_token_account_object,
                         sophiatx::plugins::custom_tokens::token_accounts_index)
CHAINBASE_SET_INDEX_TYPE(sophiatx::plugins::custom_tokens::custom_token_operation_object,
                         sophiatx::plugins::custom_tokens::token_operation_index)
CHAINBASE_SET_INDEX_TYPE(sophiatx::plugins::custom_tokens::custom_token_error_object,
                         sophiatx::plugins::custom_tokens::token_error_index)

max_stars_repo_name: SophiaTX/SophiaTx-Blockchain

max_issues_repo_name: SophiaTX/SophiaTx-Blockchain

max_forks_repo_name: SophiaTX/SophiaTx-Blockchain


text:
#include "DirectoryMount.hpp"

#include <algorithm>
#include <iterator>
#include <fstream>

#include <boost/filesystem.hpp>

#include "Path.hpp"

using namespace coconut;
using namespace coconut::milk;
using namespace coconut::milk::fs;

using namespace std::string_literals;

namespace /* anonymous */ {

template <class T>
std::unique_ptr<T> openStream(
	const boost::filesystem::path& root,
	const Path& path,
	unsigned int flags,
	bool requireExists
	) {
	const auto effectivePath = root / path.physicalPath();

	const auto exists = boost::filesystem::exists(effectivePath);

	if (exists) {
		if (!boost::filesystem::is_regular_file(effectivePath)) {
			throw InvalidPath("Not a path to a regular file: \"" + effectivePath.string() + '"');
		}
	} else if (requireExists) {
		throw InvalidPath("File does not exist: \"" + effectivePath.string() + '"');
	}

	return std::make_unique<T>(effectivePath.c_str(), flags | std::ios::binary);
}

} // anonymous namespace

DirectoryMount::DirectoryMount(boost::filesystem::path root, bool readOnly) :
	root_(std::move(root)),
	readOnly_(readOnly)
{
	if (!boost::filesystem::is_directory(root_)) {
		throw InvalidPath("Not a path to an existing directory: \""s + root_.string() + '"');
	}
}

std::vector<std::string> DirectoryMount::list(const Path& path) const {
	const auto effectivePath = root_ / path.physicalPath();

	if (!boost::filesystem::is_directory(effectivePath)) {
		throw InvalidPath("Not a path to an existing directory: \""s + effectivePath.string() + '"');
	}
	std::vector<std::string> contents;
	std::transform(
		boost::filesystem::directory_iterator(effectivePath),
		boost::filesystem::directory_iterator(),
		std::back_inserter(contents),
		[](const auto& entry) { return entry.path().filename().string(); }
		);
	return contents;
}

IStream DirectoryMount::open(const Path& path) const {
	return openStream<std::ifstream>(root_, path, std::ios::in, true);
}

OStream DirectoryMount::append(const Path& path) const {
	return openStream<std::ofstream>(root_, path, std::ios::app, false);
}

OStream DirectoryMount::overwrite(const Path& path) const {
	return openStream<std::ofstream>(root_, path, std::ios::out, false);
}

bool DirectoryMount::exists(const Path& path) const {
	const auto effectivePath = root_ / path.physicalPath();

	return boost::filesystem::exists(effectivePath);
}

max_stars_repo_name: mikosz/coconut

max_issues_repo_name: mikosz/coconut

max_forks_repo_name: mikosz/coconut


text:
#include "TypeName.h"

#include <boost/type_index.hpp>

namespace Micron
{
	static Array<MultibyteString, 18> const basicTypesAsStrings =
	{
		"Int8",
		"Int16",
		"Int32",
		"Int64",
		"UInt8",
		"UInt16",
		"UInt32",
		"UInt64",
		"Float32",
		"Float64",
		"Float128",
		"Bool",
		"Void",
		"Byte",
		"MultibyteString",
		"MultibyteStringView",
		"UnicodeString",
		"UnicodeStringView"
	};

	static Array<MultibyteString, 10> const mathTypesAsStrings =
	{
		"Vector2f",
		"Vector3f",
		"Vector4f",
		"Vector2i",
		"Vector3i",
		"Vector4i",
		"Matrix2x2",
		"Matrix3x3",
		"Matrix4x4",
		"Quaternion"
	};

	MultibyteString TypeName::ToString(BasicType const &type) noexcept
	{
		return basicTypesAsStrings[EnumToUnsignedSizeType(type)];
	}

	MultibyteString TypeName::ToString(MathType const &type) noexcept
	{
		return mathTypesAsStrings[EnumToUnsignedSizeType(type)];
	}
}


text:
#ifndef EXPSUM_REDUCTION_CHOLESKY_CAUCHY_HPP
#define EXPSUM_REDUCTION_CHOLESKY_CAUCHY_HPP

#include <armadillo>
#include <cassert>

namespace expsum
{
//
// Rank-revealing Cholesky decomposition for a positive-definite quasi-Cauchy
// matrix.
//
// This class computes the Cholesky decomposition of ``$n \times n$``
// quasi-Cauchy matrix defined as
//
// ``` math
//  C_{ij} = \frac{a_{i}^{} b_{j}^{}}{x_{i}^{} + y_{i}^{}}.
// ```
//
template <typename T>
struct cholesky_quasi_cauchy
{
public:
    using value_type = T;
    using real_type  = typename arma::get_pod_type<T>::result;
    using size_type  = arma::uword;

    using vector_type      = arma::Col<value_type>;
    using matrix_type      = arma::Mat<value_type>;
    using real_vector_type = arma::Col<real_type>;
    //
    // Pre-compute pivot order for the Cholesky factorization of Cauchy matrix.
    //
    static size_type pivot_order(vector_type& a, vector_type& b, vector_type& x,
                                 vector_type& y, real_type delta,
                                 arma::uvec& ipiv, vector_type& g);
    //
    // Compute Cholesky factors (`X` and diagonal part of `D`).
    //
    // The arrays `a,b,x,y` must be properly reordered by calling `pivot_order`
    // beforehand, so that the diagonal part of Cholesky factors appear in
    // decesnding order.
    //
    // @a vector of length ``$n$`` defining quasi-Cauchy matrix (reordered)
    // @b vector of length ``$n$`` defining quasi-Cauchy matrix (reordered)
    // @x vector of length ``$n$`` defining quasi-Cauchy matrix (reordered)
    // @y vector of length ``$n$`` defining quasi-Cauchy matrix (reordered)
    // @L Cholesky factor (lower triangular matrix)
    // @d diagonal elements of Cholesky factor ``$D$``
    // @alpha vector of length ``$n$`` as working space
    // @beta  vector of length ``$n$`` as working space
    //
    static void factorize(const vector_type& a, const vector_type& b,
                          const vector_type& x, const vector_type& y,
                          matrix_type& L, real_vector_type& d,
                          vector_type& alpha, vector_type& beta);
    //
    // Apply permutation matrix generated by previous decomposition *in-place.*
    //
    // @X $n \times k$ matrix that the row-permutation matrix is applied.
    // @ipiv vector of index with size $n$. Permutation index obtained by
    //       `pivot_order` or `pivot_order_sym`.
    // @work working space of size $n$.
    //
    template <typename MatX>
    static void apply_row_permutation(MatX& X, const arma::uvec& ipiv,
                                      vector_type& work)
    {
        const size_type n = ipiv.size();
        assert(X.n_rows == n && work.n_elem == n);

        for (size_type j = 0; j < X.n_cols; ++j)
        {
            for (size_type i = 0; i < n; ++i)
            {
                work(ipiv(i)) = X(i, j);
            }
            X.col(j) = work;
        }
    }
    //
    // Reconstruct matrix from Cholesky factor
    //
    // @X Cholesky factor computed by `cholesky_quasi_cauchy::run`.
    // @d Cholesky factor computed by `cholesky_quasi_cauchy::run`.
    //
    static matrix_type reconstruct(const matrix_type& X, const arma::uvec& ipiv,
                                   const real_vector_type& d)
    {
        matrix_type PX(X);
        vector_type work(X.n_rows);
        apply_row_permutation(PX, ipiv, work);

        return matrix_type(PX * arma::diagmat(arma::square(d)) * PX.t());
    }
};

//------------------------------------------------------------------------------
// Implementation of member functions
//------------------------------------------------------------------------------
template <typename T>
typename cholesky_quasi_cauchy<T>::size_type
cholesky_quasi_cauchy<T>::pivot_order(vector_type& a, vector_type& b,
                                      vector_type& x, vector_type& y,
                                      real_type delta, arma::uvec& ipiv,
                                      vector_type& g)
{
    const size_type n = a.size();
    assert(b.size() == n);
    assert(x.size() == n);
    assert(y.size() == n);
    assert(ipiv.size() == n);
    assert(g.size() == n);
    //
    // Set cutoff for GECP termination
    //
    const auto eta = arma::Datum<real_type>::eps * delta * delta;
    //
    // Form vector g(i) = a(i) * b(i) / (x(i) + y(i))
    //
    g = (a % b) / (x + y);
    //
    // Initialize permutation matrix
    //
    ipiv = arma::linspace<arma::uvec>(0, n - 1, n);

    size_type m = 0;
    while (m < n)
    {
        //
        // Find m <= l < n such that |g(l)| = max_{m<=k<n}|g(k)|
        //
        const auto l    = arma::abs(g.tail(n - m)).index_max() + m;
        const auto gmax = std::abs(g(l));

        if (gmax < eta)
        {
            break;
        }

        if (l != m)
        {
            // Swap elements
            std::swap(g(l), g(m));
            std::swap(a(l), a(m));
            std::swap(b(l), b(m));
            std::swap(x(l), x(m));
            std::swap(y(l), y(m));
            // Swap _rows_ of permutation matrix
            std::swap(ipiv(l), ipiv(m));
        }

        // Update diagonal of Schur complement
        const auto xm = x(m);
        const auto ym = y(m);
        for (size_type k = m + 1; k < n; ++k)
        {
            g(k) *= (x(k) - xm) * (y(k) - ym) / ((x(k) + ym) * (y(k) + xm));
        }
        ++m;
    }
    //
    // Returns the truncation size
    //
    return m;
}

template <typename T>
void cholesky_quasi_cauchy<T>::factorize(const vector_type& a,
                                         const vector_type& b,
                                         const vector_type& x,
                                         const vector_type& y, matrix_type& L,
                                         real_vector_type& d,
                                         vector_type& alpha, vector_type& beta)
{
    const auto n = L.n_rows;
    const auto m = L.n_cols;
    assert(a.size() == n);
    assert(b.size() == n);
    assert(x.size() == n);
    assert(y.size() == n);
    assert(d.size() == m);
    assert(alpha.size() == n);
    assert(beta.size() == n);

    alpha = a;
    beta  = b;

    L.zeros();
    for (size_type l = 0; l < n; ++l)
    {
        L(l, 0) = alpha(l) * beta(0) / (x(l) + y(0));
    }

    for (size_type k = 1; k < m; ++k)
    {
        // Upgrade generators
        const auto xkm1 = x(k - 1);
        const auto ykm1 = y(k - 1);
        for (size_type l = k; l < n; ++l)
        {
            alpha(l) *= (x(l) - xkm1) / (x(l) + ykm1);
            beta(l) *= (y(l) - ykm1) / (y(l) + xkm1);
        }
        // Extract k-th column for Cholesky factors
        for (size_type l = k; l < n; ++l)
        {
            L(l, k) = alpha(l) * beta(k) / (x(l) + y(k));
        }
    }
    //
    // Scale strictly lower triangular part of G
    //   - diagonal part of G contains D**2
    //   - L = tril(G) * D^{-2} + I
    //
    for (size_type j = 0; j < m; ++j)
    {
        const auto djj   = std::real(L(j, j));
        const auto scale = real_type(1) / djj;
        d(j)             = std::sqrt(djj);
        L(j, j) = real_type(1);
        for (size_type i = j + 1; i < n; ++i)
        {
            L(i, j) *= scale;
        }
    }

    return;
}

} // namespace: expsum

#endif /* EXPSUM_REDUCTION_CHOLESKY_CAUCHY_HPP */

max_stars_repo_name: hide-ikeno/expsum

max_issues_repo_name: hide-ikeno/expsum

max_forks_repo_name: hide-ikeno/expsum


text:
// Copyright (c) 2021-2022 The MetabaseNet developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/test/unit_test.hpp>

#include "crypto.h"
#include "ctsdb.h"
#include "hcode.h"
#include "test_big.h"
#include "uint256.h"

BOOST_FIXTURE_TEST_SUITE(ctsdb_tests, BasicUtfSetup)

using namespace metabasenet::storage;

class CMetaData
{
    friend class hcode::CStream;

public:
    uint224 hash;
    uint32 file;
    uint32 offset;
    uint32 blocktime;

protected:
    template <typename O>
    void Serialize(hcode::CStream& s, O& opt)
    {
        s.Serialize(hash, opt);
        s.Serialize(file, opt);
        s.Serialize(offset, opt);
        s.Serialize(blocktime, opt);
    }
};

typedef CCTSDB<uint224, CMetaData, CCTSChunkSnappy<uint224, CMetaData>> CMetaDB;
//typedef CCTSDB<uint224,CMetaData> CMetaDB;

BOOST_AUTO_TEST_CASE(ctsdb)
{
    CMetaDB db;

    std::string fullpath = boost::filesystem::initial_path<boost::filesystem::path>().string() + "/dbpath";
    std::cout << "init path: " << fullpath << std::endl;
    BOOST_CHECK(db.Initialize(boost::filesystem::path(fullpath)));

    db.RemoveAll();

    std::vector<std::pair<int64, uint224>> vTest;
    for (int loop = 0; loop < 1; loop++)
    {
        for (int i = 0; i < 3600; i++)
        {
            int64 nTime = loop * 3600 + i;
            for (int j = 0; j < 1000; j++)
            {
                uint256 txid;
                metabasenet::crypto::CryptoGetRand256(txid);

                CMetaData data;
                data.hash = uint224(txid);
                data.file = 1;
                data.offset = i * j;
                data.blocktime = nTime;

                db.Update(nTime, data.hash, data);
                if (i == j)
                {
                    vTest.push_back(std::make_pair(nTime, data.hash));
                }
            }
        }
        hcode::CTicks t1;
        BOOST_CHECK(db.Flush());
        hcode::CTicks t2;
        BOOST_CHECK(db.Flush());
        std::cout << "Flush : " << (t2 - t1) << " " << (t2.Elapse() / 1000) << "\n";
    }

    {
        hcode::CTicks t;
        for (int i = 0; i < vTest.size(); i++)
        {
            CMetaData data;
            BOOST_CHECK(db.Retrieve(vTest[i].first, vTest[i].second, data));
            BOOST_CHECK(data.hash == vTest[i].second);
        }

        std::cout << "Retrieve : " << (t.Elapse() / vTest.size()) << "\n";
    }

    db.Deinitialize();
    boost::filesystem::remove_all(fullpath);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: metabasenet/metabasenet

max_issues_repo_name: metabasenet/metabasenet

max_forks_repo_name: metabasenet/metabasenet


text:
#include <boost/test/unit_test.hpp>
#include <iostream>

struct F {
    F():i(0) { std::cout << "setup" << std::endl; }
    ~F() { std::cout << "teardown" << std::endl; }

    int i;
};

BOOST_AUTO_TEST_SUITE( test )

BOOST_FIXTURE_TEST_CASE( test_case1, F ) {
    BOOST_CHECK( i == 0 );
    ++i;
}

BOOST_AUTO_TEST_CASE( test_case2 ) {
    BOOST_REQUIRE( 2 > 1 );
}

BOOST_AUTO_TEST_CASE( test_case3 ) {
    int i = 1;
    BOOST_CHECK_EQUAL( i, 1 );
    ++i;
}

BOOST_AUTO_TEST_SUITE_END()


text:
//          Copyright Billy O'Neal 2012
// 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)
//
// vFind.cpp -- Implements the main entry point for pevFind.

#include "pch.hpp"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/trim.hpp>
#include "timeoutThread.h"
#include "utility.h"
#include "mainScanner.h"
#include "filesScanner.h"
#include "processScanner.h"
#include "consoleParser.h"
#include "globalOptions.h"
#include "criterion.h"

namespace vFind {

int main()
{
    consoleParser parseInstance;
    globalOptions::logicalTree = parseInstance.parseCmdLine(GetCommandLine());
    if (globalOptions::debug)
    {
        std::puts("# DEBUGGING OUTPUT #");
        std::wprintf(L"Format:\n%s\n\n", globalOptions::displaySpecification.c_str());
        if (globalOptions::debug)
            std::puts("Display debugging output");
        if (globalOptions::fullPath)
            std::puts("Displaying the full path");
        if (globalOptions::summary)
            std::puts("Displaying summary before termination");
        if (globalOptions::noSubDirectories)
            std::puts("Do not recurse into subdirectories");
        std::printf("Encoding: ");
        switch(globalOptions::encoding)
        {
        case globalOptions::ENCODING_TYPE_ACP:
            std::puts("ACP");
            break;
        case globalOptions::ENCODING_TYPE_OEM:
            std::puts("OEM");
            break;
        case globalOptions::ENCODING_TYPE_UTF8:
            std::puts("UTF-8");
            break;
        case globalOptions::ENCODING_TYPE_UTF16:
            std::puts("UTF-16");
            break;
        }
        std::printf("Limiting to %u lines\n", globalOptions::lineLimit);
        if (globalOptions::timeout)
            std::printf("Limiting to %u ms of execution time\n", globalOptions::timeout);
        std::fputws(L"\nInternal processing tree:\n", stdout);
        std::wstring debugTreeResult(globalOptions::logicalTree->debugTree());
        std::fputws(debugTreeResult.c_str(), stdout);
    }
    if (globalOptions::regularExpressions.empty())
    {
        std::fprintf(stderr, "Search operations must specify at least one regex.");
        return 3;
    }
    globalOptions::logicalTree->reorderTree();
    if (globalOptions::debug)
    {
        std::wstring debugTree(globalOptions::logicalTree->debugTree());
        std::wprintf(L"\nInternal processing tree after reordering:\n%s\n# END DEBUGGING OUTPUT #\n\n", debugTree.c_str());
        system("pause");
    }
    //If a timeout is set, start the watch thread to terminate this one if need be.
    if (globalOptions::timeout)
        CreateThread(NULL,50,&timeoutThread,reinterpret_cast<LPVOID>(globalOptions::timeout),NULL,NULL);
    if (!globalOptions::fileList.empty())
        scanners::filesScanner().scan();
    else if (globalOptions::killProc)
        scanners::processScanner().scan();
    else
        scanners::recursiveScanner().scan();
#ifndef NDEBUG
    system("pause");
#endif
    if (globalOptions::cancel)
        return 1;
    if (globalOptions::totalEntries)
        return 0;
    else
        return 4;
}

} //namespace vFind

max_stars_repo_name: BillyONeal/pevFind

max_issues_repo_name: BillyONeal/pevFind

max_forks_repo_name: BillyONeal/pevFind


text: #include <boost/hana/concept/group.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text: #include <boost/hana/concept/orderable.hpp>