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

#include "lanelet_aisan_converter/lanelet2aisan_converter/lanelet2aisan_converter.h"

#include <set>
#include <string>
#include <vector>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/register/point.hpp>
#include <boost/geometry/multi/geometries/register/multi_point.hpp>

#include <amathutils_lib/amathutils.hpp>

#include "lanelet_aisan_converter/lanelet_helper/lanelet_helper.h"
#include "lanelet_aisan_converter/lanelet2aisan_converter/unique_id_handler.h"

BOOST_GEOMETRY_REGISTER_MULTI_POINT(decltype(std::vector<lanelet::BasicPoint2d>{}))  // NOLINT

namespace
{
char convertLineColor(const std::string& type, const std::string& subtype)
{
  return 'W';  // Color is not supported in Lanelet2
}

uint convertLineType(const std::string& type, const std::string& subtype)
{
  if (subtype == "solid")
  {
    return vector_map_msgs::WhiteLine::SOLID_LINE;
  }
  if (subtype == "dashed")
  {
    return vector_map_msgs::WhiteLine::DASHED_LINE_SOLID;
  }

  return vector_map_msgs::WhiteLine::SOLID_LINE;  // default
}
}  // namespace

namespace lanelet2aisan_converter
{
AisanId Lanelet2AisanConverter::createDummyRoadSign(const lanelet::BasicPoint3d& p)
{
  // Create Vector
  const auto vid = createVector(p, 0, 90);

  // Create Pole
  const auto plid = createPole(p, 0, 0, 1.0, 0.02);

  // Create Feature
  vector_map_msgs::RoadSign road_sign{};
  road_sign.id = UniqueIdHandler<vector_map_msgs::RoadSign>::getInstance().generateUniqueInt32Id();
  road_sign.vid = vid;
  road_sign.plid = plid;
  road_sign.type = 1;    // Stop Sign
  road_sign.linkid = 0;  // Not supported

  // Add to list
  aisan_map_->road_signs.push_back(road_sign);
}

AisanId Lanelet2AisanConverter::createDummyUtilityPoles()
{
  for (const auto& pole : aisan_map_->poles)
  {
    // Create Feature
    vector_map_msgs::UtilityPole utility_pole{};
    utility_pole.id = UniqueIdHandler<vector_map_msgs::UtilityPole>::getInstance().generateUniqueInt32Id();
    utility_pole.plid = pole.plid;
    utility_pole.linkid = 0;  // Not supported

    // Add to list
    aisan_map_->utility_poles.push_back(utility_pole);
  }
}

void Lanelet2AisanConverter::createCrossRoads()
{
  // Build RoutingGraph
  const auto vehicle_rules =
      lanelet::traffic_rules::TrafficRulesFactory::create(lanelet::Locations::Germany, lanelet::Participants::Vehicle);

  lanelet::routing::RoutingGraphPtr vehicle_graph =
      lanelet::routing::RoutingGraph::build(*lanelet_map_, *vehicle_rules);

  // Memorize added ID
  std::set<LaneletId> already_added_set;

  for (const auto& lanelet_obj : lanelet_helper::getFilteredLanelets(*lanelet_map_, lanelet::Participants::Vehicle))
  {
    if (already_added_set.count(lanelet_obj.id()) != 0)
    {
      continue;
    }

    // Get intersection lanelets
    const auto intersection_lanelet_objs = lanelet_helper::getIntersectionLanelets(vehicle_graph, lanelet_obj);

    if (intersection_lanelet_objs.empty())
    {
      continue;
    }

    for (const auto& intersection_lanelet_obj : intersection_lanelet_objs)
    {
      already_added_set.insert(intersection_lanelet_obj.id());
    }

    // Gather all points of Lanelets in intersection
    std::vector<lanelet::BasicPoint2d> vertices;
    for (const auto& intersection_lanelet_obj : intersection_lanelet_objs)
    {
      for (const auto& p : intersection_lanelet_obj.polygon3d())
      {
        vertices.push_back(lanelet::utils::to2D(p.basicPoint()));
      }
    }

    // Get Z value
    const double z = intersection_lanelet_objs.front().centerline3d().front().z();

    // Create convex hull
    std::vector<lanelet::BasicPoint2d> convex_hull;
    boost::geometry::convex_hull(vertices, convex_hull);

    // Create 3d points
    lanelet::BasicPolygon3d ps;
    for (const auto& p : convex_hull)
    {
      ps.emplace_back(p.x(), p.y(), z);
    }

    // Create Area
    const auto aid = createArea(ps);

    // Create Feature
    vector_map_msgs::CrossRoad cross_road{};
    cross_road.id = UniqueIdHandler<vector_map_msgs::CrossRoad>::getInstance().generateUniqueInt32Id();
    cross_road.aid = aid;
    cross_road.linkid = 0;  // Not supported

    // Add to list
    aisan_map_->cross_roads.push_back(cross_road);
  }
}

void Lanelet2AisanConverter::createCrossWalks()
{
  // Prepare traffic rules
  const auto vehicle_pedestrian_graph = lanelet_helper::createRoutingGraphContainer(
      *lanelet_map_, { lanelet::Participants::Vehicle, lanelet::Participants::Pedestrian });  // NOLINT

  for (const auto& lanelet_obj : lanelet_helper::getFilteredLanelets(*lanelet_map_, lanelet::Participants::Vehicle))
  {
    // Find confligting CrossWalks
    for (const auto& cross_walk_lanelet_obj : vehicle_pedestrian_graph.conflictingInGraph(lanelet_obj, 1))
    {
      // Outline Shape
      AisanId parent_id;
      {
        // Create Area
        const lanelet::BasicPolygon3d line_string = cross_walk_lanelet_obj.polygon3d().basicPolygon();
        const auto aid = createArea(line_string);

        // Create Feature
        vector_map_msgs::CrossWalk cross_walk{};
        cross_walk.id = UniqueIdHandler<vector_map_msgs::CrossWalk>::getInstance().generateUniqueInt32Id();
        cross_walk.aid = aid;
        cross_walk.type = 0;    // Outline
        cross_walk.bdid = 0;    // No parent
        cross_walk.linkid = 0;  // Not supported

        // Save parent ID
        parent_id = cross_walk.id;

        // Add to list
        aisan_map_->cross_walks.push_back(cross_walk);
      }

      // Dummy Stripe Shape
      {
        // Create Area
        const lanelet::BasicPolygon3d line_string = cross_walk_lanelet_obj.polygon3d().basicPolygon();
        const auto aid = createArea(line_string);

        // Create Feature
        vector_map_msgs::CrossWalk cross_walk{};
        cross_walk.id = UniqueIdHandler<vector_map_msgs::CrossWalk>::getInstance().generateUniqueInt32Id();
        cross_walk.aid = aid;
        cross_walk.type = 1;  // Stripe
        cross_walk.bdid = parent_id;
        cross_walk.linkid = 0;  // Not supported

        // Add to list
        aisan_map_->cross_walks.push_back(cross_walk);
      }
    }
  }
}

void Lanelet2AisanConverter::createLanes()
{
  // Build Routing Graph
  const auto vehicle_rules =
      lanelet::traffic_rules::TrafficRulesFactory::create(lanelet::Locations::Germany, lanelet::Participants::Vehicle);

  lanelet::routing::RoutingGraphUPtr vehicle_graph =
      lanelet::routing::RoutingGraph::build(*lanelet_map_, *vehicle_rules);

  for (const auto& lanelet_obj : lanelet_helper::getFilteredLanelets(*lanelet_map_, lanelet::Participants::Vehicle))
  {
    // Calculate attributes of each point
    const auto centerline = lanelet_obj.centerline();
    const auto accumulated_lengths = lanelet_helper::calculateAccumulatedLengths(centerline);
    const auto directions = lanelet_helper::calculateDirections(centerline);

    // Calculate attributes of whole Lane
    const auto lane_count = vehicle_graph->besides(lanelet_obj).size() + 1;
    const auto lane_number = vehicle_graph->lefts(lanelet_obj).size() + 1;
    const auto speed_limit = vehicle_rules->speedLimit(lanelet_obj).speedLimit.value();

    // Create each point
    std::vector<AisanId> node_ids;
    for (const auto& p : centerline)
    {
      const auto node_id = createNode(p);
      node_ids.push_back(node_id);
    }

    // Prefetch Lane IDs
    std::vector<AisanId> lane_ids;
    const auto next_id = UniqueIdHandler<vector_map_msgs::Lane>::getInstance().getNextId();
    for (size_t i = 0; i < centerline.size(); ++i)
    {
      lane_ids.push_back(next_id + i);
    }

    const auto N = centerline.size();
    for (size_t i = 0; i < N - 1; ++i)
    {
      // Get attributes
      const lanelet::BasicPoint3d p = centerline[i];
      const auto dist = accumulated_lengths.at(i);
      const auto dir = directions.at(i);
      const auto left_width = lanelet::geometry::distance2d(p, lanelet_obj.leftBound());
      const auto right_width = lanelet::geometry::distance2d(p, lanelet_obj.rightBound());

      // Create DTLane
      const auto did = createDTLane(p, dist, dir, left_width, right_width);

      // Create Feature
      vector_map_msgs::Lane lane{};
      lane.lnid = UniqueIdHandler<vector_map_msgs::Lane>::getInstance().generateUniqueInt32Id();
      lane.did = did;
      lane.bnid = node_ids.at(i);
      lane.fnid = node_ids.at(i + 1);
      lane.span = accumulated_lengths.at(i + 1) - accumulated_lengths.at(i);
      lane.lcnt = lane_count;
      lane.lno = lane_number;
      lane.limitvel = speed_limit;
      lane.refvel = speed_limit;
      lane.lanecfgfg = (lane.lcnt > 1) ? 1 : 0;
      lane.roadsecid = 0;  // Not supported
      lane.clossid = 0;    // Not supported
      lane.linkwaid = 0;   // Not supported
      lane.jct = 0;        // Not supported
      lane.lanetype = 0;   // Not supported

      // Backward conectivities will be (re)calculated later
      lane.blid = (i == 0) ? 0 : lane_ids.at(i - 1);
      lane.blid2 = 0;
      lane.blid3 = 0;
      lane.blid4 = 0;

      // Forward conectivities  will be (re)calculated later
      lane.flid = (i == N - 2) ? 0 : lane_ids.at(i + 1);
      lane.flid2 = 0;
      lane.flid3 = 0;
      lane.flid4 = 0;

      // Save start/end Lane ID
      if (i == 0)
      {
        start_lnid_map_[lanelet_obj.id()] = lane.lnid;
      }
      if (i == N - 2)
      {
        end_lnid_map_[lanelet_obj.id()] = lane.lnid;
      }

      // Add to list
      aisan_map_->lanes.push_back(lane);
    }
  }
}

void Lanelet2AisanConverter::createSignals()
{
  // Memorize added ID
  std::set<LaneletId> already_added_set;

  for (const auto& lanelet_obj : lanelet_helper::getFilteredLanelets(*lanelet_map_, lanelet::Participants::Vehicle))
  {
    for (const auto traffic_light_reg_elem : lanelet_obj.regulatoryElementsAs<lanelet::TrafficLight>())
    {
      for (const auto traffic_light : traffic_light_reg_elem->trafficLights())
      {
        if (already_added_set.count(traffic_light.id()) != 0)
        {
          continue;
        }

        already_added_set.insert(traffic_light.id());

        if (!traffic_light.isLineString())
        {
          continue;
        }

        // Calculate lane angle
        const auto N = lanelet_obj.centerline().size();
        const auto p1 = lanelet_obj.centerline()[N - 1];
        const auto p2 = lanelet_obj.centerline()[N - 2];
        const auto lane_angle = atan2(p2.y() - p1.y(), p2.x() - p1.x());

        // Create bulb's color and position info
        struct BulbInfo
        {
          int color;
          double pos;
        };

        // NOLINTNEXTLINE
        std::vector<BulbInfo> bulb_info_list = {
          { vector_map_msgs::Signal::RED, 0.25 },
          { vector_map_msgs::Signal::YELLOW, 0.5 },
          { vector_map_msgs::Signal::BLUE, 0.75 },
        };

        // Calculate direction of light's LineString
        lanelet::ConstLineString3d light_bulb_points = traffic_light.lineString().value();
        const lanelet::BasicPoint3d start_point = light_bulb_points.front();
        const lanelet::BasicPoint3d end_point = light_bulb_points.back();
        const lanelet::BasicPoint3d direction_vector = end_point - start_point;

        // Create Pole
        const auto pole_height = 5.0;
        const auto mid_point = (start_point + end_point) / 2;
        const auto plid = createPole(mid_point, 0, 0, pole_height, 0.3);

        // Create each light bulb
        for (const auto& bulb_info : bulb_info_list)
        {
          // Calculate parameters
          const lanelet::BasicPoint3d p_bottom = start_point + bulb_info.pos * direction_vector;
          const lanelet::BasicPoint3d p(p_bottom.x(), p_bottom.y(), p_bottom.z() + pole_height);

          // Create vector
          const auto vid = createVector(p, amathutils::rad2deg(-lane_angle), 90);

          // Create Feature
          vector_map_msgs::Signal signal{};
          signal.id = UniqueIdHandler<vector_map_msgs::Signal>::getInstance().generateUniqueInt32Id();
          signal.vid = vid;
          signal.plid = plid;
          signal.type = bulb_info.color;
          signal.linkid = 0;  // Not supported

          // Add to list
          aisan_map_->signals.push_back(signal);
        }
      }
    }
  }
}

void Lanelet2AisanConverter::createStopLines()
{
  for (const auto& line_string : lanelet_map_->lineStringLayer)
  {
    if (line_string.attributeOr(lanelet::AttributeName::Type, "") != "stop_line")
    {
      continue;
    }

    // Create Line
    const lanelet::BasicLineString3d ps = line_string.basicLineString();
    const auto lid = createLine(ps, 0, 0);

    // Create Feature
    vector_map_msgs::StopLine stop_line{};
    stop_line.id = UniqueIdHandler<vector_map_msgs::StopLine>::getInstance().generateUniqueInt32Id();
    stop_line.lid = lid;
    stop_line.tlid = 0;    // Not supported
    stop_line.signid = 0;  // Not supported
    stop_line.linkid = 0;  // Not supported

    // Add to list
    aisan_map_->stop_lines.push_back(stop_line);
  }
}

void Lanelet2AisanConverter::createWayAreas()
{
  for (const auto& lanelet_obj : lanelet_helper::getFilteredLanelets(*lanelet_map_, lanelet::Participants::Vehicle))
  {
    // Create Area
    const auto aid = createArea(lanelet_obj.polygon3d().basicPolygon());

    // Create Feature
    vector_map_msgs::WayArea way_area{};
    way_area.waid = UniqueIdHandler<vector_map_msgs::WayArea>::getInstance().generateUniqueInt32Id();
    way_area.aid = aid;

    // Add to list
    aisan_map_->way_areas.push_back(way_area);
  }
}

void Lanelet2AisanConverter::createWhiteLines()
{
  for (const auto& lanelet_obj : lanelet_helper::getFilteredLanelets(*lanelet_map_, lanelet::Participants::Vehicle))
  {
    for (const auto& line_string : { lanelet_obj.leftBound(), lanelet_obj.rightBound() })
    {
      // Get attributes
      const std::string type = line_string.attributeOr(lanelet::AttributeName::Type, "");
      const std::string subtype = line_string.attributeOr(lanelet::AttributeName::Subtype, "");

      const lanelet::BasicLineString3d ps = line_string.basicLineString();

      // Prefetch Line IDs
      std::vector<AisanId> line_ids;
      const auto next_id = UniqueIdHandler<vector_map_msgs::Line>::getInstance().getNextId();
      for (size_t i = 0; i < ps.size(); ++i)
      {
        line_ids.push_back(next_id + i);
      }

      // Create each segment
      for (size_t i = 0; i < ps.size() - 1; ++i)
      {
        const auto back_line_id = (i == 0) ? 0 : line_ids.at(i);
        const auto front_line_id = (i == ps.size() - 2) ? 0 : line_ids.at(i + 1);

        const lanelet::BasicLineString3d segment{ ps.at(i), ps.at(i + 1) };
        const auto lid = createLine(segment, back_line_id, front_line_id);

        // Create Feature
        vector_map_msgs::WhiteLine white_line{};
        white_line.id = UniqueIdHandler<vector_map_msgs::WhiteLine>::getInstance().generateUniqueInt32Id();
        white_line.lid = lid;
        white_line.width = (type == "line_thick") ? 0.15 : 0.05;
        white_line.color = convertLineColor(type, subtype);
        white_line.type = convertLineType(type, subtype);
        white_line.linkid = 0;  // Not supported

        // Add to list
        aisan_map_->white_lines.push_back(white_line);
      }
    }
  }
}
}  // namespace lanelet2aisan_converter


text:
#pragma once

#include <iosfwd>
#include <utility>

#include <boost/operators.hpp>

#include <elle/serialization.hh>
#include <elle/serialization/Serializer.hh>

#include <elle/cryptography/fwd.hh>
#include <elle/cryptography/Oneway.hh>
#include <elle/cryptography/Cipher.hh>
#include <elle/cryptography/rsa/KeyPair.hh>
#include <elle/cryptography/rsa/PublicKey.hh>
#include <elle/cryptography/rsa/PrivateKey.hh>
#include <elle/cryptography/rsa/defaults.hh>

//
// ---------- Class -----------------------------------------------------------
//

namespace elle
{
  namespace cryptography
  {
    namespace rsa
    {
      /// Represent a cryptographic key pair _i.e_ a pair of public and
      /// private keys.
      ///
      /// Note that the public key is always written as a capital 'K'
      /// while a private key is noted with a lower-case 'k'.
      class KeyPair
        : public elle::Printable
        , private boost::totally_ordered<KeyPair>
      {
      public:
        /*-------------.
        | Construction |
        `-------------*/
      public:
        KeyPair(PublicKey const& K, PrivateKey const& k);
        KeyPair(std::shared_ptr<PublicKey> K,
                std::shared_ptr<PrivateKey> k);
        KeyPair(PublicKey&& K,
                PrivateKey&& k);
        KeyPair(KeyPair const& other);
        KeyPair(KeyPair&& other);
        virtual
        ~KeyPair();

        /*--------.
        | Methods |
        `--------*/
      public:
        /// Return the public key.
        PublicKey const&
        K() const;
        /// Return the private key.
        PrivateKey const&
        k() const;
        /// Return the key pair's size in bytes.
        uint32_t
        size() const;
        /// Return the key pair's length in bits.
        uint32_t
        length() const;

# if defined(ELLE_CRYPTOGRAPHY_ROTATION)
        /*---------.
        | Rotation |
        `---------*/
      public:
        explicit
        /// Deduce a keypair based out of the given seed.
        KeyPair(Seed const& seed);
# endif

        /*----------.
        | Operators |
        `----------*/
      public:
        bool
        operator ==(KeyPair const& other) const;
        ELLE_OPERATOR_NO_ASSIGNMENT(KeyPair);

        /*----------.
        | Printable |
        `----------*/
      public:
        void
        print(std::ostream& stream) const override;

        /*--------------.
        | Serialization |
        `--------------*/
      public:
        KeyPair(elle::serialization::SerializerIn& serializer);
        void
        serialize(elle::serialization::Serializer& serializer);
        using serialization_tag = elle::serialization_tag;

        /*-----------.
        | Attributes |
        `-----------*/
      private:
        /// The public key.
        ELLE_ATTRIBUTE_R(std::shared_ptr<PublicKey>, public_key);
        /// The private key.
        ELLE_ATTRIBUTE_R(std::shared_ptr<PrivateKey>, private_key);
      };
    }
  }
}

//
// ---------- Generator -------------------------------------------------------
//

namespace elle
{
  namespace cryptography
  {
    namespace rsa
    {
      namespace keypair
      {
        /*----------.
        | Functions |
        `----------*/

        /// Return a pair composed of the public and private key of a
        /// freshly generated RSA key pair.
        ///
        /// Note that the length is in bits.
        KeyPair
        generate(uint32_t const length);

        namespace der
        {
          /*----------.
          | Functions |
          `----------*/

          /// Encode the key pair in DER.
          elle::Buffer
          encode(KeyPair const& keypair);
          /// Decode the key pair from a DER representation.
          KeyPair
          decode(elle::ConstWeakBuffer const& buffer);
        }
      }
    }
  }
}

namespace std
{
  template <>
  struct hash<elle::cryptography::rsa::KeyPair>
  {
    size_t
    operator ()(elle::cryptography::rsa::KeyPair const& value) const;
  };
}

ext: hh

max_stars_repo_name: infinitio/elle

max_issues_repo_name: infinitio/elle

max_forks_repo_name: infinitio/elle


text:
#ifndef HAMILTONIANS_KITAEVHEXC24_HPP
#define HAMILTONIANS_KITAEVHEXC24_HPP
#include <Eigen/Eigen>
#include <nlohmann/json.hpp>

class KitaevHexC24
{
private:
	static constexpr int N = 24;
	double Jx_;
	double Jy_;
	double Jz_;

	double hx_;

public:

	KitaevHexC24(double J)
		: Jx_(J), Jy_(J), Jz_(J), hx_{}
	{
	}

	KitaevHexC24(double Jx, double Jy, double Jz)
		: Jx_(Jx), Jy_(Jy), Jz_(Jz), hx_{}
	{
	}

	KitaevHexC24(double J, double hx)
		: Jx_(J), Jy_(J), Jz_(J), hx_(hx)
	{
	}

	std::vector<std::pair<int,int> > xLinks() const
	{
		std::vector<std::pair<int,int> > res;
		//first row
		res.emplace_back(0,3);
		res.emplace_back(1,4);
		//second row
		res.emplace_back(5,9);
		res.emplace_back(6,10);
		res.emplace_back(7,11);
		//thrid row
		res.emplace_back(12,16);
		res.emplace_back(13,17);
		res.emplace_back(14,18);
		//forth row
		res.emplace_back(19,22);
		res.emplace_back(20,23);

		//between
		res.emplace_back(15,2);
		res.emplace_back(21,8);
		return res;
	}

	std::vector<std::pair<int,int> > yLinks() const
	{
		std::vector<std::pair<int,int> > res;
		//first row
		res.emplace_back(0,2);
		res.emplace_back(1,3);
		//second row
		res.emplace_back(5,8);
		res.emplace_back(6,9);
		res.emplace_back(7,10);
		//thrid row
		res.emplace_back(13,16);
		res.emplace_back(14,17);
		res.emplace_back(15,18);
		//forth row
		res.emplace_back(20,22);
		res.emplace_back(21,23);

		//between
		res.emplace_back(4,12);
		res.emplace_back(11,19);
		return res;
	}

	std::vector<std::pair<int,int> > zLinks() const
	{
		std::vector<std::pair<int,int> > res;
		res.emplace_back(2,5);
		res.emplace_back(3,6);
		res.emplace_back(4,7);

		res.emplace_back(8,12);
		res.emplace_back(9,13);
		res.emplace_back(10,14);
		res.emplace_back(11,15);

		res.emplace_back(16,19);
		res.emplace_back(17,20);
		res.emplace_back(18,21);
		res.emplace_back(11,15);

		res.emplace_back(0,22);
		res.emplace_back(1,23);
		return res;
	}

	nlohmann::json params() const
	{
		return nlohmann::json
		{
			{"name", "KITAEVHEXC24"},
			{"Jx", Jx_},
			{"Jy", Jy_},
			{"Jz", Jz_},
			{"hx", hx_},
		};
	}

	template<class State>
	typename State::Scalar operator()(const State& smp) const
	{
		typename State::Scalar s = 0.0;
		constexpr std::complex<double> I(0.,1.);

		for(auto &xx: xLinks())
		{
			s += Jx_*smp.ratio(xx.first, xx.second); //xx
		}
		for(auto &yy: yLinks())
		{
			int zzval = smp.sigmaAt(yy.first)*smp.sigmaAt(yy.second);
			s += -Jy_*zzval*smp.ratio(yy.first, yy.second); //yy
		}
		for(auto &zz: zLinks())
		{
			int zzval = smp.sigmaAt(zz.first)*smp.sigmaAt(zz.second);
			s += Jz_*zzval; //yy
		}
		for(int n = 0; n < N; n++)
		{
			s += hx_*smp.ratio(n);
		}
		return s;
	}

	std::map<uint32_t, double> operator()(uint32_t col) const
	{
		std::map<uint32_t, double> m;

		for(auto &xx: xLinks())
		{
			int t = (1 << xx.first) | (1 << xx.second);
			m[col ^ t] += Jx_; //xx
		}
		for(auto &yy: yLinks())
		{
			int zzval = (1-2*int((col >> yy.first) & 1))*(1-2*int((col >> yy.second) & 1));
			int t = (1 << yy.first) | (1 << yy.second);
			m[col ^ t] += -Jy_*zzval; //yy
		}
		for(auto &zz: zLinks())
		{
			int zzval = (1-2*int((col >> zz.first) & 1))*(1-2*int((col >> zz.second) & 1));
			m[col] += Jz_*zzval; //zz
		}
		for(int n = 0; n < N; n++)
		{
			m[col ^ (1<<n)] += hx_;
		}

		return m;
	}
};
#endif//HAMILTONIANS_KITAEVHEXC24_HPP

ext: hpp

max_stars_repo_name: cecri/yannq

max_issues_repo_name: cecri/yannq

max_forks_repo_name: cecri/yannq


text:
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cassert>

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

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

#include <boost/format.hpp>
#include <boost/optional.hpp>

#if defined _MSC_VER

#include <windows.h>
#define WIN32_LEAN_AND_MEAN
#include <io.h> // _findfirst
#include <direct.h> // _chdir
#include <shlobj.h> // SHGetSpecialFolderPathA
#include <process.h>

#include <ctype.h>
#include <mbctype.h>

#include <tchar.h>

#elif defined __GNUC__

#include <sys/dir.h>
#include <time.h>
#include <dirent.h>
#include <unistd.h>

#define strcmpi strcmp

#endif

#include "unportable.h"
#include "common.h"

#if ! defined _MSC_VER

#define _getcwd getcwd
#define _chdir chdir

#endif

#if OS_WIN32

#if _MSC_VER < 1400

bool splitpath(const std:: string &path, std:: string *pDir, std:: string *pFname, std:: string *pExt)
{
	char driveStr[_MAX_DRIVE];
	char dirStr[_MAX_DIR];
	char fnameStr[_MAX_FNAME];
	char extStr[_MAX_EXT];

	_splitpath(path.c_str(), driveStr, dirStr, fnameStr, extStr);

	std:: string dir = (const char *)driveStr;
	dir += (const char *)dirStr;
	std:: string fname = (const char *)fnameStr;
	std:: string ext = (const char *)extStr;

	if (path.length() != dir.length() + fname.length() + ext.length()) {
		return false;
	}

	if (pDir != NULL) {
		*pDir = dir;
	}
	if (pFname != NULL) {
		*pFname = fname;
	}
	if (pExt != NULL) {
		*pExt = ext;
	}

	return true;
}

#else

bool splitpath(const std:: string &path, std:: string *pDir, std:: string *pFname, std:: string *pExt)
{
	std::vector<char> buf;
	char *driveStr;
	char *dirStr;
	char *fnameStr;
	char *extStr;
	size_t sectionSize = _MAX_PATH;
	while (true) {
		buf.clear();
		buf.resize(sectionSize * 4, 0);
		driveStr = &buf[sectionSize * 0];
		dirStr = &buf[sectionSize * 1];
		fnameStr = &buf[sectionSize * 2];
		extStr = &buf[sectionSize * 3];
		errno_t err = _splitpath_s(path.c_str(),
			driveStr, sectionSize - 1,
			dirStr, sectionSize - 1,
			fnameStr, sectionSize - 1,
			extStr, sectionSize - 1);
		if (err == 0) {
			break; // while
		}
		else {
			if (err == ERANGE) {
				sectionSize *= 2;
			}
			else {
				assert(false);
			}
		}
	}

	std:: string dir = (const char *)driveStr;
	dir += (const char *)dirStr;
	std:: string fname = (const char *)fnameStr;
	std:: string ext = (const char *)extStr;

	if (path.length() != dir.length() + fname.length() + ext.length()) {
		return false;
	}

	if (pDir != NULL) {
		*pDir = dir;
	}
	if (pFname != NULL) {
		*pFname = fname;
	}
	if (pExt != NULL) {
		*pExt = ext;
	}

	return true;
}

#endif // #if _MSC_VER < 1400

#else

// may cause problems in a EUC like character encodings.

bool splitpath(const std:: string &path, std:: string *pDir, std:: string *pFname, std:: string *pExt)
{
	size_t p = path.rfind('/');
	if (pDir != NULL) {
		*pDir = p != std:: string::npos ? path.substr(0, p + 1) : "";
	}
	std:: string fileName = p != std:: string::npos ? path.substr(p + 1) : path;

	size_t q = fileName.rfind('.');
	if (q != std:: string::npos) {
		if (pFname != NULL) {
			*pFname = fileName.substr(0, q);
		}
		if (pExt != NULL) {
			*pExt = fileName.substr(q);
		}
	}
	else {
		if (pFname != NULL) {
			*pFname = fileName;
		}
		if (pExt != NULL) {
			*pExt = "";
		}
	}

	return true;
}

#endif

#if defined _MSC_VER

std:: string make_temp_file_on_the_same_directory(const std:: string &filePath, const std:: string &base, const std:: string &ext)
{
	std:: string dirStr;

	if (! filePath.empty()) {
		std:: string fnameStr;
		std:: string extStr;
		splitpath(filePath.c_str(), &dirStr, &fnameStr, &extStr);
	}
	else {
		dirStr = "";
	}

	DWORD processID = ::GetCurrentProcessId();

	unsigned long t;
	{
		LARGE_INTEGER largeInt;
		if (::QueryPerformanceCounter(&largeInt)) {
			t = (unsigned long)largeInt.QuadPart;
		}
		else {
			__time64_t t64;
			_time64(&t64);
			t = (unsigned long)t64;
		}
	}

	std:: string newFileName = (boost::format("%s%s-%x%x%s") % dirStr % base % (unsigned long) processID % t % ext).str();
	return newFileName;
}

std:: string make_filename_on_the_same_directory(const std:: string &fileName, const std:: string &targetPathFile)
{
	std:: string dirStr;
	std:: string fnameStr;
	std:: string extStr;

	splitpath(targetPathFile.c_str(), &dirStr, &fnameStr, &extStr);

	std:: string newFileName = (boost::format("%s%s") % dirStr % fileName).str();
	return newFileName;
}

#elif defined __GNUC__

std:: string make_temp_file_on_the_same_directory(const std:: string &filePath, const std:: string &base, const std:: string &ext)
{
	std:: string dirStr;
	std:: string fnameStr;
	std:: string extStr;

	splitpath(filePath.c_str(), &dirStr, &fnameStr, &extStr);
	pid_t pid = getpid();

	time_t timer;
	time(&timer);

	std:: string newFileName = (boost::format("%s%s-%x%x%s") % dirStr % base % (unsigned long) pid % (unsigned long) timer % ext).str();
	return newFileName;
}

std:: string make_filename_on_the_same_directory(const std:: string &fileName,  const std:: string &targetPathFile)
{
	std:: string dirStr;
	std:: string fnameStr;
	std:: string extStr;

	splitpath(targetPathFile.c_str(), &dirStr, &fnameStr, &extStr);

	std:: string newFileName = (boost::format("%s%s") % dirStr % fileName).str();
	return newFileName;
}

#endif

bool PathTime::getFileMTime(const std:: string &path, PathTime *pPathTime)
{
	struct stat t;
	int r = stat(path.c_str(), &t);
	if (r != 0) {
		return false; // fail
	}

	PathTime pt;
	pt.path = path;
	pt.mtime = t.st_mtime;

	*pPathTime = pt;

	return true;
}

std::string file_separator()
{
#if defined OS_WIN32
	return "\\";
#elif defined OS_UNIX
	return "/";
#endif
}

bool path_is_relative(const std:: string &path)
{
	if (path.length() >= 1 && path[0] == '/') {
		return false;
	}
#if defined OS_WIN32
	if (path.length() >= 1 && path[0] == '\\') {
		return false;
	}
	std::string::size_type pos = path.find(":");
	if (pos != std::string::npos && pos + 1 < path.length() && (path[pos + 1] == '\\' || path[pos + 1] == '/')) {
		return false;
	}
#endif
	return false;
}

//void split_path(const std::string &path, std::string *pDirectory, std::string *pFileName)
//{
//#if defined OS_WIN32
//	size_t pos = path.rfind('\\');
//#else
//	size_t pos = path.rfind('/');
//#endif
//	if (pos != std::string::npos) {
//		if (pDirectory != NULL) {
//#if defined OS_WIN32
//			if (pos >= 2 && path[pos - 1] == ':') {
//				*pDirectory = path.substr(0, pos + 1);
//			}
//			else {
//				*pDirectory = path.substr(0, pos);
//			}
//#else
//			*pDirectory = path.substr(0, pos);
//#endif
//			if ((*pDirectory).length() == 0) {
//				*pDirectory = path.substr(0, pos + 1);
//			}
//		}
//		if (pFileName != NULL) {
//			*pFileName = path.substr(pos + 1);
//		}
//	}
//	else {
//		if (pDirectory != NULL) {
//			*pDirectory = "";
//		}
//		if (pFileName != NULL) {
//			*pFileName = path;
//		}
//	}
//}

#if defined OS_WIN32

std::string escape_spaces(const std::string &str)
{
	if (str.find(' ') != std::string::npos) {
		if (str.length() > 0 && str[0] != '\"') {
			return "\"" + str + "\"";
		}
	}
	return str;
}

#elif defined OS_LINUX || defined OS_UBUNTU

std::string escape_spaces(const std::string &str)
{
	std::string r;

	for (size_t i = 0; i < str.length(); ++i) {
		int ch = str[i];
		switch (ch) {
		case ' ':
			r += "\\" " ";
			break;
		default:
			r += ch;
			break;
		}
	}

	return r;
}

#else
#error NO OS IS SPECIFIED
#endif

std::string get_application_data_path()
{
#if defined _MSC_VER
	boost::optional<std::string> reg_query_value(const std::string &path, const std::string &key);

	boost::optional<std::string> v = reg_query_value("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", "AppData");
	if (v) {
		return *v + "\\" + "www.ccfinder.net" + "\\" + "CCFinderX";
	}
	return "";
#else
    std::string applicationDataPath(get_application_config_path());

	return applicationDataPath;
#endif
}

#if defined _MSC_VER
#else
std::string get_application_config_path()
{
    //Excerpt from http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
    //
    //There is a single base directory relative to which user-specific configuration
    //files should be written. This directory is defined by the environment
    //variable $XDG_CONFIG_HOME.
    //
    //$XDG_CONFIG_HOME defines the base directory relative to which user specific
    //configuration files should be stored. If $XDG_CONFIG_HOME is either not set
    //or empty, a default equal to $HOME/.config should be used.
    std::string applicationConfigPath;

    const char* XDG_CONFIG_HOME = getenv("XDG_CONFIG_HOME");
    if  (XDG_CONFIG_HOME != 0) //i.e. undefined
    {
        applicationConfigPath = XDG_CONFIG_HOME;
    }
    else
    {
        const char* HOME = getenv("HOME");
        if (HOME != 0)
        {
            applicationConfigPath = HOME;
            applicationConfigPath += "/.config";
        }
        else
        {
            //Recovery if HOME not defined. /tmp should be accessible to anyone
            applicationConfigPath = "/tmp";
        }
    }
    applicationConfigPath += "/CCFinderX";

	return applicationConfigPath;
}
#endif

namespace {

#if defined _MSC_VER

const char *last_char(const char *str0)
{
	const unsigned char *str = (const unsigned char *)str0;
	const unsigned char *p = str;
	if (*p == '\x0') {
		return NULL;
	}

	const unsigned char *pos = p;
	while (*p != '\x0') {
		if (_ismbslead(pos, p) != 0) {
			pos = p;
			for (++p; *p != '\x0' && _ismbstrail(pos, p) != 0; ++p)
				NULL;
		}
		else {
			pos = p;
			++p;
		}
	}

	return (const char *)pos;
}

#elif defined __GNUC__

// may cause problems in a EUC like character encodings.

const char *last_char(const char *str0)
{
	const unsigned char *str = (const unsigned char *)str0;
	const unsigned char *p = str;
	if (*p == '\x0') {
		return NULL;
	}

	const unsigned char *pos = p;
	while (*p != '\x0') {
		assert(
            //('\x0' <= *p) && //always true
            (*p <= '\x7e'));
		pos = p;
		++p;
	}

	return (const char *)pos;
}

#endif

#if defined _MSC_VER

void find_files_i(std:: vector<std:: string> *pFiles, const std:: set<std:: string> &extensions,
		const std:: string &currentDir)
{
	struct _finddata_t c_file;
	long hFile;

	/* Find first .c file in current directory */
	if((hFile = _findfirst("*.*", &c_file)) != -1) {
		std:: vector<std:: string> files;
		std:: vector<std:: string> directories;
		while (true) {
			std:: string fileName(c_file.name);
			if (fileName == ".") {
				// do nothing
			}
			else if (fileName == "..") {
				// do nothing
			}
			else if ((c_file.attrib & _A_SUBDIR) != 0) {
				directories.push_back(fileName);
			}
			else {
				files.push_back(fileName);
			}
			if (_findnext( hFile, &c_file ) != 0) {
				break; // while true
			}
		}

		std:: sort(directories.begin(), directories.end());
		for (size_t i = 0; i < directories.size(); ++i) {
			const std:: string &fileName = directories[i];
			std:: string dir = currentDir + fileName;
			const char *lastp = last_char(dir.c_str());
			if (lastp != NULL) {
				int ch = *lastp;
				if (dir.length() > 0 && ! (ch == '/' || ch == '\\')) {
					dir += "\\";
				}
				if (_chdir(fileName.c_str()) != -1) {
					find_files_i(pFiles, extensions, dir);
					_chdir("..");
				}
			}
		}
		std:: sort(files.begin(), files.end());
		for (size_t i = 0; i < files.size(); ++i) {
			const std:: string &fileName = files[i];
			std:: string filePath = currentDir + fileName;
			for (std:: set<std:: string>::const_iterator i = extensions.begin(); i != extensions.end(); ++i) {
				std:: string ext = *i;
				if (filePath.length() >= ext.length() && strcmpi(filePath.c_str() + filePath.length() - ext.length(), ext.c_str()) == 0) {
					(*pFiles).push_back(filePath);
					break; // for i
				}
			}
		}
		_findclose( hFile );
	}
}

void find_named_directories_i(std:: vector<std:: string> *pFiles, const std:: set<std:: string> &names,
		const std:: string &currentDir)
{
	struct _finddata_t c_file;
	long hFile;

	/* Find first .c file in current directory */
	if((hFile = _findfirst("*.*", &c_file)) != -1) {
		std:: vector<std:: string> directories;
		while (true) {
			std:: string fileName(c_file.name);
			if (fileName == ".") {
				// do nothing
			}
			else if (fileName == "..") {
				// do nothing
			}
			else if ((c_file.attrib & _A_SUBDIR) != 0) {
				directories.push_back(fileName);
			}
			if (_findnext( hFile, &c_file ) != 0) {
				break; // while true
			}
		}

		std:: sort(directories.begin(), directories.end());
		for (size_t i = 0; i < directories.size(); ++i) {
			const std:: string &fileName = directories[i];
			std:: string dir = currentDir + fileName;
			if (names.find(fileName) != names.end()) {
				(*pFiles).push_back(dir);
			}
			const char *lastp = last_char(dir.c_str());
			if (lastp != NULL) {
				int ch = *lastp;
				if (dir.length() > 0 && ! (ch == '/' || ch == '\\')) {
					dir += "\\";
				}
				if (_chdir(fileName.c_str()) != -1) {
					find_named_directories_i(pFiles, names, dir);
					_chdir("..");
				}
			}
		}
		_findclose( hFile );
	}
}

#elif defined __GNUC__

// ÓIFfBNgª\[Xt@CæèOÉéæ¤ÉÍÈÁÄÈ¢

void find_files_i(std:: vector<std:: string> *pFiles, const std:: set<std:: string> &extensions,
		const std:: string &currentDir)
{
	DIR *dp;
	struct dirent *dir;
	struct stat fi;

	if ((dp = opendir(currentDir.c_str())) == NULL) {
		assert(("fail to open directory" /*, false*/)); // 2007/11/22
	}

	while ((dir = readdir(dp)) != NULL) {
		if (dir->d_ino == 0) {
			continue;
		}
		stat(dir->d_name, &fi);
		std:: string fileName = dir->d_name;
		if (S_ISDIR(fi.st_mode)) {
			if (! (fileName == "." || fileName == "..")) {
				std:: string dir = currentDir + fileName;
				if (dir.length() > 0 && dir[dir.length() - 1] != '/') {
					dir += "/";
				}
				if (_chdir(escape_spaces(fileName).c_str()) != -1) {
					find_files_i(pFiles, extensions, dir);
					_chdir("..");
				}
			}
		}
		else {
			std:: string filePath = currentDir + fileName;
			for (std:: set<std:: string>::const_iterator i = extensions.begin(); i != extensions.end(); ++i) {
				std:: string ext = *i;
				std:: string fileExt = filePath.substr(filePath.length() - ext.length());
				if (filePath.length() >= ext.length() && strcmpi(filePath.c_str() + filePath.length() - ext.length(), ext.c_str()) == 0) {
					(*pFiles).push_back(filePath);
					break; // for i
				}
			}
		}
	}

	closedir(dp); // 2007/11/22
}

void find_named_directories_i(std:: vector<std:: string> *pFiles, const std:: set<std:: string> &names,
		const std:: string &currentDir)
{
	DIR *dp;
	struct dirent *dir;
	struct stat fi;

	if ((dp = opendir(currentDir.c_str())) == NULL) {
		assert(("fail to open directory" /*, false*/)); // 2007/11/22
	}

	while ((dir = readdir(dp)) != NULL) {
		if (dir->d_ino == 0) {
			continue;
		}
		stat(dir->d_name, &fi);
		std:: string fileName = dir->d_name;
		if (S_ISDIR(fi.st_mode)) {
			if (! (fileName == "." || fileName == "..")) {
				std:: string dir = currentDir + fileName;
				if (names.find(fileName) != names.end()) {
					(*pFiles).push_back(dir);
				}
				if (dir.length() > 0 && dir[dir.length() - 1] != '/') {
					dir += "/";
				}
				if (_chdir(escape_spaces(fileName).c_str()) != -1) {
					find_named_directories_i(pFiles, names, dir);
					_chdir("..");
				}
			}
		}
	}

	closedir(dp);
}

#endif

} // namespace

bool find_files(std:: vector<std:: string> *pFiles, const std:: set<std:: string> &extensions,
		const std:: string &directory)
{
	(*pFiles).clear();

	char *szCurrentDir = _getcwd(NULL, 0);
	if (szCurrentDir == NULL) {
		return false; // failure
	}
	std:: string currentDir(szCurrentDir);
	free(szCurrentDir);

	std:: string dir = directory;
	int ch;
	if (dir.length() > 0 && ! ((ch = dir[dir.length() - 1]) == '/' || ch == '\\')) {
#if defined OS_WIN32
		dir += "\\";
#elif defined OS_UNIX || defined OS_UBUNTU
		dir += "/";
#else
#error
#endif
	}
	if (_chdir(dir.c_str()) == -1) {
		return false; // failure
	}

	find_files_i(pFiles, extensions, dir);

	_chdir(currentDir.c_str());

	return true;
}

bool find_named_directories(std:: vector<std:: string> *pFiles, const std:: set<std:: string> &names,
		const std:: string &directory)
{
	(*pFiles).clear();

	char *szCurrentDir = _getcwd(NULL, 0);
	if (szCurrentDir == NULL) {
		return false; // failure
	}
	std:: string currentDir(szCurrentDir);
	free(szCurrentDir);

	std:: string dir = directory;
	int ch;
	if (dir.length() > 0 && ! ((ch = dir[dir.length() - 1]) == '/' || ch == '\\')) {
#if defined OS_WIN32
		dir += "\\";
#elif defined OS_UNIX || defined OS_UBUNTU
		dir += "/";
#else
#error
#endif
	}
	if (_chdir(dir.c_str()) == -1) {
		return false; // failure
	}

	find_named_directories_i(pFiles, names, dir);

	_chdir(currentDir.c_str());

	return true;
}

#if defined LITTLE_ENDIAN

void flip_endian(void* UNUSED(pIntegerValue), size_t UNUSED(sizeOfIntegerType))
{
}

#else

void flip_endian(void *pIntegerValue, size_t sizeOfIntegerType)
{
	unsigned char *buffer = (unsigned char *)(void *)pValue;
	unsigned char *p = buffer;
	unsigned char *q = buffer + sizeOfIntegerType - 1;
	for (size_t i = 0; i < sizeOfIntegerType / 2; ++i) {
		unsigned char b = *p; *p = *q; *q = b;
		++p;
		--q;
	}
}

//void flip_endian(int *pValue)
//{
//	unsigned char *buffer = (unsigned char *)(void *)pValue;
//	unsigned char *p = buffer;
//	unsigned char *q = buffer + sizeof(int) - 1;
//	for (size_t i = 0; i < sizeof(int) / 2; ++i) {
//		unsigned char b = *p; *p = *q; *q = b;
//		++p;
//		--q;
//	}
//}
//
//void flip_endian(long *pValue)
//{
//	unsigned char *buffer = (unsigned char *)(void *)pValue;
//	unsigned char *p = buffer;
//	unsigned char *q = buffer + sizeof(long) - 1;
//	for (size_t i = 0; i < sizeof(long) / 2; ++i) {
//		unsigned char b = *p; *p = *q; *q = b;
//		++p;
//		--q;
//	}
//}
//
//void flip_endian(long long *pValue)
//{
//	unsigned char *buffer = (unsigned char *)(void *)pValue;
//	unsigned char *p = buffer;
//	unsigned char *q = buffer + sizeof(long long) - 1;
//	for (size_t i = 0; i < sizeof(long long) / 2; ++i) {
//		unsigned char b = *p; *p = *q; *q = b;
//		++p;
//		--q;
//	}
//}

#endif

#if defined _MSC_VER

void nice(int value)
{
	if (value > 10) {
		::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
	}
	else if (value == 10) {
		::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_NORMAL);
	}
	else {
		::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
	}
}

bool allocWorkingSetMemory(long long size)
{
	BOOL success = ::SetProcessWorkingSetSize(::GetCurrentProcess(), 1, size);
	return success != 0;
}

#endif

#if defined OS_WIN32

std::string build_system_string(const std::vector<std::string> &argv)
{
	std::string buffer;
	for (size_t i = 0; i < argv.size(); ++i) {
		if (i > 0) {
			buffer.append(" ");
		}
		std::string argvi = argv[i];
		if (argvi.find(' ') != std::string::npos) {
			if (argvi.length() > 0 && argvi[0] != '\"') {
				argvi = "\"" + argvi + "\"";
			}
		}
		buffer.append(argvi);
	}
	return buffer;
}

#else

std::string build_system_string(const std::vector<std::string> &argv)
{
	std::string buffer;
	for (size_t i = 0; i < argv.size(); ++i) {
		if (i > 0) {
			buffer.append(" ");
		}
		std::string argvi = argv[i];
		buffer.append(argvi);
	}
	return buffer;
}

#endif

// may cause problems in a EUC like character encodings.

std::string join_path(const std::string &s1, const std::string &s2)
{
	if (s1.length() >= 1 && *last_char(s1.c_str()) == '/') {
		return s1 + s2;
	}
#if defined OS_WIN32
	if (s1.length() >= 1 && *last_char(s1.c_str()) == '\\') {
		return s1 + s2;
	}
#endif

	return s1 + file_separator() + s2;
}

bool path_exists(const std::string &path)
{
	struct stat fileStatus;
	if (stat(path.c_str(), &fileStatus) != 0) {
		return false;
	}
	return true;
}

bool path_is_file(const std::string &path)
{
	struct stat fileStatus;
	if (stat(path.c_str(), &fileStatus) != 0) {
		return false; // error (maybe file doesn't exist
	}

	return (fileStatus.st_mode & S_IFMT) == S_IFREG;
}

#if defined __GNUC__

int systemv(const std::vector<std::string> &argv)
{
	std::string buf;

	for (size_t i = 0; i < argv.size(); ++i) {
		std::string s = escape_spaces(argv[i]);
		buf += s;
		buf += " ";
	}
	if (buf.length() > 0) {
		buf.erase(buf.length() - 1);
	}

	return system(buf.c_str());
}

#endif

boost::optional<std::string> getenvironmentvariable(const std::string &name)
{
#if defined _MSC_VER && _MSC_VER >= 1400
	char *buf;
	errno_t err = _dupenv_s(&buf, NULL, name.c_str());
	assert(err == 0);
	if (buf != NULL) {
		boost::optional<std::string> s;
		s = buf;
		free(buf);
		return s;
	}
	return boost::optional<std::string>();
#else
	const char *p = getenv(name.c_str());
	if (p != NULL) {
		boost::optional<std::string> s;
		s = p;
		return s;
	}
	return boost::optional<std::string>();
#endif
}

#if defined _MSC_VER

boost::optional<std::string> get_short_path_name(const std::string &path0)
{
	std::string path = path0;

	DWORD bufSize = ::GetShortPathName(path.c_str(), NULL, 0);
	if (bufSize == 0) {
		std::string dir;
		std::string fname;
		std::string ext;
		if (! splitpath(path, &dir, &fname, &ext)) {
			return boost::optional<std::string>(); // fail
		}
		if (dir.empty() || fname.empty() && ext.empty()) {
			return boost::optional<std::string>(); // fail
		}
		boost::optional<std::string> t = get_short_path_name(dir);
		if (t) {
			path = *t + fname + ext;
		}
		bufSize = ::GetShortPathName(path.c_str(), NULL, 0);
		if (bufSize == 0) {
			return boost::optional<std::string>(); // fail
		}
	}
	std::vector<char> buf(bufSize + 1);
	DWORD strLen = ::GetShortPathName(path.c_str(), &buf[0], bufSize);
	if (strLen == 0) {
		return boost::optional<std::string>(); // fail
	}
	assert(strLen <= bufSize);
	boost::optional<std::string> r;
	r = std::string((char *)&buf[0], strLen);
	return r;
}

boost::optional<std::string> reg_query_value(const std::string &path, const std::string &key)
{
	HKEY hKey;

	LONG r = ::RegOpenKeyEx(HKEY_CURRENT_USER, path.c_str(), 0, KEY_QUERY_VALUE, &hKey);
	if (r != ERROR_SUCCESS) {
		return boost::optional<std::string>(); // fail
	}

	DWORD dwType;
	DWORD dwSize;
	r = ::RegQueryValueEx(hKey, key.c_str(), NULL, &dwType, NULL, &dwSize);
	if (r != ERROR_SUCCESS) {
		return boost::optional<std::string>(); // fail
	}
	if (dwType != REG_SZ) {
		return boost::optional<std::string>(); // fail
	}

	std::vector<char> buf(dwSize);
	::RegQueryValueEx(hKey, key.c_str(), NULL, &dwType, (LPBYTE)&buf[0], &dwSize);
	if (r != ERROR_SUCCESS) {
		return boost::optional<std::string>(); // fail
	}

	assert(buf.size() >= 1);
	assert(buf[buf.size() - 1] == '\0');
	std::string value(&buf[0], buf.size() - 1);

	::RegCloseKey(hKey);

	return value;
}

#endif

ext: cpp

max_stars_repo_name: yoriyuki-aist/ccfinderx

max_issues_repo_name: yoriyuki-aist/ccfinderx

max_forks_repo_name: yoriyuki-aist/ccfinderx


text:
#ifndef SIMPLE_KADEMLIA_PROTOCOL_HPP
#define SIMPLE_KADEMLIA_PROTOCOL_HPP

#include "node/nodeinfo.hpp"
#include "routing tree/routingtree.hpp"
#include "callbacks.hpp"
#include <boost/asio.hpp>
#include <thread>
#include <messages/responseMessage.hpp>
#include <messages/queryMessage.hpp>
#include <queue>

namespace kdml {

    namespace net {
        class Network;
    }

    struct NodeInfoWrapper {
        boost::multiprecision::uint256_t key;
        NodeInfo node;

        NodeInfoWrapper(boost::multiprecision::uint256_t key, NodeInfo node) {
            this->key = key;
            this->node = node;
        }
    };

    static bool node_comp (NodeInfoWrapper a, NodeInfoWrapper b) {
        return (a.key ^ a.node.id) < (b.key ^ b.node.id);
    }

    class NodeComparison {
    public:
        bool operator() (NodeInfoWrapper a, NodeInfoWrapper b) {
            return node_comp(a, b);
        }
    };

    struct RequestState {
        boost::multiprecision::uint256_t key;
        GetCallback callback;
        int responses_waiting {0};
        bool findValue {false};
        bool store {false};

        std::set<boost::multiprecision::uint256_t> queried_nodes;
        std::set<boost::multiprecision::uint256_t> responded_nodes;

        std::set<NodeInfoWrapper, NodeComparison> k_closest_nodes;
    };

    class Protocol {

        NodeInfo owner;
        net::Network* network;
        RoutingTree routingTable;

        std::map<boost::multiprecision::uint256_t, Nodes> storage;

        boost::asio::io_service ioService;
        std::unique_ptr<boost::asio::io_service::work> ioLock;

        std::thread ioThread;

        void handleMessage(std::shared_ptr<net::Message> msg, NodeInfo sender);
        void handleQuery(std::shared_ptr<net::QueryMessage> msg, NodeInfo sender);
        void handleResponse(std::shared_ptr<net::ResponseMessage> msg);

        void probePeers(Nodes endpoints);
        Nodes resolveEndpoint(const NodeInfo& ep);

        //map of keys -> request state for lookup procedure
        std::map<boost::multiprecision::uint256_t, RequestState> lookups;

        void node_lookup_callback(mp::uint256_t sender, RequestState& request_state, Nodes k_nodes,
                                            mp::uint256_t key, bool found);

        void find_value_callback(Nodes nodes, bool found, GetCallback callback);
        void store_callback(boost::multiprecision::uint256_t key, Nodes nodes);

    public:

        // number of concurrent lookups in node lookup
        static const int ALPHA = 3;

        explicit Protocol(const NodeInfo& owner);

        void async_get(boost::multiprecision::uint256_t key, kdml::GetCallback callback);
        void async_store(boost::multiprecision::uint256_t key, NodeInfo value);

        void bootstrap(const NodeInfo& peer);
        void join();

        NodeInfo getOwner() { return owner; };

        void node_lookup(mp::uint256_t key, GetCallback callback, bool findValue, bool store);
        void handleReceive(const boost::system::error_code& error,
                           std::size_t /*bytes_transferred*/);

    };
}

#endif //SIMPLE_KADEMLIA_PROTOCOL_HPP

max_stars_repo_name: jakerachleff/simple-kademlia

max_issues_repo_name: jakerachleff/simple-kademlia

max_forks_repo_name: jakerachleff/simple-kademlia