text:
/* CirKit: A circuit toolkit
 * Copyright (C) 2009-2015  University of Bremen
 * Copyright (C) 2015-2017  EPFL
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include "read_qc.hpp"

#include <cmath>
#include <unordered_map>
#include <vector>

#include <boost/format.hpp>

#include <core/utils/range_utils.hpp>
#include <core/utils/string_utils.hpp>
#include <reversible/gate.hpp>
#include <reversible/pauli_tags.hpp>
#include <reversible/functions/add_gates.hpp>

namespace cirkit
{

circuit read_qc( const std::string& filename )
{
  circuit circ;
  std::unordered_map<std::string, unsigned> var2line;

  line_parser( filename, {
      {std::regex( "^ *#.*$" ), []( const std::smatch& m ) {
          /* comment */
        }},
      {std::regex("^ *$" ), []( const std::smatch& m ) {
          /* empty line */
        }},
      {std::regex( "^\\.v +(.*)$" ), [&circ, &var2line]( const std::smatch& m ) {
          std::vector<std::string> variables;
          split_string( variables, m[1u], " " );

          circ.set_lines( variables.size() );
          for ( const auto& v : index( variables ) )
          {
            var2line[v.value + "'"] = v.index;
            var2line[v.value] = v.index;
          }
        }},
      {std::regex( "^\\.i +(.*)$" ), [&circ, &var2line]( const std::smatch& m ) {
          std::vector<std::string> inputs( circ.lines(), "0" );
          std::vector<constant> constants( circ.lines(), constant( false ) );

          std::vector<std::string> vins;
          split_string( vins, m[1u], " " );

          const auto fmt_str = boost::str( boost::format( "pi%%0%dd" ) % ( floor( log10( vins.size() ) ) + 1 ) );

          for ( const auto& i : index( vins ) )
          {
            inputs[var2line[i.value]] = boost::str( boost::format( fmt_str ) % i.index );
            constants[var2line[i.value]] = constant();
          }

          circ.set_inputs( inputs );
          circ.set_constants( constants );
        }},
      {std::regex( "^\\.o +(.*)$" ), [&circ, &var2line]( const std::smatch& m ) {
          std::vector<std::string> outputs( circ.lines(), "--" );
          std::vector<bool> garbage( circ.lines(), true );

          std::vector<std::string> vouts;
          split_string( vouts, m[1u], " " );

          const auto fmt_str = boost::str( boost::format( "po%%0%dd" ) % ( floor( log10( vouts.size() ) ) + 1 ) );

          for ( const auto& i : index( vouts ) )
          {
            outputs[var2line[i.value]] = boost::str( boost::format( fmt_str ) % i.index );
            garbage[var2line[i.value]] = false;
          }

          circ.set_outputs( outputs );
          circ.set_garbage( garbage );
        }},
      {std::regex( "BEGIN|END" ), []( const std::smatch& m ) {
        }},
      {std::regex( "^t(of|\\d+) *(.*)$" ), [&circ, &var2line]( const std::smatch& m ) {
          std::vector<std::string> lines;
          split_string( lines, m[2u], " " );

          if ( std::string( m[1u] ) != "of" )
          {
            assert( boost::lexical_cast<unsigned>( std::string( m[1u] ) ) == lines.size() );
          }

          gate::control_container controls;
          for ( auto i = 0u; i < lines.size() - 1; ++i )
          {
            controls.push_back( make_var( var2line[lines[i]], lines[i].back() != '\'' ) );
          }
          append_toffoli( circ, controls, var2line[lines.back()] );
        }},
      {std::regex( "^H *(.*)$" ), [&circ, &var2line]( const std::smatch& m ) {
          std::vector<std::string> lines;
          split_string( lines, m[1u], " " );

          assert( lines.size() == 1u );

          append_hadamard( circ, var2line[lines.back()] );
        }},
      {std::regex( "^X *(.*)$" ), [&circ, &var2line]( const std::smatch& m ) {
          std::vector<std::string> lines;
          split_string( lines, m[1u], " " );

          assert( lines.size() == 1u );

          append_not( circ, var2line[lines.back()] );
        }},
      {std::regex( "^Z *(.*)$" ), [&circ, &var2line]( const std::smatch& m ) {
          std::vector<std::string> lines;
          split_string( lines, m[1u], " " );

          assert( lines.size() == 1u );

          append_pauli( circ, var2line[lines.back()], pauli_axis::Z );
        }},
      {std::regex( "^Y *(.*)$" ), [&circ, &var2line]( const std::smatch& m ) {
          std::vector<std::string> lines;
          split_string( lines, m[1u], " " );

          assert( lines.size() == 1u );

          append_pauli( circ, var2line[lines.back()], pauli_axis::Y );
      }},
      {std::regex( "^(S|P)(\\*?) *(.*)$" ), [&circ, &var2line]( const std::smatch& m ) {
          std::vector<std::string> lines;
          split_string( lines, m[3u], " " );

          assert( lines.size() == 1u );

          append_pauli( circ, var2line[lines.back()], pauli_axis::Z, 2u, !std::string( m[2u] ).empty() );
        }},
      {std::regex( "^T(\\*?) *(.*)$" ), [&circ, &var2line]( const std::smatch& m ) {
          std::vector<std::string> lines;
          split_string( lines, m[2u], " " );

          assert( lines.size() == 1u );

          append_pauli( circ, var2line[lines.back()], pauli_axis::Z, 4u, !std::string( m[1u] ).empty() );
        }}
    }, false );

  return circ;
}

}

// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:

max_stars_repo_name: eletesta/cirkit

max_issues_repo_name: eletesta/cirkit

max_forks_repo_name: eletesta/cirkit


text:
#include "AttrTokenizeWrapper.h"
#include <knlp/attr_tokenize.h>
#include <knlp/dictionary.h>
#include <exception>
#include <glog/logging.h>
#include <util/singleton.h>
#include <boost/filesystem.hpp>

using namespace sf1r;
namespace bfs = boost::filesystem;

AttrTokenizeWrapper::AttrTokenizeWrapper()
    : isDictLoaded_(false)
{

}

AttrTokenizeWrapper::~AttrTokenizeWrapper()
{

}

AttrTokenizeWrapper* AttrTokenizeWrapper::get()
{
    return izenelib::util::Singleton<AttrTokenizeWrapper>::get();
}

bool AttrTokenizeWrapper::loadDictFiles(const std::string& dictDir)
{
    if (isDictLoaded_)
        return true;

    dictDir_ = dictDir;
    LOG(INFO) << "Start loading attr_tokenize dictionaries in " << dictDir_;
    const bfs::path dirPath(dictDir_);

    try
    {
        attr_tokenizer_.reset(new ilplib::knlp::AttributeTokenize( dirPath.string() ));
        LOG(INFO) << "load /single_term2cate.mapping" ;
        std::string queryCate = "/single_term2cate.mapping";
        queryMultiCatesDict_.reset(new ilplib::knlp::VectorDictionary(dictDir_ + queryCate));
    }
    catch (const std::exception& e)
    {
        LOG(ERROR) << "exception: " << e.what()
                   << ", dictDir: " << dictDir_;
        return false;
    }

    isDictLoaded_ = true;
    LOG(INFO) << "Finished loading attr_tokenize dictionaries.";

    return true;
}

void AttrTokenizeWrapper::attr_tokenize_index(
    const std::string& title,
    const std::string& attr,
    const std::string& cate,
    const std::string& ocate,
    const std::string& source,
    std::vector<std::pair<std::string, double> >& tokenScoreList)
{
    attr_tokenizer_->tokenize(title, attr, cate, ocate, source, tokenScoreList);
}

void AttrTokenizeWrapper::attr_tokenize(
    const std::string& Q,
    std::vector<std::pair<std::string, int> >& tokenList, bool do_subtok)
{
    attr_tokenizer_->tokenize(Q, tokenList, do_subtok);
}

double AttrTokenizeWrapper::att_name_weight(
    const std::string& attr_name,
    const std::string& cate)
{
    return attr_tokenizer_->att_weight(attr_name, cate);
}

double AttrTokenizeWrapper::att_value_weight(
    const std::string& attr_name,
    const std::string& attr_value,
    const std::string& cate)
{
    return attr_tokenizer_->att_weight(attr_name, attr_value, cate);
}

std::vector<char*>** AttrTokenizeWrapper::get_TermCategory(const std::string& query)
{
    if (!queryMultiCatesDict_)
        return NULL;
    return queryMultiCatesDict_->value(KString(query), true);
}

ext: cpp


text:
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     https://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 <sstream>

#include <boost/test/included/unit_test_framework.hpp>
#include <boost/test/unit_test.hpp>

#include "Compiler.hh"
#include "ValidSchema.hh"

// Assert that empty defaults don't make json schema compilation violate bounds
// checks, as they did in AVRO-1853. Please note that on Linux bounds are only
// checked in Debug builds (CMAKE_BUILD_TYPE=Debug).
void testEmptyBytesDefault() {
    std::string input = "{\n\
    \"type\": \"record\",\n\
    \"name\": \"testrecord\",\n\
    \"fields\": [\n\
        {\n\
            \"name\": \"testbytes\",\n\
            \"type\": \"bytes\",\n\
            \"default\": \"\"\n\
        }\n\
    ]\n\
}\n\
";
    std::string expected = "{\n\
    \"type\": \"record\",\n\
    \"name\": \"testrecord\",\n\
    \"fields\": [\n\
        {\n\
            \"name\": \"testbytes\",\n\
            \"type\": \"bytes\",\n\
            \"default\": \"\"\n\
        }\n\
    ]\n\
}\n\
";

    avro::ValidSchema schema = avro::compileJsonSchemaFromString(input);
    std::ostringstream actual;
    schema.toJson(actual);
    BOOST_CHECK_EQUAL(expected, actual.str());
}

void test2dArray() {
    std::string input = "{\n\
    \"type\": \"array\",\n\
    \"items\": {\n\
        \"type\": \"array\",\n\
        \"items\": \"double\"\n\
    }\n\
}\n";

    std::string expected = "{\n\
    \"type\": \"array\",\n\
    \"items\": {\n\
        \"type\": \"array\",\n\
        \"items\": \"double\"\n\
    }\n\
}\n\
";
    avro::ValidSchema schema = avro::compileJsonSchemaFromString(input);
    std::ostringstream actual;
    schema.toJson(actual);
    BOOST_CHECK_EQUAL(expected, actual.str());
}

boost::unit_test::test_suite *
init_unit_test_suite(int argc, char *argv[]) {
    using namespace boost::unit_test;

    test_suite *ts = BOOST_TEST_SUITE("Avro C++ unit tests for Compiler.cc");
    ts->add(BOOST_TEST_CASE(&testEmptyBytesDefault));
    ts->add(BOOST_TEST_CASE(&test2dArray));
    return ts;
}

ext: cc

max_stars_repo_name: arenadata/avro

max_issues_repo_name: arenadata/avro

max_forks_repo_name: arenadata/avro


text:
/*=============================================================================
    Copyright (c) 2002-2003 Joel de Guzman
    Copyright (c) 2002-2003 Hartmut Kaiser
    http://spirit.sourceforge.net/

  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)
=============================================================================*/
#if !defined(BOOST_SPIRIT_TRAVERSE_HPP)
#define BOOST_SPIRIT_TRAVERSE_HPP

#include <boost/spirit/home/classic/meta/impl/traverse.ipp>
#include <boost/spirit/home/classic/namespace.hpp>

namespace boost {
namespace spirit {

BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN

///////////////////////////////////////////////////////////////////////////
//
//  Post-order traversal of auxilliary parsers.
//
///////////////////////////////////////////////////////////////////////////
struct post_order {
  //  Return the parser type, which is generated as the result of the
  //  traverse function below.

  template <typename MetaT, typename ParserT> struct result {
    typedef typename traverse_post_order_return<
        MetaT, ParserT, traverse_post_order_env<0, 0, 0, 0>>::type type;
  };

  //  Traverse a given parser and refactor it with the help of the given
  //  MetaT metafunction template.

  template <typename MetaT, typename ParserT>
  static typename result<MetaT, ParserT>::type
  traverse(MetaT const &meta_, ParserT const &parser_) {
    typedef typename ParserT::parser_category_t parser_category_t;
    return impl::traverse_post_order<parser_category_t>::generate(
        meta_, parser_, traverse_post_order_env<0, 0, 0, 0>());
  }
};

///////////////////////////////////////////////////////////////////////////
//
//  Transform policies
//
//      The following policy classes could be used to assemble some new
//      transformation metafunction which uses identity transformations
//      for some parser_category type parsers.
//
///////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////
//  transform plain parsers
template <typename TransformT> struct plain_identity_policy {
  template <typename ParserT, typename EnvT> struct plain_result {
    // plain parsers should be embedded and returned correctly
    typedef typename ParserT::embed_t type;
  };

  template <typename ParserT, typename EnvT>
  typename parser_traversal_plain_result<TransformT, ParserT, EnvT>::type
  generate_plain(ParserT const &parser_, EnvT const & /*env*/) const {
    return parser_;
  }
};

//////////////////////////////////
//  transform unary parsers
template <typename UnaryT, typename SubjectT>
struct unary_identity_policy_return {
  typedef typename UnaryT::parser_generator_t parser_generator_t;
  typedef typename parser_generator_t ::template result<SubjectT>::type type;
};

template <typename TransformT> struct unary_identity_policy {
  template <typename UnaryT, typename SubjectT, typename EnvT>
  struct unary_result {
    typedef typename unary_identity_policy_return<UnaryT, SubjectT>::type type;
  };

  template <typename UnaryT, typename SubjectT, typename EnvT>
  typename parser_traversal_unary_result<TransformT, UnaryT, SubjectT,
                                         EnvT>::type
  generate_unary(UnaryT const &, SubjectT const &subject_,
                 EnvT const & /*env*/) const {
    typedef typename UnaryT::parser_generator_t parser_generator_t;
    return parser_generator_t::template generate<SubjectT>(subject_);
  }
};

//////////////////////////////////
//  transform action parsers
template <typename TransformT> struct action_identity_policy {
  template <typename ActionT, typename SubjectT, typename EnvT>
  struct action_result {
    typedef action<SubjectT, typename ActionT::predicate_t> type;
  };

  template <typename ActionT, typename SubjectT, typename EnvT>
  typename parser_traversal_action_result<TransformT, ActionT, SubjectT,
                                          EnvT>::type
  generate_action(ActionT const &action_, SubjectT const &subject_,
                  EnvT const & /*env*/) const {
    return subject_[action_.predicate()];
  }
};

//////////////////////////////////
//  transform binary parsers
template <typename BinaryT, typename LeftT, typename RightT>
struct binary_identity_policy_return {
  typedef typename BinaryT::parser_generator_t parser_generator_t;
  typedef
      typename parser_generator_t ::template result<LeftT, RightT>::type type;
};

template <typename TransformT> struct binary_identity_policy {
  template <typename BinaryT, typename LeftT, typename RightT, typename EnvT>
  struct binary_result {

    typedef typename binary_identity_policy_return<BinaryT, LeftT, RightT>::type
        type;
  };

  template <typename BinaryT, typename LeftT, typename RightT, typename EnvT>
  typename parser_traversal_binary_result<TransformT, BinaryT, LeftT, RightT,
                                          EnvT>::type
  generate_binary(BinaryT const &, LeftT const &left_, RightT const &right_,
                  EnvT const & /*env*/) const {
    typedef typename BinaryT::parser_generator_t parser_generator_t;
    return parser_generator_t::template generate<LeftT, RightT>(left_, right_);
  }
};

///////////////////////////////////////////////////////////////////////////
//
//  transform_policies template
//
//      The transform_policies template metafunction could serve as a
//      base class for new metafunctions to be passed to the traverse meta
//      template (see above), where only minimal parts have to be
//      overwritten.
//
///////////////////////////////////////////////////////////////////////////

template <typename TransformT,
          typename PlainPolicyT = plain_identity_policy<TransformT>,
          typename UnaryPolicyT = unary_identity_policy<TransformT>,
          typename ActionPolicyT = action_identity_policy<TransformT>,
          typename BinaryPolicyT = binary_identity_policy<TransformT>>
struct transform_policies : public PlainPolicyT,
                            public UnaryPolicyT,
                            public ActionPolicyT,
                            public BinaryPolicyT {};

///////////////////////////////////////////////////////////////////////////
//
//  Identity transformation
//
//      The identity_transform metafunction supplied to the traverse
//      template will generate a new parser, which will be exactly
//      identical to the parser given as the parameter to the traverse
//      metafunction. I.e. the following conceptual 'equation' will be
//      always true:
//
//      some_parser ==
//          post_order::traverse(identity_transform(), some_parser)
//
///////////////////////////////////////////////////////////////////////////

struct identity_transform : transform_policies<identity_transform> {};

BOOST_SPIRIT_CLASSIC_NAMESPACE_END

} // namespace spirit
} // namespace boost

#endif // !defined(BOOST_SPIRIT_TRAVERSE_HPP)

ext: hpp

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#ifndef IMAGE_SOURCE_CAMERA_INFO_HPP
#define IMAGE_SOURCE_CAMERA_INFO_HPP

#include <string>

#include <camera_info_manager/camera_info_manager.h>
#include <image_transport/image_transport.h>
#include <image_transport/subscriber.h>
#include <image_transport/transport_hints.h>
#include <nodelet/nodelet.h>
#include <ros/node_handle.h>
#include <ros/publisher.h>
#include <sensor_msgs/CameraInfo.h>
#include <sensor_msgs/Image.h>

#include <boost/scoped_ptr.hpp>

namespace image_source {

class CameraInfo : public nodelet::Nodelet {
public:
  CameraInfo() {}

  virtual ~CameraInfo() {}

protected:
  virtual void onInit() {
    ros::NodeHandle &nh(getNodeHandle());
    ros::NodeHandle &pnh(getPrivateNodeHandle());
    image_transport::ImageTransport it(nh);

    info_manager_.reset(new camera_info_manager::CameraInfoManager(
        nh, pnh.param< std::string >("camera_name", "camera"),
        pnh.param< std::string >("camera_info_url", "")));
    frame_id_ = pnh.param< std::string >("frame_id", "");

    publisher_ = nh.advertise< sensor_msgs::CameraInfo >("camera_info", 1, true);

    const image_transport::TransportHints default_hints;
    subscriber_ = it.subscribe("image_in", 1, &CameraInfo::publish, this,
                               image_transport::TransportHints(default_hints.getTransport(),
                                                               default_hints.getRosHints(), pnh));
  }

  void publish(const sensor_msgs::ImageConstPtr &image) {
    const sensor_msgs::CameraInfoPtr info(
        new sensor_msgs::CameraInfo(info_manager_->getCameraInfo()));
    info->header.stamp = image->header.stamp;
    info->header.frame_id = frame_id_;
    publisher_.publish(info);
  }

protected:
  boost::scoped_ptr< camera_info_manager::CameraInfoManager > info_manager_;
  std::string frame_id_;

  ros::Publisher publisher_;
  image_transport::Subscriber subscriber_;
};

} // namespace image_source

#endif


text:
// ==========================================================================
// Paradice Active Encounter
//
// Copyright (C) 2013 Matthew Chaplain, All Rights Reserved.
//
// Permission to reproduce, distribute, perform, display, and to prepare
// derivitive works from this file under the following conditions:
//
// 1. Any copy, reproduction or derivitive work of any part of this file
//    contains this copyright notice and licence in its entirety.
//
// 2. The rights granted to you under this license automatically terminate
//    should you attempt to assert any patent claims against the licensor
//    or contributors, which in any way restrict the ability of any party
//    from using this software or portions thereof in any form under the
//    terms of this license.
//
// Disclaimer: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
//             KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//             WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
//             PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//             OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
//             OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
//             OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//             SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ==========================================================================
#ifndef PARADICE_ACTIVE_ENCOUNTER_HPP_
#define PARADICE_ACTIVE_ENCOUNTER_HPP_

#include "paradice/beast.hpp"
#include "paradice/character.hpp"
#include "paradice/dice_roll_parser.hpp"
#include <boost/variant.hpp>
#include <deque>
#include <string>
#include <vector>

namespace paradice {

//* =========================================================================
/// \brief A structure to represent an active in-game encounter.
//* =========================================================================
struct active_encounter
{
    struct player
    {
        std::weak_ptr<character> character_;
        std::string name_;
    };

    typedef boost::variant<
        player,
        std::shared_ptr<beast>
    > participant;

    struct entry
    {
        participant             participant_;
        std::string             annotation_;
        std::deque<dice_result> roll_data_;
        odin::u32               id_;
    };

    std::vector<entry> entries_;
};

//* =========================================================================
/// \brief Add a new participant to the encounter.
//* =========================================================================
void add_participant(
    std::shared_ptr<active_encounter> const &enc
  , active_encounter::participant const &part);

//* =========================================================================
/// \brief Adds a character to the encounter.
//* =========================================================================
void add_character(
    std::shared_ptr<active_encounter> const &enc
  , std::shared_ptr<character> const &ch);

//* =========================================================================
/// \brief Adds a beast (clones it first) to the encounter.
//* =========================================================================
void add_beast(
    std::shared_ptr<active_encounter> const &enc
  , std::shared_ptr<paradice::beast> const &beast);

}

#endif


text:
//------------------------------------------------------------------------------
/*
    This file is part of rippled: https://github.com/ripple/rippled
    Copyright (c) 2012-2016 Ripple Labs Inc.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose  with  or without fee is hereby granted, provided that the above
    copyright notice and this permission notice appear in all copies.

    THE  SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF
    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

#include <BeastConfig.h>
#include <casinocoin/protocol/JsonFields.h>
#include <test/jtx.h>
#include <casinocoin/beast/unit_test.h>

#include <boost/format.hpp>

namespace casinocoin {

namespace test {

namespace validator_data {
static auto const public_key =
    "nHD3pRojfDnPNyzMXsaj5hJkVRSTzG6RG5XJPq1EercmGAEyAe8Y";

static auto const token =
        "eyJtYW5pZmVzdCI6IkpBQUFBQUZ4SWUzbzhEeGhCMjhsejdOa0xCMWY0UkVEbHNWTlVESUpk\n"
        "SWFzbjkwaGRTVCtFbk1oQTN2dEpxbmtDdHM4cUgxZnpSRjdZUzVMTEtpYWpTMzBMdWJPQVlx\n"
        "UVYvY0Nka2N3UlFJaEFLSStDc2c4ZENYcGJ4T1o2WnFndndpRVBFeHd6YlR2c1MyK0I2WGdF\n"
        "V1FxQWlBcE83Rm1kNGwzNGxzNmw2TEZ1SHJ6VDc1K2pKTm04QXV1Skk3SUh5RXNoWEFTUUo3\n"
        "YVI2c2FjWEQ5bXNqVS93NmtiWVFnR1c4ZlIrSnF2b2JmakxPUXBDbkJEcGxTVUloM2pKSHBn\n"
        "dldYQTNnREUzbjNJTzZOYnhjTXJ3K0JqVHA0amdjPSIsInZhbGlkYXRpb25fc2VjcmV0X2tl\n"
        "eSI6IkFGRDlDOTJCMzFDQzk1NkQ1Q0QzQUYwN0UxMUZBRDFBRDEzNzQwRTk5MDkyQUZDNjQ4\n"
        "MDlENzEzRkU5Q0M2ODgifQ==\n";
}

class ServerInfo_test : public beast::unit_test::suite
{
public:
    static
    std::unique_ptr<Config>
    makeValidatorConfig()
    {
        auto p = std::make_unique<Config>();
        boost::format toLoad(R"rippleConfig(
[validator_token]
%1%

[validators]
%2%
)rippleConfig");

        p->loadFromString (boost::str (
            toLoad % validator_data::token % validator_data::public_key));

        setupConfigForUnitTests(*p);

        return p;
    }

    void testServerInfo()
    {
        using namespace test::jtx;

        {
            Env env(*this);
            auto const result = env.rpc("server_info", "1");
            BEAST_EXPECT(!result[jss::result].isMember (jss::error));
            BEAST_EXPECT(result[jss::status] == "success");
            BEAST_EXPECT(result[jss::result].isMember(jss::info));
        }
        {
            Env env(*this, makeValidatorConfig());
            auto const result = env.rpc("server_info", "1");
            BEAST_EXPECT(!result[jss::result].isMember (jss::error));
            BEAST_EXPECT(result[jss::status] == "success");
            BEAST_EXPECT(result[jss::result].isMember(jss::info));
            BEAST_EXPECT(result[jss::result][jss::info]
                [jss::pubkey_validator] == validator_data::public_key);
        }
    }

    void run ()
    {
        testServerInfo ();
    }
};

BEAST_DEFINE_TESTSUITE(ServerInfo,app,casinocoin);

} // test
} // casinocoin

max_stars_repo_name: MassICTBV/casinocoind

max_issues_repo_name: MassICTBV/casinocoind

max_forks_repo_name: MassICTBV/casinocoind


text:
//
// $Id: PeptideID_pepXML.hpp 3095 2011-11-01 21:12:23Z broter $
//
//
// Original author: Robert Burke <robert.burke@cshs.org>
//
// Copyright 2007 Spielberg Family Center for Applied Proteomics
//   Cedars-Sinai Medical Center, Los Angeles, California  90048
//
// 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.
//

#ifndef _PEPTIDEID_PEPXML_HPP_
#define _PEPTIDEID_PEPXML_HPP_

#include "pwiz/utility/misc/Export.hpp"
#include <map>
#include <boost/shared_ptr.hpp>

#include "PeptideID.hpp"

namespace pwiz {
namespace peptideid {

/// This class allows access to identified proteins in PeptideProphet files.

/// A PeptideID_pepXML object is contructed with either the path to a
/// PeptideProphet format file (*.pep.xml), or an std::istream open to
/// the beginning of a pep.xml file.

class PWIZ_API_DECL PeptideID_pepXml : public PeptideID
{
public:
    /// Constructor taking path to input file in std::string.
    PeptideID_pepXml(const std::string& filename);

    /// Constructor taking path to input file from const char*.
    PeptideID_pepXml(const char* filename);

    /// Constructor taking std::istream as input.
    PeptideID_pepXml(std::istream* in);

    /// Destructor.
    virtual ~PeptideID_pepXml() {}

    /// Returns the Record object associated with the given nativeID.

    /// A range_error is thrown if the nativeID isn't associated with
    /// a Record.
    virtual Record record(const Location& location) const;

    virtual std::multimap<double, boost::shared_ptr<PeptideID::Record> >::const_iterator
        record(double retention_time_sec) const;

    virtual Iterator begin() const;
    virtual Iterator end() const;

private:
    class Impl;
    boost::shared_ptr<Impl> pimpl;

};

} // namespace peptideid
} // namespace pwiz

#endif // _PEPTIDEID_PEPXML_HPP_

max_stars_repo_name: edyp-lab/pwiz-mzdb

max_issues_repo_name: shze/pwizard-deb

max_forks_repo_name: shze/pwizard-deb


text:
#pragma once

#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>

#include "Grid.hpp"
#include "Entities/Entity.hpp"
#include "Utility/Vector3D.hpp"
#include "Entities/Block.hpp"
#include "Entities/Player.hpp"

namespace CraftWorld {
	using EntityGrid = Grid<Entities::Entity>;

	/**
	 * An area of the World that contains Entities on a 3D grid.
	 */
	class Chunk :
		public EntityGrid {
			friend boost::serialization::access;

			/**
			 * Serializes the Chunk.
			 * @tparam ArchiveType The type of archive used for serialization.
			 * @param archive The archive used for serialization.
			 * @param version The version of the serialization algorithm.
			 */
			template<typename ArchiveType>
			void serialize(ArchiveType& archive, const unsigned int& version) {
				// We need to explicitly register these types as they're stored as pointers to their base class
				archive.register_type(static_cast<Entities::Block*>(nullptr));
				archive.register_type(static_cast<Entities::Player*>(nullptr));

				archive & BOOST_SERIALIZATION_BASE_OBJECT_NVP(EntityGrid);
			}

		public:
			/**
			 * Generates a new Chunk.
			 * @param blockSize The amount of Blocks the Chunk should be able to contain, in every dimension.
			 * @return The new Chunk.
			 */
			static Chunk generate(const Utility::Vector3D<int>& blockSize);

			/**
			 * Creates a new Chunk.
			 */
			Chunk() = default;

			/**
			 * Creates a new Chunk.
			 * @param blockSize The amount of Blocks the Chunk should be able to contain, in every dimension.
			 */
			Chunk(const Utility::Vector3D<int>& blockSize);

			/**
			 * Performs a tick for all Entitites in the Chunk.
			 */
			void update();

			/**
			 * Checks if the Chunk contains only air blocks.
			 * @return Whether the Chunk is empty.
			 */
			bool isEmpty() const;
	};
}

max_stars_repo_name: Adeelala/craftworld

max_issues_repo_name: Adeelala/craftworld

max_forks_repo_name: Adeelala/craftworld


text:
#pragma once
#include <memory>
#include <chrono>
#include <type_traits>
#include <system_error>

#include <boost/predef.h>

#include <ext/config.hpp>
#include <ext/net/socket_fwd.hpp>
#include <ext/unique_handle.hpp>

namespace ext::net
{
	extern const int af_unspec;  // AF_UNSPEC
	extern const int af_inet;    // AF_INET
	extern const int af_inet6;   // AF_INET6

	extern const int sock_stream;    // SOCK_STREAM
	extern const int sock_dgram;     // SOCK_DGRAM
	extern const int sock_seqpacket; // SOCK_SEQPACKET

	extern const int msg_nosignal;   // MSG_NOSIGNAL or 0 if not defined

#if BOOST_OS_WINDOWS

	using addrinfo_type = addrinfoW;
	using sockaddr_type = sockaddr;

	/// winsock initialization functons, brouht here for windows include isolation
	/// calss WSAstartup and returns call result
	int wsastartup(std::uint16_t version);
	/// calls WSAstartup with version 2.2.
	/// if call ends with failure - prints error message into std::cerr and calls std::exit(EXIT_FAILURE).
	/// For better control - call directly WSAStartup or int wsastartup(std::uint16_t version)
	void wsastartup();
	/// calls WSACleanup
	void wsacleanup();

	/// Initializes libraries needed for working with sockets.
	/// This are winsock2 and, if enabled, OpenSSL.
	/// In fact calls ext::net::wsastratup(); ext::openssl_init()
	void socket_stream_init();
	/// Deinitializes libraries needed for working with sockets.
	/// This are winsock2 and, if enabled, OpenSSL.
	/// In fact calls ext::net::wsacleanup(); ext::openssl_cleanup()
	void socket_stream_cleanup();

#else

	using addrinfo_type = addrinfo;
	using sockaddr_type = sockaddr;

	/// Initializes libraries needed for working with sockets.
	/// This is, if enabled, OpenSSL. In fact calls ext::openssl_init()
	void socket_stream_init();
	/// Deinitializes libraries needed for working with sockets.
	/// This is, if enabled, OpenSSL. In fact calls ext::openssl_cleanup()
	void socket_stream_cleanup();

#endif

	/// socket error condition, this is NOT error codes,
	/// this is convenience conditions socket can be tested on.
	///
	/// you should use them like:
	///  * if (ss.last_error() == sock_errc::error) std::cerr << ss.last_error ...
	///  * if (ss.last_error() == sock_errc::regular) { ... process result ... }
	enum class sock_errc
	{
		eof         = 1,   /// socket eof, for example recv return 0, or OpenSSL returned SSL_ERR_ZERO_RETURN
		would_block = 2,   /// operation would block, not a error
		timeout     = 3,   /// operation(connect, read, write, shutdown) timeout
		regular     = 4,   /// no a error, code == 0 or some error which is not critical, like eof(currently only eof, would_block)
		error       = 5,   /// opposite of regular, some bad unexpected error, which breaks normal flow, timeout, system error, etc
		ssl_error   = 6,   /// ssl related error(but not openssl_error::zero_return)
	};

	const std::error_category & socket_condition_category() noexcept;

	/// integration with system_error
	inline std::error_code make_error_code(sock_errc val)           noexcept { return {static_cast<int>(val), socket_condition_category()}; }
	inline std::error_condition make_error_condition(sock_errc val) noexcept { return {static_cast<int>(val), socket_condition_category()}; }
}

namespace std
{
	template <>
	struct is_error_condition_enum<ext::net::sock_errc>
		: std::true_type {};
}

namespace ext::net
{
	/// not a socket/invalid socket value
	constexpr socket_handle_type invalid_socket = -1;

	/// on POSIX systems - return ::close(sock)
	/// on WINDOWS       - return ::closesocket(sock);
	int close(socket_handle_type sock);

	struct addrinfo_deleter
	{
		void operator()(addrinfo_type * ptr) const noexcept;
	};

	struct socket_closer
	{
		static void close(socket_handle_type sock) noexcept { ext::net::close(sock); }
		static auto emptyval() noexcept -> socket_handle_type { return invalid_socket; }
	};

	using addrinfo_uptr = std::unique_ptr<addrinfo_type, addrinfo_deleter>;
	using socket_uptr = ext::unique_handle<socket_handle_type, socket_closer>;

	// special tag type, to disambiguate some overloaded constructors accepting socket handles(int type) and port(unsigned short type)
	// ext::net::listener listener(handle_arg, handle);
	struct handle_arg_type {} constexpr handle_arg;

	/// error category for network address and service translation.
	/// EAI_* codes, gai_strerror
	const std::error_category & gai_error_category();

	/// returns last socket error
	int last_socket_error() noexcept;
	/// returns socket error category:
	/// on POSIX systems it's std::generic_category(), or windows - std::system_category
	const std::error_category & socket_error_category() noexcept;
	/// returns last socket error
	std::error_code last_socket_error_code() noexcept;

	BOOST_NORETURN void throw_socket_error(int code, const char * errmsg);
	BOOST_NORETURN void throw_socket_error(int code, const std::string & errmsg);
	BOOST_NORETURN void throw_last_socket_error(const std::string & errmsg);
	BOOST_NORETURN void throw_last_socket_error(const char * errmsg);

	std::error_code socket_rw_error(int res, int last_error = last_socket_error());

#ifdef EXT_ENABLE_OPENSSL
	std::error_code socket_ssl_rw_error(int res, SSL * ssl);
#endif

	void set_port(addrinfo_type * addr, unsigned short port);
	auto get_port(addrinfo_type * addr) -> unsigned short;

	void make_timeval(std::chrono::steady_clock::duration val, timeval & tv);
	int poll_mktimeout(std::chrono::steady_clock::duration val);

	/// overflow safe timeout addition, if adding timeout will overflow - returns std::chrono::steady_clock::time_point::max()
	auto add_timeout(std::chrono::steady_clock::time_point tp, std::chrono::steady_clock::duration timeout) -> std::chrono::steady_clock::time_point;

	/// ::inet_ntop wrapper, все строки в utf8
	/// @Throws std::system_error в случае системной ошибки
	void inet_ntop(const sockaddr * addr, std::string & str, unsigned short & port);
	auto inet_ntop(const sockaddr * addr) -> std::pair<std::string, unsigned short>;

#if BOOST_OS_WINDOWS
	/// ::inet_ntop wrapper, все строки в utf16
	/// @Throws std::system_error в случае системной ошибки
	///         ext::codecvt_convert::conversion_failure(std::runtime_error derived)
	///              при ошибках конвертации utf-8 <-> utf-16
	void inet_ntop(const sockaddr * addr, std::wstring & wstr, unsigned short & port);
#endif

	/// ::inet_pton wrapper, все строки в utf8
	/// @Return false если входная строка содержит не валидный адрес
	/// @Throws std::system_error в случае системной ошибки
	bool inet_pton(int family, const char * addr, sockaddr * out);
	bool inet_pton(int family, const std::string & addr, sockaddr * out);

#if BOOST_OS_WINDOWS
	/// ::inet_pton wrapper для winsock платформы, все строки в utf16
	/// @Return false если входная строка содержит не валидный адрес
	/// @Throws std::system_error в случае системной ошибки
	///         ext::codecvt_convert::conversion_failure(std::runtime_error derived)
	///              при ошибках конвертации utf-8 <-> utf-16
	bool inet_pton(int family, const wchar_t * waddr, sockaddr * out);
	bool inet_pton(int family, const std::wstring & waddr, sockaddr * out);
#endif

	/// создает строку вида <ERR:code>, например <ENOTCONN:107>,
	/// поддерживает только ряд кодов, связанных с функциями получения/конвертация адресов: getpeername, getsockname, inet_pton, etc
	std::string make_addr_error_description(int err);
	/// возвращает строку адреса подключения вида $addr:$port, например 127.0.0.1:22, для ipv6 - [::1]:22
	/// в случае ошибок кидает исключение std::runtime_error / std::system_error
	std::string sock_addr(sockaddr * addr);
	/// safe версия sock_addr - не кидает ошибок(за исключением std::bad_alloc),
	/// в случае ошибки возвращает <ERR:code>. Например - <ENOTCONN:107>
	std::string sock_addr_noexcept(sockaddr * addr);
	/// возвращает порт подключения,
	/// если address family не поддерживает порт как таковой - кидает std::runtime_error / std::system_error
	unsigned short sock_port(sockaddr * addr);
	/// safe версия sock_port - не кидает исключений,
	/// если address family не поддерживает порт как таковой - возвращает 0
	unsigned short sock_port_noexcept(sockaddr * addr);

	/// \{
	///
	/// ::getaddrinfo wrapper, все строки в utf8
	///
	/// @Param host имя или адрес как в ::getaddrinfo
	/// @Param service/port имя сервиса или номер порта как в ::getaddrinfo
	/// @Param hints передается как есть в вызов ::getaddrinfo,
	///              null допустимое значение - в таком случае как привило используются некие default значение
	/// @Param err для nothrow overload, out параметр, тут будет ошибка, а возвращаемое значение будет null
	/// @Returns std::unique_ptr<addrinfo> resolved адрес, в случае ошибки - nullptr для error overloads
	/// @Throws std::system_error в случае системной ошибки

	addrinfo_uptr getaddrinfo(const char * host, const char * service, const addrinfo_type * hints);
	addrinfo_uptr getaddrinfo(const char * host, const char * service, const addrinfo_type * hints, std::error_code & err);

	inline addrinfo_uptr getaddrinfo(const char * host, const char * service)                          { return getaddrinfo(host, service, nullptr); }
	inline addrinfo_uptr getaddrinfo(const char * host, const char * service, std::error_code & err)   { return getaddrinfo(host, service, nullptr, err); }

	inline addrinfo_uptr getaddrinfo(const std::string & host, const std::string & service, std::error_code & err) { return getaddrinfo(host.c_str(), service.c_str(), err); }
	inline addrinfo_uptr getaddrinfo(const std::string & host, std::error_code & err)                              { return getaddrinfo(host.c_str(), nullptr, err); }
	inline addrinfo_uptr getaddrinfo(const std::string & host, const std::string & service)                        { return getaddrinfo(host.c_str(), service.c_str()); }
	inline addrinfo_uptr getaddrinfo(const std::string & host)                                                     { return getaddrinfo(host.c_str(), nullptr); }

#if BOOST_OS_WINDOWS
	addrinfo_uptr getaddrinfo(const wchar_t * host, const wchar_t * service, const addrinfo_type * hints);
	addrinfo_uptr getaddrinfo(const wchar_t * host, const wchar_t * service, const addrinfo_type * hints, std::error_code & err);

	inline addrinfo_uptr getaddrinfo(const wchar_t * host, const wchar_t * service)                           { return getaddrinfo(host, service, nullptr); }
	inline addrinfo_uptr getaddrinfo(const wchar_t * host, const wchar_t * service, std::error_code & err)    { return getaddrinfo(host, service, nullptr, err); }

	inline addrinfo_uptr getaddrinfo(const std::wstring & host, const std::wstring & service, std::error_code & err)  { return getaddrinfo(host.c_str(), service.c_str(), err); }
	inline addrinfo_uptr getaddrinfo(const std::wstring & host, std::error_code & err)                                { return getaddrinfo(host.c_str(), nullptr, err); }
	inline addrinfo_uptr getaddrinfo(const std::wstring & host, const std::wstring & service)                         { return getaddrinfo(host.c_str(), service.c_str()); }
	inline addrinfo_uptr getaddrinfo(const std::wstring & host)                                                       { return getaddrinfo(host.c_str(), nullptr); }
#endif

	/// \}

	/// Returns loopback addr with port = 0 for given address family, socket type and protocol.
	/// Resolution will be done with AI_ADDRCONFIG, so addr family in case of AF_UNSPEC, will depend on system configuration
	addrinfo_uptr loopback_addr(int address_family = af_unspec, int sock_type = 0, int sock_proto = 0);
	addrinfo_uptr loopback_addr(std::error_code & err, int address_family = af_unspec, int sock_type = sock_stream, int sock_proto = 0);

	/// manual implementation of socket pair function.
	/// This function creates listener with loopback address and zero port(port will be assigned by OS),
	/// connects socket to created listener and returns connected socket pair.
	void manual_socketpair(socket_handle_type fds[2], int address_family = af_unspec, int sock_type = 0, int sock_proto = 0);
	bool manual_socketpair(socket_handle_type fds[2], std::error_code & err, int address_family = af_unspec, int sock_type = 0, int sock_proto = 0);

	/// socket pair wrapper, if socketpair system call is not available on this platform, it will be done via manual_socketpair
	void socketpair(socket_handle_type fds[2], int address_family = af_unspec, int sock_type = 0, int sock_proto = 0);
	bool socketpair(socket_handle_type fds[2], std::error_code & err, int address_family = af_unspec, int sock_type = 0, int sock_proto = 0);
}

max_stars_repo_name: dmlys/netlib

max_issues_repo_name: dmlys/netlib

max_forks_repo_name: dmlys/netlib


text:
// Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#ifndef BOOST_HANA_TEST_AUTO_FOR_EACH_HPP
#define BOOST_HANA_TEST_AUTO_FOR_EACH_HPP

#include <boost/hana/assert.hpp>
#include <boost/hana/for_each.hpp>

#include "test_case.hpp"
#include <laws/base.hpp>

#include <vector>

TestCase test_for_each{[]{
    namespace hana = boost::hana;
    using hana::test::ct_eq;

    // Make sure the function is applied in left-to-right order.
    {
        auto check = [](auto ...xs) {
            std::vector<int> seen{};
            hana::for_each(MAKE_TUPLE(xs...), [&](int x) {
                seen.push_back(x);
            });
            BOOST_HANA_RUNTIME_CHECK(seen == std::vector<int>{xs...});
        };

        check();
        check(0);
        check(0, 1);
        check(0, 1, 2);
        check(0, 1, 2, 3);
        check(0, 1, 2, 3, 4);
    }

    // Make sure the function is never called when the sequence is empty.
    {
        struct undefined { };
        hana::for_each(MAKE_TUPLE(), undefined{});
    }

    // Make sure it works with heterogeneous sequences.
    {
        hana::for_each(MAKE_TUPLE(ct_eq<0>{}), [](auto) { });
        hana::for_each(MAKE_TUPLE(ct_eq<0>{}, ct_eq<1>{}), [](auto) { });
        hana::for_each(MAKE_TUPLE(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{}), [](auto) { });
        hana::for_each(MAKE_TUPLE(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{}, ct_eq<3>{}), [](auto) { });
    }

    // Make sure for_each is constexpr when used with a constexpr function
    // and constexpr arguments. This used not to be the case.
#ifndef MAKE_TUPLE_NO_CONSTEXPR
    {
        struct f { constexpr void operator()(int) const { } };
        constexpr int i = (hana::for_each(MAKE_TUPLE(1, 2, 3), f{}), 0);
        (void)i;
    }
#endif
}};

#endif // !BOOST_HANA_TEST_AUTO_FOR_EACH_HPP


text:
#include "physics/Collider.h"

#include <boost/format.hpp>

#include <btBulletCollisionCommon.h>

using namespace boost;

namespace epsilon
{
	Collider::Ptr Collider::CreatePlane(Vector3 normal, float constant)
	{
		return std::make_shared<Collider>(private_struct(), normal, constant);
	}

	Collider::Ptr Collider::CreateBox(Vector3 dimensions)
	{
		return std::make_shared<Collider>(private_struct(), dimensions);
	}

	Collider::Ptr Collider::CreateSphere(float radius)
	{
		return std::make_shared<Collider>(private_struct(), radius);
	}

	Collider::Ptr Collider::CreateCapsule(float radius, float height)
	{
		return std::make_shared<Collider>(private_struct(), radius, height);
	}

	/*
	Collider::Ptr Collider::CreateMesh()
	{
		return std::make_shared<Collider>(private_struct());
	}

	Collider::Ptr Collider::CreateTerrain()
	{
		return std::make_shared<Collider>(private_struct());
	}
	*/

	Collider::Collider(const private_struct &, Vector3 normal, float constant) :
		NodeComponent("PlaneCollider"),
		hasSetup(false),
		type(ColliderType::PLANE),
		normal(normal),
		constant(constant)
	{
	}

	Collider::Collider(const private_struct &, Vector3 dimensions) :
		NodeComponent("BoxCollider"),
		hasSetup(false),
		type(ColliderType::BOX),
		dimensions(dimensions)
	{
	}

	Collider::Collider(const private_struct &, float radius) :
		NodeComponent("SphereCollider"),
		hasSetup(false),
		type(ColliderType::SPHERE),
		radius(radius)
	{
	}

	Collider::Collider(const private_struct &, float radius, float height) :
		NodeComponent("CapsuleCollider"),
		hasSetup(false),
		type(ColliderType::CAPSULE),
		radius(radius),
		height(height)
	{
	}

	/*
	Collider::Collider(const private_struct &) :
		NodeComponent("MeshCollider"),
		hasSetup(false),
		type(ColliderType::MESH)
	{
	}

	Collider::Collider(const private_struct &) :
		NodeComponent("TerrainCollider"),
		hasSetup(false),
		type(ColliderType::TERRAIN)
	{
	}
	*/

	Collider::~Collider(void)
	{
		deletedCallback(GetId());
	}

	void Collider::OnSetParent()
	{
		snTransform = this->componentParent->GetComponent<Transform>();
		Setup();
	}

	void Collider::OnCreateRegister(const ColliderCreatedCallback& callback)
	{
		createdCallback = callback;
	}

	void Collider::OnDeleteRegister(const ColliderDeletedCallback& callback)
	{
		deletedCallback = callback;
	}

	void Collider::Setup()
	{
		// If the rigid body hasn't yet been setup, and there is a parent transform
		if (!hasSetup && snTransform)
		{
			//create a dynamic Collider
			switch (type)
			{
				case ColliderType::PLANE:
					colShape = new btStaticPlaneShape(btVector3(normal.x, normal.y, normal.z), constant);
					break;
				case ColliderType::BOX:
					colShape = new btBoxShape(btVector3(dimensions.x, dimensions.y, dimensions.z));
					break;
				case ColliderType::SPHERE:
					colShape = new btSphereShape(radius);
					break;
				case ColliderType::CAPSULE:
					colShape = new btCapsuleShape(radius, height);
					break;
				case ColliderType::MESH:
					//colShape = new btTriangleMeshShape(/* Mesh */);	// NYI
					break;
				case ColliderType::TERRAIN:
					//colShape = new btHeightfieldTerrainShape(btVector3(0.5f, 0.5f, 0.5f)); // NYI
					break;
			}

			createdCallback(GetId(), colShape);

			hasSetup = true;
		}
	}

	void Collider::UpdateFromBullet()
	{
		if (hasSetup)
		{

		}
	}

	void Collider::UpdateToBullet()
	{
		if (hasSetup)
		{

		}
	}
}

max_stars_repo_name: freneticmonkey/epsilonc

max_issues_repo_name: freneticmonkey/epsilonc

max_forks_repo_name: freneticmonkey/epsilonc


text:
/*
 * Copyright (C) 2014 Love Park Robotics, LLC
 *
 * 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 distribted 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 "o3d3xx/cmdline_opts.h"
#include <cstdint>
#include <functional>
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include "o3d3xx/camera.hpp"
#include "o3d3xx/version.h"

namespace po = boost::program_options;

o3d3xx::CmdLineOpts::CmdLineOpts(const std::string& description)
  : visible(description)
{
  // generic options
  po::options_description general("General");
  general.add_options()
    ("version,v", "Print version string and exit")
    ("help,h", "Produce help message");

  // options for connecting to the camera
  po::options_description connection_opts("Connection Information");
  connection_opts.add_options()
    ("ip",
     po::value<std::string>()->default_value(o3d3xx::DEFAULT_IP),
     "IP address of the camera")

    ("xmlrpc-port",
     po::value<std::uint32_t>()->default_value(o3d3xx::DEFAULT_XMLRPC_PORT),
     "XMLRPC port of the camera")

    ("password",
     po::value<std::string>()->default_value(o3d3xx::DEFAULT_PASSWORD),
     "Password for configuring the camera");

  this->visible.add(general).add(connection_opts);
}

int
o3d3xx::CmdLineOpts::Parse(int argc, const char **argv,
                           std::string *ip,
                           std::uint32_t *xmlrpc_port,
                           std::string *password,
                           std::function<void()> fn,
                           std::ostream& out)
{
  int retval = 1;
  int major, minor, patch;

  po::store(po::command_line_parser(argc, argv).
            options(this->visible).run(), this->vm);

  po::notify(this->vm);

  if (this->vm.count("help"))
    {
      out << this->visible << std::endl;
      retval = 0;
    }
  else if (this->vm.count("version"))
    {
      o3d3xx::version(&major, &minor, &patch);
      out << O3D3XX_LIBRARY_NAME
          << ": version=" << major << "."
          << minor << "." << patch << std::endl;
      retval = 0;
    }

  if (retval != 0)
    {
      if (ip != nullptr)
        {
          ip->assign(this->vm["ip"].as<std::string>());
        }

      if (xmlrpc_port != nullptr)
        {
          *xmlrpc_port = this->vm["xmlrpc-port"].as<std::uint32_t>();
        }

      if (password != nullptr)
        {
          password->assign(this->vm["password"].as<std::string>());
        }

      fn();
    }

  return retval;
}


text:
/* ----------------------------------------------------------------------------
 * Copyright 2017, Massachusetts Institute of Technology,
 * Cambridge, MA 02139
 * All Rights Reserved
 * Authors: Luca Carlone, et al. (see THANKS for the full author list)
 * See LICENSE for the license information
 * -------------------------------------------------------------------------- */

/**
 * @file   MeshOptimization.cpp
 * @brief  Optimizes vertices of a 3D mesh given depth data on a projective
 * setting (depth map, rgb-d, lidar).
 * @author Antoni Rosinol
 */

#include "kimera-vio/mesh/MeshOptimization.h"

#include <string>
#include <vector>

#include <Eigen/Core>

#include <opencv2/opencv.hpp>

#include <gtsam/geometry/Cal3_S2.h>
#include <gtsam/geometry/Pose3.h>
#include <gtsam/linear/GaussianFactorGraph.h>
#include <gtsam/nonlinear/Marginals.h>

#include "kimera-vio/common/vio_types.h"
#include "kimera-vio/frontend/Camera.h"
#include "kimera-vio/mesh/Mesh.h"
#include "kimera-vio/mesh/MeshOptimization-definitions.h"
#include "kimera-vio/mesh/MeshUtils.h"
#include "kimera-vio/mesh/Mesher-definitions.h"
#include "kimera-vio/utils/Macros.h"
#include "kimera-vio/utils/UtilsOpenCV.h"
#include "kimera-vio/visualizer/OpenCvVisualizer3D.h"
#include "kimera-vio/visualizer/Visualizer3D-definitions.h"

namespace VIO {

MeshOptimization::MeshOptimization(const MeshOptimizerType& solver_type,
                                   const MeshColorType&     mesh_color_type,
                                   Camera::ConstPtr         camera,
                                   OpenCvVisualizer3D::Ptr  visualizer)
    : visualizer_(visualizer), mesh_optimizer_type_(solver_type),
      mono_camera_(camera), body_pose_cam_(camera->getBodyPoseCam()),
      window_("Mesh Optimization"), mesh_color_type_(mesh_color_type)
{
    CHECK(camera);
    window_.setBackgroundColor(cv::viz::Color::white());
    window_.setFullScreen(true);
}

MeshOptimizationOutput::UniquePtr
MeshOptimization::spinOnce(const MeshOptimizationInput& input)
{
    return solveOptimalMesh(input.pcl, input.pcl_colors, input.mesh_2d);
}

void MeshOptimization::draw2dMeshOnImg(const Mesh2D&         mesh_2d,
                                       cv::Mat*              img,
                                       const cv::viz::Color& color,
                                       const size_t&         thickness,
                                       const int             line_type)
{
    CHECK_NOTNULL(img);
    CHECK_EQ(mesh_2d.getMeshPolygonDimension(), 3u);
    CHECK_GT(mesh_2d.getNumberOfPolygons(), 0u);
    // Draw the pixel on the image
    Mesh2D::Polygon polygon;
    for (size_t k = 0u; k < mesh_2d.getNumberOfPolygons(); k++) {
        CHECK(mesh_2d.getPolygon(k, &polygon));
        const Vertex2D& v0 = polygon.at(0).getVertexPosition();
        const Vertex2D& v1 = polygon.at(1).getVertexPosition();
        const Vertex2D& v2 = polygon.at(2).getVertexPosition();
        cv::line(*img, v0, v1, color, thickness, line_type);
        cv::line(*img, v1, v2, color, thickness, line_type);
        cv::line(*img, v2, v0, color, thickness, line_type);
    }
}

void MeshOptimization::draw3dMesh(const std::string& id,
                                  const Mesh3D&      mesh_3d,
                                  bool               display_as_wireframe,
                                  const double&      opacity)
{
    cv::Mat vertices_mesh;
    cv::Mat polygons_mesh;
    mesh_3d.getVerticesMeshToMat(&vertices_mesh);
    mesh_3d.getPolygonsMeshToMat(&polygons_mesh);
    cv::Mat colors_mesh = mesh_3d.getColorsMesh().t();  // Note the transpose.
    if (colors_mesh.empty()) {
        colors_mesh = cv::Mat(1u, mesh_3d.getNumberOfUniqueVertices(), CV_8UC3,
                              cv::viz::Color::yellow());
    }

    // Build visual mesh
    cv::viz::Mesh cv_mesh;
    cv_mesh.cloud    = vertices_mesh.t();
    cv_mesh.polygons = polygons_mesh;
    cv_mesh.colors   = colors_mesh;

    // Build widget mesh
    cv::viz::WMesh widget_cv_mesh(cv_mesh);
    widget_cv_mesh.setRenderingProperty(cv::viz::SHADING,
                                        cv::viz::SHADING_FLAT);
    widget_cv_mesh.setRenderingProperty(cv::viz::AMBIENT, 0);
    widget_cv_mesh.setRenderingProperty(cv::viz::LIGHTING, 1);
    widget_cv_mesh.setRenderingProperty(cv::viz::OPACITY, opacity);
    if (display_as_wireframe) {
        widget_cv_mesh.setRenderingProperty(cv::viz::REPRESENTATION,
                                            cv::viz::REPRESENTATION_WIREFRAME);
    }
    window_.showWidget(id.c_str(), widget_cv_mesh);
}

void MeshOptimization::collectTriangleDataPointsFast(
    const cv::Mat&        noisy_point_cloud,
    const Mesh2D&         mesh_2d,
    TriangleToDatapoints* triangles_to_datapoints_xyz,
    TriangleToPixels*     triangles_to_datapoints_pixels,
    size_t*               number_of_valid_datapoints)
{
    // Assumes ordered point cloud
    const size_t& img_height = noisy_point_cloud.rows;
    const size_t& img_width  = noisy_point_cloud.cols;
    const size_t& n_polys    = mesh_2d.getNumberOfPolygons();
    CHECK_GT(n_polys, 0u);
    CHECK_NOTNULL(triangles_to_datapoints_xyz)->reserve(n_polys);
    CHECK_NOTNULL(triangles_to_datapoints_pixels)->reserve(n_polys);
    *CHECK_NOTNULL(number_of_valid_datapoints) = 0u;

    Mesh2D::Polygon polygon;
    for (size_t k = 0u; k < n_polys; k++) {
        CHECK(mesh_2d.getPolygon(k, &polygon));
        const Vertex2D& vtx1 = polygon.at(0).getVertexPosition();
        const Vertex2D& vtx2 = polygon.at(1).getVertexPosition();
        const Vertex2D& vtx3 = polygon.at(2).getVertexPosition();

        // Loop over pixels inside the bounding box of the current triangle

        // 1. Find bounding box of triangle
        float xmin = min3(vtx1.x, vtx2.x, vtx3.x);
        float ymin = min3(vtx1.y, vtx2.y, vtx3.y);

        float xmax = max3(vtx1.x, vtx2.x, vtx3.x);
        float ymax = max3(vtx1.y, vtx2.y, vtx3.y);

        // Discard triangle out of screen
        // WARNING bcs of cv::Point2f convention x is the width...
        if (xmin > img_width - 1 || xmax < 0 || ymin > img_height - 1 ||
            ymax < 0) {
            LOG(ERROR) << "Triangle out of screen!:"
                       << "xmin: " << xmin << '\n'
                       << "xmax: " << xmax << '\n'
                       << "ymin: " << ymin << '\n'
                       << "ymax: " << ymax << '\n'
                       << "img_height" << img_height - 1 << '\n'
                       << "img_width" << img_width - 1;
            continue;
        }

        // be careful xmin/xmax/ymin/ymax can be negative. Don't cast to
        // uint32_t
        uint32_t x0 = std::max(int32_t(0), (int32_t)(std::floor(xmin)));
        uint32_t x1 =
            std::min(int32_t(img_width) - 1, (int32_t)(std::floor(xmax)));
        uint32_t y0 = std::max(int32_t(0), (int32_t)(std::floor(ymin)));
        uint32_t y1 =
            std::min(int32_t(img_height) - 1, (int32_t)(std::floor(ymax)));

        // 2. Loop over pixels in the bounding box
        /// Cache stuff
        float x12 = vtx1.x - vtx2.x;
        float y12 = vtx1.y - vtx2.y;
        float x23 = vtx2.x - vtx3.x;
        float y23 = vtx2.y - vtx3.y;
        float x31 = vtx3.x - vtx1.x;
        float y31 = vtx3.y - vtx1.y;
        for (uint32_t u = x0; u <= x1; ++u) {
            for (uint32_t v = y0; v <= y1; ++v) {
                // Check that pixel is in triangle
                float d1, d2, d3;
                bool  has_neg, has_pos;

                d1 = (u - vtx2.x) * y12 - x12 * (v - vtx2.y);
                d2 = (u - vtx3.x) * y23 - x23 * (v - vtx3.y);
                d3 = (u - vtx1.x) * y31 - x31 * (v - vtx1.y);

                has_neg = (d1 < 0) || (d2 < 0) || (d3 < 0);
                has_pos = (d1 > 0) || (d2 > 0) || (d3 > 0);

                KeypointCV pixel = cv::Point2f(u, v);
                CHECK_EQ(!(has_neg && has_pos),
                         pointInTriangle(pixel, vtx1, vtx2, vtx3));
                if (!(has_neg && has_pos)) {
                    // Point in triangle
                    const cv::Point3f& lmk =
                        noisy_point_cloud.at<cv::Point3f>(pixel);
                    if (isValidPoint(lmk, kMissingZ, kMinZ, kMaxZ)) {
                        (*triangles_to_datapoints_xyz)[k].push_back(lmk);
                        (*triangles_to_datapoints_pixels)[k].push_back(pixel);
                        ++(*number_of_valid_datapoints);
                    }
                }
            }  // loop over y
        }      // loop over x
    }
}

void MeshOptimization::collectTriangleDataPoints(
    const cv::Mat&        noisy_point_cloud,
    const Mesh2D&         mesh_2d,
    TriangleToDatapoints* corresp,
    TriangleToPixels*     pixel_corresp,
    size_t*               number_of_valid_datapoints)
{
    CHECK_NOTNULL(corresp);
    CHECK_NOTNULL(pixel_corresp);
    *CHECK_NOTNULL(number_of_valid_datapoints) = 0u;
    CHECK(mono_camera_);

    for (size_t u = 0u; u < noisy_point_cloud.cols; ++u) {
        for (size_t v = 0u; v < noisy_point_cloud.rows; ++v) {
            // 1. Project pointcloud to image (color img with projections)
            // aka get pixel coordinates for all points in pointcloud.
            // TODO(Toni): the projection of all points could be greatly
            // optimized by appending all points into a big matrix and
            // performing dense multiplication.
            const cv::Point3f& lmk = noisy_point_cloud.at<cv::Point3f>(v, u);
            if (isValidPoint(lmk, kMissingZ, kMinZ, kMaxZ)) {
                // Convert xyz to global coords (as they are given in camera
                // coords). transform from left cam frame of reference to body
                // because the camera projection function expects landmarks in
                // the body frame of reference!
                const gtsam::Point3& pt_body = body_pose_cam_.transformFrom(
                    gtsam::Point3(lmk.x, lmk.y, lmk.z));
                LandmarkCV lmk_cv;
                lmk_cv.x = pt_body.x();
                lmk_cv.y = pt_body.y();
                lmk_cv.z = pt_body.z();

                KeypointCV left_pixel;
                mono_camera_->project(lmk_cv, &left_pixel);
                CHECK_NEAR(left_pixel.x, static_cast<double>(u), 0.001);
                CHECK_NEAR(left_pixel.y, static_cast<double>(v), 0.001);

                if (visualizer_) {
                    // drawPixelOnImg(left_pixel, img_, cv::viz::Color::green(),
                    // 1u);
                }

                // 2. Generate correspondences btw points and triangles.
                // For each triangle in 2d Mesh
                // TODO(Toni): this can be greatly optimized by going on a per
                // triangle fashion and using halfplane checks on all points.
                Mesh2D::Polygon polygon;
                for (size_t k = 0; k < mesh_2d.getNumberOfPolygons(); k++) {
                    CHECK(mesh_2d.getPolygon(k, &polygon));
                    if (pointInTriangle(left_pixel,
                                        polygon.at(0).getVertexPosition(),
                                        polygon.at(1).getVertexPosition(),
                                        polygon.at(2).getVertexPosition())) {
                        // A point should only be in one triangle, once found,
                        // we can stop looping over the 2d mesh.
                        (*corresp)[k].push_back(lmk);
                        (*pixel_corresp)[k].push_back(left_pixel);
                        ++(*number_of_valid_datapoints);
                        break;
                    }
                }
            }
        }
    }
}

MeshOptimizationOutput::UniquePtr
MeshOptimization::solveOptimalMesh(const cv::Mat& noisy_pcl,
                                   const cv::Mat& pcl_colors,
                                   const Mesh2D&  mesh_2d)
{
    CHECK_GT(mesh_2d.getNumberOfPolygons(), 0);
    CHECK_GT(mesh_2d.getNumberOfUniqueVertices(), 0);
    CHECK_EQ(noisy_pcl.channels(), 3u);
    CHECK_EQ(noisy_pcl.size, pcl_colors.size);
    CHECK(!noisy_pcl.empty());
    CHECK(mono_camera_);

    // For visualization
    VisualizerOutput::UniquePtr output = VIO::make_unique<VisualizerOutput>();
    output->visualization_type_        = VisualizationType::kPointcloud;

    // Need to visualizeScene again because the image of the camera frustum
    // was updated
    if (visualizer_) {
        // Flatten and get colors for pcl
        cv::Mat viz_cloud(0, 1, CV_32FC3, cv::Scalar(0));
        cv::Mat colors_pcl = cv::Mat(0, 0, CV_8UC3, cv::viz::Color::red());
        CHECK_EQ(img_.type(), CV_8UC1);
        if (noisy_pcl.rows != 1u || noisy_pcl.cols != 1u) {
            LOG(ERROR) << "Reshaping noisy_pcl!";
            cv::Mat_<cv::Point3f> flat_pcl = cv::Mat(1, 0, CV_32FC3);
            for (int32_t v = 0u; v < noisy_pcl.rows; v++) {
                for (int32_t u = 0u; u < noisy_pcl.cols; u++) {
                    const cv::Point3f& lmk = noisy_pcl.at<cv::Point3f>(v, u);
                    if (isValidPoint(lmk)) {
                        flat_pcl.push_back(lmk);
                        colors_pcl.push_back(
                            cv::Vec3b::all(img_.at<uint8_t>(v, u)));
                    }
                }
            }
            viz_cloud = flat_pcl;
        }
        visualizer_->visualizePointCloud(
            viz_cloud, &output->widgets_,
            UtilsOpenCV::gtsamPose3ToCvAffine3d(body_pose_cam_), colors_pcl);
        // draw2dMeshOnImg(img_, mesh_2d);
        // spinDisplay();
    }

    /// Step 1: Collect all datapoints that fall within triangle
    LOG(INFO) << "Collecting triangle data points.";
    TriangleToDatapoints
                     triangles_to_datapoints_xyz;  // In left_cam_rect coords
    TriangleToPixels triangles_to_datapoints_pixels;
    size_t           number_of_valid_datapoints = 0;
    collectTriangleDataPointsFast(
        noisy_pcl, mesh_2d, &triangles_to_datapoints_xyz,
        &triangles_to_datapoints_pixels, &number_of_valid_datapoints);

    CHECK_GT(number_of_valid_datapoints, 3u);
    CHECK_GT(triangles_to_datapoints_xyz.size(), 0u);
    LOG_IF(ERROR,
           triangles_to_datapoints_xyz.size() != mesh_2d.getNumberOfPolygons())
        << "Every triangle should have some data points! (or maybe not "
           "really)";
    CHECK_EQ(triangles_to_datapoints_xyz.size(),
             triangles_to_datapoints_pixels.size());

    /// Step 2: Solve for the ys and build the Y matrix incrementally by
    /// looping over all triangles.
    LOG(INFO) << "Building optimization problem.";
    // This matrix has as columns the landmark ids, and as rows the ys of each
    // datapoint, with non-zeros only where a datapoint is associated to a
    // lmk.
    typedef std::unordered_map<Mesh2D::VertexId, Vertex3D> VtxIdToBearingVector;
    typedef std::unordered_map<Mesh2D::VertexId, Vertex2D> VtxIdToPixels;
    VtxIdToBearingVector vtx_ids_to_bearing_vectors;
    VtxIdToPixels        vtx_ids_to_pixels;

    // Mesh that will hold the reconstructed one
    Mesh3D reconstructed_mesh;

    // Create empty graph
    gtsam::GaussianFactorGraph factor_graph;

    // For each triangle in 2d Mesh (as long as non-degenerate).
    Mesh2D::Polygon polygon_2d;
    LOG_IF(ERROR,
           mesh_2d.getNumberOfPolygons() != triangles_to_datapoints_xyz.size())
        << "There are some undetermined triangles in the 2d mesh.";
    // VIT this needs to be static or out of the for loop above!
    // otw we overwrite previous rows in Y.
    std::map<gtsam::Key, size_t> vertex_supports;  //! Only for visualization.
    for (size_t tri_idx = 0; tri_idx < mesh_2d.getNumberOfPolygons();
         tri_idx++) {
        CHECK(mesh_2d.getPolygon(tri_idx, &polygon_2d));
        CHECK_EQ(polygon_2d.size(), 3);

        /// Step 2.1: Build bearing vector matrix of triangle and collect
        /// landmark
        /// ids.
        // List of landmark ids associated to the triangle vertices
        std::array<Mesh2D::VertexId, 3> vtx_ids;
        // 1 row with 3 columns: each column is a cv::Point3f
        // TODO(Toni): we are recalculating bearing vectors all the time
        // we should be calculating these only once...
        cv::Mat_<Vertex3D> triangle_bearing_vectors(1, 3);
        size_t             col = 0u;
        for (const auto& vtx : polygon_2d) {
            // Calculate bearing vectors from mesh 2d
            // vtx is pixel, get in bearing vectors?
            const Vertex2D& vtx_pixel = vtx.getVertexPosition();
            // This gets you the bearing vector in body coordinates
            cv::Point3f cv_bearing_vector_body_frame;
            getBearingVectorFrom2DPixel(vtx_pixel,
                                        &cv_bearing_vector_body_frame);

            Mesh2D::VertexId vtx_id;
            CHECK(mesh_2d.getVtxIdForLmkId(vtx.getLmkId(), &vtx_id));
            triangle_bearing_vectors[0][col]   = cv_bearing_vector_body_frame;
            vtx_ids_to_bearing_vectors[vtx_id] = cv_bearing_vector_body_frame;
            vtx_ids_to_pixels[vtx_id]          = vtx_pixel;
            vtx_ids[col]                       = vtx_id;
            col++;
        }

        /// Step 2.2: For each datapoint in current triangle solve for the ys
        /// and build big Y matrix
        // TODO(Toni): check for other degenerate configs such as all points
        // on a
        // line, or same spot or... We should use regularization to deal with
        // these
        // or maybe not if its neighbour triangles are fine.
        std::vector<cv::Point3f> triangle_datapoints_xyz_left_rect_cam_frame =
            triangles_to_datapoints_xyz[tri_idx];
        //! Pixels associated to a triangle that have a depth value (datapoint,
        //! measurements)
        KeypointsCV triangle_datapoints_pixel =
            triangles_to_datapoints_pixels[tri_idx];
        CHECK_EQ(triangle_datapoints_xyz_left_rect_cam_frame.size(),
                 triangle_datapoints_pixel.size());

        // Skip under-constrained since we do not have enough info to solve Ay=b
        if (triangle_datapoints_xyz_left_rect_cam_frame.size() < 3) {
            // ALTHOUGH WE COULD JUST USE AS PRIOR THE CURRENT DEPTH SAMPLE...
            LOG(ERROR)
                << "Degenerate case optimization problem, we need more than 3 "
                   "datapoints: offending triangle idx: "
                << tri_idx;
            continue;
        }

        VLOG(10) << "Adding "
                 << triangle_datapoints_xyz_left_rect_cam_frame.size()
                 << " datapoints to triangle with idx: " << tri_idx;
        switch (mesh_optimizer_type_) {
            case MeshOptimizerType::kGtsamMesh: {
                // Build factor graph on a per triangle basis
                for (size_t i = 0u; i < triangle_datapoints_pixel.size(); i++) {
                    const KeypointCV&  pixel = triangle_datapoints_pixel[i];
                    const cv::Point3f& lmk =
                        triangle_datapoints_xyz_left_rect_cam_frame[i];

                    // In principle, datapoints here are all valid, as filtered
                    // by the collect data points function
                    double inv_depth_meas = 1.0 / std::sqrt(lmk.dot(lmk));
                    // These should not be recomputed but cached when computing
                    // triangle rasterization pixels...
                    BaryCoord b0, b1, b2;
                    if (!barycentricCoordinates(vtx_ids_to_pixels[vtx_ids[0]],
                                                vtx_ids_to_pixels[vtx_ids[1]],
                                                vtx_ids_to_pixels[vtx_ids[2]],
                                                pixel, &b0, &b1, &b2)) {
                        // This fails for datapoints on the vertices, which I
                        // guess is good? Although we are discarding the actual
                        // depth of this point!
                        LOG(ERROR)
                            << "Query pixel: " << pixel << '\n'
                            << "vtx1 pixel: " << vtx_ids_to_pixels[vtx_ids[0]]
                            << '\n'
                            << "vtx2 pixel: " << vtx_ids_to_pixels[vtx_ids[1]]
                            << '\n'
                            << "vtx3 pixel: " << vtx_ids_to_pixels[vtx_ids[2]]
                            << '\n'
                            << "Outside triangle ";
                    }

                    //! Construct ternary factors  and them to factor graph
                    gtsam::Key      i1(vtx_ids[0]);
                    gtsam::Matrix11 A1(
                        b0);  //! barycentric coordinates of vtx 0
                    gtsam::Key      i2(vtx_ids[1]);
                    gtsam::Matrix11 A2(
                        b1);  //! barycentric coordinates of vtx 1
                    gtsam::Key      i3(vtx_ids[2]);
                    gtsam::Matrix11 A3(
                        b2);  //! barycentric coordinates of vtx 2
                    //! Inverse depth of datapoint
                    gtsam::Vector1        b(inv_depth_meas);
                    gtsam::SharedDiagonal noise_model_input =
                        gtsam::noiseModel::Diagonal::Sigmas(
                            gtsam::Vector1(kDepthMeasNoiseSigma));

                    //! one per data point influencing three variables
                    factor_graph += gtsam::JacobianFactor(
                        i1, A1, i2, A2, i3, A3, b, noise_model_input);

                    //! Count the number of points that support the vertices
                    //! (only for support visualization of the mesh).
                    vertex_supports[i1] += 1;
                    vertex_supports[i2] += 1;
                    vertex_supports[i3] += 1;
                }
            } break;
            default: {
                LOG(FATAL) << "Unknown mesh optimization type.";
            } break;
        }

        // check that the non-zero entries correspond to the adjacency
        // between
        // of the 2d mesh on a per row basis. I.e. each row should have
        // non-zero
        // entries only for cols (vtx_ids) which correspond to vtx_ids of an
        // actual triangle.
    }

    /// At this point you could drop columns (lmk_ids) for those that do
    /// not
    /// have enough measurements (although even with 0 measurements you
    /// should
    /// be able to constraint if neihbors have enough measurements).

    LOG(INFO) << "Solving optimization problem.";
    switch (mesh_optimizer_type_) {
        case MeshOptimizerType::kGtsamMesh: {
            if (kUseSpringEnergies) {
                //! Add spring energies for this triangle, but don't duplicate
                //! springs! Hence, use adjacency matrix to know where to put
                //! the springs.
                cv::Mat adjacency_matrix = mesh_2d.getAdjacencyMatrix();
                const gtsam::Vector1        kSpringRestLength(0);
                constexpr double            kSpringConstant = 1.0;
                const gtsam::Matrix11       A1(kSpringConstant);
                const gtsam::Matrix11       A2(-1.0 * kSpringConstant);
                const gtsam::SharedDiagonal kSpringNoiseModel =
                    gtsam::noiseModel::Diagonal::Sigmas(
                        gtsam::Vector1(kSpringNoiseSigma));
                // ASSUMEs that vtx ids are the indices of the adjacency matrix!
                for (size_t v = 0u; v < adjacency_matrix.rows; v++) {
                    gtsam::Key i1(v);
                    for (size_t u = 0u; u < adjacency_matrix.cols; u++) {
                        if (u < v) {
                            if (adjacency_matrix.at<uint8_t>(v, u) == 1u) {
                                // Vertices are connected!
                                gtsam::Key i2(u);
                                factor_graph += gtsam::JacobianFactor(
                                    i1, A1, i2, A2, kSpringRestLength,
                                    kSpringNoiseModel);
                            }
                        }
                        else {
                            CHECK_EQ(u, v);
                            // The matrix is symmetric, avoid adding duplicated
                            // springs.
                            break;
                        }
                    }
                }
            }

            // Solve linear factor graph Ax=b...
            // optimize the graph
            gtsam::VectorValues actual =
                factor_graph.optimize(boost::none, gtsam::EliminateQR);
            actual.print("Values after optimization");

            gtsam::VectorValues hessian = factor_graph.hessianDiagonal();

            // Find the max std deviation, just for visualization of variances
            // later.
            // double max_inv_depth = -std::numeric_limits<double>::max();
            // for (const auto& kv : actual) {
            //  if (kv.second[0] > max_inv_depth) max_inv_depth = kv.second[0];
            //}
            // double max_inv_variance_of_inv_depth =
            //    -std::numeric_limits<double>::max();
            // for (const auto& kv : hessian) {
            //  if (kv.second[0] > max_inv_depth) max_inv_depth = kv.second[0];
            //}
            // const double& max_variance_of_inv_depth =
            //    1.0 / max_inv_variance_of_inv_depth;
            // const double& max_variance_of_depth =
            //    max_variance_of_inv_depth *
            //    (1.0 / std::pow(max_inv_depth, 2));
            // const double& max_std_deviation =
            // std::sqrt(max_variance_of_depth);

            size_t max_vertex_support = 0u;
            for (auto it = vertex_supports.cbegin();
                 it != vertex_supports.cend(); ++it) {
                if (it->second > max_vertex_support) {
                    max_vertex_support = it->second;
                }
            }

            // Add new polygons to reconstructed mesh
            Mesh2D::Polygon poly_2d;
            for (size_t k = 0u; k < mesh_2d.getNumberOfPolygons(); k++) {
                CHECK(mesh_2d.getPolygon(k, &poly_2d));
                Mesh3D::Polygon poly_3d;
                poly_3d.reserve(poly_2d.size());
                bool add_poly = true;
                for (const Mesh2D::VertexType& vtx_2d : poly_2d) {
                    const LandmarkId& lmk_id = vtx_2d.getLmkId();
                    Mesh2D::VertexId  vtx_id;
                    CHECK(mesh_2d.getVtxIdForLmkId(lmk_id, &vtx_id));
                    if (!actual.exists(gtsam::Key(vtx_id))) {
                        LOG(ERROR) << "vtx_id: " << vtx_id
                                   << " is not in optimization.";
                        add_poly = false;
                        break;
                    }

                    const double& inv_depth = actual.at(gtsam::Key(vtx_id))[0];
                    if (std::isinf(inv_depth)) {
                        LOG(ERROR)
                            << "vtx_id: " << vtx_id << " goes to +/-inf.";
                        add_poly = false;
                        break;
                    }

                    //! Calculate depth estimation variance
                    // TODO(Toni): check that these divisions are not on 0;
                    const double& inv_variance_of_inv_depth =
                        hessian.at(gtsam::Key(vtx_id))[0];
                    const double& variance_of_inv_depth =
                        1.0 / inv_variance_of_inv_depth;
                    const double& variance_of_depth =
                        variance_of_inv_depth * (1.0 / std::pow(inv_depth, 2));

                    //! Calculate depth estimation
                    const double&      depth = 1.0 / inv_depth;
                    const cv::Point3f& cv_bearing_vector_body_frame =
                        vtx_ids_to_bearing_vectors[vtx_id];
                    const Vertex3D& lmk = depth * cv_bearing_vector_body_frame;

                    //! Plot confidence intervals on pixel rays.
                    const double& std_deviation = std::sqrt(variance_of_depth);

                    //! Add new vertex to polygon
                    //! Color with covariance bgr:
                    static constexpr double kScaleStdDeviation = 0.1;
                    cv::viz::Color          vtx_color = cv::viz::Color::black();
                    switch (mesh_color_type_) {
                        case MeshColorType::kVertexFlatColor: {
                            // Use color of each pixel where the landmark is
                            switch (mesh_count_ % 5) {
                                case 0:
                                    vtx_color = cv::viz::Color::red();
                                    break;
                                case 1:
                                    vtx_color = cv::viz::Color::apricot();
                                    break;
                                case 2:
                                    vtx_color = cv::viz::Color::purple();
                                    break;
                                case 3:
                                    vtx_color = cv::viz::Color::brown();
                                    break;
                                case 4:
                                    vtx_color = cv::viz::Color::pink();
                                    break;
                            }
                        } break;
                        case MeshColorType::kVertexRGB: {
                            // Use textures in the image
                        } break;
                        case MeshColorType::kVertexDepthVariance: {
                            // Use variances of the vertices
                            vtx_color = cv::Scalar(
                                0, 0,
                                std::round(std_deviation / kScaleStdDeviation *
                                           255.0),
                                255);
                        } break;
                        case MeshColorType::kVertexSupport: {
                            // Use the number of datapoints that support this
                            // vertex
                            vtx_color = cv::Scalar(
                                std::round(vertex_supports[gtsam::Key(vtx_id)] /
                                           max_vertex_support * 255.0),
                                0, 0, 255);
                        } break;
                        default: {
                            LOG(FATAL) << "Unrecognized mesh color type.";
                        }
                    }
                    poly_3d.push_back(
                        Mesh3D::VertexType(lmk_id, lmk, vtx_color));
                }
                if (add_poly) {
                    reconstructed_mesh.addPolygonToMesh(poly_3d);
                }
                else {
                    LOG(WARNING) << "Non-reconstructed poly: " << k;
                }
            }

            break;
        }
        default: {
            LOG(FATAL) << "Unknown mesh optimization type.";
        } break;
    }

    // Display reconstructed mesh.
    if (visualizer_) {
        LOG(INFO) << "Drawing optimized reconstructed mesh...";
        draw3dMesh("Reconstructed Mesh " + std::to_string(mesh_count_),
                   reconstructed_mesh, false, 0.9);
        spinDisplay();
    }
    MeshOptimizationOutput::UniquePtr mesh_output =
        VIO::make_unique<MeshOptimizationOutput>();
    mesh_output->optimized_mesh_3d = reconstructed_mesh;
    mesh_count_++;
    return mesh_output;
}

cv::Point2f MeshOptimization::generatePixelFromLandmarkGivenCamera(
    const cv::Point3f&    lmk,
    const gtsam::Pose3&   extrinsics,
    const gtsam::Cal3_S2& intrinsics)
{
    // Project 3D landmarks to camera image plane and get pixels.
    // (Sub-)Pixel coordinates
    gtsam::Vector3 v(lmk.x, lmk.y, lmk.z);
    gtsam::Point3  pixel = intrinsics.K() * extrinsics.transformTo(v);
    // cv::Point has inverted row/col wrt to cv::Mat!
    CHECK_GT(pixel.z(), 0.0);
    return cv::Point2f(pixel.x() / pixel.z(), pixel.y() / pixel.z());
}

void MeshOptimization::getBearingVectorFrom2DPixel(
    const cv::Point2f& pixel,
    cv::Point3f*       bearing_vector_body_frame)
{
    CHECK_NOTNULL(bearing_vector_body_frame);
    CHECK(mono_camera_ != nullptr);
    LandmarkCV lmk;
    // This in turn transforms the bearing vector to the camera frame of
    // reference. Therefore, bearing vector is expressed in the body frame of
    // ref.
    mono_camera_->backProject(pixel, 1.0, &lmk);
    *bearing_vector_body_frame = lmk / std::sqrt(lmk.dot(lmk));
    CHECK_NEAR(bearing_vector_body_frame->dot(*bearing_vector_body_frame), 1.0f,
               0.0001f);
}

void MeshOptimization::getBearingVectorFrom3DLmk(const gtsam::Pose3& extrinsics,
                                                 const cv::Point3f&  lmk,
                                                 cv::Point3f* bearing_vector,
                                                 float*       inverse_depth)
{
    CHECK_NOTNULL(bearing_vector);
    CHECK_NOTNULL(inverse_depth);
    const gtsam::Point3& ray =
        extrinsics.transformTo(gtsam::Vector3(lmk.x, lmk.y, lmk.z));
    const double& norm = ray.norm();
    CHECK_GT(norm, 0.0);
    *inverse_depth = 1 / norm;
    // Divide ray by its length get the normalized bearing vector.
    const gtsam::Point3& bearing = *inverse_depth * ray;
    *bearing_vector = cv::Point3d(bearing.x(), bearing.y(), bearing.z());
}

float MeshOptimization::sign(const cv::Point2f& p1,
                             const cv::Point2f& p2,
                             const cv::Point2f& p3)
{
    return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y);
}

bool MeshOptimization::pointInTriangle(const cv::Point2f& pt,
                                       const cv::Point2f& v1,
                                       const cv::Point2f& v2,
                                       const cv::Point2f& v3)
{
    float d1, d2, d3;
    bool  has_neg, has_pos;

    d1 = sign(pt, v1, v2);
    d2 = sign(pt, v2, v3);
    d3 = sign(pt, v3, v1);

    has_neg = (d1 < 0) || (d2 < 0) || (d3 < 0);
    has_pos = (d1 > 0) || (d2 > 0) || (d3 > 0);

    return !(has_neg && has_pos);
}

void MeshOptimization::drawPixelOnImg(const cv::Point2f&    pixel,
                                      const cv::Mat&        img,
                                      const cv::viz::Color& color,
                                      const size_t&         pixel_size)
{
    // Draw the pixel on the image
    cv::circle(img, pixel, pixel_size, color, -1);
}

void MeshOptimization::spinDisplay()
{
    // Display 3D window
    window_.spin();
}

}  // namespace VIO


text:
#include <boost/test/unit_test.hpp>
#include <envire_urdf/GraphLoader.hpp>
#include <envire_core/graph/EnvireGraph.hpp>
#include <envire_core/graph/GraphDrawing.hpp>
#include <envire_core/items/Item.hpp>

const std::string path="../../test/urdf/two_boxes.urdf";
const std::string pathDynamic="../../test/urdf/two_boxes_dynamic_joint.urdf";

BOOST_AUTO_TEST_CASE(it_should_not_crash_when_created)
{
    std::shared_ptr<envire::core::EnvireGraph> transformGraph;
    envire::urdf::GraphLoader loader(transformGraph);
    envire::core::Transform iniPose;
    envire::urdf::GraphLoader robotPath(transformGraph,iniPose);
}

BOOST_AUTO_TEST_CASE(initRobotGraph_noPos)
{
    std::shared_ptr<envire::core::EnvireGraph>  transformGraph( new envire::core::EnvireGraph());
    urdf::ModelInterface robot = *urdf::parseURDFFile(path).get();
    envire::core::GraphDrawing viz;
    envire::urdf::GraphLoader loader(transformGraph);
    loader.loadStructure(robot);
    viz.write(*transformGraph, "initRobotGraph_noPos_Test.dot");
}

BOOST_AUTO_TEST_CASE(initRobotGraph_withPos)
{
    std::shared_ptr<envire::core::EnvireGraph>  transformGraph( new envire::core::EnvireGraph());
    urdf::ModelInterface robot = *urdf::parseURDFFile(path).get();
    envire::core::GraphDrawing viz;
    std::cout << "Path to robot model " << path << std::endl;
    envire::core::Transform iniPose;
    iniPose.transform.orientation = base::Quaterniond::Identity();
    iniPose.transform.translation << 1.0, 1.0, 1.0;
    envire::urdf::GraphLoader loader(transformGraph,iniPose);
    envire::core::FrameId center = "center";
    transformGraph->addFrame(center);
    loader.loadStructure(transformGraph->getVertex(center), robot);
    viz.write(*transformGraph, "initRobotGraph_withPos_Test.dot");
}

BOOST_AUTO_TEST_CASE(initRobotGraph_withDynamicJoint)
{
    std::shared_ptr<envire::core::EnvireGraph>  transformGraph( new envire::core::EnvireGraph());
    urdf::ModelInterface robot = *urdf::parseURDFFile(pathDynamic).get();
    envire::core::GraphDrawing viz;
    std::cout << "Path to robot model " << pathDynamic << std::endl;
    envire::core::Transform iniPose;
    iniPose.transform.orientation = base::Quaterniond::Identity();
    iniPose.transform.translation << 1.0, 1.0, 1.0;
    envire::urdf::GraphLoader loader(transformGraph,iniPose);
    envire::core::FrameId center = "center";
    transformGraph->addFrame(center);
    loader.loadStructure(transformGraph->getVertex(center), robot);
    viz.write(*transformGraph, "initRobotGraph_withDynamicJoint_test.dot");
}

envire::urdf::GraphLoader getRobotWithInitGraph(urdf::ModelInterface& robot)
{
    std::shared_ptr<envire::core::EnvireGraph> transformGraph( new envire::core::EnvireGraph());
    envire::core::Transform iniPose;
    iniPose.transform.orientation = base::Quaterniond::Identity();
    iniPose.transform.translation << 1.0, 1.0, 1.0;
    envire::urdf::GraphLoader loader(transformGraph,iniPose);
    envire::core::FrameId center = "center";
    transformGraph->addFrame(center);
    loader.loadStructure(transformGraph->getVertex(center), robot);
    return loader;
}

BOOST_AUTO_TEST_CASE(loadFrames)
{

    urdf::ModelInterface robot = *urdf::parseURDFFile(pathDynamic);
    envire::core::GraphDrawing viz;
    envire::urdf::GraphLoader loader = getRobotWithInitGraph(robot);
    loader.loadFrames(robot);
    viz.write(*loader.getGraph(), "loadFrames_Test.dot");
}

BOOST_AUTO_TEST_CASE(loadFrames_withDynamicJoint)
{
    urdf::ModelInterface robot = *urdf::parseURDFFile(pathDynamic);
    envire::core::GraphDrawing viz;
    envire::urdf::GraphLoader loader = getRobotWithInitGraph(robot);
    loader.loadFrames(robot);
    viz.write(*loader.getGraph(), "loadFrames_withDynamicJoint_Test.dot");
}

BOOST_AUTO_TEST_CASE(loadJoints)
{
    urdf::ModelInterface robot = *urdf::parseURDFFile(pathDynamic);
    envire::core::GraphDrawing viz;
    envire::urdf::GraphLoader loader = getRobotWithInitGraph(robot);
    loader.loadJoints(robot);
    viz.write(*loader.getGraph(), "loadJoints_Test.dot");
}

BOOST_AUTO_TEST_CASE(completeTest)
{
    urdf::ModelInterface robot = *urdf::parseURDFFile(pathDynamic);
    envire::core::GraphDrawing viz;
    envire::urdf::GraphLoader loader = getRobotWithInitGraph(robot);
    loader.loadFrames(robot);
    loader.loadJoints(robot);
    viz.write(*loader.getGraph(), "completeTest_Test.dot");
}


text:
#include <itp/core>
#include <itp/timer>
#include <Eigen/Dense>
#include <array>

double** creatMatrix(int m, int n)
{
	double** ret = new double* [m];
	for (int i = 0; i < m; i++)
	{
		ret[i] = new double[n];
	}
	return ret;
}

std::vector<std::vector<double>> creatStdMatrix(int m, int n)
{
	std::vector<std::vector<double>> ret(m);
	for (auto&& r : ret)
		r.resize(n);
	return ret;
}

int main()
{
	itp::Timeit timeit;
	int N = 100000000;
	{
		timeit.start();
		auto mat1 = creatStdMatrix(N, 3);
		for (int i = 0; i < N; i++)
		{
			for (int j = 0; j < 3; j++)
			{
				mat1[i][j] = 3.25 * i + 22.64 * j;
			}
		}

		timeit.stop();
		fmt::print("vector value: {}, time: {} ms\n", mat1[N/2][1], timeit.span<itp::Timeit::milliseconds>());
	}

	{
		timeit.start();
		auto mat3 = creatMatrix(N, 3);
		for (int i = 0; i < N; i++)
		{
			for (int j = 0; j < 3; j++)
			{
				mat3[i][j] = 3.25 * i + 22.64 * j;
			}
		}

		timeit.stop();
		fmt::print("new value: {}, time: {} s\n", mat3[N / 2][1], timeit.span());
	}

	{
		timeit.start();
		std::vector<std::array<double, 3>> mat2(N);
		for (int i = 0; i < N; i++)
		{
			for (int j = 0; j < 3; j++)
			{
				mat2[i][j] = 3.25 * i + 22.64 * j;
			}
		}

		timeit.stop();
		fmt::print("std vector array value: {}, time: {} ms\n", mat2[N / 2][1], timeit.span<itp::Timeit::milliseconds>());
	}

	{
		using rvec = double[3];
		timeit.start();
		auto mat4 = new rvec[N];

		for (int i = 0; i < N; i++)
		{
			for (int j = 0; j < 3; j++)
			{
				mat4[i][j] = 3.25 * i + 22.64 * j;
			}
		}

		timeit.stop();
		fmt::print("new plain value: {}, time: {} s\n", mat4[N / 2][1], timeit.span());
	}

	{
		timeit.start();
		Eigen::ArrayXXd mat5(N, 3);

		for (int i = 0; i < N; i++)
		{
			for (int j = 0; j < 3; j++)
			{
				mat5(i, j) = 3.25 * i + 22.64 * j;
			}
		}

		timeit.stop();
		fmt::print("Eigen value: {}, time: {} s\n", mat5(N / 2, 1), timeit.span());
	}

}


text:
// Copyright 2020 Lawrence Livermore National Security, LLC and other Metall Project Developers.
// See the top-level COPYRIGHT file for details.
//
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

#ifndef METALL_CONTAINER_MAP_HPP
#define METALL_CONTAINER_MAP_HPP

#include <functional>

#include <boost/container/map.hpp>

#include <metall/metall.hpp>

namespace metall::container {

/// \brief A map container that uses Metall as its default allocator.
template <class Key,
          class T,
          class Compare = std::less<Key>,
          class Allocator = manager::allocator_type<std::pair<const Key, T>>>
using map = boost::container::map<Key, T, Compare, Allocator>;

/// \brief A multimap container that uses Metall as its default allocator.
template <class Key,
          class T,
          class Compare = std::less<Key>,
          class Allocator = manager::allocator_type<std::pair<const Key, T>>>
using multimap = boost::container::multimap<Key, T, Compare, Allocator>;

}

#endif //METALL_CONTAINER_MAP_HPP

max_stars_repo_name: dice-group/metall

max_issues_repo_name: dice-group/metall

max_forks_repo_name: dice-group/metall


text:
/*
** EPITECH PROJECT, 2021
** B-CPP-500-LYN-5-1-babel-
** File description:
** Security.hpp
*/

#ifndef SECURITY_HPP
    #define SECURITY_HPP

    #include <iostream>
    #include <list>
    #include <set>
    #include <vector>
    #include <utility>
    #include <algorithm>
    #include <string>
    #include <bitset>
    #include <boost/array.hpp>

    #include "Protocol.hpp"

    namespace security
    {
        enum {
            limit = 0b0000000000000000
        };

        boost::array<std::bitset<16>, max_length> encoder(std::string);
        std::string decoder(boost::array<std::bitset<16>, max_length>);

        std::size_t get_size(boost::array<std::bitset<16>, max_length>);
        void display(boost::array<std::bitset<16>, max_length>);
    };

#endif /* SECURITY_HPP */


text:
#include <iostream>

#define BOOST_TEST_MODULE MIAAssignTests

#include "MIAConfig.h"

#ifdef MIA_USE_HEADER_ONLY_TESTS
#include <boost/test/included/unit_test.hpp>
#else
#include <boost/test/unit_test.hpp>
#endif
#include "DenseMIA.h"

#include "Index.h"

//typedef LibMIA::DenseMIA<double,3> dmia;

template<class MIAType>
void assign_work(){

    LibMIA::MIAINDEX i;
    LibMIA::MIAINDEX j;
    LibMIA::MIAINDEX k;

    MIAType a(5,7,4);
    MIAType b;
    MIAType c;

    a.randu(-5,5);
    const MIAType temp_a(a); //check const correctness
    c=temp_a;
    BOOST_CHECK_MESSAGE(a==c,"Straight MIA assignment");

    b.zeros();
    c.zeros();
    b(i,j,k)=temp_a(i,j,k);
    c(i,j,k)=b(i,j,k);
    BOOST_CHECK_MESSAGE(a==c,"Non-shuffled MIA Expression assignment");

    b.zeros();
    c.zeros();
    b(i,j,k)=a(i,k,j);
    c(i,j,k)=b(i,k,j);
    BOOST_CHECK_MESSAGE(a==c,"Shuffled MIA Expression assignment");

    b.zeros();
    c.zeros();
    b(i,j,k)=a(i,!k,j);
    c(!i,j,k)=b(i,k,j);
    BOOST_CHECK_MESSAGE(a==c,"Shuffled MIA Expression assignment with mismatched elem-wise indices");

}

BOOST_AUTO_TEST_CASE( MIAAssignTests )
{

    assign_work<LibMIA::DenseMIA<double,3>>();
    assign_work<LibMIA::DenseMIA<float,3>>();
    assign_work<LibMIA::DenseMIA<int,3>>();
    assign_work<LibMIA::DenseMIA<long,3>>();

}

max_stars_repo_name: extragoya/LibNT

max_issues_repo_name: extragoya/LibNT

max_forks_repo_name: extragoya/LibNT