text:
#if defined(_CARTO_ROUTING_SUPPORT) && defined(_CARTO_VALHALLA_ROUTING_SUPPORT) && defined(_CARTO_OFFLINE_SUPPORT)

#include "ValhallaOfflineRoutingService.h"
#include "components/Exceptions.h"
#include "routing/utils/ValhallaRoutingProxy.h"
#include "utils/Const.h"
#include "utils/Log.h"

#include <boost/algorithm/string.hpp>

#include <sqlite3pp.h>

namespace carto {

    ValhallaOfflineRoutingService::ValhallaOfflineRoutingService(const std::string& path) :
        _database(std::make_unique<sqlite3pp::database>()),
        _profile("pedestrian"),
        _configuration(ValhallaRoutingProxy::GetDefaultConfiguration()),
        _mutex()
    {
        if (_database->connect_v2(path.c_str(), SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX) != SQLITE_OK) {
            throw FileException("Failed to open routing database", path);
        }
        _database->execute("PRAGMA temp_store=MEMORY");
    }

    ValhallaOfflineRoutingService::~ValhallaOfflineRoutingService() {
    }

    Variant ValhallaOfflineRoutingService::getConfigurationParameter(const std::string& param) const {
        std::lock_guard<std::mutex> lock(_mutex);
        std::vector<std::string> keys;
        boost::split(keys, param, boost::is_any_of("."));
        picojson::value subValue = _configuration.toPicoJSON();
        for (const std::string& key : keys) {
            if (!subValue.is<picojson::object>()) {
                return Variant();
            }
            subValue = subValue.get(key);
        }
        return Variant::FromPicoJSON(subValue);
    }

    void ValhallaOfflineRoutingService::setConfigurationParameter(const std::string& param, const Variant& value) {
        std::lock_guard<std::mutex> lock(_mutex);
        std::vector<std::string> keys;
        boost::split(keys, param, boost::is_any_of("."));
        picojson::value config = _configuration.toPicoJSON();
        picojson::value* subValue = &config;
        for (const std::string& key : keys) {
            if (!subValue->is<picojson::object>()) {
                subValue->set(picojson::object());
            }
            subValue = &subValue->get<picojson::object>()[key];
        }
        *subValue = value.toPicoJSON();
        _configuration = Variant::FromPicoJSON(config);
    }

    std::string ValhallaOfflineRoutingService::getProfile() const {
        std::lock_guard<std::mutex> lock(_mutex);
        return _profile;
    }

    void ValhallaOfflineRoutingService::setProfile(const std::string& profile) {
        std::lock_guard<std::mutex> lock(_mutex);
        _profile = profile;
    }

    std::shared_ptr<RouteMatchingResult> ValhallaOfflineRoutingService::matchRoute(const std::shared_ptr<RouteMatchingRequest>& request) const {
        if (!request) {
            throw NullArgumentException("Null request");
        }

        std::string profile;
        Variant configuration;
        {
            std::lock_guard<std::mutex> lock(_mutex);

            profile = _profile;
            configuration = _configuration;
        }
        return ValhallaRoutingProxy::MatchRoute(std::vector<std::shared_ptr<sqlite3pp::database> > { _database }, profile, configuration, request);
    }

    std::shared_ptr<RoutingResult> ValhallaOfflineRoutingService::calculateRoute(const std::shared_ptr<RoutingRequest>& request) const {
        if (!request) {
            throw NullArgumentException("Null request");
        }

        std::string profile;
        Variant configuration;
        {
            std::lock_guard<std::mutex> lock(_mutex);

            profile = _profile;
            configuration = _configuration;
        }

        return ValhallaRoutingProxy::CalculateRoute(std::vector<std::shared_ptr<sqlite3pp::database> > { _database }, profile, configuration, request);
    }

}

#endif

max_stars_repo_name: ShaneCoufreur/mobile-sdk

max_issues_repo_name: ShaneCoufreur/mobile-sdk

max_forks_repo_name: ShaneCoufreur/mobile-sdk


text:
/*!
@file
Forward declares `boost::hana::zip_shortest_with`.

@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_FWD_ZIP_SHORTEST_WITH_HPP
#define BOOST_HANA_FWD_ZIP_SHORTEST_WITH_HPP

#include <boost/hana/config.hpp>
#include <boost/hana/core/when.hpp>

BOOST_HANA_NAMESPACE_BEGIN
    //! Zip one sequence or more with a given function.
    //! @ingroup group-Sequence
    //!
    //! Given a `n`-ary function `f` and `n` sequences `s1, ..., sn`,
    //! `zip_shortest_with` produces a sequence whose `i`-th element is
    //! `f(s1[i], ..., sn[i])`, where `sk[i]` denotes the `i`-th element of
    //! the `k`-th sequence. In other words, `zip_shortest_with` produces a
    //! sequence of the form
    //! @code
    //!     [
    //!         f(s1[0], ..., sn[0]),
    //!         f(s1[1], ..., sn[1]),
    //!         ...
    //!         f(s1[M], ..., sn[M])
    //!     ]
    //! @endcode
    //! where `M` is the length of the shortest sequence. Hence, the returned
    //! sequence stops when the shortest input sequence is exhausted. If you
    //! know that all the sequences you are about to zip have the same length,
    //! you should use `zip_with` instead, since it can be more optimized.
    //! Also note that it is an error to provide no sequence at all, i.e.
    //! `zip_shortest_with` expects at least one sequence.
    //!
    //!
    //! Example
    //! -------
    //! @include example/zip_shortest_with.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
    constexpr auto zip_shortest_with = [](auto&& f, auto&& x1, ..., auto&& xn) {
        return tag-dispatched;
    };
#else
    template <typename S, typename = void>
    struct zip_shortest_with_impl : zip_shortest_with_impl<S, when<true>> { };

    struct zip_shortest_with_t {
        template <typename F, typename Xs, typename ...Ys>
        constexpr auto operator()(F&& f, Xs&& xs, Ys&& ...ys) const;
    };

    constexpr zip_shortest_with_t zip_shortest_with{};
#endif
BOOST_HANA_NAMESPACE_END

#endif // !BOOST_HANA_FWD_ZIP_SHORTEST_WITH_HPP

ext: hpp

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
/*******************************************************************************
Copyright(c) 2015-2018 LORD Corporation. All rights reserved.

MIT Licensed. See the included LICENSE.txt for a copy of the full MIT License.
*******************************************************************************/
#include "mscl/MicroStrain/ChecksumBuilder.h"

#include <boost/test/unit_test.hpp>

using namespace mscl;

BOOST_AUTO_TEST_SUITE(ChecksumBuilder_Test)

BOOST_AUTO_TEST_CASE(ChecksumBuilder_AppendByte)
{
    //append bytes to the checksum builder
    ChecksumBuilder b;
    b.append_uint8(0x01);
    b.append_uint8(0x02);
    b.append_uint8(0x04);

    //check the checksum is good
    BOOST_CHECK_EQUAL(b.simpleChecksum(), 0x07);
}

BOOST_AUTO_TEST_CASE(ChecksumBuilder_AppendWord)
{
    //append word to the checksum builder
    ChecksumBuilder b;
    b.append_uint16(0x1234);
    b.append_uint8(0x02);
    b.append_uint8(0x04);

    //check the checksum is good
    BOOST_CHECK_EQUAL(b.simpleChecksum(), 0x4C);
}

BOOST_AUTO_TEST_CASE(ChecksumBuilder_AppendDWord)
{
    //append dword to the checksum builder
    ChecksumBuilder b;
    b.append_uint32(0x12345678);
    b.append_uint8(0x02);
    b.append_uint8(0x04);

    //check the checksum is good
    BOOST_CHECK_EQUAL(b.simpleChecksum(), 0x11A);
}

BOOST_AUTO_TEST_CASE(ChecksumBuilder_AppendBytes)
{
    Bytes data;
    data.push_back(0x01);
    data.push_back(0x02);
    data.push_back(0x04);

    //append bytes to the checksum builder
    ChecksumBuilder b;
    b.appendBytes(data);

    //check the checksum is good
    BOOST_CHECK_EQUAL(b.simpleChecksum(), 0x07);
}

BOOST_AUTO_TEST_CASE(ChecksumBuilder_AppendByteStream)
{
    ByteStream bs;
    bs.append_uint8(0x01);
    bs.append_uint8(0x02);
    bs.append_uint8(0x04);

    //append bytes to the checksum builder
    ChecksumBuilder b;
    b.appendByteStream(bs);

    //check the checksum is good
    BOOST_CHECK_EQUAL(b.simpleChecksum(), 0x07);
}

BOOST_AUTO_TEST_CASE(ChecksumBuilder_FletcherChecksum)
{
    ChecksumBuilder b;
    b.append_uint32(0x12345678);

    //check that the simple checksum is what it should be
    BOOST_CHECK_EQUAL(b.fletcherChecksum(), 5128);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: HTLife/MSCL

max_stars_repo_licenses: BSL-1.0 OpenSSL MIT

max_issues_repo_name: HTLife/MSCL

max_issues_repo_licenses: BSL-1.0 OpenSSL MIT

max_forks_repo_name: HTLife/MSCL

max_forks_repo_licenses: BSL-1.0 OpenSSL MIT


text:
/*
Copyright 2009-2021 Nicolas Colombe

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

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

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

#pragma once

#ifdef EXL_LUA

#include <core/lua/luamanager.hpp>
#include <core/lua/luascript.hpp>
#include <core/type/fundesc.hpp>
#include <engine/common/world.hpp>
#include <boost/optional.hpp>
#include <core/path.hpp>

namespace eXl
{
  class LuaScriptBehaviour;

  struct BehaviourDesc
  {
    Name behaviourName;
    UnorderedMap<Name, FunDesc> functions;
  };

  class EXL_ENGINE_API LuaScriptSystem : public ComponentManager
  {
    DECLARE_RTTI(LuaScriptSystem, ComponentManager);
  public:

    LuaScriptSystem();
    ~LuaScriptSystem();

    static void AddBehaviourDesc(BehaviourDesc iDesc);
    static BehaviourDesc const* GetBehaviourDesc(Name iName);

    static Vector<Name> GetBehaviourNames();

    void LoadScript(const LuaScriptBehaviour& iBehaviour);

    void AddBehaviour(ObjectHandle, const LuaScriptBehaviour& iBehaviour);
    void DeleteComponent(ObjectHandle) override;

    static World* GetWorld();

    template <typename Ret, typename... Args>
    static bool ValidateCall(Name iBehaviour, Name iFunction)
    {
      BehaviourDesc const* desc = GetBehaviourDesc(iBehaviour);
      if (desc == nullptr)
      {
        return false;
      }
      auto iter = desc->functions.find(iFunction);
      if (iter == desc->functions.end())
      {
        return false;
      }
      if (!iter->second.ValidateSignature<Ret, Args...>())
      {
        return false;
      }

      return true;
    }

    template <typename Ret, typename... Args>
    struct Caller
    {
      static boost::optional<Ret> Call(LuaScriptSystem& iSys, ObjectHandle iHandle, Name iBehaviour, Name iFunction, Args&&... iArgs)
      {
        if (!iSys.ValidateCall<Ret, Args...>(iBehaviour, iFunction))
        {
          return {};
        }

        LuaStateHandle stateHandle = iSys.m_LuaWorld.GetState();
        lua_State* state = stateHandle.GetState();
        int32_t curTop = lua_gettop(state);

        luabind::object scriptObject;
        luabind::object function = iSys.FindFunction(iHandle, iBehaviour, iFunction, scriptObject);
        if (!function.is_valid())
        {
          return {};
        }

        boost::optional<Ret> res;
        {
          auto call = stateHandle.PrepareCall(function);
          call.Push(scriptObject);
          call.PushArgs(std::forward<Args>(iArgs)...);
          auto res = call.Call(1);

          if (!res || *res == 0)
          {
            return {};
          }

          luabind::object retObj(luabind::from_stack(state, -1));
          luabind::default_converter<Ret> converter;
          if (converter.match(state, luabind::decorate_type_t<Ret>(), -1) < 0)
          {
            luabind::detail::cast_error<Ret>(state);
            return {};
          }
          //return converter.to_cpp(state, luabind::decorate_type_t<Ret>(), -1);
          res = converter.to_cpp(state, luabind::decorate_type_t<Ret>(), -1);
        }
        eXl_ASSERT(curTop == lua_gettop(state));
        return res;
      }
    };

    template <typename... Args>
    struct Caller<void, Args...>
    {
      static Err Call(LuaScriptSystem& iSys, ObjectHandle iHandle, Name iBehaviour, Name iFunction, Args&&... iArgs)
      {
        if (!iSys.ValidateCall<void, Args...>(iBehaviour, iFunction))
        {
          return Err::Failure;
        }

        LuaStateHandle stateHandle = iSys.m_LuaWorld.GetState();
        lua_State* state = stateHandle.GetState();
        int32_t curTop = lua_gettop(state);

        luabind::object scriptObject;
        luabind::object function = iSys.FindFunction(iHandle, iBehaviour, iFunction, scriptObject);
        if (!function.is_valid())
        {
          return Err::Failure;
        }
        {
          auto call = stateHandle.PrepareCall(function);
          call.Push(scriptObject);
          call.PushArgs(std::forward<Args>(iArgs)...);
          auto res = call.Call(0);

          if (!res)
          {
            return Err::Failure;
          }
        }
        eXl_ASSERT(curTop == lua_gettop(state));

        return Err::Success;
      }
    };

    template <typename Ret, typename... Args, typename std::enable_if<!std::is_same<Ret, void>::value, bool>::type = true>
    boost::optional<Ret> CallBehaviour(ObjectHandle iHandle, Name iBehaviour, Name iFunction, Args&&... iArgs)
    {
      return Caller<Ret, Args...>::Call(*this, iHandle, iBehaviour, iFunction, std::forward<Args>(iArgs)...);
    }

    template <typename Ret, typename... Args, typename std::enable_if<std::is_same<Ret, void>::value, bool>::type = true>
    Err CallBehaviour(ObjectHandle iHandle, Name iBehaviour, Name iFunction, Args&&... iArgs)
    {
      return Caller<void, Args...>::Call(*this, iHandle, iBehaviour, iFunction, std::forward<Args>(iArgs)...);
    }

  protected:

    luabind::object FindFunction(ObjectHandle iHandle, Name iBehaviour, Name iFunction, luabind::object& oScriptObj);

    struct ScriptEntry
    {
      ResourceHandle<LuaScriptBehaviour> m_ScriptHandle;
      luabind::object m_ScriptObject;
      luabind::object m_InitFunction;
      UnorderedMap<Name, luabind::object> m_ScriptFunctions;
    };

    ObjectTable<ScriptEntry> m_Scripts;
    using ScriptHandle = ObjectTableHandle<ScriptEntry>;
    UnorderedMap<Resource::UUID, ScriptHandle> m_LoadedScripts;

    ScriptHandle LoadScript_Internal(const LuaScriptBehaviour& iBehaviour);

    struct ObjectEntry
    {
      ScriptHandle m_Script;
      luabind::object m_ScriptData;
    };

    struct BehaviourReg
    {
      UnorderedMap<ObjectHandle, ObjectEntry> m_RegisteredObjects;
    };

    UnorderedMap<Name, BehaviourReg> m_ObjectToBehaviour;

    LuaWorld m_LuaWorld;
  };
}
#endif

max_stars_repo_name: eXl-Nic/eXl

max_issues_repo_name: eXl-Nic/eXl

max_forks_repo_name: eXl-Nic/eXl


text:
// Copyright (C) 2013 The Regents of the University of California (Regents).
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//
//     * Neither the name of The Regents or University of California nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)

#include "theia/sfm/transformation/gdls_similarity_transform.h"

#include <Eigen/Core>
#include <Eigen/Eigenvalues>
#include <Eigen/Geometry>
#include <cmath>
#include <glog/logging.h>
#include <vector>

#include "theia/alignment/alignment.h"
#include "theia/sfm/pose/dls_impl.h"
#include "theia/util/random.h"

namespace theia {

using dls_impl::CreateMacaulayMatrix;
using dls_impl::ExtractJacobianCoefficients;
using dls_impl::LeftMultiplyMatrix;
using Eigen::Matrix;
using Eigen::Matrix3d;
using Eigen::Matrix4d;
using Eigen::MatrixXd;
using Eigen::Quaterniond;
using Eigen::Vector3d;

// This implementation is based off of the DLS PnP implementation. The general
// approach is to first rewrite the reprojection constraint (i.e., cost
// function) such that all unknowns appear linearly in terms of the rotation
// parameters (which are 3 parameters in the Cayley-Gibss-Rodriguez
// formulation). Then we create a system of equations from the jacobian of the
// cost function, and solve these equations via a Macaulay matrix to obtain the
// roots (i.e., the 3 parameters of rotation). The translation and scale can
// then be obtained through back-substitution.
void GdlsSimilarityTransform(const std::vector<Vector3d>& ray_origin,
                             const std::vector<Vector3d>& ray_direction,
                             const std::vector<Vector3d>& world_point,
                             std::vector<Quaterniond>* solution_rotation,
                             std::vector<Vector3d>* solution_translation,
                             std::vector<double>* solution_scale) {
  CHECK_GE(ray_direction.size(), 4);

  const int num_correspondences = ray_direction.size();
  // The bottom-right symmetric block matrix of inverse(A^T * A). This is the
  // generalized version of Matrix H from Eq. 17 in the Appendix of the gDLS
  // paper (note that term appears exactly in the bottom right 3x3 of this
  // matrix).
  Matrix4d h_inverse = Matrix4d::Zero();
  for (int i = 0; i < num_correspondences; i++) {
    h_inverse(0, 0) = h_inverse(0, 0) + ray_origin[i].squaredNorm() -
                      ray_origin[i].dot(ray_direction[i]) *
                          ray_origin[i].dot(ray_direction[i]);
    Vector3d temp_term =
        -ray_origin[i] + ray_origin[i].dot(ray_direction[i]) * ray_direction[i];
    h_inverse.block<3, 1>(1, 0) = h_inverse.block<3, 1>(1, 0) + temp_term;
    h_inverse.block<1, 3>(0, 1) =
        h_inverse.block<1, 3>(0, 1) + temp_term.transpose();
    h_inverse.block<3, 3>(1, 1) =
        h_inverse.block<3, 3>(1, 1) + Matrix3d::Identity() -
        (ray_direction[i] * ray_direction[i].transpose());
  }
  const Matrix4d h_matrix = h_inverse.inverse();

  // This is the translation and scale parameterized by the 9 entries of the
  // rotation matrix. The first row is the scale and rows 2 - 4 are the
  // translation.
  Matrix<double, 4, 9> sv_helper = Matrix<double, 4, 9>::Zero();
  for (int i = 0; i < num_correspondences; i++) {
    // Scale factor.
    sv_helper.row(0) =
        sv_helper.row(0) +
        (ray_origin[i].transpose() -
         ray_origin[i].dot(ray_direction[i]) * ray_direction[i].transpose()) *
            LeftMultiplyMatrix(world_point[i]);

    // Translation factor.
    sv_helper.block<3, 9>(1, 0) =
        sv_helper.block<3, 9>(1, 0) +
        (ray_direction[i] * ray_direction[i].transpose() -
         Matrix3d::Identity()) *
            LeftMultiplyMatrix(world_point[i]);
  }

  sv_helper = h_matrix * sv_helper;
  const Matrix<double, 1, 9>& scale_factor = sv_helper.row(0);
  const Matrix<double, 3, 9>& translation_factor = sv_helper.block<3, 9>(1, 0);

  // Compute the cost function C' of Eq. 15 in gDLS paper. This is a factorized
  // version where the rotation matrix parameters have been pulled out. The
  // entries to this equation are the coefficients to the cost function which is
  // a quartic in the rotation parameters.
  Matrix<double, 9, 9> ls_cost_coefficients = Matrix<double, 9, 9>::Zero();
  for (int i = 0; i < num_correspondences; i++) {
    const Matrix<double, 3, 9> cost_coeff_term =
        (ray_direction[i] * ray_direction[i].transpose() -
         Matrix3d::Identity()) *
        (LeftMultiplyMatrix(world_point[i]) - ray_origin[i] * scale_factor +
         translation_factor);
    ls_cost_coefficients =
        ls_cost_coefficients + cost_coeff_term.transpose() * cost_coeff_term;
  }

  // Extract the coefficients of the jacobian (Eq. 16) from the
  // ls_cost_coefficients matrix. The jacobian represent 3 monomials in the
  // rotation parameters. Each entry of the jacobian will be 0 at the roots of
  // the polynomial, so we can arrange a system of polynomials from these
  // equations.
  double f1_coeff[20];
  double f2_coeff[20];
  double f3_coeff[20];
  ExtractJacobianCoefficients(
      ls_cost_coefficients, f1_coeff, f2_coeff, f3_coeff);

  // We create one equation with random terms that is generally non-zero at the
  // roots of our system.
  const Eigen::Vector4d rand_vec = 100.0 * Eigen::Vector4d::Random();
  const double macaulay_term[4] = {
      rand_vec(0), rand_vec(1), rand_vec(2), rand_vec(3)};

  // Create Macaulay matrix that will be used to solve our polynonomial system.
  const MatrixXd& macaulay_matrix =
      CreateMacaulayMatrix(f1_coeff, f2_coeff, f3_coeff, macaulay_term);

  // Via the Schur complement trick, the top-left of the Macaulay matrix
  // contains a multiplication matrix whose eigenvectors correspond to solutions
  // to our system of equations.
  const MatrixXd solution_polynomial =
      macaulay_matrix.block<27, 27>(0, 0) -
      (macaulay_matrix.block<27, 93>(0, 27) *
       macaulay_matrix.block<93, 93>(27, 27).partialPivLu().solve(
           macaulay_matrix.block<93, 27>(27, 0)));

  // Extract eigenvectors of the solution polynomial to obtain the roots which
  // are contained in the entries of the eigenvectors.
  const Eigen::EigenSolver<MatrixXd> eigen_solver(solution_polynomial);

  // Many of the eigenvectors will contain complex solutions so we must filter
  // them to find the real solutions.
  const auto eigen_vectors = eigen_solver.eigenvectors();
  for (int i = 0; i < 27; i++) {
    // The first entry of the eigenvector should equal 1 according to our
    // polynomial, so we must divide each solution by the first entry.
    std::complex<double> s1 = eigen_vectors(9, i) / eigen_vectors(0, i);
    std::complex<double> s2 = eigen_vectors(3, i) / eigen_vectors(0, i);
    std::complex<double> s3 = eigen_vectors(1, i) / eigen_vectors(0, i);

    // If the rotation solutions are real, treat this as a valid candidate
    // rotation.
    const double kEpsilon = 1e-6;
    if (fabs(s1.imag()) < kEpsilon && fabs(s2.imag()) < kEpsilon &&
        fabs(s3.imag()) < kEpsilon) {
      // Compute the rotation (which is the transpose rotation of our solution)
      // and translation.
      Quaterniond soln_rotation(1.0, s1.real(), s2.real(), s3.real());
      soln_rotation = soln_rotation.inverse().normalized();

      const Matrix3d rot_mat = soln_rotation.inverse().toRotationMatrix();
      const Eigen::Map<const Matrix<double, 9, 1> > rot_vec(rot_mat.data());
      const Vector3d soln_translation = translation_factor * rot_vec;
      const double soln_scale = scale_factor * rot_vec;

      // TODO(cmsweeney): evaluate cost function and return it as an output
      // variable.

      // Check that all points are in front of the camera. Discard the solution
      // if this is not the case.
      bool all_points_in_front_of_camera = true;

      for (int j = 0; j < num_correspondences; j++) {
        const Vector3d transformed_point = soln_rotation * world_point[j] +
                                           soln_translation -
                                           soln_scale * ray_origin[j];

        // Find the rotation that puts the image ray at [0, 0, 1] i.e. looking
        // straightforward from the camera.
        const Quaterniond unrot =
            Quaterniond::FromTwoVectors(ray_direction[j], Vector3d(0, 0, 1));

        // Rotate the transformed point and check if the z coordinate is
        // negative. This will indicate if the point is projected behind the
        // camera.
        const Vector3d rotated_projection = unrot * transformed_point;
        if (rotated_projection.z() < 0) {
          all_points_in_front_of_camera = false;
          break;
        }
      }

      if (all_points_in_front_of_camera) {
        solution_rotation->push_back(soln_rotation);
        solution_translation->push_back(soln_translation);
        solution_scale->push_back(soln_scale);
      }
    }
  }
}

}  // namespace theia

ext: cc

max_stars_repo_name: urbste/pyTheiaSfM

max_issues_repo_name: urbste/TheiaSfM

max_forks_repo_name: urbste/TheiaSfM


text:
// Boost.Geometry Index
//
// Copyright (c) 2011-2015 Adam Wulkiewicz, Lodz, Poland.
//
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_INDEX_DETAIL_ASSERT_HPP
#define BOOST_GEOMETRY_INDEX_DETAIL_ASSERT_HPP

#include <boost/geometry/core/assert.hpp>

#undef BOOST_GEOMETRY_INDEX_ASSERT

#define BOOST_GEOMETRY_INDEX_ASSERT(CONDITION, TEXT_MSG) \
    BOOST_GEOMETRY_ASSERT_MSG(CONDITION, TEXT_MSG)

#endif // BOOST_GEOMETRY_INDEX_DETAIL_ASSERT_HPP


text:
#include "HullPaintingRobot.h"

#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>

__BEGIN_LIBRARIES_DISABLE_WARNINGS
#include <boost/algorithm/string.hpp>
__END_LIBRARIES_DISABLE_WARNINGS

namespace AdventOfCode
{
namespace Year2019
{
namespace Day11
{

using AdventOfCode::Year2019::Day05::IntcodeNumberType;
using AdventOfCode::Year2019::Day05::IntcodeProgramExecutionState;

HullPaintingRobot::HullPaintingRobot(IntcodeInterpreter interpreter)
    : HullPaintingRobot(interpreter, {})
{

}

HullPaintingRobot::HullPaintingRobot(IntcodeInterpreter interpreter, CoordinatesToColor initialCoordinatesToColor)
    : m_interpreter{std::move(interpreter)}
    , m_currentCoordinates{0, 0}
    , m_direction{Direction::UP}
    , m_coordinatesToColor{std::move(initialCoordinatesToColor)}
{

}

void HullPaintingRobot::paint()
{
    while (m_interpreter.getExecutionState() != IntcodeProgramExecutionState::TERMINATED)
    {
        m_interpreter.addInput(static_cast<IntcodeNumberType>(getCurrentColor()));
        m_interpreter.execute();

        const auto& outputs = m_interpreter.getOutputs();
        assert(outputs.size() == 0 || outputs.size() == 2);

        if (outputs.size() == 2)
        {
            m_coordinatesToColor[m_currentCoordinates] = static_cast<PaintColor>(outputs.front());

            if (outputs.back() == 0)
            {
                turnLeft();
            }
            else
            {
                turnRight();
            }

            moveForward();
            m_interpreter.clearOutputs();
        }
    }
}

unsigned HullPaintingRobot::getNumPanelsPaintedAtLeastOnce() const
{
    return m_coordinatesToColor.size();
}

std::string HullPaintingRobot::getRegistrationIdentifier() const
{
    std::pair<Vector2D, Vector2D> boundingBox = getBoundingBox();

    const Vector2D& offset = boundingBox.first;
    const Vector2D& size = boundingBox.second;

    const int width = size[0];
    const int height = size[1];

    std::vector<std::string> serializedLines(height, std::string(width, BLACK_CHAR));

    for (const auto& coordinatesAndColor : m_coordinatesToColor)
    {
        if (coordinatesAndColor.second == PaintColor::WHITE)
        {
            const Coordinates& coordinates = coordinatesAndColor.first;
            Vector2D positionVector{coordinates.first, coordinates.second};
            Vector2D positionRelativeToBoundingBox{positionVector - offset};

            const int posX = positionRelativeToBoundingBox[0];
            const int posY = positionRelativeToBoundingBox[1];

            serializedLines.at(posY).at(posX) = WHITE_CHAR;
        }
    }

    std::reverse(serializedLines.begin(), serializedLines.end());

    return boost::algorithm::join(serializedLines, "\n");
}

void HullPaintingRobot::moveForward()
{
    switch (m_direction)
    {
        case Direction::LEFT:
            m_currentCoordinates.first -= 1;
            break;
        case Direction::RIGHT:
            m_currentCoordinates.first += 1;
            break;
        case Direction::UP:
            m_currentCoordinates.second += 1;
            break;
        case Direction::DOWN:
            m_currentCoordinates.second -= 1;
            break;
        default:
            throw std::runtime_error("Invalid direction");
    }
}

void HullPaintingRobot::turnLeft()
{
    switch (m_direction)
    {
        case Direction::LEFT:
            m_direction = Direction::DOWN;
            break;
        case Direction::RIGHT:
            m_direction = Direction::UP;
            break;
        case Direction::UP:
            m_direction = Direction::LEFT;
            break;
        case Direction::DOWN:
            m_direction = Direction::RIGHT;
            break;
        default:
            throw std::runtime_error("Invalid direction");
    }
}

void HullPaintingRobot::turnRight()
{
    for (int i = 1; i <= 3; ++i)
    {
        turnLeft();
    }
}

PaintColor HullPaintingRobot::getCurrentColor() const
{
    const auto currentCoordinatesAndColorIter = m_coordinatesToColor.find(m_currentCoordinates);
    if (currentCoordinatesAndColorIter == m_coordinatesToColor.cend())
    {
        return PaintColor::BLACK;
    }
    return currentCoordinatesAndColorIter->second;
}

std::pair<Vector2D, Vector2D> HullPaintingRobot::getBoundingBox() const
{
    auto minmaxXCoordinatesIterPair = std::minmax_element(m_coordinatesToColor.cbegin(), m_coordinatesToColor.cend(), [](const auto& lhs, const auto& rhs)
                                                            {
                                                                const auto& lhsCoords = lhs.first;
                                                                const auto& rhsCoords = rhs.first;
                                                                return lhsCoords.first < rhsCoords.first;
                                                            });

    const auto& minXCoordsAndColor = minmaxXCoordinatesIterPair.first;
    const auto& maxXCoordsAndColor = minmaxXCoordinatesIterPair.second;
    const auto& minXCoords = minXCoordsAndColor->first;
    const auto& maxXCoords = maxXCoordsAndColor->first;
    const int minX = minXCoords.first;
    const int maxX = maxXCoords.first;

    auto minmaxYCoordinatesIterPair = std::minmax_element(m_coordinatesToColor.cbegin(), m_coordinatesToColor.cend(), [](const auto& lhs, const auto& rhs)
                                                            {
                                                                const auto& lhsCoords = lhs.first;
                                                                const auto& rhsCoords = rhs.first;
                                                                return lhsCoords.second < rhsCoords.second;
                                                            });

    const auto& minYCoordsAndColor = minmaxYCoordinatesIterPair.first;
    const auto& maxYCoordsAndColor = minmaxYCoordinatesIterPair.second;
    const auto& minYCoords = minYCoordsAndColor->first;
    const auto& maxYCoords = maxYCoordsAndColor->first;
    const int minY = minYCoords.second;
    const int maxY = maxYCoords.second;

    return std::make_pair(Vector2D{minX, minY}, Vector2D{maxX - minX + 1, maxY - minY + 1});
}

}
}
}

max_stars_repo_name: dbartok/advent-of-code-cpp

max_issues_repo_name: dbartok/advent-of-code-cpp

max_forks_repo_name: dbartok/advent-of-code-cpp


text:
// Copyright Ricardo Calheiros de Miranda Cosme 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#pragma once

#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/include/zip_view.hpp>

#include <utility>

namespace coruja { namespace detail {

template<typename Conns, typename Visitor, typename ObservableObjects>
inline Conns for_each_obj2conn(Visitor&& visitor, ObservableObjects&& objs)
{
    namespace fs = boost::fusion;

    using obj2conn_t = fs::vector<ObservableObjects&, Conns&>;

    Conns conns;

    auto obj2conn = fs::zip_view<obj2conn_t>(obj2conn_t(objs, conns));
    fs::for_each(obj2conn, visitor);

    return {std::move(conns)};
}

}}

max_stars_repo_name: romariorios/coruja

max_issues_repo_name: romariorios/coruja

max_forks_repo_name: romariorios/coruja


text:
#include <boost/python/class.hpp>
#include <boost/python/wrapper.hpp>
#include <boost/python/pure_virtual.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/return_by_value.hpp>
#include <boost/python/make_function.hpp>
#include <boost/python/tuple.hpp>

#include <smtbx/refinement/restraints/origin_fixing.h>

namespace smtbx { namespace refinement { namespace restraints {
  namespace boost_python {

  template <typename FloatType>
  struct origin_fixing_wrapper
  {
    typedef origin_fixing<FloatType> wt;
    typedef typename wt::scalar_t scalar_t;

    struct origin_fixing_scaffold : wt, boost::python::wrapper<wt>
    {
      origin_fixing_scaffold(sgtbx::space_group const &space_group)
      : wt(space_group)
      {}

      af::shared<scalar_t>
      weights(lstbx::normal_equations::linear_ls<scalar_t> &normal_eqns,
              scitbx::sparse::matrix<scalar_t> const
              &jacobian_transpose_matching_grad_fc,
              af::shared<constraints::scatterer_parameters> const &params)
      {
        return this->get_override("weights")(normal_eqns,
                                             jacobian_transpose_matching_grad_fc,
                                             params);
      }
    };

    static boost::python::tuple singular_directions(wt const &self) {
      using namespace boost::python;
      af::small<af::shared<scalar_t>, 3> const
      &whole_deltas = self.singular_directions();
      switch (whole_deltas.size()) {
        case 3:
          return make_tuple(whole_deltas[0],
                            whole_deltas[1],
                            whole_deltas[2]);
        case 2:
          return make_tuple(whole_deltas[0],
                            whole_deltas[1]);
        case 1:
          return make_tuple(whole_deltas[0]);
        case 0:
        default:
          return boost::python::tuple();

      }
    }

    static void wrap(char const *name) {
      using namespace boost::python;
      return_value_policy<return_by_value> rbv;
      class_<origin_fixing_scaffold, boost::noncopyable>(name, no_init)
        .def(init<sgtbx::space_group const &>())
        .def("add_to", &wt::add_to,
             (arg("normal_equations"),
              arg("jacobian_transpose_matching_grad_fc"),
              arg("scatterer_parameters")))
        .def("weights", pure_virtual(&wt::weights),
             (arg("normal_equations"),
              arg("jacobian_transpose_matching_grad_fc"),
              arg("scatterer_parameters")))
        .add_property("origin_shifts",
                      make_function(&wt::origin_shifts, rbv))
        .add_property("has_floating_directions",  &wt::has_floating_directions)
        .add_property("singular_directions", singular_directions)
        ;
    }
  };

  void wrap_origin_fixing_restraints() {
    origin_fixing_wrapper<double>::wrap("origin_fixing");
  }

}}}}


text:
// Copyright 2009 Dean Michael Berris, Jeroen Habraken.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt of copy at
// http://www.boost.org/LICENSE_1_0.txt)

#define BOOST_TEST_MODULE URL Test
#include <boost/config/warning_disable.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/network/uri.hpp>
#include <algorithm>

namespace test_suite {
template <
    class Uri
    >
void constructor_test(Uri instance,
                      const typename Uri::string_type &scheme_,
                      const typename Uri::string_type &rest_) {
    BOOST_CHECK(scheme(instance) == scheme_);
    BOOST_CHECK(valid(instance));
}

template <
    class Uri
    >
void copy_constructor_test(Uri instance) {
    Uri copy = instance;
    BOOST_CHECK(scheme(instance) == scheme(copy));
}

template <
    class Uri
    >
void assignment_test(Uri instance) {
    Uri copy;
    copy = instance;
    BOOST_CHECK(scheme(instance) == scheme(copy));
}

template <
    class Uri
    >
void http_full_uri_test(Uri instance,
                        const typename Uri::string_type &scheme_,
                        const typename Uri::string_type &rest_,
                        const typename Uri::string_type &user_info_,
                        const typename Uri::string_type &host_,
                        boost::uint16_t port_,
                        const typename Uri::string_type &path_,
                        const typename Uri::string_type &query_,
                        const typename Uri::string_type &fragment_) {
    using namespace boost::network::uri;

    BOOST_CHECK(scheme(instance) == scheme_);
    BOOST_CHECK(user_info(instance) == user_info_);
    BOOST_CHECK(host(instance) == host_);
    BOOST_CHECK(port(instance) == port_);
    BOOST_CHECK(path(instance) == path_);
    BOOST_CHECK(query(instance) == query_);
    BOOST_CHECK(fragment(instance) == fragment_);
    BOOST_CHECK(valid(instance));
}

template <
    class Uri
    >
void http_simple_uri_test(Uri instance,
                          const typename Uri::string_type &scheme_,
                          const typename Uri::string_type &rest_,
                          const typename Uri::string_type &user_info_,
                          const typename Uri::string_type &host_,
                          boost::uint16_t port_,
                          const typename Uri::string_type &path_,
                          const typename Uri::string_type &query_,
                          const typename Uri::string_type &fragment_) {
    BOOST_CHECK(scheme(instance) == scheme_);
    BOOST_CHECK(user_info(instance) == user_info_);
    BOOST_CHECK(host(instance) == host_);
    BOOST_CHECK(port(instance) == port_);
    BOOST_CHECK(path(instance) == path_);
    BOOST_CHECK(query(instance) == query_);
    BOOST_CHECK(fragment(instance) == fragment_);
    BOOST_CHECK(valid(instance));
}

template <
    class Uri
    >
void https_simple_uri_test(Uri instance,
                           const typename Uri::string_type &scheme_,
                           boost::uint32_t port_) {
    using namespace boost::network::uri;

    BOOST_CHECK(scheme(instance) == scheme_);
    BOOST_CHECK(port(instance) == port_);
}

template <
    class Uri
    >
void http_with_port_test(Uri instance,
                         const typename Uri::string_type &host_,
                         boost::uint16_t port_) {
    using namespace boost::network::uri;

    BOOST_CHECK(host(instance) == host_);
    BOOST_CHECK(port(instance) == port_);
    BOOST_CHECK(valid(instance));
}

template <
    class Uri
    >
void uri_with_spaces_should_fail(Uri instance) {
    using namespace boost::network::uri;

    // I don't know if it's a good idea to test that host and port are
    // set if the URI is invalid.
    // BOOST_CHECK_EQUAL(host(instance), std::string("www.boost.org"));
    // BOOST_CHECK_EQUAL(port(instance), 80u);
    BOOST_CHECK(!valid(instance));
}

template <
    class Uri
    >
void http_with_invalid_scheme_should_fail(Uri instance) {
    using namespace boost::network::uri;
    BOOST_CHECK(!valid(instance));
}

} // namespace test_suite

BOOST_AUTO_TEST_CASE(constructor_test) {
    test_suite::constructor_test(
        boost::network::uri::uri("http://www.boost.org/"),
        "http", "//www.boost.org/");
    test_suite::constructor_test(
        boost::network::uri::wuri(L"http://www.boost.org/"),
        L"http", L"//www.boost.org/");
    test_suite::constructor_test(
        boost::network::uri::uri("http://129.79.245.252/"),
        "http", "//www.boost.org/");
    test_suite::constructor_test(
        boost::network::uri::uri("news:comp.infosystems.www.servers.unix"),
        "news", "comp.infosystems.www.servers.unix");
}

BOOST_AUTO_TEST_CASE(copy_constructor_test) {
    test_suite::copy_constructor_test(
        boost::network::uri::uri("http://www.boost.org/"));
    test_suite::copy_constructor_test(
        boost::network::uri::wuri(L"http://www.boost.org/"));
}

BOOST_AUTO_TEST_CASE(assignment_test) {
    test_suite::assignment_test(
        boost::network::uri::uri("http://www.boost.org/"));
    test_suite::assignment_test(
        boost::network::uri::wuri(L"http://www.boost.org/"));
}

BOOST_AUTO_TEST_CASE(http_full_uri_test) {
    test_suite::http_full_uri_test(
        boost::network::uri::http::uri(
            "http://user:password@www.boost.org/path?query#fragment"),
        "http", "//user:password@www.boost.org/path?query#fragment",
        "user:password", "www.boost.org", 80u, "/path", "query", "fragment");
}

BOOST_AUTO_TEST_CASE(http_simple_uri_test) {
    test_suite::http_simple_uri_test(
        boost::network::uri::http::uri("http://www.boost.org/"),
        "http", "//www.boost.org/", "", "www.boost.org", 80u, "/", "", "");
}

BOOST_AUTO_TEST_CASE(https_simple_uri_test) {
    test_suite::https_simple_uri_test(
        boost::network::uri::http::uri("https://www.boost.org/"),
        "https", 443u);
}

BOOST_AUTO_TEST_CASE(http_with_port_test) {
    test_suite::http_with_port_test(
        boost::network::uri::http::uri("http://www.boost.org:80/"),
        "www.boost.org", 80u);
}

BOOST_AUTO_TEST_CASE(uri_with_spaces_should_fail) {
    test_suite::uri_with_spaces_should_fail(
        boost::network::uri::uri("http://www.boost.org /"));
    test_suite::uri_with_spaces_should_fail(
        boost::network::uri::wuri(L"http://www.boost.org /"));
}

BOOST_AUTO_TEST_CASE(http_with_invalid_scheme_should_fail) {
    boost::network::uri::http::uri uri("ftp://ftp.boost.org/");
    BOOST_CHECK(!valid(uri));
}

max_stars_repo_name: mclow/cpp-netlib

max_issues_repo_name: mclow/cpp-netlib

max_forks_repo_name: mclow/cpp-netlib