text:
/******************************************************************************

  Non-trivial node types (class lables) for MRF models.

  Copyright (c) 2012, 2013
  Alexander Rukletsov <rukletsov@gmail.com>
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:
  1.  Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
  2.  Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  SUCH DAMAGE.

*******************************************************************************/

#ifndef NODE_TYPES_HPP_6CF0A0E1_8AE9_4951_A785_9339B90FB976
#define NODE_TYPES_HPP_6CF0A0E1_8AE9_4951_A785_9339B90FB976

#include <cmath>
#include <iostream>
#include <boost/tuple/tuple.hpp>
#include <boost/operators.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/math/special_functions/gamma.hpp>

namespace bo {
namespace mrf {

template <typename P>
class ParametricNodeType: boost::equality_comparable1<ParametricNodeType<P> >
{
public:
    typedef boost::shared_ptr<P> ClassParamsPtr;

    ParametricNodeType(ClassParamsPtr class_params): class_params_(class_params)
    { }

    //  Generated copy c-tor and assignment operator are fine.

    virtual ~ParametricNodeType()
    { }

    // Classes are equal when their parameters are equal.
    virtual bool operator==(const ParametricNodeType<P>& other) const
    { return (class_params_ == other.class_params_); }

protected:
    ClassParamsPtr class_params_;
};

// A class representing a value (class label) with associated Gauss distribution
// parameters. Parameters structure is represented as a tuple with 4 elements:
// class label, mean, standard deviation, and additional item a = ln(sigma * sqrt(2 pi)).
template <typename RealType>
class GaussDistrClasses: public ParametricNodeType<
        boost::tuples::tuple<int, RealType, RealType, RealType> >
{
public:
    typedef GaussDistrClasses<RealType> SelfType;

    typedef boost::tuples::tuple<int, RealType, RealType, RealType> ClassParams;
    typedef ParametricNodeType<ClassParams> BaseType;
    typedef typename BaseType::ClassParamsPtr ClassParamsPtr;

public:
    GaussDistrClasses(ClassParamsPtr class_params): BaseType(class_params)
    { }

    static GaussDistrClasses CreateInstance(int idx, RealType mean, RealType sigma)
    { return (SelfType(boost::make_shared<ClassParams>(idx, mean, sigma, compute_a(sigma)))); }

    // Accessors for class label and class parameters.
    int label() const
    { return this->class_params_->template get<0>(); }

    RealType mean() const
    { return this->class_params_->template get<1>(); }

    RealType sigma() const
    { return this->class_params_->template get<2>(); }

    RealType a() const
    { return this->class_params_->template get<3>(); }

    // 2.5 is precomputed sqrt(2 pi).
    static RealType compute_a(RealType sigma)
    { return (std::log(sigma * RealType(2.5))); }
};

// A class representing a value (class label) with associated Gamma distribution
// parameters. Parameters structure is represented as a tuple with 4 elements:
// class label and a set of Gamma distribution parameters (k, theta, a), where
// a = ln(G(k)) + k ln(theta) and G(t) is the Gamma function.
template <typename RealType>
class GammaDistrClasses: public ParametricNodeType<
        boost::tuples::tuple<int, RealType, RealType, RealType> >
{
public:
    typedef GammaDistrClasses<RealType> SelfType;

    typedef boost::tuples::tuple<int, RealType, RealType, RealType> ClassParams;
    typedef ParametricNodeType<ClassParams> BaseType;
    typedef typename BaseType::ClassParamsPtr ClassParamsPtr;

public:
    GammaDistrClasses(ClassParamsPtr class_params): BaseType(class_params)
    { }

    static GammaDistrClasses CreateInstance(int idx, RealType k, RealType theta)
    { return (SelfType(boost::make_shared<ClassParams>(idx, k, theta, compute_a(k, theta)))); }

    // Accessors for class label and class parameters.
    int label() const
    { return this->class_params_->template get<0>(); }

    RealType k() const
    { return this->class_params_->template get<1>(); }

    RealType theta() const
    { return this->class_params_->template get<2>(); }

    RealType a() const
    { return this->class_params_->template get<3>(); }

    RealType mean() const
    { return (k() * theta()); }

    static RealType compute_a(RealType k, RealType theta)
    { return (boost::math::lgamma(k) + k * std::log(theta)); }
};

template <typename T>
std::ostream& operator<<(std::ostream& os, const GaussDistrClasses<T>& obj)
{
    os << obj.label() << " (mean: " << obj.mean() << ", sigma: " << obj.sigma() << ")";
    return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const GammaDistrClasses<T>& obj)
{
    os << obj.label() << " (k: " << obj.k() << ", theta: " << obj.theta() << ")";
    return os;
}

} // namespace mrf
} // namespace bo

#endif // NODE_TYPES_HPP_6CF0A0E1_8AE9_4951_A785_9339B90FB976

ext: hpp

max_stars_repo_name: rukletsov/bo

max_issues_repo_name: rukletsov/bo

max_forks_repo_name: rukletsov/bo


text:
// boost_teststatdata.cpp : Defines the entry point for the console application.
//
#define BOOST_TEST_MODULE "C++ Unit Tests for statdata"
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
/////////////////////////////

ext: cpp

max_stars_repo_name: boubad/CygProjects

max_issues_repo_name: boubad/CygProjects

max_forks_repo_name: boubad/CygProjects


text:
/*
 * Lumi3DReWeighting.cpp
 *
 *  Created on: 5 Dec 2011
 *      Author: kreczko
 */

#include "../interface/Lumi3DReWeighting.h"

#include "TRandom1.h"
#include "TRandom2.h"
#include "TRandom3.h"
#include "TStopwatch.h"
#include "TH1.h"
#include "TH3.h"
#include "TFile.h"
#include <string>
#include <algorithm>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <iostream>

namespace BAT {

Lumi3DReWeighting::Lumi3DReWeighting(std::string generatedFile, std::string dataFile,
		std::string GenHistName = "pileup", std::string DataHistName = "pileup") :
		generatedFileName_(generatedFile), //
		dataFileName_(dataFile), //
		GenHistName_(GenHistName), //
		DataHistName_(DataHistName) {
	generatedFile_ = boost::shared_ptr<TFile>(new TFile(generatedFileName_.c_str())); //MC distribution
	dataFile_ = boost::shared_ptr<TFile>(new TFile(dataFileName_.c_str())); //Data distribution

	boost::scoped_ptr<TH1> Data_temp((static_cast<TH1*>(dataFile_->Get(DataHistName_.c_str())->Clone())));

	boost::scoped_ptr<TH1> MC_temp((static_cast<TH1*>(generatedFile_->Get(GenHistName_.c_str())->Clone())));

	MC_distr_ = boost::shared_ptr<TH1>((static_cast<TH1*>(generatedFile_->Get(GenHistName_.c_str())->Clone())));
	Data_distr_ = boost::shared_ptr<TH1>((static_cast<TH1*>(dataFile_->Get(DataHistName_.c_str())->Clone())));

	// MC * data/MC = data, so the weights are data/MC:

	// normalize both histograms first

	Data_distr_->Scale(1.0 / Data_distr_->Integral());
	MC_distr_->Scale(1.0 / MC_distr_->Integral());

}

Lumi3DReWeighting::Lumi3DReWeighting(std::vector<float> MC_distr, std::vector<float> Lumi_distr) {
	// no histograms for input: use vectors

	// now, make histograms out of them:

	Int_t NMCBins = MC_distr.size();

	MC_distr_ = boost::shared_ptr<TH1>(new TH1F("MC_distr", "MC dist", NMCBins, 0., float(NMCBins)));

	Int_t NDBins = Lumi_distr.size();

	Data_distr_ = boost::shared_ptr<TH1>(new TH1F("Data_distr", "Data dist", NDBins, 0., float(NDBins)));

	for (int ibin = 1; ibin < NMCBins + 1; ++ibin) {
		MC_distr_->SetBinContent(ibin, MC_distr[ibin - 1]);
	}

	for (int ibin = 1; ibin < NDBins + 1; ++ibin) {
		Data_distr_->SetBinContent(ibin, Lumi_distr[ibin - 1]);
	}

	// check integrals, make sure things are normalized

	float deltaH = Data_distr_->Integral();
	if (fabs(1.0 - deltaH) > 0.001) { //*OOPS*...
		Data_distr_->Scale(1.0 / Data_distr_->Integral());
	}
	float deltaMC = MC_distr_->Integral();
	if (fabs(1.0 - deltaMC) > 0.001) {
		MC_distr_->Scale(1.0 / MC_distr_->Integral());
	}

}

double Lumi3DReWeighting::weight3D(int pv1, int pv2, int pv3) {

	using std::min;

	int npm1 = min(pv1, NVERTEX - 1);
	int np0 = min(pv2, NVERTEX - 1);
	int npp1 = min(pv3, NVERTEX - 1);

	return Weight3D_[npm1][np0][npp1];

}

/**
 * @PARAM ScaleFactor: Scale factor is used to shift target distribution (i.e. luminosity scale)  1. = no shift
 */
void Lumi3DReWeighting::weight3D_init(float ScaleFactor) {

	//create histogram to write output weights, save pain of generating them again...

	boost::scoped_ptr<TH3D> WHist(
			new TH3D("WHist", "3D weights", NVERTEX, -.5, 49.5, NVERTEX, -.5, 49.5, NVERTEX, -.5, 49.5));
	boost::scoped_ptr<TH3D> DHist(
			new TH3D("DHist", "3D weights", NVERTEX, -.5, 49.5, NVERTEX, -.5, 49.5, NVERTEX, -.5, 49.5));
	boost::scoped_ptr<TH3D> MHist(
			new TH3D("MHist", "3D weights", NVERTEX, -.5, 49.5, NVERTEX, -.5, 49.5, NVERTEX, -.5, 49.5));

	using std::min;

	if (MC_distr_->GetEntries() == 0) {
		std::cout << " MC and Data distributions are not initialised! You must call the Lumi3DReWeighting constructor. "
				<< std::endl;
	}

	// arrays for storing number of interactions

	double MC_ints[NVERTEX][NVERTEX][NVERTEX];
	double Data_ints[NVERTEX][NVERTEX][NVERTEX];

	for (int i = 0; i < NVERTEX; i++) {
		for (int j = 0; j < NVERTEX; j++) {
			for (int k = 0; k < NVERTEX; k++) {
				MC_ints[i][j][k] = 0.;
				Data_ints[i][j][k] = 0.;
			}
		}
	}

	double factorial[NVERTEX];
	double PowerSer[NVERTEX];
	double base = 1.;

	factorial[0] = 1.;
	PowerSer[0] = 1.;

	for (int i = 1; i < NVERTEX + 1; ++i) {
		base = base * float(i);
		factorial[i] = base;
	}

	double x;
	double xweight;
	double probi, probj, probk;
	double Expval, mean;
	int xi;

	// Get entries for Data, MC, fill arrays:

	int NMCbin = MC_distr_->GetNbinsX();

	for (int jbin = 1; jbin < NMCbin + 1; jbin++) {
		x = MC_distr_->GetBinCenter(jbin);
		xweight = MC_distr_->GetBinContent(jbin); //use as weight for matrix

		//for Summer 11, we have this int feature:
		xi = int(x);

		// Generate Poisson distribution for each value of the mean

		mean = double(xi);

		if (mean < 0.) {
//      throw cms::Exception("BadInputValue") << " Your histogram generates MC luminosity values less than zero!"
//						<< " Please Check.  Terminating." << std::endl;
		}

		if (mean == 0.) {
			Expval = 1.;
		} else {
			Expval = exp(-1. * mean);
		}

		base = 1.;

		for (int i = 1; i < NVERTEX; ++i) {
			base = base * mean;
			PowerSer[i] = base; // PowerSer is mean^i
		}

		// compute poisson probability for each Nvtx in weight matrix

		for (int i = 0; i < NVERTEX; i++) {
			probi = PowerSer[i] / factorial[i] * Expval;
			for (int j = 0; j < NVERTEX; j++) {
				probj = PowerSer[j] / factorial[j] * Expval;
				for (int k = 0; k < NVERTEX; k++) {
					probk = PowerSer[k] / factorial[k] * Expval;
					// joint probability is product of event weights multiplied by weight of input distribution bin
					MC_ints[i][j][k] = MC_ints[i][j][k] + probi * probj * probk * xweight;
				}
			}
		}

	}

	int NDatabin = Data_distr_->GetNbinsX();

	for (int jbin = 1; jbin < NDatabin + 1; jbin++) {
		mean = (Data_distr_->GetBinCenter(jbin)) * ScaleFactor;
		xweight = Data_distr_->GetBinContent(jbin);

		// Generate poisson distribution for each value of the mean

		if (mean < 0.) {
//      throw cms::Exception("BadInputValue") << " Your histogram generates Data luminosity values less than zero!"
//						<< " Please Check.  Terminating." << std::endl;
		}

		if (mean == 0.) {
			Expval = 1.;
		} else {
			Expval = exp(-1. * mean);
		}

		base = 1.;

		for (int i = 1; i < NVERTEX; ++i) {
			base = base * mean;
			PowerSer[i] = base;
		}

		// compute poisson probability for each Nvtx in weight matrix

		for (int i = 0; i < NVERTEX; i++) {
			probi = PowerSer[i] / factorial[i] * Expval;
			for (int j = 0; j < NVERTEX; j++) {
				probj = PowerSer[j] / factorial[j] * Expval;
				for (int k = 0; k < NVERTEX; k++) {
					probk = PowerSer[k] / factorial[k] * Expval;
					// joint probability is product of event weights multiplied by weight of input distribution bin
					Data_ints[i][j][k] = Data_ints[i][j][k] + probi * probj * probk * xweight;
				}
			}
		}

	}

	for (int i = 0; i < NVERTEX; i++) {
		//if(i<5) std::cout << "i = " << i << std::endl;
		for (int j = 0; j < NVERTEX; j++) {
			for (int k = 0; k < NVERTEX; k++) {
				if ((MC_ints[i][j][k]) > 0.) {
					Weight3D_[i][j][k] = Data_ints[i][j][k] / MC_ints[i][j][k];
				} else {
					Weight3D_[i][j][k] = 0.;
				}
				WHist->SetBinContent(i + 1, j + 1, k + 1, Weight3D_[i][j][k]);
				DHist->SetBinContent(i + 1, j + 1, k + 1, Data_ints[i][j][k]);
				MHist->SetBinContent(i + 1, j + 1, k + 1, MC_ints[i][j][k]);
				//	if(i<5 && j<5 && k<5) std::cout << Weight3D_[i][j][k] << " " ;
			}
			//      if(i<5 && j<5) std::cout << std::endl;
		}
	}

	std::cout << " 3D Weight Matrix initialized! " << std::endl;
	std::cout << " Writing weights to file Weight3D.root for re-use...  " << std::endl;

	boost::scoped_ptr<TFile> outfile(new TFile("Weight3D.root", "RECREATE"));
	outfile->cd();
	WHist->Write();
	MHist->Write();
	DHist->Write();
	outfile->Write();
	outfile->Close();
//	outfile->Delete();

	return;

}

void Lumi3DReWeighting::weight3D_init(std::string WeightFileName) {

	boost::scoped_ptr<TFile> infile(new TFile(WeightFileName.c_str()));
	boost::scoped_ptr<TH3D> WHist((TH3D*) infile->Get("WHist"));

	// Check if the histogram exists
	if (!WHist) {
//    throw cms::Exception("HistogramNotFound") << " Could not find the histogram WHist in the file "
//					      << "in the file " << WeightFileName << "." << std::endl;
	}

	for (int i = 0; i < NVERTEX; i++) {
		for (int j = 0; j < NVERTEX; j++) {
			for (int k = 0; k < NVERTEX; k++) {
				Weight3D_[i][j][k] = WHist->GetBinContent(i + 1, j + 1, k + 1);
			}
		}
	}

	std::cout << " 3D Weight Matrix initialized! " << std::endl;

	return;

}

void Lumi3DReWeighting::weight3D_init(std::string MCWeightFileName, std::string DataWeightFileName) {

	boost::scoped_ptr<TFile> infileMC(new TFile(MCWeightFileName.c_str()));
	boost::scoped_ptr<TH3D> MHist((TH3D*) infileMC->Get("MHist"));

	// Check if the histogram exists
	if (!MHist) {
//    throw cms::Exception("HistogramNotFound") << " Could not find the histogram MHist in the file "
//					      << "in the file " << MCWeightFileName << "." << std::endl;
	}

	boost::scoped_ptr<TFile> infileD(new TFile(DataWeightFileName.c_str()));
	boost::scoped_ptr<TH3D> DHist((TH3D*) infileD->Get("DHist"));

	// Check if the histogram exists
	if (!DHist) {
//    throw cms::Exception("HistogramNotFound") << " Could not find the histogram DHist in the file "
//					      << "in the file " << DataWeightFileName << "." << std::endl;
	}

	for (int i = 0; i < NVERTEX; i++) {
		for (int j = 0; j < NVERTEX; j++) {
			for (int k = 0; k < NVERTEX; k++) {
				Weight3D_[i][j][k] = DHist->GetBinContent(i + 1, j + 1, k + 1)
						/ MHist->GetBinContent(i + 1, j + 1, k + 1);
			}
		}
	}

	std::cout << " 3D Weight Matrix initialized! " << std::endl;

	return;

}

} /* namespace BAT */

max_stars_repo_name: jjacob/AnalysisSoftware

max_issues_repo_name: jjacob/AnalysisSoftware

max_forks_repo_name: jjacob/AnalysisSoftware


text:
// Copyright 2020 Peter Dimov
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt

#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/core/lightweight_test.hpp>

int main()
{
    {
        boost::shared_ptr<int> p1( new int );
        boost::shared_ptr<int> p2( p1 );

        BOOST_TEST( !p1.owner_before( p2 ) );
        BOOST_TEST( !p2.owner_before( p1 ) );

        boost::shared_ptr<int> p3( new int );

        BOOST_TEST( p1.owner_before( p3 ) || p3.owner_before( p1 ) );

        boost::shared_ptr<int> p4;
        boost::shared_ptr<int> p5;

        BOOST_TEST( !p4.owner_before( p5 ) );
        BOOST_TEST( !p5.owner_before( p4 ) );

        BOOST_TEST( p4.owner_before( p3 ) || p3.owner_before( p4 ) );

        boost::shared_ptr<int> p6( static_cast<int*>(0) );

        BOOST_TEST( p4.owner_before( p6 ) || p6.owner_before( p4 ) );

        boost::shared_ptr<void> p7( p1 );

        BOOST_TEST( !p1.owner_before( p7 ) );
        BOOST_TEST( !p7.owner_before( p1 ) );

        boost::shared_ptr<void> p8;

        BOOST_TEST( p1.owner_before( p8 ) || p8.owner_before( p1 ) );

        BOOST_TEST( !p4.owner_before( p8 ) );
        BOOST_TEST( !p8.owner_before( p4 ) );

        boost::weak_ptr<int> q1( p1 );

        BOOST_TEST( !p1.owner_before( q1 ) );
        BOOST_TEST( !q1.owner_before( p1 ) );

        boost::weak_ptr<int> q2( p1 );

        BOOST_TEST( !q1.owner_before( q2 ) );
        BOOST_TEST( !q2.owner_before( q1 ) );

        boost::weak_ptr<int> q3( p3 );

        BOOST_TEST( p1.owner_before( q3 ) || q3.owner_before( p1 ) );
        BOOST_TEST( q1.owner_before( q3 ) || q3.owner_before( q1 ) );

        boost::weak_ptr<int> q4;

        BOOST_TEST( !p4.owner_before( q4 ) );
        BOOST_TEST( !q4.owner_before( p4 ) );

        BOOST_TEST( q1.owner_before( q4 ) || q4.owner_before( q1 ) );

        boost::weak_ptr<void> q5;

        BOOST_TEST( !q4.owner_before( q5 ) );
        BOOST_TEST( !q5.owner_before( q4 ) );

        boost::weak_ptr<void> q7( p7 );

        BOOST_TEST( !p1.owner_before( q7 ) );
        BOOST_TEST( !q7.owner_before( p1 ) );

        BOOST_TEST( !q1.owner_before( q7 ) );
        BOOST_TEST( !q7.owner_before( q1 ) );

        p1.reset();
        p2.reset();
        p3.reset();
        p7.reset();

        BOOST_TEST( q1.expired() );
        BOOST_TEST( q2.expired() );
        BOOST_TEST( q3.expired() );
        BOOST_TEST( q7.expired() );

        BOOST_TEST( !q1.owner_before( q2 ) );
        BOOST_TEST( !q2.owner_before( q1 ) );

        BOOST_TEST( !q1.owner_before( q7 ) );
        BOOST_TEST( !q7.owner_before( q1 ) );

        BOOST_TEST( q1.owner_before( q3 ) || q3.owner_before( q1 ) );

        BOOST_TEST( q1.owner_before( q4 ) || q4.owner_before( q1 ) );
    }

    return boost::report_errors();
}


text:
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
//    names, trademarks, service marks, or product names of the Licensor
//    and its affiliates, except as required to comply with Section 4(c) of
//    the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/pxr.h"
#include "pxr/usd/usd/schemaRegistry.h"
#include "pxr/usd/usd/primDefinition.h"

#include "pxr/usd/sdf/attributeSpec.h"
#include "pxr/usd/sdf/propertySpec.h"
#include "pxr/usd/sdf/relationshipSpec.h"

#include "pxr/base/tf/pyResultConversions.h"
#include "pxr/base/tf/pySingleton.h"

#include <boost/python.hpp>

using std::string;

using namespace boost::python;

PXR_NAMESPACE_USING_DIRECTIVE

static UsdPrimDefinition *
_WrapBuildComposedPrimDefinition(const UsdSchemaRegistry &self,
    const TfToken &primType, const TfTokenVector &appliedAPISchemas)
{
    return self.BuildComposedPrimDefinition(primType, appliedAPISchemas).release();
}

void wrapUsdSchemaRegistry()
{
    typedef UsdSchemaRegistry This;
    typedef TfWeakPtr<UsdSchemaRegistry> ThisPtr;

    class_<This, ThisPtr, boost::noncopyable>("SchemaRegistry", no_init)
        .def(TfPySingleton())

        .def("GetSchemaTypeName",
             (TfToken (This::*)(const TfType &) const)
                &This::GetSchemaTypeName,
             arg("schemaType"))

        .def("IsDisallowedField",
             &This::IsDisallowedField,
             (arg("fieldName")))
        .staticmethod("IsDisallowedField")

        .def("IsTyped",
             &This::IsTyped,
             (arg("primType")))
        .staticmethod("IsTyped")

        .def("IsConcrete",
             (bool (This::*)(const TfType &) const)
             &This::IsConcrete,
             (arg("primType")))
        .def("IsConcrete",
             (bool (This::*)(const TfToken &) const)
             &This::IsConcrete,
             (arg("primType")))

        .def("IsAppliedAPISchema",
             (bool (This::*)(const TfType &) const)
             &This::IsAppliedAPISchema,
             (arg("apiSchemaType")))
        .def("IsAppliedAPISchema",
             (bool (This::*)(const TfToken &) const)
             &This::IsAppliedAPISchema,
             (arg("apiSchemaType")))

        .def("IsMultipleApplyAPISchema",
             (bool (This::*)(const TfType &) const)
             &This::IsMultipleApplyAPISchema,
             (arg("apiSchemaType")))
        .def("IsMultipleApplyAPISchema",
             (bool (This::*)(const TfToken &) const)
             &This::IsMultipleApplyAPISchema,
             (arg("apiSchemaType")))

        .def("GetTypeFromName", &This::GetTypeFromName,
            (arg("typeName")))
        .staticmethod("GetTypeFromName")

        .def("FindConcretePrimDefinition",
             &This::FindConcretePrimDefinition,
             (arg("typeName")),
             return_internal_reference<>())

        .def("FindAppliedAPIPrimDefinition",
             &This::FindAppliedAPIPrimDefinition,
             (arg("typeName")),
             return_internal_reference<>())

        .def("GetEmptyPrimDefinition",
             &This::GetEmptyPrimDefinition,
             return_internal_reference<>())

        .def("BuildComposedPrimDefinition",
             &_WrapBuildComposedPrimDefinition,
             return_value_policy<manage_new_object>())
        ;
}

max_stars_repo_name: gomez-addams/USD

max_issues_repo_name: Yangxindao/USD

max_forks_repo_name: Yangxindao/USD


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

#include <boost/format.hpp>
#include "illegalCreateQs_r10b.h"
#include "globals.h"
#include "grpDefs.h"

namespace GrpQueues {

IllegalCreateQs_r10b::IllegalCreateQs_r10b(
    string grpName, string testName) :
    Test(grpName, testName, SPECREV_10b)
{
    // 63 chars allowed:     xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    mTestDesc.SetCompliance("revision 1.0b, section 5");
    mTestDesc.SetShort(     "Create admin Q's with CreateIOQ cmds.");
    // No string size limit for the long description
    mTestDesc.SetLong(
        "Issue CreateIOSQ and CreateIOCQ cmds, specify QID = 0 trying to "
        "create all admin Q's, expect status code = \"Invalid Q ID\". Also "
        "issue a legal Create IOSQ but specify CQID = 0 for the illegal "
        "association, also expect status code = \"Completion Q Invalid\".");
}

IllegalCreateQs_r10b::~IllegalCreateQs_r10b()
{
    ///////////////////////////////////////////////////////////////////////////
    // Allocations taken from the heap and not under the control of the
    // RsrcMngr need to be freed/deleted here.
    ///////////////////////////////////////////////////////////////////////////
}

IllegalCreateQs_r10b::
IllegalCreateQs_r10b(const IllegalCreateQs_r10b &other) : Test(other)
{
    ///////////////////////////////////////////////////////////////////////////
    // All pointers in this object must be NULL, never allow shallow or deep
    // copies, see Test::Clone() header comment.
    ///////////////////////////////////////////////////////////////////////////
}

IllegalCreateQs_r10b &
IllegalCreateQs_r10b::operator=(const IllegalCreateQs_r10b &other)
{
    ///////////////////////////////////////////////////////////////////////////
    // All pointers in this object must be NULL, never allow shallow or deep
    // copies, see Test::Clone() header comment.
    ///////////////////////////////////////////////////////////////////////////
    Test::operator=(other);
    return *this;
}

Test::RunType
IllegalCreateQs_r10b::RunnableCoreTest(bool preserve)
{
    ///////////////////////////////////////////////////////////////////////////
    // All code contained herein must never permanently modify the state or
    // configuration of the DUT. Permanence is defined as state or configuration
    // changes that will not be restored after a cold hard reset.
    ///////////////////////////////////////////////////////////////////////////

    preserve = preserve;    // Suppress compiler error/warning
    return RUN_TRUE;        // This test is never destructive
}

void
IllegalCreateQs_r10b::RunCoreTest()
{
    /** \verbatim
     * Assumptions:
     * 1) Test CreateResources_r10b has run prior.
     *  \endverbatim
     */

    // Lookup objs which were created in a prior test within group
    SharedACQPtr acq = CAST_TO_ACQ(gRsrcMngr->GetObj(ACQ_GROUP_ID))
    SharedASQPtr asq = CAST_TO_ASQ(gRsrcMngr->GetObj(ASQ_GROUP_ID))

    uint32_t numEntries = 2;
    uint8_t dword;
    uint32_t mask;
    uint32_t value;
    {
        LOG_NRM("Create IOCQ ID #%d but toxify its QID to 0", IOQ_ID);
        SharedIOCQPtr iocq = SharedIOCQPtr(new IOCQ(gDutFd));
        iocq->Init(IOQ_ID, numEntries, true, 0);

        LOG_NRM("Form a Create IOCQ cmd");
        SharedCreateIOCQPtr iocqCmd = SharedCreateIOCQPtr(new CreateIOCQ());
        iocqCmd->Init(iocq);

        dword = 10;
        mask = 0xFFFF;
        value = 0;
        SendToxicCmd(asq, acq, iocqCmd, dword, mask, value, CESTAT_INVALID_QID);
    }
    {
        LOG_NRM("Create IOSQ ID #%d but toxify its QID to 0", IOQ_ID);
        SharedIOSQPtr iosq = SharedIOSQPtr(new IOSQ(gDutFd));
        iosq->Init(IOQ_ID, numEntries, IOQ_ID, 0);

        LOG_NRM("Form a Create IOSQ cmd");
        SharedCreateIOSQPtr iosqCmd = SharedCreateIOSQPtr(new CreateIOSQ());
        iosqCmd->Init(iosq);

        dword = 10;
        mask = 0xFFFF;
        value = 0;
        SendToxicCmd(asq, acq, iosqCmd, dword, mask, value, CESTAT_INVALID_QID);
    }
    {
        LOG_NRM("Create IOSQ ID #%d but wrongly associate to ACQ", IOQ_ID);
        SharedIOSQPtr iosq = SharedIOSQPtr(new IOSQ(gDutFd));
        iosq->Init(IOQ_ID, numEntries, IOQ_ID, 0);

        LOG_NRM("Form a Create IOSQ cmd");
        SharedCreateIOSQPtr iosqCmd = SharedCreateIOSQPtr(new CreateIOSQ());
        iosqCmd->Init(iosq);

        dword = 11;
        mask = 0xFFFF0000;
        value = 0;
        SendToxicCmd(asq, acq, iosqCmd, dword, mask, value, CESTAT_CQ_INVALID);
    }
}

void
IllegalCreateQs_r10b::SendToxicCmd(SharedASQPtr asq, SharedACQPtr acq,
    SharedCmdPtr cmd, uint8_t dw, uint32_t mask, uint32_t val, CEStat status)
{
    uint16_t uniqueId;
    uint32_t isrCnt;
    uint32_t numCE;
    string work;

    LOG_NRM("Send the cmd to hdw via ASQ");
    asq->Send(cmd, uniqueId);

    work = str(boost::format("%s.pure.%d") % cmd->GetName().c_str() % uniqueId);
    asq->Dump(FileSystem::PrepDumpFile(mGrpName, mTestName, "asq"
        + cmd->GetName(), work), "Just B4 modifying, dump ASQ");

    ASQCmdToxify(asq, dw, mask, val);
    work = str(boost::format("%s.toxic.%d") % cmd->GetName().c_str() % uniqueId);
    asq->Dump(FileSystem::PrepDumpFile(mGrpName, mTestName, "asq", work),
        "Just B4 ringing doorbell, dump ASQ");

    asq->Ring();

    LOG_NRM("Wait for the CE to arrive in CQ %d", acq->GetQId());
    if (acq->ReapInquiryWaitSpecify(CALC_TIMEOUT_ms(1), 1, numCE, isrCnt)
        == false) {
        acq->Dump(FileSystem::PrepDumpFile(mGrpName, mTestName, "acq.fail"),
            "Dump Entire ACQ");
        asq->Dump(FileSystem::PrepDumpFile(mGrpName, mTestName, "asq.fail"),
            "Dump Entire ASQ");
        throw FrmwkEx(HERE, "Unable to see CEs for issued cmd");
    }

    work = str(boost::format("acq.%d") % uniqueId);
    IO::ReapCE(acq, 1, isrCnt, mGrpName, mTestName, work, status);
}

void
IllegalCreateQs_r10b::ASQCmdToxify(SharedASQPtr asq, uint8_t dw, uint32_t mask,
    uint32_t val)
{
    struct nvme_gen_sq asqMetrics = asq->GetQMetrics();
    struct backdoor_inject inject;

    inject.q_id = asq->GetQId();

    if (asqMetrics.tail_ptr_virt)
        inject.cmd_ptr = asqMetrics.tail_ptr_virt - 1;
    else
        inject.cmd_ptr = asq->GetNumEntries() - 1;

    inject.dword = dw;
    inject.value_mask = mask;
    inject.value = val;

    LOG_NRM("Inject toxic parameters: (qId, cmd_ptr, dword, mask, val) = "
        "(%d, %d, %d, %d, %d)", inject.q_id, inject.cmd_ptr, inject.dword,
        inject.value_mask, inject.value);

    asq->SetToxicCmdValue(inject);
}

}   // namespace

max_stars_repo_name: jackeichen/Gaozh

max_issues_repo_name: jackeichen/Gaozh

max_forks_repo_name: jackeichen/Gaozh


text:
#include <boost/test/unit_test.hpp>
#include <fc/log/logger.hpp>

#include <fc/container/flat.hpp>
#include <fc/io/raw.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/static_variant.hpp>
#include <fc/log/logger_config.hpp>

namespace fc { namespace test {

   struct item;
   inline bool operator == ( const item& a, const item& b );
   inline bool operator < ( const item& a, const item& b );

   struct item_wrapper
   {
      item_wrapper() {}
      item_wrapper(item&& it) { v.reserve(1); v.insert( it ); }
      boost::container::flat_set<struct item> v;
   };

   inline bool operator == ( const item_wrapper& a, const item_wrapper& b )
   { return ( std::tie( a.v ) == std::tie( b.v ) ); }
   inline bool operator < ( const item_wrapper& a, const item_wrapper& b )
   { return ( std::tie( a.v ) < std::tie( b.v ) ); }

   struct item
   {
      item(int32_t lvl = 0) : level(lvl) {}
      item(item_wrapper&& wp, int32_t lvl = 0) : level(lvl), w(wp) {}
      int32_t      level;
      item_wrapper w;
   };

   inline bool operator == ( const item& a, const item& b )
   { return ( std::tie( a.level, a.w ) == std::tie( b.level, b.w ) ); }
   inline bool operator < ( const item& a, const item& b )
   { return ( std::tie( a.level, a.w ) < std::tie( b.level, b.w ) ); }

} } // namespace fc::test

FC_REFLECT( fc::test::item_wrapper, (v) );
FC_REFLECT( fc::test::item, (level)(w) );

BOOST_AUTO_TEST_SUITE(fc_variant_and_log)

BOOST_AUTO_TEST_CASE( types_edge_cases_test )
{
   using namespace fc::test;

   class sv : public fc::static_variant<>
   {
   public:
       BOOST_ATTRIBUTE_UNUSED typedef fc::static_variant<>::tag_type tag_type;
   };

   BOOST_TEST_MESSAGE( "========== Test empty static_variant ==========" );

   BOOST_CHECK_THROW( fc::static_variant<>(), fc::assert_exception );

   BOOST_TEST_MESSAGE( "========== Test static_variant with tag_type ==========" );

   sv::tag_type init_value = 2;
   fc::static_variant< sv::tag_type, std::string, fc::variant > variant_with_tagtype(init_value);

   BOOST_CHECK_EQUAL( (int)variant_with_tagtype.count(), 3 );
   BOOST_CHECK_EQUAL( variant_with_tagtype.which(), 0 );

   sv::tag_type current_value = variant_with_tagtype.get<sv::tag_type>();
   BOOST_CHECK_EQUAL( current_value, init_value );
   BOOST_CHECK( variant_with_tagtype.get<sv::tag_type>() == init_value );

   for (sv::tag_type i = variant_with_tagtype.count(); i-->0;)
   {
      variant_with_tagtype.set_which(i);
      BOOST_CHECK_EQUAL(variant_with_tagtype.which(), i);
   }

   BOOST_TEST_MESSAGE( "========== Test static_variant with static_variant ==========" );

   using sv_double = fc::static_variant<double>;
   using sv_float = fc::static_variant<float>;
   fc::static_variant< sv_float, std::string, sv_double > variant;
   sv_float variant_float = 1.5f;
   variant = variant_float;
   BOOST_CHECK_EQUAL( variant.which(), 0 );
   BOOST_CHECK_EQUAL( variant.get<sv_float>().get<float>(), 1.5f );

   sv_double variant_double = 1.0;
   variant = variant_double;
   BOOST_CHECK_EQUAL( variant.which() , 2);
   BOOST_CHECK_EQUAL( variant.get<sv_double>().get<double>(), 1.0 );
}

BOOST_AUTO_TEST_CASE( nested_objects_test )
{ try {

   ilog( "Suppressing logging (but not disabled)" );
   fc::logging_config cfg;
   fc::logger_config dlc;
   dlc.name = "default";
   dlc.level = fc::log_level::debug;
   dlc.appenders.push_back("stderr");
   cfg.loggers.push_back( dlc );
   fc::configure_logging( cfg );

   auto create_nested_object = []( uint32_t level )
   {
      ilog( "Creating nested object with ${lv} level(s)", ("lv",level) );
      fc::test::item nested;
      for( uint32_t i = 1; i <= level; i++ )
      {
         if( i % 10 == 0 )
            ilog( "Creating level ${lv}", ("lv",i) );
         fc::test::item_wrapper wp( std::move(nested) );
         nested = fc::test::item( std::move(wp), i );
      }
      return nested;
   };

   for (int nested_loops = 0; nested_loops <= 100; ++nested_loops )
   {
      int nested_levels = nested_loops * 3 + 2;
      auto nested = create_nested_object( nested_loops );

      fc::variant v;

      BOOST_TEST_MESSAGE( "========== About to nested object convert to variant. ==========" );
      BOOST_CHECK_THROW( to_variant( nested, v, nested_levels ), fc::assert_exception );
      try{ try { try { try {
         to_variant( nested, v, nested_levels ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_LOG_AND_RETHROW( (nested) ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_AND_RETHROW( (nested) ); BOOST_FAIL( "Expected exception." );
      } FC_LOG_AND_RETHROW( ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_AND_LOG ( (nested) ); // CAPTURE_AND_LOG should never throw again

      to_variant( nested, v, nested_levels + 1 );

      BOOST_TEST_MESSAGE( "========== About to convert nested object from variant. ==========" );
      fc::test::item unpacked;
      BOOST_CHECK_THROW( from_variant( v, unpacked, nested_levels ), fc::assert_exception );
      try{ try { try { try {
         from_variant( v, unpacked, nested_levels ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_LOG_AND_RETHROW( (v) ); BOOST_FAIL( "Expected exception." );
      } FC_LOG_AND_RETHROW( ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_AND_RETHROW( (v) ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_AND_LOG ( (v) ); // CAPTURE_AND_LOG should never throw again

      from_variant( v, unpacked, nested_levels + 1 );

      BOOST_CHECK( unpacked == nested );

      // both log and dump should never throw
      BOOST_TEST_MESSAGE( "========== About to log obj. ==========" );
      ilog( "The obj is ${a}, variant is ${v}", ("a",nested)("v",v) );
      BOOST_TEST_MESSAGE( "========== About to dump obj. ==========" );
      idump( (nested)(v) );

      fc::static_variant<fc::test::item> sv( nested ), sv1;
      BOOST_TEST_MESSAGE( "========== About to convert static_variant to variant. ==========" );
      BOOST_CHECK_THROW( to_variant( sv, v, nested_levels + 1 ), fc::assert_exception );
      try{ try { try { try {
         to_variant( sv, v, nested_levels + 1 ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_AND_RETHROW( (sv) ); BOOST_FAIL( "Expected exception." );
      } FC_LOG_AND_RETHROW( ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_LOG_AND_RETHROW( (sv) ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_AND_LOG ( (sv) ); // CAPTURE_AND_LOG should never throw again

      to_variant( sv, v, nested_levels + 2 );

      BOOST_TEST_MESSAGE( "========== About to convert static_variant from variant. ==========" );
      BOOST_CHECK_THROW( from_variant( v, sv1, nested_levels + 1 ), fc::assert_exception );
      try{ try { try { try {
         from_variant( v, sv1, nested_levels + 1 ); BOOST_FAIL( "Expected exception." );
      } FC_LOG_AND_RETHROW( ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_AND_RETHROW( (v) ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_LOG_AND_RETHROW( (v) ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_AND_LOG ( (v) ); // CAPTURE_AND_LOG should never throw again

      from_variant( v, sv1, nested_levels + 2 );

      BOOST_CHECK( sv == sv1 );

      // both log and dump should never throw
      BOOST_TEST_MESSAGE( "========== About to log static_variant. ==========" );
      wlog( "The static_variant is ${a}, variant is $(v)", ("a",sv)("v",v) );
      BOOST_TEST_MESSAGE( "========== About to dump static_variant. ==========" );
      wdump( (sv)(v) );

      std::vector<fc::static_variant<fc::test::item>> vec(300), vec1;
      for( int i = 0; i < 300; i++ )
         vec.push_back(sv);
      BOOST_TEST_MESSAGE( "========== About to convert vector to variant. ==========" );
      BOOST_CHECK_THROW( to_variant( vec, v, nested_levels + 2 ), fc::assert_exception );
      try{ try { try { try {
         to_variant( vec, v, nested_levels + 2 ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_AND_RETHROW( (vec) ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_LOG_AND_RETHROW( (vec) ); BOOST_FAIL( "Expected exception." );
      } FC_LOG_AND_RETHROW( ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_AND_LOG ( (vec) ); // CAPTURE_AND_LOG should never throw again

      to_variant( vec, v, nested_levels + 3 );

      BOOST_TEST_MESSAGE( "========== About to convert vector from variant. ==========" );
      BOOST_CHECK_THROW( from_variant( v, vec1, nested_levels + 2 ), fc::assert_exception );
      try{ try { try { try {
         from_variant( v, vec1, nested_levels + 2 ); BOOST_FAIL( "Expected exception." );
      } FC_LOG_AND_RETHROW( ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_LOG_AND_RETHROW( (v) ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_AND_RETHROW( (v) ); BOOST_FAIL( "Expected exception." );
      } FC_CAPTURE_AND_LOG ( (v) ); // CAPTURE_AND_LOG should never throw again

      from_variant( v, vec1, nested_levels + 3 );

      BOOST_CHECK( vec == vec1 );

      // both log and dump should never throw
      BOOST_TEST_MESSAGE( "========== About to log vector. ==========" );
      elog( "The vector is ${a}, variant is ${v}", ("a",vec)("v",v) );
      BOOST_TEST_MESSAGE( "========== About to dump vector. ==========" );
      edump( (vec)(v) );

   }

   fc::configure_logging( fc::logging_config::default_config() );
   ilog( "End suppressing logging" );

} FC_CAPTURE_LOG_AND_RETHROW ( (0) ) }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: EDCBlockchain/blockchain


text:
/*
	Simple event queue inspired by asio::io_service, but without needing
	thread-unsafe reset.

	begin: Frank Hess <frank.hess@nist.gov>  2008-05-31
*/

//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#ifndef _POET_EVENT_QUEUE_HPP
#define _POET_EVENT_QUEUE_HPP

#include <boost/function.hpp>
#include <boost/thread/mutex.hpp>
#include <deque>
namespace poet
{
	namespace detail
	{
		class event_queue
		{
		public:
			typedef boost::function<void ()> event_type;
			std::size_t poll_one()
			{
				std::size_t count = 0;
				event_type event;
				{
					boost::unique_lock<boost::mutex> lock(_mutex);
					if(_queue.empty())
					{
						return count;
					}else
					{
						event = _queue.front();
						_queue.pop_front();
						++count;
					}
				}
				event();
				return count;
			}
			std::size_t poll()
			{
				std::size_t count = 0;
				while(poll_one() == 1) ++count;
				return count;
			}
			template<typename Event>
			void post(const Event &event)
			{
				boost::unique_lock<boost::mutex> lock(_mutex);
				_queue.push_back(event);
			}
		private:
			std::deque<event_type> _queue;
			boost::mutex _mutex;
		};
	}
}

#endif // _POET_EVENT_QUEUE_HPP

max_stars_repo_name: fmhess/libpoet

max_issues_repo_name: fmhess/libpoet

max_forks_repo_name: fmhess/libpoet


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

#include <string.h>
#include <boost/format.hpp>
#include "abortByReset_r10b.h"
#include "globals.h"
#include "grpDefs.h"
#include "../Utils/kernelAPI.h"
#include "../Utils/irq.h"
#include "../Utils/io.h"
#include "../Cmds/asyncEventReq.h"
#include "../Cmds/asyncEventReqDefs.h"
#include "../Cmds/getLogPage.h"

#define SQ0TBDL     0x1000

namespace GrpAdminAsyncCmd {

AbortByReset_r10b::AbortByReset_r10b(
    string grpName, string testName) :
    Test(grpName, testName, SPECREV_10b)
{
    // 63 chars allowed:     xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    mTestDesc.SetCompliance("revision 1.0b, section 5.2");
    mTestDesc.SetShort(     "Verify an async event is aborted by reset");
    // No string size limit for the long description
    mTestDesc.SetLong(
        "Reset ctrlr to cause a clearing of DUT state. Issue 1 async cmd. "
        "Delay 5 sec, verify no CE exists in ACQ. Reset ctrlr to cause a "
        "clearing of DUT state. Ring doorbell for IOSQ #1. Delay 5 sec, "
        "verify no CE exists in ACQ.");
}

AbortByReset_r10b::~AbortByReset_r10b()
{
    ///////////////////////////////////////////////////////////////////////////
    // Allocations taken from the heap and not under the control of the
    // RsrcMngr need to be freed/deleted here.
    ///////////////////////////////////////////////////////////////////////////
}

AbortByReset_r10b::
AbortByReset_r10b(const AbortByReset_r10b &other) : Test(other)
{
    ///////////////////////////////////////////////////////////////////////////
    // All pointers in this object must be NULL, never allow shallow or deep
    // copies, see Test::Clone() header comment.
    ///////////////////////////////////////////////////////////////////////////
}

AbortByReset_r10b &
AbortByReset_r10b::operator=(const AbortByReset_r10b &other)
{
    ///////////////////////////////////////////////////////////////////////////
    // All pointers in this object must be NULL, never allow shallow or deep
    // copies, see Test::Clone() header comment.
    ///////////////////////////////////////////////////////////////////////////
    Test::operator=(other);
    return *this;
}

Test::RunType
AbortByReset_r10b::RunnableCoreTest(bool preserve)
{
    ///////////////////////////////////////////////////////////////////////////
    // All code contained herein must never permanently modify the state or
    // configuration of the DUT. Permanence is defined as state or configuration
    // changes that will not be restored after a cold hard reset.
    ///////////////////////////////////////////////////////////////////////////

    // Choose to return one of these or create your own logic
    return ((preserve == true) ? RUN_FALSE : RUN_TRUE);   // Test is destructive

}

void
AbortByReset_r10b::RunCoreTest()
{
    /** \verbatim
     * Assumptions:
     * 1) none
     *  \endverbatim
     */
    uint32_t isrCount;
    uint32_t numCE;

    if (gCtrlrConfig->SetState(ST_DISABLE_COMPLETELY) == false)
        throw FrmwkEx(HERE);

    LOG_NRM("Create admin queues ACQ and ASQ for test lifetime");
    SharedACQPtr acq = SharedACQPtr(new ACQ(gDutFd));
    acq->Init(5);

    SharedASQPtr asq = SharedASQPtr(new ASQ(gDutFd));
    asq->Init(5);

    // All queues will use identical IRQ vector
    IRQ::SetAnySchemeSpecifyNum(1);

    gCtrlrConfig->SetCSS(CtrlrConfig::CSS_NVM_CMDSET);
    if (gCtrlrConfig->SetState(ST_ENABLE) == false)
        throw FrmwkEx(HERE);

    LOG_NRM("Issue 1 async cmd");
    SendAsyncEventRequests(asq, 1);

    LOG_NRM("Delay 5 sec");
    sleep(5);
    if (acq->ReapInquiryWaitSpecify(CALC_TIMEOUT_ms(1), 1, numCE, isrCount)
        == true) {
        acq->Dump(FileSystem::PrepDumpFile(mGrpName, mTestName, "acq.fail1"),
            "Dump Entire ACQ");
        throw FrmwkEx(HERE, "0 CE's expected in ACQ but found %d CE's", numCE);
    }

    LOG_NRM("Reset ctrlr to cause a clearing of DUT state");
    if (gCtrlrConfig->SetState(ST_DISABLE) == false)
        throw FrmwkEx(HERE);
    // All queues will use identical IRQ vector
    IRQ::SetAnySchemeSpecifyNum(1);

    gCtrlrConfig->SetCSS(CtrlrConfig::CSS_NVM_CMDSET);
    if (gCtrlrConfig->SetState(ST_ENABLE) == false)
        throw FrmwkEx(HERE);

    LOG_NRM("Ring doorbell for IOSQ #1");
    InvalidSQWriteDoorbell();
    sleep(5);

    LOG_NRM("verify no CE exists in ACQ");
    if (acq->ReapInquiryWaitSpecify(CALC_TIMEOUT_ms(1), 1, numCE, isrCount)
        == true) {
        acq->Dump(FileSystem::PrepDumpFile(mGrpName, mTestName, "acq.fail2"),
            "Dump Entire ACQ");
        throw FrmwkEx(HERE, "0 CE expected in ACQ but found %d CE's", numCE);
    }
}

void
AbortByReset_r10b::SendAsyncEventRequests(SharedASQPtr &asq, uint32_t nCmds)
{
    uint16_t uniqueId;
    string work;

    LOG_NRM("Create aync event request cmd");
    SharedAsyncEventReqPtr asyncEventReqCmd =
        SharedAsyncEventReqPtr(new AsyncEventReq());

    for (uint32_t i = 0; i < nCmds; i++) {
        LOG_NRM("Send the async event request cmd to hdw via ASQ");
        asq->Send(asyncEventReqCmd, uniqueId);
        work = str(boost::format("asyncEventReq.%d") % i);
        asq->Dump(FileSystem::PrepDumpFile(mGrpName, mTestName,
            "asq", work), "Before doorbell ring");
        asq->Ring();
    }
}

void
AbortByReset_r10b::InvalidSQWriteDoorbell()
{
    uint64_t value;
    if (gRegisters->Read((CtlSpc)CTLSPC_CAP, value) == false)
        throw FrmwkEx(HERE);

    value &= CAP_DSTRD;
    uint32_t capDstrd = value >> 32;
    uint32_t sq1Doorbell = SQ0TBDL + (2 * 4 << capDstrd);
    LOG_NRM("SQ 1 doorbell in controller space = 0x%X", sq1Doorbell);

    value = 0x1;
    if (gRegisters->Write(NVMEIO_BAR01, sizeof(uint32_t), sq1Doorbell,
        (uint8_t *)&value) == false)
          throw FrmwkEx(HERE);
}

}   // namespace


text:
/*
Copyright 2018 Glen Joseph Fernandes
(glenjofe@gmail.com)

Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#include <boost/config.hpp>
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
#include <boost/core/empty_value.hpp>
#include <boost/core/lightweight_test.hpp>

struct T1 { };

struct S1
    : boost::empty_value<T1, 0, true> { };

struct T2 {
    int value;
};

struct S2
    : boost::empty_value<T1, 0, true>
    , boost::empty_value<T2, 1, true> { };

struct S3
    : boost::empty_value<T1, 0, false>
    , boost::empty_value<T2, 1, true> { };

struct T3 { };

struct S4
    : boost::empty_value<T1, 0, true>
    , boost::empty_value<T3, 1, true> { };

struct S5
    : boost::empty_value<T1, 0, false>
    , boost::empty_value<T3, 1, false> { };

struct S6
    : boost::empty_value<T1, 0, true>
    , boost::empty_value<T2, 1, true>
    , boost::empty_value<T3, 2, true> { };

int main()
{
    BOOST_TEST(sizeof(S1) == sizeof(T1));
    BOOST_TEST(sizeof(S2) == sizeof(T2));
    BOOST_TEST(sizeof(S3) > sizeof(T2));
    BOOST_TEST(sizeof(S4) == sizeof(T1));
    BOOST_TEST(sizeof(S5) > sizeof(T1));
    BOOST_TEST(sizeof(S6) == sizeof(T2));
    return boost::report_errors();
}
#else
int main()
{
    return 0;
}
#endif


text:
#ifndef ASSOCIATIVE_EXCEPTION_HPP
#define ASSOCIATIVE_EXCEPTION_HPP

#include <exception>

#include <boost/format.hpp>

namespace associative
{

	class Exception : public std::exception
	{
	private:
		std::string message;

	public:
		Exception();
		Exception(const std::string& message);
		~Exception() throw();

		virtual const char* what() const throw();
		virtual std::string getMessage() const throw();
	};

	template<typename E = Exception, typename... Args>
	E formatException(const boost::basic_format<char>& format, Args... args)
	{
		return E(format.str(), args...);
	}

}

#endif

max_stars_repo_name: larsrh/associative

max_issues_repo_name: larsrh/associative

max_forks_repo_name: larsrh/associative


text:
////////////////////////////////////////////////////////////////////////////
// Name:         AreaMover.hpp
// Description:  A class that represents the area-move capabilities
//               of a piece that can make 3-step area moves
// Created:      08/29/2004 03:37:46 Eastern Daylight Time
// Last Updated: $Date: 2004/09/18 22:23:06 $
// Revision:     $Revision: 1.1 $
// Author:       John Weathers
// Email:        hotanguish@hotmail.com
// Copyright:    (c) 2004 John Weathers
////////////////////////////////////////////////////////////////////////////

#ifndef __AreaMover_HPP__
#define __AreaMover_HPP__

// STL header files
#include <vector>

// Boost header files
#include <boost/dynamic_bitset.hpp>

// mShogi header files
#include "common.hpp"

// Forward declarations
class Board;

class AreaMover
{
private:
   // ======================================================================
   // Construction and destruction
   // ======================================================================
   AreaMover(Board* board);

public:
   static AreaMover* GetInstance(Board* board);
   ~AreaMover();

   // ======================================================================
   // Operations
   // ======================================================================
   bool HasLegalPath(int start, int finish);

private:
   void InitAttackBitboards();
   void InitAreaPaths();
   void ShiftCenter(Bitboard& bitboard, int oldcenter, int newcenter);

   // ======================================================================
   // Data
   // ======================================================================
   int mWidth, mHeight;        // Dimensions of the board
   int mSize;                  // Size of the board
   Board* mpBoard;             // Pointer to the board

public:
   // Array of attack bitboards for calculating area moves
   Bitboard* mAttackBitboards;

   // Arrays of path bitboard patterns used to calculate
   // whether a path exists between two points
   std::vector<Bitboard>** mAreaPaths;

private:
   // ======================================================================
   // Static Data
   // ======================================================================
   static AreaMover* pInstance;
};

#endif


text:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
///////////////////////////////////////////////////////////////////////////////
//
//  Not a calculator anymore, right? :-)
//
//  [ JDG April 10, 2007 ]      spirit2
//  [ JDG February 18, 2011 ]   Pure attributes. No semantic actions.
//
///////////////////////////////////////////////////////////////////////////////

#include "function.hpp"
#include "skipper.hpp"
#include "vm.hpp"
#include "compiler.hpp"
#include <boost/lexical_cast.hpp>
#include <fstream>

///////////////////////////////////////////////////////////////////////////////
//  Main program
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
    char const* filename;
    if (argc > 1)
    {
        filename = argv[1];
    }
    else
    {
        std::cerr << "Error: No input file provided." << std::endl;
        return 1;
    }

    std::ifstream in(filename, std::ios_base::in);

    if (!in)
    {
        std::cerr << "Error: Could not open input file: "
            << filename << std::endl;
        return 1;
    }

    std::string source_code; // We will read the contents here.
    in.unsetf(std::ios::skipws); // No white space skipping!
    std::copy(
        std::istream_iterator<char>(in),
        std::istream_iterator<char>(),
        std::back_inserter(source_code));

    typedef std::string::const_iterator iterator_type;
    iterator_type iter = source_code.begin();
    iterator_type end = source_code.end();

    client::vmachine vm;                        // Our virtual machine
    client::ast::function_list ast;             // Our AST

    client::error_handler<iterator_type>
        error_handler(iter, end);               // Our error handler
    client::parser::function<iterator_type>
        function(error_handler);                // Our parser
    client::parser::skipper<iterator_type>
        skipper;                                // Our skipper
    client::code_gen::compiler
        compiler(error_handler);                // Our compiler

    bool success = phrase_parse(iter, end, +function, skipper, ast);

    std::cout << "-------------------------\n";

    if (success && iter == end)
    {
        if (compiler(ast))
        {
            boost::shared_ptr<client::code_gen::function>
                p  = compiler.find_function("main");
            if (!p)
                return 1;

            int nargs = argc-2;
            if (p->nargs() != nargs)
            {
                std::cerr << "Error: main function requires " << p->nargs() << " arguments." << std::endl;
                std::cerr << nargs << " supplied." << std::endl;
                return 1;
            }

            std::cout << "Success\n";
            std::cout << "-------------------------\n";
            std::cout << "Assembler----------------\n\n";
            compiler.print_assembler();

            // Push the arguments into our stack
            for (int i = 0; i < nargs; ++i)
                vm.get_stack()[i] = boost::lexical_cast<int>(argv[i+2]);

            // Call the interpreter
            int r = vm.execute(compiler.get_code());

            std::cout << "-------------------------\n";
            std::cout << "Result: " << r << std::endl;
            std::cout << "-------------------------\n\n";
        }
        else
        {
            std::cout << "Compile failure\n";
        }
    }
    else
    {
        std::cout << "Parse failure\n";
    }
    return 0;
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
/*
 * (C) Copyright 2016 Kurento (http://kurento.org/)
 *
 * 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.
 *
 */

#define BOOST_TEST_STATIC_LINK
#define BOOST_TEST_PROTECTED_VIRTUAL

#include <boost/test/included/unit_test.hpp>
#include <MediaPipelineImpl.hpp>
#include <objects/PlayerEndpointImpl.hpp>
#include <mutex>
#include <condition_variable>
#include <ModuleManager.hpp>
#include <MediaSet.hpp>

#include <cstdio>
#include <iostream>

using namespace kurento;
using namespace boost::unit_test;

boost::property_tree::ptree config;
std::string mediaPipelineId;
ModuleManager moduleManager;

#define EXPECTED_LEN 1.0
#define PLAYED_FILE "http://files.openvidu.io/video/format/small.webm"
#define TIME 15 * G_TIME_SPAN_SECOND

struct GF {
  GF();
  ~GF();
};

BOOST_GLOBAL_FIXTURE (GF);

GF::GF()
{
  boost::property_tree::ptree ac, audioCodecs, vc, videoCodecs;
  gst_init (nullptr, nullptr);

  moduleManager.loadModulesFromDirectories ("../../src/server:../../..");

  mediaPipelineId = moduleManager.getFactory ("MediaPipeline")->createObject (
                      config, "",
                      Json::Value() )->getId();
}

GF::~GF()
{
  MediaSet::deleteMediaSet();
}

static std::shared_ptr <PlayerEndpointImpl>
createPlayerEndpoint ()
{
  std::shared_ptr <kurento::MediaObjectImpl> playerEndpoint;
  Json::Value constructorParams;

  constructorParams ["mediaPipeline"] = mediaPipelineId;
  constructorParams ["uri"] = PLAYED_FILE;

  playerEndpoint = moduleManager.getFactory ("PlayerEndpoint")->createObject (
                     config, "",
                     constructorParams );

  return std::dynamic_pointer_cast <PlayerEndpointImpl> (playerEndpoint);
}

static void
releasePlayerEndpoint (std::shared_ptr<PlayerEndpointImpl> &ep)
{
  std::string id = ep->getId();

  ep.reset();
  MediaSet::getMediaSet ()->release (id);
}

static std::shared_ptr<MediaElementImpl> createTestSink()
{
  std::shared_ptr <MediaElementImpl> src = std::dynamic_pointer_cast
      <MediaElementImpl> (MediaSet::getMediaSet()->ref (new  MediaElementImpl (
                            boost::property_tree::ptree(),
                            MediaSet::getMediaSet()->getMediaObject (mediaPipelineId),
                            "dummysink") ) );

  g_object_set (src->getGstreamerElement(), "audio", TRUE, "video", TRUE, NULL);

  return std::dynamic_pointer_cast <MediaElementImpl> (src);
}

static void
releaseTestSink (std::shared_ptr<MediaElementImpl> &ep)
{
  std::string id = ep->getId();

  ep.reset();
  MediaSet::getMediaSet ()->release (id);
}

static void
eos_received ()
{
  std::shared_ptr <PlayerEndpointImpl> player = createPlayerEndpoint ();
  std::shared_ptr <MediaElementImpl> sink = createTestSink();
  GCond cond{};
  GMutex mutex{};
  bool eos = false;
  gint64 end_time;

  g_mutex_init (&mutex);
  g_cond_init (&cond);

  player->signalEndOfStream.connect ([&] (EndOfStream event) {
    std::cout << "EOS received" << std::endl;
    g_mutex_lock (&mutex);
    eos = true;
    g_cond_signal (&cond);
    g_mutex_unlock (&mutex);
  });

  std::dynamic_pointer_cast <MediaElementImpl> (player)->connect (sink);

  player->play ();
  end_time = g_get_monotonic_time () + TIME;

  g_mutex_lock (&mutex);

  while (!eos) {
    if (!g_cond_wait_until (&cond, &mutex, end_time) ) {
      g_mutex_unlock (&mutex);
      std::cout << "EOS NOT received" << std::endl;
      BOOST_CHECK (false);
      return;
    }
  }

  g_mutex_unlock (&mutex);

  releaseTestSink (sink);
  releasePlayerEndpoint (player);
  g_mutex_clear (&mutex);
  g_cond_clear (&cond);
}

static void
eos_received_with_no_accept_eos_sink ()
{
  std::shared_ptr <PlayerEndpointImpl> player = createPlayerEndpoint ();
  std::shared_ptr <MediaElementImpl> sink = createTestSink();
  GCond cond{};
  GMutex mutex{};
  bool eos = false;
  gint64 end_time;

  g_mutex_init (&mutex);
  g_cond_init (&cond);

  g_object_set (sink->getGstreamerElement(), "accept-eos", FALSE, NULL);

  player->signalEndOfStream.connect ([&] (EndOfStream event) {
    std::cout << "EOS received" << std::endl;
    g_mutex_lock (&mutex);
    eos = true;
    g_cond_signal (&cond);
    g_mutex_unlock (&mutex);
  });

  std::dynamic_pointer_cast <MediaElementImpl> (player)->connect (sink);

  player->play ();
  end_time = g_get_monotonic_time () + TIME;

  g_mutex_lock (&mutex);

  while (!eos) {
    if (!g_cond_wait_until (&cond, &mutex, end_time) ) {
      g_mutex_unlock (&mutex);
      std::cout << "EOS NOT received" << std::endl;
      BOOST_CHECK (false);
      return;
    }
  }

  g_mutex_unlock (&mutex);

  releaseTestSink (sink);
  releasePlayerEndpoint (player);
  g_mutex_clear (&mutex);
  g_cond_clear (&cond);
}

test_suite *
init_unit_test_suite ( int, char *[] )
{
  test_suite *test = BOOST_TEST_SUITE ( "PlayerEndpoint" );

  test->add (BOOST_TEST_CASE ( &eos_received ), 0, /* timeout */ 20);
  test->add (BOOST_TEST_CASE ( &eos_received_with_no_accept_eos_sink), 0,
             /* timeout */ 20);

  return test;
}

max_stars_repo_name: eaglexmw-gmail/kms-elements

max_issues_repo_name: eaglexmw-gmail/kms-elements

max_forks_repo_name: eaglexmw-gmail/kms-elements


text:
//
// Copyright (c) 2018 CNRS
//

#ifndef __pinocchio_math_ccpad_hpp__
#define __pinocchio_math_ccpad_hpp__

// Do not include this file directly.
// Copy and use directly the intructions from <cppad/example/cppad_eigen.hpp>
// to avoid redifinition of EIGEN_MATRIXBASE_PLUGIN for Eigen 3.3.0 and later
//#include <cppad/example/cppad_eigen.hpp>

#ifdef PINOCCHIO_CPPAD_REQUIRES_MATRIX_BASE_PLUGIN
#define EIGEN_MATRIXBASE_PLUGIN <cppad/example/eigen_plugin.hpp>
#endif

#if defined(PINOCCHIO_WITH_CPPADCG_SUPPORT) && defined(PINOCCHIO_WITH_CXX11_SUPPORT)
  #include "pinocchio/math/cppadcg.hpp" // already include <Eigen/Dense>
#else
  #include <cppad/cppad.hpp>
  #include <Eigen/Dense>
#endif

namespace Eigen
{
  namespace internal
  {
    // Specialization of Eigen::internal::cast_impl for CppAD input types
    template<typename Scalar>
    struct cast_impl<CppAD::AD<Scalar>,Scalar>
    {
#if EIGEN_VERSION_AT_LEAST(3,2,90)
      EIGEN_DEVICE_FUNC
#endif
      static inline Scalar run(const CppAD::AD<Scalar> & x)
      {
        return CppAD::Value(x);
      }
    };
  }
}

/// Source from #include <cppad/example/cppad_eigen.hpp>
namespace Eigen
{
  template <class Base> struct NumTraits< CppAD::AD<Base> >
  {  // type that corresponds to the real part of an AD<Base> value
    typedef CppAD::AD<Base>   Real;
    // type for AD<Base> operations that result in non-integer values
    typedef CppAD::AD<Base>   NonInteger;
    //  type to use for numeric literals such as "2" or "0.5".
    typedef CppAD::AD<Base>   Literal;
    // type for nested value inside an AD<Base> expression tree
    typedef CppAD::AD<Base>   Nested;

    enum {
      // does not support complex Base types
      IsComplex             = 0 ,
      // does not support integer Base types
      IsInteger             = 0 ,
      // only support signed Base types
      IsSigned              = 1 ,
      // must initialize an AD<Base> object
      RequireInitialization = 1 ,
      // computational cost of the corresponding operations
      ReadCost              = 1 ,
      AddCost               = 2 ,
      MulCost               = 2
    };

    // machine epsilon with type of real part of x
    // (use assumption that Base is not complex)
    static CppAD::AD<Base> epsilon(void)
    {  return CppAD::numeric_limits< CppAD::AD<Base> >::epsilon(); }

    // relaxed version of machine epsilon for comparison of different
    // operations that should result in the same value
    static CppAD::AD<Base> dummy_precision(void)
    {  return 100. *
      CppAD::numeric_limits< CppAD::AD<Base> >::epsilon();
    }

    // minimum normalized positive value
    static CppAD::AD<Base> lowest(void)
    {  return CppAD::numeric_limits< CppAD::AD<Base> >::min(); }

    // maximum finite value
    static CppAD::AD<Base> highest(void)
    {  return CppAD::numeric_limits< CppAD::AD<Base> >::max(); }

    // number of decimal digits that can be represented without change.
    static int digits10(void)
    {  return CppAD::numeric_limits< CppAD::AD<Base> >::digits10; }
  };
}

/// Source from #include <cppad/example/cppad_eigen.hpp>
namespace CppAD
{
  // functions that return references
  template <class Base> const AD<Base>& conj(const AD<Base>& x)
  {  return x; }
  template <class Base> const AD<Base>& real(const AD<Base>& x)
  {  return x; }

  // functions that return values (note abs is defined by cppad.hpp)
  template <class Base> AD<Base> imag(const AD<Base>& /*x*/)
  {  return CppAD::AD<Base>(0.); }
  template <class Base> AD<Base> abs2(const AD<Base>& x)
  {  return x * x; }
}

#endif // #ifndef __pinocchio_math_ccpad_hpp__

max_stars_repo_name: matthieuvigne/pinocchio

max_issues_repo_name: matthieuvigne/pinocchio

max_forks_repo_name: matthieuvigne/pinocchio


text:
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <model_based_shared_control/State.h>
#include <model_based_shared_control/Control.h>
#include "robotlib/dynamicalSystems/koopman/koopman_operator.hpp"
#include "robotlib/dynamicalSystems/koopman/basis_functions/linear_basis.hpp"
#include "robotlib/dynamicalSystems/koopman/basis_functions/nonlinear_basis.hpp"
#include <armadillo>

class HumanRobot {

public:

  // publishers and subscribers
  ros::Subscriber state_sub;
  ros::Subscriber shutdown_sub;
  bool has_initialized = false;

  // messages
  model_based_shared_control::State state;
  model_based_shared_control::Control control;

  // data vectors
  arma::vec current_state;
  arma::vec dataIn;
  arma::vec dataOut;
  arma::vec cdataIn;
  arma::vec hdataIn;
  arma::vec hdataOut;

  // Koopman models
  KoopmanOperator* linear_koopman_operator;
  KoopmanOperator* nonlinear_koopman_operator;

  HumanRobot(ros::Rate* loop_rate) {

    ros::NodeHandle nh;

    // set up subscribers
    state_sub = nh.subscribe("/state", 1, &HumanRobot::get_state, this);
    shutdown_sub = nh.subscribe("/shutdown", 1, &HumanRobot::get_shutdown, this);

    // set up data vectors
    dataIn = arma::zeros<arma::vec>(6);
    dataOut = arma::zeros<arma::vec>(6);
    cdataIn = arma::zeros<arma::vec>(2);
    hdataIn = arma::zeros<arma::vec>(2);
    hdataOut = arma::zeros<arma::vec>(2);
    current_state = arma::zeros<arma::vec>(6);

    // set up Linear Koopman
    linear_koopman_operator = new KoopmanOperator(new LinearBasisFunction());

    // set up Non Linear Koopman
    nonlinear_koopman_operator = new KoopmanOperator(new NonLinearBasisFunction());

  }

  void get_state(const model_based_shared_control::State::ConstPtr& msg) {
    if (has_initialized == false) {
      dataOut[0] = msg->x;
      dataOut[1] = msg->y;
      dataOut[2] = msg->theta;
      dataOut[3] = msg->x_dot;
      dataOut[4] = msg->y_dot;
      dataOut[5] = msg->theta_dot;
      hdataOut[0] = msg->u_1;
      hdataOut[1] = msg->u_2;
      has_initialized = true;
    } else {
       if (std::abs(dataOut[0] - msg->x) + std::abs(dataOut[1] - msg->y) < 0.3){
        dataIn = dataOut;
        hdataIn = hdataOut;
        dataOut[0] = msg->x;
        dataOut[1] = msg->y;
        dataOut[2] = msg->theta;
        dataOut[3] = msg->x_dot;
        dataOut[4] = msg->y_dot;
        dataOut[5] = msg->theta_dot;
        hdataOut[0] = msg->u_1;
        hdataOut[1] = msg->u_2;
        linear_koopman_operator->gradStep(dataIn, hdataIn, dataOut, hdataOut);
        nonlinear_koopman_operator->gradStep(dataIn, hdataIn, dataOut, hdataOut);
        current_state = dataOut;
      } else {
        has_initialized = false;
      }
		}
	}

  void get_shutdown(const std_msgs::String::ConstPtr& msg) {
    std::string filePath = msg->data;
    std::string linearFilePath = filePath + "-koopman-linear";
    std::string nonlinearFilePath = filePath + "-koopman-nonlinear";
    linear_koopman_operator->saveOperator(linearFilePath);
    nonlinear_koopman_operator->saveOperator(nonlinearFilePath);
  }

};

int main(int argc, char** argv) {
  ros::init(argc, argv,"human_robot");
  ros::NodeHandle nh;
  ros::Rate loop_rate(10);
  HumanRobot sys(&loop_rate);

  while (ros::ok()) {
    loop_rate.sleep();
    ros::spinOnce();
  }

  return 0;
}


text:
// Copyright (c) 2014-2018 Bauhaus-Universitaet Weimar
// This Software is distributed under the Modified BSD License, see license.txt.
//
// Virtual Reality and Visualization Research Group
// Faculty of Media, Bauhaus-Universitaet Weimar
// http://www.uni-weimar.de/medien/vr

#include "utils.h"
#include <lamure/ren/camera.h>

#include <memory>
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>

#include "management.h"

#include <GL/freeglut.h>

#include <lamure/types.h>

#include <lamure/ren/config.h>
#include <lamure/ren/model_database.h>
#include <lamure/ren/cut_database.h>
#include <lamure/ren/dataset.h>
#include <lamure/ren/policy.h>

#include <lamure/pvs/pvs_database.h>

#include <scm/core/math.h>

#include <boost/program_options.hpp>

void initialize_glut();

void glut_display();
void glut_resize(int w, int h);
void glut_mousefunc(int button, int state, int x, int y);
void glut_mousemotion(int x, int y);
void glut_idle();
void glut_keyboard(unsigned char key, int x, int y);
void glut_keyboard_release(unsigned char key, int x, int y);
void glut_specialfunc(int key, int x, int y);
void glut_specialfunc_release(int key, int x, int y);

void glut_timer(int value);
void glut_close();

std::vector<scm::math::mat4d> const parse_camera_session_file( std::string const& session_file_path ) {

    std::ifstream camera_session_file(session_file_path);

    std::string view_matrix_as_string;

    std::vector<scm::math::mat4d> read_view_matrices;

    while( std::getline(camera_session_file, view_matrix_as_string) ) {
        scm::math::mat4d curr_view_matrix;
        std::istringstream view_matrix_as_strstream(view_matrix_as_string);

        for(int matrix_element_idx = 0;
                matrix_element_idx < 16;
                ++matrix_element_idx) {
            view_matrix_as_strstream >> curr_view_matrix[matrix_element_idx];
        }

        read_view_matrices.push_back(curr_view_matrix);

    }

    //reverse vector in order to pop_back elements in correct order
    std::reverse(read_view_matrices.begin(), read_view_matrices.end());
    return read_view_matrices;
}

void initialize_glut(int argc, char** argv, uint32_t width, uint32_t height)
{
    glutInit(&argc, argv);
    glutInitContextVersion(4, 6);
    glutInitContextProfile(GLUT_CORE_PROFILE);

	glutSetOption(
        GLUT_ACTION_ON_WINDOW_CLOSE,
		GLUT_ACTION_GLUTMAINLOOP_RETURNS
		);

    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA | GLUT_ALPHA | GLUT_MULTISAMPLE);

    glutInitWindowPosition(400,300);
    glutInitWindowSize(width, height);

    int wh1 = glutCreateWindow("Point Renderer");

    glutSetWindow(wh1);

    glutReshapeFunc(glut_resize);
    glutDisplayFunc(glut_display);
    glutKeyboardFunc(glut_keyboard);
    glutKeyboardUpFunc(glut_keyboard_release);
    glutSpecialFunc(glut_specialfunc);
    glutSpecialUpFunc(glut_specialfunc_release);
    glutMouseFunc(glut_mousefunc);
    glutMotionFunc(glut_mousemotion);
    glutIdleFunc(glut_idle);
}

management* management_ = nullptr;
bool quality_measurement_mode_enabled_ = false;

char* get_cmd_option(char** begin, char** end, const std::string & option) {
    char** it = std::find(begin, end, option);
    if (it != end && ++it != end)
        return *it;
    return 0;
}

bool cmd_option_exists(char** begin, char** end, const std::string& option) {
    return std::find(begin, end, option) != end;
}

int main(int argc, char** argv)
{
    namespace po = boost::program_options;
    namespace fs = boost::filesystem;

    const std::string exec_name = (argc > 0) ? fs::basename(argv[0]) : "";
    scm::shared_ptr<scm::core> scm_core(new scm::core(1, argv));

    putenv((char *)"__GL_SYNC_TO_VBLANK=0");

    int window_width;
    int window_height;
    unsigned int main_memory_budget;
    unsigned int video_memory_budget ;
    unsigned int max_upload_budget;

    std::string resource_file_path = "";
    std::string measurement_file_path = "";
    bool measurement_file_interpolation = false;
    float measurement_interpolation_stepsize = 1.0f;

    std::string default_background_color_rgb_string = "0x000000";

    std::string pvs_file_path = "";
    bool pvs_culling = true;

    po::options_description desc("Usage: " + exec_name + " [OPTION]... INPUT\n\n"
                               "Allowed Options");
    desc.add_options()
      ("help", "print help message")
      ("width,w", po::value<int>(&window_width)->default_value(1920), "specify window width (default=1920)")
      ("height,h", po::value<int>(&window_height)->default_value(1080), "specify window height (default=1080)")
      ("resource-file,f", po::value<std::string>(&resource_file_path), "specify resource input-file")
      ("vram,v", po::value<unsigned>(&video_memory_budget)->default_value(2048), "specify graphics memory budget in MB (default=2048)")
      ("mem,m", po::value<unsigned>(&main_memory_budget)->default_value(4096), "specify main memory budget in MB (default=4096)")
      ("upload,u", po::value<unsigned>(&max_upload_budget)->default_value(64), "specify maximum video memory upload budget per frame in MB (default=64)")
      ("measurement-file", po::value<std::string>(&measurement_file_path)->default_value(""), "specify camera session for quality measurement_file (default = \"\")")
      ("measurement-interpolate", po::value<bool>(&measurement_file_interpolation)->default_value(false), "allow interpolation between measurement transformations (default=false)")
      ("measurement-stepsize", po::value<float>(&measurement_interpolation_stepsize)->default_value(1.0f), "if interpolation is activated, this will be the stepsize in spatial units between interpolation points")
      ("pvs-file,p", po::value<std::string>(&pvs_file_path), "specify potentially visible set file.")
      ("pvs-culling", po::value<bool>(&pvs_culling)->default_value(true), "pvs will optimize drawn level of detail, yet if pvs culling is set to true, potentially occluded geometry will not be renderer")
      ("bg-color", po::value<std::string>(&default_background_color_rgb_string), "specify the default background color as RGB in hexadecimal format. (default=0x000000)");
      ;

    po::positional_options_description p;
    po::variables_map vm;

    try {
      auto parsed_options = po::command_line_parser(argc, argv).options(desc).allow_unregistered().run();
      po::store(parsed_options, vm);
      po::notify(vm);

      std::vector<std::string> to_pass_further = po::collect_unrecognized(parsed_options.options, po::include_positional);
      bool no_input = !vm.count("input") && to_pass_further.empty();

      if (resource_file_path == "") {
        if (vm.count("help") || no_input)
        {
          std::cout << desc;
          return 0;
        }
      }

      // no explicit input -> use unknown options
      if (!vm.count("input") && resource_file_path == "")
      {
        resource_file_path = "auto_generated.rsc";
        std::fstream ofstr(resource_file_path, std::ios::out);
        if (ofstr.good())
        {
          for (auto argument : to_pass_further)
          {
            ofstr << argument << std::endl;
          }
        } else {
          throw std::runtime_error("Cannot open file");
        }
        ofstr.close();
      }

    } catch (std::exception& e) {
      std::cout << "Warning: No input file specified. \n" << desc;
      return 0;
    }

    // set min and max
    window_width        = std::max(std::min(window_width, 4096), 1);
    window_height       = std::max(std::min(window_height, 2160), 1);
    main_memory_budget  = std::max(int(main_memory_budget), 1);
    video_memory_budget = std::max(int(video_memory_budget), 1);
    max_upload_budget   = std::max(int(max_upload_budget), 64);

    std::string hex_string_prefix = "0x";
    //if the hex string starts with the proper prefix '0x', strip it first
    if( hex_string_prefix == default_background_color_rgb_string.substr(0, hex_string_prefix.size() ) ) {
        default_background_color_rgb_string = default_background_color_rgb_string.substr(hex_string_prefix.size());
    }

    std::transform(default_background_color_rgb_string.begin(), default_background_color_rgb_string.end(), default_background_color_rgb_string.begin(), ::tolower);

    // check if size of prefix removed hex string is what we expect and the digits are valid.
    if( (default_background_color_rgb_string.size() != 6) || (default_background_color_rgb_string.find_first_not_of("0123456789abcdef") != std::string::npos) ){
        std::cout << "Warning: The RGB hex string does not contain 6 hex digits.\nSetting it to 0x000000.\n";
        default_background_color_rgb_string = "000000";
    }

    float bg_rgb[3] = {0.0f, 0.0f, 0.0f};

    for( int color_channel_idx = 0; color_channel_idx < 3; ++color_channel_idx) {
      unsigned color_channel_string_offset = color_channel_idx * 2;

      int unnormalized_color =  strtoul( default_background_color_rgb_string.substr( color_channel_string_offset, 2).c_str() , NULL ,16);

      bg_rgb[color_channel_idx] = unnormalized_color / 255.0f;
    }

    initialize_glut(argc, argv, window_width, window_height);

    std::pair< std::vector<std::string>, std::vector<scm::math::mat4f> > model_attributes;
    std::set<lamure::model_t> visible_set;
    std::set<lamure::model_t> invisible_set;
    model_attributes = read_model_string(resource_file_path, &visible_set, &invisible_set);

    //std::string scene_name;
    //create_scene_name_from_vector(model_attributes.first, scene_name);
    std::vector<scm::math::mat4f> & model_transformations = model_attributes.second;
    std::vector<std::string> const& model_filenames = model_attributes.first;

    lamure::ren::policy* policy = lamure::ren::policy::get_instance();
    policy->set_max_upload_budget_in_mb(max_upload_budget); //8
    policy->set_render_budget_in_mb(video_memory_budget); //2048
    policy->set_out_of_core_budget_in_mb(main_memory_budget); //4096, 8192
    policy->set_window_width(window_width);
    policy->set_window_height(window_height);

    lamure::ren::model_database* database = lamure::ren::model_database::get_instance();

    std::vector<scm::math::mat4d> parsed_views = std::vector<scm::math::mat4d>();

    std::string measurement_filename = "";

    snapshot_session_descriptor measurement_descriptor;

    if( ! measurement_file_path.empty() ) {
      measurement_descriptor.recorded_view_vector_ = parse_camera_session_file(measurement_file_path);
      measurement_descriptor.snapshot_resolution_ = scm::math::vec2ui(window_width, window_height);
      size_t last_dot_in_filename_pos = measurement_file_path.find_last_of('.');
      size_t first_slash_before_filename_pos = measurement_file_path.find_last_of("/\\", last_dot_in_filename_pos);

      measurement_descriptor.session_filename_ = measurement_file_path.substr(first_slash_before_filename_pos+1, last_dot_in_filename_pos);
      quality_measurement_mode_enabled_ = true;
      measurement_descriptor.snapshot_session_enabled_ = true;
      glutFullScreenToggle();
    }

    management_ = new management(model_filenames, model_transformations, visible_set, invisible_set, measurement_descriptor);
    management_->interpolate_between_measurement_transforms(measurement_file_interpolation);
    management_->set_interpolation_step_size(measurement_interpolation_stepsize);
    management_->enable_culling(pvs_culling);

    management_->forward_background_color(bg_rgb[0], bg_rgb[1], bg_rgb[2]);

    // PVS basic setup. If no path is given, runtime access to the PVS will always return true (visible).
    if(pvs_file_path != "")
    {
        std::string pvs_grid_file_path = pvs_file_path;
        pvs_grid_file_path.resize(pvs_grid_file_path.length() - 3);
        pvs_grid_file_path = pvs_grid_file_path + "grid";

        lamure::pvs::pvs_database* pvs = lamure::pvs::pvs_database::get_instance();
        pvs->load_pvs_from_file(pvs_grid_file_path, pvs_file_path, false);
    }

    // Start rendering main loop.
    glutMainLoop();

    if (management_ != nullptr)
    {
        delete lamure::ren::cut_database::get_instance();
        delete lamure::ren::controller::get_instance();
        delete lamure::ren::model_database::get_instance();
        delete lamure::ren::policy::get_instance();
        delete lamure::ren::ooc_cache::get_instance();

    }

    return 0;
}

void glut_display()
{
    bool signaled_shutdown = false;
    if (management_ != nullptr)
    {
        signaled_shutdown = management_->MainLoop();
        glutSwapBuffers();
    }

    if(signaled_shutdown)
    {
        glutExit();
        exit(0);
    }
}

void glut_resize(int w, int h)
{
    if (management_ != nullptr)
    {
        management_->dispatchResize(w, h);
    }
}

void glut_mousefunc(int button, int state, int x, int y)
{
    if (management_ != nullptr)
    {
        management_->RegisterMousePresses(button, state, x, y);
    }
}

void glut_mousemotion(int x, int y)
{
    if (management_ != nullptr)
    {
        management_->update_trackball(x, y);
    }
}

void glut_idle()
{
    glutPostRedisplay();
}

void Cleanup()
{
    if (management_ != nullptr)
    {
        delete management_;
        management_ = nullptr;
        delete lamure::ren::cut_database::get_instance();
        delete lamure::ren::controller::get_instance();
        delete lamure::ren::model_database::get_instance();
        delete lamure::ren::policy::get_instance();
        delete lamure::ren::ooc_cache::get_instance();
    }
}

void glut_close()
{
    if (management_ != nullptr)
    {
        delete management_;
        management_ = nullptr;
        delete lamure::ren::cut_database::get_instance();
        delete lamure::ren::controller::get_instance();
        delete lamure::ren::model_database::get_instance();
        delete lamure::ren::policy::get_instance();
        delete lamure::ren::ooc_cache::get_instance();
    }
}

void glut_keyboard(unsigned char key, int x, int y)
{
    switch(key)
    {
        case 27:
            //Cleanup();
            glutExit();
            exit(0);
            break;
        case '.':
            if(!quality_measurement_mode_enabled_)
                glutFullScreenToggle();
            break;

        default:
            if (management_ != nullptr)
            {
                management_->dispatchKeyboardInput(key);
            }
            break;

    }
}

void glut_specialfunc(int key, int x, int y) {
  switch(key) {
    default:
        if (management_ != nullptr)
        {
            management_->dispatchSpecialInput(key);
        }
        break;

  }
}

void glut_specialfunc_release(int key, int x, int y) {
  switch(key) {
    default:
        if (management_ != nullptr)
        {
            management_->dispatchSpecialInputRelease(key);
        }
        break;

  }
}

void glut_keyboard_release(unsigned char key, int x, int y)
{

}

max_stars_repo_name: vrsys/lamure

max_issues_repo_name: vrsys/lamure

max_forks_repo_name: vrsys/lamure


text:
#ifndef __STF_RECORD_POOL_HPP__
#define __STF_RECORD_POOL_HPP__

#include <array>
#include <memory>

#include "boost_pool.hpp"
#define BOOST_POOL_NO_MT
#pragma push_macro("S1")
#undef S1
#include <boost/container/static_vector.hpp>
#pragma pop_macro("S1")
#undef BOOST_POOL_NO_MT
#include "util.hpp"

namespace stf {
    class STFIFstream;

    template<typename T>
    class TypeAwareSTFRecord;

    /**
     * \struct RecordDeleter
     * Functor struct used to delete records allocated by STFRecordPool
     */
    template<typename PoolType>
    struct RecordDeleter {
        /**
         * Deletes an STFRecord
         * \param rec STFRecord to delete
         */
        __attribute__((always_inline))
        inline void operator()(const STFRecord* rec) {
            PoolType::deleter(rec);
        }
    };

    /**
     * \class STFRecordPool
     *
     * Pool allocator for STFRecords and derived classes
     *
     * NOT thread-safe
     */
    class STFRecordPool {
        private:
            template<typename RecordType>
            class STFRecordCache {
                private:
                    using FuncType = void(*)(const RecordType*);

                    static constexpr size_t MAX_SIZE_ = 3072;
#ifdef DEBUG_CACHE
                    size_t num_insertions_ = 0;
                    size_t num_hits_ = 0;
                    mutable size_t num_misses_ = 0;
#endif
                    std::array<FuncType, descriptors::internal::NUM_DESCRIPTORS> deleters_;

                    std::array<boost::container::static_vector<RecordType*, MAX_SIZE_>,
                               descriptors::internal::NUM_DESCRIPTORS> cache_;

                    bool deleters_initialized_ = false;

                    ~STFRecordCache() {
#ifdef DEBUG_CACHE
                        std::cerr << "Insertions: " << num_insertions_ << std::endl
                                  << "Hits: " << num_hits_ << std::endl
                                  << "Misses: " << num_misses_ << std::endl;
#endif
                        for(size_t i = 0; i < cache_.size(); ++i) {
                            const auto deleter = getDeleter_(i);
#ifdef DEBUG_CACHE
                            auto& cache_entry = cache_[i];
                            std::cerr << "Cache entry: " << descriptors::internal::Descriptor(i) << std::endl
                                      << "Cache size: " << cache_entry.size() << std::endl;
                            for(auto& rec: cache_entry) {
#else
                            for(auto& rec: cache_[i]) {
#endif
                                deleter(rec);
                            }
                        }
                    }

                    __attribute__((always_inline))
                    inline auto getDeleter_(const size_t desc) const {
                        return deleters_[desc];
                    }

                    __attribute__((always_inline))
                    inline auto getDeleter_(const descriptors::internal::Descriptor desc) const {
                        return getDeleter_(static_cast<size_t>(desc));
                    }

                    __attribute__((always_inline))
                    inline auto getDeleter_(const RecordType* rec) const {
                        return getDeleter_(rec->getDescriptor());
                    }

                public:
                    __attribute__((always_inline))
                    inline static STFRecordCache& get() {
                        static STFRecordCache cache;
                        return cache;
                    }

                    __attribute__((always_inline))
                    inline bool add(const RecordType* rec) {
                        auto& cache_entry = cache_[static_cast<size_t>(rec->getDescriptor())];
#ifdef DEBUG_CACHE
                        ++num_insertions_;
#endif
                        if(STF_EXPECT_FALSE(cache_entry.size() == MAX_SIZE_)) {
#ifdef DEBUG_CACHE
                            ++num_misses_;
#endif
                            return false;
                        }
                        cache_entry.emplace_back(const_cast<RecordType*>(rec));
                        return true;
                    }

                    __attribute__((always_inline))
                    inline RecordType* pop(const descriptors::internal::Descriptor desc) {
                        auto& cache_entry = cache_[static_cast<size_t>(desc)];
                        if(STF_EXPECT_FALSE(cache_entry.empty())) {
                            return nullptr;
                        }

#ifdef DEBUG_CACHE
                        ++num_hits_;
#endif
                        const auto ptr = cache_entry.back();
                        cache_entry.pop_back();
                        return ptr;
                    }

                    __attribute__((always_inline))
                    inline void deleter(const RecordType* rec) {
                        getDeleter_(rec->getDescriptor())(rec);
                    }

                    __attribute__((always_inline))
                    inline void registerDeleter(const descriptors::internal::Descriptor desc, const FuncType func) {
                        deleters_[static_cast<size_t>(desc)] = func;
                    }
            };

            /**
             * \typedef PoolAllocator
             *
             * Pool allocator used for STFRecords and derived classes
             */
            template<typename RecordType>
            using PoolAllocator = boost::fast_pool_allocator<RecordType>;

            /**
             * Gets the pool allocator for the specified record type
             */
            template<typename RecordType>
            __attribute__((always_inline))
            static inline PoolAllocator<RecordType>& getPool_() {
                static thread_local PoolAllocator<RecordType> pool;
                return pool;
            }

            /**
             * Constructs a record of the specified type, returning it as another type
             * \param args Arguments to pass to record constructor
             */
            template<typename ReturnType, typename RecordType, typename ... Args>
            __attribute__((always_inline))
            static inline typename std::enable_if<sizeof...(Args) != 1 || !type_utils::are_same<STFIFstream, std::remove_reference_t<Args>...>::value, ReturnType>::type
            construct_(Args&&... args) {
                auto& pool = getPool_<RecordType>();
                auto ptr = pool.allocate();
                stf_assert(ptr, "Failed to allocate new record from pool");
                pool.construct(ptr, std::forward<Args>(args)...);
                return ReturnType(ptr);
            }

            /**
             * Constructs a record of the specified type, returning it as another type
             * \param args Arguments to pass to record constructor
             */
            template<typename ReturnType, typename RecordType, typename ... Args>
            __attribute__((always_inline))
            static inline typename std::enable_if<sizeof...(Args) == 1 && type_utils::are_same<STFIFstream, std::remove_reference_t<Args>...>::value, ReturnType>::type
            construct_(Args&&... args) {
                auto ptr = STFRecordCache<STFRecord>::get().pop(TypeAwareSTFRecord<RecordType>::getTypeDescriptor());
                if(STF_EXPECT_FALSE(!ptr)) {
                    auto& pool = getPool_<RecordType>();
                    auto new_ptr = pool.allocate();
                    stf_assert(new_ptr, "Failed to allocate new record from pool");
                    pool.construct(new_ptr, std::forward<Args>(args)...);
                    ptr = new_ptr;
                }
                else {
                    static_cast<RecordType*>(ptr)->unpack_impl(std::forward<Args>(args)...);
                }
                return ReturnType(ptr);
            }

            template<typename RecordType>
            __attribute__((always_inline))
            static inline void deleter_(const STFRecord* rec) {
                const auto ptr = const_cast<RecordType*>(static_cast<const RecordType*>(rec));
                auto& pool = getPool_<RecordType>();
                pool.destroy(ptr);
                pool.deallocate(ptr);
            }

        public:
            /**
             * Type-specific deleter function
             * \param rec Record to delete
             */
            __attribute__((always_inline))
            static inline void deleter(const STFRecord* rec) {
                if(STF_EXPECT_FALSE(!rec)) {
                    return;
                }

                if(auto& cache = STFRecordCache<STFRecord>::get(); STF_EXPECT_FALSE(!cache.add(rec))) {
                    cache.deleter(rec);
                }
            }

            /**
             * Constructs a record of the specified type, returning it as an STFRecordConstUniqueHandle
             * \param args Arguments to pass to record constructor
             */
            template<typename RecordType, typename ... Args>
            __attribute__((always_inline))
            static inline std::unique_ptr<const STFRecord, RecordDeleter<STFRecordPool>> construct(Args&&... args) {
                return construct_<std::unique_ptr<const STFRecord, RecordDeleter<STFRecordPool>>, RecordType, Args...>(args...);
            }

            /**
             * Constructs a record of the specified type, returning it as a UniqueRecordHandle
             * \param args Arguments to pass to record constructor
             */
            template<typename RecordType, typename ... Args>
            __attribute__((always_inline))
            static inline std::unique_ptr<RecordType, RecordDeleter<STFRecordPool>> make(Args&&... args) {
                return construct_<std::unique_ptr<RecordType, RecordDeleter<STFRecordPool>>, RecordType, Args...>(args...);
            }

            /**
             * Registers a deleter method in the STFRecordCache for a particular record type
             * \param desc Descriptor for the record type being registered
             */
            template<typename RecordType>
            __attribute__((always_inline))
            static inline void registerDeleter(const descriptors::internal::Descriptor desc) {
                STFRecordCache<STFRecord>::get().registerDeleter(desc, &STFRecordPool::deleter_<RecordType>);
            }
    };

} // end namespace stf

#endif