text:
/**
 * @file
 * @copyright This code is licensed under the 3-clause BSD license.\n
 *            Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\n
 *            See LICENSE.txt for details.
 */

// Alain 18.12.2014: workaround after VS2013 & intel XE 2015
#ifndef MKL_BLAS
#  define MKL_BLAS MKL_DOMAIN_BLAS
#endif

#include <Utils/Bonds/BondOrderCollection.h>
#include <Utils/DataStructures/AtomsOrbitalsIndexes.h>
#include <Utils/DataStructures/DensityMatrix.h>
#include <Utils/DataStructures/MolecularOrbitals.h>
#include <Utils/DataStructures/SingleParticleEnergies.h>
#include <Utils/DataStructures/SpinAdaptedMatrix.h>
#include <Utils/Math/IterativeDiagonalizer/DavidsonDiagonalizer.h>
#include <Utils/Scf/LcaoUtils/LcaoUtils.h>
#include <Eigen/Eigenvalues>
#include <cmath>

namespace Scine {
namespace Utils {

namespace LcaoUtils {

void getNumberUnrestrictedElectrons(int& nAlpha, int& nBeta, int nElectrons, int spinMultiplicity) {
  assert(nElectrons >= 0);
  assert(spinMultiplicity >= 1);
  assert(spinMultiplicity <= nElectrons + 1 &&
         "Spin multiplicity is invalid with the number of electrons: too few electrons.");
  assert((spinMultiplicity + nElectrons) % 2 == 1 &&
         "Spin multiplicity is invalid with the number of electrons: they can't have the same parity.");
  // NB: system of two equations with two unknowns:
  // nAlpha + nBeta = nElectrons_
  // nAlpha - nBeta = spinMultiplicity - 1
  nAlpha = (nElectrons + spinMultiplicity - 1) / 2;
  nBeta = nElectrons - nAlpha;
}

void solveOccupiedRestrictedEigenvalueProblem(const SpinAdaptedMatrix& fockMatrix, MolecularOrbitals& coefficientMatrix,
                                              SingleParticleEnergies& singleParticleEnergies, int nElectrons) {
  if (fockMatrix.restrictedMatrix().size() == 0) {
    coefficientMatrix = MolecularOrbitals::createEmptyRestrictedOrbitals();
    singleParticleEnergies = SingleParticleEnergies::createEmptyRestrictedEnergies();
    return;
  }

  int nOccupied = nElectrons / 2;
  DavidsonDiagonalizer<Eigen::MatrixXd, DavidsonBalancedType::balanced> diagonalizer(nOccupied, nOccupied,
                                                                                fockMatrix.restrictedMatrix().cols());
  diagonalizer.setMatrixToDiagonalize(fockMatrix.restrictedMatrix());
  auto eigenPairs = diagonalizer.solve();
  eigenPairs.second.conservativeResize(Eigen::NoChange, fockMatrix.restrictedMatrix().cols());
  coefficientMatrix = MolecularOrbitals::createFromRestrictedCoefficients(std::move(eigenPairs.second));
  singleParticleEnergies.setRestricted(eigenPairs.first);
}

void solveOccupiedRestrictedGeneralizedEigenvalueProblem(const SpinAdaptedMatrix& fockMatrix,
                                                         const Eigen::MatrixXd& overlapMatrix,
                                                         MolecularOrbitals& coefficientMatrix,
                                                         SingleParticleEnergies& singleParticleEnergies, int nElectrons) {
  if (fockMatrix.restrictedMatrix().size() == 0) {
    coefficientMatrix = MolecularOrbitals::createEmptyRestrictedOrbitals();
    singleParticleEnergies = SingleParticleEnergies::createEmptyRestrictedEnergies();
    return;
  }
  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(overlapMatrix);
  const Eigen::MatrixXd invSqrtS = es.operatorInverseSqrt();
  const Eigen::MatrixXd modifiedFock =
      invSqrtS.selfadjointView<Eigen::Upper>() * fockMatrix.restrictedMatrix() * invSqrtS.selfadjointView<Eigen::Upper>();
  int nOccupied = nElectrons / 2;
  DavidsonDiagonalizer<Eigen::MatrixXd, DavidsonBalancedType::balanced> diagonalizer(nOccupied, nOccupied,
                                                                                fockMatrix.restrictedMatrix().cols());
  diagonalizer.setMatrixToDiagonalize(modifiedFock);
  auto eigenPairs = diagonalizer.solve();
  Eigen::MatrixXd deOrthogonalizedCoefficients = invSqrtS.selfadjointView<Eigen::Upper>() * eigenPairs.second;
  deOrthogonalizedCoefficients.conservativeResize(Eigen::NoChange, fockMatrix.restrictedMatrix().cols());
  coefficientMatrix = MolecularOrbitals::createFromRestrictedCoefficients(deOrthogonalizedCoefficients);
  singleParticleEnergies.setRestricted(eigenPairs.first);
}

void solveOccupiedUnrestrictedEigenvalueProblem(const SpinAdaptedMatrix& fockMatrix, MolecularOrbitals& coefficientMatrix,
                                                SingleParticleEnergies& singleParticleEnergies, int nAlphaElectrons,
                                                int nBetaElectrons) {
  if (fockMatrix.alphaMatrix().size() == 0) {
    coefficientMatrix = MolecularOrbitals::createEmptyUnrestrictedOrbitals();
    singleParticleEnergies = SingleParticleEnergies::createEmptyUnrestrictedEnergies();
    return;
  }

  DavidsonDiagonalizer<Eigen::MatrixXd, DavidsonBalancedType::balanced> diagonalizerAlpha(
      nAlphaElectrons, nAlphaElectrons, fockMatrix.alphaMatrix().cols());
  diagonalizerAlpha.setMatrixToDiagonalize(fockMatrix.alphaMatrix());
  auto alphaEigenPairs = diagonalizerAlpha.solve();
  alphaEigenPairs.second.conservativeResize(Eigen::NoChange, fockMatrix.alphaMatrix().cols());
  coefficientMatrix = MolecularOrbitals::createFromRestrictedCoefficients(std::move(alphaEigenPairs.second));
  singleParticleEnergies.setRestricted(alphaEigenPairs.first);

  DavidsonDiagonalizer<Eigen::MatrixXd, DavidsonBalancedType::balanced> diagonalizerBeta(nBetaElectrons, nBetaElectrons,
                                                                                fockMatrix.betaMatrix().cols());
  diagonalizerBeta.setMatrixToDiagonalize(fockMatrix.betaMatrix());
  auto betaEigenPairs = diagonalizerBeta.solve();
  betaEigenPairs.second.conservativeResize(Eigen::NoChange, fockMatrix.betaMatrix().cols());
  coefficientMatrix = MolecularOrbitals::createFromRestrictedCoefficients(std::move(betaEigenPairs.second));
  singleParticleEnergies.setRestricted(betaEigenPairs.first);
}

void solveOccupiedUnrestrictedGeneralizedEigenvalueProblem(const SpinAdaptedMatrix& fockMatrix,
                                                           const Eigen::MatrixXd& overlapMatrix,
                                                           MolecularOrbitals& coefficientMatrix,
                                                           SingleParticleEnergies& singleParticleEnergies,
                                                           int nAlphaElectrons, int nBetaElectrons) {
  if (fockMatrix.alphaMatrix().size() == 0) {
    coefficientMatrix = MolecularOrbitals::createEmptyUnrestrictedOrbitals();
    singleParticleEnergies = SingleParticleEnergies::createEmptyUnrestrictedEnergies();
    return;
  }
  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(overlapMatrix);
  const Eigen::MatrixXd invSqrtS = es.operatorInverseSqrt();
  const Eigen::MatrixXd modifiedAlphaFock =
      invSqrtS.selfadjointView<Eigen::Upper>() * fockMatrix.alphaMatrix() * invSqrtS.selfadjointView<Eigen::Upper>();
  const Eigen::MatrixXd modifiedBetaFock =
      invSqrtS.selfadjointView<Eigen::Upper>() * fockMatrix.betaMatrix() * invSqrtS.selfadjointView<Eigen::Upper>();

  DavidsonDiagonalizer<Eigen::MatrixXd, DavidsonBalancedType::balanced> diagonalizerAlpha(
      nAlphaElectrons, nAlphaElectrons, fockMatrix.alphaMatrix().cols());
  auto alphaEigenPairs = diagonalizerAlpha.solve();
  Eigen::MatrixXd alphaDeorthogonalizedCoefficients = invSqrtS.selfadjointView<Eigen::Upper>() * alphaEigenPairs.second;
  alphaDeorthogonalizedCoefficients.conservativeResize(Eigen::NoChange, fockMatrix.alphaMatrix().cols());
  coefficientMatrix = MolecularOrbitals::createFromRestrictedCoefficients(std::move(alphaDeorthogonalizedCoefficients));
  singleParticleEnergies.setRestricted(alphaEigenPairs.first);

  DavidsonDiagonalizer<Eigen::MatrixXd, DavidsonBalancedType::balanced> diagonalizerBeta(nBetaElectrons, nBetaElectrons,
                                                                                fockMatrix.betaMatrix().cols());
  auto betaEigenPairs = diagonalizerBeta.solve();
  Eigen::MatrixXd betaDeorthogonalizedCoefficients = invSqrtS.selfadjointView<Eigen::Upper>() * betaEigenPairs.second;
  betaDeorthogonalizedCoefficients.conservativeResize(Eigen::NoChange, fockMatrix.betaMatrix().cols());
  coefficientMatrix = MolecularOrbitals::createFromRestrictedCoefficients(std::move(betaDeorthogonalizedCoefficients));
  singleParticleEnergies.setRestricted(betaEigenPairs.first);
}

void solveRestrictedEigenvalueProblem(const SpinAdaptedMatrix& fockMatrix, MolecularOrbitals& coefficientMatrix,
                                      SingleParticleEnergies& singleParticleEnergies) {
  if (fockMatrix.restrictedMatrix().size() == 0) {
    coefficientMatrix = MolecularOrbitals::createEmptyRestrictedOrbitals();
    singleParticleEnergies = SingleParticleEnergies::createEmptyRestrictedEnergies();
    return;
  }

  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es;
  es.compute(fockMatrix.restrictedMatrix());
  coefficientMatrix = MolecularOrbitals::createFromRestrictedCoefficients(es.eigenvectors());
  singleParticleEnergies.setRestricted(es.eigenvalues());
}

void solveRestrictedGeneralizedEigenvalueProblem(const SpinAdaptedMatrix& fockMatrix, const Eigen::MatrixXd& overlapMatrix,
                                                 MolecularOrbitals& coefficientMatrix,
                                                 SingleParticleEnergies& singleParticleEnergies) {
  if (fockMatrix.restrictedMatrix().size() == 0) {
    coefficientMatrix = MolecularOrbitals::createEmptyRestrictedOrbitals();
    singleParticleEnergies = SingleParticleEnergies::createEmptyRestrictedEnergies();
    return;
  }

  Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> ges;
  ges.compute(fockMatrix.restrictedMatrix(), overlapMatrix);
  coefficientMatrix = MolecularOrbitals::createFromRestrictedCoefficients(ges.eigenvectors());
  singleParticleEnergies.setRestricted(ges.eigenvalues());
}

void solveUnrestrictedEigenvalueProblem(const SpinAdaptedMatrix& fockMatrix, MolecularOrbitals& coefficientMatrix,
                                        SingleParticleEnergies& singleParticleEnergies) {
  if (fockMatrix.alphaMatrix().size() == 0) {
    coefficientMatrix = MolecularOrbitals::createEmptyUnrestrictedOrbitals();
    singleParticleEnergies = SingleParticleEnergies::createEmptyUnrestrictedEnergies();
    return;
  }

  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es;

  es.compute(fockMatrix.alphaMatrix());
  Eigen::MatrixXd alphaCoefficients = es.eigenvectors();
  Eigen::VectorXd alpha = es.eigenvalues();

  es.compute(fockMatrix.betaMatrix());
  Eigen::MatrixXd betaCoefficients = es.eigenvectors();
  Eigen::VectorXd beta = es.eigenvalues();

  coefficientMatrix =
      MolecularOrbitals::createFromUnrestrictedCoefficients(std::move(alphaCoefficients), std::move(betaCoefficients));

  singleParticleEnergies.setUnrestricted(alpha, beta);
}

void solveUnrestrictedGeneralizedEigenvalueProblem(const SpinAdaptedMatrix& fockMatrix, const Eigen::MatrixXd& overlapMatrix,
                                                   MolecularOrbitals& coefficientMatrix,
                                                   SingleParticleEnergies& singleParticleEnergies) {
  if (fockMatrix.alphaMatrix().size() == 0) {
    coefficientMatrix = MolecularOrbitals::createEmptyUnrestrictedOrbitals();
    singleParticleEnergies = SingleParticleEnergies::createEmptyUnrestrictedEnergies();
    return;
  }

  Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> ges;

  ges.compute(fockMatrix.alphaMatrix(), overlapMatrix);
  Eigen::MatrixXd alphaCoefficients = ges.eigenvectors();
  Eigen::VectorXd alpha = ges.eigenvalues();

  ges.compute(fockMatrix.betaMatrix(), overlapMatrix);
  Eigen::MatrixXd betaCoefficients = ges.eigenvectors();
  Eigen::VectorXd beta = ges.eigenvalues();

  coefficientMatrix =
      MolecularOrbitals::createFromUnrestrictedCoefficients(std::move(alphaCoefficients), std::move(betaCoefficients));

  singleParticleEnergies.setUnrestricted(alpha, beta);
}

void calculateRestrictedDensityMatrix(DensityMatrix& densityMatrix, const MolecularOrbitals& coefficientMatrix, int nElectrons) {
  assert(nElectrons >= 0);
  const auto& C = coefficientMatrix.restrictedMatrix();
  auto nAOs = C.cols();
  Eigen::MatrixXd P = 2 * C.block(0, 0, nAOs, nElectrons / 2) * C.block(0, 0, nAOs, nElectrons / 2).transpose();

  if ((nElectrons % 2) != 0) { // if odd number of electrons
    P += C.col(nElectrons / 2) * C.col(nElectrons / 2).transpose();
  }

  densityMatrix.setDensity(std::move(P), nElectrons);
}

void calculateUnrestrictedDensityMatrices(DensityMatrix& densityMatrix, const MolecularOrbitals& coefficientMatrix,
                                          int nElectrons, int spinMultiplicity) {
  assert(nElectrons >= 0);
  assert(spinMultiplicity >= 1);

  int nAlpha, nBeta;
  getNumberUnrestrictedElectrons(nAlpha, nBeta, nElectrons, spinMultiplicity);

  const auto& cA = coefficientMatrix.alphaMatrix();
  const auto& cB = coefficientMatrix.betaMatrix();
  auto nAOs = cA.cols();
  Eigen::MatrixXd alphaMatrix = cA.block(0, 0, nAOs, nAlpha) * cA.block(0, 0, nAOs, nAlpha).transpose();
  Eigen::MatrixXd betaMatrix = cB.block(0, 0, nAOs, nBeta) * cB.block(0, 0, nAOs, nBeta).transpose();
  densityMatrix.setDensity(std::move(alphaMatrix), std::move(betaMatrix), nAlpha, nBeta);
}

void calculateRestrictedEnergyWeightedDensityMatrix(Eigen::MatrixXd& energyWeightedDensityMatrix,
                                                    const MolecularOrbitals& coefficientMatrix,
                                                    const SingleParticleEnergies& singleParticleEnergies, int nElectrons) {
  assert(nElectrons >= 0);
  const auto& C = coefficientMatrix.restrictedMatrix();
  auto nAOs = C.cols();

  Eigen::MatrixXd CEn(nAOs, (nElectrons + 1) / 2); // Eigenvector matrix multiplied by energy eigenvalues

  for (int i = 0; i < (nElectrons + 1) / 2; i++)
    CEn.col(i) = C.col(i) * singleParticleEnergies.getRestrictedEnergies()[i];

  energyWeightedDensityMatrix =
      2 * C.block(0, 0, nAOs, (nElectrons) / 2) * CEn.block(0, 0, nAOs, (nElectrons) / 2).transpose();

  if ((nElectrons % 2) != 0) // if odd number of electrons
    energyWeightedDensityMatrix += C.col(nElectrons / 2) * CEn.col(nElectrons / 2).transpose();
}

void calculateUnrestrictedEnergyWeightedDensityMatrix(Eigen::MatrixXd& energyWeightedDensityMatrix,
                                                      const MolecularOrbitals& coefficientMatrix,
                                                      const SingleParticleEnergies& singleParticleEnergies,
                                                      int nElectrons, int spinMultiplicity) {
  assert(nElectrons >= 0);
  assert(spinMultiplicity >= 1);

  int nAlpha, nBeta;
  getNumberUnrestrictedElectrons(nAlpha, nBeta, nElectrons, spinMultiplicity);

  const auto& cA = coefficientMatrix.alphaMatrix();
  const auto& cB = coefficientMatrix.betaMatrix();
  auto nAOs = cA.cols();

  Eigen::MatrixXd CEnAlpha(nAOs, nAlpha); // Alpha Eigenvector matrix multiplied by energy eigenvalues
  Eigen::MatrixXd CEnBeta(nAOs, nBeta);   // Beta Eigenvector matrix multiplied by energy eigenvalues

  for (int i = 0; i < nAlpha; i++)
    CEnAlpha.col(i) = cA.col(i) * singleParticleEnergies.getAlphaEnergies()[i];
  for (int i = 0; i < nBeta; i++)
    CEnBeta.col(i) = cB.col(i) * singleParticleEnergies.getBetaEnergies()[i];

  energyWeightedDensityMatrix = cA.block(0, 0, nAOs, nAlpha) * CEnAlpha.block(0, 0, nAOs, nAlpha).transpose() +
                                cB.block(0, 0, nAOs, nBeta) * CEnBeta.block(0, 0, nAOs, nBeta).transpose();
}

void calculateBondOrderMatrix(Utils::BondOrderCollection& bondOrderMatrix, const DensityMatrix& densityMatrix,
                              const Eigen::MatrixXd& overlapMatrix, const AtomsOrbitalsIndexes& aoIndexes) {
  // Bond order analysis (Mayer bond order)
  Eigen::MatrixXd PS = densityMatrix.restrictedMatrix() * overlapMatrix; // TODO: WHAT IF OVERLAP MATRIX IS ONLY
                                                                         // LOWER-TRIANGULAR?
  for (int i = 1; i < aoIndexes.getNAtomicOrbitals(); i++)
    for (int j = 0; j < i; j++)
      PS(i, j) = PS(i, j) * PS(j, i);
  for (int a = 1; a < aoIndexes.getNAtoms(); a++) {
    for (int b = 0; b < a; b++) {
      double order = PS.block(aoIndexes.getFirstOrbitalIndex(a), aoIndexes.getFirstOrbitalIndex(b),
                              aoIndexes.getNOrbitals(a), aoIndexes.getNOrbitals(b))
                         .sum();
      bondOrderMatrix.setOrder(a, b, order);
    }
  }
}

void calculateOrthonormalBondOrderMatrix(Utils::BondOrderCollection& bondOrderMatrix,
                                         const DensityMatrix& densityMatrix, const AtomsOrbitalsIndexes& aoIndexes) {
  // Bond order analysis (Mayer bond order), no need for overlap since it is no generalized eigenvalue problem
  const auto& P = densityMatrix.restrictedMatrix();
  Eigen::MatrixXd P2 = P.cwiseProduct(P);

  for (int a = 1; a < aoIndexes.getNAtoms(); a++) {
    for (int b = 0; b < a; b++) {
      double order = P2.block(aoIndexes.getFirstOrbitalIndex(a), aoIndexes.getFirstOrbitalIndex(b),
                              aoIndexes.getNOrbitals(a), aoIndexes.getNOrbitals(b))
                         .sum();
      bondOrderMatrix.setOrder(a, b, order);
    }
  }
}

void calculateOrthonormalAtomicCharges(std::vector<double>& mullikenCharges, const std::vector<double>& coreCharges,
                                       const DensityMatrix& densityMatrix, const AtomsOrbitalsIndexes& aoIndexes) {
  // in the case of an orthonormal basis, the partial charge of an atom is given as
  // q_A = Z_A - \sum_{i in A} P_ii
  for (int a = 0; a < aoIndexes.getNAtoms(); a++) {
    mullikenCharges[a] = coreCharges[a];
    int nAOsA = aoIndexes.getNOrbitals(a);
    int index = aoIndexes.getFirstOrbitalIndex(a);

    double nElectronsOnAtom = densityMatrix.restrictedMatrix().block(index, index, nAOsA, nAOsA).trace();
    mullikenCharges[a] = coreCharges[a] - nElectronsOnAtom;
  }
}

void calculateMullikenAtomicCharges(std::vector<double>& mullikenCharges, const std::vector<double>& coreCharges,
                                    const DensityMatrix& densityMatrix, const Eigen::MatrixXd& overlapMatrix,
                                    const AtomsOrbitalsIndexes& aoIndexes) {
  // Calculation of the Mulliken charges as described in elstner1998
  Eigen::MatrixXd D = densityMatrix.restrictedMatrix().cwiseProduct(overlapMatrix); // population matrix

  for (int a = 0; a < aoIndexes.getNAtoms(); a++) {
    mullikenCharges[a] = coreCharges[a];
    int nAOsA = aoIndexes.getNOrbitals(a);
    int index = aoIndexes.getFirstOrbitalIndex(a);

    for (int mu = 0; mu < nAOsA; mu++) {
      for (int nu = 0; nu < aoIndexes.getNAtomicOrbitals(); nu++)
        mullikenCharges[a] -= D(index + mu, nu);
    }
  }
}

} // namespace LcaoUtils
} // namespace Utils
} // namespace Scine

max_stars_repo_name: DockBio/utilities

max_issues_repo_name: DockBio/utilities

max_forks_repo_name: DockBio/utilities


text:
//*****************************************************************************
// Copyright (c) 2003. All rights reserved.
// Developed by Jarl Lindrud.
// Contact: jlindrud@hotmail.com .
//*****************************************************************************

#ifndef _UTIL_THROW_HPP_
#define _UTIL_THROW_HPP_

#include <exception>

#include <boost/current_function.hpp>

#include "VariableArgMacro.hpp"

namespace util {

    template<typename E>
    struct ThrowFunctor : public VariableArgMacroFunctor
    {
        ~ThrowFunctor()
        {
            if (!std::uncaught_exception())
            {
                throw E( (header.str() + args.str()).c_str() );
            }
        }
    };

#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4355 )  // warning C4355: 'this' : used in base member initializer list
#endif

#ifdef NDEBUG

    #define UTIL_THROW(E, msg)                throw E(msg); DUMMY_VARIABLE_ARG_MACRO()

#else

    DECLARE_VARIABLE_ARG_MACRO_T1( UTIL_THROW, ThrowFunctor );
    #define UTIL_THROW(E, msg)                while (true) util::VariableArgMacro<util::ThrowFunctor< E > >().init( "THROW : " #E ": ", msg, __FILE__, __LINE__, BOOST_CURRENT_FUNCTION ).cast( (util::VariableArgMacro<util::ThrowFunctor< E > > *) NULL ).UTIL_THROW_A
    #define UTIL_THROW_A(x)                   UTIL_THROW_OP(x, B)
    #define UTIL_THROW_B(x)                   UTIL_THROW_OP(x, A)
    #define UTIL_THROW_OP(x, next)            UTIL_THROW_A.notify_((x), #x).UTIL_THROW_ ## next

#endif

#ifdef _MSC_VER
#pragma warning( pop )
#endif

} // namespace util

#endif // ! _UTIL_THROW_HPP_

ext: hpp

max_stars_repo_name: importlib/klib

max_issues_repo_name: isuhao/klib

max_forks_repo_name: isuhao/klib


text:
// Copyright 2019 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_UTILITY_DETAIL_NAMED_PROXY_HPP
#define METALL_UTILITY_DETAIL_NAMED_PROXY_HPP

#include <boost/interprocess/detail/named_proxy.hpp>

namespace metall {
namespace detail {
namespace utility {

template <typename segment_manager, typename T, bool is_iterator>
using named_proxy = boost::interprocess::ipcdetail::named_proxy<segment_manager, T, is_iterator>;

} // namespace utility
} // namespace detail
} // namespace metall

#endif //METALL_UTILITY_DETAIL_NAMED_PROXY_HPP

max_stars_repo_name: correaa/metall

max_issues_repo_name: correaa/metall

max_forks_repo_name: correaa/metall


text:
/*
  Reality plug-in
  Copyright (c) Pret-a-3D/Paolo Ciccone 2014. All rights reserved.
*/

#include "ReSceneDataGlobal.h"
#include "RePythonSceneExporter.h"
#include "RePythonTools.h"
#include <boost/python.hpp>

#ifdef __clang__
// Avoid being harassed about missing switch cases and other thing.
#pragma clang diagnostic ignored "-Wswitch"
#endif

namespace python = boost::python;

using namespace Reality;

void RePythonSceneExporter::exportScene( const int frameNo,
                                         boost::any& data )
{
  try {
    python::dict pySceneData;
    data = pySceneData;
    auto exporter = RealitySceneData->getSceneExporter("map");
    boost::any sceneData;
    // No matter what is passed in the frameNo parameter, we specify
    // zero because we are not rendering but exporting the data for saving
    exporter->exportScene(0, sceneData);
    QVariantMap qSceneData = boost::any_cast<QVariantMap>(sceneData);
    QVariantMapToDict(qSceneData, pySceneData);
  }
  catch(...) {
    RE_LOG_INFO() << "Error in conversion of scene data";
  }
}

ext: cpp


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

#include "SectionDNACertificate.h"

#include "XclBinUtilities.h"
#include <boost/format.hpp>
#include <boost/functional/factory.hpp>
#include <string>

namespace XUtil = XclBinUtilities;

// Static Variables / Classes
SectionDNACertificate::init SectionDNACertificate::initializer;

SectionDNACertificate::init::init()
{
  auto sectionInfo = std::make_unique<SectionInfo>(DNA_CERTIFICATE, "DNA_CERTIFICATE", boost::factory<SectionDNACertificate*>());

  addSectionType(std::move(sectionInfo));
}

#define signatureSizeBytes 512

#define dnaEntrySizeBytes 12

struct dnaEntry {
  char bytes[dnaEntrySizeBytes];
};

#define dnaByteAlignment 64

void
SectionDNACertificate::marshalToJSON(char* _pDataSection,
                                     unsigned int _sectionSize,
                                     boost::property_tree::ptree& _ptree) const
{
  XUtil::TRACE("");
  XUtil::TRACE("Extracting: DNA_CERTIFICATE");
  XUtil::TRACE_BUF("Section Buffer", reinterpret_cast<const char*>(_pDataSection), _sectionSize);

  if ((_sectionSize % dnaByteAlignment ) != 0) {
    auto errMsg = boost::format("ERROR: The DNA_CERTIFICATE section size doesn't align to 64 byte boundaries.  Current size: %ld") % _sectionSize;
    throw std::runtime_error(errMsg.str());
  }

  static const int minimumSectionSizeBytes = signatureSizeBytes + dnaByteAlignment;
  if (_sectionSize < minimumSectionSizeBytes ) {
    auto errMsg = boost::format("ERROR: The DNA_CERTIFICATE section size (%ld) is smaller then the minimum section permitted (%ld).") % _sectionSize % minimumSectionSizeBytes;
    throw std::runtime_error(errMsg.str());
  }

  // Get the dnsSignature
  std::string sDNSSignature;
  XUtil::binaryBufferToHexString((unsigned char *) &_pDataSection[_sectionSize - signatureSizeBytes], signatureSizeBytes, sDNSSignature);

  // Get the number of sections
  unsigned char *pWorking = (unsigned char *) &_pDataSection[_sectionSize - signatureSizeBytes - sizeof (uint64_t)];
  XUtil::TRACE_BUF("DNA Entries", (char *) pWorking, sizeof(uint64_t));
  uint64_t dnaEntriesBitSize = 0;;
  for (unsigned int index = 0; index < sizeof(uint64_t); ++index) {
    dnaEntriesBitSize = dnaEntriesBitSize << 8;
    dnaEntriesBitSize += (uint64_t) pWorking[index];
  }

  // Instead of dividing by 8 we multiple the other side by 8
  if ((dnaEntriesBitSize % (8 * dnaEntrySizeBytes)) != 0) {
    auto errMsg = boost::format("ERROR: The DNA_CERTIFICATE reserved DNA entries bit size (0x%lx) does not align with the byte boundary (0x%lx)") % dnaEntriesBitSize % dnaEntrySizeBytes;
    throw std::runtime_error(errMsg.str());
  }

  if (((dnaEntriesBitSize / 8) > _sectionSize)) {
    auto errMsg = boost::format("ERROR: The message DNA length (0x%x bytes) exceeds the DNA_CERTIFICATE size (0x%x bytes).") % (dnaEntriesBitSize / 8) % _sectionSize;
    throw std::runtime_error(errMsg.str());
  }

  uint64_t dnaEntryCount = (dnaEntriesBitSize / 8) / dnaEntrySizeBytes;
  XUtil::TRACE("DNA Entry Count: " + std::to_string(dnaEntryCount));

  // Get padding string
  std::string sPadding;
  uint64_t paddingOffset = dnaEntryCount * dnaEntrySizeBytes;
  uint64_t paddingSize = (_sectionSize - signatureSizeBytes) - paddingOffset;
  XUtil::binaryBufferToHexString((unsigned char *) &_pDataSection[paddingOffset], paddingSize, sPadding);

  boost::property_tree::ptree dna_list;
  struct dnaEntry *dnaEntries = reinterpret_cast<struct dnaEntry *>((void *)_pDataSection);

  for (unsigned int index = 0; index < dnaEntryCount; ++index) {
    std::string dnaString;
    XUtil::binaryBufferToHexString((unsigned char *) &dnaEntries[index], dnaEntrySizeBytes, dnaString);

    boost::property_tree::ptree ptDNA;
    ptDNA.put("", dnaString.c_str());
    dna_list.push_back(std::make_pair("", ptDNA));
  }
  XUtil::TRACE_PrintTree("DNA_LIST", dna_list);

  boost::property_tree::ptree ptDNACertificate;
  ptDNACertificate.add_child("dna_list", dna_list);
  ptDNACertificate.put("padding", sPadding.c_str());
  ptDNACertificate.put("signature", sDNSSignature.c_str());

  XUtil::TRACE_PrintTree("DNA_TREE", ptDNACertificate);

  _ptree.add_child("dna_certificate", ptDNACertificate);
}

bool
SectionDNACertificate::doesSupportDumpFormatType(FormatType _eFormatType) const
{
    if ((_eFormatType == FormatType::JSON) ||
        (_eFormatType == FormatType::HTML) ||
        (_eFormatType == FormatType::RAW))
    {
      return true;
    }

    return false;
}

ext: cxx

max_stars_repo_name: mariodruiz/XRT

max_issues_repo_name: mariodruiz/XRT

max_forks_repo_name: mariodruiz/XRT


text:
/* MLDB-1742-tabular-dataset-integer-columns.cc
   Jeremy Barnes, 20 March 2015
   Copyright (c) 2015 mldb.ai inc.  All rights reserved.

*/

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <boost/algorithm/string.hpp>
#include <boost/test/unit_test.hpp>
#include "mldb/plugins/tabular/frozen_column.h"
#include "mldb/plugins/tabular/tabular_dataset_column.h"
#include "mldb/server/mldb_server.h"
#include "mldb/arch/timers.h"
#include "mldb/types/set_description.h"
#include "mldb/types/vector_description.h"

using namespace std;

using namespace MLDB;

std::shared_ptr<FrozenColumn>
freezeAndTest(const std::vector<CellValue> & cells, size_t offset = 0)
{
    TabularDatasetColumn col;
    MemorySerializer serializer;

    BOOST_CHECK_EQUAL(col.columnTypes.numStrings, 0);

    for (size_t i = 0;  i < cells.size();  ++i) {
        col.add(i + offset, cells[i]);
    }

    ColumnFreezeParameters params;
    std::shared_ptr<FrozenColumn> frozen = col.freeze(serializer, params);

    cerr << "testing " << MLDB::type_name(*frozen) << " with "
         << cells.size() << " values and offset " << offset << endl;
    if (cells.size() < 100)
        cerr << jsonEncodeStr(cells) << endl;

    ExcAssertEqual(frozen->size(), cells.size());

    for (size_t i = 0;  i < cells.size();  ++i) {
        BOOST_REQUIRE_EQUAL(frozen->get(i + offset), cells[i]);
    }

    {
        std::vector<CellValue> outVals(cells.size());
        std::set<int64_t> done;
        size_t numDone = 0;

        auto onEntry = [&] (int64_t rowNum, CellValue val)
            {
                //cerr << "got " << val << " at row " << rowNum << endl;
                BOOST_CHECK_GE(rowNum, offset);
                BOOST_CHECK_LT(rowNum, offset + cells.size());
                BOOST_CHECK_EQUAL(done.count(rowNum), false);
                done.insert(rowNum);
                outVals[rowNum - offset] = std::move(val);
                ++numDone;
                return true;
            };

        frozen->forEachDense(onEntry);

        BOOST_CHECK_EQUAL(numDone, cells.size());

        for (size_t i = 0;  i < outVals.size();  ++i) {
            BOOST_CHECK_EQUAL(cells[i], outVals[i]);
        }
    }

    {
        std::vector<CellValue> outVals(cells.size());
        std::set<int64_t> done;

        auto onEntry = [&] (int64_t rowNum, CellValue val)
            {
                if (val.empty()) {
                    cerr << "rowNum " <<rowNum << " has null" << endl;
                }
                BOOST_CHECK_GE(rowNum, offset);
                BOOST_CHECK_LT(rowNum, offset + cells.size());
                BOOST_CHECK_EQUAL(done.count(rowNum), false);
                BOOST_CHECK(!val.empty());
                done.insert(rowNum);
                outVals[rowNum - offset] = std::move(val);
                return true;
            };

        frozen->forEach(onEntry);

        for (size_t i = 0;  i < outVals.size();  ++i) {
            BOOST_CHECK_EQUAL(cells[i], outVals[i]);
        }
    }

    {
        std::set<CellValue> vals, cellVals;

        auto onDistinct = [&] (CellValue val)
            {
                bool inserted = vals.insert(val).second;
                if (!inserted) {
                    cerr << "error on " << jsonEncodeStr(val) << endl;
                }
                BOOST_CHECK(inserted);
                return true;
            };

        frozen->forEachDistinctValue(onDistinct);

        for (auto & c: cells) {
            if (!vals.count(c)) {
                cerr << "error on " << jsonEncodeStr(c) << endl;
            }
            BOOST_CHECK_EQUAL(vals.count(c), 1);
            cellVals.insert(c);
        }

        if (vals != cellVals) {
            cerr << jsonEncodeStr(vals) << endl;
            cerr << jsonEncodeStr(cellVals) << endl;
        }

        BOOST_CHECK_EQUAL_COLLECTIONS(vals.begin(), vals.end(),
                                      cellVals.begin(), cellVals.end());
    }

    BOOST_REQUIRE_EQUAL(frozen->size(), cells.size());

    return frozen;
}

// Simple positive and zero integers
BOOST_AUTO_TEST_CASE( test_frozen_ints_only )
{
    std::vector<CellValue> vals;
    for (unsigned i = 0;  i < 100;  ++i) {
        vals.push_back(i);
    }

    auto frozen = freezeAndTest(vals);

    BOOST_CHECK_EQUAL(MLDB::type_name(*frozen),
                      "MLDB::IntegerFrozenColumn");

    freezeAndTest(vals, 1020 /* offset */);
}

// Simple positive and null integers
BOOST_AUTO_TEST_CASE( test_frozen_ints_and_nulls_only )
{
    std::vector<CellValue> vals;
    for (int i = 0;  i < 100;  ++i) {
        vals.push_back(i);
    }
    vals.emplace_back();  // add a null

    auto frozen = freezeAndTest(vals);

    BOOST_CHECK_EQUAL(MLDB::type_name(*frozen),
                      "MLDB::IntegerFrozenColumn");

    freezeAndTest(vals, 1020 /* offset */);
}

// Simple negative, positive and null integers
BOOST_AUTO_TEST_CASE( test_frozen_neg_ints )
{
    std::vector<CellValue> vals;
    for (int i = 0;  i < 100;  ++i) {
        vals.push_back(i);
        vals.push_back(-i);
    }

    auto frozen = freezeAndTest(vals);

    BOOST_CHECK_EQUAL(MLDB::type_name(*frozen),
                   "MLDB::IntegerFrozenColumn");

    freezeAndTest(vals, 1020 /* offset */);
}

// Simple negative, positive and null integers
BOOST_AUTO_TEST_CASE( test_frozen_neg_ints_and_nulls_only )
{
    std::vector<CellValue> vals;
    for (int i = 0;  i < 100;  ++i) {
        vals.push_back(i);
        vals.push_back(-i);
    }
    vals.emplace_back();  // add a null

    auto frozen = freezeAndTest(vals);

    BOOST_CHECK_EQUAL(MLDB::type_name(*frozen),
                   "MLDB::IntegerFrozenColumn");

    freezeAndTest(vals, 1020 /* offset */);
}

// Simple negative, positive and null integers
BOOST_AUTO_TEST_CASE( test_frozen_neg_only_ints_and_nulls )
{
    std::vector<CellValue> vals;
    for (int i = 0;  i < 100;  ++i) {
        vals.push_back(-i-1);
    }
    vals.emplace_back();  // add a null

    auto frozen = freezeAndTest(vals);

    BOOST_CHECK_EQUAL(MLDB::type_name(*frozen),
                   "MLDB::IntegerFrozenColumn");

    freezeAndTest(vals, 1020 /* offset */);
}

// Simple negative, positive and null integers
BOOST_AUTO_TEST_CASE( test_large_positive_ints )
{
    std::vector<CellValue> vals;

    // Check for large integers (we have uint64_t so we end up with overflow
    for (uint64_t i = 0;  i < 100;  ++i) {
        vals.push_back(-i);
    }

    freezeAndTest(vals);

    freezeAndTest(vals, 1020 /* offset */);
}

// Simple negative, positive and null integers
BOOST_AUTO_TEST_CASE( test_large_positive_ints_and_nulls )
{
    std::vector<CellValue> vals;

    // Check for large integers (we have uint64_t so we end up with overflow
    for (uint64_t i = 0;  i < 100;  ++i) {
        vals.push_back(-i);
    }
    vals.emplace_back();  // add a null

    freezeAndTest(vals);

    freezeAndTest(vals, 1020 /* offset */);
}

// Simple negative, positive and null integers
BOOST_AUTO_TEST_CASE( test_big_range )
{
    std::vector<CellValue> vals;

    // Check for large integers (we have uint64_t so we end up with overflow
    for (uint64_t i = 0;  i < 100;  ++i) {
        vals.push_back(-i);
    }
    vals.emplace_back();  // add a null

    freezeAndTest(vals);

    freezeAndTest(vals, 1020 /* offset */);
}

// Simple negative, positive and null integers
BOOST_AUTO_TEST_CASE( test_big_pos_neg_range )
{
    std::vector<CellValue> vals;

    // Check for large integers (we have uint64_t so we end up with overflow
    for (int64_t i = 0;  i < 100;  ++i) {
        vals.push_back(std::numeric_limits<int64_t>::min() + i);
        vals.push_back(std::numeric_limits<int64_t>::max() - i);
    }

    auto frozen = freezeAndTest(vals);

    BOOST_CHECK_EQUAL(MLDB::type_name(*frozen),
                   "MLDB::IntegerFrozenColumn");

    freezeAndTest(vals, 1020 /* offset */);
}

// Full range and nulls.  Not enough 64 bit integers to represent all values.
BOOST_AUTO_TEST_CASE( test_big_pos_neg_range_and_nulls )
{
    std::vector<CellValue> vals;

    // Check for large integers (we have uint64_t so we end up with overflow
    for (int64_t i = 0;  i < 100;  ++i) {
        vals.push_back(std::numeric_limits<int64_t>::min() + i);
        vals.push_back(std::numeric_limits<int64_t>::max() - i);
    }
    vals.emplace_back();

    freezeAndTest(vals);

    freezeAndTest(vals, 1020 /* offset */);
}

BOOST_AUTO_TEST_CASE( test_double_basics )
{
    std::vector<CellValue> vals;

    for (int64_t i = 0;  i < 100;  ++i) {
        vals.push_back(i * 0.5);
    }

    auto frozen = freezeAndTest(vals);
    BOOST_CHECK_EQUAL(MLDB::type_name(*frozen),
                      "MLDB::DoubleFrozenColumn");

    freezeAndTest(vals, 1020 /* offset */);
}

BOOST_AUTO_TEST_CASE( test_double_special_values )
{
    std::vector<CellValue> vals;
    vals.emplace_back();
    vals.emplace_back(INFINITY);
    vals.emplace_back(-INFINITY);
    vals.emplace_back(std::numeric_limits<double>::quiet_NaN());
    vals.emplace_back(0.0);
    vals.emplace_back(-0.0);
    vals.emplace_back(1);
    vals.emplace_back(std::numeric_limits<double>::max());
    vals.emplace_back(std::numeric_limits<double>::min());
    vals.emplace_back(std::numeric_limits<double>::lowest());

    auto frozen = freezeAndTest(vals);
    BOOST_CHECK_EQUAL(MLDB::type_name(*frozen),
                      "MLDB::DoubleFrozenColumn");

    freezeAndTest(vals, 1020 /* offset */);
}

BOOST_AUTO_TEST_CASE( test_double_basics_null )
{
    std::vector<CellValue> vals;
    vals.emplace_back();

    for (int64_t i = 0;  i < 100;  ++i) {
        vals.push_back(i * 0.5);
        vals.emplace_back();
        vals.push_back(-(i * 0.5));
    }
    vals.emplace_back();

    auto frozen = freezeAndTest(vals);
    BOOST_CHECK_EQUAL(MLDB::type_name(*frozen),
                      "MLDB::DoubleFrozenColumn");

    freezeAndTest(vals, 1020 /* offset */);
}

BOOST_AUTO_TEST_CASE( test_timestamp_basics )
{
    std::vector<CellValue> vals;

    for (int64_t i = 0;  i < 100;  ++i) {
        vals.push_back(Date::now().plusSeconds(i * 0.5));
    }

    auto frozen = freezeAndTest(vals);
    BOOST_CHECK_EQUAL(MLDB::type_name(*frozen),
                      "MLDB::TimestampFrozenColumn");

    freezeAndTest(vals, 1020 /* offset */);
}

BOOST_AUTO_TEST_CASE( test_timestamp_special_values )
{
    std::vector<CellValue> vals;
    vals.emplace_back();
    vals.emplace_back(Date::positiveInfinity());
    vals.emplace_back(Date::negativeInfinity());
    vals.emplace_back(Date::notADate());
    vals.emplace_back(Date::fromSecondsSinceEpoch(0.0));
    vals.emplace_back(Date::fromSecondsSinceEpoch(1));
    vals.emplace_back(Date::fromSecondsSinceEpoch(std::numeric_limits<double>::max()));
    vals.emplace_back(Date::fromSecondsSinceEpoch(std::numeric_limits<double>::min()));
    vals.emplace_back(Date::fromSecondsSinceEpoch(std::numeric_limits<double>::lowest()));

    auto frozen = freezeAndTest(vals);
    BOOST_CHECK_EQUAL(MLDB::type_name(*frozen),
                      "MLDB::TimestampFrozenColumn");

    freezeAndTest(vals, 1020 /* offset */);
}

BOOST_AUTO_TEST_CASE( test_timestamp_basics_null )
{
    std::vector<CellValue> vals;
    vals.emplace_back();

    for (int64_t i = 0;  i < 100;  ++i) {
        vals.push_back(Date::now().plusSeconds(i * 0.5));
        vals.emplace_back();
        vals.push_back(Date::now().plusSeconds(-i * 0.5));
    }
    vals.emplace_back();

    auto frozen = freezeAndTest(vals);
    BOOST_CHECK_EQUAL(MLDB::type_name(*frozen),
                      "MLDB::TimestampFrozenColumn");

    freezeAndTest(vals, 1020 /* offset */);
}

ext: cc

max_stars_repo_name: kstepanmpmg/mldb

max_issues_repo_name: tomzhang/mldb

max_forks_repo_name: matebestek/mldb


text:
#include <tiny.h>
#include <mass.h>
#include <geometry.h>
#include <mesh_array.h>
#include <simulators.h>
#include <procedural.h>

#include <util_config_file.h>
#include <util_string_helper.h>
#include <util_log.h>
#include <util_timestamp.h>

#include <boost/algorithm/string.hpp>

#include <sstream>
#include <string>
#include <cmath>

namespace rigid_body
{
  namespace cmd
  {

    class Application
    {
    public:

      typedef tiny::MathTypes<float> MT;
      typedef MT::real_type          T;
      typedef MT::vector3_type       V;
      typedef MT::matrix3x3_type     M;
      typedef MT::quaternion_type    Q;
      typedef MT::coordsys_type      C;
      typedef MT::value_traits       VT;

    protected:

      T             m_time;
      T             m_time_step;
      T             m_total_time;
      T             m_fps;
      bool          m_profiling;
      bool          m_xml_record;
      bool          m_save_contact_data;

      std::string   m_matlab_file;
      std::string   m_procedural_scene;
      std::string   m_xml_save_scene_file;
      std::string   m_xml_save_channel_file;

      std::string                       m_obj_path;
      std::string                       m_output_path;
      std::string                       m_working_directory;

      util::ConfigFile                    m_config_file;
      procedural::MaterialInfo<T>         m_mat_info;
      simulators::ProxEngine              m_engine;
      content::ChannelStorage             m_channel_storage;
      size_t                              m_key_idx;
      size_t                              m_max_keys;

    protected:

      void clear()
      {
        m_obj_path                 = "";
        m_output_path              = "";
        m_working_directory        = "";

        m_time                     = VT::zero();
        m_time_step                = VT::numeric_cast(0.01f);
        m_fps                      = VT::numeric_cast(25.0f);

        m_profiling                = false;
        m_xml_record               = false;
        m_save_contact_data        = false;

        m_matlab_file              = "out.m";
        m_procedural_scene         = "wall";
        m_xml_save_channel_file    = "out_channels.xml";
        m_xml_save_scene_file      = "out_scene.xml";

        m_engine.clear();
        m_config_file.clear();
      }

    public:

      void save_xml_file()
      {
        content::xml_write(m_output_path + m_xml_save_scene_file, &m_engine);
        content::xml_write(m_output_path + m_xml_save_channel_file, m_channel_storage);
      }

      void load_config_file(std::string const & cfg_file)
      {
        clear();

        {
          util::Log logging;

          logging << "loading cfg: " << cfg_file << util::Log::newline();
        }

        bool cfg_loaded = m_config_file.load(cfg_file);

        assert(cfg_loaded || !"load_config_file(): cfg file could not be loaded");

        util::LogInfo::on()            = util::to_value<bool>(m_config_file.get_value("logging","true"));
        util::LogInfo::console()       = util::to_value<bool>(m_config_file.get_value("console","true"));
        util::LogInfo::filename()      = m_config_file.get_value("log_file","log.txt");

        {
          util::Log logging;

          logging << "### " << util::timestamp() << util::Log::newline();
        }

        m_obj_path               = m_config_file.get_value( "obj_path",                ""                   );
        m_working_directory      = m_config_file.get_value( "working_directory",       ""                   );
        m_output_path            = m_config_file.get_value( "output_path",             ""                   );

        m_matlab_file            = m_config_file.get_value( "matlab_file",             "output.m"           );
        m_procedural_scene       = m_config_file.get_value( "procedural_scene",        "wall"               );
        m_xml_save_scene_file    = m_config_file.get_value( "xml_save_scene_file",     "out_scene.xml"      );
        m_xml_save_channel_file  = m_config_file.get_value( "xml_save_channel_file",   "out_channels.xml"   );

        m_xml_record             = util::to_value<bool>(  m_config_file.get_value("xml_record", "false"   ) );
        m_total_time             = util::to_value<float>( m_config_file.get_value("total_time",  "3.0"    ) );
        m_time_step              = util::to_value<float>( m_config_file.get_value("time_step",   "0.01"   ) );
        m_fps                    = util::to_value<float>( m_config_file.get_value("fps",         "25.0"   ) );
        m_profiling              = util::to_value<bool>(  m_config_file.get_value("profiling",   "false"  ) );
        m_save_contact_data      = util::to_value<bool>(  m_config_file.get_value("save_contact_data", "false"   ));

        assert( m_time_step*m_fps < VT::one() || !"Application::run(): Invalid fps & timestep setting");

        m_engine.set_parameters_from_config_file( cfg_file );

        procedural::make_scene<MT>(m_procedural_scene, m_obj_path, &m_engine, m_config_file);

        if(m_xml_record)
        {
          // Prepare xml channel storage for recording
          std::vector<size_t> rids;
          size_t const N = m_engine.get_number_of_rigid_bodies();
          rids.resize(N);
          m_engine.get_rigid_body_indices( &rids[0] );

          m_channel_storage.clear();

          for(size_t i = 0u; i < N; ++i)
          {
            size_t const id = rids[i];

            std::string const name = m_engine.get_rigid_body_name(id);

            m_channel_storage.create_channel( id, name );
          }
        }
      }

      void save_contact_data()
      {
        static int counter = 0u;

        std::stringstream filename;

        // compute output width for filename
        static int width = std::ceil( std::log10( std::ceil( m_total_time / m_time_step ) ) ) + 1;

        filename << m_output_path
        << m_procedural_scene
        << "contact_data_"
        << std::setw(width)
        << std::setfill('0')
        << counter
        << ".m";

        m_engine.write_contact_data(filename.str(), counter);

        ++counter;
      }

      int run()
      {
        using std::min;

        T const frame_time = 1.0 / m_fps;   // The time between two frames

        while (m_time < m_total_time)
        {
          T const time_left = m_total_time - m_time;

          {
            util::Log logging;

            logging << "Application::run(): Time : " << m_time << " / " << m_total_time << util::Log::newline();
            logging << "Application::run(): Time left : " << time_left<< util::Log::newline();
            logging.flush();
          }

          T const time_to_next_frame    = min(time_left, frame_time);
          T       time_left_to_simulate = time_to_next_frame;

          while(time_left_to_simulate > VT::zero())
          {
            T const safe_time_step = min(m_time_step, time_left_to_simulate);

            m_engine.simulate(safe_time_step);
            time_left_to_simulate = time_left_to_simulate - safe_time_step;
          }

          m_time += time_to_next_frame;

          if (m_xml_record)
          {
            //--- record xml motion channel data -----------------------------

            float const time = m_engine.get_time();

            for(size_t channel_idx = 0u; channel_idx < m_channel_storage.get_number_of_channels(); ++channel_idx )
            {
              size_t const body_idx = m_channel_storage.get_channel_id( channel_idx);
              size_t const key_idx  = m_channel_storage.create_key( channel_idx, time);
              {
                float x= 0.0f;
                float y= 0.0f;
                float z= 0.0f;

                m_engine.get_rigid_body_position( body_idx, x, y, z);

                m_channel_storage.set_key_position( channel_idx, key_idx, x, y, z);
              }

              {
                float qs = 0.0f;
                float qx = 0.0f;
                float qy = 0.0f;
                float qz = 0.0f;

                m_engine.get_rigid_body_orientation( body_idx, qs, qx, qy, qz);

                m_channel_storage.set_key_orientation( channel_idx, key_idx, qs, qx, qy, qz);
              }
            }
          }

          if (m_save_contact_data)
          {
            save_contact_data();
          }

        }

        {
          util::Log logging;

          logging << "Application::run(): Total time reached "
          << m_total_time
          << util::Log::newline();
        }

        if(m_profiling)
        {
          m_engine.write_profiling( m_output_path + m_matlab_file );
        }

        if(m_xml_record)
        {
          save_xml_file();
        }

        return 0;
      }

    public:

      Application()
      {
      }

      virtual ~Application()
      {
        clear();
      }

    };

  }// end of namespace cmd
}// end of namespace rigid_body

int main(int argc, char **argv)
{
  rigid_body::cmd::Application app;

  std::string cfg_file = "";

  if (argv[1])
    cfg_file = argv[1];
  else
    cfg_file = "default.cfg";

  app.load_config_file(cfg_file);

  return app.run();
}

max_stars_repo_name: diku-dk/PROX

max_issues_repo_name: diku-dk/PROX

max_forks_repo_name: diku-dk/PROX


text:
//------------------------------------------------------------------------------
/*
    This file is part of rippled: https://github.com/ripple/rippled
    Copyright (c) 2012, 2013 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 "../beast/modules/beast_core/system/BeforeBoost.h"
#include <boost/bimap.hpp>
#include <boost/bimap/list_of.hpp>
#include <boost/bimap/multiset_of.hpp>
#include <boost/bimap/unordered_set_of.hpp>
#include <boost/optional.hpp>
#include <boost/version.hpp>

#include <sodium.h>

#include "ripple_app.h"

#include "../ripple_net/ripple_net.h"
#include "../ripple_rpc/ripple_rpc.h"
#include "../ripple_websocket/ripple_websocket.h"
#include "../ripple/common/jsonrpc_fields.h"

// This .cpp will end up including all of the public header
// material in Ripple since it holds the Application object.

#include "../ripple/common/seconds_clock.h"
#include "../ripple/http/ripple_http.h"
#include "../ripple/resource/ripple_resource.h"
#include "../ripple/sitefiles/ripple_sitefiles.h"
#include "../ripple/validators/ripple_validators.h"

#include "../beast/beast/asio/io_latency_probe.h"
#include "../beast/beast/cxx14/memory.h"

# include "main/CollectorManager.h"
#include "main/CollectorManager.cpp"

#include "misc/ProofOfWorkFactory.h"

# include "main/NodeStoreScheduler.h"
#include "main/NodeStoreScheduler.cpp"

# include "main/IoServicePool.h"
#include "main/IoServicePool.cpp"

# include "main/FatalErrorReporter.h"
#include "main/FatalErrorReporter.cpp"

# include "rpc/RPCHandler.h"
# include "rpc/RPCServerHandler.h"
# include "main/RPCHTTPServer.h"
#include "main/RPCHTTPServer.cpp"
#include "rpc/RPCServerHandler.cpp"
#include "rpc/RPCHandler.cpp"

#include "websocket/WSConnection.h"

# include "tx/TxQueueEntry.h"
#include "tx/TxQueueEntry.cpp"
# include "tx/TxQueue.h"
#include "tx/TxQueue.cpp"

# include "websocket/WSServerHandler.h"
#include "websocket/WSServerHandler.cpp"
#include "websocket/WSConnection.cpp"
# include "websocket/WSDoor.h"
#include "websocket/WSDoor.cpp"

#include "../ripple/common/ResolverAsio.h"

# include "node/SqliteFactory.h"
#include "node/SqliteFactory.cpp"

#include "main/Application.cpp"

#include "main/Main.cpp"

//------------------------------------------------------------------------------

namespace ripple {
int run (int argc, char** argv);
}

struct ProtobufLibrary
{
    ~ProtobufLibrary ()
    {
        google::protobuf::ShutdownProtobufLibrary();
    }
};

// Must be outside the namespace for obvious reasons
//
int main (int argc, char** argv)
{
#if defined(__GNUC__) && !defined(__clang__)
    auto constexpr gccver = (__GNUC__ * 100 * 100) +
                            (__GNUC_MINOR__ * 100) +
                            __GNUC_PATCHLEVEL__;

    static_assert (gccver >= 40801,
        "GCC version 4.8.1 or later is required to compile paysharesd.");
#endif

#ifdef _MSC_VER
    static_assert (_MSC_VER >= 1800,
        "Visual Studio 2013 or later is required to compile paysharesd.");
#endif

    static_assert (BOOST_VERSION >= 105500,
        "Boost version 1.55 or later is required to compile paysharesd");

    if (sodium_init() == -1) {
        std::cerr << "sodium_init failed\n";
        return 1;
    }

    //
    // These debug heap calls do nothing in release or non Visual Studio builds.
    //

    // Checks the heap at every allocation and deallocation (slow).
    //
    //beast::Debug::setAlwaysCheckHeap (false);

    // Keeps freed memory blocks and fills them with a guard value.
    //
    //beast::Debug::setHeapDelayedFree (false);

    // At exit, reports all memory blocks which have not been freed.
    //
#if RIPPLE_DUMP_LEAKS_ON_EXIT
    beast::Debug::setHeapReportLeaks (true);
#else
    beast::Debug::setHeapReportLeaks (false);
#endif

    beast::SharedSingleton <ProtobufLibrary>::get ();

    return ripple::run (argc, argv);
}

max_stars_repo_name: Payshare/paysharesd

max_issues_repo_name: Payshare/paysharesd

max_forks_repo_name: Payshare/paysharesd


text:
#define BOOST_TEST_MODULE citation_graph_TESTS

#include <boost/test/included/unit_test.hpp>
#include <boost/test/execution_monitor.hpp>
#include <boost/operators.hpp>
#include "citation_graph_memory_testing.h"
#include "citation_graph.h"

long long steps_left_to_throw = 0;
bool test_memory = false;

class Publication {
public:
    typedef typename std::string id_type;

    Publication(id_type const &_id) : id(_id) {
    }

    id_type get_id() const noexcept {
        return id;
    }

private:
    id_type id;
};

static long long constructor_passes_after;

static long long inf = std::numeric_limits<long long>::max();

void except() {
    --steps_left_to_throw;
    if (steps_left_to_throw <= 0) {
        throw "error";
    }
}

class Id : public boost::totally_ordered<Id> {
private:
    int id;
    static int steps_left_to_throw;

public:
    Id(int const &id) : id(id) {
        except();
    }

    Id(const Id &other) {
        except();
        this->id = other.id;
    }

    Id(Id &&other) {
        except();
        this->id = other.id;
    }

    Id &operator=(const Id &other) {
        except();
        this->id = other.id;
        return *this;
    }

    bool operator==(const Id &other) const {

        except();

        return this->id == other.id;
    }

    bool operator<(const Id &other) const {

        except();

        return this->id < other.id;
    }

    friend std::ostream& operator<<(std::ostream &os, const Id &id);
};

std::ostream& operator<<(std::ostream &os, const Id &id) {
    return (os << id.id);
}

class Publication2 {
public:
    typedef Id id_type;

    Publication2(id_type const &_id) : id(_id) {
        except();
    }

    Publication2(const Publication2 &other) : id(other.id) {
        except();
    }

    Publication2(Publication2 &&other) : id(std::move(other.id)) {
        except();
    }

    id_type get_id() const {
        except();
        return id;
    }

private:
    id_type id;
};
BOOST_AUTO_TEST_SUITE(CitationGraphTests)

    std::shared_ptr<CitationGraph<Publication2>> build1() {
        steps_left_to_throw = inf;
        std::shared_ptr<CitationGraph<Publication2>> graph = std::shared_ptr<CitationGraph<Publication2>>(
                new CitationGraph<Publication2>(Id(1)));

        graph->create(Id(2), Id(1));
        graph->create(Id(3), Id(2));

        graph->create(Id(4), Id(1));
        graph->create(Id(5), Id(4));
        graph->create(Id(6), Id(4));

        graph->create(Id(7), std::vector<Id>{Id(6), Id(2)});
        graph->create(Id(8), std::vector<Id>{Id(5), Id(7)});
        graph->create(Id(9), Id(5));
        graph->add_citation(Id(9), Id(4));

        return graph;

    }

    inline void check_parents(std::shared_ptr<CitationGraph<Publication2>> &graph, Id id, std::vector<Id> expected) {
        steps_left_to_throw = inf;
        std::sort(expected.begin(), expected.end());
        std::vector<Id> result = graph->get_parents(id);

        std::sort(result.begin(), result.end());

        BOOST_REQUIRE_EQUAL(expected.size(), result.size());
        BOOST_CHECK_EQUAL_COLLECTIONS(expected.begin(), expected.end(), result.begin(), result.end());
    }

    inline void check_children(std::shared_ptr<CitationGraph<Publication2>> &graph, Id id, std::vector<Id> expected) {
        steps_left_to_throw = inf;
        std::sort(expected.begin(), expected.end());
        std::vector<Id> result = graph->get_children(id);

        std::sort(result.begin(), result.end());

        BOOST_REQUIRE_EQUAL(expected.size(), result.size());

        BOOST_CHECK_EQUAL_COLLECTIONS(expected.begin(), expected.end(), result.begin(), result.end());

    }

    inline void check_build1(std::shared_ptr<CitationGraph<Publication2>> &graph) {
        steps_left_to_throw = inf;

        BOOST_CHECK_EQUAL(graph->get_parents(1).size(), 0);

        check_parents(graph, 2, std::vector<Id>{1});

        check_parents(graph, 3, std::vector<Id>{2});

        check_parents(graph, 4, std::vector<Id>{1});

        check_parents(graph, 5, std::vector<Id>{4});

        check_parents(graph, 6, std::vector<Id>{4});

        check_parents(graph, 7, std::vector<Id>{2, 6});

        check_parents(graph, 8, std::vector<Id>{7, 5});

        check_parents(graph, 9, std::vector<Id>{4, 5});

        check_children(graph, 1, std::vector<Id>{2, 4});

        check_children(graph, 2, std::vector<Id>{7, 3});

        check_children(graph, 3, std::vector<Id>{});

        check_children(graph, 4, std::vector<Id>{5, 6, 9});

        check_children(graph, 5, std::vector<Id>{8, 9});

        check_children(graph, 6, std::vector<Id>{7});

        check_children(graph, 7, std::vector<Id>{8});

        check_children(graph, 8, std::vector<Id>{});

        check_children(graph, 9, std::vector<Id>{});

    }

    constexpr size_t build2_list_size = 100;

    std::shared_ptr<CitationGraph<Publication2>> build2_list() {
        steps_left_to_throw = inf;
        std::shared_ptr<CitationGraph<Publication2>> graph = std::shared_ptr<CitationGraph<Publication2>>(
                new CitationGraph<Publication2>(Id(1)));

        for (size_t i = 2; i <= build2_list_size; ++i) {
            graph->create(i, i - 1);
        }

        return graph;

    }

    inline void check_build2_list(std::shared_ptr<CitationGraph<Publication2>> &graph) {
        steps_left_to_throw = inf;

        BOOST_CHECK_EQUAL(graph->get_parents(1).size(), 0);

        for (int i = 1; i < build2_list_size; ++i) {
            check_children(graph, i, std::vector<Id>{i + 1});
        }
        check_children(graph, build2_list_size, std::vector<Id>{});

        for (int i = 2; i <= build2_list_size; ++i) {
            check_parents(graph, i, std::vector<Id>{i - 1});
        }
    }

    void test(std::shared_ptr<CitationGraph<Publication2>> (*creator)(),
              void (*basic_check)(std::shared_ptr<CitationGraph<Publication2>> &),
              void (*operation)(std::shared_ptr<CitationGraph<Publication2>> &),
              void (*after_check)(std::shared_ptr<CitationGraph<Publication2>> &)) {
        for (long long step = 0;; ++step) {
            std::shared_ptr graph = creator();
            steps_left_to_throw = step;
            try {
                test_memory = true;
                operation(graph);
            } catch (...) {
                test_memory = false;
                //std::cerr << step << std::endl;
                basic_check(graph);
                continue;
            }
            test_memory = false;
            std::cerr << "Steps " << step << std::endl;
            if (after_check != nullptr) {
                after_check(graph);
            }
            break;

        }
    }

    BOOST_AUTO_TEST_CASE(example) {

        CitationGraph<Publication> gen("Goto Considered Harmful");
        Publication::id_type const id1 = gen.get_root_id(); // Czy to jest noexcept?
        BOOST_CHECK((gen.exists(id1)));
        BOOST_CHECK_EQUAL(gen.get_parents(id1).size(), 0);
        gen.create("A", id1);
        gen.create("B", id1);
        BOOST_CHECK_EQUAL(gen.get_children(id1).size(), 2);
        gen.create("C", "A");
        gen.add_citation("C", "B");
        BOOST_CHECK_EQUAL(gen.get_parents("C").size(), 2);
        BOOST_CHECK_EQUAL(gen.get_children("A").size(), 1);
        std::vector<Publication::id_type> parents;
        parents.push_back("A");
        parents.push_back("B");
        gen.create("D", parents);
        BOOST_CHECK_EQUAL(gen.get_parents("D").size(), parents.size());
        BOOST_CHECK_EQUAL(gen.get_children("A").size(), 2);
        BOOST_CHECK_EQUAL("D", gen["D"].get_id());
        gen.remove("A");
        BOOST_CHECK((!gen.exists("A")));
        BOOST_CHECK((gen.exists("B")));
        BOOST_CHECK((gen.exists("C")));
        BOOST_CHECK((gen.exists("D")));
        gen.remove("B");
        BOOST_CHECK((!gen.exists("A")));
        BOOST_CHECK((!gen.exists("B")));
        BOOST_CHECK((!gen.exists("C")));
        BOOST_CHECK((!gen.exists("D")));

        try {
            BOOST_CHECK_THROW(gen["E"], PublicationNotFound);
            gen["E"];
        }
        catch (std::exception &e) {
            BOOST_CHECK_EQUAL(e.what(), "PublicationNotFound");
        }
        try {
            gen.create("E", "Goto Considered Harmful");
            BOOST_CHECK_THROW(gen.create("E", "Goto Considered Harmful"), PublicationAlreadyCreated);
            gen.create("E", "Goto Considered Harmful");
        }
        catch (std::exception &e) {
            BOOST_CHECK_EQUAL(e.what(), "PublicationAlreadyCreated");
        }
        try {
            BOOST_CHECK_THROW(gen.remove("Goto Considered Harmful"), TriedToRemoveRoot);
            gen.remove("Goto Considered Harmful");
        }
        catch (std::exception &e) {
            BOOST_CHECK_EQUAL(e.what(), "TriedToRemoveRoot");
        }
    }

    BOOST_AUTO_TEST_CASE(remove) {
        std::cerr << "Test " << __LINE__ + 1 << std::endl;
        test(build1, check_build1, [](std::shared_ptr<CitationGraph<Publication2>> &graph) { graph->remove(4); },
             [](std::shared_ptr<CitationGraph<Publication2>> &graph) {
                 steps_left_to_throw = inf;

                 BOOST_CHECK_EQUAL(graph->get_parents(1).size(), 0);

                 check_parents(graph, 2, std::vector<Id>{1});

                 check_parents(graph, 3, std::vector<Id>{2});

                 BOOST_CHECK_THROW((*graph)[4], PublicationNotFound);
                 BOOST_CHECK_THROW((*graph)[5], PublicationNotFound);
                 BOOST_CHECK_THROW((*graph)[6], PublicationNotFound);

                 check_parents(graph, 7, std::vector<Id>{2});

                 check_parents(graph, 8, std::vector<Id>{7});

                 BOOST_CHECK_THROW((*graph)[9], PublicationNotFound);

                 check_children(graph, 1, std::vector<Id>{2});

                 check_children(graph, 2, std::vector<Id>{7, 3});

                 check_children(graph, 3, std::vector<Id>{});

                 check_children(graph, 7, std::vector<Id>{8});

                 check_children(graph, 8, std::vector<Id>{});

             });

        std::cerr << "Test " << __LINE__ + 1 << std::endl;
        test(build1, check_build1, [](std::shared_ptr<CitationGraph<Publication2>> &graph) { graph->remove(7); },
             [](std::shared_ptr<CitationGraph<Publication2>> &graph) {
                 steps_left_to_throw = inf;

                 BOOST_CHECK_EQUAL(graph->get_parents(1).size(), 0);

                 check_parents(graph, 2, std::vector<Id>{1});

                 check_parents(graph, 3, std::vector<Id>{2});

                 check_parents(graph, 4, std::vector<Id>{1});

                 check_parents(graph, 5, std::vector<Id>{4});

                 check_parents(graph, 6, std::vector<Id>{4});

                 BOOST_CHECK_THROW((*graph)[7], PublicationNotFound);

                 check_parents(graph, 8, std::vector<Id>{5});

                 check_parents(graph, 9, std::vector<Id>{4, 5});

                 check_children(graph, 1, std::vector<Id>{2, 4});

                 check_children(graph, 2, std::vector<Id>{3});

                 check_children(graph, 3, std::vector<Id>{});

                 check_children(graph, 4, std::vector<Id>{5, 6, 9});

                 check_children(graph, 5, std::vector<Id>{8, 9});

                 check_children(graph, 6, std::vector<Id>{});

                 check_children(graph, 8, std::vector<Id>{});

                 check_children(graph, 9, std::vector<Id>{});
             });
    }

    BOOST_AUTO_TEST_CASE(single_create) {
        std::cerr << "Test " << __LINE__ + 1 << std::endl;
        test(build1, check_build1, [](std::shared_ptr<CitationGraph<Publication2>> &graph) { graph->create(22, 1); },
             [](std::shared_ptr<CitationGraph<Publication2>> &graph) {
                 steps_left_to_throw = inf;

                 BOOST_CHECK_EQUAL(graph->get_parents(1).size(), 0);

                 check_parents(graph, 2, std::vector<Id>{1});

                 check_parents(graph, 3, std::vector<Id>{2});

                 check_parents(graph, 4, std::vector<Id>{1});

                 check_parents(graph, 5, std::vector<Id>{4});

                 check_parents(graph, 6, std::vector<Id>{4});

                 check_parents(graph, 7, std::vector<Id>{2, 6});

                 check_parents(graph, 8, std::vector<Id>{7, 5});

                 check_parents(graph, 9, std::vector<Id>{4, 5});

                 check_parents(graph, 22, std::vector<Id>{1});

                 check_children(graph, 1, std::vector<Id>{2, 4, 22});

                 check_children(graph, 2, std::vector<Id>{7, 3});

                 check_children(graph, 3, std::vector<Id>{});

                 check_children(graph, 4, std::vector<Id>{5, 6, 9});

                 check_children(graph, 5, std::vector<Id>{8, 9});

                 check_children(graph, 6, std::vector<Id>{7});

                 check_children(graph, 7, std::vector<Id>{8});

                 check_children(graph, 8, std::vector<Id>{});

                 check_children(graph, 9, std::vector<Id>{});
             });

        std::cerr << "Test " << __LINE__ + 1 << std::endl;
        test(build1, check_build1, [](std::shared_ptr<CitationGraph<Publication2>> &graph) { graph->create(22, 9); },
             [](std::shared_ptr<CitationGraph<Publication2>> &graph) {
                 steps_left_to_throw = inf;

                 BOOST_CHECK_EQUAL(graph->get_parents(1).size(), 0);

                 check_parents(graph, 2, std::vector<Id>{1});

                 check_parents(graph, 3, std::vector<Id>{2});

                 check_parents(graph, 4, std::vector<Id>{1});

                 check_parents(graph, 5, std::vector<Id>{4});

                 check_parents(graph, 6, std::vector<Id>{4});

                 check_parents(graph, 7, std::vector<Id>{2, 6});

                 check_parents(graph, 8, std::vector<Id>{7, 5});

                 check_parents(graph, 9, std::vector<Id>{4, 5});

                 check_parents(graph, 22, std::vector<Id>{9});

                 check_children(graph, 1, std::vector<Id>{2, 4});

                 check_children(graph, 2, std::vector<Id>{7, 3});

                 check_children(graph, 3, std::vector<Id>{});

                 check_children(graph, 4, std::vector<Id>{5, 6, 9});

                 check_children(graph, 5, std::vector<Id>{8, 9});

                 check_children(graph, 6, std::vector<Id>{7});

                 check_children(graph, 7, std::vector<Id>{8});

                 check_children(graph, 8, std::vector<Id>{});

                 check_children(graph, 9, std::vector<Id>{22});
             });
    }

    BOOST_AUTO_TEST_CASE(vector_create) {
        std::cerr << "Test " << __LINE__ + 1 << std::endl;
        test(build1, check_build1,
             [](std::shared_ptr<CitationGraph<Publication2>> &graph) { graph->create(22, {1, 2, 3, 4, 6, 7, 8, 9}); },
             [](std::shared_ptr<CitationGraph<Publication2>> &graph) {
                 steps_left_to_throw = inf;

                 BOOST_CHECK_EQUAL(graph->get_parents(1).size(), 0);

                 check_parents(graph, 2, std::vector<Id>{1});

                 check_parents(graph, 3, std::vector<Id>{2});

                 check_parents(graph, 4, std::vector<Id>{1});

                 check_parents(graph, 5, std::vector<Id>{4});

                 check_parents(graph, 6, std::vector<Id>{4});

                 check_parents(graph, 7, std::vector<Id>{2, 6});

                 check_parents(graph, 8, std::vector<Id>{7, 5});

                 check_parents(graph, 9, std::vector<Id>{4, 5});

                 check_parents(graph, 22, std::vector<Id>{1, 2, 3, 4, 6, 7, 8, 9});

                 check_children(graph, 1, std::vector<Id>{2, 4, 22});

                 check_children(graph, 2, std::vector<Id>{7, 3, 22});

                 check_children(graph, 3, std::vector<Id>{22});

                 check_children(graph, 4, std::vector<Id>{5, 6, 9, 22});

                 check_children(graph, 5, std::vector<Id>{8, 9});

                 check_children(graph, 6, std::vector<Id>{7, 22});

                 check_children(graph, 7, std::vector<Id>{8, 22});

                 check_children(graph, 8, std::vector<Id>{22});

                 check_children(graph, 9, std::vector<Id>{22});

                 check_children(graph, 22, std::vector<Id>{});
             });

        {
            CitationGraph<Publication> graph("A");
            BOOST_CHECK_THROW(graph.create("B", std::vector<Publication::id_type>{}), PublicationNotFound);
        }
    }

    BOOST_AUTO_TEST_CASE(add_citation) {

        std::cerr << "Test " << __LINE__ + 1 << std::endl;
        test(build1, check_build1,
             [](std::shared_ptr<CitationGraph<Publication2>> &graph) { graph->add_citation(5, 1); },
             [](std::shared_ptr<CitationGraph<Publication2>> &graph) {
                 steps_left_to_throw = inf;

                 BOOST_CHECK_EQUAL(graph->get_parents(1).size(), 0);

                 check_parents(graph, 2, std::vector<Id>{1});

                 check_parents(graph, 3, std::vector<Id>{2});

                 check_parents(graph, 4, std::vector<Id>{1});

                 check_parents(graph, 5, std::vector<Id>{4, 1});

                 check_parents(graph, 6, std::vector<Id>{4});

                 check_parents(graph, 7, std::vector<Id>{2, 6});

                 check_parents(graph, 8, std::vector<Id>{7, 5});

                 check_parents(graph, 9, std::vector<Id>{4, 5});

                 check_children(graph, 1, std::vector<Id>{2, 4, 5});

                 check_children(graph, 2, std::vector<Id>{7, 3});

                 check_children(graph, 3, std::vector<Id>{});

                 check_children(graph, 4, std::vector<Id>{5, 6, 9});

                 check_children(graph, 5, std::vector<Id>{8, 9});

                 check_children(graph, 6, std::vector<Id>{7});

                 check_children(graph, 7, std::vector<Id>{8});

                 check_children(graph, 8, std::vector<Id>{});

                 check_children(graph, 9, std::vector<Id>{});
             });

        std::cerr << "Test " << __LINE__ + 1 << std::endl;
        test(build1, check_build1,
             [](std::shared_ptr<CitationGraph<Publication2>> &graph) { graph->add_citation(9, 2); },
             [](std::shared_ptr<CitationGraph<Publication2>> &graph) {
                 steps_left_to_throw = inf;

                 BOOST_CHECK_EQUAL(graph->get_parents(1).size(), 0);

                 check_parents(graph, 2, std::vector<Id>{1});

                 check_parents(graph, 3, std::vector<Id>{2});

                 check_parents(graph, 4, std::vector<Id>{1});

                 check_parents(graph, 5, std::vector<Id>{4});

                 check_parents(graph, 6, std::vector<Id>{4});

                 check_parents(graph, 7, std::vector<Id>{2, 6});

                 check_parents(graph, 8, std::vector<Id>{7, 5});

                 check_parents(graph, 9, std::vector<Id>{4, 5, 2});

                 check_children(graph, 1, std::vector<Id>{2, 4});

                 check_children(graph, 2, std::vector<Id>{7, 3, 9});

                 check_children(graph, 3, std::vector<Id>{});

                 check_children(graph, 4, std::vector<Id>{5, 6, 9});

                 check_children(graph, 5, std::vector<Id>{8, 9});

                 check_children(graph, 6, std::vector<Id>{7});

                 check_children(graph, 7, std::vector<Id>{8});

                 check_children(graph, 8, std::vector<Id>{});

                 check_children(graph, 9, std::vector<Id>{});
             });
    }

    BOOST_AUTO_TEST_CASE(memoryCombined) {

        std::cerr << "Test " << __LINE__ + 1 << std::endl;
        test(build2_list, check_build2_list,
             [](std::shared_ptr<CitationGraph<Publication2>> &graph) {
                 auto cpy = steps_left_to_throw;
                 steps_left_to_throw = inf;
                 std::vector<Id> add_vector;

                 for (size_t i = 1; i <= 50; ++i) {
                     add_vector.push_back(i);
                 }

                 steps_left_to_throw = cpy;

                 graph->create(0, add_vector);

                 try {
                     graph->remove(10);
                 } catch (...) {
                     steps_left_to_throw = inf;
                     graph->remove(0);
                     throw;
                 }
             }, [](std::shared_ptr<CitationGraph<Publication2>> &graph) {
                    steps_left_to_throw = inf;

                    for (size_t i = 0; i <= 9; ++i) {
                        BOOST_CHECK_NO_THROW((*graph)[i]);
                        BOOST_CHECK_EQUAL(graph->exists(i), true);
                    }

                    for (size_t i = 10; i <= build2_list_size; ++i) {
                        BOOST_CHECK_THROW((*graph)[i], PublicationNotFound);
                        BOOST_CHECK_EQUAL(graph->exists(i), false);
                    }

                    for (int i = 1; i < 9; ++i) {
                        check_children(graph, i, std::vector<Id>{i + 1, 0});
                    }

                    check_children(graph, 9, std::vector<Id>{0});
                    check_children(graph, 0, std::vector<Id>{});

                    for (int i = 2; i <= 9; ++i) {
                        check_parents(graph, i, std::vector<Id>{i - 1});
                    }

                    std::vector<Id> parentsOf0;

                    for (size_t i = 1; i <= 9; ++i) {
                        parentsOf0.push_back(i);
                    }

                    check_parents(graph, 0, parentsOf0);
                });
    }

    Publication::id_type
    no_except_id_pub_get_id_wrapper() noexcept(noexcept(std::declval<CitationGraph<Publication>>().get_root_id())) {
        return CitationGraph<Publication>("A").get_root_id();
    }

    Publication2::id_type
    except_id_pub_get_id_wrapper() noexcept(noexcept(std::declval<CitationGraph<Publication2>>().get_root_id())) {
        return CitationGraph<Publication2>(2).get_root_id();
    }

//    BOOST_AUTO_TEST_CASE(get_id) {
//        steps_left_to_throw = inf;
//        BOOST_CHECK(
//                (std::is_nothrow_invocable_r<Publication::id_type, decltype(no_except_id_pub_get_id_wrapper)>::value));
//        BOOST_CHECK(
//                (!std::is_nothrow_invocable_r<Publication2::id_type, decltype(except_id_pub_get_id_wrapper)>::value));
//    }

    BOOST_AUTO_TEST_CASE(constructor) {
        { //creation
            for (long long step = 0;; ++step) {
                steps_left_to_throw = step;
                try {
                    test_memory = true;
                    CitationGraph<Publication2> graph(Id(1));
                } catch (...) {
                    test_memory = false;
                    continue;
                }
                test_memory = false;

                constructor_passes_after = step;
                //constructor_passes_after = inf;
                std::cerr << "constructor passes after:" << constructor_passes_after << std::endl;
                break;

            }

        }

        BOOST_CHECK((!std::is_copy_constructible<CitationGraph<Publication2>>::value));

        BOOST_CHECK((std::is_nothrow_move_constructible<CitationGraph<Publication2>>::value));
        { //move
            steps_left_to_throw = inf;
            CitationGraph<Publication2> to_move(Id(1));

            steps_left_to_throw = 0;
            auto test_lambda = [&to_move]() {
                test_memory = true;
                CitationGraph<Publication2> graph(std::move(to_move));
                test_memory = false;
            };
            BOOST_CHECK_NO_THROW(test_lambda());

        }

        {//move with some nodes
            steps_left_to_throw = inf;
            std::shared_ptr<CitationGraph<Publication2>> to_move = build1();

            steps_left_to_throw = 0;
            std::shared_ptr<CitationGraph<Publication2>> graph(new CitationGraph<Publication2>(std::move(*to_move)));

            steps_left_to_throw = inf;
            check_build1(graph);

        }
    }

    BOOST_AUTO_TEST_CASE(destructor) {
        BOOST_CHECK((std::is_nothrow_destructible<CitationGraph<Publication2>>::value));
    }

    BOOST_AUTO_TEST_CASE(assign) {
        BOOST_CHECK((!std::is_copy_assignable<CitationGraph<Publication2>>::value));
    }

    BOOST_AUTO_TEST_CASE(move) {

        BOOST_CHECK((std::is_nothrow_move_assignable<CitationGraph<Publication2>>::value));
        { //move assign
            steps_left_to_throw = inf;
            CitationGraph<Publication2> graph(Id(1));

            steps_left_to_throw = inf;
            CitationGraph<Publication2> graph2(Id(1));

            steps_left_to_throw = 0;
            BOOST_CHECK_NO_THROW(graph2 = std::move(graph));
        }

        { //move with some nodes
            steps_left_to_throw = inf;
            std::shared_ptr<CitationGraph<Publication2>> to_move = build1();
            std::shared_ptr<CitationGraph<Publication2>> graph(new CitationGraph<Publication2>(0));

            steps_left_to_throw = 0;
            test_memory = true;
            *graph = std::move(*to_move);
            test_memory = false;

            steps_left_to_throw = inf;
            check_build1(graph);
        }

        { //self move
            steps_left_to_throw = inf;
            std::shared_ptr<CitationGraph<Publication2>> to_move = build1();

            steps_left_to_throw = 0;
            test_memory = true;
            *to_move = std::move(*to_move);
            test_memory = false;

            steps_left_to_throw = inf;
            check_build1(to_move);
        }
    }

    BOOST_AUTO_TEST_CASE(exitMemory) {
        std::atexit(memCheck);
    }

BOOST_AUTO_TEST_SUITE_END()


text:
/***************************************************************************
   Copyright 2015 Ufora Inc.

   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.
****************************************************************************/
#pragma once

#include <stdint.h>
#include <boost/python.hpp>
#include "../lassert.hpp"
#include "../containers/ImmutableTreeVector.hppml"
#include "../containers/ImmutableTreeMap.hppml"
#include "../numpy/TypedNumpyWrapper.hpp"
#include "../math/Nullable.hpp"
#include "../Logging.hpp"
#include "../PolymorphicSharedPtr.hpp"
#include <vector>

namespace Ufora {
namespace python {

//take a pair of C++ iterators and append their elements onto the end of a new python
//list. The objects must be convertable to python objects.
template<class iterator_type>
boost::python::object iteratorPairToList(iterator_type begin, iterator_type end)
	{
	boost::python::list l;
	while (begin != end)
		{
		l.append(*begin);
		begin++;
		}

	return l;
	}

//take a pair of C++ iterators and append their elements onto the end of a new python
//list, applying inAdapter to each element. The result of the inAdapter call
// must be convertable to a python object.
template<class iterator_type, class adapter_type>
boost::python::object iteratorPairToList(iterator_type begin, iterator_type end, const adapter_type& inAdapter)
	{
	boost::python::list l;
	while (begin != end)
		{
		l.append(inAdapter(*begin));
		begin++;
		}

	return l;
	}

//take a C++ class that exposes begin/end pairs and pack it into a new python list.
template<class T>
boost::python::object containerWithBeginEndToList(const T& in)
	{
	return iteratorPairToList(in.begin(), in.end());
	}

//take a C++ class that exposes begin/end pairs and pack it into a new python list.
//applies 'inAdapter' to every element
template<class T, class adapter_type>
boost::python::object containerWithBeginEndToList(const T& in, const adapter_type& inAdapter)
	{
	return iteratorPairToList(in.begin(), in.end(), inAdapter);
	}

template<class T>
class	Converter {
public:
		static boost::python::object	toPython(const T& in)
			{
			return boost::python::object(in);
			}
		static void toCPP(boost::python::object o, T& outT)
			{
			lassert(boost::python::extract<T>(o).check());
			outT = boost::python::extract<T>(o);
			}
		static void toCPPAsInit(boost::python::object o, T& outT)
			{
			lassert(boost::python::extract<T>(o).check());
			new (&outT) T(boost::python::extract<T>(o));
			}
};

template<class T>
void	toCPP(boost::python::object o, T& outT)
	{
	try {
		Converter<T>::toCPP(o, outT);
		}
	catch(...)
		{
		LOG_WARN << "RANDOM TOCPP... " << Ufora::debug::StackTrace::demangle(typeid(T).name()) << "\n";
		}
	}
template<class T>
void	toCPPAsInit(boost::python::object o, T& outT)
	{
	try {
		Converter<T>::toCPPAsInit(o, outT);
		}
	catch(...)
		{
		LOG_WARN << "RANDOM TOCPP INIT " << Ufora::debug::StackTrace::demangle(typeid(T).name()) << "...\n";
		}
	}
template<class T>
boost::python::object	toPython(const T& inT)
	{
	try {
		return Converter<T>::toPython(inT);
		}
	catch(...)
		{
		LOG_WARN << "RANDOM...\n";
		return boost::python::object("FAILED");
		}
	}

template<class T>
std::tuple<T> toTuple(boost::python::tuple pyTuple)
	{
	lassert(boost::python::len(pyTuple) == 1);
	boost::python::extract<T> extractor(pyTuple[0]);
	lassert(extractor.check());

	return std::make_tuple(extractor());
	}

template<class T1, class T2>
std::tuple<T1, T2> toTuple(boost::python::tuple pyTuple)
	{
	lassert(boost::python::len(pyTuple) == 2);
	boost::python::extract<T1> extractor1(pyTuple[0]);
	lassert(extractor1.check());
	boost::python::extract<T2> extractor2(pyTuple[1]);
	lassert(extractor2.check());

	return std::make_tuple(extractor1(), extractor2());
	}

template<class T1, class T2, class T3>
std::tuple<T1, T2, T3> toTuple(boost::python::tuple pyTuple)
	{
	lassert(boost::python::len(pyTuple) == 3);
	boost::python::extract<T1> extractor1(pyTuple[0]);
	lassert(extractor1.check());
	boost::python::extract<T2> extractor2(pyTuple[1]);
	lassert(extractor2.check());
	boost::python::extract<T3> extractor3(pyTuple[2]);
	lassert(extractor3.check());

	return std::make_tuple(extractor1(), extractor2(), extractor3());
	}

template<class T1, class T2, class T3, class T4>
std::tuple<T1, T2, T3, T4> toTuple(boost::python::tuple pyTuple)
	{
	lassert(boost::python::len(pyTuple) == 4);
	boost::python::extract<T1> extractor1(pyTuple[0]);
	lassert(extractor1.check());
	boost::python::extract<T2> extractor2(pyTuple[1]);
	lassert(extractor2.check());
	boost::python::extract<T3> extractor3(pyTuple[2]);
	lassert(extractor3.check());
	boost::python::extract<T4> extractor4(pyTuple[3]);
	lassert(extractor4.check());

	return std::make_tuple(extractor1(), extractor2(), extractor3(), extractor4());
	}

template<>
class Converter<vector<double> > {
public:
		typedef double	T;

		static void	toCPPAsInit(boost::python::object o, vector<T>& outT)
			{
			new (&outT) vector<T>();
			toCPP(o, outT);
			}
		static void	toCPP(boost::python::object o, vector<T>& outT)
			{
			outT.resize(0);

			try {
				::Ufora::numpy::TypedNumpyWrapper<double, 1> wrap(o);
				outT.resize(wrap.size());
				for (int32_t k = 0; k < outT.size(); k++)
					outT[k] = wrap[k];
				return;
				}
			catch(...)
				{
				}

			try {
				Ufora::numpy::TypedNumpyWrapper<float, 1> wrap(o);
				outT.resize(wrap.size());
				for (int32_t k = 0; k < outT.size(); k++)
					outT[k] = wrap[k];
				return;
				}
			catch(...)
				{
				}

			//generic iterator...
			boost::python::object it = o.attr("__iter__")();

			try {
				while(1)
					{
					outT.resize(outT.size() + 1);
					Converter<T>::toCPP(it.attr("next")(), outT.back());
					}
				}
			catch(...)
				{
				outT.resize(outT.size()-1);
				PyErr_Clear();
				}
			}

		static boost::python::object	toPython(const vector<T>& inT)
			{
			boost::python::object numpy = boost::python::import("numpy");

			boost::python::object o = numpy.attr("zeros")(inT.size()).attr("astype")("double");
			::Ufora::numpy::TypedNumpyWrapper<T, 1> wrap(o);

			for (int32_t k = 0; k < inT.size();k++)
				o[k] = inT[k];

			return o;
			}
};

template<>
class Converter<vector<std::complex<double> > > {
public:
		typedef std::complex<double>	T;

		static void	toCPPAsInit(boost::python::object o, vector<T>& outT)
			{
			new (&outT) vector<T>();
			toCPP(o, outT);
			}
		static void	toCPP(boost::python::object o, vector<T>& outT)
			{
			outT.resize(0);

			try {
				Ufora::numpy::TypedNumpyWrapper<std::complex<double>, 1> wrap(o);
				outT.resize(wrap.size());
				for (int32_t k = 0; k < outT.size(); k++)
					outT[k] = wrap[k];
				return;
				}
			catch(...)
				{
				}

			try {
				Ufora::numpy::TypedNumpyWrapper<std::complex<float>, 1> wrap(o);
				outT.resize(wrap.size());
				for (int32_t k = 0; k < outT.size(); k++)
					outT[k] = wrap[k];
				return;
				}
			catch(...)
				{
				}

			//generic iterator...
			boost::python::object it = o.attr("__iter__")();

			try {
				while(1)
					{
					outT.resize(outT.size() + 1);
					Converter<T>::toCPP(it.attr("next")(), outT.back());
					}
				}
			catch(...)
				{
				outT.resize(outT.size()-1);
				PyErr_Clear();
				}
			}

		static boost::python::object	toPython(const vector<T>& inT)
			{
			boost::python::object numpy = boost::python::import("numpy");

			boost::python::object o = numpy.attr("zeros")(inT.size()).attr("astype")("complex");
			Ufora::numpy::TypedNumpyWrapper<T, 1> wrap(o);

			for (int32_t k = 0; k < inT.size();k++)
				o[k] = inT[k];

			return o;
			}
};

template<>
class Converter<vector<float> > {
public:
		typedef float	T;

		static void	toCPPAsInit(boost::python::object o, vector<T>& outT)
			{
			new (&outT) vector<T>();
			toCPP(o, outT);
			}
		static void	toCPP(boost::python::object o, vector<T>& outT)
			{
			outT.resize(0);

			try {
				Ufora::numpy::TypedNumpyWrapper<float, 1> wrap(o);
				outT.resize(wrap.size());
				for (int32_t k = 0; k < outT.size(); k++)
					outT[k] = wrap[k];
				return;
				}
			catch(...)
				{
				}

			try {
				Ufora::numpy::TypedNumpyWrapper<double, 1> wrap(o);
				outT.resize(wrap.size());
				for (int32_t k = 0; k < outT.size(); k++)
					outT[k] = wrap[k];
				return;
				}
			catch(...)
				{
				}

			//generic iterator...
			boost::python::object it = o.attr("__iter__")();

			try {
				while(1)
					{
					outT.resize(outT.size() + 1);
					Converter<T>::toCPP(it.attr("next")(), outT.back());
					}
				}
			catch(...)
				{
				outT.resize(outT.size()-1);
				PyErr_Clear();
				}
			}

		static boost::python::object	toPython(const vector<T>& inT)
			{
			boost::python::object numpy = boost::python::import("numpy");

			boost::python::object o = numpy.attr("zeros")(inT.size()).attr("astype")("float");
			Ufora::numpy::TypedNumpyWrapper<T, 1> wrap(o);

			for (int32_t k = 0; k < inT.size();k++)
				o[k] = inT[k];

			return o;
			}
};

template<class T>
class Converter<vector<T> > {
public:
		static void	toCPP(boost::python::object o, vector<T>& outT)
			{
			outT.clear();

			boost::python::object it = o.attr("__iter__")();

			try {
				while(1)
					{
					char dat[sizeof(T)];
					Converter<T>::toCPPAsInit(it.attr("next")(), ((T*)dat)[0]);
					outT.push_back(((T*)dat)[0]);
					((T*)dat)->~T();
					}
				}
			catch(...)
				{
				PyErr_Clear();
				}
			}

		static boost::python::object	toPython(const vector<T>& inT)
			{
			boost::python::list o = boost::python::list();

			for (int32_t k = 0; k < inT.size();k++)
				o.append(Converter<T>::toPython(inT[k]));
			return o;
			}
};

template<class T>
class Converter<ImmutableTreeVector<T> > {
public:
		static void	toCPP(boost::python::object o, ImmutableTreeVector<T>& outT)
			{
			outT = ImmutableTreeVector<T>();

			boost::python::object it = o.attr("__iter__")();

			while(1)
				{
				T t;

				boost::python::object o;
				try {
					o = it.attr("next")();
					}
				catch(...)
					{
					PyErr_Clear();
					return;
					}

				Converter<T>::toCPP(o, t);
				outT = outT + t;
				}
			}

		static boost::python::object	toPython(const ImmutableTreeVector<T>& inT)
			{
			boost::python::list o = boost::python::list();

			for (int32_t k = 0; k < inT.size();k++)
				o.append(Converter<T>::toPython(inT[k]));

			return o;
			}
};

template<class T1, class T2>
class Converter<ImmutableTreeMap<T1, T2> > {
public:
		static void	toCPP(boost::python::object o, ImmutableTreeMap<T1, T2>& outT)
			{
			outT = ImmutableTreeMap<T1, T2>();

			boost::python::object it = o.attr("__iter__")();

			while(1)
				{
				T1 t1;
				T2 t2;

				boost::python::object key;
				try {
					key = it.attr("next")();
					}
				catch(...)
					{
					PyErr_Clear();
					return;
					}

				Converter<T1>::toCPP(key, t1);
				Converter<T2>::toCPP(o[key], t2);

				outT = outT + make_pair(t1, t2);
				}
			}

		static boost::python::object	toPython(const ImmutableTreeMap<T1, T2>& inT)
			{
			boost::python::dict o = boost::python::dict();

			for (int32_t k = 0; k < inT.size();k++)
				o[Converter<T1>::toPython(inT.pairAtPosition(k).first)]
				 					= Converter<T2>::toPython(inT.pairAtPosition(k).second);

			return o;
			}
};

template<class T1, class T2>
class Converter<pair<T1, T2> > {
public:
		static void	toCPPAsInit(boost::python::object o, pair<T1, T2>& outT)
			{
			new (&outT) pair<T1, T2>();
			toCPP(o, outT);
			}
		boost::python::object	toPython(const pair<T1, T2>& inT)
			{
			return boost::python::make_tuple(Converter<T1>::toPython(inT.first), Converter<T2>::toPython(inT.second));
			}

		static void toCPP(boost::python::object o, pair<T1, T2>& outT)
			{
			try {
				Converter<T1>::toCPP(o[0], outT.first);
				Converter<T2>::toCPP(o[1], outT.second);
				}
			catch(...)
				{
				PyErr_Clear();
				}
			}
};

template<class T1>
class Converter<Nullable<T1> > {
public:
		boost::python::object	toPython(const Nullable<T1>& inT)
			{
			if (!inT)
				return boost::python::object();
			return boost::python::object(Converter<T1>::toPython(*inT));
			}

		static void toCPP(boost::python::object o, Nullable<T1>& outT)
			{
			if (!o.ptr())
				{
				outT = null();
				return;
				}

			try {
				T1 final;

				Converter<T1>::toCPP(o, final);

				outT = final;
				}
			catch(...)
				{
				PyErr_Clear();
				}
			}
};
class Holder {
public:
		Holder(const string& inEval, const string& inSpace)
			{
			mEval = inEval;
			mSpace = inSpace;
			mInitialized = false;
			}
		boost::python::object get(void)
			{
			if (!mInitialized)
				{
				boost::python::object ns = boost::python::import(mSpace.c_str()).attr("__dict__");
				o = boost::python::eval(mEval.c_str(), ns, ns);
				mInitialized = true;
				}
			return o;
			}
private:
		bool mInitialized;
		boost::python::object o;
		string mEval, mSpace;
};

inline boost::python::object evalInModule(const char *inObjectName, const char *inNamespace)
	{
	boost::python::object ns = boost::python::import(inNamespace).attr("__dict__");
	return boost::python::eval(inObjectName, ns, ns);
	}

inline boost::python::object isInstance(boost::python::object inO1, boost::python::object inO2)
	{
	static boost::python::object _isInstance;
	if (_isInstance == boost::python::object())
		_isInstance = evalInModule("__builtin__.isinstance", "site");

	return _isInstance(inO1, inO2);
	}

inline string pyToString(boost::python::object o)
	{
	lassert(boost::python::extract<string>(boost::python::str(o)).check());
	return boost::python::extract<string>(boost::python::str(o));
	}

inline unsigned long id(const boost::python::object& inO)
	{
	return (unsigned long)inO.ptr();
	}

};
};

max_stars_repo_name: ufora/ufora