text:
#include "test_Prefix.h"
#include <boost/unordered_set.hpp>
#include <boost/foreach.hpp>

template< typename G,
          typename ForwardRange,
          typename IndexPropertyMap
          >
void index_uniqueness(const G&,
                      ForwardRange range,
                      IndexPropertyMap pm)
{
  typename boost::range_iterator<ForwardRange>::type
    begin = boost::begin(range),
    begin2 = boost::begin(range),
    end = boost::end(range);

  typedef boost::unordered_set<typename IndexPropertyMap::value_type> id_map;
  typedef std::pair<typename id_map::iterator, bool> resultp;
  id_map m;

  while(begin != end) {
    resultp r = m.insert(get(pm, *begin));
    ++begin;
    assert(r.second);
  }

  assert(std::distance(begin2, end) == static_cast<std::ptrdiff_t>(m.size()));
}

void index_uniqueness_poly(const Polyhedron& g)
{
  std::cerr << "testing Polyhedron\n";
  index_uniqueness(g, edges(g) ,    get(boost::edge_index, g));
  index_uniqueness(g, vertices(g),  get(boost::vertex_index, g));
  index_uniqueness(g, faces(g),     get(boost::face_index, g));
  index_uniqueness(g, halfedges(g), get(boost::halfedge_index, g));

  index_uniqueness(g, edges(g) ,    get(boost::edge_external_index, g));
  index_uniqueness(g, vertices(g),  get(boost::vertex_external_index, g));
  index_uniqueness(g, faces(g),     get(boost::face_external_index, g));
  index_uniqueness(g, halfedges(g), get(boost::halfedge_external_index, g));
}
#if defined(CGAL_USE_SURFACE_MESH)
void index_uniqueness_sm(const SM& g)
{
  std::cerr << "testing Surface_mesh\n";
  index_uniqueness(g, edges(g) ,    get(boost::edge_index, g));
  index_uniqueness(g, vertices(g),  get(boost::vertex_index, g));
  index_uniqueness(g, faces(g),     get(boost::face_index, g));
  index_uniqueness(g, halfedges(g), get(boost::halfedge_index, g));
}
#endif

#if defined(CGAL_USE_OPENMESH)
void index_uniqueness_omesh(const OMesh& g)
{
  std::cerr << "testing OpenMesh\n";
  index_uniqueness(g, edges(g) ,    get(boost::edge_index, g));
  index_uniqueness(g, vertices(g),  get(boost::vertex_index, g));
  index_uniqueness(g, faces(g),     get(boost::face_index, g));
  index_uniqueness(g, halfedges(g), get(boost::halfedge_index, g));
}
#endif

int
main()
{
  std::vector<Polyhedron> polys = poly_data();

  BOOST_FOREACH(Polyhedron p, polys){
    index_uniqueness_poly(p);
  }

#if defined(CGAL_USE_SURFACE_MESH)
  std::vector<SM> sms = sm_data();

  BOOST_FOREACH(SM p, sms){
    index_uniqueness_sm(p);
  }
#endif

#if defined(CGAL_USE_OPENMESH)
  std::vector<OMesh> omeshs = omesh_data();
  BOOST_FOREACH(OMesh p, omeshs){
    index_uniqueness_omesh(p);
  }
#endif

  std::cerr << "done\n";
  return 0;
}

max_stars_repo_name: hlzz/dotfiles

max_issues_repo_name: hlzz/dotfiles

max_forks_repo_name: hlzz/dotfiles


text:
/*
LICENSE: see isogeometric_application/LICENSE.txt
*/

//
//   Project Name:        Kratos
//   Last modified by:    $Author: hbui $
//   Date:                $Date: Nov 11, 2017 $
//   Revision:            $Revision: 1.1 $
//
//

// System includes
#include <string>

// External includes
#include <boost/foreach.hpp>
#include <boost/python.hpp>
#include <boost/python/stl_iterator.hpp>
#include <boost/python/operators.hpp>

// Project includes
#include "includes/define.h"
#include "custom_utilities/control_point.h"
#include "custom_utilities/control_grid.h"
#include "custom_utilities/fespace.h"
#include "custom_utilities/grid_function.h"

namespace Kratos
{

namespace Python
{

using namespace boost::python;

template<class TGridFrunctionType>
typename TGridFrunctionType::FESpaceType::Pointer GridFunction_GetFESpace(TGridFrunctionType& rDummy)
{
    return rDummy.pFESpace();
}

template<class TGridFrunctionType>
void GridFunction_SetFESpace(TGridFrunctionType& rDummy, typename TGridFrunctionType::FESpaceType::Pointer pNewFESpace)
{
    rDummy.SetFESpace(pNewFESpace);
}

template<class TGridFrunctionType>
typename TGridFrunctionType::ControlGridType::Pointer GridFunction_GetControlGrid(TGridFrunctionType& rDummy)
{
    return rDummy.pControlGrid();
}

template<class TGridFrunctionType>
void GridFunction_SetControlGrid(TGridFrunctionType& rDummy, typename TGridFrunctionType::ControlGridType::Pointer pNewControlGrid)
{
    rDummy.SetControlGrid(pNewControlGrid);
}

template<class TGridFrunctionType>
typename TGridFrunctionType::DataType GridFunction_GetValue1(TGridFrunctionType& rDummy, const boost::python::list& xi)
{
    std::vector<double> xi_vec;
    typedef boost::python::stl_input_iterator<double> iterator_value_type;
    BOOST_FOREACH(const iterator_value_type::value_type& v, std::make_pair(iterator_value_type(xi), iterator_value_type() ) )
    {
        xi_vec.push_back(v);
    }

    return rDummy.GetValue(xi_vec);
}

template<class TGridFrunctionType>
typename TGridFrunctionType::DataType GridFunction_GetValue2(TGridFrunctionType& rDummy, const array_1d<double, 3>& xi)
{
    return rDummy.GetValue(xi);
}

template<class TGridFrunctionType>
boost::python::list GridFunction_GetDerivative1(TGridFrunctionType& rDummy, const boost::python::list& xi)
{
    std::vector<double> xi_vec;
    typedef boost::python::stl_input_iterator<double> iterator_value_type;
    BOOST_FOREACH(const iterator_value_type::value_type& v, std::make_pair(iterator_value_type(xi), iterator_value_type() ) )
    {
        xi_vec.push_back(v);
    }

    std::vector<typename TGridFrunctionType::DataType> derivatives;
    rDummy.GetDerivative(derivatives, xi_vec);

    boost::python::list results;
    for (std::size_t i = 0; i < derivatives.size(); ++i)
        results.append(derivatives[i]);

    return results;
}

template<class TGridFrunctionType>
boost::python::list GridFunction_GetDerivative2(TGridFrunctionType& rDummy, const array_1d<double, 3>& xi)
{
    std::vector<typename TGridFrunctionType::DataType> derivatives;
    rDummy.GetDerivative(derivatives, xi);

    boost::python::list results;
    for (std::size_t i = 0; i < derivatives.size(); ++i)
        results.append(derivatives[i]);

    return results;
}

template<class TGridFrunctionType, typename TCoordinatesType>
boost::python::list GridFunction_LocalCoordinates(TGridFrunctionType& rDummy,
        const typename TGridFrunctionType::DataType& v, const TCoordinatesType& xi0)
{
    TCoordinatesType xi = xi0;
    int stat = rDummy.LocalCoordinates(v, xi);
    // KRATOS_WATCH(v)
    // KRATOS_WATCH(stat)
    // KRATOS_WATCH(xi)
    boost::python::list output;
    output.append(stat);
    output.append(xi);
    return output;
}

///////////////////////////////////////////////////////

template<int TDim>
void IsogeometricApplication_AddGridFunctionsToPython()
{
    std::stringstream ss;

    ss.str(std::string());
    ss << "ControlPointGridFunction" << TDim << "D";
    typedef GridFunction<TDim, ControlPoint<double> > ControlPointGridFunctionType;
    class_<ControlPointGridFunctionType, typename ControlPointGridFunctionType::Pointer, boost::noncopyable>
    (ss.str().c_str(), init<typename FESpace<TDim>::Pointer, typename ControlGrid<ControlPoint<double> >::Pointer>())
    .add_property("FESpace", GridFunction_GetFESpace<ControlPointGridFunctionType>, GridFunction_SetFESpace<ControlPointGridFunctionType>)
    .add_property("ControlGrid", GridFunction_GetControlGrid<ControlPointGridFunctionType>, GridFunction_SetControlGrid<ControlPointGridFunctionType>)
    .def("GetValue", &GridFunction_GetValue1<ControlPointGridFunctionType>)
    .def("GetValue", &GridFunction_GetValue2<ControlPointGridFunctionType>)
    .def("GetDerivative", &GridFunction_GetDerivative1<ControlPointGridFunctionType>)
    .def("GetDerivative", &GridFunction_GetDerivative2<ControlPointGridFunctionType>)
    .def(self_ns::str(self))
    ;

    ss.str(std::string());
    ss << "DoubleGridFunction" << TDim << "D";
    typedef GridFunction<TDim, double> DoubleGridFunctionType;
    class_<DoubleGridFunctionType, typename DoubleGridFunctionType::Pointer, boost::noncopyable>
    (ss.str().c_str(), init<typename FESpace<TDim>::Pointer, typename ControlGrid<double>::Pointer>())
    .add_property("FESpace", GridFunction_GetFESpace<DoubleGridFunctionType>, GridFunction_SetFESpace<DoubleGridFunctionType>)
    .add_property("ControlGrid", GridFunction_GetControlGrid<DoubleGridFunctionType>, GridFunction_SetControlGrid<DoubleGridFunctionType>)
    .def("GetValue", &GridFunction_GetValue1<DoubleGridFunctionType>)
    .def("GetValue", &GridFunction_GetValue2<DoubleGridFunctionType>)
    .def("GetDerivative", &GridFunction_GetDerivative1<DoubleGridFunctionType>)
    .def("GetDerivative", &GridFunction_GetDerivative2<DoubleGridFunctionType>)
    .def(self_ns::str(self))
    ;

    ss.str(std::string());
    ss << "Array1DGridFunction" << TDim << "D";
    typedef GridFunction<TDim, array_1d<double, 3> > Array1DGridFunctionType;
    class_<Array1DGridFunctionType, typename Array1DGridFunctionType::Pointer, boost::noncopyable>
    (ss.str().c_str(), init<typename FESpace<TDim>::Pointer, typename ControlGrid<array_1d<double, 3> >::Pointer>())
    .add_property("FESpace", GridFunction_GetFESpace<Array1DGridFunctionType>, GridFunction_SetFESpace<Array1DGridFunctionType>)
    .add_property("ControlGrid", GridFunction_GetControlGrid<Array1DGridFunctionType>, GridFunction_SetControlGrid<Array1DGridFunctionType>)
    .def("GetValue", &GridFunction_GetValue1<Array1DGridFunctionType>)
    .def("GetValue", &GridFunction_GetValue2<Array1DGridFunctionType>)
    .def("GetDerivative", &GridFunction_GetDerivative1<Array1DGridFunctionType>)
    .def("GetDerivative", &GridFunction_GetDerivative2<Array1DGridFunctionType>)
    .def("LocalCoordinates", &GridFunction_LocalCoordinates<Array1DGridFunctionType, array_1d<double, 3> >)
    .def(self_ns::str(self))
    ;

    ss.str(std::string());
    ss << "VectorGridFunction" << TDim << "D";
    typedef GridFunction<TDim, Vector> VectorGridFunctionType;
    class_<VectorGridFunctionType, typename VectorGridFunctionType::Pointer, boost::noncopyable>
    (ss.str().c_str(), init<typename FESpace<TDim>::Pointer, typename ControlGrid<Vector>::Pointer>())
    .add_property("FESpace", GridFunction_GetFESpace<VectorGridFunctionType>, GridFunction_SetFESpace<VectorGridFunctionType>)
    .add_property("ControlGrid", GridFunction_GetControlGrid<VectorGridFunctionType>, GridFunction_SetControlGrid<VectorGridFunctionType>)
    .def("GetValue", &GridFunction_GetValue1<VectorGridFunctionType>)
    .def("GetValue", &GridFunction_GetValue2<VectorGridFunctionType>)
    .def("GetDerivative", &GridFunction_GetDerivative1<VectorGridFunctionType>)
    .def("GetDerivative", &GridFunction_GetDerivative2<VectorGridFunctionType>)
    .def("LocalCoordinates", &GridFunction_LocalCoordinates<VectorGridFunctionType, array_1d<double, 3> >)
    .def(self_ns::str(self))
    ;
}

}  // namespace Python.

} // Namespace Kratos

ext: hpp


text:
//////////////////////////////////////////////////////////////////////////////////
//
//  Python wrappers
//
// -------------------------------------------------------------------------------
//
//  AUTHOR: Miguel Ramos Pernas
//  e-mail: miguel.ramos.pernas@cern.ch
//
//  Last update: 03/07/2017
//
// -------------------------------------------------------------------------------
//
//  Description:
//
//  Wrappers from the AdaptiveBinning library
//
// -------------------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////////////////

#include "GlobalWrappers.hpp"

#include <boost/python.hpp>
#include <boost/python/list.hpp>
#include <boost/python/numpy.hpp>

#include "AdaptiveBinning.hpp"
#include "AdaptiveBinning1D.hpp"
#include "AdaptiveBinning2D.hpp"
#include "Bin.hpp"
#include "Bin1D.hpp"
#include "Bin2D.hpp"
#include "Definitions.hpp"

#include "TPython.h"

namespace py = boost::python;
namespace np = boost::python::numpy;

//_______________________________________________________________________________

// Wrappers for the class AdaptiveBinning
namespace AdBin {

  struct AdaptiveBinningWrap : isis::AdaptiveBinning,
			       py::wrapper<isis::AdaptiveBinning> {

    inline TObject* getStruct( const char *name = "",
			       const char *title = "" ) const {

      return this->get_override("getStruct")(name, title);
    }

    inline PyObject* getStructWrap( const isis::AdaptiveBinning1D &adbin,
				    const char *name = "",
				    const char *title = "" ) const {

      return TPython::ObjectProxy_FromVoidPtr( this->getStruct(name, title),
					       "TObject",
					       false );
    }

    inline py::list getBinListWrap() const {

      return iboost::stdContToBoostList(this->getBinList());
    }

  };

}

// Wrappers for the class AdaptiveBinning1D
namespace AdBin1D {

  //_______________________________________________________________________________
  //
  inline boost::shared_ptr<isis::AdaptiveBinning1D>
  constructor( size_t occ,
	       double vmin,
	       double vmax,
	       np::ndarray values,
	       np::ndarray weights ) {

    auto vec_values  = iboost::numpyArrayToStdCont<isis::Doubles>( values );
    auto vec_weights = iboost::numpyArrayToStdCont<isis::Doubles>( weights );
    auto adbin       = new isis::AdaptiveBinning1D(occ, vmin, vmax,
						   vec_values, vec_weights);

    return boost::shared_ptr<isis::AdaptiveBinning1D>( adbin );
  }

  //_______________________________________________________________________________
  //
  inline boost::shared_ptr<isis::AdaptiveBinning1D>
  constructor_NoWgts( size_t occ,
		      double vmin,
		      double vmax,
		      np::ndarray values ) {

    return constructor(occ, vmin, vmax, values, np::array(py::list()));
  }

  //_______________________________________________________________________________
  //
  inline PyObject* getStruct( const isis::AdaptiveBinning1D &adbin,
		       const char *name = "",
		       const char *title = "" ) {

    return TPython::ObjectProxy_FromVoidPtr( adbin.getStruct(name, title),
					     "TH1D",
					     false );
  }

  BOOST_PYTHON_FUNCTION_OVERLOADS(getStruct_Overloads, getStruct, 1, 3);
}

// Wrappers for the class AdaptiveBinning2D
namespace AdBin2D {

  //_______________________________________________________________________________
  //
  inline boost::shared_ptr<isis::AdaptiveBinning2D>
  constructor( size_t occ,
	       double xmin, double xmax,
	       double ymin, double ymax,
	       np::ndarray xvalues,
	       np::ndarray yvalues,
	       np::ndarray weights ) {

    auto vec_xvalues = iboost::numpyArrayToStdCont<isis::Doubles>( xvalues );
    auto vec_yvalues = iboost::numpyArrayToStdCont<isis::Doubles>( yvalues );
    auto vec_weights = iboost::numpyArrayToStdCont<isis::Doubles>( weights );
    auto adbin       = new isis::AdaptiveBinning2D(occ,
						   xmin, xmax,
						   ymin, ymax,
						   vec_xvalues, vec_yvalues,
						   vec_weights);

    return boost::shared_ptr<isis::AdaptiveBinning2D>( adbin );
  }

  //_______________________________________________________________________________
  //
  inline boost::shared_ptr<isis::AdaptiveBinning2D>
  constructor_NoWgts( size_t occ,
		      double xmin,
		      double xmax,
		      double ymin,
		      double ymax,
		      np::ndarray xvalues,
		      np::ndarray yvalues ) {

    return constructor(occ, xmin, xmax, ymin, ymax, xvalues, yvalues, np::array(py::list()));
  }

  //_______________________________________________________________________________
  //
  inline PyObject* getAdjStruct( const isis::AdaptiveBinning2D &adbin,
				 const char *name = "",
				 const char *title = "" ) {

    return TPython::ObjectProxy_FromVoidPtr( adbin.getAdjStruct(name, title),
					     "TH2Poly",
					     false );
  }

  BOOST_PYTHON_FUNCTION_OVERLOADS(getAdjStruct_Overloads, getAdjStruct, 1, 3);

  //_______________________________________________________________________________
  //
  inline PyObject* getStruct( const isis::AdaptiveBinning2D &adbin,
			      const char *name = "",
			      const char *title = "" ) {

    return TPython::ObjectProxy_FromVoidPtr( adbin.getStruct(name, title),
					     "TH2Poly",
					     false );
  }

  BOOST_PYTHON_FUNCTION_OVERLOADS(getStruct_Overloads, getStruct, 1, 3);
}

max_stars_repo_name: mrpPhys/Isis

max_issues_repo_name: mrpPhys/Isis

max_forks_repo_name: mrpPhys/Isis


text:
#ifndef _MICA_DEF
#define _MICA_DEF

#include <array>
#include <cstdint>
#include <utility>
#include <vector>
#include <boost/program_options/variables_map.hpp>
#include <string>

#include "net/packet.hh"
#include "net/udp.hh"
#include "net/ip_checksum.hh"
#include "net/ip.hh"
#include "net/net.hh"
#include "net/byteorder.hh"

#include <rte_ether.h>
#include <rte_ip.h>
#include <rte_udp.h>

#include "netstar/port.hh"

using namespace seastar;
using namespace std;

namespace netstar{

struct endpoint_info{
    net::ethernet_address eth_addr;
    net::ipv4_address ip_addr;
    uint16_t udp_port;
    std::pair<uint16_t, uint16_t> lcore_port_pair;

    explicit endpoint_info(net::ethernet_address eaddr,
                           net::ipv4_address ipaddr,
                           uint16_t u_port,
                           std::pair<uint16_t, uint16_t> lp_pair) :
            eth_addr(eaddr),
            ip_addr(ipaddr),
            udp_port(u_port),
            lcore_port_pair(lp_pair) {}
};

struct RequestBatchHeader {
    // 0
    uint8_t header[sizeof(ether_hdr) + sizeof(ipv4_hdr) + sizeof(udp_hdr)];
    // 42
    uint8_t magic;  // 0x78 for requests; 0x79 for responses.
    uint8_t num_requests;
    // 44
    uint32_t reserved0;
    // 48
    // KeyValueRequestHeader
};

struct RequestHeader {
    // 0
    uint8_t operation;  // ::mica::processor::Operation
    uint8_t result;     // ::mica::table::Result
    // 2
    uint16_t reserved0;
    // 4
    uint32_t kv_length_vec;  // key_length: 8, value_length: 24
    // 8
    uint64_t key_hash;
    // 16
    uint32_t opaque;
    uint32_t reserved1;
    // 24
    // Key-value data
};

enum class Operation : uint8_t{
    kReset = 0,
    kNoopRead,
    kNoopWrite,
    kAdd,
    kSet,
    kGet,
    kTest,
    kDelete,
    kIncrement,
};

enum class Result : uint8_t {
    kSuccess = 0,
    kError,
    kInsufficientSpace,
    kExists,
    kNotFound,
    kPartialValue,
    kNotProcessed,
    kNotSupported,
    kTimedOut,
    kRejected,
};

// The following definitions and functions are used to initialize
// a so-called "queue mapping". This is used to direct packet from
// one core on the mica client to a specific core on the mica server.
// If the fdir functionality works correctly on our x710 NIC, we wouldn't
// need to calculate the queue mapping in such a complicated manner.

struct port_pair{
    uint16_t local_port;
    uint16_t remote_port;
};

vector<vector<port_pair>>
calculate_queue_mapping(boost::program_options::variables_map& opts,
                        port& pt);
} // namespace netstar

#endif // _MICA_CLIENT_DEF

ext: hh


text:
/*
   Copyright (c) Marshall Clow 2012-2015.

   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)

    For more information, see http://www.boost.org

    Based on the StringRef implementation in LLVM (http://llvm.org) and
    N3422 by Jeffrey Yasskin
        http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3442.html

*/

#ifndef BOOST_STRING_REF_HPP
#define BOOST_STRING_REF_HPP

#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/utility/string_ref_fwd.hpp>
#include <boost/utility/string_view.hpp>

//	The primary template has been changed to basic_string_view
//	The convenience typedefs string_ref still exist.

#endif

max_stars_repo_name: ericsium/boost-header-only

max_issues_repo_name: ericsium/boost-header-only

max_forks_repo_name: ericsium/boost-header-only


text:
/*
 * Sampling.hpp
 *
 *  Created on: Aug 24, 2012
 *      Author: david
 */

#ifndef DASP_IMPL_SAMPLING_HPP_
#define DASP_IMPL_SAMPLING_HPP_

#include "../Point.hpp"
#include "../Seed.hpp"
#include <Eigen/Dense>
#include <vector>

namespace dasp
{
	Eigen::MatrixXf ComputeDepthDensity(const ImagePoints& points, const Parameters& opt);

	Eigen::MatrixXf ComputeSaliency(const ImagePoints& points, const Parameters& opt);

	void AdaptClusterRadiusBySaliency(ImagePoints& points, const Eigen::MatrixXf& saliency, const Parameters& opt);

}

#endif

max_stars_repo_name: jbellis/superpixel-benchmark

max_issues_repo_name: jbellis/superpixel-benchmark

max_forks_repo_name: jbellis/superpixel-benchmark


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

  @copyright 2015 NumScale SAS
  @copyright 2015 J.T.Lapreste

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

#include <boost/simd/function/definition/rem_pio2.hpp>
#include <boost/simd/arch/common/scalar/function/rem_pio2.hpp>
#include <boost/simd/arch/common/generic/function/rem_pio2.hpp>

#endif


text:
// Copyright (c) 2018 Graphcore Ltd. All rights reserved.
#define BOOST_TEST_MODULE ReduceMaxClassGather
#include <poplar/Engine.hpp>
#include <poplibs_support/TestDevice.hpp>

#include "poplibs_support/Algorithm.hpp"
#include "poplibs_test/Util.hpp"
#include "popnn/codelets.hpp"
#include "poputil/VertexTemplates.hpp"

#include <boost/program_options.hpp>
#include <boost/random.hpp>
#include <cstdint>

using namespace poplar;
using namespace poplar::program;
using namespace poplibs_test::util;
using namespace poputil;
using namespace poplibs_support;

namespace {

static void modelVertex(const std::vector<double> &activations, unsigned index,
                        std::vector<double> &maxActs,
                        std::vector<std::uint64_t> &maxIndices, unsigned size,
                        unsigned divisor) {

  const auto nOutputs = (size + divisor - 1) / divisor;
  for (std::size_t i = 0; i < nOutputs; ++i) {
    unsigned maxLabel = i * divisor;
    double max = activations[maxLabel];
    const auto end = std::min(size, maxLabel + divisor);
    for (std::size_t j = maxLabel + 1; j < end; ++j) {
      if (activations[j] > max) {
        max = activations[j];
        maxLabel = j;
      }
    }
    maxActs[i] = max;
    maxIndices[i] = maxLabel + index;
  }
}

static bool doTest(const DeviceType &deviceType, const Type &activationsType,
                   const Type &labelType, unsigned divisor, unsigned size) {
  auto device = createTestDevice(deviceType);
  auto &target = device.getTarget();

  if ((divisor & (divisor - 1)) != 0) {
    throw std::logic_error("divisor is not a power of 2");
  }
  const auto nOutputs = (size + divisor - 1) / divisor;
  if (nOutputs > target.getNumWorkerContexts()) {
    throw std::logic_error(
        "Divisor is not large enough for the vertex to process all inputs");
  }

  Graph graph(target);
  popnn::addCodelets(graph);
  auto partialsType = (activationsType == HALF || activationsType == FLOAT)
                          ? FLOAT
                          : activationsType;

  auto activations = graph.addVariable(activationsType, {size}, "activations");
  auto maxActs =
      graph.addVariable(partialsType, {nOutputs}, "maxValuePartials");
  auto maxIndices =
      graph.addVariable(labelType, {nOutputs}, "maxIndexPartials");
  graph.setTileMapping(activations, 0);
  graph.setTileMapping(maxActs, 0);
  graph.setTileMapping(maxIndices, 0);

  Sequence uploadProg, downloadProg;
  std::vector<std::pair<std::string, char *>> tmap;
  auto rawHostActivations = allocateHostMemoryForTensor(
      activations, "activations", graph, uploadProg, downloadProg, tmap);
  auto rawHostMaxActs = allocateHostMemoryForTensor(
      maxActs, "maxValuePartials", graph, uploadProg, downloadProg, tmap);
  auto rawHostMaxIndices = allocateHostMemoryForTensor(
      maxIndices, "maxIndexPartials", graph, uploadProg, downloadProg, tmap);

  std::mt19937 randomEngine;
  std::vector<double> hostActivations(size);
  const bool isFpType = activationsType == FLOAT || activationsType == HALF;
  const bool isInt = activationsType == INT;
  writeRandomValues(target, activationsType, hostActivations.data(),
                    hostActivations.data() + hostActivations.size(),
                    isInt ? std::numeric_limits<int>::min() : 0.0,
                    isFpType ? 1.0 : std::numeric_limits<int>::max(),
                    randomEngine);
  copy(target, hostActivations.data(), size, activationsType,
       rawHostActivations.get());

  auto cs = graph.addComputeSet();
  auto v = graph.addVertex(cs, templateVertex("popnn::ReduceMaxClassGather",
                                              activationsType, labelType));
  graph.setTileMapping(v, 0);

  // TODO: T12987 Add test case for when index != 0.
  unsigned index = 0;
  graph.connect(v["activations"], activations);
  graph.setInitialValue(v["index"], index);
  graph.connect(v["maxValue"], maxActs);
  graph.connect(v["maxIndex"], maxIndices);
  graph.setInitialValue(v["size"], size);
  graph.setInitialValue(v["workerSize"], divisor);

  Engine e(std::move(graph), Sequence{uploadProg, Execute(cs), downloadProg});
  attachStreams(e, tmap);
  device.bind([&](const Device &d) { e.loadAndRun(d); });

  std::vector<double> modelMaxActs(nOutputs);
  std::vector<std::uint64_t> modelMaxIndices(nOutputs);
  modelVertex(hostActivations, index, modelMaxActs, modelMaxIndices, size,
              divisor);

  std::vector<double> hostMaxActs(nOutputs);
  std::vector<std::uint64_t> hostMaxIndices(nOutputs);
  copy(target, partialsType, rawHostMaxActs.get(), hostMaxActs.data(),
       nOutputs);
  copy(target, labelType, rawHostMaxIndices.get(), hostMaxIndices.data(),
       nOutputs);

  bool success = true;
  success &= checkIsClose("maxValue", hostMaxActs.data(), {nOutputs},
                          modelMaxActs.data(), nOutputs, 0.1,
                          activationsType == HALF ? 1e-7 : 1e-20);
  success &= checkEqual("maxIndex", hostMaxIndices.data(), {nOutputs},
                        modelMaxIndices.data(), nOutputs);
  return success;
}

} // end anonymous namespace

int main(int argc, char **argv) {
  namespace po = boost::program_options;

  DeviceType deviceType;
  Type activationType;
  Type labelType = UNSIGNED_INT;
  unsigned divisor, size;
  po::options_description desc("Options");
  // clang-format off
  desc.add_options()
    ("help", "Print help")
    ("device-type",
     po::value<DeviceType>(&deviceType)->required(),
     "Device Type")
    ("activation-type",
     po::value<Type>(&activationType)->required(),
     "Element type for input activations")
    ("divisor",
     po::value<unsigned>(&divisor)->required(),
     "Factor by which to reduce max class")
    ("size",
     po::value<unsigned>(&size)->required(),
     "Total size to process with vertex");
  // clang-format on

  po::variables_map vm;
  try {
    po::store(po::parse_command_line(argc, argv, desc), vm);
    if (vm.count("help")) {
      std::cout << desc << "\n\n";
      return 1;
    }
    po::notify(vm);
  } catch (std::exception &e) {
    std::cerr << "error: " << e.what() << "\n";
    return 1;
  }

  if (!doTest(deviceType, activationType, labelType, divisor, size))
    return 1;
  return 0;
}

ext: cpp

max_stars_repo_name: graphcore/poplibs

max_issues_repo_name: graphcore/poplibs

max_forks_repo_name: graphcore/poplibs


text:
#ifndef GCT_IO_CONTEXT_HPP
#define GCT_IO_CONTEXT_HPP
#include <boost/asio/io_context.hpp>
#include <thread>
#include <vector>
#include <memory>
namespace gct {
  boost::asio::io_context &get_io_context();
  class thread_pool {
  public:
    static void init();
  private:
    thread_pool();
    ~thread_pool();
    std::vector< std::thread > threads;
    std::unique_ptr< boost::asio::io_context::work > keep;
  };
  template< typename F >
  void async(
    unsigned int max,
    const F &func
  ) {
    const auto jobs = std::min( std::thread::hardware_concurrency(), max );
    for( unsigned int i = 0u; i != jobs; ++i )
      get_io_context().post( func );
  }
}
#endif

max_stars_repo_name: Fadis/gct

max_issues_repo_name: Fadis/gct

max_forks_repo_name: Fadis/gct


text:
//
// Copyright (c) 2016-2017 Haggai Eran, Gabi Malka, Lior Zeno, Maroun Tork
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//  * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

#include <pcap/pcap.h>
#include <iostream>
#include <string>
#include <unistd.h>
#include <endian.h>
#include <boost/lexical_cast.hpp>
#include <algorithm>
#include "gtest/gtest.h"

#include "udp.h"
#include "tb.h"

using std::cout;
using std::endl;
using std::string;
using boost::lexical_cast;

using namespace udp_tb;

struct packet_handler_context {
    mlx::stream& stream;
    int count;
    int range_start;
    int range_end;
    pkt_id_verifier* verifier;
    hls::stream<mlx::user_t>* user_values;
    testbench::callback_t callback;

    explicit packet_handler_context(mlx::stream& stream,
                                    hls::stream<mlx::user_t>* user_values) :
        stream(stream), count(0), user_values(user_values) {}
};

void packet_handler(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes)
{
    auto context = reinterpret_cast<packet_handler_context*>(user);
    mlx::stream& stream = context->stream;
    const int b = MLX_AXI4_WIDTH_BYTES;
    mlx::user_t mlx_user;
    if (context->user_values) {
        mlx_user = (random() & 1) ? MLX_TUSER_MAGIC : 0;
        if (mlx_user)
            context->user_values->write(mlx_user);
    } else {
        mlx_user = MLX_TUSER_MAGIC;
    }

    if (h->caplen != h->len)
        return;

    if (context->count < context->range_start || context->count >= context->range_end)
        goto end;

    for (unsigned word = 0; word < ALIGN(h->len, b); word += b) {
        mlx::axi4s input(0, 0xffffffff, false);
        for (unsigned byte = 0; byte < b && word + byte < h->len; ++byte)
            input.data(input.data.width - 1 - 8 * byte, input.data.width - 8 - 8 * byte) = bytes[word + byte];
        if ((word + b) >= h->len) {
            input.keep = hls_ik::axi_data::keep_bytes(h->len - word - b);
            input.last = true;
        }

        input.id = context->count & 7;
        input.user = mlx_user;
        if (context->verifier && word == 0)
                context->verifier->inc(input.id);
        stream.write(input);
    }
end:
    ++context->count;

    if (context->callback)
        context->callback();
}

testbench::testbench() :
    cxp2sbu("cxp2sbu"), sbu2cxp("sbu2cxp"),
    nwp2sbu("nwp2sbu"), sbu2nwp("sbu2nwp"),
    count(0)
{}

int testbench::read_pcap(const string& filename, mlx::stream& stream,
        int range_start, int range_end, pkt_id_verifier* verifier,
        hls::stream<mlx::user_t>* user_values)
{
    return read_pcap_callback(filename, stream, range_start, range_end, verifier, user_values, NULL);
}

int testbench::read_pcap_callback(
    const std::string& filename, mlx::stream& stream,
    int range_start, int range_end,
    pkt_id_verifier* verifier,
    hls::stream<mlx::user_t>* user_values,
    testbench::callback_t callback)
{
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t *file = pcap_open_offline(filename.c_str(), errbuf);

    if (!file) {
        fprintf(stderr, "%s\n", errbuf);
        return -1;
    }

    auto context = packet_handler_context(stream, user_values);
    context.range_start = range_start; context.range_end = range_end;
    context.verifier = verifier;
    context.callback = callback;
    int ret = pcap_loop(file, 0, &packet_handler, (u_char *)&context);
    if (ret == -1) {
        perror("pcap_loop returned error");
        return -1;
    }

    pcap_close(file);

    return context.count;
}

int testbench::write_pcap(FILE* file, mlx::stream& stream, bool expected_lossy,
                          pkt_id_verifier* verifier, hls::stream<mlx::user_t>* user_values)
{
    int ret;
    int count = 0;

    pcap_t *dead = pcap_open_dead(DLT_EN10MB, 65535);
    if (!dead) {
        perror("pcap_open_dead failed");
        return -1;
    }

    pcap_dumper_t *output = pcap_dump_fopen(dead, file);
    if (!output) {
        perror("pcap_dump_open failed");
        return -1;
    }

    u_char buffer[65535];
    pcap_pkthdr h = {};
    h.len = 0;
    mlx::pkt_id_t cur_pkt_id;
    mlx::user_t cur_user;

    while (!stream.empty()) {
        mlx::axi4s w = stream.read();
        const mlx::user_t masked_user = w.user & MLX_TUSER_MAGIC_MASK;

        if (h.len == 0) {
            // new packet
            if (verifier) {
                verifier->dec(w.id);
                cur_pkt_id = w.id;
            }
            if (masked_user && user_values) {
                EXPECT_FALSE(user_values->empty());
                cur_user = user_values->read();
            } else if (masked_user && !user_values) {
                cur_user = MLX_TUSER_MAGIC;
            } else if (!masked_user) {
                cur_user = 0;
            }
        } else {
            // middle of a packet
            if (verifier)
                EXPECT_EQ(w.id, cur_pkt_id);
        }
        EXPECT_EQ(masked_user, cur_user) << "tuser";

        for (int byte = 0; byte < w.data.width / 8; ++byte)
            buffer[h.len + byte] = w.data(w.data.width - 1 - byte * 8,
                                          w.data.width - 8 - byte * 8);
        h.len += w.data.width / 8;
        if (w.last) {
            for (int i = 0; i < w.data.width / 8; ++i)
                if (!w.keep(i, i))
                    --h.len;
                else
                    break;
            /* Minimum Ethernet packet length is 64 bytes including the FCS */
            h.caplen = h.len;
            if (!w.user(0, 0)) /* Drop bit cleared */ {
                pcap_dump((u_char *)output, &h, buffer);
                ++count;
            }
            EXPECT_EQ(bool(w.user(2,2)), expected_lossy);
            h.len = 0;
        } else {
            EXPECT_EQ(~w.keep, 0);
        }
    }

    EXPECT_EQ(h.len, 0);
    EXPECT_TRUE(stream.empty());
    EXPECT_TRUE(!verifier || verifier->verify());

    ret = pcap_dump_flush(output);
    if (ret) {
        perror("pcap_dump_flush returned error");
        return -1;
    }

    pcap_close(dead);
    fdatasync(fileno(file));

    return count;
}

void testbench::run()
{
    // TODO run simulation until it ends?
    for (int i = 0; i < num_extra_clocks(); ++i)
        top();

    EXPECT_TRUE(nwp2sbu.empty());
    EXPECT_TRUE(cxp2sbu.empty());
}

bool testbench::compare_output(const string& pcap1, const string& filter1,
                               const string& pcap2, const string& filter2)
{
    string dump1 = "tcpdump -r '" + pcap1 + "' -xxtn " + filter1;
    string dump2 = "tcpdump -r '" + pcap2 + "' -xxtn " + filter2;
    string compare_output = "bash -c \"diff -u <(" + dump1 + ") <(" + dump2 + ")\"";
    cout << compare_output << endl;
    int ret = system(compare_output.c_str());
    return ret == 0 && !WEXITSTATUS(ret);
}

bool testbench::compare_output(const string& pcap1, const string& filter1,
                               const string& output_txt_file)
{
    string dump1 = "tcpdump -r '" + pcap1 + "' -xxtn '" + filter1 + "'";
    string compare_output = "bash -c \"diff -u <(" + dump1 + ") '" + output_txt_file + "'\"";
    cout << compare_output << endl;
    int ret = system(compare_output.c_str());
    return ret == 0 && !WEXITSTATUS(ret);
}

string testbench::filename(FILE* file)
{
    return "/proc/self/fd/" + lexical_cast<string>(fileno(file));
}

void testbench::TearDown()
{
    EXPECT_TRUE(nwp2sbu.empty());
    EXPECT_TRUE(cxp2sbu.empty());
    EXPECT_TRUE(sbu2nwp.empty());
    EXPECT_TRUE(sbu2cxp.empty());
}

pkt_id_verifier::pkt_id_verifier() : count() {}

void pkt_id_verifier::inc(mlx::pkt_id_t id)
{
    if (id)
        ++count[id];
}

void pkt_id_verifier::dec(mlx::pkt_id_t id)
{
    if (id)
        EXPECT_TRUE(--count[id] >= 0);
}

bool pkt_id_verifier::verify() const
{
    return std::all_of(count, &count[8], [](int x) { return x >= 0; });
}

max_stars_repo_name: haggaie/nica

max_issues_repo_name: lastweek/nica

max_forks_repo_name: lastweek/nica


text:
/* handles a connection with the client
 */

#include <strings.h>

#include "handler.hpp"
#include "../utility/common.hpp"
#include "../utility/easylogging++.h"

#include <errno.h>

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

#include <boost/lexical_cast.hpp>

#ifdef __cplusplus /* If this is a C++ compiler, use C linkage */
extern "C" {
#endif

#include "../utility/http/http_parse.h"

#ifdef __cplusplus /* If this is a C++ compiler, end C linkage */
}
#endif

using std::string;
using boost::lexical_cast;
using myio::StreamChannel;

#define _LOG_PREFIX(inst) << "hndlr= " << (inst)->objId() << ": "

/* "inst" stands for instance, as in, instance of a class */
#define vloginst(level, inst) VLOG(level) _LOG_PREFIX(inst)
#define vlogself(level) vloginst(level, this)

#define dvloginst(level, inst) DVLOG(level) _LOG_PREFIX(inst)
#define dvlogself(level) dvloginst(level, this)

#define loginst(level, inst) LOG(level) _LOG_PREFIX(inst)
#define logself(level) loginst(level, this)

Handler::Handler(StreamChannel::UniquePtr channel,
                 HandlerObserver* observer)
    : channel_(std::move(channel))
    , observer_(observer)
    , http_req_state_(HTTPReqState::HTTP_REQ_STATE_REQ_LINE)
    , remaining_req_body_length_(0)
{
    CHECK_NOTNULL(observer_);
    bzero(&current_req_, sizeof current_req_);

    channel_->set_observer(this);
}

void
Handler::_maybe_consume_input()
{
    vlogself(2) << "begin";

    char *line = nullptr;
    bool keep_consuming = true;

    // don't free this inbuf
    struct evbuffer *inbuf = channel_->get_input_evbuf();
    CHECK_NOTNULL(inbuf);

    vlogself(2) << "num bytes available in inbuf: "
                << evbuffer_get_length(inbuf);

    if (evbuffer_get_length(inbuf) == 0) {
        vlogself(2) << "no input available";
        return;
    }

    do {
        switch (http_req_state_) {
        case HTTPReqState::HTTP_REQ_STATE_REQ_LINE: {
            /* readln() does drain the buffer */
            size_t line_len = 0;
            line = evbuffer_readln(
                inbuf, &line_len, EVBUFFER_EOL_CRLF_STRICT);
            if (line) {
                CHECK_EQ(current_req_.active, 0);
                vlogself(2) << "got request line: [" << line << "]";

                // we handle exactly one request
                CHECK_EQ(line_len, common::http::request_line_len);
                DCHECK(!strcmp(line, common::http::request_line));

                current_req_.active = 1;

                http_req_state_ = HTTPReqState::HTTP_REQ_STATE_HEADERS;
                free(line);
                line = nullptr;
            } else {
                // not enough input data to find whole request line
                keep_consuming = false;
            }
            break;
        }

        case HTTPReqState::HTTP_REQ_STATE_HEADERS: {
            size_t line_len = 0;
            while (nullptr != (line = evbuffer_readln(
                                   inbuf, &line_len, EVBUFFER_EOL_CRLF_STRICT)))
            {
                if (line[0] == '\0') {
                    vlogself(2) << "no more hdrs";
                    free(line);
                    line = nullptr;

                    const RequestInfo& reqinfo = current_req_;
                    vlogself(2) << "req: resp_meta_size: "
                                << reqinfo.resp_meta_size
                                << ", resp_body_size: "
                                << reqinfo.resp_body_size
                                << ", content_length: "
                                << remaining_req_body_length_;

                    if (remaining_req_body_length_) {
                        // there's a req body we need to consume
                        http_req_state_ = HTTPReqState::HTTP_REQ_STATE_BODY;
                    } else {
                        // no req body, so go serve response
                        _serve_response();
                    }

                    break; // out of while loop trying to read header
                           // lines
                }
                else {
                    vlogself(2) << "whole req hdr line: [" << line << "]";

                    CHECK_LT(line_len, 127); // arbitrary value

                    char *tmp = strchr(line, ':');
                    CHECK_NOTNULL(tmp);
                    // check bounds
                    CHECK_LE((tmp - line), (line_len - 3));

                    *tmp = '\0'; /* colon becomes NULL */
                    ++tmp;
                    *tmp = '\0'; /* blank space becomes NULL */
                    ++tmp;

                    const auto name_str = line;
                    const auto value_str = tmp;

                    RequestInfo& reqinfo = current_req_;

                    struct {
                        const char* hdr_name;
                        size_t* hdr_value_ptr;
                    } hdrs_to_parse[] = {
                        {
                            common::http::resp_meta_size_name,
                            &(reqinfo.resp_meta_size),
                        },
                        {
                            common::http::resp_body_size_name,
                            &(reqinfo.resp_body_size),
                        },
                        {
                            common::http::content_length_name,
                            &remaining_req_body_length_,
                        }
                    };

                    auto matched = false;
                    for (auto hdr_to_parse : hdrs_to_parse) {
                        if (!strcmp(name_str, hdr_to_parse.hdr_name)) {
                            try {
                                *(hdr_to_parse.hdr_value_ptr) =
                                    lexical_cast<size_t>(value_str);
                                matched = true;
                            } catch (const boost::bad_lexical_cast&) {
                                logself(FATAL) << "bad header value: " << value_str;
                            }
                            break;
                        }
                    }

                    CHECK(matched) << "unknown header name: [" << name_str << "]";

                    free(line);
                    line = nullptr;
                }
            } // end while readline for headers

            if (http_req_state_ == HTTPReqState::HTTP_REQ_STATE_HEADERS) {
                // if we're still trying to get more headers, that
                // means there was not enough input
                keep_consuming = false;
            }

            break;
        }

        case HTTPReqState::HTTP_REQ_STATE_BODY: {
            CHECK_GT(remaining_req_body_length_, 0);
            vlogself(2) << "drain body bytes that might already in input buf";
            const auto buflen = evbuffer_get_length(inbuf);
            const auto drain_len = std::min(buflen, remaining_req_body_length_);
            vlogself(2) << buflen << ", " << remaining_req_body_length_ << ", "
                        << drain_len;
            if (drain_len > 0) {
                auto rv = evbuffer_drain(inbuf, drain_len);
                CHECK_EQ(rv, 0);
                remaining_req_body_length_ -= drain_len;
            }

            if (remaining_req_body_length_ > 0) {
                CHECK_EQ(drain_len, buflen);
                CHECK_EQ(evbuffer_get_length(inbuf), 0);
                keep_consuming = false;
                vlogself(2) << "tell channel to drop "
                        << remaining_req_body_length_ << " future bytes";
                channel_->drop_future_input(
                    this, remaining_req_body_length_, false);
            } else {
                // have fully finished with req body, so go serve
                _serve_response();
            }
            break;
        }

        default:
            logself(FATAL) << "invalid state: " << common::as_integer(http_req_state_);
            break;
        }

    } while (keep_consuming && evbuffer_get_length(inbuf) > 0);

    if (line) {
        free(line);
    }
    vlogself(2) << "done";
    return;
}

void
Handler::_serve_response()
{
    CHECK_EQ(remaining_req_body_length_, 0);
    CHECK_EQ(current_req_.active, 1);

    std::unique_ptr<struct evbuffer, void(*)(struct evbuffer*)> buf(
        evbuffer_new(), evbuffer_free);
    CHECK_NOTNULL(buf.get());

    auto rv = evbuffer_add_printf(
        buf.get(),
        "%s\r\n"
        "%s: %ld\r\n"
        "%s: ",
        common::http::resp_status_line,
        common::http::content_length_name, current_req_.resp_body_size,
        common::http::dummy_name);
    CHECK_GT(rv, 0);

    /* the resp_meta_size is NOT strict; we don't have to write
     * exactly that amount, just close to it is fine.
     */

    // how much extra dummy header/meta bytes do we need to send
    ssize_t num_dummy_hdr_bytes_needed =
        current_req_.resp_meta_size - evbuffer_get_length(buf.get());
    num_dummy_hdr_bytes_needed -= 4; /* for the \r\n\r\n we will add
                                      * later to close the resp
                                      * status/header part */
    if (num_dummy_hdr_bytes_needed > 0) {
        // only if it's greater than zero do we tell channel to write
        // dummy

        // BUT FIRST: tell channel to write buf
        rv = channel_->write_buffer(buf.get());
        CHECK_EQ(rv, 0);
        DCHECK_EQ(evbuffer_get_length(buf.get()), 0);

        vlogself(2) << "tell channel to write "
                    << num_dummy_hdr_bytes_needed
                    << " dummy header bytes";
        rv = channel_->write_dummy(num_dummy_hdr_bytes_needed);
        CHECK_EQ(rv, 0);
    } else {
        // need to write at least one byte for dummy header value
        rv = evbuffer_add_printf(buf.get(), "n/a");
        CHECK_EQ(rv, 3) << "rv= " << rv;
    }

    // end the dummy header and overall resp meta info
    rv = evbuffer_add_printf(buf.get(), "\r\n\r\n");
    CHECK_GT(rv, 0);

    rv = channel_->write_buffer(buf.get());
    CHECK_EQ(rv, 0);
    DCHECK_EQ(evbuffer_get_length(buf.get()), 0);

    if (current_req_.resp_body_size > 0) {
        vlogself(2) << "tell channel to write "
                    << current_req_.resp_body_size << " dummy BODY bytes";

        rv = channel_->write_dummy(current_req_.resp_body_size);
        CHECK_EQ(rv, 0);
    }

    vlogself(2) << "reset state to get next request";

    bzero(&current_req_, sizeof current_req_);
    http_req_state_ = HTTPReqState::HTTP_REQ_STATE_REQ_LINE;
}

void
Handler::onNewReadDataAvailable(StreamChannel* channel) noexcept
{
    CHECK_EQ(channel_.get(), channel);
    vlogself(2) << "notified of new data";
    _maybe_consume_input();
}

void
Handler::onEOF(StreamChannel* channel) noexcept
{
    CHECK_EQ(channel_.get(), channel);
    DestructorGuard dg(this);
    observer_->onHandlerDone(this);
}

void
Handler::onError(StreamChannel* channel, int errorcode) noexcept
{
    CHECK_EQ(channel_.get(), channel);
    logself(WARNING) << "channel closed on error: " << errorcode;
    DestructorGuard dg(this);
    observer_->onHandlerDone(this);
}

void
Handler::onInputBytesDropped(StreamChannel* channel, size_t len) noexcept
{
    vlogself(2) << "notified of " << len << " input bytes dropped";
    CHECK_EQ(channel_.get(), channel);
    CHECK_EQ(http_req_state_, HTTPReqState::HTTP_REQ_STATE_BODY);
    CHECK_EQ(remaining_req_body_length_, len);

    remaining_req_body_length_ -= len;
    CHECK_EQ(remaining_req_body_length_, 0);

    _serve_response();
}

Handler::~Handler()
{
    vlogself(2) << "handler destructor";
}

ext: cc

max_stars_repo_name: cauthu/shadow-browser-plugin

max_issues_repo_name: cauthu/shadow-browser-plugin

max_forks_repo_name: cauthu/shadow-browser-plugin


text:
////////////////////////////////////////////////////////////////////////////////////////////////////
// map_list_of.cpp
// Implement the map_list_of utility from Boost.Assign.
//
//  Copyright 2013 Eric Niebler. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <map>
#include <iostream>
#include <boost/proto/v5/proto.hpp>
using namespace boost::proto;

struct map_list_of_ {};

struct MapListOf : def<
    match(
        case_(  terminal(map_list_of_),
            void()
        ),
        case_(  function(MapListOf, terminal(_), terminal(_)),
            MapListOf(_child0),
            assign(subscript(_data, _value(_child1)), _value(_child2))
        )
    )
> {};

template<typename ExprDesc>
struct map_list_of_expr
  : expr<map_list_of_expr<ExprDesc>, domain<_,MapListOf>>
{
    using expr<map_list_of_expr<ExprDesc>, domain<_,MapListOf>>::expr;

    template< class K, class V, class C, class A>
    operator std::map<K, V, C, A> () const
    {
        assert_matches<MapListOf>(*this);
        std::map<K, V, C, A> map;
        MapListOf()(*this, data = map);
        return map;
    }
};

constexpr map_list_of_expr<terminal(map_list_of_)> map_list_of{};

int main()
{
    // Initialize a map with a list of key/value pairs
    std::map<int, int> vals = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);

    // Print out the key/value pairs
    for(auto const &p : vals)
    {
        std::cout << p.first << " : " << p.second << std::endl;
    }
}


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

#include <algorithm>
using std::remove_if;
#include <cctype>
using std::isalpha;
#include <cmath>
using std::sqrt;
#include <iostream>
using std::cout;
using std::endl;
#include <fstream>
using std::getline;
using std::ifstream;
#include <string>
using std::string;
#include <utility>
using std::pair;
#include <vector>
using std::vector;

#include "bloomfilter/BloomFilter.h"
using bloomfilter::BloomFilter;
using bloomfilter::BloomFilterStandard;
#include "bloomfilter/HashSet.h"
using bloomfilter::HashSetPair;
#include "bloomfilter/InsertionPolicy.h"
using bloomfilter::InsertionBigramWithSentinel;
using bloomfilter::InsertionTrigramWithSentinel;
#include "hash/HashFactory.h"
#include "util/Timer.h"
using util::Timer;

#include "graph/Traversals.h"

#include <boost/algorithm/string.hpp>

#include "bfeattacks/FilterDictionary.h"
#include "bfeattacks/FilterRequireExactly.h"
#include "bfeattacks/FilterSize.h"
#include "bfeattacks/SingleRecord.h"

#include "bfeattacks/Accumulator.h"
using bfeattacks::Accumulator;

void test_bfe(string test, string alphabet,
              vector<graph::Traversal> &traversals, Accumulator &stats);

void test_bfe(string test, string alphabet,
              vector<graph::Traversal> &traversals, Accumulator &stats) {
  // Construct the record
  HashSetPair hs(30);
  hs.add(hash::MD5).add(hash::SHA3_256);
  bfeattacks::SingleRecord<BloomFilterStandard> rec(
      BloomFilterStandard(1000, hs));

  // Populate the bloom filter
  rec.insert(test);

  // Construct the graph
  rec.construct_graph(alphabet);
  //std::ofstream outfile(test + ".graphml");
  //rec.write_graphml(outfile);
  //outfile.close();

  //cout << rec.bf << endl;
  // cout << "estimated elements: " << rec.estimate_elements() << endl;

  // Run the traversals
  rec.setup_traversals(traversals);
  for (const auto i : traversals)
    rec.run_traversal(i);
  rec.simplify_paths();

  // Apply filters
  auto est_elts = std::lround(rec.estimate_elements());
  size_t est_len =
      static_cast<size_t>(est_elts) - 1; // 1 is n of n-grams minus 1
  // cout << "Filter len [" << est_len - 1 << ", " << est_len + 1 << "]" <<
  // endl;
  bfeattacks::filter_size(rec, est_len - 1, est_len + 1);
  bfeattacks::filter_require_exactly(rec);

  // bfeattacks::filter_dictionary(rec);

  // Collect stats
  stats.add(rec);
}

int main(int argc, char **argv) {
  vector<graph::Traversal> traversals = {
    { graph::Traversal::depth_first_search, graph::Traversal::all_simple_paths,
      graph::Traversal::all_edge_disjoint_paths }
  };
  Accumulator stats(traversals);

  if (argc <= 1) {
    // Smoke test
    // cout << "Test [1/4]--------------------------------------\n";
    // test_bfe("mississippi", "abcdefghijklmnopqrstuvwxyz", traversals, stats);
    // cout << "Test [2/4]--------------------------------------\n";
    // test_bfe("william", "abcdefghijklmnopqrstuvwxyz", traversals, stats);
    test_bfe("william", "abcdefghijklmnopqrstuvwxyz", traversals, stats);
    // cout << "Test [3/4]--------------------------------------\n";
    // test_bfe("ramakrishna", "abcdefghijklmnopqrstuvwxyz", traversals, stats);
    // cout << "Test [4/4]--------------------------------------\n";
    test_bfe("max", "abcdefghijklmnopqrstuvwxyz", traversals, stats);
    // test_bfe("youngbloodstillwell", "abcdefghijklmnopqrstuvwxyz", traversals,
    // stats);

    cout << stats << endl;
    return 0;
  }

  string filename(argv[1]);
  cout << "Will process file: '" << filename << "'\n";
  ifstream input(filename);

  for (string line; getline(input, line);) {
    // Clean up the string to be sure
    boost::algorithm::to_lower(line);
    line.erase(
        remove_if(line.begin(), line.end(), [](char a) { return !isalpha(a); }),
        line.end());

    test_bfe(line, "abcdefghijklmnopqrstuvwxyz", traversals, stats);
  }

  cout << stats << endl;

  return 0;
}


text:
#ifndef TRADESREQUESTPARAMETERS_HPP
#define TRADESREQUESTPARAMETERS_HPP

#include <QVariant>
#include <QMetaType>

#include <boost/optional.hpp>

#include "basictypes.h"

namespace bitinvest {
namespace core {
namespace bom {

struct TradesParameters
{
    TradesParameters():
        mSymbol(boost::none),
        mFilterSpecifier(boost::none),
        mDataSpecifier(boost::none)
    {}

    TradesParameters(
            const Symbol &iSymbol):
        mSymbol(iSymbol), mFilterSpecifier(boost::none), mDataSpecifier(boost::none)
    {}

    TradesParameters(
            const Symbol &iSymbol,
            const DataSpecifier& iDataSpecifier):
        mSymbol(iSymbol), mFilterSpecifier(boost::none), mDataSpecifier(iDataSpecifier)
    {}

    TradesParameters(
            const Symbol &iSymbol,
            const FilterSpecifier & iFilterSpecifier):
        mSymbol(iSymbol), mFilterSpecifier(iFilterSpecifier), mDataSpecifier(boost::none)
    {}

    TradesParameters(
            const Symbol & iSymbol,
            const FilterSpecifier & iFilterSpecifier,
            const DataSpecifier & iDataSpecifier):
        mSymbol(iSymbol), mFilterSpecifier(iFilterSpecifier), mDataSpecifier(iDataSpecifier)
    {}

    TradesParameters(const TradesParameters & other):
            mSymbol(other.mSymbol), mFilterSpecifier(other.mFilterSpecifier), mDataSpecifier(other.mDataSpecifier)
    {}

    boost::optional<Symbol> mSymbol;
    boost::optional<FilterSpecifier> mFilterSpecifier;
    boost::optional<DataSpecifier> mDataSpecifier;
};

}
}
}

Q_DECLARE_METATYPE(bitinvest::core::bom::TradesParameters)
#endif // TRADESREQUESTPARAMETERS_HPP

max_stars_repo_name: AndreaCitrolo/Trader

max_issues_repo_name: AndreaCitrolo/Trader

max_forks_repo_name: AndreaCitrolo/Trader


text:
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

#include "stdafx.h"

#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"
#include "Common/Uri.h"
#include "AssertWF.h"

using namespace Common;

namespace Common
{
    class UriTest
    {
    };

    BOOST_FIXTURE_TEST_SUITE(UriTestSuite,UriTest)

    BOOST_AUTO_TEST_CASE(UriCreationTest)
    {
        Uri one(L"scheme");
        Uri two(L"scheme", L"auth");
        Uri three(L"scheme", L"auth", L"path");
        Uri four(L"scheme", L"auth", L"path/morePath");
        Uri five(L"wf", L"foo", L"bar");

        CODING_ERROR_ASSERT(one.Scheme == two.Scheme);
        CODING_ERROR_ASSERT(one.Segments.empty() && two.Segments.empty());
        CODING_ERROR_ASSERT(two.Authority == three.Authority);
        CODING_ERROR_ASSERT(one.Authority != two.Authority);
        CODING_ERROR_ASSERT(one.Path != four.Path);
        CODING_ERROR_ASSERT(three.Segments.size() == 1);
        CODING_ERROR_ASSERT(four.Segments.size() == 2);
        CODING_ERROR_ASSERT(one.Scheme != five.Scheme);
        CODING_ERROR_ASSERT(two.Authority != five.Authority);
        CODING_ERROR_ASSERT(three.Path != five.Path);
    }

    BOOST_AUTO_TEST_CASE(UriSchemeCompareTest)
    {
        Uri one(L"red");
        Uri two(L"Red");
        Uri three(L"blue");
        Uri four(L"blue");

        CODING_ERROR_ASSERT(one == two);
        CODING_ERROR_ASSERT(three == four);
        CODING_ERROR_ASSERT(one != three);
    }

    BOOST_AUTO_TEST_CASE(UriAuthorityCompareTest)
    {
        Uri one(L"green", L"square");
        Uri two(L"green", L"Square");
        Uri three(L"green", L"square");
        Uri four(L"green", L"square", L"light");
        Uri five(L"green", L"Square", L"light");
        Uri six(L"green", L"square", L"dark");
        Uri seven(L"green", L"circle", L"light");
        Uri eight(L"yellow", L"square", L"light");

        CODING_ERROR_ASSERT(one == three);
        CODING_ERROR_ASSERT(one == two);
        CODING_ERROR_ASSERT(one.Scheme == four.Scheme);
        CODING_ERROR_ASSERT(one.Authority == four.Authority);
        CODING_ERROR_ASSERT(one.Scheme == five.Scheme);
        CODING_ERROR_ASSERT(one.Authority == five.Authority);
        CODING_ERROR_ASSERT(five.Scheme == one.Scheme);
        CODING_ERROR_ASSERT(five.Authority == one.Authority);
        CODING_ERROR_ASSERT(five.Scheme == six.Scheme);
        CODING_ERROR_ASSERT(five.Authority == six.Authority);
        CODING_ERROR_ASSERT(six.Scheme == seven.Scheme);
        CODING_ERROR_ASSERT(six.Authority != seven.Authority);
        CODING_ERROR_ASSERT(six.Scheme != eight.Scheme);
        CODING_ERROR_ASSERT(six.Authority == eight.Authority);
    }

    BOOST_AUTO_TEST_CASE(UriPathCompareTest)
    {
        Uri one(L"gold", L"triangle", L"dim");
        Uri two(L"gold", L"triangle", L"dim");
        Uri three(L"gold", L"triangle", L"bright");
        Uri four(L"gold", L"triangle", L"Dim");
        Uri five(L"gold", L"octagon", L"bright");

        CODING_ERROR_ASSERT(one == two);
        CODING_ERROR_ASSERT(one != three);
        CODING_ERROR_ASSERT(one != four);
        CODING_ERROR_ASSERT(one != five);
        CODING_ERROR_ASSERT(three != five);
    }

    BOOST_AUTO_TEST_CASE(UriToStringTest)
    {
        Uri one(L"orange", L"pentagon", L"cloudy");
        Uri two(L"purple", L"hexagon");
        Uri three(L"fuchsia", L"");

        CODING_ERROR_ASSERT(one.ToString() == L"orange://pentagon/cloudy");
        CODING_ERROR_ASSERT(two.ToString() == L"purple://hexagon");
        CODING_ERROR_ASSERT(three.ToString() == L"fuchsia:");
    }

    BOOST_AUTO_TEST_CASE(UriParseTest)
    {
        std::wstring zero = L"amber:";
        std::wstring one = L"pink://";
        std::wstring two = L"brown://decagon";
        std::wstring three = L"black://dodecagon/sparkly";
        std::wstring four = L"olive:/";
        std::wstring five = L"purple//septagon";
        std::wstring six = L"magenta:/torus/drab";
        std::wstring seven = L"oval/pale";
        std::wstring eight = L"black://purple/white/pink";
        std::wstring nine = L"green://yellow:808/rhombus";
        std::wstring ten = L"plaid://127.0.0.1:9000";
        std::wstring eleven = L"chartreuse://[2001:4898:0:fff:0:5efe:10.121.33.93]:103";
        std::wstring twelve = L"red://grey:987654321/";
        std::wstring legal13 = L"indigo://white/space";
        std::wstring legal14 = L"\t\r\n indigo://white/space \n\r\t";
        std::wstring legal15 = L"indigo://white/ space";
        std::wstring illegal16 = L"indigo://wh ite/space";
        std::wstring illegal17 = L"indi go://white/space";
        std::wstring legal18 = L"mauve://circle/no%20white%20space";
        std::wstring illegal19 = L"mauve://circle/no%20white%2/space";
        Uri temp(L"white", L"rhombus", L"brilliant");
        std::wstring tempS = temp.ToString();

        CODING_ERROR_ASSERT(Uri::TryParse(zero, temp));
        CODING_ERROR_ASSERT(temp.ToString() == zero);
        CODING_ERROR_ASSERT(Uri::TryParse(one, temp));
        CODING_ERROR_ASSERT(temp.ToString() == one);
        CODING_ERROR_ASSERT(Uri::TryParse(two, temp));
        CODING_ERROR_ASSERT(temp.ToString() == two);
        CODING_ERROR_ASSERT(Uri::TryParse(three, temp));
        CODING_ERROR_ASSERT(temp.ToString() == three);
        CODING_ERROR_ASSERT(Uri::TryParse(eight, temp));
        CODING_ERROR_ASSERT(temp.ToString() == eight);
        CODING_ERROR_ASSERT(temp.Segments.size() == 2);
        CODING_ERROR_ASSERT(Uri::TryParse(four, temp));
        CODING_ERROR_ASSERT(temp.ToString() == four);
        CODING_ERROR_ASSERT(Uri::TryParse(six, temp));
        CODING_ERROR_ASSERT(temp.ToString() == six);
        CODING_ERROR_ASSERT(Uri::TryParse(legal13, temp));
        CODING_ERROR_ASSERT(temp.ToString() == legal13);
        CODING_ERROR_ASSERT(Uri::TryParse(legal14, temp));
        CODING_ERROR_ASSERT(temp.ToString() == legal13); // mismatch intentional: 13 is same as 14 but without spaces
        CODING_ERROR_ASSERT(Uri::TryParse(legal15, temp));
        CODING_ERROR_ASSERT(temp.ToString() == legal15);
        CODING_ERROR_ASSERT(Uri::TryParse(legal18, temp));
        CODING_ERROR_ASSERT(temp.ToString() == legal18);

        CODING_ERROR_ASSERT(Uri::TryParse(nine, temp));
        CODING_ERROR_ASSERT(temp.ToString() == nine);
        CODING_ERROR_ASSERT(temp.Port == 808);

        CODING_ERROR_ASSERT(Uri::TryParse(ten, temp));
        CODING_ERROR_ASSERT(temp.ToString() == ten);
        CODING_ERROR_ASSERT(temp.Port == 9000);

        CODING_ERROR_ASSERT(Uri::TryParse(eleven, temp));
        CODING_ERROR_ASSERT(temp.ToString() == eleven);
        CODING_ERROR_ASSERT(temp.Port == 103);

        temp = Uri(L"white", L"rhombus", L"brilliant");

        CODING_ERROR_ASSERT(!Uri::TryParse(five, temp));
        CODING_ERROR_ASSERT(temp.ToString() == tempS);
        CODING_ERROR_ASSERT(!Uri::TryParse(seven, temp));
        CODING_ERROR_ASSERT(temp.ToString() == tempS);
        CODING_ERROR_ASSERT(!Uri::TryParse(twelve, temp));
        CODING_ERROR_ASSERT(temp.ToString() == tempS);
        CODING_ERROR_ASSERT(!Uri::TryParse(illegal16, temp));
        CODING_ERROR_ASSERT(temp.ToString() == tempS);
        CODING_ERROR_ASSERT(!Uri::TryParse(illegal17, temp));
        CODING_ERROR_ASSERT(temp.ToString() == tempS);
        CODING_ERROR_ASSERT(!Uri::TryParse(illegal19, temp));
        CODING_ERROR_ASSERT(temp.ToString() == tempS);
    }

    BOOST_AUTO_TEST_CASE(LessThanTest)
    {
        Uri one(L"bronze");
        Uri two(L"Copper");
        Uri three(L"silver");
        Uri four(L"SILVER");

        CODING_ERROR_ASSERT(one < two && two < three);
        CODING_ERROR_ASSERT(!(three < four));

        Uri five(L"bronze", L"parallelogram");
        Uri six(L"bronze", L"Rectangle");
        Uri seven(L"bronze", L"trapezoid");
        Uri eight(L"bronze", L"TRAPEZOID");

        CODING_ERROR_ASSERT(five < six && six < seven);
        CODING_ERROR_ASSERT(!(seven < eight));

        Uri nine(L"bronze", L"parallelogram", L"fiery");
        Uri ten(L"bronze", L"parallelogram", L"iridescent");
        Uri eleven(L"bronze", L"parallelogram", L"shiny");
        Uri twelve(L"bronze", L"parallelogram", L"SHINY");

        CODING_ERROR_ASSERT(nine < ten && ten < eleven);
        CODING_ERROR_ASSERT(twelve < eleven);
    }

    BOOST_AUTO_TEST_CASE(UnicodeTest)
    {
        Uri uri;

        // *** arbitrary unicode characters
        std::wstring unicode(L"unicodetest1:/");
        unicode.push_back(L'\u9EAD');
        unicode.push_back(L'\uAEEF');
        unicode.push_back(L'/');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\uCACE');
        unicode.push_back(L'\u3060'); // Hiragana

        VERIFY_IS_TRUE(Uri::TryParse(unicode, uri));
        VERIFY_IS_TRUE(uri.ToString() == unicode);

        // *** combining diacritical marks
        unicode = L"unicodetest2:/";
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u0300');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u032F');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u036F');
        unicode.push_back(L'/');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u0300');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u032F');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u036F');

        VERIFY_IS_TRUE(Uri::TryParse(unicode, uri));
        VERIFY_IS_TRUE(uri.ToString() == unicode);

        // *** combining diacritical marks supplement
        unicode = L"unicodetest3:/";
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u1DC0');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u1DA3');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u1DFF');
        unicode.push_back(L'/');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u1DC0');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u1DA3');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u1DFF');

        VERIFY_IS_TRUE(Uri::TryParse(unicode, uri));
        VERIFY_IS_TRUE(uri.ToString() == unicode);

        // *** combining half marks
        unicode = L"unicodetest4:/";
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\uFE20');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\uFE2C');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\uFE2F');
        unicode.push_back(L'/');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\uFE20');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\uFE2C');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\uFE2F');

        VERIFY_IS_TRUE(Uri::TryParse(unicode, uri));
        VERIFY_IS_TRUE(uri.ToString() == unicode);

        // *** combining diacritical marks for symbols
        unicode = L"unicodetest5:/";
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u20D0');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u20EB');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u20FF');
        unicode.push_back(L'/');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u20D0');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u20EB');
        unicode.push_back(L'\uB00D');
        unicode.push_back(L'\u20FF');

        VERIFY_IS_TRUE(Uri::TryParse(unicode, uri));
        VERIFY_IS_TRUE(uri.ToString() == unicode);
    }

    BOOST_AUTO_TEST_CASE(UnicodeSurrogatePairsTest)
    {
        Uri uri;

        // *** surrogate pairs in the valid range
        std::wstring unicode(L"surrogatepairs1:/");

        // first in range
        unicode.push_back(static_cast<wchar_t>(0xD800));
        unicode.push_back(static_cast<wchar_t>(0xDC00));

        // arbitrary in range
        unicode.push_back(static_cast<wchar_t>(0xDAAA));
        unicode.push_back(static_cast<wchar_t>(0xDEEB));

        // last in range
        unicode.push_back(static_cast<wchar_t>(0xDBFF));
        unicode.push_back(static_cast<wchar_t>(0xDFFF));

        unicode.push_back(L'/');

        // first in range
        unicode.push_back(static_cast<wchar_t>(0xD800));
        unicode.push_back(static_cast<wchar_t>(0xDC00));

        // arbitrary in range
        unicode.push_back(static_cast<wchar_t>(0xDAAA));
        unicode.push_back(static_cast<wchar_t>(0xDEEB));

        // last in range
        unicode.push_back(static_cast<wchar_t>(0xDBFF));
        unicode.push_back(static_cast<wchar_t>(0xDFFF));

        VERIFY_IS_TRUE(Uri::TryParse(unicode, uri));
        VERIFY_IS_TRUE(uri.ToString() == unicode);

        // *** reverse byte order of the above (no byte ordering is assumed)
        unicode = L"surrogatepairs2:/";

        // first in range
        unicode.push_back(static_cast<wchar_t>(0xDC00));
        unicode.push_back(static_cast<wchar_t>(0xD800));

        // arbitrary in range
        unicode.push_back(static_cast<wchar_t>(0xDEEB));
        unicode.push_back(static_cast<wchar_t>(0xDAAA));

        // last in range
        unicode.push_back(static_cast<wchar_t>(0xDFFF));
        unicode.push_back(static_cast<wchar_t>(0xDBFF));

        unicode.push_back(L'/');

        // first in range
        unicode.push_back(static_cast<wchar_t>(0xDC00));
        unicode.push_back(static_cast<wchar_t>(0xD800));

        // arbitrary in range
        unicode.push_back(static_cast<wchar_t>(0xDEEB));
        unicode.push_back(static_cast<wchar_t>(0xDAAA));

        // last in range
        unicode.push_back(static_cast<wchar_t>(0xDFFF));
        unicode.push_back(static_cast<wchar_t>(0xDBFF));

        VERIFY_IS_TRUE(Uri::TryParse(unicode, uri));
        VERIFY_IS_TRUE(uri.ToString() == unicode);

        // *** missing leading code
        unicode = L"surrogatepairs3:/";

        // first in range
        unicode.push_back(static_cast<wchar_t>(0xDC00));

        // arbitrary in range
        unicode.push_back(static_cast<wchar_t>(0xDEEB));

        // last in range
        unicode.push_back(static_cast<wchar_t>(0xDFFF));

        unicode.push_back(L'/');

        // first in range
        unicode.push_back(static_cast<wchar_t>(0xDC00));

        // arbitrary in range
        unicode.push_back(static_cast<wchar_t>(0xDEEB));

        // last in range
        unicode.push_back(static_cast<wchar_t>(0xDFFF));

        VERIFY_IS_FALSE(Uri::TryParse(unicode, uri));

        // *** missing trailing code
        unicode = L"surrogatepairs4:/";

        // first in range
        unicode.push_back(static_cast<wchar_t>(0xD800));

        // arbitrary in range
        unicode.push_back(static_cast<wchar_t>(0xDAAA));

        // last in range
        unicode.push_back(static_cast<wchar_t>(0xDBFF));

        unicode.push_back(L'/');

        // first in range
        unicode.push_back(static_cast<wchar_t>(0xD800));

        // arbitrary in range
        unicode.push_back(static_cast<wchar_t>(0xDAAA));

        // last in range
        unicode.push_back(static_cast<wchar_t>(0xDBFF));

        VERIFY_IS_FALSE(Uri::TryParse(unicode, uri));

        // *** code is surrounded by non-surrogate code
        unicode = L"surrogatepairs5:/";

        // first in range
        unicode.push_back(static_cast<wchar_t>(0xB00D));
        unicode.push_back(static_cast<wchar_t>(0xDC00));
        unicode.push_back(static_cast<wchar_t>(0xB00D));

        // arbitrary in range
        unicode.push_back(static_cast<wchar_t>(0xDEEB));
        unicode.push_back(static_cast<wchar_t>(0xB00D));

        // last in range
        unicode.push_back(static_cast<wchar_t>(0xDFFF));
        unicode.push_back(static_cast<wchar_t>(0xB00D));

        unicode.push_back(L'/');

        // first in range
        unicode.push_back(static_cast<wchar_t>(0xB00D));
        unicode.push_back(static_cast<wchar_t>(0xD800));
        unicode.push_back(static_cast<wchar_t>(0xB00D));

        // arbitrary in range
        unicode.push_back(static_cast<wchar_t>(0xDAAA));
        unicode.push_back(static_cast<wchar_t>(0xB00D));

        // last in range
        unicode.push_back(static_cast<wchar_t>(0xDBFF));
        unicode.push_back(static_cast<wchar_t>(0xB00D));

        VERIFY_IS_FALSE(Uri::TryParse(unicode, uri));
    }

    BOOST_AUTO_TEST_SUITE_END()
}

max_stars_repo_name: AnthonyM/service-fabric

max_issues_repo_name: AnthonyM/service-fabric

max_forks_repo_name: AnthonyM/service-fabric


text:
/*

 Copyright (c) 2005-2015, University of Oxford.
 All rights reserved.

 University of Oxford means the Chancellor, Masters and Scholars of the
 University of Oxford, having an administrative office at Wellington
 Square, Oxford OX1 2JD, UK.

 This file is part of Chaste.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright notice,
 this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.
 * Neither the name of the University of Oxford nor the names of its
 contributors may be used to endorse or promote products derived from this
 software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 */

/*
 Jessica Cervi and Raymond J. Spiteri
 Numerical Simulation Laboratory
 University of Saskatchewan
 August 2016
 */

#ifndef THIRDORDERRDIRKOPERATORSPLITTINGBIDOMAINSOLVER_HPP_
#define THIRDORDERRDIRKOPERATORSPLITTINGBIDOMAINSOLVER_HPP_

#include "UblasIncludes.hpp"

//#include <iostream>
#include <vector>
#include <petscvec.h>

#include "AbstractBidomainSolver.hpp"
#include "HeartConfig.hpp"
#include "BidomainAssembler.hpp"
#include "BidomainMassMatrixAssembler.hpp"
#include "BidomainStiffnessMatrixAssembler.hpp"
#include "BidomainCorrectionTermAssembler.hpp"
#include "BidomainNeumannSurfaceTermAssembler.hpp"
#include "TimeStepper.hpp"

#include <boost/numeric/ublas/vector_proxy.hpp>

//EDIT COMMENTS HERE!!!
/**
 *  A bidomain solver that uses Strang operator splitting of the diffusion (conductivity) term and the reaction
 *  (ionic current) term, instead of solving the full reaction-diffusion PDE. This does NOT refer to operator splitting
 *  of the two PDEs in the bidomain equations. For details see for example Sundnes et al "Computing the Electrical
 *  Activity of the Heart". This solves the PDEs using the SDIRK2O2 method (second order).
 *
 *  The algorithm is, for solving from t=T to T+dt.
 *
 *  (i)   Solve ODEs   dV/dt = Iionic, du/dt = f(u,V)  for t=T to T+dt/2
 *        [giving updated V (internally, and in solution vector) and updated state variables]
 *  (ii)  Solve PDE    dV/dt = div (sigma_i grad V) + div (sigma_i grad phi_e), div (sigma_i grad V) + div ((sigma_i+sigma_e) grad phi_e) = 0
 *        for t=T to dt         [using V from step i, --> updated V]
 *  (iii) Solve ODEs   dV/dt = Iionic, du/dt = f(u,V)  for t=T+dt/2 to T+dt  [using V from step ii, --> final V]
 *
 *  Notes
 *   (a)  Stages (iii) and (i) can normally be solved together in one go, except just before/after printing the voltage to file.
 *        However for simplicity of code this has not been implemented
 *   (b)  Therefore, the effective ODE timestep will be:  min(ode_dt, pde_dt/2), where ode_dt and pde_dt are those
 *        given via HeartConfig.
 *   (c)  This solver is FOR COMPARING ACCURACY, NOT PERFORMANCE. It has not been optimised and may or may not
 *        perform well in parallel.
 *   (d)  Usage: add the follwoing lines to your original code:
 *        HeartConfig::Instance()->SetUseReactionDiffusionOperatorSplittingBidomainSolver();
 * 	  HeartConfig::Instance()->SetUseReactionDiffusionThirdOrderOperatorSplittingBidomainSolver();
 */
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
class ThirdOrderRDIRKOperatorSplittingBidomainSolver : public AbstractBidomainSolver<ELEMENT_DIM, SPACE_DIM>
{
private:

    /** Coefficient for SDIRK2O3 method */
    double mGamma;

    /** Mass matrix, used to computing the RHS vector (actually: mass-matrix in
     *  voltage-voltage block, zero elsewhere
     */
    Mat mMassMatrix;

    /** Ai matrix, used to computing the RHS vector (actually: Ai-matrix in
     *  voltage-voltage block, zero elsewhere
     */

    Mat mAiMatrix;

    /**
     *  The vector multiplied by the mass matrix. Ie, if the linear system to
     *  be solved is Ax=b, this vector is z1 where b = M z1 + Ai z2.
     */
    Vec mVecForConstructingRhs1;

    /**
     *  The vector multiplied by the Ai matrix. Ie, if the linear system to
     *  be solved is Ax=b, this vector is z2 where b = M z1 + Ai z2.
     */
    Vec mVecForConstructingRhs2;
    /**
     *  The vector multiplied by the mass matrix. Ie, if the linear system to
     *  be solved is Ax=b, this vector is z1 where b = M z1 + Ai z2., Third stage
     */
    Vec mVecForConstructingRhs1_2;

    /**
     *  The vector multiplied by the Ai matrix. Ie, if the linear system to
     *  be solved is Ax=b, this vector is z2 where b = M z1 + Ai z2. Third Stage
     */
    Vec mVecForConstructingRhs2_2;

    /** The bidomain assembler, used to set up the LHS matrix */
    BidomainAssembler<ELEMENT_DIM, SPACE_DIM>* mpBidomainAssembler;

    /** Assembler for surface integrals coming from any non-zero Neumann boundary conditions */
    BidomainNeumannSurfaceTermAssembler<ELEMENT_DIM, SPACE_DIM>* mpBidomainNeumannSurfaceTermAssembler;

    /**
     * If using state variable interpolation, points to an assembler to use in
     * computing the correction term to apply to the RHS.
     */
    BidomainCorrectionTermAssembler<ELEMENT_DIM, SPACE_DIM>* mpBidomainCorrectionTermAssembler;

    /**
     *  The linear system that will be set up and solved first as part of the
     *  PDE solve
     */
    //LinearSystem* mpLinearSystem_first_solve;

    /**
     * If using state variable interpolation, points to an assembler to use in
     * computing the correction term to apply to the RHS.
     */
    //BidomainCorrectionTermAssembler<ELEMENT_DIM,SPACE_DIM>* mpBidomainCorrectionTermAssembler;

    /** Overloaded InitialiseForSolve() which calls base version but also
     *  initialises mMassMatrix and mVecForConstructingRhs
     *
     *  @param initialSolution initial solution
     */
    void InitialiseForSolve(Vec initialSolution);

    /**
     *  Implementation of SetupLinearSystem() which uses the assembler to compute the
     *  LHS matrix, but sets up the RHS vector using the mass-matrix (constructed
     *  using a separate assembler) multiplied by a vector
     *
     *  @param currentSolution Solution at current time
     *  @param computeMatrix Whether to compute the matrix of the linear system
     */
    void SetupLinearSystem(Vec currentSolution, bool computeMatrix);

    /**
     *  Called before setting up the linear system, used to solve the cell models for first half timestep (step (i) above)
     *  @param currentSolution the latest solution vector
     */
    void PrepareForSetupLinearSystem(Vec currentSolution);

    /**
     *  Called after solving the linear system, used to solve the cell models for second half timestep (step (iii) above)
     *  @param currentSolution the latest solution vector (ie the solution of the linear system).
     */
    void FollowingSolveLinearSystem(Vec currentSolution);

    /**
     * Called when we are ready to solve the splitted system
     */
    Vec SolveOS(Vec currentSolution);

    /**
     * Whether we are solving the cell system or not
     */
    bool SolvingCellSystem;

    /**
     * When using third-order OS, the substeps for the ODE and PDE system have to be the following
     */
    double ThirdOrderTimeSteps;

    /**
     * Index for the time-step array
     */
    int TimeSubStepIndex;

    /**
     * Index for the whether solving the cell system of not
     */
    int BackwardTimeIntegrationIndex;

    /**
     * Index for DIRK stage
     */
    int DIRKStage;

    /*
     *Stepper
     */
    TimeStepper stepper();

    /*
     *Stage counter for DIRK method
     */
    int currentStage;

public:
    /**
     * Constructor
     *
     * @param bathSimulation Whether the simulation involves a perfusing bath
     * @param pMesh pointer to the mesh
     * @param pTissue pointer to the tissue
     * @param pBoundaryConditions pointer to the boundary conditions
     */
    ThirdOrderRDIRKOperatorSplittingBidomainSolver(bool bathSimulation,
                                              AbstractTetrahedralMesh<ELEMENT_DIM, SPACE_DIM>* pMesh,
                                              BidomainTissue<SPACE_DIM>* pTissue,
                                              BoundaryConditionsContainer<ELEMENT_DIM, SPACE_DIM,2>* pBoundaryConditions);

    ~ThirdOrderRDIRKOperatorSplittingBidomainSolver();

    //  void FinaliseLinearSystem_first_solve(Vec existingSolution);

};

#endif /*THIRDORDERRDIRKOPERATORSPLITTINGBIDOMAINSOLVER_HPP_*/

max_stars_repo_name: uofs-simlab/ChasteOS

max_issues_repo_name: uofs-simlab/ChasteOS

max_forks_repo_name: uofs-simlab/ChasteOS