text:
/**
 * @file
 * @brief Implementations from make_quad_rule.h
 * @author Raffael Casagrande
 * @date   2018-08-19 06:35:16
 * @copyright MIT License
 */

#include "make_quad_rule.h"
#include <Eigen/KroneckerProduct>
#include "gauss_quadrature.h"

namespace lf::quad {
namespace detail {
template <base::RefElType REF_EL, int Order>
QuadRule HardcodedQuadRule();
}

QuadRule make_QuadRule(base::RefEl ref_el, unsigned char order) {
  if (ref_el == base::RefEl::kSegment()) {
    quadOrder_t n = order / 2 + 1;
    auto [points, weights] = GaussLegendre(n);
    return QuadRule(base::RefEl::kSegment(), points.transpose(),
                    std::move(weights), 2 * n - 1);
  }
  if (ref_el == base::RefEl::kQuad()) {
    quadOrder_t n = order / 2 + 1;
    auto [points1d, weights1d] = GaussLegendre(n);
    Eigen::MatrixXd points2d(2, n * n);
    points2d.row(0) = Eigen::kroneckerProduct(points1d.transpose(),
                                              Eigen::MatrixXd::Ones(1, n));
    points2d.row(1) = points1d.transpose().replicate(1, n);
    return QuadRule(base::RefEl::kQuad(), std::move(points2d),
                    Eigen::kroneckerProduct(weights1d, weights1d), 2 * n - 1);
  }
  if (ref_el == base::RefEl::kTria()) {
    switch (order) {
      case 1:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 1>();
      case 2:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 2>();
      case 3:  // user order 4 rule instead
      case 4:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 4>();
      case 5:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 5>();
      case 6:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 6>();
      case 7:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 7>();
      case 8:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 8>();
      case 9:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 9>();
      case 10:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 10>();
      case 11:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 11>();
      case 12:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 12>();
      case 13:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 13>();
      case 14:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 14>();
      case 15:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 15>();
      case 16:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 16>();
      case 17:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 17>();
      case 18:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 18>();
      case 19:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 19>();
      case 20:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 20>();
      case 21:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 21>();
      case 22:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 22>();
      case 23:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 23>();
      case 24:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 24>();
      case 25:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 25>();
      case 26:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 26>();
      case 27:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 27>();
      case 28:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 28>();
      case 29:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 29>();
      case 30:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 30>();
      case 31:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 31>();
      case 32:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 32>();
      case 33:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 33>();
      case 34:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 34>();
      case 35:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 35>();
      case 36:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 36>();
      case 37:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 37>();
      case 38:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 38>();
      case 39:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 39>();
      case 40:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 40>();
      case 41:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 41>();
      case 42:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 42>();
      case 43:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 43>();
      case 44:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 44>();
      case 45:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 45>();
      case 46:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 46>();
      case 47:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 47>();
      case 48:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 48>();
      case 49:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 49>();
      case 50:
        return detail::HardcodedQuadRule<base::RefEl::kTria(), 50>();
      default:
        // Create a quadrule using tensor product quadrature rule + duffy
        // transform
        quadOrder_t n = order / 2 + 1;
        auto [leg_p, leg_w] = GaussLegendre(n);
        auto [jac_p, jac_w] = GaussJacobi(n, 1, 0);
        jac_p.array() = (jac_p.array() + 1) / 2.;  // rescale to [0,1]
        jac_w.array() *= 0.25;
        Eigen::MatrixXd points2d(2, n * n);
        points2d.row(0) = Eigen::kroneckerProduct(
            leg_p.transpose(), (1 - jac_p.transpose().array()).matrix());
        points2d.row(1) = jac_p.transpose().replicate(1, n);
        return QuadRule(base::RefEl::kTria(), std::move(points2d),
                        Eigen::kroneckerProduct(leg_w, jac_w), 2 * n - 1);
    }
  }
  LF_VERIFY_MSG(
      false, "No Quadrature rules implemented for this reference element yet.");
}
}  // namespace lf::quad

max_stars_repo_name: Cryoris/lehrfempp

max_issues_repo_name: Cryoris/lehrfempp

max_forks_repo_name: Cryoris/lehrfempp


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

    Use modification and distribution are 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).
==============================================================================*/

#if !defined(BOOST_FUSION_FUNCTIONAL_INVOCATION_DETAIL_THAT_PTR_HPP_INCLUDED)
#define BOOST_FUSION_FUNCTIONAL_INVOCATION_DETAIL_THAT_PTR_HPP_INCLUDED

#include <boost/fusion/support/config.hpp>
#include <boost/get_pointer.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/utility/addressof.hpp>

namespace boost {
namespace fusion {
namespace detail {
template <typename Wanted> struct that_ptr {
private:
  typedef typename remove_reference<Wanted>::type pointee;

  template <typename T>
  BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static inline pointee *
  do_get_pointer(T &, pointee *x) {
    return x;
  }
  template <typename T>
  BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static inline pointee *
  do_get_pointer(T &x, void const *) {
    return get_pointer(x);
  }

public:
  BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static inline pointee *
  get(pointee *x) {
    return x;
  }

  BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static inline pointee *
  get(pointee &x) {
    return boost::addressof(x);
  }

  template <typename T>
  BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static inline pointee *get(T &x) {
    return do_get_pointer(x, boost::addressof(x));
  }
};

template <typename PtrOrSmartPtr> struct non_const_pointee;

#if defined(BOOST_MSVC) ||                                                     \
    (defined(__BORLANDC__) && !defined(BOOST_DISABLE_WIN32))
#define BOOST_FUSION_TRAIT_DECL __cdecl
#else
#define BOOST_FUSION_TRAIT_DECL /**/
#endif

namespace adl_barrier {
using boost::get_pointer;
void const *BOOST_FUSION_TRAIT_DECL get_pointer(...); // fallback

template <typename T> char const_tester(T *);
template <typename T> long const_tester(T const *);

template <typename Ptr> struct non_const_pointee_impl {
  static Ptr &what;

  static bool const value = sizeof(const_tester(get_pointer(what))) == 1;
};
} // namespace adl_barrier

template <typename PtrOrSmartPtr>
struct non_const_pointee
    : adl_barrier::non_const_pointee_impl<typename remove_cv<
          typename remove_reference<PtrOrSmartPtr>::type>::type> {
  typedef non_const_pointee type;
  typedef bool value_type;
};

} // namespace detail
} // namespace fusion
} // namespace boost

#endif

ext: hpp

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
// Copyright 2018-2019 Josh Pieper, jjp@pobox.com.
//
// 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 <iostream>

#include <boost/assert.hpp>
#include <boost/format.hpp>
#include <boost/timer/timer.hpp>

#include <opencv2/aruco.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>

extern "C" {

int main(int argc, char** argv) {
  BOOST_VERIFY(argc >= 3);

  cv::Mat markerImage;

  cv::Ptr<cv::aruco::Dictionary> dictionary =
      cv::aruco::getPredefinedDictionary(cv::aruco::DICT_4X4_50);

  cv::aruco::drawMarker(dictionary, std::stoi(argv[1]), 200, markerImage, 1);

  cv::imwrite(argv[2], markerImage);

  return 0;
}

}

ext: cc


text:
/*
 * Copyright (c) 2019 Opticks Team. All Rights Reserved.
 *
 * This file is part of Opticks
 * (see https://bitbucket.org/simoncblyth/opticks).
 *
 * 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 <boost/math/constants/constants.hpp>

#include "NGLMExt.hpp"
#include "GLMPrint.hpp"
#include "NPY.hpp"

#include "NQuad.hpp"
#include "NBBox.hpp"
#include "NTrianglesNPY.hpp"
#include "NTesselate.hpp"
#include "NTriangle.hpp"

#include "NTris.hpp"

#include "PLOG.hh"

#ifdef _MSC_VER
// instanciations of 'NTrianglesNPY' raise warning:
//    object allocated on the heap may not be aligned 16
// https://github.com/g-truc/glm/issues/235
// apparently fixed by 0.9.7.1 Release : currently on 0.9.6.3

#pragma warning( disable : 4316 )
#endif

const char* NTrianglesNPY::PLACEHOLDER = "PLACEHOLDER" ;

NPY<float>* NTrianglesNPY::getTris() const
{
    return m_tris ;
}
NPY<float>* NTrianglesNPY::getNormals() const
{
    return m_normals ;
}

float NTrianglesNPY::maxdiff( const NTrianglesNPY* other, bool dump )
{
    return m_tris->maxdiff( other->getTris(), dump );
}

void NTrianglesNPY::dump(const char* msg) const
{
    LOG(info) << "NTrianglesNPY::dump"
              << " tris " << m_tris->getShapeString()
              ;

    m_tris->dump(msg);
}

void NTrianglesNPY::setPoly(const std::string& poly)
{
   m_poly = poly ;
}
const std::string& NTrianglesNPY::getPoly()
{
   return m_poly ;
}

void NTrianglesNPY::setMessage(const std::string& msg)
{
   m_message = msg ;
}
const std::string& NTrianglesNPY::getMessage()
{
   return m_message ;
}

bool NTrianglesNPY::hasMessage(const std::string& msg)
{
    return m_message.compare(msg) == 0 ;
}
bool NTrianglesNPY::isPlaceholder()
{
    return m_message.compare(PLACEHOLDER) == 0 ;
}

void NTrianglesNPY::setTransform(const glm::mat4& transform_)
{
    m_transform = transform_ ;
}
glm::mat4 NTrianglesNPY::getTransform()
{
    return m_transform ;
}

NTrianglesNPY::NTrianglesNPY(const NTriSource* tris)
   :
   m_tris(NPY<float>::make(0,3,3)),
   m_normals(NPY<float>::make(0,3,3)),
   m_transform(1.0f)
{
    glm::uvec3 t ;
    glm::vec3 a ;
    glm::vec3 b ;
    glm::vec3 c ;

    unsigned ntri = tris->get_num_tri();
    for(unsigned i=0 ; i < ntri ; i++)
    {
        tris->get_tri(i,t,a,b,c );
        add(a,b,c);
    }
}

NTrianglesNPY::NTrianglesNPY()
   :
   m_tris(NPY<float>::make(0,3,3)),
   m_normals(NPY<float>::make(0,3,3)),
   m_transform(1.0f)
{
}

NTrianglesNPY::NTrianglesNPY(NPY<float>* tris, NPY<float>* normals)
   :
   m_tris(tris),
   m_normals(normals),
   m_transform(1.0f)
{
}

NTrianglesNPY* NTrianglesNPY::transform(glm::mat4& m)
{
    NPY<float>* tbuf = m_tris->transform(m);

    NTrianglesNPY* t = new NTrianglesNPY(tbuf);

    return t ;
}

NTrianglesNPY* NTrianglesNPY::subdivide(unsigned int nsubdiv)
{
    NTesselate* tess = new NTesselate(m_tris);

    tess->subdivide(nsubdiv);

    NPY<float>* tbuf = tess->getBuffer();

    NTrianglesNPY* t = new NTrianglesNPY(tbuf);

    t->setTransform( getTransform() );

    return t ;
}

unsigned int NTrianglesNPY::getNumTriangles()
{
    return m_tris->getNumItems();
}

void NTrianglesNPY::add(const glm::vec3& a, const glm::vec3& b, const glm::vec3& c, const glm::vec3& d)
{
   /*
         a------d
         |    . |
         |  .   |
         |.     |
         b------c

   */
    add(a,b,d);
    add(d,b,c);
}

void NTrianglesNPY::add(const glm::vec3& a, const glm::vec3& b, const glm::vec3& c)
{
    ntriangle t(a,b,c);
    add(t);
}

void NTrianglesNPY::addNormal(const glm::vec3& nrm )  // in triplicate
{
    int n = 3*3 ;
    float* vals = new float[n] ;
    for(int i=0 ; i < 3 ; i++)
    {
       vals[i*3+0] = nrm.x ;
       vals[i*3+1] = nrm.y ;
       vals[i*3+2] = nrm.z ;
    }
    m_normals->add(vals, n);
    delete [] vals ;
}

void NTrianglesNPY::addNormal(const glm::vec3& a, const glm::vec3& b, const glm::vec3& c )
{
    float vals[9] ;

    vals[0*3 + 0 ] = a.x ;
    vals[0*3 + 1 ] = a.y ;
    vals[0*3 + 2 ] = a.z ;

    vals[1*3 + 0 ] = b.x ;
    vals[1*3 + 1 ] = b.y ;
    vals[1*3 + 2 ] = b.z ;

    vals[2*3 + 0 ] = c.x ;
    vals[2*3 + 1 ] = c.y ;
    vals[2*3 + 2 ] = c.z ;

    m_normals->add(vals, 9);
}

void NTrianglesNPY::add(const ntriangle& t )
{
    unsigned int n = 3*3 ;
    float* vals = new float[n] ;
    t.copyTo(vals);
    m_tris->add(vals, n);
    delete [] vals ;
}

void NTrianglesNPY::add(NTrianglesNPY* other )
{
    m_tris->add(other->getTris());
}

nbbox* NTrianglesNPY::findBBox()
{
    NPY<float>* buf = getTris();
    assert(buf && buf->hasItemShape(3,3));
    unsigned nitem = buf->getShape(0);
    nbbox* bb = NULL ;
    if(nitem > 0)
    {
        ntrange3<float> r = buf->minmax3();
        bb = new nbbox ;
        bb->min.x = r.min.x ;
        bb->min.y = r.min.y ;
        bb->min.z = r.min.z ;

        bb->max.x = r.max.x ;
        bb->max.y = r.max.y ;
        bb->max.z = r.max.z ;
    }
    return bb ;
}

/* for icosahedron

* 20 faces (triangular)
* 12 verts
* 30 edges

*/
#define CZ (0.89442719099991)   /*  2/sqrt(5) */
#define SZ (0.44721359549995)   /*  1/sqrt(5) */
#define C1 (0.951056516)        /* cos(18),  */
#define S1 (0.309016994)        /* sin(18) */
#define C2 (0.587785252)        /* cos(54),  */
#define S2 (0.809016994)        /* sin(54) */
#define X1 (C1*CZ)
#define Y1 (S1*CZ)
#define X2 (C2*CZ)
#define Y2 (S2*CZ)

const glm::vec3 NTrianglesNPY::Ip0 = glm::vec3(0,0,1.) ;
const glm::vec3 NTrianglesNPY::Ip1 = glm::vec3(-X2,-Y2,SZ) ;
const glm::vec3 NTrianglesNPY::Ip2 = glm::vec3( X2,-Y2,SZ) ;
const glm::vec3 NTrianglesNPY::Ip3 = glm::vec3( X1, Y1,SZ) ;
const glm::vec3 NTrianglesNPY::Ip4 = glm::vec3(  0, CZ,SZ) ;
const glm::vec3 NTrianglesNPY::Ip5 = glm::vec3(-X1, Y1,SZ) ;

const glm::vec3 NTrianglesNPY::Im0 = glm::vec3(-X1, -Y1,-SZ) ;
const glm::vec3 NTrianglesNPY::Im1 = glm::vec3(  0, -CZ,-SZ) ;
const glm::vec3 NTrianglesNPY::Im2 = glm::vec3( X1, -Y1,-SZ) ;
const glm::vec3 NTrianglesNPY::Im3 = glm::vec3( X2,  Y2,-SZ) ;
const glm::vec3 NTrianglesNPY::Im4 = glm::vec3(-X2,  Y2,-SZ) ;
const glm::vec3 NTrianglesNPY::Im5 = glm::vec3(0,0,-1.) ;

NTrianglesNPY* NTrianglesNPY::icosahedron()
{
    NTrianglesNPY* tris = new NTrianglesNPY();

    /* front pole */
    tris->add(Ip0, Ip1, Ip2);
    tris->add(Ip0, Ip5, Ip1);
    tris->add(Ip0, Ip4, Ip5);
    tris->add(Ip0, Ip3, Ip4);
    tris->add(Ip0, Ip2, Ip3);

    /* mid */
    tris->add(Ip1, Im0, Im1);
    tris->add(Im0, Ip1, Ip5);
    tris->add(Ip5, Im4, Im0);
    tris->add(Im4, Ip5, Ip4);
    tris->add(Ip4, Im3, Im4);
    tris->add(Im3, Ip4, Ip3);
    tris->add(Ip3, Im2, Im3);
    tris->add(Im2, Ip3, Ip2);
    tris->add(Ip2, Im1, Im2);
    tris->add(Im1, Ip2, Ip1);

    /* back pole */
    tris->add(Im3, Im2, Im5);
    tris->add(Im4, Im3, Im5);
    tris->add(Im0, Im4, Im5);
    tris->add(Im1, Im0, Im5);
    tris->add(Im2, Im1, Im5);

    return tris ;
}

NTrianglesNPY* NTrianglesNPY::from_indexed( NPY<float>* vtx, NPY<unsigned>* idx )
{
    assert( vtx->hasShape( -1, 3) && idx->hasShape(-1,3) );
    // each idx entry of 3 unsigned ints points to three vertices of the triangle

    unsigned nvtx = vtx->getShape(0) ;
    unsigned ntri = idx->getShape(0) ;

    LOG(info) << " idx " << idx->getShapeString() ;
    LOG(info) << " vtx " << vtx->getShapeString() ;

    NTrianglesNPY* tris = new NTrianglesNPY();

    for(unsigned i=0 ; i < ntri ; i++)
    {
        unsigned v0 = idx->getValue( i, 0, 0,  0 );
        unsigned v1 = idx->getValue( i, 0, 0,  1 );
        unsigned v2 = idx->getValue( i, 0, 0,  2 );

        assert( v0 < nvtx );
        assert( v1 < nvtx );
        assert( v2 < nvtx );

        glm::vec3 vtx0 ;
        vtx0.x = vtx->getValue( v0, 0, 0,  0 );
        vtx0.y = vtx->getValue( v0, 0, 0,  1 );
        vtx0.z = vtx->getValue( v0, 0, 0,  2 );

        glm::vec3 vtx1 ;
        vtx1.x = vtx->getValue( v1, 0, 0,  0 );
        vtx1.y = vtx->getValue( v1, 0, 0,  1 );
        vtx1.z = vtx->getValue( v1, 0, 0,  2 );

        glm::vec3 vtx2 ;
        vtx2.x = vtx->getValue( v2, 0, 0,  0 );
        vtx2.y = vtx->getValue( v2, 0, 0,  1 );
        vtx2.z = vtx->getValue( v2, 0, 0,  2 );

        tris->add( vtx0, vtx1, vtx2 );
    }
    return tris ;
}

void NTrianglesNPY::to_vtxidx(NVtxIdx& vtxidx)
{
    assert( m_tris->hasShape(-1,3,3) );  // items with 3*3 float for each tri
    unsigned ntri = m_tris->getShape(0) ;

    NPY<float>* vtx = NPY<float>::copy( m_tris ) ;
    vtx->reshape( ntri*3 , 3 );

    NPY<unsigned>* idx = NPY<unsigned>::make( ntri, 3 ) ;
    idx->zero();

    vtxidx.vtx = vtx ;   // duplicate vertices for each use in a face
    vtxidx.idx = idx ;

    for(unsigned i=0 ; i < ntri ; i++)
    {
        idx->setValue( i, 0, 0,  0,  i*3+0  );
        idx->setValue( i, 0, 0,  1,  i*3+1  );
        idx->setValue( i, 0, 0,  2,  i*3+2  );
    }
}

const glm::vec3 NTrianglesNPY::PX = glm::vec3(1,0,0) ;
const glm::vec3 NTrianglesNPY::PY = glm::vec3(0,1,0) ;
const glm::vec3 NTrianglesNPY::PZ = glm::vec3(0,0,1) ;
const glm::vec3 NTrianglesNPY::MX = glm::vec3(-1,0,0) ;
const glm::vec3 NTrianglesNPY::MY = glm::vec3(0,-1,0) ;
const glm::vec3 NTrianglesNPY::MZ = glm::vec3(0,0,-1) ;

NTrianglesNPY* NTrianglesNPY::octahedron()
{
    NTrianglesNPY* tris = new NTrianglesNPY();

    // PZ pyramid
    tris->add(PX,PZ,MY);
    tris->add(MY,PZ,MX);
    tris->add(MX,PZ,PY);
    tris->add(PY,PZ,PX);

    // MZ pyramid
    tris->add(PX,MY,MZ);
    tris->add(MY,MX,MZ);
    tris->add(MX,PY,MZ);
    tris->add(PY,PX,MZ);

    return tris ;
}

NTrianglesNPY* NTrianglesNPY::hemi_octahedron()
{
    NTrianglesNPY* tris = new NTrianglesNPY();

    // PZ pyramid
    tris->add(PX,PZ,MY);
    tris->add(MY,PZ,MX);
    tris->add(MX,PZ,PY);
    tris->add(PY,PZ,PX);

    return tris ;
}

NTrianglesNPY* NTrianglesNPY::sphere(unsigned int n_polar, unsigned int n_azimuthal)
{
    glm::vec4 param(-1.f, 1.f, 0.f, 1.f);
    return sphere(param, n_polar, n_azimuthal);
}

void NTrianglesNPY::setTransform(const glm::vec3& scale, const glm::vec3& translate)
{
    glm::mat4 m_scale = glm::scale(glm::mat4(1.0f), scale);
    glm::mat4 m_translate = glm::translate(glm::mat4(1.0f), translate);
    glm::mat4 mat = m_translate * m_scale ;

    //print(mat, "NTrianglesNPY::setTransform");

    setTransform(mat);
}

NTrianglesNPY* NTrianglesNPY::sphere(glm::vec4& param, unsigned int n_polar, unsigned int n_azimuthal)
{
    float ctmin = param.x ;
    float ctmax = param.y ;
    float zpos  = param.z ;
    float radius = param.w ;

    // unit sphere at origin
    NTris* ts = NTris::make_sphere( n_polar, n_azimuthal, ctmin, ctmax );

    NTrianglesNPY* tris = new NTrianglesNPY(ts);

    glm::vec3 scale(radius);
    glm::vec3 translate(0,0,zpos);
    tris->setTransform(scale, translate);

    // dont apply the transform yet, as whilst sphere at origin
    // can easily get normals from the positions

    return tris ;
}

/*
         p0     p1

     t0  x00----x10
          |   .  |
          | .    |
     t1  x01----x11

      t = 0  => t0 = 0
               x00 x10 degenerate (0,0,1)

      t = n_polar - 1 => t1 = pi
               x01 x11 degenerate (0,0,-1)

*/

NTrianglesNPY* NTrianglesNPY::disk(glm::vec4& param, unsigned int n_azimuthal)
{
    float ct = param.x ;
    double ct0, st0 ;
    sincos_<double>(acos(ct), st0, ct0 );
    float pi = boost::math::constants::pi<float>() ;

    NTrianglesNPY* tris = new NTrianglesNPY();
    for(unsigned int p=0 ; p < n_azimuthal ; p++)
    {
        float p0 = 2.0f*pi*float(p)/n_azimuthal ;
        float p1 = 2.0f*pi*float(p+1)/n_azimuthal ;

        double sp0,sp1,cp0,cp1 ;
        sincos_<double>(p0, sp0, cp0 );
        sincos_<double>(p1, sp1, cp1 );

        glm::vec3 x0(   st0*cp0,  st0*sp0,   ct0 );
        glm::vec3 x1(   st0*cp1,  st0*sp1,   ct0 );
        glm::vec3 xc(         0,        0,   ct0 );

        tris->add(x0,x1,xc); // winding order directs normal along -z
    }
    return tris ;
}

const glm::vec3 NTrianglesNPY::PXPYPZ = glm::vec3(1,1,1) ;
const glm::vec3 NTrianglesNPY::PXPYMZ = glm::vec3(1,1,-1) ;
const glm::vec3 NTrianglesNPY::PXMYPZ = glm::vec3(1,-1,1) ;
const glm::vec3 NTrianglesNPY::PXMYMZ = glm::vec3(1,-1,-1) ;

const glm::vec3 NTrianglesNPY::MXPYPZ = glm::vec3(-1,1,1) ;
const glm::vec3 NTrianglesNPY::MXPYMZ = glm::vec3(-1,1,-1) ;
const glm::vec3 NTrianglesNPY::MXMYPZ = glm::vec3(-1,-1,1) ;
const glm::vec3 NTrianglesNPY::MXMYMZ = glm::vec3(-1,-1,-1) ;

NTrianglesNPY* NTrianglesNPY::cube()
{
    NTrianglesNPY* tris = new NTrianglesNPY();

    tris->add(PXPYPZ, MXPYPZ, MXMYPZ, PXMYPZ);    // PZ face
    tris->add(PXPYPZ, PXMYPZ, PXMYMZ, PXPYMZ);    // PX face
    tris->add(PXPYPZ, PXPYMZ, MXPYMZ, MXPYPZ);    // PY face

    tris->add(MXMYMZ, PXMYMZ, PXPYMZ, MXPYMZ);    // MZ face
    tris->add(MXMYMZ, MXPYMZ, MXPYPZ, MXMYPZ);    // MX face
    tris->add(MXMYMZ, MXMYPZ, PXMYPZ, PXMYMZ);    // MY face

    return tris ;
}

NTrianglesNPY* NTrianglesNPY::box(const nbbox& bb)
{
    NTrianglesNPY* tris = new NTrianglesNPY();

    glm::vec3 P(bb.max.x, bb.max.y, bb.max.z );
    glm::vec3 M(bb.min.x, bb.min.y, bb.min.z );

    glm::vec3 _PXPYPZ( P.x, P.y, P.z );
    glm::vec3 _PXPYMZ( P.x, P.y, M.z );
    glm::vec3 _PXMYPZ( P.x, M.y, P.z );
    glm::vec3 _PXMYMZ( P.x, M.y, M.z );

    glm::vec3 _MXPYPZ( M.x, P.y, P.z );
    glm::vec3 _MXPYMZ( M.x, P.y, M.z );
    glm::vec3 _MXMYPZ( M.x, M.y, P.z );
    glm::vec3 _MXMYMZ( M.x, M.y, M.z ) ;

    tris->add(_PXPYPZ, _MXPYPZ, _MXMYPZ, _PXMYPZ);    // PZ face
    tris->add(_PXPYPZ, _PXMYPZ, _PXMYMZ, _PXPYMZ);    // PX face
    tris->add(_PXPYPZ, _PXPYMZ, _MXPYMZ, _MXPYPZ);    // PY face

    tris->add(_MXMYMZ, _PXMYMZ, _PXPYMZ, _MXPYMZ);    // MZ face
    tris->add(_MXMYMZ, _MXPYMZ, _MXPYPZ, _MXMYPZ);    // MX face
    tris->add(_MXMYMZ, _MXMYPZ, _PXMYPZ, _PXMYMZ);    // MY face

    return tris ;
}

NTrianglesNPY* NTrianglesNPY::prism(const glm::vec4& param)
{
/*
::

   .

               A'
                    A  (0,height)
                   /|\
                  / | \
                 /  |  \
                /   h   \
               /    |    \ (x,y)
         L'   M     |     N
             /      |      \
            L-------O-------R

     (-hwidth,0)  (0,0)    (hwidth, 0)

*/

    // hmm how to avoid duplication between here and hemi-pmt.cu/make_prism
    float angle = param.x > 0.f ? param.x : 60.f ;
    float height = param.y > 0.f ? param.y : param.w  ;
    float depth = param.z > 0.f ? param.z : param.w ;

    float pi = boost::math::constants::pi<float>() ;
    float hwidth = height*tan((pi/180.f)*angle/2.0f) ;

    float ymax =  height/2.0f ;
    float ymin = -height/2.0f ;

    glm::vec3 apex_near(0.f,     ymax, depth/2.f );
    glm::vec3 apex_far( 0.f,     ymax, -depth/2.f );

    glm::vec3 left_near(-hwidth,  ymin, depth/2.f);
    glm::vec3 left_far(-hwidth,   ymin, -depth/2.f);

    glm::vec3 right_near( hwidth, ymin, depth/2.f);
    glm::vec3 right_far( hwidth,  ymin, -depth/2.f);

    NTrianglesNPY* tris = new NTrianglesNPY();

    tris->add( apex_near, apex_far, left_far, left_near );
    tris->add( apex_near, right_near,  right_far,  apex_far );
    tris->add( left_near, left_far, right_far, right_near );
    tris->add( apex_near, left_near, right_near );
    tris->add( apex_far,  right_far, left_far );

    return tris ;
}

ext: cpp

max_stars_repo_name: hanswenzel/opticks

max_issues_repo_name: hanswenzel/opticks

max_forks_repo_name: hanswenzel/opticks


text:
#include "cerealHelper.hpp"
#include <Eigen/Dense>
#include <boost/program_options.hpp>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <pcl/common/common.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/visualization/cloud_viewer.h>
#include <thread>

/* Include the C++ DDS API. */
#include "dds/dds.hpp"

/* Include data type and specific traits to be used with the C++ DDS API. */
#include "ExampleIdlData.hpp"

namespace po = boost::program_options;
using namespace org::eclipse::cyclonedds;

static inline std::stringstream toString(const std::vector<unsigned char>& data) {
    std::stringstream ss;
    ss.write((char const*)data.data(), std::streamsize(data.size()));
    return ss;
}

void processMsg(const ExampleIdlData::Msg& msg);

int main(int argc, char** argv)
{
    // --- Send through DDS

    /* First, a domain participant is needed.
     * Create one on the default domain. */
    dds::domain::DomainParticipant participant(domain::default_id());

    /* To publish something, a topic is needed. */
    dds::topic::Topic<ExampleIdlData::Msg> topic(participant, "example_topic");

    /* A reader also needs a subscriber. */
    dds::sub::Subscriber subscriber(participant);

    /* Now, the reader can be created to subscribe to a HelloWorld message. */
    dds::sub::DataReader<ExampleIdlData::Msg> reader(subscriber, topic);

    /* Poll until a message has been read.
     * It isn't really recommended to do this kind wait in a polling loop.
     * It's done here just to illustrate the easiest way to get data.
     * Please take a look at Listeners and WaitSets for much better
     * solutions, albeit somewhat more elaborate ones. */
    std::cout << "=== [Subscriber] Wait for message." << std::endl;
    bool poll = true;
    while (poll) {
        /* For this example, the reader will return a set of messages (aka
         * Samples). There are other ways of getting samples from reader.
         * See the various read() and take() functions that are present. */
        dds::sub::LoanedSamples<ExampleIdlData::Msg> samples;

        /* Try taking samples from the reader. */
        samples = reader.take();

        /* Are samples read? */
        if (samples.length() > 0) {
            /* Use an iterator to run over the set of samples. */
            dds::sub::LoanedSamples<ExampleIdlData::Msg>::const_iterator sample_iter;
            for (sample_iter = samples.begin(); sample_iter < samples.end(); ++sample_iter) {
                /* Get the message and sample information. */
                const ExampleIdlData::Msg& msg = sample_iter->data();
                const dds::sub::SampleInfo& info = sample_iter->info();

                /* Sometimes a sample is read, only to indicate a data
                 * state change (which can be found in the info). If
                 * that's the case, only the key value of the sample
                 * is set. The other data parts are not.
                 * Check if this sample has valid data. */
                if (info.valid()) {
                    std::cout << "=== [Subscriber] Message received:" << std::endl;
                    std::cout << "    userID  : " << msg.id() << std::endl;
                    std::cout << "    Message : \"" << msg.message() << "\"" << std::endl;

                    processMsg(msg);

                    /* Only 1 message is expected in this example. */
                    poll = false;
                }
            }
        } else {
            std::this_thread::sleep_for(std::chrono::milliseconds(20));
        }
    }

    // ---
    return 0;
}

void processMsg(const ExampleIdlData::Msg& msg) {

    // --- Processing Normal (Numpy) Matrix

    Eigen::Affine3d htMat{Eigen::Affine3d::Identity()};
    auto eigenStream = toString(msg.payloadEigen());
    cereal::BinaryInputArchive inputArchive(eigenStream);
    inputArchive(CEREAL_NVP(htMat));
    std::cout << "htMat: " << std::endl << htMat.matrix() << std::endl;

    // ---

}

max_stars_repo_name: vbillys/reading-group-serialization

max_issues_repo_name: vbillys/reading-group-serialization

max_forks_repo_name: vbillys/reading-group-serialization


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef OOX_DRAWINGML_CUSTOMSHAPEPROPERTIES_HXX
#define OOX_DRAWINGML_CUSTOMSHAPEPROPERTIES_HXX

#include <boost/shared_ptr.hpp>
#include <vector>
#include <map>
#include <com/sun/star/drawing/EnhancedCustomShapeParameterPair.hpp>
#include <com/sun/star/drawing/EnhancedCustomShapeParameterType.hpp>
#include <com/sun/star/drawing/EnhancedCustomShapeSegment.hpp>
#include <com/sun/star/drawing/EnhancedCustomShapeGluePointType.hpp>
#include <com/sun/star/drawing/EnhancedCustomShapeSegmentCommand.hpp>
#include <com/sun/star/drawing/EnhancedCustomShapeTextFrame.hpp>
#include <com/sun/star/drawing/EnhancedCustomShapeAdjustmentValue.hpp>
#include <com/sun/star/drawing/EnhancedCustomShapeTextPathMode.hpp>
#include <com/sun/star/beans/PropertyValues.hpp>
#include <com/sun/star/drawing/ProjectionMode.hpp>
#include <com/sun/star/drawing/XShape.hpp>
#include <com/sun/star/graphic/XGraphic.hpp>
#include "oox/core/xmlfilterbase.hxx"
#include "oox/drawingml/color.hxx"
#include "oox/helper/helper.hxx"
#include "oox/helper/propertymap.hxx"
#include "oox/token/tokens.hxx"

namespace oox { namespace drawingml {

class CustomShapeProperties;

typedef boost::shared_ptr< CustomShapeProperties > CustomShapePropertiesPtr;

struct CustomShapeGuide
{
	rtl::OUString	maName;
	rtl::OUString	maFormula;
};

struct AdjustHandle
{
	sal_Bool								polar;
	com::sun::star::drawing::EnhancedCustomShapeParameterPair
											pos;

	// depending to the type (polar or not):
	OptValue< rtl::OUString >				gdRef1;	// gdRefX	or gdRefR
	OptValue< com::sun::star::drawing::EnhancedCustomShapeParameter >
											min1;	// minX		or minR
	OptValue< com::sun::star::drawing::EnhancedCustomShapeParameter >
											max1;	// maxX		or maxR
	OptValue< rtl::OUString >				gdRef2;	// gdRefY	or gdRefAng
	OptValue< com::sun::star::drawing::EnhancedCustomShapeParameter >
											min2;	// minX		or minAng
	OptValue< com::sun::star::drawing::EnhancedCustomShapeParameter >
											max2;	// maxY		or maxAng

	AdjustHandle( sal_Bool bPolar ) : polar( bPolar ) {};
};

struct ConnectionSite
{
	com::sun::star::drawing::EnhancedCustomShapeParameterPair
								pos;
	com::sun::star::drawing::EnhancedCustomShapeParameter
								ang;
};

struct GeomRect
{
	com::sun::star::drawing::EnhancedCustomShapeParameter	l;
	com::sun::star::drawing::EnhancedCustomShapeParameter	t;
	com::sun::star::drawing::EnhancedCustomShapeParameter	r;
	com::sun::star::drawing::EnhancedCustomShapeParameter	b;
};

struct Path2D
{
	sal_Int64	w;
	sal_Int64	h;
	sal_Int32	fill;
	sal_Bool	stroke;
	sal_Bool	extrusionOk;
	std::vector< com::sun::star::drawing::EnhancedCustomShapeParameterPair > parameter;

	Path2D() : w( 0 ), h( 0 ), fill( XML_norm ), stroke( sal_True ), extrusionOk( sal_True ) {};
};

class CustomShapeProperties
{
public:

	CustomShapeProperties();
    virtual ~CustomShapeProperties();

	void apply( const CustomShapePropertiesPtr& );
    void pushToPropSet( const ::oox::core::FilterBase& rFilterBase,
			const ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySet > & xPropSet,
                        const ::com::sun::star::uno::Reference < ::com::sun::star::drawing::XShape > & xShape) const;

	void setShapePresetType( const rtl::OUString& rShapePresetType ){ maShapePresetType = rShapePresetType; };

	std::vector< CustomShapeGuide >&	getAdjustmentGuideList(){ return maAdjustmentGuideList; };
	std::vector< CustomShapeGuide >&	getGuideList(){ return maGuideList; };
	std::vector< AdjustHandle >&		getAdjustHandleList(){ return maAdjustHandleList; };
	std::vector< ConnectionSite >&		getConnectionSiteList(){ return maConnectionSiteList; };
	OptValue< GeomRect >&				getTextRect(){ return maTextRect; };
	std::vector< Path2D >&				getPath2DList(){ return maPath2DList; };
	std::vector< com::sun::star::drawing::EnhancedCustomShapeSegment >& getSegments(){ return maSegments; };
	void								setMirroredX( sal_Bool bMirroredX ) { mbMirroredX = bMirroredX; };
	void								setMirroredY( sal_Bool bMirroredY ) { mbMirroredY = bMirroredY; };

    // #119920# Add missing extra text rotation
    void setTextRotation(sal_Int32 nTextRotation) { mnTextRotation = nTextRotation; }

	double getValue( const std::vector< CustomShapeGuide >&, sal_uInt32 nIndex ) const;
	static sal_Int32 SetCustomShapeGuideValue( std::vector< CustomShapeGuide >& rGuideList, const CustomShapeGuide& rGuide );
	static sal_Int32 GetCustomShapeGuideValue( const std::vector< CustomShapeGuide >& rGuideList, const rtl::OUString& rFormulaName );

private:

	rtl::OUString					maShapePresetType;
	std::vector< CustomShapeGuide >	maAdjustmentGuideList;
	std::vector< CustomShapeGuide >	maGuideList;
	std::vector< AdjustHandle >		maAdjustHandleList;
	std::vector< ConnectionSite >	maConnectionSiteList;
	OptValue< GeomRect >			maTextRect;
	std::vector< Path2D >			maPath2DList;

	std::vector< com::sun::star::drawing::EnhancedCustomShapeSegment >
									maSegments;
	sal_Bool						mbMirroredX;
	sal_Bool						mbMirroredY;

    // #119920# Add missing extra text rotation
    sal_Int32                       mnTextRotation;
};

} }

#endif  //  OOX_DRAWINGML_CUSTOMSHAPEPROPERTIES_HXX

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
//*****************************************************************************
// Copyright 2015 MIT Lincoln Laboratory
// Project:            SPAR
// Authors:            ni24039
// Description:        Unit tests for ServerSUTProtocolStack.
//
// Modifications:
// Date          Name           Modification
// ----          ----           ------------
// 15 Nov 2012   ni24039        Original Version
//*****************************************************************************

#define BOOST_TEST_MODULE ServerSUTProtocolStackTest
#include <boost/assign/list_of.hpp>

#include "server-sut-protocol-stack.h"
#include "test-harness/common/root-mode-command-sender.h"
#include "test-harness/common/numbered-command-sender.h"
#include "test-harness/common/spawn-sut.h"
#include "common/event-loop.h"
#include "common/test-init.h"
#include "common/test-util.h"
#include "common/util.h"

using boost::assign::list_of;
using namespace std;

BOOST_AUTO_TEST_CASE(ServerSUTProtocolStackWorks) {
  EventLoop event_loop;
  ServerSUTProtocolStack protocol_stack;
  int sut_stdin_read_fd;
  int sut_stdout_write_fd;

  // Set up the function that will set up the notional SUT's pipes.
  auto pipe_fun = [&](int* sut_stdin, int* sut_stdout) {
    SetupPipes(sut_stdout, &sut_stdout_write_fd,
               &sut_stdin_read_fd, sut_stdin);
    return 0;
  };

  // Spawn the notional SUT and build its protocol stack.
  SpawnSUT(pipe_fun, "", false, &event_loop, nullptr, nullptr,
      &protocol_stack, nullptr);

  event_loop.Start();

  // Set up access to the notional SUT's stdin/out.
  FileHandleOStream sut_output_stream(sut_stdout_write_fd);
  FileHandleIStream sut_input_stream(sut_stdin_read_fd);

  // Perform command sequence. SUT output is simulated by writing to
  // sut_output_stream while test harness output is simulated by using
  // protocol_stack's API. SUT input is verified via VerifyIStreamContents.
  LOG(DEBUG) << "SUT sending READY...";
  sut_output_stream << "READY" << endl;

  LOG(DEBUG) << "TH sending PUBLISH...";
  protocol_stack.WaitUntilReady();
  LineRawData<Knot> publish_data;
  // This is the publication metadata.
  publish_data.AddLine(Knot(new string("John,McClane,123456789,1955-05-23")));
  // This is the publication payload.
  publish_data.AddRaw(Knot(new string(
    "Come out to the coast, we'll get together, have a few laughs...")));
  NumberedCommandSender::ResultsFuture sub_f =
    protocol_stack.GetPublishCommand()->Schedule(publish_data);
  VerifyIStreamContents(list_of(string("COMMAND 0"))("PUBLISH")
      ("METADATA")("John,McClane,123456789,1955-05-23")("PAYLOAD")
      ("RAW")("63")
      ("Come out to the coast, we'll get together, have a few laughs...ENDRAW")
      ("ENDPAYLOAD")("ENDPUBLISH")("ENDCOMMAND"),
      &sut_input_stream);

  LOG(DEBUG) << "SUT sending RESULTS...";
  sut_output_stream << "RESULTS 0\nDONE\nENDRESULTS\nREADY" << endl;
  BOOST_CHECK_EQUAL(sub_f.Value()->command_id, 0);
  BOOST_REQUIRE_EQUAL(sub_f.Value()->results_received.Size(), 1);
  BOOST_CHECK_EQUAL(sub_f.Value()->results_received.IsRaw(0), false);
  BOOST_CHECK_EQUAL(sub_f.Value()->results_received.Get(0), "DONE");

  LOG(DEBUG) << "TH sending SHUTDOWN...";
  protocol_stack.WaitUntilReady();
  protocol_stack.GetRootModeCommandSender()->SendCommand("SHUTDOWN");
  VerifyIStreamContents(list_of(string("SHUTDOWN")), &sut_input_stream);
  sut_output_stream << "DONE" << endl;
  // This final READY/wait sequence is done to ensure protocol_stack receives
  // all of the notional SUT's output before event_loop terminates.
  sut_output_stream << "READY" << endl;
  sut_output_stream.close();
  protocol_stack.WaitUntilReady();
  event_loop.ExitLoopAndWait();
}

max_stars_repo_name: nathanawmk/SPARTA

max_issues_repo_name: nathanawmk/SPARTA

max_forks_repo_name: nathanawmk/SPARTA


text:
#include <iostream>
#include <string>
#include <ctime>
#include <chrono>
#include <boost/date_time/gregorian/gregorian.hpp>
#include "_datetime.h"
#include "_math.h"

void _datetime::init()
{
  // current date/time based on current system
  time_t now = time(0);

  // convert now to string form
  char* dt = ctime(&now);

  // convert now to string form
  std::string strdt = ctime(&now);

  // convert now to tm struct for UTC
  tm *gmtm = gmtime(&now);
  std::string strUTCdt = asctime(gmtm);

  //boost datetime
  boost::gregorian::date weekstart(2002,boost::gregorian::Feb,1);

  std::cout<< "(now)[time_t now = time(0);]: "<< now <<"\n";
  std::cout<< "(dt)[char* dt = ctime(&now);]: "<< dt <<"\n";
  std::cout<< "(strdt)[std::string strdt = ctime(&now);]: "<< strdt <<"\n";
  std::cout<< "(strdt)[std::string strUTCdt = asctime(gmtm);]: "<< strUTCdt <<"\n";
  std::cout<< "(now)[boost::gregorian::date weekstart(2002,Feb,1);]: "<< weekstart <<"\n";
}

void _datetime::sample()
{
  auto start = std::chrono::system_clock::now();
  std::cout << "f(44) = " << _math::fibonacci(44) << '\n';
  auto end = std::chrono::system_clock::now();

  std::chrono::duration<double> elapsed_seconds = end-start;
  std::time_t end_time = std::chrono::system_clock::to_time_t(end);

  std::cout << "finished computation at " << std::ctime(&end_time)
            << "elapsed time: " << elapsed_seconds.count() << "s\n";
}


text: #include <boost/spirit/home/classic/core/primitives/numerics_fwd.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <claire/netty/TcpClient.h>

#include <stdio.h>

#include <boost/bind.hpp>
#include <boost/make_shared.hpp>

#include <claire/netty/Connector.h>
#include <claire/netty/Socket.h>
#include <claire/netty/TcpConnection.h>
#include <claire/common/base/WeakCallback.h>
#include <claire/common/events/EventLoop.h>
#include <claire/common/threading/Mutex.h>
#include <claire/common/logging/Logging.h>

namespace claire {

class TcpClient::Impl : boost::noncopyable,
                        public boost::enable_shared_from_this<TcpClient::Impl>
{
public:
    Impl(EventLoop* loop__, const std::string& name__)
        : loop_(loop__),
          name_(name__),
          retry_(false),
          connect_(false),
          next_id_(1)
    {}

    ~Impl()
    {
        MutexLock lock(mutex_);
        if (!connection_ && connector_)
        {
            connector_->Stop();
        }
    }

    void Connect(const InetAddress& server_address)
    {
        LOG(INFO) << "TcpClient::Connect[" << name_ << "] - connecting to "
                  << server_address.ToString();

        connect_ = true;
        connector_.reset(new Connector(loop_, server_address));
        connector_->set_new_connection_callback(
            boost::bind(&Impl::NewConnection, this, _1));
        connector_->Connect();
    }

    void Shutdown()
    {
        connect_ = false;
        {
            MutexLock lock(mutex_);
            if (connection_)
            {
                connection_->Shutdown();
            }
        }
    }

    void Stop()
    {
        connect_ = false;
        if (connector_)
        {
            connector_->Stop();
        }
    }

    bool retry() const { return retry_; }
    void set_retry(bool on) { retry_ = on; }

    void set_connection_callback(const ConnectionCallback& callback)
    {
        connection_callback_ = callback;
    }

    void set_message_callback(const MessageCallback& callback)
    {
        message_callback_ = callback;
    }

    void set_write_complete_callback(const WriteCompleteCallback& callback)
    {
        write_complete_callback_ = callback;
    }

    TcpConnectionPtr connection() const
    {
        MutexLock lock(mutex_);
        return connection_;
    }

    EventLoop* loop() { return loop_; }

private:
    void NewConnection(Socket& socket)
    {
        loop_->AssertInLoopThread();

        // FIXME poll with zero timeout to double confirm the new connection
        TcpConnectionPtr connection__(
            boost::make_shared<TcpConnection>(loop_,
                                              std::move(socket),
                                              next_id_++));
        connection__->set_connection_callback(connection_callback_);
        connection__->set_message_callback(message_callback_);
        connection__->set_write_complete_callback(write_complete_callback_);

        auto callback = MakeWeakCallback(&Impl::RemoveConnection, shared_from_this());
        connection__->set_close_callback(callback);

        {
            MutexLock lock(mutex_);
            connection_ = connection__;
        }
        connection_->ConnectEstablished();
    }

    void RemoveConnection(const TcpConnectionPtr& connection__)
    {
        loop_->AssertInLoopThread();
        DCHECK(loop_ == connection__->loop());

        {
            MutexLock lock(mutex_);
            DCHECK(connection__ == connection_);
            connection_.reset();
        }

        loop_->Post(
            boost::bind(&TcpConnection::ConnectDestroyed, connection__)); // thread safe
        if (retry_ && connect_)
        {
            LOG(INFO) << "TcpClient::RemoveConnection[" << name_ << "] - Reconnecting to "
                      << connection__->peer_address().ToString();
            connector_->Restart();
        }
    }

    EventLoop* loop_;
    ConnectorPtr connector_;
    const std::string name_;

    ConnectionCallback connection_callback_;
    MessageCallback message_callback_;
    WriteCompleteCallback write_complete_callback_;

    boost::atomic<bool> retry_;
    boost::atomic<bool> connect_;

    TcpConnection::Id next_id_; // overflow is ok

    mutable Mutex mutex_;
    TcpConnectionPtr connection_; //@GUARD_BY mutex_
};

TcpClient::TcpClient(EventLoop* loop__,
                     const std::string& name__)
    : impl_(new Impl(loop__, name__)) {}

TcpClient::~TcpClient() {}

void TcpClient::Connect(const InetAddress& server_address)
{
    impl_->Connect(server_address);
}

void TcpClient::Shutdown()
{
    impl_->Shutdown();
}

void TcpClient::Stop()
{
    impl_->Stop();
}

bool TcpClient::retry() const
{
    return impl_->retry();
}

void TcpClient::set_retry(bool on)
{
    impl_->set_retry(on);
}

void TcpClient::set_connection_callback(const ConnectionCallback& callback)
{
    impl_->set_connection_callback(callback);
}

void TcpClient::set_message_callback(const MessageCallback& callback)
{
    impl_->set_message_callback(callback);
}

void TcpClient::set_write_complete_callback(const WriteCompleteCallback& callback)
{
    impl_->set_write_complete_callback(callback);
}

TcpConnectionPtr TcpClient::connection() const
{
    return impl_->connection();
}

EventLoop* TcpClient::loop()
{
    return impl_->loop();
}

} // namespace claire

max_stars_repo_name: robbinfan/claire

max_issues_repo_name: robbinfan/claire

max_forks_repo_name: robbinfan/claire


text:
/*
 * libfreelan - A C++ library to establish peer-to-peer virtual private
 * networks.
 * Copyright (C) 2010-2011 Julien KAUFFMANN <julien.kauffmann@freelan.org>
 *
 * This file is part of libfreelan.
 *
 * libfreelan 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.
 *
 * libfreelan 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.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.  If you delete this exception statement from all source
 * files in the program, then also delete it here.
 *
 * If you intend to use libfreelan in a commercial software, please
 * contact me : we may arrange this for a small fee or no fee at all,
 * depending on the nature of your project.
 */

/**
 * \file client.hpp
 * \author Julien KAUFFMANN <julien.kauffmann@freelan.org>
 * \brief A client implementation.
 */

#pragma once

#include <set>

#include <boost/asio.hpp>
#include <boost/function.hpp>
#include <boost/enable_shared_from_this.hpp>

#include <cryptoplus/x509/certificate.hpp>
#include <cryptoplus/x509/certificate_request.hpp>

#include <fscp/logger.hpp>

#include <asiotap/types/endpoint.hpp>

#include "os.hpp"
#include "configuration.hpp"
#include "curl.hpp"

namespace freelan
{
	class web_client : public boost::enable_shared_from_this<web_client>
	{
		public:
			typedef boost::function<void (const boost::system::error_code&, cryptoplus::x509::certificate)> request_certificate_callback;
			typedef boost::function<void (const boost::system::error_code&, const boost::posix_time::ptime&)> registration_callback;
			typedef boost::function<void (const boost::system::error_code&)> unregistration_callback;
			typedef boost::function<void (const boost::system::error_code&, const std::set<asiotap::endpoint>&, const std::set<asiotap::endpoint>&)> set_contact_information_callback;
			typedef boost::function<void (const boost::system::error_code&, const std::map<fscp::hash_type, std::set<asiotap::endpoint>>&)> get_contact_information_callback;

			/**
			 * \brief Create a new web client.
			 * \param io_service The io_service to bind to.
			 * \param _logger The logger to use.
			 * \param configuration The configuration to use.
			 */
			static boost::shared_ptr<web_client> create(boost::asio::io_service& io_service, fscp::logger& _logger, const freelan::client_configuration& configuration)
			{
				return boost::shared_ptr<web_client>(new web_client(io_service, _logger, configuration));
			}

			/**
			 * \brief Request the server for a certificate.
			 * \param certifcate_request The certificate request to send.
			 * \param handler The handler that will get called when the response is received.
			 */
			void request_certificate(cryptoplus::x509::certificate_request certificate_request, request_certificate_callback handler);

			/**
			 * \brief Request the server's CA certificate.
			 * \param handler The handler that will get called when the response is received.
			 */
			void request_ca_certificate(request_certificate_callback handler);

			/**
			 * \brief Register upon the server.
			 * \param certifcate The certificate to send.
			 * \param handler The handler that will get called when the response is received.
			 */
			void register_(cryptoplus::x509::certificate certificate, registration_callback handler);

			/**
			 * \brief Unregister from the server.
			 * \param handler The handler that will get called when the response is received.
			 */
			void unregister(unregistration_callback handler);

			/**
			 * \brief Set contact information on the server.
			 * \param public_endpoints The public endpoints.
			 * \param handler The handler that will get called when the response is received.
			 */
			void set_contact_information(const std::set<asiotap::endpoint>& public_endpoints, set_contact_information_callback handler);

			/**
			 * \brief Get contact information from the server.
			 * \param requested_contacts The hashes of the contacts to request.
			 * \param handler The handler that will get called when the response is received.
			 */
			void get_contact_information(const std::set<fscp::hash_type>& requested_contacts, get_contact_information_callback handler);

		private:
			web_client(boost::asio::io_service& io_service, fscp::logger& _logger, const freelan::client_configuration& configuration);
			boost::shared_ptr<curl> make_request(const std::string& path) const;

			boost::shared_ptr<curl_multi_asio> m_curl_multi_asio;
			fscp::logger& m_logger;
			freelan::client_configuration m_configuration;
			std::string m_url_prefix;
	};
}

max_stars_repo_name: krattai/AEBL

max_issues_repo_name: krattai/AEBL

max_forks_repo_name: krattai/AEBL


text:
/*
 *  MIT License
 *
 *  Copyright (c) 2017 Piotr Dobrowolski
 *
 *  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.
 *
 */
/*
 * Author: Piotr Dobrowolski
 * dobrypd[at]gmail[dot]com
 *
 */
#ifndef REALTIMEENGINE_HPP_
#define REALTIMEENGINE_HPP_

#include "config.h"
#include "ProcessingEngine.hpp"
#include "kernel/GenericFrame.hpp"
#include "kernel/ExposureValue.hpp"
#include "kernel/HdrCreation/HDRCreator.hpp"
#include "kernel/TonemappingOperators/dobrowolski15/Dobrowolski15.hpp"

#include <boost/interprocess/sync/interprocess_semaphore.hpp>
#include <opencv2/opencv.hpp>
#include <vector>

namespace ui
{

/*
 *
 */
class RealtimeEngine
{
private:
    const char* windowOriginalLabel = "Original image";

    cv::VideoCapture videoCapture;
    cv::VideoWriter videoWriter;
    bool createOutput;

    HDRCreation::HDRCreator hdrCreator;
    TMO::Dobrowolski15 tmo;

    unsigned int exposuresPerHDR;
    boost::interprocess::interprocess_semaphore semSwitch;
    boost::interprocess::interprocess_semaphore semCapture;

    typedef boost::shared_ptr<std::vector<kernel::GenericFramePtr> > vectorOfFramePtrsPtr_t;
    vectorOfFramePtrsPtr_t buffer;
    vectorOfFramePtrsPtr_t work;

    bool quit;

    float fps;
    unsigned int delayMs;

    std::string deviceName;
    unsigned int exposureCompensactionRange;
    bool initializedOnlyGenericDevice;

    const GlobalArgs_t & globalArgs;

    bool initializeDevice();
    kernel::ExposureValue changeDeviceSettings(int expNo, bool & success);
    bool openVideoWriter(kernel::GenericFramePtr & frame);

    void videoCapturer();
    void creator();

public:
    explicit RealtimeEngine(const GlobalArgs_t & globalArgs, int exposuresPerHDR = 1);

    void run();
};

} /* namespace ui */

#endif /* REALTIMEENGINE_HPP_ */

max_stars_repo_name: dobrypd/HDR-Simple-Framework

max_issues_repo_name: dobrypd/HDR-Simple-Framework

max_forks_repo_name: dobrypd/HDR-Simple-Framework


text:
// Copyright 2017 The Ray Authors.
//
// 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 "ray/raylet/raylet.h"

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>

#include "ray/common/status.h"
#include "ray/util/util.h"

namespace {

const std::vector<std::string> GenerateEnumNames(const char *const *enum_names_ptr,
                                                 int start_index, int end_index) {
  std::vector<std::string> enum_names;
  for (int i = 0; i < start_index; ++i) {
    enum_names.push_back("EmptyMessageType");
  }
  size_t i = 0;
  while (true) {
    const char *name = enum_names_ptr[i];
    if (name == nullptr) {
      break;
    }
    enum_names.push_back(name);
    i++;
  }
  RAY_CHECK(static_cast<size_t>(end_index) == enum_names.size() - 1)
      << "Message Type mismatch!";
  return enum_names;
}

static const std::vector<std::string> node_manager_message_enum =
    GenerateEnumNames(ray::protocol::EnumNamesMessageType(),
                      static_cast<int>(ray::protocol::MessageType::MIN),
                      static_cast<int>(ray::protocol::MessageType::MAX));
}  // namespace

namespace ray {

namespace raylet {

Raylet::Raylet(boost::asio::io_service &main_service, const std::string &socket_name,
               const std::string &node_ip_address, const std::string &redis_address,
               int redis_port, const std::string &redis_password,
               const NodeManagerConfig &node_manager_config,
               const ObjectManagerConfig &object_manager_config,
               std::shared_ptr<gcs::GcsClient> gcs_client, int metrics_export_port)
    : self_node_id_(ClientID::FromRandom()),
      gcs_client_(gcs_client),
      object_directory_(
          RayConfig::instance().ownership_based_object_directory_enabled()
              ? std::dynamic_pointer_cast<ObjectDirectoryInterface>(
                    std::make_shared<OwnershipBasedObjectDirectory>(main_service,
                                                                    gcs_client_))
              : std::dynamic_pointer_cast<ObjectDirectoryInterface>(
                    std::make_shared<ObjectDirectory>(main_service, gcs_client_))),
      object_manager_(main_service, self_node_id_, object_manager_config,
                      object_directory_),
      node_manager_(main_service, self_node_id_, node_manager_config, object_manager_,
                    gcs_client_, object_directory_),
      socket_name_(socket_name),
      acceptor_(main_service, ParseUrlEndpoint(socket_name)),
      socket_(main_service) {
  self_node_info_.set_node_id(self_node_id_.Binary());
  self_node_info_.set_state(GcsNodeInfo::ALIVE);
  self_node_info_.set_node_manager_address(node_ip_address);
  self_node_info_.set_raylet_socket_name(socket_name);
  self_node_info_.set_object_store_socket_name(object_manager_config.store_socket_name);
  self_node_info_.set_object_manager_port(object_manager_.GetServerPort());
  self_node_info_.set_node_manager_port(node_manager_.GetServerPort());
  self_node_info_.set_node_manager_hostname(boost::asio::ip::host_name());
  self_node_info_.set_metrics_export_port(metrics_export_port);
}

Raylet::~Raylet() {}

void Raylet::Start() {
  RAY_CHECK_OK(RegisterGcs());

  // Start listening for clients.
  DoAccept();
}

void Raylet::Stop() {
  object_manager_.Stop();
  RAY_CHECK_OK(gcs_client_->Nodes().UnregisterSelf());
  acceptor_.close();
}

ray::Status Raylet::RegisterGcs() {
  RAY_RETURN_NOT_OK(gcs_client_->Nodes().RegisterSelf(self_node_info_));

  RAY_LOG(DEBUG) << "Node manager " << self_node_id_ << " started on "
                 << self_node_info_.node_manager_address() << ":"
                 << self_node_info_.node_manager_port() << " object manager at "
                 << self_node_info_.node_manager_address() << ":"
                 << self_node_info_.object_manager_port() << ", hostname "
                 << self_node_info_.node_manager_hostname();

  // Add resource information.
  const NodeManagerConfig &node_manager_config = node_manager_.GetInitialConfig();
  std::unordered_map<std::string, std::shared_ptr<gcs::ResourceTableData>> resources;
  for (const auto &resource_pair : node_manager_config.resource_config.GetResourceMap()) {
    auto resource = std::make_shared<gcs::ResourceTableData>();
    resource->set_resource_capacity(resource_pair.second);
    resources.emplace(resource_pair.first, resource);
  }
  RAY_RETURN_NOT_OK(
      gcs_client_->Nodes().AsyncUpdateResources(self_node_id_, resources, nullptr));

  RAY_RETURN_NOT_OK(node_manager_.RegisterGcs());

  return Status::OK();
}

void Raylet::DoAccept() {
  acceptor_.async_accept(socket_, boost::bind(&Raylet::HandleAccept, this,
                                              boost::asio::placeholders::error));
}

void Raylet::HandleAccept(const boost::system::error_code &error) {
  if (!error) {
    // TODO: typedef these handlers.
    ClientHandler client_handler = [this](ClientConnection &client) {
      node_manager_.ProcessNewClient(client);
    };
    MessageHandler message_handler = [this](std::shared_ptr<ClientConnection> client,
                                            int64_t message_type,
                                            const std::vector<uint8_t> &message) {
      node_manager_.ProcessClientMessage(client, message_type, message.data());
    };
    // Accept a new local client and dispatch it to the node manager.
    auto new_connection = ClientConnection::Create(
        client_handler, message_handler, std::move(socket_), "worker",
        node_manager_message_enum,
        static_cast<int64_t>(protocol::MessageType::DisconnectClient));
  }
  // We're ready to accept another client.
  DoAccept();
}

}  // namespace raylet

}  // namespace ray

max_stars_repo_name: carlos-aguayo/ray

max_issues_repo_name: carlos-aguayo/ray

max_forks_repo_name: carlos-aguayo/ray


text:
#pragma once
#include <type_traits>
#include <utility>

#include <boost/hana/tuple.hpp>
#include <boost/hana/zip_with.hpp>
#include <boost/static_assert.hpp>

#include <jni.h>

#include <cppjni/jni_wrappers/call_constructor.hpp>
#include <cppjni/jni_wrappers/call_static_method.hpp>
#include <cppjni/jni_wrappers/call_object_method.hpp>
#include <cppjni/jni_wrappers/generate_jni_signature_string.hpp>
#include <cppjni/jni_wrappers/current_environment.hpp>
#include <cppjni/jni_wrappers/method_id_cache.hpp>
#include <cppjni/meta_declaration/method_scope_category.hpp>
#include <cppjni/mpl/all.hpp>
#include <cppjni/mpl/filter.hpp>
#include <cppjni/mpl/find_if.hpp>
#include <cppjni/mpl/list.hpp>
#include <cppjni/mpl/optional.hpp>
#include <cppjni/mpl/pipeline.hpp>
#include <cppjni/mpl/size.hpp>
#include <cppjni/mpl/zip.hpp>

namespace cppjni
{
namespace methodcall
{
    template<bool is_class_scope>
    struct is_allowed_method_category;

    template<>
    struct is_allowed_method_category<true>
    {
        template<typename method_declaration_t>
        using f = std::integral_constant<
                    bool,
                       method_declaration_t::scope_category == metadeclaration::MethodScopeCategory::STATIC
                    || method_declaration_t::scope_category == metadeclaration::MethodScopeCategory::CONSTRUCTOR
                  >;
    };

    template<>
    struct is_allowed_method_category<false>
    {
        template<typename method_declaration_t>
        using f = std::integral_constant<
                    bool,
                    method_declaration_t::scope_category  == metadeclaration::MethodScopeCategory::INSTANCE
                  >;
    };

    template<typename T>
    struct list_to_tuple;

    template<typename... Ts>
    struct list_to_tuple<mpl::list<Ts...>>
    {
        static constexpr auto value = boost::hana::make_tuple(Ts{}...);
    };

    template<std::size_t args_count>
    struct has_args_count
    {
        template<typename T>
        using f = std::integral_constant<bool, mpl::eager::size<typename T::arguments_t>::value == args_count>;
    };

    struct is_convertible
    {
        template<typename T1, typename T2>
        using f = typename T2::template isConvertible<T1>;
    };

    template<typename container_t, typename converted_args_t, typename method_name_t, typename jni_return_type_t>
    struct call_static_method
    {
        auto operator()(const container_t& container, jmethodID methodID, converted_args_t&& convertedArguments) const
        {
            auto&& caller =
                typename mpl::condition<std::is_same<method_name_t, jniwrappers::constructor_method_name_t>::value>::template f<
                    jniwrappers::call_constructor,
                    jniwrappers::call_static_method
                >{};
            return caller.template operator()<jni_return_type_t>(container.jni_getClass(), methodID, std::move(convertedArguments));
        }
    };

    template<typename container_t, typename converted_args_t, typename jni_return_type_t>
    struct call_object_method
    {
        auto operator()(const container_t& container, jmethodID methodID, converted_args_t&& convertedArguments) const
        {
            return jniwrappers::call_object_method{}.operator()<jni_return_type_t>(container.jni_getObject(), methodID, std::move(convertedArguments));
        }
    };

    template<typename container_t, typename scope_caller_t, typename converted_args_t>
    struct call_function_returning_void
    {
        void operator()(const container_t& container, jmethodID methodID, converted_args_t&& convertedArguments) const
        {
            constexpr jniwrappers::CurrentEnvironment env{};
            scope_caller_t{}(container, methodID, std::move(convertedArguments));
            env.exceptionCheck();
        }
    };

    template<typename container_t, typename return_type_converter_t, typename scope_caller_t, typename converted_args_t>
    struct call_function_returning_value
    {
        auto operator()(const container_t& container, jmethodID methodID, converted_args_t&& convertedArguments) const
        {
            constexpr jniwrappers::CurrentEnvironment env{};
            auto&& jniCallResult = scope_caller_t{}(container, methodID, std::move(convertedArguments));
            env.exceptionCheck();
            return return_type_converter_t{}.convertFromJni(std::move(jniCallResult));
        }
    };

    /**
     * Implementation of actual Java method call - both compile-time and run-time.
     */
    template<typename class_path_t, typename all_overloads_t, typename instance_container_t>
    struct method_caller
    {
        template<typename... passed_args_t>
        struct are_overloaded_args_convertible_to_passed_args
        {
            template<typename overload_decl_t>
            using f =
                typename mpl::apply<
                    mpl::pipeline<
                        mpl::zip_with<is_convertible, passed_args_t...>,
                        mpl::all<mpl::is_true>
                    >,
                    typename overload_decl_t::arguments_t
                >::template continuation<mpl::identity>;
        };

        template<typename... passed_args_t>
        static auto call(const instance_container_t& container, passed_args_t&&... args)
        {
            jniwrappers::Environment env;
            (void)env;
            namespace hana = boost::hana;
            using namespace metadeclaration;

            using is_allowed_method_category_for_current_scope = is_allowed_method_category<instance_container_t::isClassScope::value>;

            using found_overload_t =
                typename mpl::apply<
                    typename mpl::pipeline<
                        mpl::filter<is_allowed_method_category_for_current_scope::template f>,
                        mpl::filter<
                            has_args_count<
                                sizeof...(passed_args_t)
                            >::template f
                        >,
                        mpl::find_if<
                            are_overloaded_args_convertible_to_passed_args<passed_args_t...>::template f
                        >
                    >,
                    all_overloads_t
                >::template continuation<mpl::optional>;
            static_assert(
                found_overload_t::has_type::value == true,
                "Couldn't convert all parameters to appropriate overload!"
            );

            using selected_declaration_t = typename found_overload_t::type;
            jmethodID methodID = jniwrappers::MethodIdStaticCache{}.findMethodId<class_path_t, selected_declaration_t>(container);

            constexpr auto converters = list_to_tuple<typename selected_declaration_t::arguments_t>::value;
            auto&& passedArgs = hana::make_tuple(std::forward<passed_args_t>(args)...);
            auto&& convertedArguments = hana::zip_with(
                [](auto&& native, auto converter) {
                    return converter.convertToJni(native);
                },
                passedArgs,
                converters
            );

            using method_name_t = typename selected_declaration_t::name_t;
            using return_t = typename selected_declaration_t::return_t;
            using jni_return_type_t = typename return_t::jni_t;
            using scope_caller_t =
                typename mpl::condition<instance_container_t::isClassScope::value>::template f<
                    call_static_method<instance_container_t, decltype(convertedArguments), method_name_t, jni_return_type_t>,
                    call_object_method<instance_container_t, decltype(convertedArguments), jni_return_type_t>
                >;

            using return_result_t = typename return_t::native_t;
            using result_returner_t =
                typename mpl::condition<std::is_same<return_result_t, void>::value>::template f<
                    call_function_returning_void<instance_container_t, scope_caller_t, decltype(convertedArguments)>,
                    call_function_returning_value<instance_container_t, return_t, scope_caller_t, decltype(convertedArguments)>
                >;
            return result_returner_t{}(
                container,
                methodID,
                std::move(convertedArguments)
            );
        }
    };
}
}

max_stars_repo_name: CMakeezer/cppJNI

max_issues_repo_name: CMakeezer/cppJNI

max_forks_repo_name: CMakeezer/cppJNI


text:
/**
 * Adobe Experience Manager (AEM) API
 * Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API
 *
 * The version of the OpenAPI document: 3.5.0-pre.0
 * Contact: opensource@shinesolutions.com
 *
 * NOTE: This class is auto generated by OpenAPI-Generator 5.2.1.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

#include "InstallStatus_status.h"

#include <string>
#include <sstream>
#include <stdexcept>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree;
using boost::property_tree::read_json;
using boost::property_tree::write_json;

namespace org {
namespace openapitools {
namespace server {
namespace model {

InstallStatus_status::InstallStatus_status()
{
	m_Finished = false;
	m_ItemCount = 0;
}

InstallStatus_status::~InstallStatus_status()
{
}

std::string InstallStatus_status::toJsonString(bool prettyJson)
{
	std::stringstream ss;
	write_json(ss, this->toPropertyTree(), prettyJson);
	return ss.str();
}

void InstallStatus_status::fromJsonString(std::string const& jsonString)
{
	std::stringstream ss(jsonString);
	ptree pt;
	read_json(ss,pt);
	this->fromPropertyTree(pt);
}

ptree InstallStatus_status::toPropertyTree()
{
	ptree pt;
	ptree tmp_node;
	pt.put("finished", m_Finished);
	pt.put("itemCount", m_ItemCount);
	return pt;
}

void InstallStatus_status::fromPropertyTree(ptree const &pt)
{
	ptree tmp_node;
	m_Finished = pt.get("finished", false);
	m_ItemCount = pt.get("itemCount", 0);
}

bool InstallStatus_status::isFinished() const
{
    return m_Finished;
}
void InstallStatus_status::setFinished(bool value)
{
	m_Finished = value;
}
int32_t InstallStatus_status::getItemCount() const
{
    return m_ItemCount;
}
void InstallStatus_status::setItemCount(int32_t value)
{
	m_ItemCount = value;
}

}
}
}
}

max_stars_repo_name: shinesolutions/swagger-aem

max_issues_repo_name: shinesolutions/swagger-aem

max_forks_repo_name: shinesolutions/swagger-aem


text:
/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2015
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/

#include <sstream>
#include <boost/algorithm/string/replace.hpp>

#include <round/common/encoding/Base64.h>
#include <round/core/Log.h>
#include <round/script/Tcl.h>

#if defined(ROUND_SUPPORT_TCL)

const std::string Round::TclEngine::LANGUAGE = "tcl";

////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////

Round::TclEngine::TclEngine() : ScriptEngine(LANGUAGE) {
  /*
  this->interp = Tcl_CreateInterp();
   */
}

////////////////////////////////////////////////
// Destructor
////////////////////////////////////////////////

Round::TclEngine::~TclEngine() {
}

////////////////////////////////////////////////
// compile
////////////////////////////////////////////////

bool Round::TclEngine::compile(const Script *script) const {
  return true;
}

////////////////////////////////////////////////
// run
////////////////////////////////////////////////

bool Round::TclEngine::run(const Script *tclScript, const std::string &params, std::string *results, Error *error) const {
  return false;
}

bool Round::TclEngine::run(const std::string &script, std::string *result, Error *error) const {
  return false;
}

#endif

max_stars_repo_name: cybergarage/round-cc

max_issues_repo_name: cybergarage/round-cc

max_forks_repo_name: cybergarage/round-cc


text:
//  Copyright (c) 2018-2019 Cem Bassoy
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#include <boost/test/unit_test.hpp>
#include <boost/numeric/ublas/tensor/extents.hpp>
#include <vector>

BOOST_AUTO_TEST_SUITE ( test_extents )

//*boost::unit_test::label("extents")
//*boost::unit_test::label("constructor")

BOOST_AUTO_TEST_CASE(test_extents_ctor)
{
	using namespace boost::numeric;
	using extents = ublas::basic_extents<unsigned>;

	auto e0 = extents{};
	BOOST_CHECK( e0.empty());
	BOOST_CHECK_EQUAL ( e0.size(),0);

	auto e1 = extents{1,1};
	BOOST_CHECK(!e1.empty());
	BOOST_CHECK_EQUAL ( e1.size(),2);

	auto e2 = extents{1,2};
	BOOST_CHECK(!e2.empty());
	BOOST_CHECK_EQUAL ( e2.size(),2);

	auto e3 = extents{2,1};
	BOOST_CHECK (!e3.empty());
	BOOST_CHECK_EQUAL  ( e3.size(),2);

	auto e4 = extents{2,3};
	BOOST_CHECK(!e4.empty());
	BOOST_CHECK_EQUAL ( e4.size(),2);

	auto e5 = extents{2,3,1};
	BOOST_CHECK (!e5.empty());
	BOOST_CHECK_EQUAL  ( e5.size(),3);

	auto e6 = extents{1,2,3}; // 6
	BOOST_CHECK(!e6.empty());
	BOOST_CHECK_EQUAL ( e6.size(),3);

	auto e7 = extents{4,2,3};  // 7
	BOOST_CHECK(!e7.empty());
	BOOST_CHECK_EQUAL ( e7.size(),3);

	BOOST_CHECK_THROW( extents({1,0}), std::length_error );
	BOOST_CHECK_THROW( extents({0}  ), std::length_error );
	BOOST_CHECK_THROW( extents({3}  ), std::length_error );
	BOOST_CHECK_THROW( extents({0,1}), std::length_error );
}

struct fixture {
	using extents_type = boost::numeric::ublas::basic_extents<unsigned>;
	fixture() : extents{
	              extents_type{},            // 0

	              extents_type{1,1},         // 1
	              extents_type{1,2},         // 2
	              extents_type{2,1},         // 3

	              extents_type{2,3},         // 4
	              extents_type{2,3,1},       // 5
	              extents_type{1,2,3},       // 6
	              extents_type{1,1,2,3},     // 7
	              extents_type{1,2,3,1,1},   // 8

	              extents_type{4,2,3},       // 9
	              extents_type{4,2,1,3},     // 10
	              extents_type{4,2,1,3,1},   // 11
	              extents_type{1,4,2,1,3,1}, // 12
}  // 13
	{}
	std::vector<extents_type> extents;
};

BOOST_FIXTURE_TEST_CASE(test_extents_access, fixture, *boost::unit_test::label("extents") *boost::unit_test::label("access"))
{
	using namespace boost::numeric;

	BOOST_REQUIRE_EQUAL(extents.size(),13);

	BOOST_CHECK_EQUAL  (extents[ 0].size(), 0);
	BOOST_CHECK (extents[ 0].empty()  );

	BOOST_REQUIRE_EQUAL(extents[ 1].size(), 2);
	BOOST_REQUIRE_EQUAL(extents[ 2].size(), 2);
	BOOST_REQUIRE_EQUAL(extents[ 3].size(), 2);
	BOOST_REQUIRE_EQUAL(extents[ 4].size(), 2);
	BOOST_REQUIRE_EQUAL(extents[ 5].size(), 3);
	BOOST_REQUIRE_EQUAL(extents[ 6].size(), 3);
	BOOST_REQUIRE_EQUAL(extents[ 7].size(), 4);
	BOOST_REQUIRE_EQUAL(extents[ 8].size(), 5);
	BOOST_REQUIRE_EQUAL(extents[ 9].size(), 3);
	BOOST_REQUIRE_EQUAL(extents[10].size(), 4);
	BOOST_REQUIRE_EQUAL(extents[11].size(), 5);
	BOOST_REQUIRE_EQUAL(extents[12].size(), 6);

	BOOST_CHECK_EQUAL(extents[1][0],1);
	BOOST_CHECK_EQUAL(extents[1][1],1);

	BOOST_CHECK_EQUAL(extents[2][0],1);
	BOOST_CHECK_EQUAL(extents[2][1],2);

	BOOST_CHECK_EQUAL(extents[3][0],2);
	BOOST_CHECK_EQUAL(extents[3][1],1);

	BOOST_CHECK_EQUAL(extents[4][0],2);
	BOOST_CHECK_EQUAL(extents[4][1],3);

	BOOST_CHECK_EQUAL(extents[5][0],2);
	BOOST_CHECK_EQUAL(extents[5][1],3);
	BOOST_CHECK_EQUAL(extents[5][2],1);

	BOOST_CHECK_EQUAL(extents[6][0],1);
	BOOST_CHECK_EQUAL(extents[6][1],2);
	BOOST_CHECK_EQUAL(extents[6][2],3);

	BOOST_CHECK_EQUAL(extents[7][0],1);
	BOOST_CHECK_EQUAL(extents[7][1],1);
	BOOST_CHECK_EQUAL(extents[7][2],2);
	BOOST_CHECK_EQUAL(extents[7][3],3);

	BOOST_CHECK_EQUAL(extents[8][0],1);
	BOOST_CHECK_EQUAL(extents[8][1],2);
	BOOST_CHECK_EQUAL(extents[8][2],3);
	BOOST_CHECK_EQUAL(extents[8][3],1);
	BOOST_CHECK_EQUAL(extents[8][4],1);

	BOOST_CHECK_EQUAL(extents[9][0],4);
	BOOST_CHECK_EQUAL(extents[9][1],2);
	BOOST_CHECK_EQUAL(extents[9][2],3);

	BOOST_CHECK_EQUAL(extents[10][0],4);
	BOOST_CHECK_EQUAL(extents[10][1],2);
	BOOST_CHECK_EQUAL(extents[10][2],1);
	BOOST_CHECK_EQUAL(extents[10][3],3);

	BOOST_CHECK_EQUAL(extents[11][0],4);
	BOOST_CHECK_EQUAL(extents[11][1],2);
	BOOST_CHECK_EQUAL(extents[11][2],1);
	BOOST_CHECK_EQUAL(extents[11][3],3);
	BOOST_CHECK_EQUAL(extents[11][4],1);

	BOOST_CHECK_EQUAL(extents[12][0],1);
	BOOST_CHECK_EQUAL(extents[12][1],4);
	BOOST_CHECK_EQUAL(extents[12][2],2);
	BOOST_CHECK_EQUAL(extents[12][3],1);
	BOOST_CHECK_EQUAL(extents[12][4],3);
	BOOST_CHECK_EQUAL(extents[12][5],1);
}

BOOST_FIXTURE_TEST_CASE(test_extents_copy_ctor, fixture, *boost::unit_test::label("extents") *boost::unit_test::label("copy_ctor"))
{
	BOOST_REQUIRE_EQUAL(extents.size(),13);

	auto e0  = extents[ 0]; // {}
	auto e1  = extents[ 1]; // {1,1}
	auto e2  = extents[ 2]; // {1,2}
	auto e3  = extents[ 3]; // {2,1}
	auto e4  = extents[ 4]; // {2,3}
	auto e5  = extents[ 5]; // {2,3,1}
	auto e6  = extents[ 6]; // {1,2,3}
	auto e7  = extents[ 7]; // {1,1,2,3}
	auto e8  = extents[ 8]; // {1,2,3,1,1}
	auto e9  = extents[ 9]; // {4,2,3}
	auto e10 = extents[10]; // {4,2,1,3}
	auto e11 = extents[11]; // {4,2,1,3,1}
	auto e12 = extents[12]; // {1,4,2,1,3,1}

	BOOST_CHECK_EQUAL  (e0.size(), 0);
	BOOST_CHECK (e0.empty()  );

	BOOST_REQUIRE_EQUAL(e1 .size(), 2);
	BOOST_REQUIRE_EQUAL(e2 .size(), 2);
	BOOST_REQUIRE_EQUAL(e3 .size(), 2);
	BOOST_REQUIRE_EQUAL(e4 .size(), 2);
	BOOST_REQUIRE_EQUAL(e5 .size(), 3);
	BOOST_REQUIRE_EQUAL(e6 .size(), 3);
	BOOST_REQUIRE_EQUAL(e7 .size(), 4);
	BOOST_REQUIRE_EQUAL(e8 .size(), 5);
	BOOST_REQUIRE_EQUAL(e9 .size(), 3);
	BOOST_REQUIRE_EQUAL(e10.size(), 4);
	BOOST_REQUIRE_EQUAL(e11.size(), 5);
	BOOST_REQUIRE_EQUAL(e12.size(), 6);

	BOOST_CHECK_EQUAL(e1[0],1);
	BOOST_CHECK_EQUAL(e1[1],1);

	BOOST_CHECK_EQUAL(e2[0],1);
	BOOST_CHECK_EQUAL(e2[1],2);

	BOOST_CHECK_EQUAL(e3[0],2);
	BOOST_CHECK_EQUAL(e3[1],1);

	BOOST_CHECK_EQUAL(e4[0],2);
	BOOST_CHECK_EQUAL(e4[1],3);

	BOOST_CHECK_EQUAL(e5[0],2);
	BOOST_CHECK_EQUAL(e5[1],3);
	BOOST_CHECK_EQUAL(e5[2],1);

	BOOST_CHECK_EQUAL(e6[0],1);
	BOOST_CHECK_EQUAL(e6[1],2);
	BOOST_CHECK_EQUAL(e6[2],3);

	BOOST_CHECK_EQUAL(e7[0],1);
	BOOST_CHECK_EQUAL(e7[1],1);
	BOOST_CHECK_EQUAL(e7[2],2);
	BOOST_CHECK_EQUAL(e7[3],3);

	BOOST_CHECK_EQUAL(e8[0],1);
	BOOST_CHECK_EQUAL(e8[1],2);
	BOOST_CHECK_EQUAL(e8[2],3);
	BOOST_CHECK_EQUAL(e8[3],1);
	BOOST_CHECK_EQUAL(e8[4],1);

	BOOST_CHECK_EQUAL(e9[0],4);
	BOOST_CHECK_EQUAL(e9[1],2);
	BOOST_CHECK_EQUAL(e9[2],3);

	BOOST_CHECK_EQUAL(e10[0],4);
	BOOST_CHECK_EQUAL(e10[1],2);
	BOOST_CHECK_EQUAL(e10[2],1);
	BOOST_CHECK_EQUAL(e10[3],3);

	BOOST_CHECK_EQUAL(e11[0],4);
	BOOST_CHECK_EQUAL(e11[1],2);
	BOOST_CHECK_EQUAL(e11[2],1);
	BOOST_CHECK_EQUAL(e11[3],3);
	BOOST_CHECK_EQUAL(e11[4],1);

	BOOST_CHECK_EQUAL(e12[0],1);
	BOOST_CHECK_EQUAL(e12[1],4);
	BOOST_CHECK_EQUAL(e12[2],2);
	BOOST_CHECK_EQUAL(e12[3],1);
	BOOST_CHECK_EQUAL(e12[4],3);
	BOOST_CHECK_EQUAL(e12[5],1);

}

BOOST_FIXTURE_TEST_CASE(test_extents_is, fixture, *boost::unit_test::label("extents") *boost::unit_test::label("query"))
{
	BOOST_REQUIRE_EQUAL(extents.size(),13);

	auto e0  = extents[ 0]; // {}
	auto e1  = extents[ 1]; // {1,1}
	auto e2  = extents[ 2]; // {1,2}
	auto e3  = extents[ 3]; // {2,1}
	auto e4  = extents[ 4]; // {2,3}
	auto e5  = extents[ 5]; // {2,3,1}
	auto e6  = extents[ 6]; // {1,2,3}
	auto e7  = extents[ 7]; // {1,1,2,3}
	auto e8  = extents[ 8]; // {1,2,3,1,1}
	auto e9  = extents[ 9]; // {4,2,3}
	auto e10 = extents[10]; // {4,2,1,3}
	auto e11 = extents[11]; // {4,2,1,3,1}
	auto e12 = extents[12]; // {1,4,2,1,3,1}

	BOOST_CHECK(   e0.empty    ());
	BOOST_CHECK( ! e0.is_scalar());
	BOOST_CHECK( ! e0.is_vector());
	BOOST_CHECK( ! e0.is_matrix());
	BOOST_CHECK( ! e0.is_tensor());

	BOOST_CHECK( ! e1.empty    () );
	BOOST_CHECK(   e1.is_scalar() );
	BOOST_CHECK( ! e1.is_vector() );
	BOOST_CHECK( ! e1.is_matrix() );
	BOOST_CHECK( ! e1.is_tensor() );

	BOOST_CHECK( ! e2.empty    () );
	BOOST_CHECK( ! e2.is_scalar() );
	BOOST_CHECK(   e2.is_vector() );
	BOOST_CHECK( ! e2.is_matrix() );
	BOOST_CHECK( ! e2.is_tensor() );

	BOOST_CHECK( ! e3.empty    () );
	BOOST_CHECK( ! e3.is_scalar() );
	BOOST_CHECK(   e3.is_vector() );
	BOOST_CHECK( ! e3.is_matrix() );
	BOOST_CHECK( ! e3.is_tensor() );

	BOOST_CHECK( ! e4.empty    () );
	BOOST_CHECK( ! e4.is_scalar() );
	BOOST_CHECK( ! e4.is_vector() );
	BOOST_CHECK(   e4.is_matrix() );
	BOOST_CHECK( ! e4.is_tensor() );

	BOOST_CHECK( ! e5.empty    () );
	BOOST_CHECK( ! e5.is_scalar() );
	BOOST_CHECK( ! e5.is_vector() );
	BOOST_CHECK(   e5.is_matrix() );
	BOOST_CHECK( ! e5.is_tensor() );

	BOOST_CHECK( ! e6.empty    () );
	BOOST_CHECK( ! e6.is_scalar() );
	BOOST_CHECK( ! e6.is_vector() );
	BOOST_CHECK( ! e6.is_matrix() );
	BOOST_CHECK(   e6.is_tensor() );

	BOOST_CHECK( ! e7.empty    () );
	BOOST_CHECK( ! e7.is_scalar() );
	BOOST_CHECK( ! e7.is_vector() );
	BOOST_CHECK( ! e7.is_matrix() );
	BOOST_CHECK(   e7.is_tensor() );

	BOOST_CHECK( ! e8.empty    () );
	BOOST_CHECK( ! e8.is_scalar() );
	BOOST_CHECK( ! e8.is_vector() );
	BOOST_CHECK( ! e8.is_matrix() );
	BOOST_CHECK(   e8.is_tensor() );

	BOOST_CHECK( ! e9.empty    () );
	BOOST_CHECK( ! e9.is_scalar() );
	BOOST_CHECK( ! e9.is_vector() );
	BOOST_CHECK( ! e9.is_matrix() );
	BOOST_CHECK(   e9.is_tensor() );

	BOOST_CHECK( ! e10.empty    () );
	BOOST_CHECK( ! e10.is_scalar() );
	BOOST_CHECK( ! e10.is_vector() );
	BOOST_CHECK( ! e10.is_matrix() );
	BOOST_CHECK(   e10.is_tensor() );

	BOOST_CHECK( ! e11.empty    () );
	BOOST_CHECK( ! e11.is_scalar() );
	BOOST_CHECK( ! e11.is_vector() );
	BOOST_CHECK( ! e11.is_matrix() );
	BOOST_CHECK(   e11.is_tensor() );

	BOOST_CHECK( ! e12.empty    () );
	BOOST_CHECK( ! e12.is_scalar() );
	BOOST_CHECK( ! e12.is_vector() );
	BOOST_CHECK( ! e12.is_matrix() );
	BOOST_CHECK(   e12.is_tensor() );
}

BOOST_FIXTURE_TEST_CASE(test_extents_squeeze, fixture, *boost::unit_test::label("extents") *boost::unit_test::label("squeeze"))
{
	BOOST_REQUIRE_EQUAL(extents.size(),13);

	auto e0  = extents[ 0].squeeze(); // {}
	auto e1  = extents[ 1].squeeze(); // {1,1}
	auto e2  = extents[ 2].squeeze(); // {1,2}
	auto e3  = extents[ 3].squeeze(); // {2,1}

	auto e4  = extents[ 4].squeeze(); // {2,3}
	auto e5  = extents[ 5].squeeze(); // {2,3}
	auto e6  = extents[ 6].squeeze(); // {2,3}
	auto e7  = extents[ 7].squeeze(); // {2,3}
	auto e8  = extents[ 8].squeeze(); // {2,3}

	auto e9  = extents[ 9].squeeze(); // {4,2,3}
	auto e10 = extents[10].squeeze(); // {4,2,3}
	auto e11 = extents[11].squeeze(); // {4,2,3}
	auto e12 = extents[12].squeeze(); // {4,2,3}

	BOOST_CHECK( (e0  == extents_type{}   ) );
	BOOST_CHECK( (e1  == extents_type{1,1}) );
	BOOST_CHECK( (e2  == extents_type{1,2}) );
	BOOST_CHECK( (e3  == extents_type{2,1}) );

	BOOST_CHECK( (e4  == extents_type{2,3}) );
	BOOST_CHECK( (e5  == extents_type{2,3}) );
	BOOST_CHECK( (e6  == extents_type{2,3}) );
	BOOST_CHECK( (e7  == extents_type{2,3}) );
	BOOST_CHECK( (e8  == extents_type{2,3}) );

	BOOST_CHECK( (e9  == extents_type{4,2,3}) );
	BOOST_CHECK( (e10 == extents_type{4,2,3}) );
	BOOST_CHECK( (e11 == extents_type{4,2,3}) );
	BOOST_CHECK( (e12 == extents_type{4,2,3}) );

}

BOOST_FIXTURE_TEST_CASE(test_extents_valid, fixture, *boost::unit_test::label("extents") *boost::unit_test::label("valid"))
{

	using namespace boost::numeric;

	BOOST_REQUIRE_EQUAL(extents.size(),13);

	for(auto const& e : extents){
		if(e.empty())
			BOOST_CHECK_EQUAL(e.valid(),false);
		else
			BOOST_CHECK_EQUAL(e.valid(), true );
	}

	BOOST_CHECK_EQUAL( extents_type{}.valid() , false  );

	BOOST_CHECK_THROW( ublas::basic_extents<unsigned>({0,1}), std::length_error  );
	BOOST_CHECK_THROW( ublas::basic_extents<unsigned>({1,0,1}), std::length_error  );

}

BOOST_FIXTURE_TEST_CASE(test_extents_product, fixture, *boost::unit_test::label("extents") *boost::unit_test::label("product"))
{

	auto e0  = extents[ 0].product(); // {}
	auto e1  = extents[ 1].product(); // {1,1}
	auto e2  = extents[ 2].product(); // {1,2}
	auto e3  = extents[ 3].product(); // {2,1}
	auto e4  = extents[ 4].product(); // {2,3}
	auto e5  = extents[ 5].product(); // {2,3,1}
	auto e6  = extents[ 6].product(); // {1,2,3}
	auto e7  = extents[ 7].product(); // {1,1,2,3}
	auto e8  = extents[ 8].product(); // {1,2,3,1,1}
	auto e9  = extents[ 9].product(); // {4,2,3}
	auto e10 = extents[10].product(); // {4,2,1,3}
	auto e11 = extents[11].product(); // {4,2,1,3,1}
	auto e12 = extents[12].product(); // {1,4,2,1,3,1}

	BOOST_CHECK_EQUAL( e0 ,  0 );
	BOOST_CHECK_EQUAL( e1 ,  1 );
	BOOST_CHECK_EQUAL( e2 ,  2 );
	BOOST_CHECK_EQUAL( e3 ,  2 );
	BOOST_CHECK_EQUAL( e4 ,  6 );
	BOOST_CHECK_EQUAL( e5 ,  6 );
	BOOST_CHECK_EQUAL( e6 ,  6 );
	BOOST_CHECK_EQUAL( e7 ,  6 );
	BOOST_CHECK_EQUAL( e8 ,  6 );
	BOOST_CHECK_EQUAL( e9 , 24 );
	BOOST_CHECK_EQUAL( e10, 24 );
	BOOST_CHECK_EQUAL( e11, 24 );
	BOOST_CHECK_EQUAL( e12, 24 );

}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: cpp-pm/boost

max_issues_repo_name: cpp-pm/boost

max_forks_repo_name: cpp-pm/boost


text:
//
//  OutputEstimate.cpp
//
//
//  Created by Tobey Carman on 6/22/17.
//
//

#include <map>
#include <boost/algorithm/string.hpp>

#include "../include/OutputEstimate.h"
#include "../include/TEMUtilityFunctions.h"

#include "../include/TEMLogger.h"

extern src::severity_logger< severity_level > glg;

OutputEstimate::OutputEstimate(const ModelData& md, bool calmode) {

  stage_output_estimates = {
      // Table of coefficients for bytes per year of run-time for
      // each stage and different types of json output (archive, daily, etc).
      {StageOutputEstimate("pr", md.pr_yrs, 22000,  41000,  200000,  20000)},
      {StageOutputEstimate("eq", md.eq_yrs, 56000,  41000,  240000,  24000)},
      {StageOutputEstimate("sp", md.sp_yrs, 15000,  36000,  199000,  16000)},
      {StageOutputEstimate("tr", md.tr_yrs, 15000,  36000,  199000,  16000)},
      {StageOutputEstimate("sc", md.sc_yrs, 15000,  36000,  199000,  16000)},
  };

  // Open the run mask (spatial mask) and count all the non-zero cells.
  std::vector< std::vector<int> > run_mask = temutil::read_run_mask(md.runmask_file);

  this->active_cells = 0;

  // Use a few type definitions to save some typing.
  typedef std::vector<int> vec;
  typedef std::vector<vec> vec2D;

  vec2D::const_iterator row;
  vec::const_iterator col;
  for (row = run_mask.begin(); row != run_mask.end() ; ++row) {
    for (col = row->begin(); col != row->end(); ++col) {
      bool mask_value = *col;
      if (mask_value) {this->active_cells++;}
    }
  }

  BOOST_LOG_SEV(glg, debug) << "Number of active cells in run-mask: " << this->active_cells;

  std::vector<StageOutputEstimate>::iterator itr;
  for (itr = stage_output_estimates.begin(); itr != stage_output_estimates.end(); itr++){

    BOOST_LOG_SEV(glg, debug) << "Estimating output for stage: " << itr->name;
    // handle all the calibration/json stuff
    if (calmode) {
      // cal mode means at least yearly and daily
      BOOST_LOG_SEV(glg, debug) << "  Estimating JSON CALIBRATION output";
      itr->json_out.yearly = itr->runyears * itr->json_out.jcoef_yearly;
      itr->json_out.daily = itr->runyears * itr->json_out.jcoef_daily;

      // setting in config file
      if (md.output_monthly) {
        itr->json_out.monthly = itr->runyears * itr->json_out.jcoef_monthly;
      } else {
        itr->json_out.monthly = 0;
      }
      // could be an overestimate if user does not have monthly enabled too?
      if (md.tar_caljson) {
        itr->json_out.archive = itr->runyears * itr->json_out.jcoef_archive;
      } else {
        itr->json_out.archive = 0;
      }
    }

    // Handle the NetCDF stuff...
    double D_est = 0; double M_est = 0; double Y_est = 0;

    // yearly
    BOOST_LOG_SEV(glg, debug) << "  Estimating YEARLY NC output for stage: " << itr->name;
    std::map<std::string, OutputSpec>::const_iterator map_itr;
    for(map_itr = md.yearly_netcdf_outputs.begin(); map_itr != md.yearly_netcdf_outputs.end(); ++map_itr ){

      double output_estimate = 8;
      OutputSpec os = map_itr->second;

      (os.pft) ? (output_estimate *= NUM_PFT) : output_estimate *= 1;
      (os.compartment) ? (output_estimate *= NUM_PFT_PART) : output_estimate *= 1;
      (os.layer) ? (output_estimate *= MAX_SOI_LAY) : output_estimate *= 1;
      (os.yearly) ? (output_estimate *= (1 * itr->runyears)) : output_estimate *= 1;

      Y_est += output_estimate;
    }
    map_itr = md.yearly_netcdf_outputs.end();

    // monthly
    BOOST_LOG_SEV(glg, debug) << "  Estimating MONTHLY NC output for stage: " << itr->name;
    for(map_itr = md.monthly_netcdf_outputs.begin(); map_itr != md.monthly_netcdf_outputs.end(); ++map_itr ){

      double output_estimate = 8;
      OutputSpec os = map_itr->second;

      (os.pft) ? (output_estimate *= NUM_PFT) : output_estimate *= 1;
      (os.compartment) ? (output_estimate *= NUM_PFT_PART) : output_estimate *= 1;
      (os.layer) ? (output_estimate *= MAX_SOI_LAY) : output_estimate *= 1;
      (os.monthly) ? (output_estimate *= (12 * itr->runyears)) : output_estimate *= 1;

      M_est += output_estimate;
    }
    map_itr = md.monthly_netcdf_outputs.end();

    // daily
    BOOST_LOG_SEV(glg, debug) << "  Estimating DAILY NC output for stage: " << itr->name;
    for(map_itr = md.daily_netcdf_outputs.begin(); map_itr != md.daily_netcdf_outputs.end(); ++map_itr ){

      double output_estimate = 8;
      OutputSpec os = map_itr->second;

      (os.pft) ? (output_estimate *= NUM_PFT) : output_estimate *= 1;
      (os.compartment) ? (output_estimate *= NUM_PFT_PART) : output_estimate *= 1;
      (os.layer) ? (output_estimate *= MAX_SOI_LAY) : output_estimate *= 1;
      (os.daily) ? (output_estimate *= (365 * itr->runyears)) : output_estimate *= 1;

      D_est += output_estimate;
    }
    map_itr = md.daily_netcdf_outputs.end();

    itr->nc_out.yearly = Y_est;
    itr->nc_out.monthly = M_est;
    itr->nc_out.daily = D_est;

  }

}

std::string OutputEstimate::estimate_as_table(){

  std::stringstream ss;
  std::vector<StageOutputEstimate>::iterator itr;

  ss << "-- calibration json output data volume estimates: " << hsize(json_total()) << std::endl;
  ss << std::setw(10) << " "
     << std::setw(10) << "run years"
     << std::setw(10) << "archive"
     << std::setw(10) << "daily"
     << std::setw(10) << "monthly"
     << std::setw(10) << "yearly"
     << std::endl;
  for (itr = stage_output_estimates.begin(); itr != stage_output_estimates.end(); itr++) {
    ss << std::setw(10) << (*itr).name
       << std::setw(10) << (*itr).runyears
       << std::setw(10) << hsize((*itr).json_out.archive)
       << std::setw(10) << hsize((*itr).json_out.daily)
       << std::setw(10) << hsize((*itr).json_out.monthly)
       << std::setw(10) << hsize((*itr).json_out.yearly)
       << std::endl;
  }
  itr = stage_output_estimates.end();
  ss << std::endl;

  ss << "-- netcdf output data volume estimate: " << hsize(netcdf_total()) << std::endl;
  ss << std::setw(10) << " "
     << std::setw(10) << "run years"
     << std::setw(10) << "daily"
     << std::setw(10) << "monthly"
     << std::setw(10) << "yearly"
     << std::endl;

  for (itr = stage_output_estimates.begin(); itr != stage_output_estimates.end(); itr++) {
    ss << std::setw(10) << (*itr).name;
    ss << std::setw(10) << (*itr).runyears;
    ss << std::setw(10) << hsize((*itr).nc_out.daily);
    ss << std::setw(10) << hsize((*itr).nc_out.monthly);
    ss << std::setw(10) << hsize((*itr).nc_out.yearly);
    ss << std::endl;
  }
  itr = stage_output_estimates.end();
  ss << std::endl;

  ss << "Cell Total: " << hsize(this->cell_total());
  ss << std::endl;
  ss << "All cells: " << hsize(this->all_cells_total());

  return ss.str();

}

double OutputEstimate::netcdf_total() {
  double t = 0;
  std::vector<StageOutputEstimate>::iterator itr;
  for (itr = stage_output_estimates.begin(); itr != stage_output_estimates.end(); itr++) {
    t += (*itr).nc_out.daily;
    t += (*itr).nc_out.monthly;
    t += (*itr).nc_out.yearly;
  }
  return t;
}

double OutputEstimate::json_total() {
  // This will probably over-estimate, as the yearly/monthly/daily outputs
  // are deleted for each stage. Maybe should find the stage with the max
  // runyears and use that for the yearly/monthly/daily estimates.
  double t = 0;
  std::vector<StageOutputEstimate>::iterator itr;
  for (itr = stage_output_estimates.begin(); itr != stage_output_estimates.end(); itr++) {
    t += (*itr).json_out.archive;
    t += (*itr).json_out.daily;
    t += (*itr).json_out.monthly;
    t += (*itr).json_out.yearly;
  }
  return t;
}

double OutputEstimate::cell_total() {
  double t = 0;
    t += json_total();
    t += netcdf_total();
  return t;
}

double OutputEstimate::all_cells_total() {
  return active_cells * (json_total() + netcdf_total());
}

/** Returns a 'human readable' size string with SI suffix */
std::string OutputEstimate::hsize(double size) {
  int i = 0;
  const std::string units[] = {"B","kB","MB","GB","TB","PB","EB","ZB","YB"};
  while (size > 1024) {
    size /= 1024;
    i++;
  }
  std::stringstream ss;
  ss.precision(0);
  (size < 0.5) ? size = 0 : size=size;
  ss << fixed << size << " " << units[i];
  std::string size_string = ss.str();
  return size_string;
}

/** Given a string like "1.5 MB" should return a double in bytes.
*
* Function is reasonably tolerant to strange input string formatting as
* all leading and trailing whitespace should be stripped before conversion
* is attempted. The function will exit with an error message if the units
* are invalid, or if the string to number conversion fails.
*/
double OutputEstimate::hsize2bytes(std::string sizestr) {

  std::vector<std::string> units = boost::assign::list_of("B")("kB")("MB")("GB")("TB")("PB")("EB")("ZB")("YB");

  // strip any whitespace....
  boost::algorithm::trim(sizestr);

  // split the string up into the numeric portion and the units suffix
  std::string hrunit = sizestr.substr(sizestr.size()-2, std::string::npos);
  std::string numeric_part = sizestr.substr(0, sizestr.size()-2);

  // strip any remaining whitespace...
  boost::algorithm::trim(numeric_part);

  bool found = (std::find(units.begin(), units.end(), hrunit) != units.end());
  if ( !found ) {
    BOOST_LOG_SEV(glg, fatal) << "INVALID UNIT SPECIFICATION!: " << hrunit;
    exit(-1);
  }

  double size;
  try {
    size = boost::lexical_cast<double>(numeric_part);
  } catch (boost::bad_lexical_cast &) {
    BOOST_LOG_SEV(glg, fatal) << "Problem casting '" << numeric_part << "' to double!";
    exit(-1);
  }

  int i = 0;
  while ( (!(hrunit.compare(units[i]))) == 0 && (i < units.size()) )  {
    size *= 1024;
    i++;
  }
  return size; // in bytes
}

// ideas for  API functions
//  oe.per_grid_cell()
//  oe.per_year()
//  oe.print_table()

max_stars_repo_name: valeriabriones/dvm-dos-tem

max_issues_repo_name: valeriabriones/dvm-dos-tem

max_forks_repo_name: valeriabriones/dvm-dos-tem