text:
#ifndef BOOST_QVM_QUAT_HPP_INCLUDED
#define BOOST_QVM_QUAT_HPP_INCLUDED

/// Copyright (c) 2008-2021 Emil Dotchevski and Reverge Studios, Inc.

/// 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/qvm/detail/quat_assign.hpp>
#include <boost/qvm/assert.hpp>
#include <boost/qvm/static_assert.hpp>

namespace boost { namespace qvm {

template <class T>
struct
quat
    {
    T a[4];
    template <class R>
    operator R() const
        {
        R r;
        assign(r,*this);
        return r;
        }
    };

template <class Q>
struct quat_traits;

template <class T>
struct
quat_traits< quat<T> >
    {
    typedef quat<T> this_quaternion;
    typedef T scalar_type;

    template <int I>
    static
    BOOST_QVM_INLINE_CRITICAL
    scalar_type
    read_element( this_quaternion const & x )
        {
        BOOST_QVM_STATIC_ASSERT(I>=0);
        BOOST_QVM_STATIC_ASSERT(I<4);
        return x.a[I];
        }

    template <int I>
    static
    BOOST_QVM_INLINE_CRITICAL
    scalar_type &
    write_element( this_quaternion & x )
        {
        BOOST_QVM_STATIC_ASSERT(I>=0);
        BOOST_QVM_STATIC_ASSERT(I<4);
        return x.a[I];
        }
    };

} }

#endif


text:
// Copyright (C) 2015, Pawel Tomulik <ptomulik@meil.pw.edu.pl>
//
// 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)

// txpl/vm/symbol.hpp

/** // doc: txpl/vm/symbol.hpp {{{
 * \file txpl/vm/symbol.hpp
 * \todo Write documentation
 */ // }}}
#ifndef TXPL_VM_SYMBOL_HPP
#define TXPL_VM_SYMBOL_HPP

#include <txpl/vm/scope_fwd.hpp>
#include <txpl/vm/value.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <boost/blank.hpp>
#include <map>

namespace txpl { namespace vm {
/** // doc: symbol {{{
 * \todo Write documentation
 */ // }}}
template<typename Value = value<> >
using symbol = typename boost::make_recursive_variant<
    boost::blank
  , Value
  , scope_fwd<boost::recursive_variant_>
>::type;
} } // end namespace txpl::vm

#endif /* TXPL_VM_SYMBOL_HPP */
// vim: set expandtab tabstop=2 shiftwidth=2:
// vim: set foldmethod=marker foldcolumn=4:

ext: hpp

max_stars_repo_name: ptomulik/txpl

max_issues_repo_name: ptomulik/txpl

max_forks_repo_name: ptomulik/txpl


text:
// Copyright 2011-2017 Ryan Curtin (http://www.ratml.org/)
// Copyright 2017 National ICT Australia (NICTA)
//
// 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 <armadillo>

#include "catch.hpp"

using namespace arma;

TEST_CASE("fn_mean_spmat_empty_test")
  {
  SpMat<double> m(20, 25);

  SpRow<double> result = mean(m, 0);
  REQUIRE( result.n_nonzero == 0 );
  REQUIRE( result.n_rows == 1 );
  REQUIRE( result.n_cols == 25 );

  SpCol<double> result2 = mean(m, 1);
  REQUIRE( result2.n_nonzero == 0 );
  REQUIRE( result2.n_rows == 20 );
  REQUIRE( result2.n_cols == 1 );

  double r = mean(mean(m));
  REQUIRE( r == Approx(0.0) );

  // Now the same with subviews.
  result = mean(m.submat(2, 2, 11, 16));
  REQUIRE( result.n_nonzero == 0 );
  REQUIRE( result.n_rows == 1 );
  REQUIRE( result.n_cols == 15 );

  result2 = mean(m.submat(2, 2, 11, 16), 1);
  REQUIRE( result2.n_nonzero == 0 );
  REQUIRE( result2.n_rows == 10 );
  REQUIRE( result2.n_cols == 1 );

  r = mean(mean(m.submat(2, 2, 11, 16)));
  REQUIRE( r == Approx(0.0) );

  // And with an operation.
  result = mean(trans(m));
  REQUIRE( result.n_nonzero == 0 );
  REQUIRE( result.n_rows == 1 );
  REQUIRE( result.n_cols == 20 );

  result2 = mean(trans(m), 1);
  REQUIRE( result2.n_nonzero == 0 );
  REQUIRE( result2.n_rows == 25 );
  REQUIRE( result2.n_cols == 1 );

  r = mean(mean(trans(m)));
  REQUIRE( r == Approx(0.0) );
  }

TEST_CASE("fn_mean_spcxmat_empty_test")
  {
  // Now with complex numbers.
  SpMat<std::complex<double> > m(20, 25);
  SpRow<std::complex<double> > result = mean(m, 0);

  REQUIRE( result.n_nonzero == 0 );
  REQUIRE( result.n_rows == 1 );
  REQUIRE( result.n_cols == 25 );

  SpCol<std::complex<double> > result2 = mean(m, 1);

  REQUIRE( result2.n_nonzero == 0 );
  REQUIRE( result2.n_rows == 20 );
  REQUIRE( result2.n_cols == 1 );

  std::complex<double> r = mean(mean(m));

  REQUIRE( real(r) == Approx(0.0) );
  REQUIRE( imag(r) == Approx(0.0) );

  // Now the same with subviews.
  result = mean(m.submat(2, 2, 11, 16));
  REQUIRE( result.n_nonzero == 0 );
  REQUIRE( result.n_rows == 1 );
  REQUIRE( result.n_cols == 15 );

  result2 = mean(m.submat(2, 2, 11, 16), 1);
  REQUIRE( result2.n_nonzero == 0 );
  REQUIRE( result2.n_rows == 10 );
  REQUIRE( result2.n_cols == 1 );

  r = mean(mean(m.submat(2, 2, 11, 16)));
  REQUIRE( real(r) == Approx(0.0) );
  REQUIRE( imag(r) == Approx(0.0) );

  // And with an operation.
  result = mean(trans(m));
  REQUIRE( result.n_nonzero == 0 );
  REQUIRE( result.n_rows == 1 );
  REQUIRE( result.n_cols == 20 );

  result2 = mean(trans(m), 1);
  REQUIRE( result2.n_nonzero == 0 );
  REQUIRE( result2.n_rows == 25 );
  REQUIRE( result2.n_cols == 1 );

  r = mean(mean(trans(m)));
  REQUIRE( real(r) == Approx(0.0) );
  REQUIRE( imag(r) == Approx(0.0) );
  }

TEST_CASE("fn_mean_spmat_test")
  {
  // Create a random matrix and do mean testing on it, with varying levels of
  // nonzero (eventually this becomes a fully dense matrix).
  for (int i = 0; i < 10; ++i)
    {
    SpMat<double> x;
    x.sprandu(50, 75, ((double) (i + 1)) / 10);
    mat d(x);

    SpRow<double> rr = mean(x);
    rowvec drr = mean(d);

    REQUIRE( rr.n_rows == 1 );
    REQUIRE( rr.n_cols == 75 );
    for (uword j = 0; j < 75; ++j)
      REQUIRE( drr[j] == Approx((double) rr[j]) );

    SpCol<double> cr = mean(x, 1);
    vec dcr = mean(d, 1);

    REQUIRE( cr.n_rows == 50 );
    REQUIRE( cr.n_cols == 1 );
    for (uword j = 0; j < 50; ++j)
      REQUIRE( dcr[j] == Approx((double) cr[j]) );

    double dr = mean(mean(x));
    double ddr = mean(mean(d));

    REQUIRE( dr == Approx(ddr) );

    // Now on a subview.
    rr = mean(x.submat(11, 11, 30, 45), 0);
    drr = mean(d.submat(11, 11, 30, 45), 0);

    REQUIRE( rr.n_rows == 1 );
    REQUIRE( rr.n_cols == 35 );
    for (uword j = 0; j < 35; ++j)
      REQUIRE( drr[j] == Approx((double) rr[j]) );

    cr = mean(x.submat(11, 11, 30, 45), 1);
    dcr = mean(d.submat(11, 11, 30, 45), 1);

    REQUIRE( cr.n_rows == 20 );
    REQUIRE( cr.n_cols == 1 );
    for (uword j = 0; j < 20; ++j)
      REQUIRE( dcr[j] == Approx((double) cr[j]) );

    dr = mean(mean(x.submat(11, 11, 30, 45)));
    ddr = mean(mean(d.submat(11, 11, 30, 45)));

    REQUIRE( dr == Approx(ddr) );

    // Now on an SpOp (spop_scalar_times)
    rr = mean(3.0 * x);
    drr = mean(3.0 * d);

    REQUIRE( rr.n_rows == 1 );
    REQUIRE( rr.n_cols == 75 );
    for (uword j = 0; j < 75; ++j)
      REQUIRE( drr[j] == Approx((double) rr[j]) );

    cr = mean(4.5 * x, 1);
    dcr = mean(4.5 * d, 1);

    REQUIRE( cr.n_rows == 50 );
    REQUIRE( cr.n_cols == 1 );
    for (uword j = 0; j < 50; ++j)
      REQUIRE( dcr[j] == Approx((double) cr[j]) );

    dr = mean(mean(1.2 * x));
    ddr = mean(mean(1.2 * d));

    REQUIRE( dr == Approx(ddr) );

    // Now on an SpGlue!
    SpMat<double> y;
    y.sprandu(50, 75, 0.3);
    mat e(y);

    rr = mean(x + y);
    drr = mean(d + e);

    REQUIRE( rr.n_rows == 1 );
    REQUIRE( rr.n_cols == 75 );
    for (uword j = 0; j < 75; ++j)
      REQUIRE( drr[j] == Approx((double) rr[j]) );

    cr = mean(x + y, 1);
    dcr = mean(d + e, 1);

    REQUIRE( cr.n_rows == 50 );
    REQUIRE( cr.n_cols == 1 );
    for (uword j = 0; j < 50; ++j)
      REQUIRE( dcr[j] == Approx((double) cr[j]) );

    dr = mean(mean(x + y));
    ddr = mean(mean(d + e));

    REQUIRE( dr == Approx(ddr) );
    }
  }

TEST_CASE("fn_mean_spcxmat_test")
  {
  // Create a random matrix and do mean testing on it, with varying levels of
  // nonzero (eventually this becomes a fully dense matrix).
  for (int i = 0; i < 10; ++i)
  {
    SpMat<std::complex<double> > x;
    x.sprandu(50, 75, ((double) (i + 1)) / 10);
    cx_mat d(x);

    SpRow<std::complex<double> > rr = mean(x);
    cx_rowvec drr = mean(d);

    REQUIRE( rr.n_rows == 1 );
    REQUIRE( rr.n_cols == 75 );
    for (uword j = 0; j < 75; ++j)
      {
      REQUIRE( real(drr[j]) == Approx(real((std::complex<double>) rr[j])) );
      REQUIRE( imag(drr[j]) == Approx(imag((std::complex<double>) rr[j])) );
      }

    SpCol<std::complex<double> > cr = mean(x, 1);
    cx_vec dcr = mean(d, 1);

    REQUIRE( cr.n_rows == 50 );
    REQUIRE( cr.n_cols == 1 );
    for (uword j = 0; j < 50; ++j)
      {
      REQUIRE( real(dcr[j]) == Approx(real((std::complex<double>) cr[j])) );
      REQUIRE( imag(dcr[j]) == Approx(imag((std::complex<double>) cr[j])) );
      }

    std::complex<double> dr = mean(mean(x));
    std::complex<double> ddr = mean(mean(d));

    REQUIRE( real(dr) == Approx(real(ddr)) );
    REQUIRE( imag(dr) == Approx(imag(ddr)) );

    // Now on a subview.
    rr = mean(x.submat(11, 11, 30, 45), 0);
    drr = mean(d.submat(11, 11, 30, 45), 0);

    REQUIRE( rr.n_rows == 1 );
    REQUIRE( rr.n_cols == 35 );
    for (uword j = 0; j < 35; ++j)
      {
      REQUIRE( real(drr[j]) == Approx(real((std::complex<double>) rr[j])) );
      REQUIRE( imag(drr[j]) == Approx(imag((std::complex<double>) rr[j])) );
      }

    cr = mean(x.submat(11, 11, 30, 45), 1);
    dcr = mean(d.submat(11, 11, 30, 45), 1);

    REQUIRE( cr.n_rows == 20 );
    REQUIRE( cr.n_cols == 1 );
    for (uword j = 0; j < 20; ++j)
      {
      REQUIRE( real(dcr[j]) == Approx(real((std::complex<double>) cr[j])) );
      REQUIRE( imag(dcr[j]) == Approx(imag((std::complex<double>) cr[j])) );
      }

    dr = mean(mean(x.submat(11, 11, 30, 45)));
    ddr = mean(mean(d.submat(11, 11, 30, 45)));

    REQUIRE( real(dr) == Approx(real(ddr)) );
    REQUIRE( imag(dr) == Approx(imag(ddr)) );

    // Now on an SpOp (spop_scalar_times)
    rr = mean(3.0 * x);
    drr = mean(3.0 * d);

    REQUIRE( rr.n_rows == 1 );
    REQUIRE( rr.n_cols == 75 );
    for (uword j = 0; j < 75; ++j)
      {
      REQUIRE( real(drr[j]) == Approx(real((std::complex<double>) rr[j])) );
      REQUIRE( imag(drr[j]) == Approx(imag((std::complex<double>) rr[j])) );
      }

    cr = mean(4.5 * x, 1);
    dcr = mean(4.5 * d, 1);

    REQUIRE( cr.n_rows == 50 );
    REQUIRE( cr.n_cols == 1 );
    for (uword j = 0; j < 50; ++j)
      {
      REQUIRE( real(dcr[j]) == Approx(real((std::complex<double>) cr[j])) );
      REQUIRE( imag(dcr[j]) == Approx(imag((std::complex<double>) cr[j])) );
      }

    dr = mean(mean(1.2 * x));
    ddr = mean(mean(1.2 * d));

    REQUIRE( real(dr) == Approx(real(ddr)) );
    REQUIRE( imag(dr) == Approx(imag(ddr)) );

    // Now on an SpGlue!
    SpMat<std::complex<double> > y;
    y.sprandu(50, 75, 0.3);
    cx_mat e(y);

    rr = mean(x + y);
    drr = mean(d + e);

    REQUIRE( rr.n_rows == 1 );
    REQUIRE( rr.n_cols == 75 );
    for (uword j = 0; j < 75; ++j)
      {
      REQUIRE( real(drr[j]) == Approx(real((std::complex<double>) rr[j])) );
      REQUIRE( imag(drr[j]) == Approx(imag((std::complex<double>) rr[j])) );
      }

    cr = mean(x + y, 1);
    dcr = mean(d + e, 1);

    REQUIRE( cr.n_rows == 50 );
    REQUIRE( cr.n_cols == 1 );
    for (uword j = 0; j < 50; ++j)
      {
      REQUIRE( real(dcr[j]) == Approx(real((std::complex<double>) cr[j])) );
      REQUIRE( imag(dcr[j]) == Approx(imag((std::complex<double>) cr[j])) );
      }

    dr = mean(mean(x + y));
    ddr = mean(mean(d + e));

    REQUIRE( real(dr) == Approx(real(ddr)) );
    REQUIRE( imag(dr) == Approx(imag(ddr)) );
    }
  }

TEST_CASE("fn_mean_sp_vector_test")
  {
  // Test mean() on vectors.
  SpCol<double> c(1000);

  SpCol<double> cr = mean(c, 0);
  REQUIRE( cr.n_rows == 1 );
  REQUIRE( cr.n_cols == 1 );
  REQUIRE( (double) cr[0] == Approx(0.0) );

  cr = mean(c, 1);
  REQUIRE( cr.n_rows == 1000 );
  REQUIRE( cr.n_cols == 1 );
  for (uword i = 0; i < 1000; ++i)
    {
    REQUIRE( (double) cr[i] == Approx(0.0) );
    }

  double ddcr = mean(c);
  REQUIRE( ddcr == Approx(0.0) );

  c.sprandu(1000, 1, 0.3);
  vec dc(c);

  cr = mean(c, 0);
  vec dcr = mean(dc, 0);

  REQUIRE( cr.n_rows == 1 );
  REQUIRE( cr.n_cols == 1 );
  REQUIRE( (double) cr[0] == Approx(dcr[0]) );

  cr = mean(c, 1);
  dcr = mean(dc, 1);

  REQUIRE( cr.n_rows == 1000 );
  REQUIRE( cr.n_cols == 1 );
  for (uword i = 0; i < 1000; ++i)
    {
    REQUIRE( (double) cr[i] == Approx(dcr[i]) );
    }

  ddcr = mean(c);
  double dddr = mean(dc);

  REQUIRE( ddcr == Approx(dddr) );

  SpRow<double> r;
  r.sprandu(1, 1000, 0.3);
  rowvec dr(r);

  SpRow<double> rr = mean(r, 0);
  rowvec drr = mean(dr, 0);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 1000 );
  for (uword i = 0; i < 1000; ++i)
    {
    REQUIRE( (double) rr[i] == Approx(drr[i]) );
    }

  rr = mean(r, 1);
  drr = mean(dr, 1);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 1 );
  REQUIRE( (double) rr[0] == Approx(drr[0]) );

  ddcr = mean(r);
  dddr = mean(dr);

  REQUIRE( ddcr == Approx(dddr) );
  }

TEST_CASE("fn_mean_sp_cx_vector_test")
  {
  // Test mean() on vectors.
  SpCol<std::complex<double> > c(1000);

  SpCol<std::complex<double> > cr = mean(c, 0);
  REQUIRE( cr.n_rows == 1 );
  REQUIRE( cr.n_cols == 1 );
  REQUIRE( real((std::complex<double>) cr[0]) == Approx(0.0) );
  REQUIRE( imag((std::complex<double>) cr[0]) == Approx(0.0) );

  cr = mean(c, 1);
  REQUIRE( cr.n_rows == 1000 );
  REQUIRE( cr.n_cols == 1 );
  for (uword i = 0; i < 1000; ++i)
  {
    REQUIRE( real((std::complex<double>) cr[i]) == Approx(0.0) );
    REQUIRE( imag((std::complex<double>) cr[i]) == Approx(0.0) );
  }

  std::complex<double> ddcr = mean(c);
  REQUIRE( real(ddcr) == Approx(0.0) );
  REQUIRE( imag(ddcr) == Approx(0.0) );

  c.sprandu(1000, 1, 0.3);
  cx_vec dc(c);

  cr = mean(c, 0);
  cx_vec dcr = mean(dc, 0);

  REQUIRE( cr.n_rows == 1 );
  REQUIRE( cr.n_cols == 1 );
  REQUIRE( real((std::complex<double>) cr[0]) == Approx(real(dcr[0])) );
  REQUIRE( imag((std::complex<double>) cr[0]) == Approx(imag(dcr[0])) );

  cr = mean(c, 1);
  dcr = mean(dc, 1);

  REQUIRE( cr.n_rows == 1000 );
  REQUIRE( cr.n_cols == 1 );
  for (uword i = 0; i < 1000; ++i)
    {
    REQUIRE( real((std::complex<double>) cr[i]) == Approx(real(dcr[i])) );
    REQUIRE( imag((std::complex<double>) cr[i]) == Approx(imag(dcr[i])) );
    }

  ddcr = mean(c);
  std::complex<double> dddr = mean(dc);

  REQUIRE( real(ddcr) == Approx(real(dddr)) );
  REQUIRE( imag(ddcr) == Approx(imag(dddr)) );

  SpRow<std::complex<double> > r;
  r.sprandu(1, 1000, 0.3);
  cx_rowvec dr(r);

  SpRow<std::complex<double> > rr = mean(r, 0);
  cx_rowvec drr = mean(dr, 0);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 1000 );
  for (uword i = 0; i < 1000; ++i)
    {
    REQUIRE( real((std::complex<double>) rr[i]) == Approx(real(drr[i])) );
    REQUIRE( imag((std::complex<double>) rr[i]) == Approx(imag(drr[i])) );
    }

  rr = mean(r, 1);
  drr = mean(dr, 1);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 1 );
  REQUIRE( real((std::complex<double>) rr[0]) == Approx(real(drr[0])) );
  REQUIRE( imag((std::complex<double>) rr[0]) == Approx(imag(drr[0])) );

  ddcr = mean(r);
  dddr = mean(dr);

  REQUIRE( real(ddcr) == Approx(real(dddr)) );
  REQUIRE( imag(ddcr) == Approx(imag(dddr)) );
  }

TEST_CASE("fn_mean_robust_sparse_test")
  {
  // Create a sparse matrix with values that will overflow.
  SpMat<double> x;
  x.sprandu(50, 75, 0.1);
  for (SpMat<double>::iterator i = x.begin(); i != x.end(); ++i)
    {
    (*i) *= std::numeric_limits<double>::max();
    }
  mat d(x);

  SpRow<double> rr = mean(x);
  rowvec drr = mean(d);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 75 );
  for (uword j = 0; j < 75; ++j)
    {
    REQUIRE( drr[j] == Approx((double) rr[j]) );
    }

  SpCol<double> cr = mean(x, 1);
  vec dcr = mean(d, 1);

  REQUIRE( cr.n_rows == 50 );
  REQUIRE( cr.n_cols == 1 );
  for (uword j = 0; j < 50; ++j)
    {
    REQUIRE( dcr[j] == Approx((double) cr[j]) );
    }

  double dr = mean(mean(x));
  double ddr = mean(mean(d));

  REQUIRE( dr == Approx(ddr) );

  // Now on a subview.
  rr = mean(x.submat(11, 11, 30, 45), 0);
  drr = mean(d.submat(11, 11, 30, 45), 0);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 35 );
  for (uword j = 0; j < 35; ++j)
    {
    REQUIRE( drr[j] == Approx((double) rr[j]) );
    }

  cr = mean(x.submat(11, 11, 30, 45), 1);
  dcr = mean(d.submat(11, 11, 30, 45), 1);

  REQUIRE( cr.n_rows == 20 );
  REQUIRE( cr.n_cols == 1 );
  for (uword j = 0; j < 20; ++j)
    {
    REQUIRE( dcr[j] == Approx((double) cr[j]) );
    }

  dr = mean(mean(x.submat(11, 11, 30, 45)));
  ddr = mean(mean(d.submat(11, 11, 30, 45)));

  REQUIRE( dr == Approx(ddr) );

  // Now on an SpOp (spop_scalar_times)
  rr = mean(0.4 * x);
  drr = mean(0.4 * d);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 75 );
  for (uword j = 0; j < 75; ++j)
    {
    REQUIRE( drr[j] == Approx((double) rr[j]) );
    }

  cr = mean(0.1 * x, 1);
  dcr = mean(0.1 * d, 1);

  REQUIRE( cr.n_rows == 50 );
  REQUIRE( cr.n_cols == 1 );
  for (uword j = 0; j < 50; ++j)
    {
    REQUIRE( dcr[j] == Approx((double) cr[j]) );
    }

  dr = mean(mean(0.7 * x));
  ddr = mean(mean(0.7 * d));

  REQUIRE( dr == Approx(ddr) );

  // Now on an SpGlue!
  SpMat<double> y;
  y.sprandu(50, 75, 0.3);
  for (SpMat<double>::iterator i = y.begin(); i != y.end(); ++i)
    {
    (*i) *= std::numeric_limits<double>::max();
    }
  mat e(y);

  rr = mean(0.5 * x + 0.5 * y);
  drr = mean(0.5 * d + 0.5 * e);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 75 );
  for (uword j = 0; j < 75; ++j)
    {
    REQUIRE( drr[j] == Approx((double) rr[j]) );
    }

  cr = mean(0.5 * x + 0.5 * y, 1);
  dcr = mean(0.5 * d + 0.5 * e, 1);

  REQUIRE( cr.n_rows == 50 );
  REQUIRE( cr.n_cols == 1 );
  for (uword j = 0; j < 50; ++j)
    {
    REQUIRE( dcr[j] == Approx((double) cr[j]) );
    }

  dr = mean(mean(0.5 * x + 0.5 * y));
  ddr = mean(mean(0.5 * d + 0.5 * e));

  REQUIRE( dr == Approx(ddr) );
  }

TEST_CASE("fn_mean_robust_cx_sparse_test")
  {
  SpMat<std::complex<double> > x;
  x.sprandu(50, 75, 0.3);
  for (SpMat<std::complex<double> >::iterator i = x.begin(); i != x.end(); ++i)
    {
    (*i) *= std::numeric_limits<double>::max();
    }
  cx_mat d(x);

  SpRow<std::complex<double> > rr = mean(x);
  cx_rowvec drr = mean(d);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 75 );
  for (uword j = 0; j < 75; ++j)
    {
    REQUIRE( real(drr[j]) == Approx(real((std::complex<double>) rr[j])) );
    REQUIRE( imag(drr[j]) == Approx(imag((std::complex<double>) rr[j])) );
    }

  SpCol<std::complex<double> > cr = mean(x, 1);
  cx_vec dcr = mean(d, 1);

  REQUIRE( cr.n_rows == 50 );
  REQUIRE( cr.n_cols == 1 );
  for (uword j = 0; j < 50; ++j)
    {
    REQUIRE( real(dcr[j]) == Approx(real((std::complex<double>) cr[j])) );
    REQUIRE( imag(dcr[j]) == Approx(imag((std::complex<double>) cr[j])) );
    }

  std::complex<double> dr = mean(mean(x));
  std::complex<double> ddr = mean(mean(d));

  REQUIRE( real(dr) == Approx(real(ddr)) );
  REQUIRE( imag(dr) == Approx(imag(ddr)) );

  // Now on a subview.
  rr = mean(x.submat(11, 11, 30, 45), 0);
  drr = mean(d.submat(11, 11, 30, 45), 0);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 35 );
  for (uword j = 0; j < 35; ++j)
    {
    REQUIRE( real(drr[j]) == Approx(real((std::complex<double>) rr[j])) );
    REQUIRE( imag(drr[j]) == Approx(imag((std::complex<double>) rr[j])) );
    }

  cr = mean(x.submat(11, 11, 30, 45), 1);
  dcr = mean(d.submat(11, 11, 30, 45), 1);

  REQUIRE( cr.n_rows == 20 );
  REQUIRE( cr.n_cols == 1 );
  for (uword j = 0; j < 20; ++j)
    {
    REQUIRE( real(dcr[j]) == Approx(real((std::complex<double>) cr[j])) );
    REQUIRE( imag(dcr[j]) == Approx(imag((std::complex<double>) cr[j])) );
    }

  dr = mean(mean(x.submat(11, 11, 30, 45)));
  ddr = mean(mean(d.submat(11, 11, 30, 45)));

  REQUIRE( real(dr) == Approx(real(ddr)) );
  REQUIRE( imag(dr) == Approx(imag(ddr)) );

  // Now on an SpOp (spop_scalar_times)
  rr = mean(0.5 * x);
  drr = mean(0.5 * d);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 75 );
  for (uword j = 0; j < 75; ++j)
    {
    REQUIRE( real(drr[j]) == Approx(real((std::complex<double>) rr[j])) );
    REQUIRE( imag(drr[j]) == Approx(imag((std::complex<double>) rr[j])) );
    }

  cr = mean(0.7 * x, 1);
  dcr = mean(0.7 * d, 1);

  REQUIRE( cr.n_rows == 50 );
  REQUIRE( cr.n_cols == 1 );
  for (uword j = 0; j < 50; ++j)
    {
    REQUIRE( real(dcr[j]) == Approx(real((std::complex<double>) cr[j])) );
    REQUIRE( imag(dcr[j]) == Approx(imag((std::complex<double>) cr[j])) );
    }

  dr = mean(mean(0.6 * x));
  ddr = mean(mean(0.6 * d));

  REQUIRE( real(dr) == Approx(real(ddr)) );
  REQUIRE( imag(dr) == Approx(imag(ddr)) );

  // Now on an SpGlue!
  SpMat<std::complex<double> > y;
  y.sprandu(50, 75, 0.3);
  for (SpMat<std::complex<double> >::iterator i = y.begin(); i != y.end(); ++i)
    {
    (*i) *= std::numeric_limits<double>::max();
    }
  cx_mat e(y);

  rr = mean(0.5 * x + 0.5 * y);
  drr = mean(0.5 * d + 0.5 * e);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 75 );
  for (uword j = 0; j < 75; ++j)
    {
    REQUIRE( real(drr[j]) == Approx(real((std::complex<double>) rr[j])) );
    REQUIRE( imag(drr[j]) == Approx(imag((std::complex<double>) rr[j])) );
    }

  cr = mean(0.5 * x + 0.5 * y, 1);
  dcr = mean(0.5 * d + 0.5 * e, 1);

  REQUIRE( cr.n_rows == 50 );
  REQUIRE( cr.n_cols == 1 );
  for (uword j = 0; j < 50; ++j)
    {
    REQUIRE( real(dcr[j]) == Approx(real((std::complex<double>) cr[j])) );
    REQUIRE( imag(dcr[j]) == Approx(imag((std::complex<double>) cr[j])) );
    }

  dr = mean(mean(0.5 * x + 0.5 * y));
  ddr = mean(mean(0.5 * d + 0.5 * e));

  REQUIRE( real(dr) == Approx(real(ddr)) );
  REQUIRE( imag(dr) == Approx(imag(ddr)) );
  }

TEST_CASE("fn_mean_robust_sparse_vector_test")
  {
  // Test mean() on vectors.
  SpCol<double> c(1000);

  SpCol<double> cr;
  double ddcr;

  c.sprandu(1000, 1, 0.3);
  for (SpCol<double>::iterator i = c.begin(); i != c.end(); ++i)
    {
    (*i) *= (std::numeric_limits<double>::max());
    }
  vec dc(c);

  cr = mean(c, 0);
  vec dcr = mean(dc, 0);

  REQUIRE( cr.n_rows == 1 );
  REQUIRE( cr.n_cols == 1 );
  REQUIRE( (double) cr[0] == Approx(dcr[0]) );

  cr = mean(c, 1);
  dcr = mean(dc, 1);

  REQUIRE( cr.n_rows == 1000 );
  REQUIRE( cr.n_cols == 1 );
  for (uword i = 0; i < 1000; ++i)
    {
    REQUIRE( (double) cr[i] == Approx(dcr[i]) );
    }

  ddcr = mean(c);
  double dddr = mean(dc);

  REQUIRE( ddcr == Approx(dddr) );

  SpRow<double> r;
  r.sprandu(1, 1000, 0.3);
  for (SpRow<double>::iterator i = r.begin(); i != r.end(); ++i)
    {
    (*i) *= (std::numeric_limits<double>::max());
    }
  rowvec dr(r);

  SpRow<double> rr = mean(r, 0);
  rowvec drr = mean(dr, 0);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 1000 );
  for (uword i = 0; i < 1000; ++i)
    {
    REQUIRE( (double) rr[i] == Approx(drr[i]) );
    }

  rr = mean(r, 1);
  drr = mean(dr, 1);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 1 );
  REQUIRE( (double) rr[0] == Approx(drr[0]) );

  ddcr = mean(r);
  dddr = mean(dr);

  REQUIRE( ddcr == Approx(dddr) );
  }

TEST_CASE("fn_mean_robust_cx_sparse_vector_test")
  {
  // Test mean() on vectors.
  SpCol<std::complex<double> > c(1000);

  SpCol<std::complex<double> > cr;
  std::complex<double> ddcr;

  c.sprandu(1000, 1, 0.3);
  for (SpCol<std::complex<double> >::iterator i = c.begin(); i != c.end(); ++i)
    {
    (*i) *= (std::numeric_limits<double>::max());
    }
  cx_vec dc(c);

  cr = mean(c, 0);
  cx_vec dcr = mean(dc, 0);

  REQUIRE( cr.n_rows == 1 );
  REQUIRE( cr.n_cols == 1 );
  REQUIRE( real((std::complex<double>) cr[0]) == Approx(real(dcr[0])) );
  REQUIRE( imag((std::complex<double>) cr[0]) == Approx(imag(dcr[0])) );

  cr = mean(c, 1);
  dcr = mean(dc, 1);

  REQUIRE( cr.n_rows == 1000 );
  REQUIRE( cr.n_cols == 1 );
  for (uword i = 0; i < 1000; ++i)
    {
    REQUIRE( real((std::complex<double>) cr[i]) == Approx(real(dcr[i])) );
    REQUIRE( imag((std::complex<double>) cr[i]) == Approx(imag(dcr[i])) );
    }

  ddcr = mean(c);
  std::complex<double> dddr = mean(dc);

  REQUIRE( real(ddcr) == Approx(real(dddr)) );
  REQUIRE( imag(ddcr) == Approx(imag(dddr)) );

  SpRow<std::complex<double> > r;
  r.sprandu(1, 1000, 0.3);
  cx_rowvec dr(r);

  SpRow<std::complex<double> > rr = mean(r, 0);
  cx_rowvec drr = mean(dr, 0);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 1000 );
  for (uword i = 0; i < 1000; ++i)
    {
    REQUIRE( real((std::complex<double>) rr[i]) == Approx(real(drr[i])) );
    REQUIRE( imag((std::complex<double>) rr[i]) == Approx(imag(drr[i])) );
    }

  rr = mean(r, 1);
  drr = mean(dr, 1);

  REQUIRE( rr.n_rows == 1 );
  REQUIRE( rr.n_cols == 1 );
  REQUIRE( real((std::complex<double>) rr[0]) == Approx(real(drr[0])) );
  REQUIRE( imag((std::complex<double>) rr[0]) == Approx(imag(drr[0])) );

  ddcr = mean(r);
  dddr = mean(dr);

  REQUIRE( real(ddcr) == Approx(real(dddr)) );
  REQUIRE( imag(ddcr) == Approx(imag(dddr)) );
  }

TEST_CASE("fn_mean_sparse_alias_test")
  {
  sp_mat s;
  s.sprandu(70, 70, 0.3);
  mat d(s);

  s = mean(s);
  d = mean(d);

  REQUIRE( d.n_rows == s.n_rows );
  REQUIRE( d.n_cols == s.n_cols );
  for (uword i = 0; i < d.n_elem; ++i)
    {
    REQUIRE( d[i] == Approx((double) s[i]) );
    }

  s.sprandu(70, 70, 0.3);
  d = s;

  s = mean(s, 1);
  d = mean(d, 1);
  for (uword i = 0; i < d.n_elem; ++i)
    {
    REQUIRE( d[i] == Approx((double) s[i]) );
    }
  }

ext: cpp


text:
#include "lib/visitor.hpp"

#include "lib/eval.hpp"
#include "lib/function.hpp"
#include "lib/prelude.hpp"
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include <sstream>

using namespace afct;

class Visitor : public IVisitor
{
public:
  std::ostringstream stream;

  void null_value() override
  {
    stream << "null";
  }

  void bool_value(bool value) override
  {
    stream << "bool " << value;
  }

  void double_value(double value) override
  {
    stream << "double " << value;
  }

  void int_value(int64_t value) override
  {
    stream << "int " << value;
  }

  void string_value(std::string const& value) override
  {
    stream << "string " << value;
  }

  void name_value(std::string const& value) override
  {
    stream << "name " << value;
  }

  void lambda_value(Lambda const& value) override
  {
    stream << "lambda";
  }

  void builtin_value(Builtin const& value) override
  {
    stream << "builtin " << value;
  }

  void start_list(size_t size) override
  {
    stream << "start list size " << size;
  }

  void end_list() override
  {
    stream << "end list";
  }

  void start_table(size_t size) override
  {
    stream << "start table size " << size;
  }

  void start_key() override
  {
    stream << "start key";
  }

  void end_key() override
  {
    stream << "end key";
  }

  void end_table() override
  {
    stream << "end table";
  }
};

BOOST_AUTO_TEST_CASE(visitor)
{
  auto code =
      R"((list null true false 2.7 27 "hello" 'lambda (lambda (a) (* a 2)) max '(1 2) '#(1 2)))";
  auto env = Prelude();
  auto expr = Eval(std::string(code), env);

  Visitor visitor;
  Visit(expr, &visitor);
  auto string = visitor.stream.str();

  auto expected = "start list size 11"
                  "null"
                  "bool 1"
                  "bool 0"
                  "double 2.7"
                  "int 27"
                  "string hello"
                  "name lambda"
                  "lambda"
                  "builtin max"
                  "start list size 2"
                  "int 1"
                  "int 2"
                  "end list"
                  "start table size 1"
                  "start key"
                  "int 1"
                  "end key"
                  "int 2"
                  "end table"
                  "end list";
  BOOST_TEST(string == expected);
}

max_stars_repo_name: intephom/artifact

max_issues_repo_name: intephom/artifact

max_forks_repo_name: intephom/artifact


text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2014-2016 The Bitcoin Core developers
// Original code was distributed under the MIT software license.
// Copyright (c) 2014-2017 Coin Sciences Ltd
// MultiChain code distributed under the GPLv3 license, see COPYING file.

#include "script/standard.h"

#include "keys/pubkey.h"
#include "script/script.h"
#include "utils/util.h"
#include "utils/utilstrencodings.h"

#include "multichain/multichain.h"

#include <boost/foreach.hpp>

using namespace std;

typedef vector<unsigned char> valtype;

unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY;

CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {}

const char* GetTxnOutputType(txnouttype t)
{
    switch (t)
    {
    case TX_NONSTANDARD: return "nonstandard";
    case TX_PUBKEY: return "pubkey";
    case TX_PUBKEYHASH: return "pubkeyhash";
    case TX_SCRIPTHASH: return "scripthash";
    case TX_MULTISIG: return "multisig";
    case TX_NULL_DATA: return "nulldata";
    }
    return NULL;
}

/**
 * Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
 */
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
{
    // Templates
    static multimap<txnouttype, CScript> mTemplates;
    if (mTemplates.empty())
    {
        // Standard tx, sender provides pubkey, receiver adds signature
        mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));

        // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
        mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));

        // Sender provides N pubkeys, receivers provides M signatures
        mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));

        // Empty, provably prunable, data-carrying output
        if (GetBoolArg("-datacarrier", true))
            mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));

        mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN));

/* MCHN START*/
        if(mc_gState->m_NetworkParams->IsProtocolMultichain())
        {
            mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_DROPDATA << OP_DROP << OP_RETURN));
            mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_DROPDATA << OP_DROP << OP_RETURN << OP_SMALLDATA));
            mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_DROPDATA << OP_DROP << OP_DROPDATA << OP_DROP << OP_RETURN));
            mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_DROPDATA << OP_DROP << OP_DROPDATA << OP_DROP << OP_RETURN << OP_SMALLDATA));
        }

        mTemplates.insert(make_pair(TX_SCRIPTHASH, CScript() << OP_HASH160 << OP_PUBKEYHASH << OP_EQUAL));
/* MCHN END */
    }

    // Shortcut for pay-to-script-hash, which are more constrained than the other types:
    // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
/* MCHN START - commented out*/
/*
    if (scriptPubKey.IsPayToScriptHash())
    {
        typeRet = TX_SCRIPTHASH;
        vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
        vSolutionsRet.push_back(hashBytes);
        return true;
    }
 */
/* MCHN END */

    // Scan templates
    const CScript& script1 = scriptPubKey;
    BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
    {
/* MCHN START*/
//        const CScript& script2 = tplate.second;
        CScript script2 = CScript(tplate.second);

        for(int d=0;d<=MCP_STD_OP_DROP_COUNT;d++)
        {
/* MCHN END*/

        vSolutionsRet.clear();

        opcodetype opcode1, opcode2;
        vector<unsigned char> vch1, vch2;

        // Compare
        CScript::const_iterator pc1 = script1.begin();
        CScript::const_iterator pc2 = script2.begin();
        while (true)
        {
            if (pc1 == script1.end() && pc2 == script2.end())
            {
                // Found a match
                typeRet = tplate.first;
                if (typeRet == TX_MULTISIG)
                {
                    // Additional checks for TX_MULTISIG:
                    unsigned char m = vSolutionsRet.front()[0];
                    unsigned char n = vSolutionsRet.back()[0];
                    if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
                        return false;
                }
/* MCHN START */
                if(d)
                {
//                    LogPrint("mchnminor","mchn: %d OP_DROP element(s) found in script\n",d);
                }
/* MCHN END */
                return true;
            }
            if (!script1.GetOp(pc1, opcode1, vch1))
                break;
            if (!script2.GetOp(pc2, opcode2, vch2))
                break;

            // Template matching opcodes:
            if (opcode2 == OP_PUBKEYS)
            {
                while (vch1.size() >= 33 && vch1.size() <= 65)
                {
                    vSolutionsRet.push_back(vch1);
                    if (!script1.GetOp(pc1, opcode1, vch1))
                        break;
                }
                if (!script2.GetOp(pc2, opcode2, vch2))
                    break;
                // Normal situation is to fall through
                // to other if/else statements
            }

            if (opcode2 == OP_PUBKEY)
            {
                if (vch1.size() < 33 || vch1.size() > 65)
                    break;
                vSolutionsRet.push_back(vch1);
            }
            else if (opcode2 == OP_PUBKEYHASH)
            {
                if (vch1.size() != sizeof(uint160))
                    break;
                vSolutionsRet.push_back(vch1);
            }
            else if (opcode2 == OP_SMALLINTEGER)
            {   // Single-byte small integer pushed onto vSolutions
                if (opcode1 == OP_0 ||
                    (opcode1 >= OP_1 && opcode1 <= OP_16))
                {
                    char n = (char)CScript::DecodeOP_N(opcode1);
                    vSolutionsRet.push_back(valtype(1, n));
                }
                else
                    break;
            }
            else if (opcode2 == OP_SMALLDATA)
            {
                // small pushdata, <= nMaxDatacarrierBytes
/* MCHN START */
                nMaxDatacarrierBytes=MAX_OP_RETURN_RELAY;
/* MCHN END */
                if (vch1.size() > nMaxDatacarrierBytes)
                    break;
            }
/* MCHN START */
            else if (opcode2 == OP_DROPDATA)
            {
                // small pushdata, <= nMaxDatacarrierBytes
                if (vch1.size() > MAX_SCRIPT_ELEMENT_SIZE)
                    break;
            }
/* MCHN END */
            else if (opcode1 != opcode2 || vch1 != vch2)
            {
                // Others must match exactly
                break;
            }
        }

/* MCHN START */
        script2 << OP_DROPDATA << OP_DROP;
        }
/* MCHN END */
    }

    vSolutionsRet.clear();
    typeRet = TX_NONSTANDARD;
    return false;
}

int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
{
    switch (t)
    {
    case TX_NONSTANDARD:
    case TX_NULL_DATA:
        return -1;
    case TX_PUBKEY:
        return 1;
    case TX_PUBKEYHASH:
        return 2;
    case TX_MULTISIG:
        if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
            return -1;
        return vSolutions[0][0] + 1;
    case TX_SCRIPTHASH:
        return 1; // doesn't include args needed by the script
    }
    return -1;
}

bool IsStandardFull(const CScript& scriptPubKey, txnouttype& whichType)
{
    vector<valtype> vSolutions;
    if (!Solver(scriptPubKey, whichType, vSolutions))
        return false;

    if (whichType == TX_MULTISIG)
    {
        unsigned char m = vSolutions.front()[0];
        unsigned char n = vSolutions.back()[0];
        // Support up to x-of-3 multisig txns as standard
        if (n < 1 || n > 3)
            return false;
        if (m < 1 || m > n)
            return false;
    }

    return whichType != TX_NONSTANDARD;
}

bool ExtractDestinationScriptValid(const CScript& scriptPubKey, CTxDestination& addressRet)
{
/*
    if(mc_gState->m_NetworkParams->IsProtocolMultichain() == 0)
    {
        return ExtractDestination(scriptPubKey, addressRet);
    }
 */
    CScript::const_iterator pc1 = scriptPubKey.begin();
    unsigned char *ptr;
    int size;

    ptr=(unsigned char*)(&pc1[0]);
    size=scriptPubKey.end()-pc1;

    if( (size >= 25) && (ptr[0] == OP_DUP) )                                    // pay-to-pubkeyhash
    {
        addressRet = CKeyID(*(uint160*)(ptr+3));
        return true;
    }

    if( (size >= 23) && (ptr[0] == OP_HASH160) )                                // pay-to-scripthash
    {
        addressRet = CScriptID(*(uint160*)(ptr+2));
        return true;

    }

    if( size >= 35 )                                                            // pay-to-pubkey
    {
        if( (ptr[0] >= 33) && (ptr[0] <= 65) )
        {
            if(size >= 2+ptr[0])
            {
                CPubKey pubKey(ptr+1, ptr+1+ptr[0]);
                if (!pubKey.IsValid())
                    return false;

                addressRet = pubKey.GetID();
                return true;
            }
        }
    }

    return false;
}

bool ExtractDestinationFull(const CScript& scriptPubKey, CTxDestination& addressRet)
{
    vector<valtype> vSolutions;
    txnouttype whichType;
    if (!Solver(scriptPubKey, whichType, vSolutions))
        return false;

    if (whichType == TX_PUBKEY)
    {
        CPubKey pubKey(vSolutions[0]);
        if (!pubKey.IsValid())
            return false;

        addressRet = pubKey.GetID();
        return true;
    }
    else if (whichType == TX_PUBKEYHASH)
    {
        addressRet = CKeyID(uint160(vSolutions[0]));
        return true;
    }
    else if (whichType == TX_SCRIPTHASH)
    {
        addressRet = CScriptID(uint160(vSolutions[0]));
        return true;
    }
    // Multisig txns have more than one address...
    return false;
}

bool ExtractDestinationsFull(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
{
    addressRet.clear();
    typeRet = TX_NONSTANDARD;
    vector<valtype> vSolutions;

/* MCHN START */
    const CScript& scriptPubKeyDestinationOnly=scriptPubKey.RemoveOpDrops();
    if (!Solver(scriptPubKeyDestinationOnly, typeRet, vSolutions))
        return false;
/* MCHN END */
    if (typeRet == TX_NULL_DATA){
        // This is data, not addresses
        return false;
    }

    if (typeRet == TX_MULTISIG)
    {
        nRequiredRet = vSolutions.front()[0];
        for (unsigned int i = 1; i < vSolutions.size()-1; i++)
        {
            CPubKey pubKey(vSolutions[i]);
            if (!pubKey.IsValid())
                continue;

            CTxDestination address = pubKey.GetID();
            addressRet.push_back(address);
        }

        if (addressRet.empty())
            return false;
    }
    else
    {
        nRequiredRet = 1;
        CTxDestination address;
//        if (!ExtractDestination(scriptPubKey, address))
        if (!ExtractDestinationScriptValid(scriptPubKeyDestinationOnly, address))
           return false;
        addressRet.push_back(address);
    }

    return true;
}

bool IsStandardNullData(const CScript& scriptPubKey,bool standard_check)
{
    opcodetype opcode;
    vector<unsigned char> vch;
    bool recheck=false;
    bool fixed=(mc_gState->m_Features->FixedDestinationExtraction() != 0);
    int op_drop_count=0;
    int max_op_drop_count=2;
    bool check_sizes=false;

    if( !fixed || standard_check )
    {
        check_sizes=true;
    }

    if(mc_gState->m_Features->FormattedData())
    {
        max_op_drop_count=MAX_OP_RETURN_OP_DROP_COUNT;
    }

    CScript::const_iterator pc = scriptPubKey.begin();

    while( op_drop_count < max_op_drop_count+1 )
    {
        if(!scriptPubKey.GetOp(pc, opcode))
        {
            return false;
        }

        if(opcode == OP_RETURN)
        {
            op_drop_count=max_op_drop_count+1;
        }
        else
        {
            if(op_drop_count == max_op_drop_count)
            {
                return false;
            }
        }

        if(op_drop_count < max_op_drop_count+1)
        {
            if( opcode < OP_PUSHDATA1 )
            {
                if(check_sizes)
                {
                    if( (unsigned int)opcode > MAX_SCRIPT_ELEMENT_SIZE )
                    {
                        return false;
                    }
                }
            }
            else
            {
                if( opcode <= OP_PUSHDATA4 )
                {
                    if( !fixed || standard_check )
                    {
                        recheck=true;
                    }
                }
                else
                {
                    if(fixed)
                    {
                        return false;
                    }
                }
            }

            if(!scriptPubKey.GetOp(pc, opcode))
            {
                return false;
            }
            if(opcode != OP_DROP)
            {
                return false;
            }
            op_drop_count++;
        }
    }

    if (pc < scriptPubKey.end())
    {
        if(pc + OP_PUSHDATA1 < scriptPubKey.end())
        {
            scriptPubKey.GetOp(pc, opcode, vch);
            if( !fixed || standard_check )
            {
                if (vch.size() > MAX_OP_RETURN_RELAY)
                {
                    return false;
                }
            }
        }
        else
        {
            scriptPubKey.GetOp(pc, opcode);
            if(opcode >= OP_PUSHDATA1)
            {
                if(mc_gState->m_Features->FormattedData())
                {
                    if(opcode > OP_16)
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            if( !fixed || standard_check )
            {
                if ((unsigned int)opcode > MAX_OP_RETURN_RELAY)
                {
                    return false;
                }
            }
        }
        if(scriptPubKey.GetOp(pc, opcode))
        {
            return false;
        }
    }

    if(check_sizes && recheck)
    {
        pc = scriptPubKey.begin();

        op_drop_count=0;
        while( op_drop_count < max_op_drop_count+1 )
        {
            scriptPubKey.GetOp(pc, opcode, vch);
            if(opcode == OP_RETURN)
            {
                op_drop_count=max_op_drop_count+1;
            }
            if( opcode >= OP_PUSHDATA1 )
            {
                if( opcode <= OP_PUSHDATA4 )
                {
                    if( (unsigned int)vch.size() > MAX_SCRIPT_ELEMENT_SIZE )
                    {
                        return false;
                    }
                }
            }
            if(op_drop_count < max_op_drop_count+1)
            {
                scriptPubKey.GetOp(pc, opcode);
                op_drop_count++;
            }
        }

/*
        for(op_drop_count=0;op_drop_count<max_op_drop_count;op_drop_count++)
        {
            if( sizes[op_drop_count] > MAX_SCRIPT_ELEMENT_SIZE )
            {
                return false;
            }
        }
 */
/*
        if( (sizes[0] > MAX_SCRIPT_ELEMENT_SIZE) || (sizes[1] > MAX_SCRIPT_ELEMENT_SIZE) )
        {
            return false;
        }
*/
    }

    return true;
}

bool CScript::IsUnspendable() const
{
    if(mc_gState->m_Features->FixedIsUnspendable() == 0)
    {
        int op_drop_offset[2];
        int op_drop_size[2];
        int op_return_offset,op_return_size;
        return (mc_ParseOpDropOpReturnScript((unsigned char*)&begin()[0],(int)size(),op_drop_offset,op_drop_size,2,&op_return_offset,&op_return_size)) != NULL;
    }
    return IsStandardNullData(*this,false);
}

bool ExtractDestinations10008(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet, bool no_clear, bool *not_cleared)
{
    addressRet.clear();
    typeRet = TX_NONSTANDARD;
    opcodetype opcode;
    vector<unsigned char> vch;

    if(not_cleared)
    {
        *not_cleared=false;
    }
    nRequiredRet=1;

    CScript::const_iterator pc = scriptPubKey.begin();

    if (scriptPubKey.GetOp(pc, opcode))
    {
        if(opcode == OP_DUP)
        {
            if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_HASH160) )
            {
                return false;
            }
            if ( !scriptPubKey.GetOp(pc, opcode, vch) || (vch.size() != 20) )
            {
                return false;
            }
            addressRet.push_back(CKeyID(uint160(vch)));
            if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_EQUALVERIFY) )
            {
                return false;
            }
            if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_CHECKSIG) )
            {
                return false;
            }
            typeRet = TX_PUBKEYHASH;
        }
        else
        {
            if(opcode == OP_HASH160)
            {
                if ( !scriptPubKey.GetOp(pc, opcode, vch) || (vch.size() != 20) )
                {
                    return false;
                }
                addressRet.push_back(CScriptID(uint160(vch)));
                if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_EQUAL) )
                {
                    return false;
                }
                typeRet = TX_SCRIPTHASH;
            }
            else
            {
                if(IsStandardNullData(scriptPubKey,false))
                {
                    typeRet=TX_NULL_DATA;
                    return false;
                }
                else
                {
                    return ExtractDestinationsFull(scriptPubKey,typeRet,addressRet,nRequiredRet);
                }
            }
        }
    }

    if (pc < scriptPubKey.end())                                                // This code should match behavior of RemoveOpDrops
    {
        if (scriptPubKey.GetOp(pc, opcode))
        {
            if(opcode != OP_RETURN)
            {
                if (pc < scriptPubKey.end())
                {
                    if (scriptPubKey.GetOp(pc, opcode))
                    {
                        if(opcode == OP_DROP)
                        {
                            return true;
                        }
                    }
                }
            }
        }
    }
    else
    {
        return true;
    }

    if(!no_clear)
    {
        addressRet.clear();
    }
    else
    {
        if(not_cleared)
        {
            *not_cleared=true;
        }
    }
    typeRet = TX_NONSTANDARD;
    return true;
}

CTxDestination VectorToAddress(vector<unsigned char>& vch)
{
    CTxDestination addressRet;
    addressRet=CNoDestination();

    if( (vch.size() >= 33) && (vch.size() <= 65) )
    {
        CPubKey pubKey(vch.begin(), vch.end());
        if (pubKey.IsValid())
        {
            addressRet = pubKey.GetID();
        }
    }

    return addressRet;
}

bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet,vector<vector<unsigned char> >* lpvSolutionsRet)
{
    if(mc_gState->m_Features->FixedDestinationExtraction() == 0)
    {
        return ExtractDestinations10008(scriptPubKey,typeRet,addressRet,nRequiredRet,false,NULL);
    }

    addressRet.clear();
    typeRet = TX_NONSTANDARD;
    opcodetype opcode;
    vector<unsigned char> vch;
    CTxDestination pkAddress;
    int n;

    nRequiredRet=1;

    CScript::const_iterator pc = scriptPubKey.begin();

    if (scriptPubKey.GetOp(pc, opcode))
    {
        if(opcode == OP_DUP)                                                    // pay-to-pubkeyhash
        {
            if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_HASH160) )
            {
                return false;
            }
            if ( !scriptPubKey.GetOp(pc, opcode, vch) || (vch.size() != 20) )
            {
                return false;
            }
            addressRet.push_back(CKeyID(uint160(vch)));
            if(lpvSolutionsRet)
            {
                lpvSolutionsRet->push_back(vch);
            }
            if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_EQUALVERIFY) )
            {
                return false;
            }
            if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_CHECKSIG) )
            {
                return false;
            }
            typeRet = TX_PUBKEYHASH;
        }
        else
        {
            if(opcode == OP_HASH160)                                            // pay-to-scripthash
            {
                if ( !scriptPubKey.GetOp(pc, opcode, vch) || (vch.size() != 20) )
                {
                    return false;
                }
                addressRet.push_back(CScriptID(uint160(vch)));
                if(lpvSolutionsRet)
                {
                    lpvSolutionsRet->push_back(vch);
                }
                if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_EQUAL) )
                {
                    return false;
                }
                typeRet = TX_SCRIPTHASH;
            }
            else
            {
                if(IsStandardNullData(scriptPubKey,false))                      // null-data
                {
                    typeRet=TX_NULL_DATA;
                    return false;
                }
                else
                {
                    pc = scriptPubKey.begin();
                    if ( !scriptPubKey.GetOp(pc, opcode, vch) )
                    {
                        return false;
                    }

                    pkAddress=VectorToAddress(vch);
                    if( boost::get<CKeyID> (&pkAddress) )                       // pay-to-pubkey
                    {
                        if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_CHECKSIG) )
                        {
                            return false;
                        }
                        addressRet.push_back(pkAddress);
                        if(lpvSolutionsRet)
                        {
                            lpvSolutionsRet->push_back(vch);
                        }
                        typeRet = TX_PUBKEY;
                    }
                    else
                    {
                        if ( (opcode >= OP_1 && opcode <= OP_16) )              // bare multisig
                        {
                            nRequiredRet=CScript::DecodeOP_N(opcode);
                            if(lpvSolutionsRet)
                            {
                                lpvSolutionsRet->push_back(valtype(1, (char)nRequiredRet));
                            }

                            n=-1;
                            while(n != (int)addressRet.size())
                            {
                                if ( !scriptPubKey.GetOp(pc, opcode, vch) )
                                {
                                    return false;
                                }
                                if ( (opcode >= OP_1 && opcode <= OP_16) )
                                {
                                    n=CScript::DecodeOP_N(opcode);
                                    if(n != (int)addressRet.size())
                                    {
                                        return false;
                                    }
                                }
                                else
                                {
                                    pkAddress=VectorToAddress(vch);
                                    if( boost::get<CKeyID> (&pkAddress) )
                                    {
                                        addressRet.push_back(pkAddress);
                                        if(lpvSolutionsRet)
                                        {
                                            lpvSolutionsRet->push_back(vch);
                                        }
                                    }
                                    else
                                    {
                                        return false;
                                    }
                                }
                            }
                            if(lpvSolutionsRet)
                            {
                                lpvSolutionsRet->push_back(valtype(1, (char)n));
                            }

                            if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_CHECKMULTISIG) )
                            {
                                return false;
                            }
                            typeRet = TX_MULTISIG;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
            }
        }
    }

    while(pc < scriptPubKey.end())
    {
        if ( !scriptPubKey.GetOp(pc, opcode) || (opcode > OP_PUSHDATA4) )
        {
            typeRet = TX_NONSTANDARD;
            return false;
        }
        if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_DROP) )
        {
            typeRet = TX_NONSTANDARD;
            return false;
        }
    }

    return true;
}

bool TemplateSolver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet)
{
    vector<CTxDestination> addressRet;
    int nRequiredRet;

    if(mc_gState->m_Features->FixedDestinationExtraction() == 0)
    {
        return Solver(scriptPubKey,typeRet,vSolutionsRet);
    }
    return ExtractDestinations(scriptPubKey,typeRet,addressRet,nRequiredRet,&vSolutionsRet);
}

bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
{
    vector<CTxDestination> addressRets;
    txnouttype typeRet;
    int nRequiredRet;

    if(!ExtractDestinations(scriptPubKey,typeRet,addressRets,nRequiredRet))
    {
        return false;
    }

    if(typeRet == TX_MULTISIG)
    {
        return false;
    }

    addressRet=addressRets[0];
    return true;
}

bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
{
    opcodetype opcode;
    vector<unsigned char> vch;
    whichType = TX_NONSTANDARD;
    int max_op_drops;
    bool result;

    CScript::const_iterator pc = scriptPubKey.begin();

    if (scriptPubKey.GetOp(pc, opcode))
    {
        if(opcode == OP_DUP)
        {
            if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_HASH160) )
            {
                return false;
            }
            if ( !scriptPubKey.GetOp(pc, opcode, vch) || (vch.size() != 20) )
            {
                return false;
            }
            if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_EQUALVERIFY) )
            {
                return false;
            }
            if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_CHECKSIG) )
            {
                return false;
            }
            whichType = TX_PUBKEYHASH;
        }
        else
        {
            if(opcode == OP_HASH160)
            {
                if ( !scriptPubKey.GetOp(pc, opcode, vch) || (vch.size() != 20) )
                {
                    return false;
                }
                if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_EQUAL) )
                {
                    return false;
                }
                whichType = TX_SCRIPTHASH;
            }
            else
            {
                if(IsStandardNullData(scriptPubKey,true))
                {
                    whichType=TX_NULL_DATA;
                    return true;
                }
                else
                {
                    result=IsStandardFull(scriptPubKey,whichType);
                    if( (whichType == TX_PUBKEY) || (whichType == TX_MULTISIG) )
                    {
                        return result;
                    }
                    else                                                        // Avoiding duplicate check for other type
                    {
                        whichType = TX_NONSTANDARD;
                        return false;
                    }
                }
            }
        }
    }

    max_op_drops=MCP_STD_OP_DROP_COUNT;

    for(int d=0;d<max_op_drops;d++)
    {
        if (pc < scriptPubKey.end())
        {
            if ( !scriptPubKey.GetOp(pc, opcode, vch) || (vch.size() > MAX_SCRIPT_ELEMENT_SIZE) )
            {
                whichType = TX_NONSTANDARD;
                return false;
            }
            if ( !scriptPubKey.GetOp(pc, opcode) || (opcode != OP_DROP) )
            {
                whichType = TX_NONSTANDARD;
                return false;
            }
        }
        else
        {
            return true;
        }
    }

    if (pc < scriptPubKey.end())
    {
        whichType = TX_NONSTANDARD;
        return false;
    }

    return true;
}

namespace
{
class CScriptVisitor : public boost::static_visitor<bool>
{
private:
    CScript *script;
public:
    CScriptVisitor(CScript *scriptin) { script = scriptin; }

    bool operator()(const CNoDestination &dest) const {
        script->clear();
        return false;
    }

    bool operator()(const CKeyID &keyID) const {
        script->clear();
        *script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
        return true;
    }

    bool operator()(const CScriptID &scriptID) const {
        script->clear();
        *script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL;
        return true;
    }
};
}

CScript GetScriptForDestination(const CTxDestination& dest)
{
    CScript script;

    boost::apply_visitor(CScriptVisitor(&script), dest);
    return script;
}

CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys)
{
    CScript script;

    script << CScript::EncodeOP_N(nRequired);
    BOOST_FOREACH(const CPubKey& key, keys)
        script << ToByteVector(key);
    script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
    return script;
}

/* MCHN START */
CScript GetScriptForPubKey(const CPubKey& key)
{
    CScript script;
    script << ToByteVector(key);
    script << OP_CHECKSIG;

    return script;
}
/* MCHN END */

max_stars_repo_name: VersumDEX/VersumClient

max_issues_repo_name: VersumDEX/VersumClient

max_forks_repo_name: VersumDEX/VersumClient


text:
#include <abb_librws/v2_0/rws.h>

#include <boost/throw_exception.hpp>

#include <iostream>
#include <stdexcept>

namespace abb :: rws :: v2_0
{
  const std::string Identifiers::ACTIVE                         = "active";
  const std::string Identifiers::ARM                            = "arm";
  const std::string Identifiers::CFG_DT_INSTANCE_LI             = "cfg-dt-instance-li";
  const std::string Identifiers::CFG_IA_T_LI                    = "cfg-ia-t-li";
  const std::string Identifiers::CTRL_TYPE                      = "ctrl-type";
  const std::string Identifiers::CTRLEXECSTATE                  = "ctrlexecstate";
  const std::string Identifiers::CTRLSTATE                      = "ctrlstate";
  const std::string Identifiers::DATTYP                         = "dattyp";
  const std::string Identifiers::EXCSTATE                       = "excstate";
  const std::string Identifiers::IOS_SIGNAL                     = "ios-signal";
  const std::string Identifiers::HOME_DIRECTORY                 = "$home";
  const std::string Identifiers::LVALUE                         = "lvalue";
  const std::string Identifiers::MECHANICAL_UNIT                = "mechanical_unit";
  const std::string Identifiers::MECHANICAL_UNIT_GROUP          = "mechanical_unit_group";
  const std::string Identifiers::MOC                            = "moc";
  const std::string Identifiers::MODULE                         = "module";
  const std::string Identifiers::MODULEPATH                     = "modulepath";
  const std::string Identifiers::MOTIONTASK                     = "motiontask";
  const std::string Identifiers::NAME                           = "name";
  const std::string Identifiers::OPMODE                         = "opmode";
  const std::string Identifiers::PRESENT_OPTIONS                = "present_options";
  const std::string Identifiers::RAP_MODULE_INFO_LI             = "rap-module-info-li";
  const std::string Identifiers::RAP_TASK_LI                    = "rap-task-li";
  const std::string Identifiers::ROBOT                          = "robot";
  const std::string Identifiers::RW_VERSION_NAME                = "rwversionname";
  const std::string Identifiers::SINGLE                         = "single";
  const std::string Identifiers::STATE                          = "state";
  const std::string Identifiers::SYS                            = "sys";
  const std::string Identifiers::SYS_OPTION_LI                  = "sys-option-li";
  const std::string Identifiers::SYS_SYSTEM_LI                  = "sys-system-li";
  const std::string Identifiers::TITLE                          = "title";
  const std::string Identifiers::TYPE                           = "type";
  const std::string Identifiers::VALUE                          = "value";
  const std::string Identifiers::CLASS                          = "class";
  const std::string Identifiers::OPTION                         = "option";
  const std::string Queries::ACTION_LOAD_MODULE                 = "loadmod";
  const std::string Queries::ACTION_RELEASE                     = "action=release";
  const std::string Queries::ACTION_REQUEST                     = "action=request";
  const std::string Queries::ACTION_RESETPP                     = "resetpp";
  const std::string Queries::ACTION_SET                         = "set-value";
  const std::string Queries::ACTION_SETCTRLSTATE                = "action=setctrlstate";  // TODO remove
  const std::string Queries::ACTION_SET_LOCALE                  = "action=set-locale";
  const std::string Queries::ACTION_START                       = "start";
  const std::string Queries::ACTION_STOP                        = "stop";
  const std::string Queries::ACTION_UNLOAD_MODULE               = "unloadmod";
  const std::string Queries::TASK                               = "task=";
  const std::string Services::CTRL                              = "/ctrl";
  const std::string Services::FILESERVICE                       = "/fileservice";
  const std::string Services::RW                                = "/rw";
  const std::string Services::SUBSCRIPTION                      = "/subscription";
  const std::string Services::USERS                             = "/users";
  const std::string Resources::INSTANCES                        = "/instances";
  const std::string Resources::JOINTTARGET                      = "/jointtarget";
  const std::string Resources::LOGOUT                           = "/logout";
  const std::string Resources::ROBTARGET                        = "/robtarget";
  const std::string Resources::RW_CFG                           = Services::RW + "/cfg";
  const std::string Resources::RW_IOSYSTEM_SIGNALS              = Services::RW + "/iosystem/signals";
  const std::string Resources::RW_MOTIONSYSTEM_MECHUNITS        = Services::RW + "/motionsystem/mechunits";
  const std::string Resources::RW_PANEL_CTRLSTATE               = Services::RW + "/panel/ctrl-state";
  const std::string Resources::RW_PANEL_OPMODE                  = Services::RW + "/panel/opmode";
  const std::string Resources::RW_RAPID_EXECUTION               = Services::RW + "/rapid/execution";
  const std::string Resources::RW_RAPID_MODULES                 = Services::RW + "/rapid/modules";
  const std::string Resources::RW_RAPID_SYMBOL_DATA_RAPID       = Services::RW + "/rapid/symbol/RAPID";
  const std::string Resources::RW_RAPID_SYMBOL_PROPERTIES_RAPID = Services::RW + "/rapid/symbol/RAPID";   // TODO merge with symbol data
  const std::string Resources::RW_RAPID_TASKS                   = Services::RW + "/rapid/tasks";
  const std::string Resources::RW_SYSTEM                        = Services::RW + "/system";

  const XMLAttribute XMLAttributes::CLASS_ACTIVE(Identifiers::CLASS            , Identifiers::ACTIVE);
  const XMLAttribute XMLAttributes::CLASS_CFG_DT_INSTANCE_LI(Identifiers::CLASS, Identifiers::CFG_DT_INSTANCE_LI);
  const XMLAttribute XMLAttributes::CLASS_CFG_IA_T_LI(Identifiers::CLASS       , Identifiers::CFG_IA_T_LI);
  const XMLAttribute XMLAttributes::CLASS_CTRL_TYPE(Identifiers::CLASS         , Identifiers::CTRL_TYPE);
  const XMLAttribute XMLAttributes::CLASS_CTRLEXECSTATE(Identifiers::CLASS     , Identifiers::CTRLEXECSTATE);
  const XMLAttribute XMLAttributes::CLASS_CTRLSTATE(Identifiers::CLASS         , Identifiers::CTRLSTATE);
  const XMLAttribute XMLAttributes::CLASS_DATTYP(Identifiers::CLASS            , Identifiers::DATTYP);
  const XMLAttribute XMLAttributes::CLASS_EXCSTATE(Identifiers::CLASS          , Identifiers::EXCSTATE);
  const XMLAttribute XMLAttributes::CLASS_IOS_SIGNAL(Identifiers::CLASS        , Identifiers::IOS_SIGNAL);
  const XMLAttribute XMLAttributes::CLASS_LVALUE(Identifiers::CLASS            , Identifiers::LVALUE);
  const XMLAttribute XMLAttributes::CLASS_MOTIONTASK(Identifiers::CLASS        , Identifiers::MOTIONTASK);
  const XMLAttribute XMLAttributes::CLASS_NAME(Identifiers::CLASS              , Identifiers::NAME);
  const XMLAttribute XMLAttributes::CLASS_OPMODE(Identifiers::CLASS            , Identifiers::OPMODE);
  const XMLAttribute XMLAttributes::CLASS_RAP_MODULE_INFO_LI(Identifiers::CLASS, Identifiers::RAP_MODULE_INFO_LI);
  const XMLAttribute XMLAttributes::CLASS_RAP_TASK_LI(Identifiers::CLASS       , Identifiers::RAP_TASK_LI);
  const XMLAttribute XMLAttributes::CLASS_RW_VERSION_NAME(Identifiers::CLASS   , Identifiers::RW_VERSION_NAME);
  const XMLAttribute XMLAttributes::CLASS_STATE(Identifiers::CLASS             , Identifiers::STATE);
  const XMLAttribute XMLAttributes::CLASS_SYS_OPTION_LI(Identifiers::CLASS     , Identifiers::SYS_OPTION_LI);
  const XMLAttribute XMLAttributes::CLASS_SYS_SYSTEM_LI(Identifiers::CLASS     , Identifiers::SYS_SYSTEM_LI);
  const XMLAttribute XMLAttributes::CLASS_TYPE(Identifiers::CLASS              , Identifiers::TYPE);
  const XMLAttribute XMLAttributes::CLASS_VALUE(Identifiers::CLASS             , Identifiers::VALUE);
  const XMLAttribute XMLAttributes::CLASS_OPTION(Identifiers::CLASS            , Identifiers::OPTION);

  std::ostream& operator<<(std::ostream& os, MastershipDomain domain)
  {
    switch (domain)
    {
      case MastershipDomain::edit:
        os << "edit";
        break;
      case MastershipDomain::motion:
        os << "motion";
        break;
      default:
        BOOST_THROW_EXCEPTION(std::logic_error {"Invalid v2_0::MastershipDomain value"});
    }

    return os;
  }
}


text:
// Copyright (c) 2016
// Author: Chrono Law
#include <std.hpp>
using namespace std;

#include <boost/checked_delete.hpp>
using namespace boost;

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

class demo_class;

void do_delete(demo_class* p)
//{   delete p;}
{   checked_delete(p);}

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

void case1()
{
    auto p1 = new int(10);
    checked_delete(p1);

    auto p2 = new int[10];
    checked_array_delete(p2);

}

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

class demo_class
{
public:
    ~demo_class()
    {   cout << "dtor exec." << endl;   }
};

void case2()
{
    auto p1 = new demo_class;

    //checked_delete(p1);
    checked_deleter<demo_class>()(p1);

    auto p2 = new demo_class[10];

    //checked_array_delete(p2);
    checked_array_deleter<demo_class>()(p2);

    cout << "try for_each" << endl;

    vector<demo_class*> v;
    v.push_back(new demo_class);
    v.push_back(new demo_class);

    for_each(v.begin(),v.end(), checked_deleter<demo_class>());

}

///////////////////////////////////////
struct my_checked_deleter
{
    typedef void result_type;

    template<class T>
    void operator()(T* x) const
    {
        boost::checked_delete(x);
    }
};

void case3()
{
    cout << "my_checked_deleter" << endl;

    auto p = new int(10);
    my_checked_deleter()(p);

    vector<int*> v;

    v.push_back(new int(10));
    for_each(v.begin(), v.end(),
            my_checked_deleter());

}

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

void case4()
{
    cout << "incomplete type" << endl;

    auto p = new demo_class();
    //auto p = (demo_class*)(1996);

    do_delete(p);
}

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

#include <boost/static_assert.hpp>

template<class Pointer> inline
void my_checked_delete(Pointer p)
{
    BOOST_STATIC_ASSERT(is_pointer<Pointer>::value);

    typedef typename remove_pointer<Pointer>::type T;
    BOOST_STATIC_ASSERT(is_object<T>::value);
    BOOST_STATIC_ASSERT(!is_array<T>::value);
    BOOST_STATIC_ASSERT(sizeof(T) >0 );

    delete p;
}

void case5()
{
    //auto p = new int[2][2];
    auto p = new int;
    my_checked_delete(p);
}

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

int main()
{
    std::cout << "hello checked_delete" << std::endl;

    case1();
    case2();
    case3();
    case4();
    case5();
}


text:
//
// main.cpp
// ~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <server/server.hpp>

int main(int argc, char* argv[])
{
  const std::string ip = "0.0.0.0";
  const std::string port = "8000";
  const std::string path = "./";

  std::cout << "Serving HTTP on " << ip << " port " << port << " ..." << std::endl;

  http::server::server s(ip, port, path);
  s.run();

  return 0;
}

max_stars_repo_name: tfussell/cort

max_issues_repo_name: tfussell/cort

max_forks_repo_name: tfussell/cort


text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_BOOLEAN_FUNCTIONS_LOGICAL_NOTOR_HPP_INCLUDED
#define BOOST_SIMD_BOOLEAN_FUNCTIONS_LOGICAL_NOTOR_HPP_INCLUDED
/*!
 * \file
**/
#include <boost/simd/include/functor.hpp>
#include <boost/dispatch/include/functor.hpp>
#include <boost/proto/tags.hpp>

/*!
 * \ingroup boost_simd_operator
 * \defgroup boost_simd_operator_logical_notor logical_notor
 *
 * \par Description
 * return the logical or of the negation of the first parameter and the second parameter
 * the result type is logical type associated to the first parameter
 *
 * \par Header file
 *
 * \code
 * #include <nt2/include/functions/logical_notor.hpp>
 * \endcode
 *
 * \par Alias
 * \arg l_notor
 *
 * \synopsis
 *
 * \code
 * namespace boost::simd
 * {
 *   template <class A0>
 *     meta::call<tag::logical_notor_(A0,A1)>::type
 *     logical_notor(const A0 & a0,const A1 & a1);
 * }
 * \endcode
 *
 * \param a0 the first parameter of logical_notor
 * \param a1 the second parameter of logical_notor
 *
 * \return a value of the logical type associated to the first parameter
 *
 * \par Notes
 * In SIMD mode, this function acts elementwise on the inputs vectors elements
 * \par
 * This is a logical operation. Such operations return logical types.
 * You are invited to consult the rationale.
 *
**/

namespace boost { namespace simd
{
  namespace tag
  {
    /*!
     * \brief Define the tag logical_notor_ of functor logical_notor
     *        in namespace boost::simd::tag for toolbox boost.simd.operator
    **/
    struct logical_notor_ : ext::elementwise_<logical_notor_> { typedef ext::elementwise_<logical_notor_> parent; };
  }

  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::logical_notor_      , logical_notor     , 2 )
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::logical_notor_      , l_notor           , 2 )
} }

#include <boost/simd/operator/specific/common.hpp>

#endif


text:
// Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.

#include "Generic/common/leak_detection.h"

#include "Arabic/relations/ar_RelationModel.h"
#include "Generic/relations/VectorModel.h"
#include "Arabic/relations/ar_RelationUtilities.h"
#include "Generic/common/Symbol.h"
#include "Generic/common/NgramScoreTable.h"
#include "Generic/relations/PotentialRelationInstance.h"
#include "Arabic/relations/ar_PotentialRelationCollector.h"
#include "Generic/preprocessors/EntityTypes.h"
#include "Generic/preprocessors/RelationTypeMap.h"
#include "Arabic/relations/ar_PotentialRelationExtractor.h"
#include "Arabic/relations/ar_PotentialRelationInstance.h"
#include "Generic/common/ParamReader.h"
#include "Generic/common/UTF8InputStream.h"
#include "Generic/driver/SessionProgram.h"
#include "Generic/driver/DocumentDriver.h"
#include "Arabic/common/ar_StringTransliterator.h"
#include <boost/scoped_ptr.hpp>

const Symbol BAD_EDT_SYM = Symbol(L"BAD EDT");
const Symbol SAME_ENTITY_SYM = Symbol(L"SAME ENTITY");
const Symbol NEG_HYPO_SYM = Symbol(L"NEG/HYPO");

ArabicRelationModel::ArabicRelationModel() :  _maxEntModel(0)
{
	//_maxEntModel = _new MaxEntRelationModel();

	_debugStream.init(Symbol(L"relations_debug"));
	_vectorModel = _new VectorModel();
}

ArabicRelationModel::ArabicRelationModel(const char *file_prefix) : _maxEntModel(0)
{
	//_maxEntModel = _new MaxEntRelationModel(file_prefix);

	std::string debug_file = ParamReader::getParam("relations_debug");
	if (!debug_file.empty()) {
		_debugStream.openFile(debug_file.c_str());
	}
}

ArabicRelationModel::~ArabicRelationModel() {
	//delete _maxEntModel;
}

void ArabicRelationModel::trainFromStateFileList(char *training_file, char* output_file_prefix) {
	_vectorModel->trainFromStateFileList(training_file, output_file_prefix);

}

void ArabicRelationModel::generateVectorsAndTrain(char *packet_file,
											char* vector_file,
											char* output_file_prefix)
{
	// read in PotentialTrainingRelations from packet_file annotation
	// MEM: must delete annotation set when finished
	PotentialRelationMap *annotationSet = readPacketAnnotation(packet_file);

	// extract PotentialTrainingRelations from batch
	PotentialRelationCollector* resultCollector = PotentialRelationCollector::build(ArabicPotentialRelationCollector::TRAIN);
	extractTrainingRelations(*resultCollector);

	_debugStream << "Found " << resultCollector->getNRelations() << " potential relations.\n";
	NgramScoreTable vectors(AR_POTENTIAL_RELATION_INSTANCE_NGRAM_SIZE, resultCollector->getNRelations());
	for (int i = 0; i < resultCollector->getNRelations(); i++) {
		PotentialTrainingRelation *rel = resultCollector->getPotentialTrainingRelation(i);
		_debugStream << rel->toString();
		PotentialRelationMap::iterator it = annotationSet->find(*rel);
		if (it != annotationSet->end())  {
			_debugStream << L"Found it!\n";
			PotentialRelationInstance *instance = resultCollector->getPotentialRelationInstance(i);

			instance->setRelationType((*it).second);
			instance->setReverse((((*it).first).relationIsReversed() || rel->argsAreReversed()) &&
							    !(((*it).first).relationIsReversed() && rel->argsAreReversed()));

			// coerce entity types (we assume the annotation is correct)
			if (rel->_type1 != ((*it).first)._type1) {
				if (!rel->argsAreReversed())
					instance->setLeftEntityType((((*it).first)._type1).getName());
				else
					instance->setRightEntityType((((*it).first)._type1).getName());
			}
			if (rel->_type2 != ((*it).first)._type2) {
				if (!rel->argsAreReversed())
					instance->setRightEntityType((((*it).first)._type2).getName());
				else
					instance->setLeftEntityType((((*it).first)._type2).getName());
			}

			if (instance->getRelationType() != BAD_EDT_SYM &&
				instance->getRelationType() != SAME_ENTITY_SYM &&
				instance->getRelationType() != NEG_HYPO_SYM)
			{
				vectors.add(instance->getTrainingNgram());
			}
			_debugStream << instance->toString() << L"\n";
		}
		else 	_debugStream << L"Didn't find it!\n";

	}

	vectors.print(vector_file);

	//train(vector_file, output_file_prefix);

	delete annotationSet;
}

ArabicRelationModel::PotentialRelationMap *ArabicRelationModel::readPacketAnnotation(const char *packet_file) {
	PotentialRelationMap *annotationSet = _new PotentialRelationMap(1024);
	boost::scoped_ptr<UTF8InputStream> packet_scoped_ptr(UTF8InputStream::build());
	UTF8InputStream& packet(*packet_scoped_ptr);
	wchar_t line[200];

	packet.open(packet_file);
	if (packet.fail()) {

		char message[300];
		sprintf(message, "Could not open packet file `%s'", packet_file);
		throw UnexpectedInputException("ArabicRelationModel::readPacketAnnotation()", message);
	}
	packet.getLine(line, 200);
	int n_packet_files = _wtoi(line);
	for (int i = 0; i < n_packet_files; i++) {
		PotentialTrainingRelation rel;
		boost::scoped_ptr<UTF8InputStream> in_scoped_ptr(UTF8InputStream::build());
		UTF8InputStream& in(*in_scoped_ptr);

		if (packet.eof()) {
			char message[300];
			sprintf(message, "Reached unexpected end of `%s'", packet_file);
			throw UnexpectedInputException("ArabicRelationModel::readPacketAnnotation()",  message);
		}
		packet.getLine(line, 200);
		in.open(line);
		if (in.fail()) {
			char message[300];
			char cline[300];
			ArabicStringTransliterator::transliterateToEnglish(cline, line, 300);
			sprintf(message, "Could not open annotation file `%s'", cline);
			throw UnexpectedInputException("ArabicRelationModel::readPacketAnnotation()", message);
		}
		in.getLine(line, 200);
		int n_relations = _wtoi(line);
		for (int j = 0; j < n_relations; j++) {
			in >> rel;
			(*annotationSet)[rel] = rel.getRelationType();
		}
		in.close();

	}
	packet.close();
	return annotationSet;
}

void ArabicRelationModel::extractTrainingRelations(PotentialRelationCollector &resultCollector) {
	SessionProgram sessionProgram;
	sessionProgram.setStageActiveness(Stage("sent-break"), true);
	sessionProgram.setStageActiveness(Stage("tokens"), true);
	sessionProgram.setStageActiveness(Stage("parse"), true);
	sessionProgram.setStageActiveness(Stage("mentions"), true);
	sessionProgram.setStageActiveness(Stage("props"), true);
	sessionProgram.setStageActiveness(Stage("metonymy"), true);
	sessionProgram.setStageActiveness(Stage("entities"), true);
	sessionProgram.setStageActiveness(Stage("events"), false);
	sessionProgram.setStageActiveness(Stage("relations"), false);
	sessionProgram.setStageActiveness(Stage("doc-entities"), false);
	sessionProgram.setStageActiveness(Stage("doc-relations-events"), false);
	sessionProgram.setStageActiveness(Stage("generics"), false);
	sessionProgram.setStageActiveness(Stage("output"), true);
	sessionProgram.setStageActiveness(Stage("score"), false);
	sessionProgram.setStageActiveness(Stage("END"), false);

	DocumentDriver documentDriver(&sessionProgram,
			  					  &resultCollector);
	documentDriver.run();
}

/*void ArabicRelationModel::extractTrainingRelations(ArabicPotentialRelationCollector &resultCollector) {

	char input_list[501];
	char parse_dir[501];
	char entity_types[501];
	char line[200];
	char prefix[200];
	char parse_file[200];
	bool use_default;

	if (!ParamReader::getParam("input_list",input_list, 500))	{
		throw UnexpectedInputException("RelationMode::extractTrainingRelations()",
										"Param `input_list' not defined");
	}
	if (!ParamReader::getParam("parse_dir",parse_dir, 500))	{
		throw UnexpectedInputException("RelationMode::extractTrainingRelations()",
										"Param `parse_dir' not defined");
	}
	if (!ParamReader::getParam("entity_type_list",entity_types, 500))	{
		throw UnexpectedInputException("RelationMode::extractTrainingRelations()",
										"Param `entity_type_list' not defined");
	}
	if (ParamReader::getParam(Symbol(L"use_default_entity_types")) == Symbol(L"true"))
		use_default = true;
	else if (ParamReader::getParam(Symbol(L"use_default_entity_types")) == Symbol(L"false"))
		use_default = false;
	else {
		throw UnexpectedInputException("RelationMode::extractTrainingRelations()",
										"Param `use_default_entity_types' must be set to 'true' or 'false'");
	}

	EntityTypes entityTypes(entity_types, use_default);
	PotentialRelationExtractor extractor(&entityTypes, &resultCollector);

	ifstream in;
	in.open(input_list);
	if (in.fail()) {
		char message[300];
		sprintf(message, "Could not open input file list `%s'", input_list);
			throw UnexpectedInputException("ArabicRelationModel::extractTrainingRelations()", message);
	}
	while (!in.eof()) {
		in.getline(line, 200);
		if (line[0] != '\0' && line[0] != '#') {
			// strip \r if it's there
			char* c = line;
			while (*c != '\0' && c != &line[199]) {
				if (*c == '\r') {
					*c = '\0';
					break;
				}
				c++;
			}
			char *end;
			strcpy(prefix, line);
			char *short_prefix;
			if ((end = strstr(prefix, ".out.sgm")) != NULL)
				*end = '\0';
			int len = static_cast<int>(strlen(prefix));
			for (int i = len - 1; i >= 0; i--) {
				if (prefix[i] == '\\' || prefix[i] == '/') {
					short_prefix = &prefix[i + 1];
					break;
				}
			}
			sprintf(parse_file, "%s\\", parse_dir);
			strcat(parse_file, short_prefix);
			strcat(parse_file, ".arparse");
			// Process the document.
			extractor.processDocument(line, parse_file);
		}
	}
	in.close();
}*/

max_stars_repo_name: BBN-E/serif

max_issues_repo_name: BBN-E/serif

max_forks_repo_name: BBN-E/serif


text:
// Document/View sample for Boost.Signals2.
// Expands on doc_view.cpp example by using automatic
// connection management.
//
// Copyright Keith MacDonald 2005.
// Copyright Frank Mori Hess 2009.
//
// Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// For more information, see http://www.boost.org

#include <iostream>
#include <string>
#include <boost/bind.hpp>
#include <boost/signals2/signal.hpp>
#include <boost/shared_ptr.hpp>

class Document
{
public:
  typedef boost::signals2::signal<void ()>  signal_t;

public:
  Document()
  {}

  /* connect a slot to the signal which will be emitted whenever
    text is appended to the document. */
  boost::signals2::connection connect(const signal_t::slot_type &subscriber)
  {
    return m_sig.connect(subscriber);
  }

  void append(const char* s)
  {
    m_text += s;
    m_sig();
  }

  const std::string& getText() const
  {
    return m_text;
  }

private:
  signal_t    m_sig;
  std::string m_text;
};

class TextView
{
public:
  // static factory function that sets up automatic connection tracking
  static boost::shared_ptr<TextView> create(Document& doc)
  {
    boost::shared_ptr<TextView> new_view(new TextView(doc));
    {
      typedef Document::signal_t::slot_type slot_type;
      slot_type myslot(&TextView::refresh, new_view.get());
      doc.connect(myslot.track(new_view));
    }
    return new_view;
  }

  void refresh() const
  {
    std::cout << "TextView: " << m_document.getText() << std::endl;
  }
private:
    // private constructor to force use of static factory function
    TextView(Document &doc): m_document(doc)
    {}

    Document&               m_document;
};

class HexView
{
public:
  // static factory function that sets up automatic connection tracking
  static boost::shared_ptr<HexView> create(Document& doc)
  {
    boost::shared_ptr<HexView> new_view(new HexView(doc));
    {
      typedef Document::signal_t::slot_type slot_type;
      slot_type myslot(&HexView::refresh, new_view.get());
      doc.connect(myslot.track(new_view));
    }
    return new_view;
  }

  void refresh() const
  {
    const std::string&  s = m_document.getText();

    std::cout << "HexView:";

    for (std::string::const_iterator it = s.begin(); it != s.end(); ++it)
      std::cout << ' ' << std::hex << static_cast<int>(*it);

    std::cout << std::endl;
  }
private:
  // private constructor to force use of static factory function
  HexView(Document& doc): m_document(doc)
  {}

  Document&               m_document;
};

int main(int argc, char* argv[])
{
  Document    doc;
  boost::shared_ptr<TextView> v1 = TextView::create(doc);
  boost::shared_ptr<HexView> v2 = HexView::create(doc);

  doc.append(argc >= 2 ? argv[1] : "Hello world!");

  v2.reset(); // destroy the HexView, automatically disconnecting
  doc.append("  HexView should no longer be connected.");

  return 0;
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
#pragma once
#include <vector>
#include <string>
#include <future>
#include <unordered_map>
#include <cpr/cpr.h>
#include <boost/program_options.hpp>
#include <boost/config.hpp>
#include <spdlog/spdlog.h>
#include "Simple-Web-Server/server_http.hpp"
using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP>;

template <typename T>
std::vector<T> join_all_async(std::vector<std::future<T>> &futures)
{
    std::vector<T> result;
    for (auto &future : futures)
    {
        result.push_back(future.get());
    }
    return result;
}

cpr::Header multimap_to_cpr_header(SimpleWeb::CaseInsensitiveMultimap &headers)
{
    cpr::Header h;
    for (auto &header : headers)
    {
        h[header.first] = header.second;
    }
    return h;
}

SimpleWeb::CaseInsensitiveMultimap cpr_header_to_multimap(cpr::Header &headers)
{
    SimpleWeb::CaseInsensitiveMultimap h;
    for (auto &header : headers)
    {
        h.emplace(header.first, header.second);
    }
    return h;
}

void csv_to_vec(std::string csv, std::vector<std::string> &vec)
{
    std::stringstream ss(csv);
    std::string item;
    while (std::getline(ss, item, ','))
    {
        vec.push_back(item);
    }
}

boost::program_options::variables_map parse_args(int argc, char *argv[])
{
    // we need to accept the following arguments:
    // -p, --port <port>
    // --nodes <nodes> (comma separated list of nodes)
    // --fcu-invalid-threshold <threshold>
    // -h, --help
    // -v, --version

    boost::program_options::options_description desc("Allowed options");
    desc.add_options()

        ("help,h", "produce help message")                                                              // help message
        ("version,v", "print version")                                                                  // version message
        ("port,p", boost::program_options::value<int>(), "port to listen on")                           // port to listen on
        ("nodes,n", boost::program_options::value<std::string>(), "comma separated list of nodes")      // comma separated list of nodes
        ("fcu-invalid-threshold,fcu", boost::program_options::value<double>(), "fcU invalid threshold") // fcU invalid threshold
        ;

    boost::program_options::variables_map vm;
    boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
    boost::program_options::notify(vm);

    if (vm.count("help"))
    {
        std::cout << desc << std::endl;
        exit(0);
    }

    if (vm.count("version"))
    {
        std::cout << "executionbackup-cpp version 0.1.0 BETA\n";
        std::cout << "Compiled with " << BOOST_COMPILER << std::endl;
        exit(0);
    }

    if (vm.count("nodes") == 0)
    {
        spdlog::critical("no nodes specified, exiting");
        exit(1);
    }

    if (vm.count("port") == 0)
    {
        spdlog::warn("no port specified, using default port 8000");
    }

    return vm;
}

max_stars_repo_name: TennisBowling/executionbackup

max_issues_repo_name: TennisBowling/executionbackup

max_forks_repo_name: TennisBowling/executionbackup


text:
#ifndef OB_CONFIG_HPP
#define OB_CONFIG_HPP

#include <Eigen/Dense>
#include <vector>
#include <limits>
#include <memory>
#include <iostream>

namespace OB
{
    // We could also use 16 bits to save space?
    using FeatureId = uint32_t;

    using Real = double;
    using Point = Eigen::Matrix<Real, 3, 1>;
    using Vector = Point;
    using Matrix3 = Eigen::Matrix<Real,3,3>;
    using DiagonalMatrix3 = Eigen::DiagonalMatrix<Real,3>;
    using Plane = Eigen::Hyperplane<Real,3>;

    // Affine looks like slow...
    constexpr enum Eigen::TransformTraits Isometry = Eigen::Isometry;
    //constexpr enum Eigen::TransformTraits Isometry = Eigen::Affine;

    // can't get it to work with CompactAffine
    constexpr enum Eigen::TransformTraits DefaultTransformTrait = Eigen::Affine;
    using Transform = Eigen::Transform<Real,3,DefaultTransformTrait>; //size:128 with double

    using Translation = Eigen::Translation<Real,3>;
    using Quaternion = Eigen::Quaternion<Real>;
    using AngleAxis = Eigen::AngleAxis<Real>;
    using ParametrizedLine = Eigen::ParametrizedLine<Real,3>;

    constexpr Real PI = EIGEN_PI;

    template<typename ScalarType>
    bool is_zero(ScalarType value, ScalarType prec = std::numeric_limits< float >::epsilon())
    {
        return Eigen::internal::isMuchSmallerThan(value,
                                                  static_cast<ScalarType>(1.0),
                                                  prec);
    }

}

#endif


text:
//###
#if 0

#include <iostream>

#include <rafl/base/ProbabilityMassFunction.h>
using namespace rafl;

int main()
{
  Histogram<int> hist;
  for(int i=0; i<5; ++i) hist.add(23);
  for(int i=0; i<5; ++i) hist.add(9);
  for(int i=0; i<5; ++i) hist.add(84);
  for(int i=0; i<500; ++i) hist.add(24);
  ProbabilityMassFunction<int> pmf(hist);
  const std::map<int,float>& masses = pmf.get_masses();
  /*for(std::map<int,float>::const_iterator it = masses.begin(), iend = masses.end(); it != iend; ++it)
  {
    std::cout << it->first << ' ' << it->second << '\n';
  }*/
  //std::cout << pmf << '\n';
  std::cout << pmf << '\n';
  std::cout << "Entropy=" << pmf.calculate_entropy() << '\n';
  return 0;
}

#endif

//###
#if 1

#include <Eigen/Dense>

#include <rafl/core/RandomForest.h>
#include <rafl/decisionfunctions/FeatureThresholdingDecisionFunctionGenerator.h>
using namespace rafl;

typedef int Label;
typedef boost::shared_ptr<const Example<Label> > Example_CPtr;
typedef DecisionTree<Label> DT;
typedef RandomForest<Label> RF;
typedef boost::shared_ptr<DT::Settings> Settings_Ptr;

Descriptor_CPtr make_descriptor(float *arr)
{
  Descriptor_Ptr d(new Descriptor(10));
  for(int i = 0; i < 10; ++i)
  {
    (*d)[i] = arr[i];
  }
  return d;
}

int main(int argc, char *argv[])
{
  if(argc != 3)
  {
    std::cout << "Silly boy - enter the path of the training set, followed by the path of the test set!\n";
  }
  else
  {
    std::string trainingSetPath = argv[1];
    std::string testingSetPath = argv[2];

    std::cout << "Training set: " << trainingSetPath << "\n";
    std::cout << "Testing set: " << testingSetPath << "\n";

    // Register the relevant decision function generators with the factory.
    DecisionFunctionGeneratorFactory<Label>::instance().register_rafl_makers();

    // Construct the random forest.
    Settings_Ptr settings;
    try
    {
      settings.reset(new DT::Settings("settings.txt"));
    }
    catch(std::exception&)
    {
      // If the settings file can't be found or is invalid, use default settings.
      unsigned int seed = 12345;
      tvgutil::RandomNumberGenerator_Ptr randomNumberGenerator(new tvgutil::RandomNumberGenerator(seed));
      DT::DecisionFunctionGenerator_CPtr decisionFunctionGenerator(new FeatureThresholdingDecisionFunctionGenerator<Label>);

      settings.reset(new DT::Settings);
      settings->candidateCount = 256;
      settings->decisionFunctionGenerator = decisionFunctionGenerator;
      settings->gainThreshold = 0.0f;
      settings->maxClassSize = 10000;
      settings->maxTreeHeight = 15;
      settings->randomNumberGenerator = randomNumberGenerator;
      settings->seenExamplesThreshold = 30;
      settings->splittabilityThreshold = 0.5f;
    }

    const size_t treeCount = 8;
    RF rf(treeCount, *settings);

    // Train the random forest.
    std::cout << "Training the random forest..\n";
    std::vector<Example_CPtr> trainingExamples = ExampleUtil::load_examples<Label>(trainingSetPath);
    std::set<Label> classLabels;
    for(size_t i = 0, iend = trainingExamples.size(); i < iend; ++i)
    {
      classLabels.insert( trainingExamples.at(i)->get_label() );
    }

    rf.add_examples(trainingExamples);
    const size_t splitBudget = 32768;
    rf.train(splitBudget);
    rf.output(std::cout);

    // Test the random forest and output the results.
    std::cout << "Testing the random forest..\n";
    std::vector<Example_CPtr> testingExamples = ExampleUtil::load_examples<Label>(testingSetPath);
    std::vector<Label> expectedLabels, predictedLabels;

    float totalTests = static_cast<float>(testingExamples.size());
    size_t correctTests = 0, wrongTests = 0;
    for(std::vector<Example_CPtr>::const_iterator it = testingExamples.begin(), iend = testingExamples.end(); it != iend; ++it)
    {
      const Descriptor_CPtr& descriptor = (*it)->get_descriptor();
      const Label& expectedLabel = (*it)->get_label();
      Label predictedLabel = rf.predict(descriptor);
      expectedLabels.push_back(expectedLabel);
      predictedLabels.push_back(predictedLabel);
      if(predictedLabel == expectedLabel) ++correctTests;
      else ++wrongTests;
    }

    std::cout << "Correct %: " << correctTests / totalTests << '\n';
    std::cout << "Wrong %: " << wrongTests / totalTests << '\n';
  }
  return 0;
}

#endif

max_stars_repo_name: torrvision/spaint

max_issues_repo_name: GucciPrada/spaint

max_forks_repo_name: GucciPrada/spaint