text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2015-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/move for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_MOVE_TEST_ORDER_TYPE_HPP
#define BOOST_MOVE_TEST_ORDER_TYPE_HPP

#include <boost/config.hpp>
#include <boost/move/core.hpp>
#include <cstddef>
#include <cstdio>

struct order_perf_type
{
   public:
   std::size_t key;
   std::size_t val;

   order_perf_type()
   {
      ++num_elements;
   }

   order_perf_type(const order_perf_type& other)
      : key(other.key), val(other.val)
   {
      ++num_elements;
      ++num_copy;
   }

   order_perf_type & operator=(const order_perf_type& other)
   {
      ++num_copy;
      key = other.key;
      val = other.val;
      return *this;
   }

   ~order_perf_type ()
   {
      --num_elements;
   }

   static void reset_stats()
   {
      num_compare=0;
      num_copy=0;
   }

   friend bool operator< (const order_perf_type& left, const order_perf_type& right)
   {  ++num_compare; return left.key < right.key;  }

   static boost::ulong_long_type num_compare;
   static boost::ulong_long_type num_copy;
   static boost::ulong_long_type num_elements;
};

boost::ulong_long_type order_perf_type::num_compare = 0;
boost::ulong_long_type order_perf_type::num_copy = 0;
boost::ulong_long_type order_perf_type::num_elements = 0;

struct order_move_type
{
   BOOST_MOVABLE_BUT_NOT_COPYABLE(order_move_type)

   public:
   std::size_t key;
   std::size_t val;

   static const std::size_t moved_constr_mark = std::size_t(-1);
   static const std::size_t moved_assign_mark = std::size_t(-2);

   order_move_type()
      : key(0u), val(0u)
   {}

   order_move_type(BOOST_RV_REF(order_move_type) other)
      : key(other.key), val(other.val)
   {
      other.key = other.val = std::size_t(-1);
   }

   order_move_type & operator=(BOOST_RV_REF(order_move_type) other)
   {
      key = other.key;
      val = other.val;
      other.key = other.val = std::size_t(-2);
      return *this;
   }

   friend bool operator< (const order_move_type& left, const order_move_type& right)
   {  return left.key < right.key;  }

   ~order_move_type ()
   {
      key = val = std::size_t(-3);
   }
};

struct order_type_less
{
   template<class T, class U>
   bool operator()(const T &a, U const &b) const
   {  return a < b;   }
};

template<class T>
inline bool is_order_type_ordered(T *elements, std::size_t element_count, bool stable = true)
{
   for(std::size_t i = 1; i < element_count; ++i){
      if(order_type_less()(elements[i], elements[i-1])){
         std::printf("\n Ord KO !!!!");
         return false;
      }
      if( stable && !(order_type_less()(elements[i-1], elements[i])) && (elements[i-1].val > elements[i].val) ){
         std::printf("\n Stb KO !!!! ");
         return false;
      }
   }
   return true;
}

namespace boost {
namespace movelib {
namespace detail_adaptive {

}}}

template<class T>
inline bool is_key(T *elements, std::size_t element_count)
{
   for(std::size_t i = 1; i < element_count; ++i){
      if(elements[i].key >= element_count){
         std::printf("\n Key.key KO !!!!");
         return false;
      }
      if(elements[i].val != std::size_t(-1)){
         std::printf("\n Key.val KO !!!!");
         return false;
      }
   }
   return true;
}

template<class T>
inline bool is_buffer(T *elements, std::size_t element_count)
{
   for(std::size_t i = 1; i < element_count; ++i){
      if(elements[i].key != std::size_t(-1)){
         std::printf("\n Buf.key KO !!!!");
         return false;
      }
      if(elements[i].val >= element_count){
         std::printf("\n Buf.val KO !!!!");
         return false;
      }
   }
   return true;
}

#endif   //BOOST_MOVE_TEST_ORDER_TYPE_HPP

ext: hpp


text:
#ifndef WZP_EIGEN_MATRIX_HPP_
#define WZP_EIGEN_MATRIX_HPP_

/**
 * This is just a wapper for eigen matrix(DYNAMIC)
 */
#include <cassert>

#include <Eigen/Dense>

namespace wzp
{

template<typename Dtype>
class EMatrix {
private:
    // the alias for inner use of raw eigen matrix
    template<typename F>
    using RawMatrix = Eigen::Matrix<F, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;

    // define the index type
    typedef Eigen::Index Index;

public:
    /**
     * Constructors
     */
    // default contructor
    EMatrix() : m_mat() {}

    // construct by size
    EMatrix(Index m) : m_mat(m, m) { InitByValue(0); }

    // construct by two size
    EMatrix(Index m, Index n, Dtype init_val = 0) : m_mat(m, n) {InitByValue(init_val); }

    // construct by raw point
    EMatrix(Index m, Index n, Dtype* raw_data_ptr) {
        m_mat = std::move(Eigen::Map<RawMatrix<Dtype>>(raw_data_ptr, m, n));
    }

    // construct by datas
    EMatrix(RawMatrix<Dtype>&& raw_mat) : m_mat(std::move(raw_mat)) {}
    EMatrix(const RawMatrix<Dtype>& raw_mat) : m_mat(raw_mat) {}

    // move construct
    EMatrix(EMatrix<Dtype>&& other) : m_mat(std::move(other.m_mat)) { }

    // move operator
    EMatrix<Dtype>& operator= (EMatrix<Dtype>&& other) {
        assert(this != &other);
        m_mat = std::move(other.m_mat);
        return *this;
    }

    // copy constructor
    EMatrix(const EMatrix<Dtype>&) = default;
    EMatrix<Dtype>& operator= (const EMatrix<Dtype>&) = default;

    // get the raw matrix
    inline RawMatrix<Dtype>& get_raw_mat() { return m_mat; }
    inline const RawMatrix<Dtype>& get_raw_mat() const { return m_mat; }

    /**
     * reshape functions
     */
    inline void reshape(Index m, Index n) {
        if(m == m_mat.rows() && n == m_mat.cols()) return;
        m_mat.resize(m, n);
    }

    /**
     * transpose and adjoint
     */
    // transpose
    EMatrix<Dtype> transpose() const {
        auto tmp = m_mat.transpose();
        return EMatrix<Dtype>(std::move(tmp));
    }

    // adjoint
    EMatrix<Dtype> adjoint() const {
        auto tmp = m_mat.adjoint();
        return EMatrix<Dtype>(std::move(tmp));
    }

    /**
     * operations by contant value
     */
    // scalar product
    EMatrix<Dtype> operator* (Dtype val) const {
        auto tmp = m_mat * val;
        return EMatrix<Dtype>(std::move(tmp));
    }

    EMatrix<Dtype>& operator*= (Dtype val) {
        m_mat *= val;
        return *this;
    }

    // scalar +
    EMatrix<Dtype> operator+ (Dtype val) const {
        auto tmp = m_mat + val;
        return EMatrix<Dtype>(std::move(tmp));
    }

    EMatrix<Dtype>& operator+= (Dtype val) {
        m_mat += val;
        return *this;
    }

    // scalar -
    EMatrix<Dtype> operator- (Dtype val) const {
        auto tmp = m_mat - val;
        return EMatrix<Dtype>(std::move(tmp));
    }

    EMatrix<Dtype>& operator-= (Dtype val) {
        m_mat -= val;
        return *this;
    }

    // matrix dot product
    EMatrix<Dtype> operator* (const EMatrix<Dtype>& other) const {
        auto tmp = m_mat * other.get_raw_mat();
        return EMatrix<Dtype>(std::move(tmp));
    }

    // matrix add function
    EMatrix<Dtype> operator+ (const EMatrix<Dtype>& other) const {
        if(other.rows() == 1) {
            assert(other.cols() == cols());
            EMatrix<Dtype> tmp_mat(*this);
            for(Index i = 0; i < rows(); ++i) {
                for(Index j = 0; j < cols(); ++j) {
                    tmp_mat.at(i, j) += other(0, j);
                }
            }
            return tmp_mat;
        } else if(other.cols() == 1) {
            assert(other.rows() == rows());
            EMatrix<Dtype> tmp_mat(*this);
            for(Index j = 0; j < cols(); ++j) {
                for(Index i = 0; i < rows(); ++i) {
                    tmp_mat.at(i, j) += other(i, 0);
                }
            }
            return tmp_mat;
        } else {
            auto tmp = m_mat + other.get_raw_mat();
            return EMatrix<Dtype>(std::move(tmp));
        }
    }

    EMatrix<Dtype>& operator+= (const EMatrix<Dtype>& other) {
        if(other.rows() == 1) {
            assert(other.cols() == cols());
            for(Index i = 0; i < rows(); ++i) {
                for(Index j = 0; j < cols(); ++j) {
                    at(i, j) += other(0, j);
                }
            }
        } else if(other.cols() == 1) {
            assert(other.rows() == rows());
            EMatrix<Dtype> tmp_mat(*this);
            for(Index j = 0; j < cols(); ++j) {
                for(Index i = 0; i < rows(); ++i) {
                    at(i, j) += other(i, 0);
                }
            }
        } else {
            m_mat += other.get_raw_mat();
        }
        return *this;
    }

    /**
     * Block
     */
    EMatrix<Dtype> block(Index i, Index j, Index h, Index w) const {
        auto tmp = m_mat.block(i, j, h, w);
        return EMatrix<Dtype>(std::move(tmp));
    }

    EMatrix<Dtype> row(Index i) const {
        auto tmp = m_mat.row(i);
        return EMatrix<Dtype>(std::move(tmp));
    }

    EMatrix<Dtype> col(Index j) const {
        auto tmp = m_mat.col(j);
        return EMatrix<Dtype>(std::move(tmp));
    }

    void mutable_row(Index i, const EMatrix<Dtype>& row_vec) {
        m_mat.row(i) = row_vec.get_raw_mat();
    }

    void mutable_col(Index j, const EMatrix<Dtype>& col_vec) {
        m_mat.col(j) = col_vec.get_raw_mat();
    }

    /**
     * Getters
     */
    inline bool empty() const { return m_mat.rows() == 0; }
    inline Index rows() const { return m_mat.rows(); }
    inline Index cols() const { return m_mat.cols(); }
    inline Dtype at(Index i, Index j) const { return m_mat(i, j); }
    inline Dtype& at(Index i, Index j) { return m_mat(i, j); }
    inline Dtype operator() (Index i, Index j) const { return at(i, j); }
    inline Dtype& operator() (Index i, Index j) { return at(i, j); }
    inline Dtype at(Index i) const { return m_mat(i); }
    inline Dtype& at(Index i) { return m_mat(i); }
    inline Dtype operator() (Index i) const { return at(i); }
    inline Dtype& operator() (Index i) { return at(i); }

    /**
     * some simple function
     */
    inline Dtype sum() const { return m_mat.sum(); }
    inline Dtype prod() const { return m_mat.prod(); }
    inline Dtype min() const { return m_mat.minCoeff(); }
    inline Dtype max() const { return m_mat.maxCoeff(); }
    inline Dtype trace() const { return m_mat.trace(); }

    /**
     * the print functions
     */
    inline friend std::ostream& operator<<(std::ostream &os, const EMatrix<Dtype>& e) {
        os << e.m_mat;
        return os;
    }

private:
    //the contranier of matrix datas
    RawMatrix<Dtype> m_mat;

private:

    void InitByValue(Dtype val) {
        Index length = m_mat.rows() * m_mat.cols();
        for(Index i = 0; i < length; ++i) {
            m_mat(i) = val;
        }
    }

public:
    // the function to apply element wise operation
    template<typename Fun, typename... Args>
    void element_apply(Index i, Index j, Index p, Index q, Fun&& fun, Args&&... args) {
        assert(i >= 0 && j >= 0 && i + p < rows() && j + q < cols());
        for(Index ii = i; ii < i + p; ++ii) {
            for(Index jj = j; jj < j + q; ++jj) {
                m_mat(ii, jj) = fun(std::forward<Args>(args)...);
            }
        }
    }

};

} //wzp

#endif /*WZP_EIGEN_MATRIX_HPP_*/

max_stars_repo_name: wzppengpeng/LittleConv

max_issues_repo_name: wzppengpeng/LittleConv

max_forks_repo_name: wzppengpeng/LittleConv


text:
/*
The MIT License

Copyright 2019 hiratake26to

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once

#include <iostream>
#include <optional>
#include <sstream>
#include <string>
#include <list>
#include <vector>
#include <functional>
#include <algorithm>
#include <utility>
#include <map>
#include <typeinfo>
#include <any>
#include <variant>
#include <boost/core/demangle.hpp>
#include "../schedule/schedule.hpp"

using std::cout;
using std::endl;
using std::optional;
using std::string;
using std::vector; // should not use reference to a element of vector.
using std::list; // allow to use reference of a element.
using std::pair;
using std::map;
using std::type_info;
using std::any;

#include "entity/entity.hpp"

namespace tgim {
// box
class Box {
private:
  // [TODO] 名前をポインタとして使ってしまっているので, 別途ポインタを用意する?
  string name_;
  string type_;
  Point point_;
  Schedule schedule_;

public:
  // NOTE mutable is meaning that allow returning reference from 'const function'
  mutable list<Node> nodes;
  mutable list<Channel> channels;
  mutable list<Port2> ports; // ports is channels which has used by box connecting.

public:
  Box(string name, string type);
  Box& SetName(string name);
  Box& SetType(string type);
  Box& SetPoint(Point pt);
  string GetName() const;
  string GetType() const;
  vector<string> GetPorts() const;
  Point GetPoint() const;
  string AsHost() const;
  //int PortNum(string) const;
  Box Fork(string name) const;
  Box Fork(string name, string type) const;
  Channel& CopyChannel(string src, string dst);
  Channel& CreateChannel(string name, string type);
  Node& CopyNode(string src, string dst);
  Node& CreateNode(string name, string type);
  Port2& CreatePort(const string& from_this_channel_name, const string& port_name);
  void ConnectNodeToChannel(const string& node_name, const string& channel_name, const vector<string>& roles = {});
  void ConnectPort(const string& from_this_port_name, Box& to_box, const string& to_box_port_name);
  void SetPortMaxConnection(const string& port_name, int num);
  void TriConnect(string node_name, string channel_name, string port_name);
  void TriConnect(vector<string> node_roles, string node_name, string channel_name, string port_name);

  optional<std::reference_wrapper<Channel>> FindChannel(string name) const;
  optional<std::reference_wrapper<Node>> FindNodeFromType(string type) const;
  optional<std::reference_wrapper<Node>> FindNode(string name) const;
  optional<std::reference_wrapper<Port2>> FindPort2(string name) const;

  //optional<string> ResolveConn(string channel_name) const;
  vector<string> ResolveConn(string channel_name) const;

  ScheduleControllBlock At(EventSpecifer es);
  ScheduleControllBlock Sdl2();
  ScheduleControllBlock Sdl(const Schedule& sdl);
  Schedule GetSchedule() const;
  string DumpSchedule() const;
  string ToString(int level=0) const;
  vector<Task> FlattenSchedule() const;
  void ClearSchedule();

  vector<Netif> GenNodeConnList(const Node& node) const;
  void Mangle();

private:
  vector<Event> SearchPrimitiveEvents(const vector<Task>& sdl, const Task& task) const;
  static vector<Event> SearchPrimitiveEvents(const vector<Task>& sdl, const Task& task, vector<Task>& breadcrumb);
  optional<string> CheckInvalidChannel(const Channel& from_channel, const Channel& to_channel);
  // not recommendation for user to use
  void AddTask(Event evt, Action action);
  vector<Task> FlattenSchedule(const Schedule& sdl,int callid=0) const;
  string PrefixBox(string name) const;
  string PrefixNode(string name) const;
  string PrefixChannel(string name) const;
  string PrefixPort(string name) const;
  string PrefixTag(string name) const;
};
}


text:
#include "raft_test_log_gen.h"
#include "proto/proto.h"
#include "common/json_pretty.h"
#include <boost/filesystem.hpp>
#include <fstream>

void raft_test_log_gen() {
  raft_test_log l;
  uint64_t term = 12;
  log_state *s = l.mutable_state();
  s->set_consistency_index(0);
  s->set_term(term);
  s->set_vote(0);
  s->set_commit_index(0);
  uint64_t num_tx = 2;
  uint64_t num_e = 10;
  for (uint64_t i = 0; i < num_e; i++) {
    uint64_t index = i + 1;
    auto e = l.add_entries();
    e->set_index(index);
    e->set_term(term);
    for (uint64_t j = 0; j < num_tx; j++) {
      auto x = e->add_xlog();
      x->set_log_type(tx_cmd_type::TX_CMD_RM_COMMIT);
      x->set_xid(1000 * (i + 1) + (j + 1));
      x->set_index(index);
    }
  }

  std::string json = pb_to_json(l);
  std::stringstream ssm;
  ssm << pb_to_json(l);
  boost::filesystem::path p(__FILE__);
  p = p.parent_path().append("raft_test.json");
  std::ofstream of(p.c_str());
  json_pretty(ssm, of);
}

ext: cpp

max_stars_repo_name: ybbhwxfj/block-db

max_issues_repo_name: ybbhwxfj/block-db

max_forks_repo_name: ybbhwxfj/block-db


text:
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include <vapor/vpvoid.hpp>

using namespace std;
using namespace vapor;

BOOST_AUTO_TEST_SUITE(test_suite1)

BOOST_AUTO_TEST_CASE(vpvoid_serialize)
{
    vparchive_t expect, result;
    vpvoid vpnull1;

    expect = vpvoid::SERIALIZED;
    result = vpnull1.serialize();
    BOOST_REQUIRE_EQUAL(expect, result);
}

BOOST_AUTO_TEST_CASE(vpvoid_deserialize)
{
    vpvoid expect, result;
    vparchive_t a;

    try {
        result.deserialize("none;0;");
        BOOST_FAIL("bad type shoud fail: void");
    }
    catch (invalid_argument ex) {}

    result.deserialize(vpvoid::SERIALIZED);
    BOOST_REQUIRE_EQUAL(expect, result);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: prodigeinfo/libvapor

max_issues_repo_name: prodigeinfo/libvapor

max_forks_repo_name: prodigeinfo/libvapor


text:
/* Copyright Institute of Sound and Vibration Research - All rights reserved */

#ifndef VISR_LIBRRL_SCHEDULING_GRAPH_HPP_INCLUDED
#define VISR_LIBRRL_SCHEDULING_GRAPH_HPP_INCLUDED

#include "parameter_connection_map.hpp"

#include <libvisr/constants.hpp>
// #include <libvisr/parameter_port_base.hpp> // Temporary fix (otherwise

#include <ciso646>
#include <iosfwd>
#include <map>
#include <memory>
#include <ostream>
#include <stdexcept>
#include <tuple>
#include <vector>

#include <boost/graph/adjacency_list.hpp>

namespace visr
{
// Forward declarations
class AtomicComponent; // TODO: Replace by ExecutableInterface at some point?
namespace impl
{
class ComponentImplementation;
class ParameterPortBaseImplementation;
}

namespace rrl
{
// Forward declarations
class AudioConnectionMap;
class AudioChannel;

class SchedulingGraph
{
public:
  SchedulingGraph();

  /**
   * Destructor.
   */
  ~SchedulingGraph();

  void initialise( impl::ComponentImplementation const & flow,
                   AudioConnectionMap const & audioConnections,
                   ParameterConnectionMap const & parameterConnections );

  std::vector<AtomicComponent *> sequentialSchedule() const;

private:

  /**
   * Check whether the graph contains a closed delay-free loop.
   * @param messages Output stream to receive error messages and informational messages.
   * @return True is the graph is loop-free, false otherwise.
   */
  bool checkAcyclicGraph( std::ostream & messages ) const;

  enum class NodeType
  {
    Source,
    Sink,
    Processor
  };

  struct ProcessingNode: public std::tuple<NodeType, impl::ComponentImplementation const *>
  {
  public:
    ProcessingNode();

    explicit ProcessingNode( NodeType nodeType );

    explicit ProcessingNode( impl::ComponentImplementation const * atom );

    explicit ProcessingNode( NodeType nodeType, impl::ComponentImplementation const * atom );

    impl::ComponentImplementation const * node() const { return std::get<1>(*this); }

    NodeType type() const { return std::get<0>(*this); }

  private:
  };

  using GraphType = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, ProcessingNode >;

  GraphType mDependencyGraph;

  ProcessingNode const & getNode( GraphType::vertex_descriptor vertex ) const;

  std::string nodeName( ProcessingNode const & node ) const;

  /**
   * Insert a new edge into the dependency graph.
   * @throw std::logic_error If the edge already exists
   * @throw std::runtime_error If the edge insertion fails (likely an internal failure of the graph library).
   */
  void insertDependencyEdge( GraphType::vertex_descriptor sourceVertex, GraphType::vertex_descriptor destVertex );

//  using VertexMap = std::map<ProcessingNode, GraphType::vertex_descriptor, CompareProcessingNodes >;
  using VertexMap = std::map<ProcessingNode, GraphType::vertex_descriptor >;

  VertexMap mVertexLookup;

  GraphType::vertex_descriptor mSourceVertex;

  GraphType::vertex_descriptor mSinkVertex;
};

} // namespace rrl
} // namespace visr

#endif // #ifndef VISR_LIBRRL_SCHEDULING_GRAPH_HPP_INCLUDED


text:
// Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, version 2.0,
// as published by the Free Software Foundation.
//
// This program is also distributed with certain software (including
// but not limited to OpenSSL) that is licensed under separate terms,
// as designated in a particular file or component or in included license
// documentation.  The authors of MySQL hereby grant you an additional
// permission to link the program and your derivative works with the
// separately licensed software that they have included with MySQL.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License, version 2.0, for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA.

/// @file
///
/// This file implements utility functions for working with geometrycollections.

#include "sql/gis/gc_utils.h"

#include <boost/geometry.hpp>  // boost::geometry::difference

#include "my_dbug.h"  // DBUG_ASSERT
#include "sql/gis/difference_functor.h"
#include "sql/gis/geometries.h"
#include "sql/gis/geometries_cs.h"
#include "sql/gis/geometries_traits.h"
#include "sql/gis/union_functor.h"
#include "template_utils.h"  // down_cast

namespace bg = boost::geometry;

namespace gis {

template <typename Pt, typename Ls, typename Py, typename GC, typename MPt,
          typename MLs, typename MPy>
static void typed_split_gc(const GC *gc, MPt *mpt, MLs *mls, MPy *mpy) {
  DBUG_ASSERT(gc->coordinate_system() == mpt->coordinate_system() &&
              gc->coordinate_system() == mls->coordinate_system() &&
              gc->coordinate_system() == mpy->coordinate_system());

  for (const auto g : *gc) {
    switch (g->type()) {
      case Geometry_type::kPoint:
        mpt->push_back(*down_cast<Pt *>(g));
        break;
      case Geometry_type::kLinestring:
        mls->push_back(*down_cast<Ls *>(g));
        break;
      case Geometry_type::kPolygon:
        mpy->push_back(*down_cast<Py *>(g));
        break;
      case Geometry_type::kGeometrycollection:
        typed_split_gc<Pt, Ls, Py, GC, MPt, MLs, MPy>(down_cast<GC *>(g), mpt,
                                                      mls, mpy);
        break;
      case Geometry_type::kMultipoint: {
        const MPt *m = down_cast<const MPt *>(g);
        for (std::size_t i = 0; i < m->size(); i++)
          mpt->push_back(static_cast<const Pt &>((*m)[i]));
        break;
      }
      case Geometry_type::kMultilinestring: {
        const MLs *m = down_cast<const MLs *>(g);
        for (std::size_t i = 0; i < m->size(); i++)
          mls->push_back(static_cast<const Ls &>((*m)[i]));
        break;
      }
      case Geometry_type::kMultipolygon: {
        const MPy *m = down_cast<const MPy *>(g);
        for (std::size_t i = 0; i < m->size(); i++)
          mpy->push_back(static_cast<const Py &>((*m)[i]));
        break;
      }
      case Geometry_type::kGeometry:
        DBUG_ASSERT(false);
        break;
    }
  }
}

void split_gc(const Geometrycollection *gc, std::unique_ptr<Multipoint> *mpt,
              std::unique_ptr<Multilinestring> *mls,
              std::unique_ptr<Multipolygon> *mpy) {
  switch (gc->coordinate_system()) {
    case Coordinate_system::kCartesian:
      mpt->reset(new Cartesian_multipoint());
      mls->reset(new Cartesian_multilinestring());
      mpy->reset(new Cartesian_multipolygon());
      typed_split_gc<Cartesian_point, Cartesian_linestring, Cartesian_polygon,
                     Cartesian_geometrycollection, Cartesian_multipoint,
                     Cartesian_multilinestring, Cartesian_multipolygon>(
          down_cast<const Cartesian_geometrycollection *>(gc),
          down_cast<Cartesian_multipoint *>(mpt->get()),
          down_cast<Cartesian_multilinestring *>(mls->get()),
          down_cast<Cartesian_multipolygon *>(mpy->get()));
      break;
    case Coordinate_system::kGeographic:
      mpt->reset(new Geographic_multipoint());
      mls->reset(new Geographic_multilinestring());
      mpy->reset(new Geographic_multipolygon());
      typed_split_gc<Geographic_point, Geographic_linestring,
                     Geographic_polygon, Geographic_geometrycollection,
                     Geographic_multipoint, Geographic_multilinestring,
                     Geographic_multipolygon>(
          down_cast<const Geographic_geometrycollection *>(gc),
          down_cast<Geographic_multipoint *>(mpt->get()),
          down_cast<Geographic_multilinestring *>(mls->get()),
          down_cast<Geographic_multipolygon *>(mpy->get()));
      break;
  }
}

template <typename MPt, typename MLs, typename MPy>
void typed_gc_union(double semi_major, double semi_minor,
                    std::unique_ptr<Multipoint> *mpt,
                    std::unique_ptr<Multilinestring> *mls,
                    std::unique_ptr<Multipolygon> *mpy) {
  Difference difference(semi_major, semi_minor);
  Union union_(semi_major, semi_minor);

  std::unique_ptr<MPy> polygons(new MPy());
  for (auto &py : *down_cast<MPy *>(mpy->get())) {
    polygons.reset(down_cast<MPy *>(union_(polygons.get(), &py)));
    if (polygons->coordinate_system() == Coordinate_system::kGeographic &&
        polygons->is_empty()) {
      // The result of a union between a geographic multipolygon and a
      // geographic polygon is empty. There are two reasons why this may happen:
      //
      // 1. One of the polygons involved are invalid.
      // 2. One of the polygons involved covers half the globe, or more.
      //
      // Since invalid input is only reported to the extent it is explicitly
      // detected, we can simply return a too large polygon error in both cases.
      throw too_large_polygon_exception();
    }
  }

  std::unique_ptr<MLs> linestrings(new MLs());
  linestrings.reset(down_cast<MLs *>(difference(mls->get(), polygons.get())));

  std::unique_ptr<MPt> points(down_cast<MPt *>(
      difference(down_cast<MPt *>(mpt->get()), linestrings.get())));
  points.reset(down_cast<MPt *>(difference(points.get(), polygons.get())));

  mpy->reset(polygons.release());
  mls->reset(linestrings.release());
  mpt->reset(points.release());
}

void gc_union(double semi_major, double semi_minor,
              std::unique_ptr<Multipoint> *mpt,
              std::unique_ptr<Multilinestring> *mls,
              std::unique_ptr<Multipolygon> *mpy) {
  DBUG_ASSERT(mpt->get() && mls->get() && mpy->get());
  DBUG_ASSERT((*mpt)->coordinate_system() == (*mls)->coordinate_system() &&
              (*mpt)->coordinate_system() == (*mpy)->coordinate_system());
  // We're using empty GCs to detect invalid geometries, so empty geometry
  // collections should be filtered out before calling gc_union.
  DBUG_ASSERT(!(*mpt)->empty() || !(*mls)->empty() || !(*mpy)->empty());

  switch ((*mpt)->coordinate_system()) {
    case Coordinate_system::kCartesian: {
      typed_gc_union<Cartesian_multipoint, Cartesian_multilinestring,
                     Cartesian_multipolygon>(semi_major, semi_minor, mpt, mls,
                                             mpy);
      break;
    }
    case Coordinate_system::kGeographic: {
      typed_gc_union<Geographic_multipoint, Geographic_multilinestring,
                     Geographic_multipolygon>(semi_major, semi_minor, mpt, mls,
                                              mpy);
      break;
    }
  }

  // If all collections are empty, we've encountered at least one invalid
  // geometry.
  if ((*mpt)->empty() && (*mls)->empty() && (*mpy)->empty())
    throw invalid_geometry_exception();

  DBUG_ASSERT(mpt->get() && mls->get() && mpy->get());
  DBUG_ASSERT(!(*mpt)->empty() || !(*mls)->empty() || !(*mpy)->empty());
}

}  // namespace gis

ext: cc


text:
// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_GRID_SEARCH_HH
#define DUNE_STUFF_GRID_SEARCH_HH

#if HAVE_DUNE_GRID

#include <vector>

#include <boost/range/iterator_range.hpp>

#if HAVE_DUNE_GEOMETRY
#include <dune/geometry/referenceelements.hh>
#else
#include <dune/grid/common/genericreferenceelements.hh>
#endif
#include <dune/grid/common/gridview.hh>

#include <dune/stuff/aliases.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/grid/entity.hh>

namespace Dune {
namespace Stuff {
namespace Grid {

template <class GridViewType>
class EntitySearchBase
{
  typedef typename GridViewType::Traits ViewTraits;
  static_assert(std::is_base_of<GridView<ViewTraits>, GridViewType>::value,
                "GridViewType has to be derived from GridView!");

public:
  typedef typename ViewTraits::template Codim<0>::Entity EntityType;
  typedef typename EntityType::Geometry::LocalCoordinate LocalCoordinateType;
  typedef typename EntityType::Geometry::GlobalCoordinate GlobalCoordinateType;
  typedef std::vector<std::unique_ptr<EntityType>> EntityVectorType;
}; // class EntitySearchBase

template <class GridViewType>
class EntityInlevelSearch : public EntitySearchBase<GridViewType>
{
  typedef EntitySearchBase<GridViewType> BaseType;

  typedef typename GridViewType::template Codim<0>::Iterator IteratorType;

public:
  typedef typename BaseType::EntityVectorType EntityVectorType;

private:
  inline typename EntityVectorType::value_type check_add(const typename BaseType::EntityType& entity,
                                                         const typename BaseType::GlobalCoordinateType& point) const
  {
    const auto& geometry   = entity.geometry();
    const auto& refElement = DSG::reference_element(geometry);
    if (refElement.checkInside(geometry.local(point))) {
      return DSC::make_unique<typename BaseType::EntityType>(entity);
    }
    return nullptr;
  }

public:
  EntityInlevelSearch(const GridViewType& gridview) : gridview_(gridview), it_last_(gridview_.template begin<0>()) {}

  template <class PointContainerType>
  EntityVectorType operator()(const PointContainerType& points)
  {
    const IteratorType begin = gridview_.template begin<0>();
    const IteratorType end = gridview_.template end<0>();
    EntityVectorType ret(points.size());
    typename EntityVectorType::size_type idx(0);
    for (const auto& point : points) {
      IteratorType it_current = it_last_;
      bool it_reset = true;
      typename EntityVectorType::value_type tmp_ptr(nullptr);
      for (; it_current != end; ++it_current) {
        if ((tmp_ptr = check_add(*it_current, point))) {
          ret[idx++] = std::move(tmp_ptr);
          tmp_ptr    = nullptr;
          it_reset   = false;
          it_last_   = it_current;
          break;
        }
      }
      if (!it_reset)
        continue;
      for (it_current = begin; it_current != it_last_; ++it_current) {
        if ((tmp_ptr = check_add(*it_current, point))) {
          ret[idx++] = std::move(tmp_ptr);
          tmp_ptr    = nullptr;
          it_reset   = false;
          it_last_   = it_current;
          break;
        }
      }
    }
    return ret;
  } // ... operator()

private:
  const GridViewType gridview_;
  IteratorType it_last_;
}; // class EntityInlevelSearch

template <class GridViewType>
class EntityHierarchicSearch : public EntitySearchBase<GridViewType>
{
  typedef EntitySearchBase<GridViewType> BaseType;

  const GridViewType gridview_;
  const int start_level_;

public:
  EntityHierarchicSearch(const GridViewType& gridview) : gridview_(gridview), start_level_(0) {}

  typedef typename BaseType::EntityVectorType EntityVectorType;

  template <class PointContainerType>
  EntityVectorType operator()(const PointContainerType& points) const
  {
    auto level = std::min(gridview_.grid().maxLevel(), start_level_);
    auto range = DSC::entityRange(gridview_.grid().levelView(level));
    return process(points, range);
  }

private:
  template <class QuadpointContainerType, class RangeType>
  EntityVectorType process(const QuadpointContainerType& quad_points, const RangeType& range) const
  {
    EntityVectorType ret;

    for (const auto& my_ent : range) {
      const auto my_level    = my_ent.level();
      const auto& geometry   = my_ent.geometry();
      const auto& refElement = DSG::reference_element(geometry);
      for (const auto& point : quad_points) {
        if (refElement.checkInside(geometry.local(point))) {
          // if I cannot descend further add this entity even if it's not my view
          if (gridview_.grid().maxLevel() <= my_level || gridview_.contains(my_ent)) {
            ret.emplace_back(my_ent);
          } else {
            const auto h_end   = my_ent.hend(my_level + 1);
            const auto h_begin = my_ent.hbegin(my_level + 1);
            const auto h_range = boost::make_iterator_range(h_begin, h_end);
            const auto kids = process(QuadpointContainerType(1, point), h_range);
            ret.insert(ret.end(), kids.begin(), kids.end());
          }
        }
      }
    }
    return ret;
  }
}; // class EntityHierarchicSearch

template <class GV>
EntityInlevelSearch<GV> make_entity_in_level_search(const GV& grid_view)
{
  return EntityInlevelSearch<GV>(grid_view);
}

template <class GV>
EntityHierarchicSearch<GV> make_entity_hierarchic_search(const GV& grid_view)
{
  return EntityHierarchicSearch<GV>(grid_view);
}

} // namespace Grid
} // namespace Stuff
} // namespace Dune

#endif // HAVE_DUNE_GRID

#endif // DUNE_STUFF_GRID_SEARCH_HH

ext: hh

max_stars_repo_name: ftalbrecht/dune-stuff-simplified

max_issues_repo_name: ftalbrecht/dune-stuff-simplified

max_forks_repo_name: ftalbrecht/dune-stuff-simplified


text:
/****************************************************************************
**
** Copyright (C) 2017 TU Wien, ACIN, Vision 4 Robotics (V4R) group
** Contact: v4r.acin.tuwien.ac.at
**
** This file is part of V4R
**
** V4R is distributed under dual licenses - GPLv3 or closed source.
**
** GNU General Public License Usage
** V4R is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published
** by the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** V4R is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** Please review the following information to ensure the GNU General Public
** License requirements will be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
**
** Commercial License Usage
** If GPL is not suitable for your project, you must purchase a commercial
** license to use V4R. Licensees holding valid commercial V4R licenses may
** use this file in accordance with the commercial license agreement
** provided with the Software or, alternatively, in accordance with the
** terms contained in a written agreement between you and TU Wien, ACIN, V4R.
** For licensing terms and conditions please contact office<at>acin.tuwien.ac.at.
**
**
** The copyright holder additionally grants the author(s) of the file the right
** to use, copy, modify, merge, publish, distribute, sublicense, and/or
** sell copies of their contributions without any restrictions.
**
****************************************************************************/

/**
 * @file main.cpp
 * @author Johann Prankl (prankl@acin.tuwien.ac.at)
 * @date 2017
 * @brief
 *
 */

#include <GL/glut.h>
#include <v4r/features/FeatureDetector_KD_SIFTGPU.h>
#include <Eigen/Dense>

namespace v4r {

using namespace std;

FeatureDetector_KD_SIFTGPU::FeatureDetector_KD_SIFTGPU(const Parameter &_p, const cv::Ptr<SiftGPU> &_sift)
: FeatureDetector(FeatureDetector::Type::KD_SIFTGPU), param(_p) {
  descr_name_ = "sift_gpu";
  // init sift
  if (_sift.empty()) {
    const char *argv[] = {"-m", "-fo", "-1", "-s", "-v", "1", "-pack"};
    int argc = sizeof(argv) / sizeof(char *);
    sift = new SiftGPU();
    sift->ParseParam(argc, (char **)argv);
    // create an OpenGL context for computation
    if (sift->CreateContextGL() != SiftGPU::SIFTGPU_FULL_SUPPORTED)
      throw runtime_error("[FeatureDetector_KD_SIFTGPU::FeatureDetector_KD_SIFTGPU] No GL support!");
  } else
    sift = _sift;
}

FeatureDetector_KD_SIFTGPU::~FeatureDetector_KD_SIFTGPU() {}

void FeatureDetector_KD_SIFTGPU::transformToRootSIFT(cv::Mat &descriptors) const {
  float norm;

  for (int i = 0; i < descriptors.rows; i++) {
    Eigen::Map<Eigen::VectorXf> desc(&descriptors.at<float>(i, 0), descriptors.cols);
    norm = desc.lpNorm<1>();
    desc.array() /= norm;
    desc.array() = desc.array().sqrt();
  }
}

void FeatureDetector_KD_SIFTGPU::detectAndCompute(const cv::Mat &image, std::vector<cv::KeyPoint> &keypoints,
                                                  cv::Mat &descriptors, const cv::Mat &object_mask) {
  cv::Mat_<unsigned char> im_gray;
  if (image.type() != CV_8U)
    cv::cvtColor(image, im_gray, cv::COLOR_RGB2GRAY);
  else
    im_gray = image;

  descriptors = cv::Mat();
  keypoints.clear();

  SiftGPU *pSift = (SiftGPU *)&(*sift);

  if (pSift->CreateContextGL() != SiftGPU::SIFTGPU_FULL_SUPPORTED)
    throw std::runtime_error("SiftGPU: No GL support!");

  pSift->VerifyContextGL();

  if (pSift->RunSIFT(im_gray.cols, im_gray.rows, im_gray.ptr<uchar>(0), GL_LUMINANCE, GL_UNSIGNED_BYTE)) {
    int rows = pSift->GetFeatureNum();
    if (rows > 0) {
      vector<SiftGPU::SiftKeypoint> ks(rows);
      descriptors = cv::Mat(rows, 128, CV_32F);

      pSift->GetFeatureVector(&ks[0], descriptors.ptr<float>(0));

      keypoints.resize(rows);
      keypoint_indices_.resize(rows);

      size_t kept = 0;
      for (size_t i = 0; i < keypoints.size(); i++) {
        int u = std::min<int>(im_gray.cols - 1, ks[i].x + 0.5f);
        int v = std::min<int>(im_gray.rows - 1, ks[i].y + 0.5f);
        int idx = v * im_gray.cols + u;

        if (object_mask.empty() || object_mask.at<uchar>(v, u)) {  // keypoint belongs to given object mask
          descriptors.row(i).copyTo(descriptors.row(kept));
          keypoints[kept] = cv::KeyPoint(ks[i].x, ks[i].y, ks[i].s * 3, -ks[i].o * 180 / M_PI, 1, 0, i);
          keypoint_indices_[kept] = idx;
          kept++;
        }
      }
      descriptors.resize(kept);
      keypoints.resize(kept);
      keypoint_indices_.resize(kept);

      if (param.computeRootSIFT)
        transformToRootSIFT(descriptors);

    } else
      cout << "No SIFT found" << endl;
  } else
    throw runtime_error("PSiftGPU::Detect: SiftGPU Error!");
}

void FeatureDetector_KD_SIFTGPU::detect(const cv::Mat &image, std::vector<cv::KeyPoint> &keypoints,
                                        const cv::Mat &object_mask) {
  if (image.type() != CV_8U)
    cv::cvtColor(image, im_gray_, cv::COLOR_RGB2GRAY);
  else
    im_gray_ = image;

  keypoints.clear();

  SiftGPU *pSift = (SiftGPU *)&(*sift);

  if (pSift->CreateContextGL() != SiftGPU::SIFTGPU_FULL_SUPPORTED)
    throw std::runtime_error("SiftGPU: No GL support!");

  pSift->VerifyContextGL();

  if (pSift->RunSIFT(im_gray_.cols, im_gray_.rows, im_gray_.ptr<uchar>(0), GL_LUMINANCE, GL_UNSIGNED_BYTE)) {
    int num = pSift->GetFeatureNum();
    if (num > 0) {
      vector<SiftGPU::SiftKeypoint> ks(num);

      pSift->GetFeatureVector(&ks[0], NULL);

      // copy sift
      keypoints.resize(num);
      keypoint_indices_.resize(num);
      size_t kept = 0;
      for (int i = 0; i < num; i++) {
        int u = std::min<int>(im_gray_.cols - 1, ks[i].x + 0.5f);
        int v = std::min<int>(im_gray_.rows - 1, ks[i].y + 0.5f);
        int idx = v * im_gray_.cols + u;

        if (object_mask.empty() || object_mask.at<uchar>(v, u)) {  // keypoint belongs to given object mask
          keypoints[kept] = cv::KeyPoint(ks[i].x, ks[i].y, ks[i].s * 3, -ks[i].o * 180 / M_PI, 1, 0, i);
          keypoint_indices_[kept] = idx;
          kept++;
        }
      }
      keypoints.resize(kept);
      keypoint_indices_.resize(kept);
    } else
      cout << "No SIFT found" << endl;
  } else
    throw runtime_error("PSiftGPU::Detect: SiftGPU Error!");
}

void FeatureDetector_KD_SIFTGPU::compute(const cv::Mat &image, std::vector<cv::KeyPoint> &keypoints,
                                         cv::Mat &descriptors) {
  if (keypoints.empty())
    return;

  if (image.type() != CV_8U)
    cv::cvtColor(image, im_gray_, cv::COLOR_RGB2GRAY);
  else
    im_gray_ = image;

  vector<SiftGPU::SiftKeypoint> ks(keypoints.size());
  for (size_t i = 0; i < ks.size(); i++) {
    ks[i].x = keypoints[i].pt.x;
    ks[i].y = keypoints[i].pt.y;
    ks[i].s = keypoints[i].size / 3.;
    ks[i].o = -keypoints[i].angle * M_PI / 180.;
  }

  SiftGPU *pSift = (SiftGPU *)&(*sift);

  if (pSift->CreateContextGL() != SiftGPU::SIFTGPU_FULL_SUPPORTED)
    throw std::runtime_error("SiftGPU: No GL support!");

  pSift->VerifyContextGL();

  pSift->SetKeypointList(ks.size(), &ks[0], 0);

  if (pSift->RunSIFT(im_gray_.cols, im_gray_.rows, im_gray_.ptr<uchar>(0), GL_LUMINANCE, GL_UNSIGNED_BYTE)) {
    int num = pSift->GetFeatureNum();
    if (num == (int)keypoints.size()) {
      descriptors = cv::Mat(num, 128, CV_32F);
      pSift->GetFeatureVector(NULL, descriptors.ptr<float>(0));
      if (param.computeRootSIFT)
        transformToRootSIFT(descriptors);
    } else
      cerr << "Keypoints returned by SiftGPU is different than the number of keypoints given to this function." << endl;
  } else
    throw runtime_error("PSiftGPU::computeImpl: SiftGPU Error!");
}

std::vector<std::pair<int, int>> FeatureDetector_KD_SIFTGPU::matchSIFT(const cv::Mat &desc1, const cv::Mat &desc2) {
  SiftMatchGPU matcher(4096 * 4);
  matcher.VerifyContextGL();

  matcher.SetDescriptors(0, desc1.rows, desc1.data);  // image 1
  matcher.SetDescriptors(1, desc2.rows, desc2.data);  // image 2

  // match and get result.
  int(*match_buf)[2] = new int[desc1.rows][2];

  //        int num_match = matcher->GetSiftMatch(desc1.rows, match_buf,0.75f, 0.8f, 1);
  int num_match = matcher.GetSiftMatch(desc1.rows, match_buf, 0.5f, 0.95f, 1);

  std::vector<std::pair<int, int>> matches(num_match);
  for (int j = 0; j < num_match; j++)
    matches[j] = std::pair<int, int>(match_buf[j][0], match_buf[j][1]);

  delete[] match_buf;
  return matches;
}

}  // namespace v4r


text:
// Copyright Kevlin Henney, 2000-2005.
// Copyright Alexander Nasonov, 2006-2010.
// Copyright Antony Polukhin, 2011-2020.
//
// 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)
//
// what:  lexical_cast custom keyword cast
// who:   contributed by Kevlin Henney,
//        enhanced with contributions from Terje Slettebo,
//        with additional fixes and suggestions from Gennaro Prota,
//        Beman Dawes, Dave Abrahams, Daryle Walker, Peter Dimov,
//        Alexander Nasonov, Antony Polukhin, Justin Viiret, Michael Hofmann,
//        Cheng Yang, Matthew Bradbury, David W. Birdsall, Pavel Korzh and other Boosters
// when:  November 2000, March 2003, June 2005, June 2006, March 2011 - 2014

#ifndef BOOST_LEXICAL_CAST_DETAIL_INF_NAN_HPP
#define BOOST_LEXICAL_CAST_DETAIL_INF_NAN_HPP

#include <boost/config.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#   pragma once
#endif

#if defined(BOOST_NO_STRINGSTREAM) || defined(BOOST_NO_STD_WSTRING)
#define BOOST_LCAST_NO_WCHAR_T
#endif

#include <cstddef>
#include <cstring>
#include <boost/limits.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/math/special_functions/sign.hpp>
#include <boost/math/special_functions/fpclassify.hpp>

#include <boost/lexical_cast/detail/lcast_char_constants.hpp>

namespace boost {
    namespace detail
    {
        template <class CharT>
        bool lc_iequal(const CharT* val, const CharT* lcase, const CharT* ucase, unsigned int len) BOOST_NOEXCEPT {
            for( unsigned int i=0; i < len; ++i ) {
                if ( val[i] != lcase[i] && val[i] != ucase[i] ) return false;
            }

            return true;
        }

        /* Returns true and sets the correct value if found NaN or Inf. */
        template <class CharT, class T>
        inline bool parse_inf_nan_impl(const CharT* begin, const CharT* end, T& value
            , const CharT* lc_NAN, const CharT* lc_nan
            , const CharT* lc_INFINITY, const CharT* lc_infinity
            , const CharT opening_brace, const CharT closing_brace) BOOST_NOEXCEPT
        {
            using namespace std;
            if (begin == end) return false;
            const CharT minus = lcast_char_constants<CharT>::minus;
            const CharT plus = lcast_char_constants<CharT>::plus;
            const int inifinity_size = 8; // == sizeof("infinity") - 1

            /* Parsing +/- */
            bool const has_minus = (*begin == minus);
            if (has_minus || *begin == plus) {
                ++ begin;
            }

            if (end - begin < 3) return false;
            if (lc_iequal(begin, lc_nan, lc_NAN, 3)) {
                begin += 3;
                if (end != begin) {
                    /* It is 'nan(...)' or some bad input*/

                    if (end - begin < 2) return false; // bad input
                    -- end;
                    if (*begin != opening_brace || *end != closing_brace) return false; // bad input
                }

                if( !has_minus ) value = std::numeric_limits<T>::quiet_NaN();
                else value = (boost::math::changesign) (std::numeric_limits<T>::quiet_NaN());
                return true;
            } else if (
                ( /* 'INF' or 'inf' */
                  end - begin == 3      // 3 == sizeof('inf') - 1
                  && lc_iequal(begin, lc_infinity, lc_INFINITY, 3)
                )
                ||
                ( /* 'INFINITY' or 'infinity' */
                  end - begin == inifinity_size
                  && lc_iequal(begin, lc_infinity, lc_INFINITY, inifinity_size)
                )
             )
            {
                if( !has_minus ) value = std::numeric_limits<T>::infinity();
                else value = (boost::math::changesign) (std::numeric_limits<T>::infinity());
                return true;
            }

            return false;
        }

        template <class CharT, class T>
        bool put_inf_nan_impl(CharT* begin, CharT*& end, const T& value
                         , const CharT* lc_nan
                         , const CharT* lc_infinity) BOOST_NOEXCEPT
        {
            using namespace std;
            const CharT minus = lcast_char_constants<CharT>::minus;
            if ((boost::math::isnan)(value)) {
                if ((boost::math::signbit)(value)) {
                    *begin = minus;
                    ++ begin;
                }

                memcpy(begin, lc_nan, 3 * sizeof(CharT));
                end = begin + 3;
                return true;
            } else if ((boost::math::isinf)(value)) {
                if ((boost::math::signbit)(value)) {
                    *begin = minus;
                    ++ begin;
                }

                memcpy(begin, lc_infinity, 3 * sizeof(CharT));
                end = begin + 3;
                return true;
            }

            return false;
        }

#ifndef BOOST_LCAST_NO_WCHAR_T
        template <class T>
        bool parse_inf_nan(const wchar_t* begin, const wchar_t* end, T& value) BOOST_NOEXCEPT {
            return parse_inf_nan_impl(begin, end, value
                               , L"NAN", L"nan"
                               , L"INFINITY", L"infinity"
                               , L'(', L')');
        }

        template <class T>
        bool put_inf_nan(wchar_t* begin, wchar_t*& end, const T& value) BOOST_NOEXCEPT {
            return put_inf_nan_impl(begin, end, value, L"nan", L"infinity");
        }

#endif
#if !defined(BOOST_NO_CXX11_CHAR16_T) && !defined(BOOST_NO_CXX11_UNICODE_LITERALS)
        template <class T>
        bool parse_inf_nan(const char16_t* begin, const char16_t* end, T& value) BOOST_NOEXCEPT {
            return parse_inf_nan_impl(begin, end, value
                               , u"NAN", u"nan"
                               , u"INFINITY", u"infinity"
                               , u'(', u')');
        }

        template <class T>
        bool put_inf_nan(char16_t* begin, char16_t*& end, const T& value) BOOST_NOEXCEPT {
            return put_inf_nan_impl(begin, end, value, u"nan", u"infinity");
        }
#endif
#if !defined(BOOST_NO_CXX11_CHAR32_T) && !defined(BOOST_NO_CXX11_UNICODE_LITERALS)
        template <class T>
        bool parse_inf_nan(const char32_t* begin, const char32_t* end, T& value) BOOST_NOEXCEPT {
            return parse_inf_nan_impl(begin, end, value
                               , U"NAN", U"nan"
                               , U"INFINITY", U"infinity"
                               , U'(', U')');
        }

        template <class T>
        bool put_inf_nan(char32_t* begin, char32_t*& end, const T& value) BOOST_NOEXCEPT {
            return put_inf_nan_impl(begin, end, value, U"nan", U"infinity");
        }
#endif

        template <class CharT, class T>
        bool parse_inf_nan(const CharT* begin, const CharT* end, T& value) BOOST_NOEXCEPT {
            return parse_inf_nan_impl(begin, end, value
                               , "NAN", "nan"
                               , "INFINITY", "infinity"
                               , '(', ')');
        }

        template <class CharT, class T>
        bool put_inf_nan(CharT* begin, CharT*& end, const T& value) BOOST_NOEXCEPT {
            return put_inf_nan_impl(begin, end, value, "nan", "infinity");
        }
    }
} // namespace boost

#undef BOOST_LCAST_NO_WCHAR_T

#endif // BOOST_LEXICAL_CAST_DETAIL_INF_NAN_HPP

max_stars_repo_name: fmilano/CppMicroServices

max_issues_repo_name: fmilano/CppMicroServices

max_forks_repo_name: fmilano/CppMicroServices


text:
#ifndef  BOOST_SERIALIZATION_VOID_CAST_HPP
#define BOOST_SERIALIZATION_VOID_CAST_HPP

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// void_cast.hpp:   interface for run-time casting of void pointers.

// (C) Copyright 2002-2009 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// gennadiy.rozental@tfn.com

//  See http://www.boost.org for updates, documentation, and revision history.

#include <cstddef> // for ptrdiff_t
#include <boost/noncopyable.hpp>

#include <boost/serialization/config.hpp>
#include <boost/serialization/smart_cast.hpp>
#include <boost/serialization/singleton.hpp>
#include <boost/serialization/force_include.hpp>
#include <boost/serialization/type_info_implementation.hpp>
#include <boost/serialization/extended_type_info.hpp>
#include <boost/type_traits/is_virtual_base_of.hpp>
#include <boost/serialization/void_cast_fwd.hpp>

#include <boost/config/abi_prefix.hpp> // must be the last header

#ifdef BOOST_MSVC
#  pragma warning(push)
#  pragma warning(disable : 4251 4231 4660 4275)
#endif

namespace boost {
namespace serialization {

class extended_type_info;

// Given a void *, assume that it really points to an instance of one type
// and alter it so that it would point to an instance of a related type.
// Return the altered pointer. If there exists no sequence of casts that
// can transform from_type to to_type, return a NULL.

BOOST_SERIALIZATION_DECL(void const *)
void_upcast(
    extended_type_info const & derived,
    extended_type_info const & base,
    void const * const t
);

inline void *
void_upcast(
    extended_type_info const & derived,
    extended_type_info const & base,
    void * const t
){
    return const_cast<void*>(void_upcast(
        derived,
        base,
        const_cast<void const *>(t)
    ));
}

BOOST_SERIALIZATION_DECL(void const *)
void_downcast(
    extended_type_info const & derived,
    extended_type_info const & base,
    void const * const t
);

inline void *
void_downcast(
    extended_type_info const & derived,
    extended_type_info const & base,
    void * const t
){
    return const_cast<void*>(void_downcast(
        derived,
        base,
        const_cast<void const *>(t)
    ));
}

namespace void_cast_detail {

class BOOST_SERIALIZATION_DECL(BOOST_PP_EMPTY()) void_caster :
    private boost::noncopyable
{
    friend
    BOOST_SERIALIZATION_DECL(void const *)
    boost::serialization::void_upcast(
        extended_type_info const & derived,
        extended_type_info const & base,
        void const * const
    );
    friend
    BOOST_SERIALIZATION_DECL(void const *)
    boost::serialization::void_downcast(
        extended_type_info const & derived,
        extended_type_info const & base,
        void const * const
    );
protected:
    void recursive_register(bool includes_virtual_base = false) const;
    void recursive_unregister() const;
public:
    // Data members
    const extended_type_info * m_derived;
    const extended_type_info * m_base;
    /*const*/ std::ptrdiff_t m_difference;
    void_caster const * const m_parent;

    // note that void_casters are keyed on value of
    // member extended type info records - NOT their
    // addresses.  This is necessary in order for the
    // void cast operations to work across dll and exe
    // module boundries.
    bool operator<(const void_caster & rhs) const;

    const void_caster & operator*(){
        return *this;
    }
    // each derived class must re-implement these;
    virtual void const * upcast(void const * const t) const = 0;
    virtual void const * downcast(void const * const t) const = 0;
    // Constructor
    void_caster(
        extended_type_info const * derived,
        extended_type_info const * base,
        std::ptrdiff_t difference = 0,
        void_caster const * const parent = 0
    ) :
        m_derived(derived),
        m_base(base),
        m_difference(difference),
        m_parent(parent)
    {}
    virtual ~void_caster(){}
};

#ifdef BOOST_MSVC
#  pragma warning(push)
#  pragma warning(disable : 4251 4231 4660 4275 4511 4512)
#endif

template <class Derived, class Base>
class void_caster_primitive :
    public void_caster
{
    virtual void const * downcast(void const * const t) const {
        const Derived * d =
            boost::serialization::smart_cast<const Derived *, const Base *>(
                static_cast<const Base *>(t)
            );
        return d;
    }
    virtual void const * upcast(void const * const t) const {
        const Base * b =
            boost::serialization::smart_cast<const Base *, const Derived *>(
                static_cast<const Derived *>(t)
            );
        return b;
    }
public:
    void_caster_primitive();
    virtual ~void_caster_primitive();
};

template <class Derived, class Base>
void_caster_primitive<Derived, Base>::void_caster_primitive() :
    void_caster(
        & type_info_implementation<Derived>::type::get_const_instance(),
        & type_info_implementation<Base>::type::get_const_instance(),
        // note:I wanted to display from 0 here, but at least one compiler
        // treated 0 by not shifting it at all.
        reinterpret_cast<std::ptrdiff_t>(
            static_cast<Derived *>(
                reinterpret_cast<Base *>(1)
            )
        ) - 1
    )
{
    recursive_register();
}

template <class Derived, class Base>
void_caster_primitive<Derived, Base>::~void_caster_primitive(){
    recursive_unregister();
}

template <class Derived, class Base>
class void_caster_virtual_base :
    public void_caster
{
public:
    virtual void const * downcast(void const * const t) const {
        const Derived * d =
            dynamic_cast<const Derived *>(
                static_cast<const Base *>(t)
            );
        return d;
    }
    virtual void const * upcast(void const * const t) const {
        const Base * b =
            dynamic_cast<const Base *>(
                static_cast<const Derived *>(t)
            );
        return b;
    }
    void_caster_virtual_base();
    virtual ~void_caster_virtual_base();
};

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

template <class Derived, class Base>
void_caster_virtual_base<Derived,Base>::void_caster_virtual_base() :
    void_caster(
        & (type_info_implementation<Derived>::type::get_const_instance()),
        & (type_info_implementation<Base>::type::get_const_instance())
    )
{
    recursive_register(true);
}

template <class Derived, class Base>
void_caster_virtual_base<Derived,Base>::~void_caster_virtual_base(){
    recursive_unregister();
}

template <class Derived, class Base>
struct void_caster_base :
    public void_caster
{
    typedef
        BOOST_DEDUCED_TYPENAME mpl::eval_if<boost::is_virtual_base_of<Base,Derived>,
            mpl::identity<
                void_cast_detail::void_caster_virtual_base<Derived, Base>
            >
        ,// else
            mpl::identity<
                void_cast_detail::void_caster_primitive<Derived, Base>
            >
        >::type type;
};

} // void_cast_detail

template<class Derived, class Base>
BOOST_DLLEXPORT
inline const void_cast_detail::void_caster & void_cast_register(
    Derived const * /* dnull = NULL */,
    Base const * /* bnull = NULL */
){
    typedef
        BOOST_DEDUCED_TYPENAME mpl::eval_if<boost::is_virtual_base_of<Base,Derived>,
            mpl::identity<
                void_cast_detail::void_caster_virtual_base<Derived, Base>
            >
        ,// else
            mpl::identity<
                void_cast_detail::void_caster_primitive<Derived, Base>
            >
        >::type typex;
    return singleton<typex>::get_const_instance();
}

template<class Derived, class Base>
class void_caster :
    public void_cast_detail::void_caster_base<Derived, Base>::type
{
};

} // namespace serialization
} // namespace boost

#ifdef BOOST_MSVC
#  pragma warning(pop)
#endif

#include <boost/config/abi_suffix.hpp> // pops abi_suffix.hpp pragmas

#endif // BOOST_SERIALIZATION_VOID_CAST_HPP

max_issues_repo_name: jonstewart/boost-svn

max_forks_repo_name: jonstewart/boost-svn


text:
#include "Exp.hh"
#include "TypeClasses.hh"
using namespace TypeClasses;

#include <Eigen/Core>
#include "config_vars.h"

#ifdef GNA_CUDA_SUPPORT
#include "cuElementary.hh"
#endif

namespace GNA {
  namespace GNAObjectTemplates {
    /**
     * @brief Constructor.
     */
    template<typename FloatType>
    ExpT<FloatType>::ExpT() {
        this->transformation_("exp")
            .input("points")
    	    .output("result")
    	    .types(new CheckKindT<FloatType>(DataKind::Points), new PassTypeT<FloatType>(0, {0,-1}))
    	    .func(&ExpT<FloatType>::calculate)
    #ifdef GNA_CUDA_SUPPORT
    	    .func("gpu", &ExpT<FloatType>::calc_gpu, DataLocation::Device)
    #endif
          ;
    }

    /**
     * @brief Calculate the value of function.
     */
    template<typename FloatType>
    void ExpT<FloatType>::calculate(FunctionArgs& fargs){
        fargs.rets[0].x = fargs.args[0].x.exp();
    }

#ifdef GNA_CUDA_SUPPORT
    template<typename FloatType>
    void ExpT<FloatType>::calc_gpu(FunctionArgs& fargs) {
            fargs.args.touch();
            auto& gpuargs=fargs.gpu;
            gpuargs->provideSignatureDevice();
            auto** source=gpuargs->args;
            auto** dest  =gpuargs->rets;
            cuexp(source, dest, gpuargs->nargs, fargs.args[0].arr.size());
    }
#endif
  }
}

template class GNA::GNAObjectTemplates::ExpT<double>;
#ifdef PROVIDE_SINGLE_PRECISION
  template class GNA::GNAObjectTemplates::ExpT<float>;
#endif

max_stars_repo_name: gnafit/gna

max_issues_repo_name: gnafit/gna

max_forks_repo_name: gnafit/gna


text:
#ifndef LIBTRELLIS_BITDATABASE_HPP
#define LIBTRELLIS_BITDATABASE_HPP

#include <vector>
#include <map>
#include <string>
#include <cstdint>
#include <boost/optional.hpp>
#include <mutex>
#ifndef NO_THREADS
#include <boost/thread/shared_mutex.hpp>
#include <atomic>
#endif
#include <set>
#include <unordered_set>
#include "Util.hpp"

#ifdef FUZZ_SAFETY_CHECK

#include <boost/interprocess/sync/file_lock.hpp>

#endif

using namespace std;
namespace Trellis {
/*
The BitDatabase keeps track of what each bit in a tile does. Unlike other databases, this database is mutable from
 within libtrellis, for use during fuzzing.
 */

// A single configuration bit, given by its offset inside the tile,
// and whether or not it is inverted
struct ConfigBit
{
    int frame;
    int bit;
    bool inv = false;

    inline bool operator==(const ConfigBit &other) const
    {
        return (frame == other.frame) && (bit == other.bit) && (inv == other.inv);
    }
};

inline bool operator<(const ConfigBit &a, const ConfigBit &b)
{
    if (a.frame < b.frame) {
        return true;
    } else if (a.frame > b.frame) {
        return false;
    } else {
        if (a.bit < b.bit) {
            return true;
        } else if (a.bit > b.bit) {
            return false;
        } else {
            return a.inv < b.inv;
        }
    }
}
}

namespace std {
// Hash function for ConfigBit
template<>
struct hash<Trellis::ConfigBit>
{
public:
    inline size_t operator()(const Trellis::ConfigBit &bit) const
    {
        hash<int> hash_i_fn;
        hash<bool> hash_b_fn;
        return hash_i_fn(bit.frame) + hash_i_fn(bit.bit) + hash_b_fn(bit.inv);
    }
};
}

namespace Trellis {
typedef unordered_set<ConfigBit> BitSet;

// Write a configuration bit to string
inline string to_string(ConfigBit b)
{
    ostringstream ss;
    if (b.inv) ss << "!";
    ss << "F" << b.frame;
    ss << "B" << b.bit;
    return ss.str();
}

// Read a configuration bit from a string
ConfigBit cbit_from_str(const string &s);

class CRAMView;

struct ChangedBit;
typedef vector<ChangedBit> CRAMDelta;

// A BitGroup is a list of configuration bits that correspond to a given setting
struct BitGroup
{
    // Create an empty BitGroup
    BitGroup();

    // Create a BitGroup from a delta.
    // Delta should be calculated as (with feature) - (without feature)
    explicit BitGroup(const CRAMDelta &delta);

    set<ConfigBit> bits;

    // Return true if the BitGroup is set in a tile
    bool match(const CRAMView &tile) const;

    // Update a coverage set with the bitgroup
    void add_coverage(BitSet &known_bits, bool value = true) const;

    // Set the BitGroup in a tile
    void set_group(CRAMView &tile) const;

    // Clear the BitGroup in a tile
    void clear_group(CRAMView &tile) const;

    inline bool operator==(const BitGroup &other) const
    {
        return bits == other.bits;
    }
};

// Write BitGroup to output
ostream &operator<<(ostream &out, const BitGroup &bits);

// Read a BitGroup from input (until end of line)
istream &operator>>(istream &out, BitGroup &bits);

// An arc is a configurable connection between two nodes, defined within a mux
struct ArcData
{
    string source;
    string sink;
    BitGroup bits;

    inline bool operator==(const ArcData &other) const
    {
        return (source == other.source) && (sink == other.sink) && (bits == other.bits);
    }
};

// A mux specifies all the possible source node arcs driving a sink node
struct MuxBits
{
    string sink;
    map<string, ArcData> arcs;

    // Get a list of sources for the mux
    vector<string> get_sources() const;

    // Work out which connection inside the mux, if any, is made inside a tile
    boost::optional<string>
    get_driver(const CRAMView &tile, boost::optional<BitSet &> coverage = boost::optional<BitSet &>()) const;

    // Set the driver to a given value inside the tile
    void set_driver(CRAMView &tile, const string &driver) const;

    inline bool operator==(const MuxBits &other) const
    {
        return (sink == other.sink) && (arcs == other.arcs);
    }
};

// Write mux database entry to output
ostream &operator<<(ostream &out, const MuxBits &mux);

// Read mux database entry (excluding .mux token) from input
istream &operator>>(istream &in, MuxBits &mux);

// There are three types of non-routing config setting in the database
// word  : a multibit setting, such as LUT initialisation
// simple: a single on/off setting, a special case of the above
// enum  : a setting with several different textual values, such as an IO type

struct WordSettingBits
{
    string name;
    vector<BitGroup> bits;
    vector<bool> defval;

    // Return the word value in a tile, returning empty if equal to the default
    boost::optional<vector<bool>>
    get_value(const CRAMView &tile, boost::optional<BitSet &> coverage = boost::optional<BitSet &>()) const;

    // Set the word value in a tile
    void set_value(CRAMView &tile, const vector<bool> &value) const;

    inline bool operator==(const WordSettingBits &other) const
    {
        return (name == other.name) && (bits == other.bits) && (defval == other.defval);
    }
};

// Write config word setting bits to output
ostream &operator<<(ostream &out, const WordSettingBits &ws);

// Read config word database entry (excluding .config token) from input
istream &operator>>(istream &out, WordSettingBits &ws);

struct EnumSettingBits
{
    string name;
    map<string, BitGroup> options;
    boost::optional<string> defval;

    // Needed for Python
    void set_defval(string val);

    string get_defval() const;

    vector<string> get_options() const;

    // Get the value of the enumeration, returning empty if not set or set to default, if default is non-empty
    boost::optional<string>
    get_value(const CRAMView &tile, boost::optional<BitSet &> coverage = boost::optional<BitSet &>()) const;

    // Set the value of the enumeration in a tile
    void set_value(CRAMView &tile, const string &value) const;

    inline bool operator==(const EnumSettingBits &other) const
    {
        return (name == other.name) && (options == other.options) && (defval == other.defval);
    }
};

// Write config enum bits to output
ostream &operator<<(ostream &out, const EnumSettingBits &es);

// Read config enum bits database entry (excluding .config_enum token) from input
istream &operator>>(istream &out, EnumSettingBits &es);

// A fixed connection inside a tile
struct FixedConnection
{
    string source;
    string sink;

    inline bool operator==(const FixedConnection &other) const
    {
        return (source == other.source) && (sink == other.sink);
    }
};

inline bool operator<(const FixedConnection &a, const FixedConnection &b)
{
    if (a.sink < b.sink) {
        return true;
    } else if (a.sink > b.sink) {
        return false;
    } else {
        return a.source < b.source;
    }
}

// Write fixed connection to output
ostream &operator<<(ostream &out, const FixedConnection &es);

// Read fixed connection from input
istream &operator>>(istream &out, FixedConnection &es);

struct TileConfig;
struct TileLocator;
struct TileInfo;

class RoutingGraph;

class TileBitDatabase
{
public:
    // Access functions

    // Convert TileConfigs to and from actual Tile CRAM
    void config_to_tile_cram(const TileConfig &cfg, CRAMView &tile, bool is_tilegroup = false, set<string> *tg_matches = nullptr) const;

    TileConfig tile_cram_to_config(const CRAMView &tile) const;

    // All these functions are designed to be thread safe during fuzzing and database modification
    // Maybe we should have faster unsafe versions too, as that will be the majority of the use cases?
    vector<string> get_sinks() const;

    MuxBits get_mux_data_for_sink(const string &sink) const;

    vector<string> get_settings_words() const;

    WordSettingBits get_data_for_setword(const string &name) const;

    vector<string> get_settings_enums() const;

    EnumSettingBits get_data_for_enum(const string &name) const;

    vector<FixedConnection> get_fixed_conns() const;
    // TODO: function to get routing graph of tile

    // Get a list of wires downhill in the tile of a given wire
    // Returns pair<wire, configurable>
    vector<pair<string, bool>> get_downhill_wires(const string &wire) const;

    // Add the bit database for a tile to the routing graph
    void add_routing(const TileInfo &tile, RoutingGraph &graph) const;

    // Add relevant items to the database
    void add_mux_arc(const ArcData &arc);

    void add_setting_word(const WordSettingBits &wsb);

    void add_setting_enum(const EnumSettingBits &esb);

    void add_fixed_conn(const FixedConnection &conn);

    void remove_fixed_sink(const string &sink);
    void remove_setting_enum(const string &enum_name);
    void remove_setting_word(const string &word_name);

    // Save the bit database to file
    void save();

    // Function to obtain the singleton BitDatabase for a given tile
    friend shared_ptr<TileBitDatabase> get_tile_bitdata(const TileLocator &tile);

    // This should not be used, but is required for PyTrellis
    TileBitDatabase(const TileBitDatabase &other);

    ~TileBitDatabase();

private:
    explicit TileBitDatabase(const string &filename);

#ifdef NO_THREADS
    bool dirty = false;
#else
    mutable boost::shared_mutex db_mutex;
    atomic<bool> dirty{false};
#endif
    map<string, MuxBits> muxes;
    map<string, WordSettingBits> words;
    map<string, EnumSettingBits> enums;
    map<string, set<FixedConnection>> fixed_conns;
    string filename;

    void load();

#ifdef FUZZ_SAFETY_CHECK
    boost::interprocess::file_lock ip_db_lock;
#endif
};

// Represents a conflict while adding something to the database
class DatabaseConflictError : public runtime_error
{
public:
    explicit DatabaseConflictError(const string &desc);
};

}

#endif //LIBTRELLIS_BITDATABASE_HPP

max_stars_repo_name: umarcor/prjtrellis

max_issues_repo_name: umarcor/prjtrellis

max_forks_repo_name: umarcor/prjtrellis


text:
//
// Created by w1ckedente on 16.02.2021.
//

#ifndef MULTI_THREADING_ASYNC_LOGGER_PROTOTYPE_HPP
#define MULTI_THREADING_ASYNC_LOGGER_PROTOTYPE_HPP

#include <boost/log/trivial.hpp>
#include <iostream>
#include <thread>
#include <tools/blocking_queue.hpp>
#include <utility>

namespace hasher::logging {
template <typename log_message_t, typename log_message_handler_t>
class async_logger_prototype {
 public:
  typedef boost::log::trivial::severity_level log_level;
  typedef log_message_t log_message;

  explicit async_logger_prototype(log_message_handler_t log_message_handler)
      : _log_message_handler(std::move(log_message_handler)),
        _stopped(false),
        _logging_worker([this] {
          while (!_stopped) {
            // todo logging worker
          }
        }) {}

  async_logger_prototype(const async_logger_prototype &) = delete;
  async_logger_prototype(async_logger_prototype &&) = delete;
  async_logger_prototype &operator=(const async_logger_prototype &) = delete;
  async_logger_prototype &operator=(async_logger_prototype &&) = delete;

  void write_message(log_level level, const log_message_t &message) {
    _messages_queue.push({level, message});
  }

  ~async_logger_prototype() { _messages_queue.stop(); }

  void enable() {
    _stopped = false;
    _logging_worker = std::thread([this] {
      while (!_stopped) {
        // todo logging worker
      }
    });
  }

  void disable() {
    _stopped = true;
    if (_logging_worker.joinable()) _logging_worker.join();
    _messages_queue.stop();
  }

 private:
  struct _log_message_meta {
    log_level level;
    log_message_t message;
  };

  log_message_handler_t _log_message_handler;
  std::atomic_bool _stopped;
  blocking_queue<_log_message_meta> _messages_queue;
  std::thread _logging_worker;
};
}  // namespace hasher::logging

#endif  // MULTI_THREADING_ASYNC_LOGGER_PROTOTYPE_HPP


text:
/** ***************************************************************************
 *
 *                             Password Generator
 *
 *  ***************************************************************************
 *
 *  Author: Jose Fernando Lopez Fernandez
 *
 *  Date:	05-May-2018
 *
 *  TODO:
 *      1. Pass in length of password                          - DONE
 *      2. Pass in number of passwords to generate             - DONE
 *      3. Improve random number generation
 *      4. Explore using other probability distributions
 *      5. Implement program options                           - IN PROGRESS
 *      6. Pass in password charset rule (regex)
 *      7. Time generation tracker
 *      8. Setup version tracker                               - DONE
 *      9. Create program configuration class/manager?
 *     10. Customize PRNG
 *     11. Implement logger class (?)
 *     12. Parse configuration file
 *     13. Parse environment
 *     14. Generate password from mask                         - CRITICAL
 *     15. Calculate password entropy                          - CRITICAL
 *     16. Write a parser for regexp->string generation
 *     17. Generate passwords with random words
 *     18. Modify words in password Tr0ub&dour style
 *     19. Accept restricted character set to avoid
 *
 *  **************************************************************************/

#ifdef UNICODE
#undef UNICODE
#endif

#include <iostream>
#include <sstream>
#include <string>

#include <boost/optional.hpp>
#include <boost/program_options.hpp>
#include <boost/random.hpp>
#include <boost/random/random_device.hpp>
#include <boost/regex.hpp>

#include <gsl/gsl>

#include "version.h"

namespace Options = boost::program_options;

using OptsDescription = boost::program_options::options_description;

const std::string charset(
    "abcdefghijklmnopqrstuvwxyz"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "1234567890"
    "!@#$%^&*()`~-_=+[{]}\\|;:'\",<.>/? "
);

std::string restrictedCharset = "";

boost::random::ranlux48 gen;
boost::random::uniform_int_distribution<> indexDistribution(0, gsl::narrow<std::size_t, int>(charset.size()) - 1);

struct Constants {
    static constexpr auto FALSE = 0;
    static constexpr auto TRUE = 1;
};

struct Configuration {
    static constexpr auto verbose = Constants::FALSE;
};

inline void PrintHelp(const OptsDescription& description) {
	PrintVersion();

	std::cout << description << "\n";
}

/** Password Mask rules:
 *
 *  * - any character
 *  l - lowercase letter
 *  L - capital letter
 *  d - digit
 *  s - symbol (no whitespace)
 *  ? - any symbol
 *
 */

// Complying with Warning C26451 - (https://docs.microsoft.com/en-us/visualstudio/code-quality/c26451)
const char LOWERCASE_START = gsl::narrow<char>('a');
const char UPPERCASE_START = gsl::narrow<char>('A');
const char ALPHA_RANGE     = gsl::narrow<char>('z' - 'a');
const char ONE             = gsl::narrow<char>(1);

char getNextCharacter(const char characterMask) {
    char newCharacter = '\0';

    do {
        newCharacter = [=](const char mask) -> char {
            switch (mask) {
                case '*': {
                    return charset[indexDistribution(gen)];
                } break;

                case 'l': {
                    return charset[(indexDistribution(gen) % ALPHA_RANGE) + LOWERCASE_START - ONE];
                } break;

                case 'L': {
                    // TODO: Fix
                    return charset[indexDistribution(gen)];
                }

                case 'd': {
                    // TODO: Fix
                    return charset[indexDistribution(gen)];
                }

                case 's': {
                    // TODO: Fix
                    return charset[indexDistribution(gen)];
                }

                case '?': {
                    // TODO: Fix
                    return charset[indexDistribution(gen)];
                }

                default:
                    return '0';
            }
        }(characterMask);

    // TODO: Check the new character is not on the restricted list
    } while (newCharacter == '\0');

    return '0';
}

int main(int argc, const char const *argv[])
{
    size_t n = 1;
	size_t length = 8;

	std::string mask = "********";

    boost::optional<size_t> entropy;
    boost::optional<std::string> inputMask;
    boost::optional<std::string> restrictedCharacters;
	boost::optional<std::string> configFile;

	try {
		OptsDescription generic("Generic options");
		generic.add_options()
			("help,h", "Display help dialog")
			("version,v", "Display program version")
			("password-length,l", Options::value<size_t>(&length)->default_value(8), "Password length")
			("passwords,n", Options::value<size_t>(&n)->default_value(1), "Number of passwords to generate")
            ("entropy", Options::value(&entropy), "Minimum password entropy tolerance")
            ("mask,m", Options::value(&inputMask), "Password mask (pattern)")
            ("restricted,r", Options::value(&restrictedCharacters), "Restricted characters")
            ("configuration-file,f", Options::value(&configFile), "Configuration file to use")
			;

		Options::variables_map map;
		Options::store(Options::parse_command_line(argc, argv, generic), map);
		Options::notify(map);

		if (map.count("help")) {
			PrintHelp(generic);

			return EXIT_SUCCESS;
		}

		if (map.count("version")) {
			PrintVersion();

			return EXIT_SUCCESS;
		}

		if (map.count("password-length")) {
			std::cout << "\n";
			std::cout << "Password Length: " << length << "\n";

            if (inputMask) {
                if ((*inputMask).size() != length) {
                    std::cerr << "\n[Error]: password length and mask size are not equal.\n";
                    std::cerr << "\tMask [" << *inputMask << "]\n";
                    std::cerr << "\tSize: " << (*inputMask).size() << "\n";
                    std::cerr << "\tPassword Length: " << length << "\n\n";

                    return EXIT_FAILURE;
                }

                mask = *inputMask;
            }
		}

		if (map.count("passwords")) {
			std::cout << "Number of passwords to generate: " << n << "\n";
		}

        if (entropy) {
            std::cout << "Minimum password entropy tolerance: " << *entropy << "\n";
        } else {
            if (Configuration::verbose) {
                std::cout << "<No minimum entropy tolerance set>\n";
            }
        }

        if (restrictedCharacters) {
            restrictedCharset = *restrictedCharacters;
        }

		if (configFile) {
			std::cout << "Config file: " << *configFile << "\n";
		} else {
			if (Configuration::verbose) {
				std::cout << "<No configuration file>\n";
			}
		}

	} catch (std::exception& e) {
		std::cerr << "[Error]: " << e.what() << "\n";
	}

	std::cout << "\n\n";

	for (auto count = 0; count < n; count++) {
        std::ostringstream newPassword { "" };

		for (auto position = 0; position < length; position++) {
            newPassword << getNextCharacter(mask[position]);
		}

		std::cout << newPassword.str() << "\n";
	}

	std::cout << "\n\n";

	return EXIT_SUCCESS;
}

max_stars_repo_name: lopezfjose/Password-Generator

max_issues_repo_name: lopezfjose/Password-Generator

max_forks_repo_name: lopezfjose/Password-Generator


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

#include <scorum/chain/database/block_tasks/process_bets_resolving.hpp>
#include <scorum/chain/database/block_tasks/process_bets_auto_resolving.hpp>

#include <scorum/chain/schema/account_objects.hpp>
#include <scorum/chain/schema/betting_property_object.hpp>
#include <scorum/chain/schema/bet_objects.hpp>
#include <scorum/chain/schema/game_object.hpp>
#include <scorum/chain/schema/dynamic_global_property_object.hpp>
#include <scorum/chain/schema/chain_property_object.hpp>

#include <scorum/chain/dba/db_accessor.hpp>
#include <scorum/chain/services/dynamic_global_property.hpp>
#include <scorum/chain/services/witness.hpp>
#include <scorum/chain/services/witness_schedule.hpp>
#include <scorum/chain/services/account.hpp>
#include <scorum/chain/services/betting_property.hpp>

#include <scorum/chain/betting/betting_service.hpp>
#include <scorum/chain/betting/betting_matcher.hpp>
#include <scorum/chain/betting/betting_resolver.hpp>
#include <scorum/protocol/betting/market.hpp>

#include <db_mock.hpp>
#include <hippomocks.h>
#include <defines.hpp>

namespace {
using namespace scorum;
using namespace scorum::chain;
using namespace scorum::protocol;
using namespace scorum::chain::database_ns;

struct chain_capital_fixture
{
    chain_capital_fixture()
        : betting_prop_dba(db)
        , matched_bet_dba(db)
        , pending_bet_dba(db)
        , game_dba(db)
        , dprop_dba(db)
        , account_dba(db)
        , uuid_hist_dba(db)
        , chain_dba(db)
        , dprop_svc(db)
        , witness_schedule_svc(db)
        , witness_svc(db, witness_schedule_svc, dprop_svc, chain_dba)
        , account_svc(db, dprop_svc, witness_svc)
    {
        db.add_index<betting_property_index>();
        db.add_index<pending_bet_index>();
        db.add_index<matched_bet_index>();
        db.add_index<game_index>();
        db.add_index<account_index>();
        db.add_index<dynamic_global_property_index>();
        db.add_index<bet_uuid_history_index>();

        mocks.OnCall(vop_emitter, database_virtual_operations_emmiter_i::push_virtual_operation);
    }

    MockRepository mocks;
    database_virtual_operations_emmiter_i* vop_emitter = mocks.Mock<database_virtual_operations_emmiter_i>();

    db_mock db;
    dba::db_accessor<betting_property_object> betting_prop_dba;
    dba::db_accessor<matched_bet_object> matched_bet_dba;
    dba::db_accessor<pending_bet_object> pending_bet_dba;
    dba::db_accessor<game_object> game_dba;
    dba::db_accessor<dynamic_global_property_object> dprop_dba;
    dba::db_accessor<account_object> account_dba;
    dba::db_accessor<bet_uuid_history_object> uuid_hist_dba;
    dba::db_accessor<chain_property_object> chain_dba;

    dbs_dynamic_global_property dprop_svc;
    dbs_witness_schedule witness_schedule_svc;
    dbs_witness witness_svc;
    dbs_account account_svc;
};

BOOST_FIXTURE_TEST_SUITE(betting_chain_capital_tests, chain_capital_fixture)

SCORUM_TEST_CASE(pending_bet_creation_should_change_betting_capital)
{
    // clang-format off
    dprop_dba.create([&](auto& o) { o.time = fc::time_point_sec(42); });
    account_dba.create([&](auto& o) { o.name = "alice"; o.balance = ASSET_SCR(1000); });
    // clang-format on

    betting_service svc(account_svc, *vop_emitter, betting_prop_dba, matched_bet_dba, pending_bet_dba, game_dba,
                        dprop_dba, uuid_hist_dba);

    svc.create_pending_bet("alice", ASSET_SCR(1000), odds(10, 2), result_home::yes{}, { 0 }, uuid_type{ 1 },
                           pending_bet_kind::live);

    BOOST_CHECK_EQUAL(dprop_dba.get().betting_stats.pending_bets_volume.amount, 1000u);
    BOOST_CHECK_EQUAL(dprop_dba.get().betting_stats.matched_bets_volume.amount, 0u);
}

SCORUM_TEST_CASE(bets_resolving_should_change_matched_betting_capital)
{
    account_dba.create([](account_object&) {});
    game_dba.create([](game_object& o) {});
    matched_bet_dba.create([](matched_bet_object& o) {
        o.game_uuid = { 0 };
        o.market = result_home{};
        o.bet1_data.stake = ASSET_SCR(500);
        o.bet1_data.wincase = result_home::yes{};
        o.bet2_data.stake = ASSET_SCR(2000);
        o.bet2_data.wincase = result_home::no{};
    });
    dprop_dba.create([&](dynamic_global_property_object& o) { o.betting_stats.matched_bets_volume = ASSET_SCR(2500); });

    betting_resolver resolver(account_svc, *vop_emitter, matched_bet_dba, game_dba, dprop_dba);

    resolver.resolve_matched_bets({ 0 }, { result_home::yes{} });

    BOOST_CHECK_EQUAL(0u, dprop_dba.get().betting_stats.matched_bets_volume.amount);
}

SCORUM_TEST_CASE(cancel_all_bets_should_change_betting_capital)
{
    account_dba.create([](account_object&) {});
    game_dba.create([](game_object& o) {});
    pending_bet_dba.create([](pending_bet_object& o) {
        o.game_uuid = { 0 };
        o.data.stake = ASSET_SCR(1000);
    });
    matched_bet_dba.create([](matched_bet_object& o) {
        o.game_uuid = { 0 };
        o.market = result_home{};
        o.bet1_data.stake = ASSET_SCR(500);
        o.bet2_data.stake = ASSET_SCR(2000);
    });
    dprop_dba.create([&](dynamic_global_property_object& o) {
        o.time = fc::time_point_sec(42);
        o.betting_stats.pending_bets_volume = ASSET_SCR(1000);
        o.betting_stats.matched_bets_volume = ASSET_SCR(2500);
    });

    betting_service svc(account_svc, *vop_emitter, betting_prop_dba, matched_bet_dba, pending_bet_dba, game_dba,
                        dprop_dba, uuid_hist_dba);

    svc.cancel_bets({ 0 });

    BOOST_CHECK_EQUAL(dprop_dba.get().betting_stats.pending_bets_volume.amount, 0u);
    BOOST_CHECK_EQUAL(dprop_dba.get().betting_stats.matched_bets_volume.amount, 0u);
}

SCORUM_TEST_CASE(cancel_bets_all_bets_created_after_game_started_should_be_removed_from_betting_stats)
{
    account_dba.create([](account_object&) {});
    const auto& g = game_dba.create([](game_object& o) { o.start_time = fc::time_point_sec(7); });
    pending_bet_dba.create([](pending_bet_object& o) {
        o.game_uuid = { 0 };
        o.data.created = fc::time_point_sec(42);
        o.data.stake = ASSET_SCR(1000);
    });
    matched_bet_dba.create([](matched_bet_object& o) {
        o.game_uuid = { 0 };
        o.market = result_home{};
        o.created = fc::time_point_sec(42);
        o.bet1_data.stake = ASSET_SCR(500);
        o.bet1_data.created = fc::time_point_sec(42);
        o.bet2_data.stake = ASSET_SCR(2000);
        o.bet2_data.created = fc::time_point_sec(42);
    });
    dprop_dba.create([&](dynamic_global_property_object& o) {
        o.time = fc::time_point_sec(99);
        o.betting_stats.pending_bets_volume = ASSET_SCR(1000);
        o.betting_stats.matched_bets_volume = ASSET_SCR(2500);
    });

    betting_service svc(account_svc, *vop_emitter, betting_prop_dba, matched_bet_dba, pending_bet_dba, game_dba,
                        dprop_dba, uuid_hist_dba);

    svc.cancel_bets({ 0 }, g.start_time);

    BOOST_CHECK_EQUAL(dprop_dba.get().betting_stats.pending_bets_volume.amount, 0u);
    BOOST_CHECK_EQUAL(dprop_dba.get().betting_stats.matched_bets_volume.amount, 0u);
}

SCORUM_TEST_CASE(cancel_bets_pending_bet_created_before_game_started_shouldnt_be_removed_from_betting_stats)
{
    const auto& g = game_dba.create([](game_object& o) { o.start_time = fc::time_point_sec(7); });
    pending_bet_dba.create([](pending_bet_object& o) {
        o.game_uuid = { 0 };
        o.data.created = fc::time_point_sec(5);
        o.data.stake = ASSET_SCR(1000);
    });
    dprop_dba.create([&](dynamic_global_property_object& o) {
        o.time = fc::time_point_sec(99);
        o.betting_stats.pending_bets_volume = ASSET_SCR(1000);
    });

    betting_service svc(account_svc, *vop_emitter, betting_prop_dba, matched_bet_dba, pending_bet_dba, game_dba,
                        dprop_dba, uuid_hist_dba);

    svc.cancel_bets({ 0 }, g.start_time);

    BOOST_CHECK_EQUAL(dprop_dba.get().betting_stats.pending_bets_volume.amount, 1000u);
}

SCORUM_TEST_CASE(
    cancel_bets_pending_bet_created_before_game_started_which_was_matched_after_game_started_shouldnt_be_removed_from_betting_stats)
{
    account_dba.create([](account_object&) {});
    const auto& g = game_dba.create([](game_object& o) { o.start_time = fc::time_point_sec(42); });
    matched_bet_dba.create([](matched_bet_object& o) {
        o.game_uuid = { 0 };
        o.market = result_home{};
        o.created = fc::time_point_sec(42);
        o.bet1_data.stake = ASSET_SCR(500);
        o.bet1_data.created = fc::time_point_sec(42);
        o.bet2_data.stake = ASSET_SCR(2000);
        o.bet2_data.created = fc::time_point_sec(13);
    });
    dprop_dba.create([&](dynamic_global_property_object& o) {
        o.time = fc::time_point_sec(99);
        o.betting_stats.matched_bets_volume = ASSET_SCR(2500);
    });

    betting_service svc(account_svc, *vop_emitter, betting_prop_dba, matched_bet_dba, pending_bet_dba, game_dba,
                        dprop_dba, uuid_hist_dba);

    svc.cancel_bets({ 0 }, g.start_time);

    BOOST_CHECK_EQUAL(dprop_dba.get().betting_stats.matched_bets_volume.amount, 0u);
    BOOST_CHECK_EQUAL(dprop_dba.get().betting_stats.pending_bets_volume.amount, 2000u);
}

SCORUM_TEST_CASE(cancel_pending_bets_only_live_pending_bet_should_be_removed_from_betting_stats)
{
    account_dba.create([](account_object&) {});
    game_dba.create([](game_object& o) {});
    pending_bet_dba.create([](pending_bet_object& o) {
        o.game_uuid = { 0 };
        o.data.uuid = { 0 };
        o.data.kind = pending_bet_kind::live;
        o.data.stake = ASSET_SCR(500);
    });
    pending_bet_dba.create([](pending_bet_object& o) {
        o.game_uuid = { 0 };
        o.data.uuid = { 1 };
        o.data.kind = pending_bet_kind::non_live;
        o.data.stake = ASSET_SCR(1000);
    });
    dprop_dba.create([&](dynamic_global_property_object& o) { o.betting_stats.pending_bets_volume = ASSET_SCR(1500); });

    betting_service svc(account_svc, *vop_emitter, betting_prop_dba, matched_bet_dba, pending_bet_dba, game_dba,
                        dprop_dba, uuid_hist_dba);

    svc.cancel_pending_bets({ 0 }, pending_bet_kind::live);

    BOOST_CHECK_EQUAL(dprop_dba.get().betting_stats.pending_bets_volume.amount, 1000u);
}

BOOST_AUTO_TEST_SUITE_END()
}

max_stars_repo_name: scorum/scorum

max_issues_repo_name: Scorum/Scorum

max_forks_repo_name: Scorum/Scorum


text:
#include <iostream>
#include <fstream>
#include <map>

#include <boost/config.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options/detail/config_file.hpp>

namespace pod = boost::program_options::detail;
namespace fs = boost::filesystem;

std::map<std::string, std::string> parse_config(std::string conf)
{
  fs::path conf_directory(conf);
  conf_directory = conf_directory.parent_path();

  std::ifstream config(conf);
  if(!config)
  {
    std::cerr << "File " << conf << " not found!" << std::endl;
    return std::map<std::string, std::string>();
  }

  std::set<std::string> options;
  options.insert("*");
  std::map<std::string, std::string> result;

  try
  {
    for (pod::config_file_iterator i(config, options), e; i != e; ++i)
    {
      if (i->string_key == "Repo.Path")
        result.insert({"path", (conf_directory/i->value[0]).string()});
      if (i->string_key == "Extensions.Directory")
        result.insert({"ext", (conf_directory/i->value[0]).string()});
      if (i->string_key == "Network.Port")
        result.insert({"port", i->value[0]});
      if (i->string_key == "Repo.SavePeriod")
        result.insert({"save_period", i->value[0]});
      if (i->string_key == "Stat.UpdatePeriod")
        result.insert({"update_period", i->value[0]});
      if (i->string_key == "Stat.Path")
        result.insert({"stat_path", i->value[0]});
    }
  }
  catch(std::exception & e)
  {
    SC_LOG_ERROR(e.what());
  }
  result["path"].append("kb.bin/");
  size_t path_length = 0;
  for (auto it : result)
  {
    path_length = it.second.size() - 1;
    if (path_length == '/')
      it.second = it.second.substr(0, path_length);
  }
  return result;
}

max_stars_repo_name: ostis-ai/sc-machine

max_issues_repo_name: ostis-ai/sc-machine

max_forks_repo_name: ostis-ai/sc-machine