text:
/*
 Copyright (C) 2016 Quaternion Risk Management Ltd
 All rights reserved.

 This file is part of ORE, a free-software/open-source library
 for transparent pricing and risk analysis - http://opensourcerisk.org

 ORE is free software: you can redistribute it and/or modify it
 under the terms of the Modified BSD License.  You should have received a
 copy of the license along with this program.
 The license is also available online at <http://opensourcerisk.org>

 This program is distributed on the basis that it will form a useful
 contribution to risk analytics and model standardisation, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/

#include "toplevelfixture.hpp"
#include <boost/test/unit_test.hpp>
#include <ql/time/calendar.hpp>
#include <ql/time/calendars/austria.hpp>
#include <qle/calendars/belgium.hpp>
#include <qle/calendars/chile.hpp>
#include <qle/calendars/colombia.hpp>
#include <qle/calendars/france.hpp>
#include <qle/calendars/israel.hpp>
#include <qle/calendars/luxembourg.hpp>
#include <qle/calendars/malaysia.hpp>
#include <qle/calendars/netherlands.hpp>
#include <qle/calendars/peru.hpp>
#include <qle/calendars/philippines.hpp>
#include <qle/calendars/spain.hpp>
#include <qle/calendars/thailand.hpp>

using namespace QuantLib;
using namespace QuantExt;
using namespace boost::unit_test_framework;
using namespace std;

namespace check {

void checkCalendars(const std::vector<Date>& expectedHolidays, const std::vector<Date>& testHolidays) {

    for (Size i = 0; i < expectedHolidays.size(); i++) {
        if (testHolidays[i] != expectedHolidays[i])
            BOOST_FAIL("expected holiday was " << expectedHolidays[i] << " while calculated holiday is "
                                               << testHolidays[i]);
    }
}
} // namespace check

BOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)

BOOST_AUTO_TEST_SUITE(CalendarsTest)

BOOST_AUTO_TEST_CASE(testPeruvianCalendar) {

    BOOST_TEST_MESSAGE("Testing Peruvian holiday list");

    std::vector<Date> expectedHolidays;

    expectedHolidays.push_back(Date(1, January, 2018));
    expectedHolidays.push_back(Date(29, March, 2018));
    expectedHolidays.push_back(Date(30, March, 2018));
    expectedHolidays.push_back(Date(1, May, 2018));
    expectedHolidays.push_back(Date(29, June, 2018));
    expectedHolidays.push_back(Date(27, July, 2018));
    expectedHolidays.push_back(Date(30, August, 2018));
    expectedHolidays.push_back(Date(31, August, 2018));
    expectedHolidays.push_back(Date(8, October, 2018));
    expectedHolidays.push_back(Date(1, November, 2018));
    expectedHolidays.push_back(Date(2, November, 2018));
    expectedHolidays.push_back(Date(25, December, 2018));

    Calendar c = Peru();

    std::vector<Date> hol = c.holidayList(Date(1, January, 2018), Date(31, December, 2018));

    BOOST_CHECK(hol.size() == expectedHolidays.size());

    check::checkCalendars(expectedHolidays, hol);
}

BOOST_AUTO_TEST_CASE(testColombianCalendar) {

    BOOST_TEST_MESSAGE("Testing Colombian holiday list");

    std::vector<Date> expectedHolidays;

    expectedHolidays.push_back(Date(1, January, 2018));
    expectedHolidays.push_back(Date(8, January, 2018));
    expectedHolidays.push_back(Date(19, March, 2018));
    expectedHolidays.push_back(Date(29, March, 2018));
    expectedHolidays.push_back(Date(30, March, 2018));
    expectedHolidays.push_back(Date(1, May, 2018));
    expectedHolidays.push_back(Date(14, May, 2018));
    expectedHolidays.push_back(Date(4, June, 2018));
    expectedHolidays.push_back(Date(11, June, 2018));
    expectedHolidays.push_back(Date(2, July, 2018));
    expectedHolidays.push_back(Date(20, July, 2018));
    expectedHolidays.push_back(Date(7, August, 2018));
    expectedHolidays.push_back(Date(20, August, 2018));
    expectedHolidays.push_back(Date(15, October, 2018));
    expectedHolidays.push_back(Date(5, November, 2018));
    expectedHolidays.push_back(Date(12, November, 2018));
    expectedHolidays.push_back(Date(25, December, 2018));

    Calendar c = Colombia();

    std::vector<Date> hol = c.holidayList(Date(1, January, 2018), Date(31, December, 2018));

    BOOST_CHECK(hol.size() == expectedHolidays.size());

    check::checkCalendars(expectedHolidays, hol);
}

BOOST_AUTO_TEST_CASE(testPhilippineCalendar) {

    BOOST_TEST_MESSAGE("Testing Philippine holiday list");

    std::vector<Date> expectedHolidays;

    expectedHolidays.push_back(Date(1, January, 2018));
    expectedHolidays.push_back(Date(2, January, 2018));
    expectedHolidays.push_back(Date(29, March, 2018));
    expectedHolidays.push_back(Date(30, March, 2018));
    expectedHolidays.push_back(Date(9, April, 2018));
    expectedHolidays.push_back(Date(1, May, 2018));
    expectedHolidays.push_back(Date(12, June, 2018));
    expectedHolidays.push_back(Date(21, August, 2018));
    expectedHolidays.push_back(Date(27, August, 2018));
    expectedHolidays.push_back(Date(1, November, 2018));
    expectedHolidays.push_back(Date(30, November, 2018));
    expectedHolidays.push_back(Date(25, December, 2018));
    expectedHolidays.push_back(Date(31, December, 2018));

    Calendar c = Philippines();

    std::vector<Date> hol = c.holidayList(Date(1, January, 2018), Date(31, December, 2018));

    check::checkCalendars(expectedHolidays, hol);
}

BOOST_AUTO_TEST_CASE(testThaiCalendar) {

    BOOST_TEST_MESSAGE("Testing Thai holiday list");

    std::vector<Date> expectedHolidays;

    expectedHolidays.push_back(Date(1, January, 2018));
    expectedHolidays.push_back(Date(2, January, 2018));
    expectedHolidays.push_back(Date(6, April, 2018));
    expectedHolidays.push_back(Date(13, April, 2018));
    expectedHolidays.push_back(Date(16, April, 2018));
    expectedHolidays.push_back(Date(1, May, 2018));
    expectedHolidays.push_back(Date(30, July, 2018));
    expectedHolidays.push_back(Date(13, August, 2018));
    expectedHolidays.push_back(Date(15, October, 2018));
    expectedHolidays.push_back(Date(23, October, 2018));
    expectedHolidays.push_back(Date(5, December, 2018));
    expectedHolidays.push_back(Date(10, December, 2018));
    expectedHolidays.push_back(Date(31, December, 2018));

    Calendar c = Thailand();

    std::vector<Date> hol = c.holidayList(Date(1, January, 2018), Date(31, December, 2018));

    BOOST_CHECK(hol.size() == expectedHolidays.size());

    check::checkCalendars(expectedHolidays, hol);
}

BOOST_AUTO_TEST_CASE(testMalaysianCalendar) {

    BOOST_TEST_MESSAGE("Testing Malaysian holiday list");

    std::vector<Date> expectedHolidays;

    expectedHolidays.push_back(Date(1, January, 2018));
    expectedHolidays.push_back(Date(1, February, 2018));
    expectedHolidays.push_back(Date(1, May, 2018));
    expectedHolidays.push_back(Date(31, August, 2018));
    expectedHolidays.push_back(Date(17, September, 2018));
    expectedHolidays.push_back(Date(25, December, 2018));

    Calendar c = Malaysia();

    std::vector<Date> hol = c.holidayList(Date(1, January, 2018), Date(31, December, 2018));

    BOOST_CHECK(hol.size() == expectedHolidays.size());

    check::checkCalendars(expectedHolidays, hol);
}

BOOST_AUTO_TEST_CASE(testChileanCalendar) {

    BOOST_TEST_MESSAGE("Testing Chilean holiday list");

    std::vector<Date> expectedHolidays;

    expectedHolidays.push_back(Date(1, January, 2018));
    expectedHolidays.push_back(Date(30, March, 2018));
    expectedHolidays.push_back(Date(1, May, 2018));
    expectedHolidays.push_back(Date(21, May, 2018));
    expectedHolidays.push_back(Date(16, July, 2018));
    expectedHolidays.push_back(Date(15, August, 2018));
    expectedHolidays.push_back(Date(1, November, 2018));
    expectedHolidays.push_back(Date(25, December, 2018));

    Calendar c = Chile();

    std::vector<Date> hol = c.holidayList(Date(1, January, 2018), Date(31, December, 2018));

    BOOST_CHECK(hol.size() == expectedHolidays.size());

    check::checkCalendars(expectedHolidays, hol);
}

BOOST_AUTO_TEST_CASE(testNetherlandianCalendar) {

    BOOST_TEST_MESSAGE("Testing Netherlandian holiday list");

    std::vector<Date> expectedHolidays;

    expectedHolidays.push_back(Date(1, January, 2018));
    expectedHolidays.push_back(Date(30, March, 2018));
    expectedHolidays.push_back(Date(2, April, 2018));
    expectedHolidays.push_back(Date(27, April, 2018));
    expectedHolidays.push_back(Date(10, May, 2018));
    expectedHolidays.push_back(Date(21, May, 2018));
    expectedHolidays.push_back(Date(25, December, 2018));
    expectedHolidays.push_back(Date(26, December, 2018));

    Calendar c = Netherlands();

    std::vector<Date> hol = c.holidayList(Date(1, January, 2018), Date(31, December, 2018));

    BOOST_CHECK(hol.size() == expectedHolidays.size());

    check::checkCalendars(expectedHolidays, hol);
}

BOOST_AUTO_TEST_CASE(testFrenchCalendar) {

    BOOST_TEST_MESSAGE("Testing French holiday list");

    std::vector<Date> expectedHolidays;

    expectedHolidays.push_back(Date(1, January, 2018));
    expectedHolidays.push_back(Date(30, March, 2018));
    expectedHolidays.push_back(Date(2, April, 2018));
    expectedHolidays.push_back(Date(1, May, 2018));
    expectedHolidays.push_back(Date(8, May, 2018));
    expectedHolidays.push_back(Date(10, May, 2018));
    expectedHolidays.push_back(Date(21, May, 2018));
    expectedHolidays.push_back(Date(15, August, 2018));
    expectedHolidays.push_back(Date(1, November, 2018));
    expectedHolidays.push_back(Date(25, December, 2018));
    expectedHolidays.push_back(Date(26, December, 2018));

    Calendar c = France();

    std::vector<Date> hol = c.holidayList(Date(1, January, 2018), Date(31, December, 2018));

    BOOST_CHECK(hol.size() == expectedHolidays.size());

    check::checkCalendars(expectedHolidays, hol);
}

BOOST_AUTO_TEST_CASE(testIsraelTelbor) {

    BOOST_TEST_MESSAGE("Testing Israel Telbor standard weekends");

    Calendar c = QuantExt::Israel(QuantExt::Israel::Telbor);

    BOOST_CHECK(!c.isWeekend(Friday));
    BOOST_CHECK(c.isWeekend(Saturday));
    BOOST_CHECK(c.isWeekend(Sunday));
}

BOOST_AUTO_TEST_CASE(testIsraelTelAviv) {

    BOOST_TEST_MESSAGE("Testing Israel TelAviv weekends");

    Calendar c = QuantExt::Israel(QuantExt::Israel::Settlement);

    BOOST_CHECK(c.isWeekend(Friday));
    BOOST_CHECK(c.isWeekend(Saturday));
    BOOST_CHECK(!c.isWeekend(Sunday));
}

BOOST_AUTO_TEST_CASE(testAustrianCalendar) {

    BOOST_TEST_MESSAGE("Testing Austrian holiday list");

    std::vector<Date> expectedHolidays;

    expectedHolidays.push_back(Date(1, January, 2020));
    expectedHolidays.push_back(Date(6, January, 2020));
    expectedHolidays.push_back(Date(13, April, 2020));
    expectedHolidays.push_back(Date(1, May, 2020));
    expectedHolidays.push_back(Date(21, May, 2020));
    expectedHolidays.push_back(Date(1, June, 2020));
    expectedHolidays.push_back(Date(11, June, 2020));
    // expectedHolidays.push_back(Date(15, August, 2020)); //Saturday
    expectedHolidays.push_back(Date(26, October, 2020));
    // expectedHolidays.push_back(Date(1, November, 2020)); //Sunday
    expectedHolidays.push_back(Date(8, December, 2020));
    expectedHolidays.push_back(Date(25, December, 2020));
    // expectedHolidays.push_back(Date(26, December, 2020)); //Saturday

    Calendar c = Austria();

    std::vector<Date> hol = c.holidayList(Date(1, January, 2020), Date(31, December, 2020));

    BOOST_CHECK(hol.size() == expectedHolidays.size());

    check::checkCalendars(expectedHolidays, hol);
}

BOOST_AUTO_TEST_CASE(testSpanishCalendar) {

    BOOST_TEST_MESSAGE("Testing Spanish holiday list");

    std::vector<Date> expectedHolidays;

    expectedHolidays.push_back(Date(1, January, 2020));
    expectedHolidays.push_back(Date(6, January, 2020));
    expectedHolidays.push_back(Date(10, April, 2020));
    expectedHolidays.push_back(Date(1, May, 2020));
    // expectedHolidays.push_back(Date(15, August, 2020)); //Saturday
    expectedHolidays.push_back(Date(12, October, 2020));
    // expectedHolidays.push_back(Date(1, November, 2020)); //Sunday
    // expectedHolidays.push_back(Date(6, December, 2020));  //Sunday
    expectedHolidays.push_back(Date(8, December, 2020));
    expectedHolidays.push_back(Date(25, December, 2020));

    Calendar c = Spain();

    std::vector<Date> hol = c.holidayList(Date(1, January, 2020), Date(31, December, 2020));

    BOOST_CHECK(hol.size() == expectedHolidays.size());

    check::checkCalendars(expectedHolidays, hol);
}

BOOST_AUTO_TEST_CASE(testLuxembourgianCalendar) {

    BOOST_TEST_MESSAGE("Testing Luxembourgian holiday list");

    std::vector<Date> expectedHolidays;

    expectedHolidays.push_back(Date(1, January, 2020));
    expectedHolidays.push_back(Date(13, April, 2020));
    expectedHolidays.push_back(Date(1, May, 2020));
    // expectedHolidays.push_back(Date(9, May, 2020)); //Saturday
    expectedHolidays.push_back(Date(21, May, 2020));
    expectedHolidays.push_back(Date(1, June, 2020));
    expectedHolidays.push_back(Date(23, June, 2020));
    // expectedHolidays.push_back(Date(15, August, 2020)); //Saturday
    // expectedHolidays.push_back(Date(1, November, 2020)); //Sunday
    expectedHolidays.push_back(Date(25, December, 2020));
    // expectedHolidays.push_back(Date(26, December, 2020)); //Saturday

    Calendar c = Luxembourg();

    std::vector<Date> hol = c.holidayList(Date(1, January, 2020), Date(31, December, 2020));

    BOOST_CHECK(hol.size() == expectedHolidays.size());

    check::checkCalendars(expectedHolidays, hol);
}

BOOST_AUTO_TEST_CASE(testBelgianCalendar) {

    BOOST_TEST_MESSAGE("Testing Belgian holiday list");

    std::vector<Date> expectedHolidays;

    expectedHolidays.push_back(Date(1, January, 2020));
    // expectedHolidays.push_back(Date(12, April, 2020)); //Sunday
    expectedHolidays.push_back(Date(13, April, 2020));
    expectedHolidays.push_back(Date(1, May, 2020));
    expectedHolidays.push_back(Date(21, May, 2020));
    // expectedHolidays.push_back(Date(31, May, 2020)); //Sunday
    expectedHolidays.push_back(Date(1, June, 2020));
    expectedHolidays.push_back(Date(21, July, 2020));
    // expectedHolidays.push_back(Date(15, August, 2020)); //Saturday
    // expectedHolidays.push_back(Date(1, November, 2020)); //Sunday
    expectedHolidays.push_back(Date(11, November, 2020));
    expectedHolidays.push_back(Date(25, December, 2020));

    Calendar c = Belgium();

    std::vector<Date> hol = c.holidayList(Date(1, January, 2020), Date(31, December, 2020));

    BOOST_CHECK(hol.size() == expectedHolidays.size());

    check::checkCalendars(expectedHolidays, hol);
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: nvolfango/Engine

max_issues_repo_name: zhangjiayin/Engine

max_forks_repo_name: zhangjiayin/Engine


text:
#include <EigenFaceMaskedArray.h>
#include <EigenFace.h>
#include <EigenFaceData.h>

#include <QByteArray>
#include <QBuffer>
#include <QDomDocument>
#include <QDomElement>
#include <QFile>
#include <QIODevice>
#include <QString>
#include <QStringList>
#include <QVector>

#include <Return.h>

Return EigenFaceMaskedArray::readXmlFile(const QString & fileName,
											   const QString & tagName)
{
	QString errMsg;
	int errLine, errCol;
	QDomDocument doc;

	QFile file(fileName);
	if ( ! file.open(QIODevice::ReadOnly))
		return Return::qfileError(file);
	if ( ! doc.setContent(&file, &errMsg, &errLine, &errCol))
		return Return(Return::ReturnXmlParse, fileName, errMsg, errLine, errCol);

	QDomElement de = doc.firstChildElement(tagName);
	if (de.isNull())
		return Return(Return::ReturnXmlParse, fileName,
				"Null " + EigenFaceData::bitMaskTagName + "element");

	return read(de);
}
Return EigenFaceMaskedArray::read(const QDomElement & de)
{
	clear();
	Id = de.attribute("Id").toInt();
	int n = de.attribute("Count").toInt();
	if ( ! n)
		return Return(Return::ReturnXmlParse, de.tagName(),
				"Missing Count Attribute");

	QString txtString = de.text().simplified();
	QStringList txtFloats = txtString.split(" ", QString::SkipEmptyParts);
	if (n > txtFloats.size())
		return Return(Return::ReturnXmlParse, de.tagName(), "Missing Data");

	data.fill(0.0, n);
	minData = INT_MAX, maxData = INT_MIN;
	int x = 0;
	while (n)
	{
		bool ok;
		QString s = txtFloats.at(x);
		qreal v = s.toDouble(&ok);
		if ( ! ok)
		{
			clear();
			return Return(Return::ReturnXmlParse, de.tagName(), "Invalid floating point data");
		}
		data[x] = v;
		if (v < minData)	minData = v;
		if (v > maxData)	maxData = v;
		--n, ++x;
	}

	if ( ! isValid())
		return Return(EigenFace::ReturnInvalidStructure, de.tagName());

	return Return();
} // read(de)

Return EigenFaceMaskedArray::write(QByteArray * ba) const
{
	Return rtn;

	if ( ! ba)
		return Return(EigenFace::ReturnStatusNull);
	if ( ! isValid())
		return Return(EigenFace::ReturnInvalidStructure, "MaskedArray");

	QBuffer buf;
	rtn = write(&buf);
	if (rtn.isError())
		return rtn;

	*ba = buf.data();
	return Return();
} // write(ba)

Return EigenFaceMaskedArray::write(QIODevice * io) const
{
	if ( ! isValid())
		return Return(EigenFace::ReturnInvalidStructure, "MaskedArray");

	// write stream id
	int i = StreamId;
	io->write((char *)&i, sizeof(i));

	// write basic data
	io->write((char *)&Id, sizeof(Id));
	io->write((char *)&VectorKey, sizeof(VectorKey));
	io->write((char *)&Residual, sizeof(Residual));

	i = data.size();
	io->write((char *)&i, sizeof(i));
	if (i * sizeof(qreal) != io->write((char *)data.data(), i * sizeof(qreal)))
		return Return::errorString(io->errorString());

	return Return();
} // write(io)

Return EigenFaceMaskedArray::write(QDomElement * de) const
{
	if ( ! isValid())
		return Return(EigenFace::ReturnInvalidStructure, "MaskedArray");

	QString txtString;
	int n = efData->mask().count();

	de->setAttribute("Id", Id);
	de->setAttribute("MinData", minData);
	de->setAttribute("MaxData", maxData);
	de->setAttribute("Count", n);

	txtString.reserve(n * 16);
	for (int x = 0; x < n; ++x)
	{
		if (0 == x % 8)
			txtString.append("\n");
		txtString.append(QString::number(data.at(x), 'f', 12) + " ");
	}

	QDomText txtNode = de->ownerDocument().createTextNode(txtString);
	de->appendChild(txtNode);

	return Return();
} // write(de)

Return EigenFaceMaskedArray::write(QDomDocument * doc, const QString & tagName) const
{
	if ( ! isValid())
		return Return(EigenFace::ReturnInvalidStructure, tagName);

	QDomElement de = doc->firstChildElement(tagName);
	while ( ! de.isNull())
	{
		doc->removeChild(de);
		de = de.nextSiblingElement(tagName);
	}

	QDomElement tag = doc->createElement(tagName);
	Return rtn = write(&tag);
	if ( ! rtn.isError())
		doc->appendChild(tag);

	return rtn;
} // write(doc)

Return EigenFaceMaskedArray::read(const QByteArray & ba)
{
	QBuffer buf;
	buf.setData(ba);
	return read(&buf);
}

Return EigenFaceMaskedArray::read(QIODevice * io)
{
	int i;

	clear();

	// Check Stream Id
	io->read((char *)&i, sizeof(i));
	if (StreamId != i)
		return Return(EigenFace::ReturnInvalidStructure, "EFMA:StreamId");

	// Read basic data
	io->read((char *)&Id, sizeof(Id));
	io->read((char *)&VectorKey, sizeof(VectorKey));
	io->read((char *)&Residual, sizeof(Residual));

	// Read data vector
	io->read((char *)&i, sizeof(i));
	data.fill(i, 0.0);
	if (i * sizeof(qreal) != io->read((char *)data.data(), i * sizeof(qreal)))
		return Return::errorString(io->errorString());

	if (data.isEmpty())
		minData = maxData = 0.0;
	else
	{
		minData = INT_MAX, maxData = INT_MIN;
		foreach(qreal v, data)
		{
			if (v < minData)	minData = v;
			if (v > maxData)	maxData = v;
		}
	}

	if (isValid())
		return Return();
	else
		return Return(EigenFace::ReturnInvalidStructure, "MaskedArray");
}

ext: cpp


text:
/*
 *            Copyright 2009-2020 The VOTCA Development Team
 *                       (http://www.votca.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.
 *
 */
/// For an earlier history see ctp repo commit
/// 77795ea591b29e664153f9404c8655ba28dc14e9

// Third party includes
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <libint2/initialize.h>

// Local VOTCA includes
#include "votca/xtp/parallelxjobcalc.h"

using boost::format;

namespace votca {
namespace xtp {

template <typename JobContainer>
bool ParallelXJobCalc<JobContainer>::Evaluate(const Topology &top) {
  libint2::initialize();
  // INITIALIZE PROGRESS OBSERVER
  std::string progFile = jobfile_;
  std::unique_ptr<JobOperator> master = std::unique_ptr<JobOperator>(
      new JobOperator(-1, top, *this, openmp_threads_));
  master->getLogger().setReportLevel(Log::current_level);
  master->getLogger().setMultithreading(true);
  master->getLogger().setPreface(Log::info, "\nMST INF");
  master->getLogger().setPreface(Log::error, "\nMST ERR");
  master->getLogger().setPreface(Log::warning, "\nMST WAR");
  master->getLogger().setPreface(Log::debug, "\nMST DBG");
  progObs_->InitFromProgFile(progFile, *(master.get()));

  // CREATE + EXECUTE THREADS (XJOB HANDLERS)
  std::vector<std::unique_ptr<JobOperator>> jobOps;

  for (Index id = 0; id < nThreads_; id++) {
    jobOps.push_back(std::unique_ptr<JobOperator>(
        new JobOperator(id, top, *this, openmp_threads_)));
  }

  for (Index id = 0; id < nThreads_; ++id) {
    CustomizeLogger(*jobOps[id]);
  }

  if (!maverick_) {
    std::cout << std::endl;  // REQUIRED FOR PROGRESS BAR IN OBSERVER
  }

  for (Index id = 0; id < nThreads_; id++) {
    jobOps[id]->Start();
  }

  for (Index id = 0; id < nThreads_; id++) {
    jobOps[id]->WaitDone();
  }

  if (!maverick_) {
    for (Index id = 0; id < nThreads_; id++) {
      std::cout << std::endl << (jobOps[id]->getLogger()) << std::flush;
    }
  }

  jobOps.clear();

  // SYNC REMAINING COMPLETE JOBS
  progObs_->SyncWithProgFile(*(master.get()));
  libint2::finalize();
  return true;
}

template <typename JobContainer>
void ParallelXJobCalc<JobContainer>::JobOperator::Run() {
  OPENMP::setMaxThreads(openmp_threads_);
  while (true) {
    Job *job = master_.progObs_->RequestNextJob(*this);

    if (job == nullptr) {
      break;
    } else {
      Result res = this->master_.EvalJob(top_, *job, *this);
      this->master_.progObs_->ReportJobDone(*job, res, *this);
    }
  }
}

template <typename JobContainer>
void ParallelXJobCalc<JobContainer>::ParseCommonOptions(
    const tools::Property &options) {
  std::cout << "\n... ... Initialized with " << nThreads_ << " threads.\n";

  maverick_ = (nThreads_ == 1) ? true : false;

  std::cout << "\n... ... Using " << openmp_threads_ << " openmp threads for "
            << nThreads_ << "x" << openmp_threads_ << "="
            << nThreads_ * openmp_threads_ << " total threads." << std::flush;
  jobfile_ = options.get(".job_file").as<std::string>();
  mapfile_ = options.get(".map_file").as<std::string>();
}

template <typename JobContainer>
void ParallelXJobCalc<JobContainer>::CustomizeLogger(QMThread &thread) {

  // CONFIGURE LOGGER
  Logger &log = thread.getLogger();
  log.setReportLevel(Log::current_level);
  log.setMultithreading(maverick_);

  log.setPreface(Log::info,
                 (format("\nT%1$02d INF ...") % thread.getId()).str());
  log.setPreface(Log::error,
                 (format("\nT%1$02d ERR ...") % thread.getId()).str());
  log.setPreface(Log::warning,
                 (format("\nT%1$02d WAR ...") % thread.getId()).str());
  log.setPreface(Log::debug,
                 (format("\nT%1$02d DBG ...") % thread.getId()).str());
}

// REGISTER PARALLEL CALCULATORS
template class ParallelXJobCalc<std::vector<Job>>;

}  // namespace xtp
}  // namespace votca

ext: cc

max_stars_repo_name: rubengerritsen/xtp

max_issues_repo_name: rubengerritsen/xtp

max_forks_repo_name: rubengerritsen/xtp


text:
//==================================================================================================
/*!
  @file

    @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_EXPRECNEGC_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_EXPRECNEGC_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-exponential
    This function object computes: \f$1-e^{-\frac1x}\f$

    @par Header <boost/simd/function/exprecnegc.hpp>

    @par Notes

    - result is accurate even for large @c x

    @par Example:

      @snippet exprecnegc.cpp exprecnegc

    @par Possible output:

      @snippet exprecnegc.txt exprecnegc

  **/
  IEEEValue exprecnegc(IEEEValue const& x);
} }
#endif

#include <boost/simd/function/scalar/exprecnegc.hpp>
#include <boost/simd/function/simd/exprecnegc.hpp>

#endif

ext: hpp

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
// Copyright (c) 2020 fortiss GmbH
//
// Authors: Julian Bernhard, Klemens Esterle, Patrick Hart and
// Tobias Kessler
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.

#ifndef BARK_MODELS_DYNAMIC_INTEGRATION_HPP_
#define BARK_MODELS_DYNAMIC_INTEGRATION_HPP_
#include <Eigen/Core>

#include "bark/geometry/angle.hpp"
#include "bark/models/dynamic/dynamic_model.hpp"

namespace bark {
namespace models {
namespace dynamic {

inline State euler_int(const DynamicModel& model,
                const State &x,
                const Input &u,
                float dt) {
  State new_x = x + dt * model.StateSpaceModel(x, u);
  new_x(StateDefinition::THETA_POSITION) =
      geometry::Norm0To2PI(new_x(StateDefinition::THETA_POSITION));
  return new_x;
}

inline State rk4(const DynamicModel& model, const State& x, const Input& u,
                 float dt) {
  State k0 = dt * model.StateSpaceModel(x, u);
  State k1 = dt * model.StateSpaceModel(x + k0 / 2, u);
  State k2 = dt * model.StateSpaceModel(x + k1 / 2, u);
  State k3 = dt * model.StateSpaceModel(x + k2, u);
  return x + 1.0 / 6.0 * (k0 + 2 * k1 + 2 * k2 + k3);
}

}  // namespace dynamic
}  // namespace models
}  // namespace bark

#endif  // BARK_MODELS_DYNAMIC_INTEGRATION_HPP_

max_stars_repo_name: BastianHofmann/bark

max_issues_repo_name: BastianHofmann/bark

max_forks_repo_name: BastianHofmann/bark


text:
//==================================================================================================
/**
  EVE - Expressive Vector Engine
  Copyright : EVE Contributors & Maintainers
  SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include <eve/detail/diff_div.hpp>
#include <eve/function/diff/gegenbauer.hpp>
#include <boost/math/special_functions/gegenbauer.hpp>
#include <type_traits>

TTS_CASE_TPL("Check diff(gegenbauer) return type", EVE_TYPE)
{
    TTS_EXPR_IS(eve::diff(eve::gegenbauer)((unsigned int)(0), T(), T()), T);
}

TTS_CASE_TPL("Check eve::diff(eve::gegenbauer) behavior", EVE_TYPE)
{
  using elt_t = eve::element_type_t<T>;
  elt_t l(-3.0/8.0);
  auto eve__gegenbauer =  [&l](unsigned n, auto x) { return eve::diff(eve::gegenbauer)(n, T(l), x); };
  auto boost_gegenbauer =  [&l](unsigned n, auto x) { return boost::math::gegenbauer_derivative(n, double(l), x, 1u); };

  for(unsigned int i=0; i < 10; ++i)
  {
    TTS_ULP_EQUAL(eve__gegenbauer(i, T(10)), T(boost_gegenbauer(i, 10.0)), 1);
    TTS_ULP_EQUAL(eve__gegenbauer(i, T(5)), T(boost_gegenbauer(i, 5.0)), 1);
    TTS_ULP_EQUAL(eve__gegenbauer(i, T(2)), T(boost_gegenbauer(i, 2.0)), 1);
    TTS_ULP_EQUAL(eve__gegenbauer(i, T(1)), T(boost_gegenbauer(i, 1.0)), 20);
    TTS_ULP_EQUAL(eve__gegenbauer(i, T(0)), T(boost_gegenbauer(i, 0.0)), 1);
  }
}

max_stars_repo_name: orao/eve

max_issues_repo_name: orao/eve

max_forks_repo_name: orao/eve


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2013-2021 Regents of the University of California.
 *
 * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
 *
 * ndn-cxx library is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
 *
 * You should have received copies of the GNU General Public License and GNU Lesser
 * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
 */

#include "ndn-cxx/util/scheduler.hpp"

#include "tests/boost-test.hpp"
#include "tests/unit/io-fixture.hpp"

#include <boost/lexical_cast.hpp>

namespace ndn {
namespace scheduler {
namespace tests {

class SchedulerFixture : public ndn::tests::IoFixture
{
protected:
  Scheduler scheduler{m_io};
};

BOOST_AUTO_TEST_SUITE(Util)
BOOST_FIXTURE_TEST_SUITE(TestScheduler, SchedulerFixture)

BOOST_AUTO_TEST_SUITE(General)

BOOST_AUTO_TEST_CASE(Events)
{
  size_t count1 = 0;
  size_t count2 = 0;

  scheduler.schedule(500_ms, [&] {
    ++count1;
    BOOST_CHECK_EQUAL(count2, 1);
  });

  EventId i = scheduler.schedule(1_s, [] { BOOST_ERROR("This event should not have been fired"); });
  i.cancel();

  scheduler.schedule(250_ms, [&] {
    BOOST_CHECK_EQUAL(count1, 0);
    ++count2;
  });

  i = scheduler.schedule(50_ms, [&] { BOOST_ERROR("This event should not have been fired"); });
  i.cancel();

  advanceClocks(25_ms, 1000_ms);
  BOOST_CHECK_EQUAL(count1, 1);
  BOOST_CHECK_EQUAL(count2, 1);
}

BOOST_AUTO_TEST_CASE(CallbackException)
{
  class MyException : public std::exception
  {
  };
  scheduler.schedule(10_ms, [] {
    // use plain 'throw' to ensure that Scheduler does not depend on the
    // internal machinery of NDN_THROW and that it can catch all exceptions
    // regardless of how they are thrown by the application
    throw MyException{};
  });

  bool isCallbackInvoked = false;
  scheduler.schedule(20_ms, [&isCallbackInvoked] { isCallbackInvoked = true; });

  BOOST_CHECK_THROW(this->advanceClocks(6_ms, 2), MyException);
  this->advanceClocks(6_ms, 2);
  BOOST_CHECK(isCallbackInvoked);
}

BOOST_AUTO_TEST_CASE(CancelEmptyEvent)
{
  EventId i;
  i.cancel();

  // avoid "test case [...] did not check any assertions" message from Boost.Test
  BOOST_CHECK(true);
}

BOOST_AUTO_TEST_CASE(SelfCancel)
{
  EventId selfEventId;
  selfEventId = scheduler.schedule(100_ms, [&] { selfEventId.cancel(); });
  BOOST_REQUIRE_NO_THROW(advanceClocks(100_ms, 10));
}

class SelfRescheduleFixture : public SchedulerFixture
{
public:
  void
  reschedule()
  {
    EventId eventId = scheduler.schedule(100_ms, [this] { reschedule(); });
    selfEventId.cancel();
    selfEventId = eventId;

    if (count < 5)
      count++;
    else
      selfEventId.cancel();
  }

  void
  reschedule2()
  {
    selfEventId.cancel();

    if (count < 5)  {
      selfEventId = scheduler.schedule(100_ms, [this] { reschedule2(); });
      count++;
    }
  }

  void
  reschedule3()
  {
    selfEventId.cancel();

    scheduler.schedule(100_ms, [&] { ++count; });
    scheduler.schedule(100_ms, [&] { ++count; });
    scheduler.schedule(100_ms, [&] { ++count; });
    scheduler.schedule(100_ms, [&] { ++count; });
    scheduler.schedule(100_ms, [&] { ++count; });
    scheduler.schedule(100_ms, [&] { ++count; });
  }

public:
  EventId selfEventId;
  size_t count = 0;
};

BOOST_FIXTURE_TEST_CASE(Reschedule, SelfRescheduleFixture)
{
  selfEventId = scheduler.schedule(0_s, [this] { reschedule(); });
  BOOST_REQUIRE_NO_THROW(advanceClocks(50_ms, 1000_ms));
  BOOST_CHECK_EQUAL(count, 5);
}

BOOST_FIXTURE_TEST_CASE(Reschedule2, SelfRescheduleFixture)
{
  selfEventId = scheduler.schedule(0_s, [this] { reschedule2(); });
  BOOST_REQUIRE_NO_THROW(advanceClocks(50_ms, 1000_ms));
  BOOST_CHECK_EQUAL(count, 5);
}

BOOST_FIXTURE_TEST_CASE(Reschedule3, SelfRescheduleFixture)
{
  selfEventId = scheduler.schedule(0_s, [this] { reschedule3(); });
  BOOST_REQUIRE_NO_THROW(advanceClocks(50_ms, 1000_ms));
  BOOST_CHECK_EQUAL(count, 6);
}

class CancelAllFixture : public SchedulerFixture
{
public:
  void
  event()
  {
    ++count;
    scheduler.schedule(1_s, [&] { event(); });
  }

public:
  uint32_t count = 0;
};

BOOST_FIXTURE_TEST_CASE(CancelAll, CancelAllFixture)
{
  scheduler.schedule(500_ms, [&] { scheduler.cancelAllEvents(); });
  scheduler.schedule(1_s, [&] { event(); });
  scheduler.schedule(3_s, [] { BOOST_ERROR("This event should have been cancelled" ); });

  advanceClocks(100_ms, 100);
  BOOST_CHECK_EQUAL(count, 0);
}

BOOST_AUTO_TEST_CASE(CancelAllWithScopedEventId) // Bug 3691
{
  ScopedEventId eid = scheduler.schedule(10_ms, []{});
  scheduler.cancelAllEvents();
  eid.cancel(); // should not crash

  // avoid "test case [...] did not check any assertions" message from Boost.Test
  BOOST_CHECK(true);
}

BOOST_AUTO_TEST_SUITE_END() // General

BOOST_AUTO_TEST_SUITE(EventId)

using scheduler::EventId;

BOOST_AUTO_TEST_CASE(ConstructEmpty)
{
  EventId eid;
  BOOST_CHECK(!eid);
}

BOOST_AUTO_TEST_CASE(Equality)
{
  EventId eid, eid2;
  BOOST_CHECK(eid == eid2);

  eid = scheduler.schedule(10_ms, []{});
  BOOST_CHECK(eid != eid2);

  eid2 = scheduler.schedule(10_ms, []{});
  BOOST_CHECK(eid != eid2);

  eid.cancel();
  BOOST_CHECK(eid != eid2);
  BOOST_CHECK(eid == EventId{});

  eid2.cancel();
  BOOST_CHECK(eid == eid2);

  eid = eid2 = scheduler.schedule(20_ms, []{});
  BOOST_CHECK(eid == eid2);
  BOOST_CHECK(eid != EventId{});

  eid.cancel();
  BOOST_CHECK(eid == eid2);
  BOOST_CHECK(eid == EventId{});
}

BOOST_AUTO_TEST_CASE(OperatorBool)
{
  EventId eid;
  BOOST_CHECK_EQUAL(static_cast<bool>(eid), false);
  BOOST_CHECK_EQUAL(!eid, true);

  eid = scheduler.schedule(10_ms, []{});
  BOOST_CHECK_EQUAL(static_cast<bool>(eid), true);
  BOOST_CHECK_EQUAL(!eid, false);

  EventId eid2 = eid;
  eid2.cancel();
  BOOST_CHECK(!eid);
  BOOST_CHECK(!eid2);
}

BOOST_AUTO_TEST_CASE(DuringCallback)
{
  EventId eid;
  EventId eid2 = scheduler.schedule(20_ms, []{});

  bool isCallbackInvoked = false;
  eid = scheduler.schedule(10_ms, [&eid, &eid2, &isCallbackInvoked] {
    isCallbackInvoked = true;

    // eid is "expired" during callback execution
    BOOST_CHECK(!eid);
    BOOST_CHECK_NE(eid, eid2);

    eid2.cancel();
    BOOST_CHECK_EQUAL(eid, eid2);
  });

  this->advanceClocks(6_ms, 2);
  BOOST_CHECK(isCallbackInvoked);
}

BOOST_AUTO_TEST_CASE(Reset)
{
  bool isCallbackInvoked = false;
  EventId eid = scheduler.schedule(10_ms, [&isCallbackInvoked] { isCallbackInvoked = true; });
  eid.reset();
  BOOST_CHECK(!eid);

  this->advanceClocks(6_ms, 2);
  BOOST_CHECK(isCallbackInvoked);
}

BOOST_AUTO_TEST_CASE(ToString)
{
  std::string nullString = boost::lexical_cast<std::string>(shared_ptr<int>());

  EventId eid;
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(eid), nullString);

  eid = scheduler.schedule(10_ms, []{});
  BOOST_CHECK_NE(boost::lexical_cast<std::string>(eid), nullString);
}

BOOST_AUTO_TEST_SUITE_END() // EventId

BOOST_AUTO_TEST_SUITE(ScopedEventId)

using scheduler::ScopedEventId;

BOOST_AUTO_TEST_CASE(Destruct)
{
  int hit = 0;
  {
    ScopedEventId se = scheduler.schedule(10_ms, [&] { ++hit; });
  } // se goes out of scope
  this->advanceClocks(1_ms, 15);
  BOOST_CHECK_EQUAL(hit, 0);
}

BOOST_AUTO_TEST_CASE(Assign)
{
  int hit1 = 0, hit2 = 0;
  ScopedEventId se1 = scheduler.schedule(10_ms, [&] { ++hit1; });
  se1 = scheduler.schedule(10_ms, [&] { ++hit2; });
  this->advanceClocks(1_ms, 15);
  BOOST_CHECK_EQUAL(hit1, 0);
  BOOST_CHECK_EQUAL(hit2, 1);
}

BOOST_AUTO_TEST_CASE(Release)
{
  int hit = 0;
  {
    ScopedEventId se = scheduler.schedule(10_ms, [&] { ++hit; });
    se.release();
  } // se goes out of scope
  this->advanceClocks(1_ms, 15);
  BOOST_CHECK_EQUAL(hit, 1);
}

BOOST_AUTO_TEST_CASE(Move)
{
  int hit = 0;
  unique_ptr<ScopedEventId> se2;
  {
    ScopedEventId se = scheduler.schedule(10_ms, [&] { ++hit; });
    se2 = make_unique<ScopedEventId>(std::move(se)); // move constructor
  } // se goes out of scope
  this->advanceClocks(1_ms, 15);
  BOOST_CHECK_EQUAL(hit, 1);

  ScopedEventId se3;
  {
    ScopedEventId se = scheduler.schedule(10_ms, [&] { ++hit; });
    se3 = std::move(se); // move assignment
  } // se goes out of scope
  this->advanceClocks(1_ms, 15);
  BOOST_CHECK_EQUAL(hit, 2);
}

BOOST_AUTO_TEST_CASE(OperatorBool)
{
  ScopedEventId se;
  BOOST_CHECK_EQUAL(static_cast<bool>(se), false);
  BOOST_CHECK_EQUAL(!se, true);

  se = scheduler.schedule(10_ms, []{});
  BOOST_CHECK_EQUAL(static_cast<bool>(se), true);
  BOOST_CHECK_EQUAL(!se, false);

  se.cancel();
  BOOST_CHECK(!se);

  se = scheduler.schedule(10_ms, []{});
  BOOST_CHECK(se);

  se.release();
  BOOST_CHECK(!se);
}

BOOST_AUTO_TEST_SUITE_END() // ScopedEventId

BOOST_AUTO_TEST_SUITE_END() // TestScheduler
BOOST_AUTO_TEST_SUITE_END() // Util

} // namespace tests
} // namespace scheduler
} // namespace ndn

max_stars_repo_name: Pesa/ndn-cxx

max_issues_repo_name: Pesa/ndn-cxx

max_forks_repo_name: Pesa/ndn-cxx


text:
#include "FloatingObject.hpp"
#include <algorithm>
#include <vector>
#include <mutex>
#include <shared_mutex>
#include <Eigen\Geometry>

#define NOMINMAX
#include <Windows.h>

namespace {
	const float pi = 3.14159265359;
	constexpr float AIR_DENSITY = 1.293e-9; // [kg/mm3]
}

namespace dynaman {
	FloatingObject::FloatingObject(
		const Eigen::Vector3f& positionTarget,
		const Eigen::Vector3f& lowerbound,
		const Eigen::Vector3f& upperbound,
		float radius,
		float weight
	):
		m_position(positionTarget),
		m_velocity(Eigen::Vector3f::Zero()),
		m_integral(Eigen::Vector3f::Zero()),
		m_lowerbound(lowerbound),
		m_upperbound(upperbound),
		m_weight(weight),
		m_radius(radius),
		m_is_tracked(false),
		m_lastDeterminationTime(0),
		velocityBufferSize(3),
		positionBuffer(velocityBufferSize, positionTarget),
		velocityBuffer(velocityBufferSize, Eigen::Vector3f::Zero()),
		dTBuffer(velocityBufferSize, 1),
		m_pTrajectory(std::make_shared<TrajectoryConstantState>(positionTarget)
		)
	{}

	FloatingObjectPtr FloatingObject::Create(
		const Eigen::Vector3f& posTgt,
		const Eigen::Vector3f& lowerbound,
		const Eigen::Vector3f& upperbound,
		float radius,
		float weight
	){
		return std::make_shared<FloatingObject>(posTgt, lowerbound, upperbound, radius, weight);
	}

	float FloatingObject::sphereMass()
	{
		return AIR_DENSITY * 4.0f * pi * m_radius * m_radius * m_radius / 3.0f;
	}

	float FloatingObject::radius() {
		return m_radius;
	}

	float FloatingObject::weight()
	{
		return m_weight;
	}

	float FloatingObject::totalMass()
	{
		return sphereMass() + weight();
	}

	DWORD FloatingObject::lastDeterminationTime() {
		std::lock_guard<std::mutex> lock(mtxState);
		return m_lastDeterminationTime;
	}

	Eigen::Vector3f FloatingObject::position()
	{
		std::lock_guard<std::mutex> lock(mtxState);
		return m_position;
	}

	Eigen::Vector3f FloatingObject::velocity()
	{
		std::lock_guard<std::mutex> lock(mtxState);
		return averageVelocity(this->velocityBuffer, this->dTBuffer);
	}

	Eigen::Vector3f FloatingObject::integral()
	{
		std::lock_guard<std::mutex> lock(mtxState);
		return m_integral;
	}

	Eigen::Vector3f FloatingObject::positionTarget(DWORD systime_ms)
	{
		std::shared_lock<std::shared_mutex> lock(mtxTrajectory);
		return m_pTrajectory->pos(systime_ms);
	}

	Eigen::Vector3f FloatingObject::velocityTarget(DWORD systime_ms)
	{
		std::shared_lock<std::shared_mutex> lock(mtxTrajectory);
		return m_pTrajectory->vel(systime_ms);
	}

	Eigen::Vector3f FloatingObject::accelTarget(DWORD systime_ms)
	{
		std::shared_lock<std::shared_mutex> lock(mtxTrajectory);
		return m_pTrajectory->accel(systime_ms);
	}

	void FloatingObject::getStates(
		Eigen::Vector3f& pos,
		Eigen::Vector3f& vel,
		Eigen::Vector3f& integ
	) {
		std::lock_guard<std::mutex> lock(mtxState);
		pos = m_position;
		vel = averageVelocity(this->velocityBuffer, this->dTBuffer);
		integ = m_integral;
	}

	void FloatingObject::updateStates(DWORD determinationTime, const Eigen::Vector3f& positionNew)
	{
		std::lock_guard<std::mutex> lock(mtxState);
		float dt = (float)(determinationTime - m_lastDeterminationTime) / 1000.f; // [sec]
		m_velocity = (positionNew - m_position) / dt;
		dTBuffer.push_back(dt);
		dTBuffer.pop_front();
		positionBuffer.push_back(positionNew);
		positionBuffer.pop_front();
		velocityBuffer.push_back(m_velocity);
		velocityBuffer.pop_front();
		if (isTracked())
		{
			m_integral += (0.5f * (positionNew + m_position) - positionTarget()) * dt;
		}
		m_position = positionNew;
		m_lastDeterminationTime = determinationTime;
	}

	void FloatingObject::resetIntegral() {
		std::lock_guard<std::mutex> lock(mtxState);
		m_integral.setZero();
	}

	void FloatingObject::getStatesTarget(
		Eigen::Vector3f& posTgt,
		Eigen::Vector3f& velTgt,
		Eigen::Vector3f& accelTgt,
		DWORD time
	) {
		std::lock_guard<std::shared_mutex> lock(mtxTrajectory);
		posTgt = m_pTrajectory->pos(time);
		velTgt = m_pTrajectory->vel(time);
		accelTgt = m_pTrajectory->accel(time);
	}

	void FloatingObject::updateStatesTarget(
		const Eigen::Vector3f& _positionTarget,
		const Eigen::Vector3f& _velocityTarget,
		const Eigen::Vector3f& _accelTarget)
	{
		auto constTrajPtr = TrajectoryConstantState::Create(_positionTarget, _velocityTarget, _accelTarget);
		setTrajectory(constTrajPtr);
	}

	bool FloatingObject::isTracked() {
		std::lock_guard<std::mutex> lock(mtxTrack);
		return m_is_tracked;
	}

	void FloatingObject::setTrackingStatus(bool is_tracked) {
		std::lock_guard<std::mutex> lock(mtxTrack);
		this->m_is_tracked = is_tracked;
	}

	Eigen::Vector3f FloatingObject::averageVelocity(
		std::deque<Eigen::Vector3f> velocityBuffer,
		std::deque<float> intervalBuffer
	) {
		auto itrVel = velocityBuffer.begin();
		auto itrDT = intervalBuffer.begin();
		Eigen::Vector3f distSum(0.f, 0.f, 0.f);
		float period = 0;
		while (itrVel != velocityBuffer.end())
		{
			distSum += (*itrDT) * (*itrVel);
			period += *itrDT;
			itrDT++;
			itrVel++;
		}
		return distSum /= period;
	}

	Eigen::Vector3f FloatingObject::averagePosition() {
		Eigen::Vector3f posAverage(0, 0, 0);
		std::lock_guard<std::mutex> lock(mtxState);
		for (auto itr = positionBuffer.begin(); itr != positionBuffer.end(); itr++) {
			posAverage += *itr;
		}
		return posAverage / positionBuffer.size();
	}

	bool FloatingObject::isInsideWorkspace()
	{
		auto pos = position();
		Eigen::Vector3f v0 = pos - lowerbound();
		Eigen::Vector3f v1 = pos - upperbound();
		return (v0.x() * v1.x() <= 0) && (v0.y() * v1.y() <= 0) && (v0.z() * v1.z() <= 0);
	}

	void FloatingObject::setTrajectory(std::shared_ptr<Trajectory> newTrajectoryPtr)
	{
		std::lock_guard<std::shared_mutex> lock(mtxTrajectory);
		m_pTrajectory = newTrajectoryPtr;
	}

	Eigen::Vector3f FloatingObject::lowerbound() {
		return m_lowerbound;
	}

	Eigen::Vector3f FloatingObject::upperbound() {
		return m_upperbound;
	}

	std::string FloatingObject::logCtrlHeader() const {
		return "sys_time,x,y,z,vx,vy,vz,ix,iy,iz,xTgt,yTgt,zTgt,vxTgt,vyTgt,vzTgt,axTgt,ayTgt,azTgt";
	}

	std::ofstream& operator<<(std::ostream& ofs, FloatingObjectPtr pObject) {
		DWORD time = pObject->lastDeterminationTime();
		Eigen::Vector3f pos, vel, integ, posTgt, velTgt, accelTgt;
		pObject->getStates(pos, vel, integ);
		pObject->getStatesTarget(posTgt, velTgt, accelTgt, time);
		ofs
			<< time << ","
			<< pos.x() << "," << pos.y() << "," << pos.z() << ","
			<< vel.x() << "," << vel.y() << "," << vel.z() << ","
			<< integ.x() << "," << integ.y() << "," << integ.z() << ","
			<< posTgt.x() << "," << posTgt.y() << "," << posTgt.z() << ","
			<< velTgt.x() << "," << velTgt.y() << "," << velTgt.z() << ","
			<< accelTgt.x() << "," << accelTgt.y() << "," << accelTgt.z();
	}
}

max_stars_repo_name: shinolab/dynamic-manipulation

max_issues_repo_name: shinolab/dynamic-manipulation

max_forks_repo_name: shinolab/dynamic-manipulation


text:
// Copyright Matt Overby 2021.
// Distributed under the MIT License.

#ifndef MCL_MESHDATA_HPP
#define MCL_MESHDATA_HPP 1

#include "Singleton.hpp"
#include <Eigen/Geometry>
#include <vector>
#include <unordered_map>

namespace mcl
{

//
// Stores all of the input mesh information.
// All const accessors are thread safe.
// Any non-const functions are not guaranteed to be.
//
class MeshData : public Singleton<MeshData>
{
public:
	typedef Eigen::Matrix<int,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor> RowMatrixXi;
	typedef Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor> RowMatrixXd;

	MeshData() { clear(); }

	// Prints details about mesh
	std::string print_stats() const;

	// Resets all mesh data
	void clear();

	int dim() const { return mDim; }
	int num_meshes() const { return std::max(0, (int)m_V_offsets.size()-1); }

	// Computes mesh quantities, connectivities, etc...
	void initialize();
	bool needs_initialize() const { return needs_init; }

	// General queries
	bool is_texture_param() const;
	bool is_dynamic_vert(int idx) const;
	int mesh_idx_from_element(int elem_idx) const;

	// Get mesh features
	const RowMatrixXi& get_faces() const; // 2D = same as elements, 3D = same as facets
	const RowMatrixXi& get_boundary_edges() const; // same as facets if 2D
	const Eigen::VectorXi& get_boundary_verts() const;
	const RowMatrixXi& get_elements() const { return mP; } // 2D = triangles, 3D = tets
	const RowMatrixXi& get_facets() const { return mF; } // boundary, 2D = edges, 3D = triangles
	Eigen::Vector2i get_adjacent_faces(int e0, int e1) const; // returns faces of edge (-1 if not found)

	// Get mesh quantities
	const Eigen::VectorXd& get_mesh_measures() const; // per-mesh total area or volume
	const Eigen::VectorXd& get_measures() const; // per-element 2D=area, 3D=volume
	void update_measure(int idx, double m); // change per-element measure
	const Eigen::VectorXd& get_scalings() const; // per-element 2D=inv perim, 3D=inv surface area
	const std::vector<std::vector<int> >& get_graph() const; // per-vertex non-directed connectivity of elems

	// Initializer is the starting point of the optimization.
	// If not set before optimization starts, rest shape is used.
	const RowMatrixXd& get_initializer() const;
	void set_initializer(const RowMatrixXd& V) { mVinit = V; }

	// Rest shape defines the energy of the mesh.
	// By default the rest shape is whatever is passed to add_mesh
	const RowMatrixXd& get_rest() const { return mV; }
	void set_rest(const RowMatrixXd& V);

	// Returns offsets [start, end] for elements of the stacked matrix. E.g.,
	// mesh0 = E.block(offsets[0], 0, offsets[1], dim+1)
	// mesh1 = E.block(offsets[1], 0, offsets[2], dim+1)
	// etc...
	const Eigen::VectorXi& get_element_offsets() const { return m_P_offsets; }
	const Eigen::VectorXi& get_vertex_offsets() const { return m_V_offsets; }
	const Eigen::VectorXi& get_facet_offsets() const { return m_F_offsets; }
	const Eigen::VectorXi& get_face_offsets() const;

	// Handy hash map to get the feature indices. Returns -1 if not found.
	// Winding order does not matter.
	int get_face_index(int f0, int f1, int f2) const;
	int get_tet_index(int t0, int t1, int t2, int t3) const;

	// Returns index of the mesh, or -1 if there was an error.
	// If init=true, initialize() is called immediately which can be slow for many large meshes.
	int add_mesh(const RowMatrixXd &V, const RowMatrixXi &P, bool init=true); // auto computes faces
	int add_mesh(const RowMatrixXd &V, const RowMatrixXi &P, const RowMatrixXi &F, bool init=true);

	// Special case: adds a mesh to be parameterized.
	// In this case, the 2D texture coords are the dynamic variable (initializer) and
	// the 3D mesh is the rest mesh (incl. rest_volume=area, rest_surf_area=perimeter, etc...).
	// The input mesh must be a 3D triangular mesh.
	// If UVinit is not given, one is computed (Tutte).
	// TODO: Some validation and error checking on compatibility.
	int add_parameterized_mesh(const RowMatrixXd &V, const RowMatrixXi &F,
		const RowMatrixXd &UVinit = RowMatrixXd(), bool init=true);

 	// Computes (volume-weighted) masses with unit-volume density.
	// If negative, defaults are used: 1100 for volumetric, 0.4 for cloth/2D
	// See: https://www.engineeringtoolbox.com/density-solids-d_1265.html
	// Masses are not needed for static solves.
	// If masses are not computed/set, an empty vector is returned
	void compute_masses(double density_kg = -1);
	void set_masses(const Eigen::VectorXd &m) { m_masses=m; }
	const Eigen::VectorXd& get_masses() const { return m_masses; }
	double get_rest_radius() const;

	// Serialize
	template<class Archive> void save(Archive& archive) const;
	template<class Archive> void load(Archive& archive);

protected:

	// Edges if 2D, triangles if 3D
	void compute_facets(const RowMatrixXi &P, RowMatrixXi &F);

	// Boundary edges, vertices, etc.
	void init_boundary_mappings();

	// Updates per-element internal data
	void init_per_element_data();

	// Mappings to edge/face/etc...
	void init_feature_mapping();

	int mDim;
	bool needs_init;

	// Dynamic:
	RowMatrixXd mV; // rest vertices
	RowMatrixXd mVinit; // initializer
	RowMatrixXi mP; // (internal) elements
	RowMatrixXi mF; // facets
	Eigen::VectorXd m_masses; // per-vertex masses
	Eigen::VectorXd m_rest_bmin_mbax; // [bmin, bmax]

	// Stacked (computed) quantities [dynamic, kinematic]
	// Most are computed on initialize
	Eigen::VectorXd m_mesh_measures; // mesh-measure
	Eigen::VectorXi m_V_offsets; // indices into stacked V
	Eigen::VectorXi m_P_offsets; // indices into stacked P
	Eigen::VectorXi m_F_offsets; // indices into stacked F
	Eigen::VectorXd m_measures; // rest volume/area
	Eigen::VectorXd m_scalings; // inv surface areas/perimeter
	RowMatrixXi m_bnd_edges; // boundary edges
	Eigen::VectorXi m_bnd_verts; // boundary vertices

	// Mappings
	std::vector<std::vector<int> > m_V_graph; // vertex-to-vertex connectivity
	std::unordered_map<std::string, int> m_faces_map; // inds to face, [f0,f1,f2] -> f, f0<f1<f2
	std::unordered_map<std::string, int> m_tets_map; // inds to tet, [t0,t1,...] -> t, t0<t1<...
	std::unordered_map<std::string, Eigen::Vector2i> m_E_to_F; // adj faces, [e0,e1] -> [f0,f1]

}; // class MeshData

} // ns mcl

#endif

max_stars_repo_name: mattoverby/mclapp

max_issues_repo_name: mattoverby/mclapp

max_forks_repo_name: mattoverby/mclapp


text:
#include "WcsConvenience.h"
#include "WcsException.h"
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/spirit/include/qi.hpp>
#include <macgyver/TimeParser.h>
#include <cctype>
#include <sstream>

namespace SmartMet
{
namespace Plugin
{
namespace WCS
{
std::string xmlEscape(const std::string& src)
{
  std::ostringstream output;

  for (char c : src)
  {
    switch (c)
    {
      case '<':
        output << "<";
        break;
      case '>':
        output << ">";
        break;
      case '&':
        output << "&";
        break;
      case '\'':
        output << "'";
        break;
      case '"':
        output << """;
        break;
      default:
        output << c;
        break;
    }
  }

  return output.str();
}

std::string getMandatoryHeader(const SmartMet::Spine::HTTP::Request& request,
                               const std::string& name)
{
  auto value = request.getHeader(name);
  if (not value)
  {
    std::ostringstream msg;
    msg << "Mandatory HTTP request header " << name << " missing";
    throw WcsException(WcsException::OPERATION_PARSING_FAILED, msg.str());
  }

  return *value;
}

void checkTimeInterval(const boost::posix_time::ptime& start,
                       const boost::posix_time::ptime& end,
                       double maxHours)
{
  namespace pt = boost::posix_time;

  if (start > end)
  {
    std::ostringstream msg;
    msg << "Invalid time interval: starttime is greater than endtime"
        << " (found starttime='" << pt::to_simple_string(start) << "' endtime='"
        << pt::to_simple_string(end) << "'";
    throw WcsException(WcsException::OPERATION_PARSING_FAILED, msg.str());
  }

  pt::time_duration intervalLength = end - start;
  int miHours = static_cast<int>(std::floor(maxHours));
  int miSec = static_cast<int>(std::floor(3600.0 * (maxHours - miHours)));
  if (intervalLength > pt::hours(miHours) + pt::seconds(miSec))
  {
    std::ostringstream msg;
    msg << "Too long time interval '" << pt::to_simple_string(start) << "' to '"
        << pt::to_simple_string(end) << "' specified"
        << " (no more than " << maxHours << " hours allowed)";
    throw WcsException(WcsException::OPERATION_PROCESSING_FAILED, msg.str());
  }
}

void assertUnreachable(const char* file, int line)
{
  std::ostringstream msg;
  msg << "INTERNAL ERROR in " << file << " at line " << line << ": not supposed to get here";
  throw std::runtime_error(msg.str());
}

std::string asString(const std::vector<Spine::Value>& src)
{
  std::ostringstream ost;
  ost << "(ValueArray ";
  for (const auto& item : src)
  {
    ost << item;
  }
  ost << ")";
  return ost.str();
}

std::string asString(const boost::variant<Spine::Value, std::vector<Spine::Value> >& src)
{
  std::ostringstream ost;
  if (src.which() == 0)
  {
    ost << boost::get<Spine::Value>(src);
  }
  else
  {
    ost << asString(boost::get<std::vector<Spine::Value> >(src));
  }
  return ost.str();
}

std::string removeTrailing0(const std::string& src)
{
  std::string tmp = boost::algorithm::trim_copy(src);
  if ((tmp.find_first_not_of("+-.0123456789") == std::string::npos) and
      (tmp.find('.') != std::string::npos))
  {
    const char* c1 = tmp.c_str();
    const char* c2 = c1 + tmp.length();
    while (*(c2 - 1) == '0' and std::isdigit(*(c2 - 2)))
      c2--;
    return std::string(c1, c2);
  }
  else
  {
    return src;
  }
}

NFmiPoint transform(const std::unique_ptr<OGRCoordinateTransformation>& transformation,
                    const NFmiPoint& p)
{
  double x = p.X();
  double y = p.Y();
  if (not transformation->Transform(1, &x, &y))
  {
    std::ostringstream msg;
    msg << "Transformation failed from '" << transformation->GetSourceCS()->GetEPSGGeogCS()
        << "' to '" << transformation->GetTargetCS()->GetEPSGGeogCS() << "'.";
    WcsException err(WcsException::NO_APPLICABLE_CODE, msg.str());
    throw err;
  }

  return NFmiPoint(x, y);
}

std::int64_t unixTimeFromPtime(const boost::posix_time::ptime& epoch)
{
  static const long refJd = boost::gregorian::date(1970, 1, 1).julian_day();
  long long jd = epoch.date().julian_day();
  long seconds = epoch.time_of_day().total_seconds();
  INT_64 secEpoch = 86400LL * (jd - refJd) + seconds;
  return secEpoch;
}

boost::posix_time::ptime ptimeFromUnixTime(const std::int64_t& unixTime)
{
  boost::gregorian::date d(1970, 1, 1);
  return (boost::posix_time::ptime(d) + boost::posix_time::seconds(unixTime));
}

NFmiPoint swap(const NFmiPoint& p, const bool& swap)
{
  return (swap ? NFmiPoint(p.Y(), p.X()) : p);
}
}  // namespace WCS
}  // namespace Plugin
}  // namespace SmartMet

max_stars_repo_name: fmidev/smartmet-plugin-wcs

max_issues_repo_name: fmidev/smartmet-plugin-wcs

max_forks_repo_name: fmidev/smartmet-plugin-wcs


text: #include <boost/fusion/include/replace_if.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**
 * Copyright (C) 2015 Dato, Inc.
 * All rights reserved.
 *
 * This software may be modified and distributed under the terms
 * of the BSD license. See the LICENSE file for details.
 */
/*
 * Copyright (c) 2009 Carnegie Mellon University.
 *     All rights reserved.
 *
 *  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.
 *
 * For more about this software visit:
 *
 *      http://www.graphlab.ml.cmu.edu
 *
 */

#ifndef GRAPHLAB_BLOCK_LINK_LIST_HPP
#define GRAPHLAB_BLOCK_LINK_LIST_HPP
#include <graphlab/util/generics/dynamic_block.hpp>
#include <logger/assertions.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/iterator/iterator_adaptor.hpp>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/utility/enable_if.hpp>

#include <stdint.h>
#include <algorithm>

namespace graphlab {
  template<typename valuetype, uint32_t blocksize=(4096-20)/sizeof(valuetype)>
  /**
   * This class represents a forward linked list of dynamic block.
   */
  class block_linked_list {
   public:
     typedef dynamic_block<valuetype, blocksize> blocktype;

   //////////////////// Constructors /////////////////////////
   public:
     /// Construct empty list
     block_linked_list() : head(NULL), tail(NULL), _size(0) { }

     /// Construct list from container
     template<typename InputIterator>
     block_linked_list(InputIterator first, InputIterator last) {
       if (first == last)
         return;
       assign(first, last);
     }

     /// Destructor
     ~block_linked_list() { clear(); }

     /**
      * Assign the list with values from given iterator pair.
      */
     template<typename InputIterator>
     void assign(InputIterator first, InputIterator last)  {

       size_t new_size = last - first;
       if (new_size == 0)
         return;

       if (_size > 0)
         clear();

       InputIterator iter = first;

       blocktype* current = head;
       // if the list is empty, create the head block.
       if (current == NULL) {
         current = head = tail = new blocktype();
       }

       while (iter != last) {
         InputIterator end =  std::min(iter+blocksize, last);
         current->assign(iter, end);
         iter = end;
         if (iter != last) {
           current = new blocktype();
           tail->_next = current;
           tail = current;
         }
       }
       _size = new_size;
     }

     /// Returns the size of the list
     size_t size() const { return _size; }

     static const size_t get_blocksize() {
       return blocksize;
     }

   //////////////////// Iterator API /////////////////////////
   public:
     /**
      * Defines the iterator of the values stored in the list.
      * The iterator has random_access_traversal_tag, however
      * the actual random access takes O(n/blocksize);
      */
     template <typename value>
     class value_iterator :
         public boost::iterator_facade<value_iterator<value>, value,
                                       boost::random_access_traversal_tag> {
     private:
        struct enabler {};

     public:
        value_iterator(blocktype* blockptr, uint32_t offset) :
            blockptr(blockptr), offset(offset) { }

        template <typename othervalue>
            value_iterator(value_iterator<othervalue> const& other,
                        typename boost::enable_if<
                        boost::is_convertible<othervalue*,value*>,
                        enabler>::type = enabler())
            : blockptr(other.blockptr), offset(other.offset) { }

     public:
        // public wrapper of the private distance_to
      ptrdiff_t pdistance_to(const value_iterator& other) const {
        return distance_to(other);
      }

      // core access functions
      private:
        friend class boost::iterator_core_access;
        template <class> friend class value_iterator;

        /////////////////  Forward traversal core functions ///////////////
        void increment() {
          if (offset < blockptr->size()-1) {
            ++offset;
          } else {
            blockptr = blockptr->_next;
            offset = 0;
          }
        }

        template <typename othervalue>
        bool equal(value_iterator<othervalue> const& other) const {
          return (blockptr == other.blockptr) && (offset == other.offset);
        }

        value& dereference() const {
          return blockptr->values[offset];
        }

        /////////////////  Random access core functions ///////////////
        void advance(int n) {
          size_t dist = n+offset;
          while(dist >= blockptr->size() && blockptr != NULL) {
            dist -= blockptr->size();
            blockptr = blockptr->next();
          }
          if (blockptr == NULL) {
            offset = 0;
          } else {
            offset = dist;
          }
        }

        ptrdiff_t distance_to(const value_iterator& other) const {
          ptrdiff_t dist = 0;
          if (blockptr == other.blockptr) {
            return ((ptrdiff_t)other.offset - offset);
          } else {
            blocktype* cur = blockptr;
            // try moving forward until we hit other or NULL
            while (cur != NULL && cur != other.blockptr) {
              dist += cur->size();
              cur = cur->next();
            }

            // this catched other
            if (cur != NULL || other.blockptr == NULL) {
              return (dist + (ptrdiff_t)other.offset - offset);
            } else {
              logstream(LOG_INFO)<< "block list iterator reverse direction!!" << std::endl;
              // this hit the dead end, need to move backwards
              dist = 0;
              cur = other.blockptr;
              while (cur != NULL && cur != blockptr) {
                dist += cur->size();
                cur = cur->next();
              }
              return -(dist + (ptrdiff_t)offset - other.offset);
            }
          }
        }

     // For internal use only. Get access to the internal block pointer and offset.
     public:
        // returns block pinter
        blocktype*& get_blockptr() {
          return blockptr;
        }
        uint32_t& get_offset() {
          return offset;
        }

      private:
        blocktype* blockptr;
        uint32_t offset;
     }; // end of value iterator

     typedef value_iterator<valuetype> iterator;
     typedef value_iterator<valuetype const> const_iterator;

     iterator begin() {
       return iterator(head, 0);
     }

     iterator end() {
       return iterator(NULL, 0);
     }

     const_iterator begin() const {
       return const_iterator(head, 0);
     }

     const_iterator end() const {
       return const_iterator(NULL, 0);
     }

   //////////////////// Insertion API /////////////////////////
   /*
    * Insert value into the location of iter.
    * Split the block when necessary.
    * Returns iterator to the new value.
    */
   iterator insert(iterator iter, const valuetype& val) {
     iterator ins_iter = get_insert_iterator(iter);
     blocktype* ins_ptr = ins_iter.get_blockptr();
     uint32_t offset = ins_iter.get_offset();
     ASSERT_TRUE(ins_ptr != NULL);
     if (ins_ptr->is_full()) {
       // split the block
       ins_ptr->split();
       if(ins_ptr == tail) {
         // update tail pointer
         tail = ins_ptr->next();
       }
       if (offset >= blocksize/2) {
         ins_ptr = ins_ptr->next();
         offset -= (blocksize/2);
       }
     }
     ins_ptr->insert(val,offset);
     ++_size;
     return iterator(ins_ptr, offset);
   }

   /**
    * Insert a range of values into the position of the given iterator.
    * Will create new blocks after the given block when necessary.
    *
    * Returns the begin and end iterator to the new elements.
    *
    * \note
    * This operation will NOT affect the blocks after the given block.
    * |x1,x2,y1,y2,y3,y4 , _ , _ , _ , _| -> | ... | -> |...|
    *        ^
    *        p
    * blocksize = 10
    * iterator: blockptr = p, offset = 2
    */
   template<typename InputIterator>
   std::pair<iterator, iterator>
     insert(iterator iter, InputIterator first, InputIterator last) {

     typedef std::pair<iterator, iterator> ret_type;
     const size_t len = last - first;
     if (len == 0) return ret_type(iter, iter);

     iterator ins_iter = get_insert_iterator(iter);

     // Pointers to the block of the insertion point.
     blocktype* ibegin_ptr = ins_iter.get_blockptr();
     // number of elements before the insertion point in the block
     size_t nx = ins_iter.get_offset();
     // number of elements after the insertion point in the block
     size_t ny = ibegin_ptr->size()-nx;

     // save ys
     valuetype* swap = (valuetype*)malloc((ny)*sizeof(valuetype));
     memcpy(swap, &(ibegin_ptr->values[nx]), ny*sizeof(valuetype)) ;

     // remove y temporarily
     ibegin_ptr->_size -= ny;
     _size -= ny;

     // Insert new elements to the end of the block,
     // record the begin and end iterators
     ret_type iter_pair = append_to_block(ibegin_ptr, first, last);

     iterator begin_ins_iter = iter_pair.first;
     iterator end_ins_iter = iter_pair.second;
     // the end iterator returned by append_to_block may need adjustment
     if (end_ins_iter.get_offset() == end_ins_iter.get_blockptr()->size()) {
       end_ins_iter.get_blockptr() = end_ins_iter.get_blockptr()->next();
       end_ins_iter.get_offset() = 0;
     }

     // add y back
     if (ny > 0) {
       blocktype* iend_ptr = iter_pair.second.get_blockptr();
       ret_type iter_pair2 = append_to_block(iend_ptr, swap, swap+ny);
       end_ins_iter = iter_pair2.first;
     }

     return ret_type(begin_ins_iter, end_ins_iter);
   }

   /*
    * Move up the content of the next block to the end of this block.
    * Delete the next block if it becomes empty.
    */
   void merge_next(blocktype* bptr) {
     if (bptr == NULL || bptr->next() == NULL || bptr->is_full()) {
       return;
     }
     blocktype* nextptr = bptr->next();
     size_t spaceleft = blocksize - bptr->size(); // num space left
     size_t nnext = nextptr->size(); // num elems in the next block
     size_t nmove = std::min(spaceleft, nnext); // num elems to move

     // move up nmove elements
     std::copy(nextptr->values, nextptr->values+nmove,
               bptr->values + bptr->_size);
     if (nnext > nmove) {
       valuetype* p = nextptr->values;
       for (size_t i = 0; i < (nnext-nmove); ++i) {
         *(p+i) = *(p+i+nmove);
       }
     }

     // update the size
     bptr->_size += nmove;
     nextptr->_size -= nmove;

     // remove the next block if empty
     if (nextptr->size() == 0) {
       bptr->_next = nextptr->next();
       if (nextptr == tail) {
         tail = bptr;
       }
       delete nextptr;
     }
   }

   /// Repack the space for a given key
   void repack(iterator begin_iter, iterator end_iter) {
     blocktype* bptr = begin_iter.get_blockptr();
     blocktype* eptr = end_iter.get_blockptr();

     if (bptr == NULL || bptr == eptr) {
       return;
     }
     while (bptr != eptr && bptr->next() != eptr) {
       merge_next(bptr);
       if (bptr->is_full())  {
         bptr = bptr->next();
       }
     }
    }

   //////////////////// Block Access API /////////////////////////
   /*
    * Returns the nth block in the list. Linear time.
    */
   blocktype* get_block(size_t n) {
     size_t i = 0;
     blocktype* cur = head;
     while (cur != NULL && i < n) {
       cur = cur->_next;
       ++i;
     }
     return cur;
   }

   size_t num_blocks() const {
     if (head == NULL)
       return 0;
     size_t ret = 1;
     blocktype* ptr = head;
     while (ptr != tail) {
       ptr = ptr->next();
       ++ret;
     }
     return ret;
   }

   //////////////////// Pretty print API /////////////////////////
   void print(std::ostream& out) const {
     blocktype* cur = head;
     while (cur != NULL) {
       cur->print(out);
       out << "-> ";
       cur = cur->_next;
     }
     out << "||" << std::endl;
   }

   //////////////////// Read Write /////////////////////////
     void swap (block_linked_list& other) {
       clear();
       delete head;
       head = other.head;
       tail = other.tail;
       _size = other._size;
       other.head = other.tail = NULL;
       other._size = 0;
     }

     void clear() {
       blocktype* tmp = NULL;
       while(head != tail) {
         ASSERT_TRUE(head != NULL);
         tmp = head;
         head = head->_next;
         delete tmp;
       }
       delete head;
       head = tail = NULL;
       _size = 0;
     }

     void save(oarchive& oarc) const {
       serialize_iterator(oarc, begin(), end(), size());
     }

   //////////////////// Helper Function /////////////////////////
   private:
   /**
    * \internal
    * Allocate new space for insertion if the iterator is end.
    * Return the iterator to the new space.
    */
   iterator get_insert_iterator(iterator iter) {
     bool is_end = (iter == end());
     if (is_end) {
       if (tail == NULL) {
         head = tail = new blocktype();
       } else if (tail->is_full()) {
         append_block();
       }
       iter.get_blockptr() = tail;
       iter.get_offset() = tail->size();
     }
     return iter;
   }

   blocktype* insert_block(blocktype* ins) {
     blocktype* ret = new blocktype();
     ret->_next = ins->next();
     ins->_next = ret;
     if (ins == tail) {
       tail = ret;
     }
     return ret;
   }

   blocktype* append_block() {
     return insert_block(tail);
   }

   /**
    * \internal
    * Insert a range of values into the end of the given block.
    * Will create new blocks after the given block when necessary.
    *
    * \note
    * This operation will NOT affect the blocks after the given block.
    *
    * Returns the begin and end iterator to the new elements.
    *
    * \note
    * The end iterator does jump to the next block. Instead, it points at the
    * memory of last_block->size().
    */
  template<typename InputIterator>
  std::pair<iterator, iterator>
     append_to_block(blocktype* ibegin_ptr, InputIterator first, InputIterator last) {
     ASSERT_TRUE(ibegin_ptr != NULL);
     const size_t len = last-first;

     /// If nothing to append, return the begin location
     if (len == 0) {
       iterator ret(ibegin_ptr, ibegin_ptr->size());
       return std::pair<iterator, iterator>(ret, ret);
     }

     /// elements to return
     blocktype* iend_ptr = ibegin_ptr;
     uint32_t ibegin_offset, iend_offset;

     // create a new block if the current is full
     if (ibegin_ptr->is_full()) {
       ibegin_ptr = insert_block(ibegin_ptr);
     }

     /// Fill in the rest of the current block
     size_t nold = ibegin_ptr->size(); // num of old elements
     size_t spaceleft = (blocksize - nold);  // room left
     size_t nnew = std::min(len, spaceleft); // num of new elements to insert
     ASSERT_TRUE(nold+nnew <= blocksize);
     ASSERT_TRUE(nnew > 0);
     std::copy(first, first+nnew, &(ibegin_ptr->values[nold]));
     ibegin_ptr->_size += nnew;
     ibegin_offset = nold;
     iend_ptr = ibegin_ptr;
     iend_offset = ibegin_ptr->size();

     // Creates a block chain for remaining elements
     if (len > spaceleft) {
       blocktype* current = insert_block(ibegin_ptr);
       InputIterator iter = first + spaceleft;
       while (iter != last) {
         InputIterator end =  std::min(iter+blocksize, last);
         current->assign(iter, end);
         iter = end;
         if (iter != last) {
           current = insert_block(current);
         }
       }
       iend_ptr = current;
       iend_offset = current->size();
     }
     _size += len;

     return std::pair<iterator,iterator>(
         iterator(ibegin_ptr, ibegin_offset)
         ,iterator(iend_ptr, iend_offset));
   }

  // Disable copy constructor
    block_linked_list(const block_linked_list& that) = delete;
    block_linked_list& operator=(const block_linked_list& that) = delete;

   //////////////////// Private Data Member /////////////////////////
   private:
     blocktype* head;
     blocktype* tail;
     size_t _size;
  };
} // end of namespace
#endif

     // }
     // else {
     //   blocktype* splitblk = insert_block(ibegin_ptr);
     //   size_t nfirst = (nold+nnew)/2;
     //   size_t nsecond = (nold+nnew-nfirst);
     //   ibegin_ptr->_size = nfirst;
     //   splitblk->_size = nsecond;
     //   if (nold < nfirst) {
     //     size_t padsize = nfirst - nold;
     //     std::copy(first, first+padsize, &(ibegin_ptr->values[nold]));
     //     std::copy(first+padsize, first+nnew, splitblk->values);
     //     ibegin_offset = nold;
     //   } else {
     //     size_t padsize = nold-nfirst;
     //     memcpy(splitblk->values, &(ibegin_ptr->values[nfirst]), padsize*sizeof(valuetype));
     //     std::copy(first, first+nnew, &(splitblk->values[padsize]));
     //     ibegin_ptr = splitblk;
     //     ibegin_offset = padsize;
     //  }
       // if (!add_new_blocks) {
       //    iend_ptr = splitblk;
       //    iend_offset = nsecond;
       // }
     // }

max_stars_repo_name: parquette/ParFrame

max_issues_repo_name: parquette/ParFrame

max_forks_repo_name: parquette/ParFrame


text:
//  (C) Copyright Edward Diener 2011-2015
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).

#if !defined(BOOST_VMD_DETAIL_MODS_HPP)
#define BOOST_VMD_DETAIL_MODS_HPP

#include <boost/preprocessor/arithmetic/inc.hpp>
#include <boost/preprocessor/comparison/equal.hpp>
#include <boost/preprocessor/comparison/greater.hpp>
#include <boost/preprocessor/control/iif.hpp>
#include <boost/preprocessor/control/while.hpp>
#include <boost/preprocessor/punctuation/is_begin_parens.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/tuple/pop_front.hpp>
#include <boost/preprocessor/tuple/push_back.hpp>
#include <boost/preprocessor/tuple/replace.hpp>
#include <boost/preprocessor/tuple/size.hpp>
#include <boost/preprocessor/variadic/to_tuple.hpp>
#include <boost/vmd/identity.hpp>
#include <boost/vmd/is_empty.hpp>
#include <boost/vmd/is_type.hpp>
#include <boost/vmd/detail/modifiers.hpp>

#define BOOST_VMD_DETAIL_MODS_NO_RETURN 0
#define BOOST_VMD_DETAIL_MODS_RETURN 1
#define BOOST_VMD_DETAIL_MODS_RETURN_TUPLE 2
#define BOOST_VMD_DETAIL_MODS_RETURN_ARRAY 3
#define BOOST_VMD_DETAIL_MODS_RETURN_LIST 4
#define BOOST_VMD_DETAIL_MODS_NO_AFTER 0
#define BOOST_VMD_DETAIL_MODS_RETURN_AFTER 1
#define BOOST_VMD_DETAIL_MODS_NO_INDEX 0
#define BOOST_VMD_DETAIL_MODS_RETURN_INDEX 1
#define BOOST_VMD_DETAIL_MODS_NO_ONLY_AFTER 0
#define BOOST_VMD_DETAIL_MODS_RETURN_ONLY_AFTER 1

#define BOOST_VMD_DETAIL_MODS_TUPLE_RETURN 0
#define BOOST_VMD_DETAIL_MODS_TUPLE_AFTER 1
#define BOOST_VMD_DETAIL_MODS_TUPLE_INDEX 2
#define BOOST_VMD_DETAIL_MODS_TUPLE_OTHER 3
#define BOOST_VMD_DETAIL_MODS_TUPLE_ONLY_AFTER 4
#define BOOST_VMD_DETAIL_MODS_TUPLE_TYPE 5

#define BOOST_VMD_DETAIL_MODS_DATA_INPUT 0
#define BOOST_VMD_DETAIL_MODS_DATA_INDEX 1
#define BOOST_VMD_DETAIL_MODS_DATA_SIZE 2
#define BOOST_VMD_DETAIL_MODS_DATA_RESULT 3
#define BOOST_VMD_DETAIL_MODS_DATA_ALLOW 4

#define BOOST_VMD_DETAIL_MODS_STATE_INPUT(state) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_DATA_INPUT,state) \
/**/

#define BOOST_VMD_DETAIL_MODS_STATE_INDEX(state) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_DATA_INDEX,state) \
/**/

#define BOOST_VMD_DETAIL_MODS_STATE_SIZE(state) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_DATA_SIZE,state) \
/**/

#define BOOST_VMD_DETAIL_MODS_STATE_RESULT(state) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_DATA_RESULT,state) \
/**/

#define BOOST_VMD_DETAIL_MODS_STATE_ALLOW(state) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_DATA_ALLOW,state) \
/**/

#define BOOST_VMD_DETAIL_MODS_STATE_IS_ALLOW_ALL(state) \
    BOOST_VMD_DETAIL_IS_ALLOW_ALL(BOOST_VMD_DETAIL_MODS_STATE_ALLOW(state)) \
/**/

#define BOOST_VMD_DETAIL_MODS_STATE_IS_ALLOW_RETURN(state) \
    BOOST_VMD_DETAIL_IS_ALLOW_RETURN(BOOST_VMD_DETAIL_MODS_STATE_ALLOW(state)) \
/**/

#define BOOST_VMD_DETAIL_MODS_STATE_IS_ALLOW_AFTER(state) \
    BOOST_VMD_DETAIL_IS_ALLOW_AFTER(BOOST_VMD_DETAIL_MODS_STATE_ALLOW(state)) \
/**/

#define BOOST_VMD_DETAIL_MODS_STATE_IS_ALLOW_INDEX(state) \
    BOOST_VMD_DETAIL_IS_ALLOW_INDEX(BOOST_VMD_DETAIL_MODS_STATE_ALLOW(state)) \
/**/

#define BOOST_VMD_DETAIL_MODS_STATE_CURRENT(state) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_STATE_INDEX(state),BOOST_VMD_DETAIL_MODS_STATE_INPUT(state)) \
/**/

#define BOOST_VMD_DETAIL_MODS_STATE_TYPE(state) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_TUPLE_RETURN,BOOST_VMD_DETAIL_MODS_STATE_RESULT(state)) \
/**/

#define BOOST_VMD_DETAIL_MODS_STATE_AFTER(state) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_TUPLE_AFTER,BOOST_VMD_DETAIL_MODS_STATE_RESULT(state)) \
/**/

#define BOOST_VMD_DETAIL_MODS_STATE_ONLY_AFTER(state) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_TUPLE_ONLY_AFTER,BOOST_VMD_DETAIL_MODS_STATE_RESULT(state)) \
/**/

#define BOOST_VMD_DETAIL_MODS_STATE_TINDEX(state) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_TUPLE_INDEX,BOOST_VMD_DETAIL_MODS_STATE_RESULT(state)) \
/**/

#define BOOST_VMD_DETAIL_MODS_RESULT_RETURN_TYPE(result) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_TUPLE_RETURN,result) \
/**/

#define BOOST_VMD_DETAIL_MODS_IS_RESULT_AFTER(result) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_TUPLE_AFTER,result) \
/**/

#define BOOST_VMD_DETAIL_MODS_IS_RESULT_ONLY_AFTER(result) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_TUPLE_ONLY_AFTER,result) \
/**/

#define BOOST_VMD_DETAIL_MODS_IS_RESULT_INDEX(result) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_TUPLE_INDEX,result) \
/**/

#define BOOST_VMD_DETAIL_MODS_RESULT_OTHER(result) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_TUPLE_OTHER,result) \
/**/

#define BOOST_VMD_DETAIL_MODS_RESULT_TYPE(result) \
    BOOST_PP_TUPLE_ELEM(BOOST_VMD_DETAIL_MODS_TUPLE_TYPE,result) \
/**/

#define BOOST_VMD_DETAIL_MODS_PRED(d,state) \
    BOOST_PP_GREATER_D(d,BOOST_VMD_DETAIL_MODS_STATE_SIZE(state),BOOST_VMD_DETAIL_MODS_STATE_INDEX(state))
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_RETURN_TYPE(d,state,number) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_UPDATE \
        ( \
        d, \
        BOOST_PP_TUPLE_REPLACE_D \
            ( \
            d, \
            state, \
            BOOST_VMD_DETAIL_MODS_DATA_RESULT, \
            BOOST_PP_TUPLE_REPLACE_D \
                ( \
                d, \
                BOOST_VMD_DETAIL_MODS_STATE_RESULT(state), \
                BOOST_VMD_DETAIL_MODS_TUPLE_RETURN, \
                number \
                ) \
            ) \
        ) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_ONLY_AFTER(d,state,id) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_UPDATE \
        ( \
        d, \
        BOOST_PP_TUPLE_REPLACE_D \
            ( \
            d, \
            state, \
            BOOST_VMD_DETAIL_MODS_DATA_RESULT, \
            BOOST_PP_TUPLE_REPLACE_D \
                ( \
                d, \
                BOOST_PP_TUPLE_REPLACE_D \
                    ( \
                    d, \
                    BOOST_VMD_DETAIL_MODS_STATE_RESULT(state), \
                    BOOST_VMD_DETAIL_MODS_TUPLE_ONLY_AFTER, \
                    1 \
                    ), \
                BOOST_VMD_DETAIL_MODS_TUPLE_AFTER, \
                1 \
                ) \
            ) \
        ) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_INDEX(d,state,number) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_UPDATE \
        ( \
        d, \
        BOOST_PP_TUPLE_REPLACE_D \
            ( \
            d, \
            state, \
            BOOST_VMD_DETAIL_MODS_DATA_RESULT, \
            BOOST_PP_TUPLE_REPLACE_D \
                ( \
                d, \
                BOOST_VMD_DETAIL_MODS_STATE_RESULT(state), \
                BOOST_VMD_DETAIL_MODS_TUPLE_INDEX, \
                number \
                ) \
            ) \
        ) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_GTT(d,state,id) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_RETURN_TYPE(d,state,BOOST_VMD_DETAIL_MODS_RETURN_TUPLE) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_ET(d,state,id) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_RETURN_TYPE(d,state,BOOST_VMD_DETAIL_MODS_RETURN) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_SA(d,state,id) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_RETURN_TYPE(d,state,BOOST_VMD_DETAIL_MODS_RETURN_ARRAY) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_SL(d,state,id) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_RETURN_TYPE(d,state,BOOST_VMD_DETAIL_MODS_RETURN_LIST) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_NT(d,state,id) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_RETURN_TYPE(d,state,BOOST_VMD_DETAIL_MODS_NO_RETURN) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_AFT(d,state,id) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_UPDATE \
        ( \
        d, \
        BOOST_PP_TUPLE_REPLACE_D \
            ( \
            d, \
            state, \
            BOOST_VMD_DETAIL_MODS_DATA_RESULT, \
            BOOST_PP_TUPLE_REPLACE_D \
                ( \
                d, \
                BOOST_VMD_DETAIL_MODS_STATE_RESULT(state), \
                BOOST_VMD_DETAIL_MODS_TUPLE_AFTER, \
                BOOST_VMD_DETAIL_MODS_RETURN_AFTER \
                ) \
            ) \
        ) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_NOAFT(d,state,id) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_UPDATE \
        ( \
        d, \
        BOOST_PP_TUPLE_REPLACE_D \
            ( \
            d, \
            state, \
            BOOST_VMD_DETAIL_MODS_DATA_RESULT, \
            BOOST_PP_TUPLE_REPLACE_D \
                ( \
                d, \
                BOOST_PP_TUPLE_REPLACE_D \
                    ( \
                    d, \
                    BOOST_VMD_DETAIL_MODS_STATE_RESULT(state), \
                    BOOST_VMD_DETAIL_MODS_TUPLE_ONLY_AFTER, \
                    0 \
                    ), \
                BOOST_VMD_DETAIL_MODS_TUPLE_AFTER, \
                BOOST_VMD_DETAIL_MODS_NO_AFTER \
                ) \
            ) \
        ) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_IND(d,state,id) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_INDEX(d,state,BOOST_VMD_DETAIL_MODS_RETURN_INDEX) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_NO_IND(d,state,id) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_INDEX(d,state,BOOST_VMD_DETAIL_MODS_NO_INDEX) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN_CTUPLE_REPLACE(d,state,id) \
    BOOST_PP_TUPLE_REPLACE_D \
        ( \
        d, \
        BOOST_VMD_DETAIL_MODS_STATE_RESULT(state), \
        BOOST_VMD_DETAIL_MODS_TUPLE_OTHER, \
        BOOST_PP_VARIADIC_TO_TUPLE(id) \
        ) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN_CTUPLE_ADD(d,state,id) \
    BOOST_PP_TUPLE_REPLACE_D \
        ( \
        d, \
        BOOST_VMD_DETAIL_MODS_STATE_RESULT(state), \
        BOOST_VMD_DETAIL_MODS_TUPLE_OTHER, \
        BOOST_PP_TUPLE_PUSH_BACK \
            ( \
            BOOST_VMD_DETAIL_MODS_RESULT_OTHER(BOOST_VMD_DETAIL_MODS_STATE_RESULT(state)), \
            id \
            ) \
        ) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN_CTUPLE(d,state,id) \
    BOOST_PP_IIF \
        ( \
        BOOST_VMD_IS_EMPTY \
            ( \
            BOOST_VMD_DETAIL_MODS_RESULT_OTHER(BOOST_VMD_DETAIL_MODS_STATE_RESULT(state)) \
            ), \
        BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN_CTUPLE_REPLACE, \
        BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN_CTUPLE_ADD \
        ) \
    (d,state,id) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN_TYPE_RETURN(d,state,id) \
    BOOST_PP_TUPLE_REPLACE_D \
        ( \
        d, \
        BOOST_VMD_DETAIL_MODS_STATE_RESULT(state), \
        BOOST_VMD_DETAIL_MODS_TUPLE_RETURN, \
        BOOST_PP_IIF \
            ( \
            BOOST_VMD_DETAIL_EQUAL_TYPE_D(d,id,BOOST_VMD_TYPE_ARRAY), \
            BOOST_VMD_DETAIL_MODS_RETURN_ARRAY, \
            BOOST_PP_IIF \
                ( \
                BOOST_VMD_DETAIL_EQUAL_TYPE_D(d,id,BOOST_VMD_TYPE_LIST), \
                BOOST_VMD_DETAIL_MODS_RETURN_LIST, \
                BOOST_VMD_DETAIL_MODS_RETURN_TUPLE \
                ) \
            ) \
        ) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN_TYPE(d,state,id) \
    BOOST_PP_TUPLE_REPLACE_D \
        ( \
        d, \
        BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN_TYPE_RETURN(d,state,id), \
        BOOST_VMD_DETAIL_MODS_TUPLE_TYPE, \
        id \
        ) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN(d,state,id) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_UPDATE \
        ( \
        d, \
        BOOST_PP_TUPLE_REPLACE_D \
            ( \
            d, \
            state, \
            BOOST_VMD_DETAIL_MODS_DATA_RESULT, \
            BOOST_PP_IIF \
                ( \
                BOOST_PP_BITAND \
                    ( \
                    BOOST_VMD_DETAIL_MODS_STATE_IS_ALLOW_ALL(state), \
                    BOOST_VMD_IS_TYPE_D(d,id) \
                    ), \
                BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN_TYPE, \
                BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN_CTUPLE \
                ) \
            (d,state,id) \
            ) \
        ) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_UPDATE(d,state) \
    BOOST_PP_TUPLE_REPLACE_D \
        ( \
        d, \
        state, \
        BOOST_VMD_DETAIL_MODS_DATA_INDEX, \
        BOOST_PP_INC(BOOST_VMD_DETAIL_MODS_STATE_INDEX(state)) \
        ) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_ALLOW_ALL(d,state,id) \
    BOOST_PP_IIF \
        ( \
        BOOST_VMD_DETAIL_IS_RETURN_TYPE_TUPLE(id), \
        BOOST_VMD_DETAIL_MODS_OP_CURRENT_GTT, \
        BOOST_PP_IIF \
            ( \
            BOOST_VMD_DETAIL_IS_RETURN_TYPE(id), \
            BOOST_VMD_DETAIL_MODS_OP_CURRENT_ET, \
            BOOST_PP_IIF \
                ( \
                BOOST_VMD_DETAIL_IS_RETURN_TYPE_ARRAY(id), \
                BOOST_VMD_DETAIL_MODS_OP_CURRENT_SA, \
                BOOST_PP_IIF \
                    ( \
                    BOOST_VMD_DETAIL_IS_RETURN_TYPE_LIST(id), \
                    BOOST_VMD_DETAIL_MODS_OP_CURRENT_SL, \
                    BOOST_PP_IIF \
                        ( \
                        BOOST_VMD_DETAIL_IS_RETURN_NO_TYPE(id), \
                        BOOST_VMD_DETAIL_MODS_OP_CURRENT_NT, \
                        BOOST_PP_IIF \
                            ( \
                            BOOST_VMD_DETAIL_IS_RETURN_AFTER(id), \
                            BOOST_VMD_DETAIL_MODS_OP_CURRENT_AFT, \
                            BOOST_PP_IIF \
                                ( \
                                BOOST_VMD_DETAIL_IS_RETURN_NO_AFTER(id), \
                                BOOST_VMD_DETAIL_MODS_OP_CURRENT_NOAFT, \
                                BOOST_PP_IIF \
                                    ( \
                                    BOOST_VMD_DETAIL_IS_RETURN_ONLY_AFTER(id), \
                                    BOOST_VMD_DETAIL_MODS_OP_CURRENT_ONLY_AFTER, \
                                    BOOST_PP_IIF \
                                        ( \
                                        BOOST_VMD_DETAIL_IS_RETURN_INDEX(id), \
                                        BOOST_VMD_DETAIL_MODS_OP_CURRENT_IND, \
                                        BOOST_PP_IIF \
                                            ( \
                                            BOOST_VMD_DETAIL_IS_RETURN_NO_INDEX(id), \
                                            BOOST_VMD_DETAIL_MODS_OP_CURRENT_NO_IND, \
                                            BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN \
                                            ) \
                                        ) \
                                    ) \
                                ) \
                            ) \
                        ) \
                    ) \
                ) \
            ) \
        ) \
    (d,state,id) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_ALLOW_RETURN(d,state,id) \
    BOOST_PP_IIF \
        ( \
        BOOST_VMD_DETAIL_IS_RETURN_TYPE_TUPLE(id), \
        BOOST_VMD_DETAIL_MODS_OP_CURRENT_GTT, \
        BOOST_PP_IIF \
            ( \
            BOOST_VMD_DETAIL_IS_RETURN_TYPE(id), \
            BOOST_VMD_DETAIL_MODS_OP_CURRENT_ET, \
            BOOST_PP_IIF \
                ( \
                BOOST_VMD_DETAIL_IS_RETURN_TYPE_ARRAY(id), \
                BOOST_VMD_DETAIL_MODS_OP_CURRENT_SA, \
                BOOST_PP_IIF \
                    ( \
                    BOOST_VMD_DETAIL_IS_RETURN_TYPE_LIST(id), \
                    BOOST_VMD_DETAIL_MODS_OP_CURRENT_SL, \
                    BOOST_PP_IIF \
                        ( \
                        BOOST_VMD_DETAIL_IS_RETURN_NO_TYPE(id), \
                        BOOST_VMD_DETAIL_MODS_OP_CURRENT_NT, \
                        BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN \
                        ) \
                    ) \
                ) \
            ) \
        ) \
    (d,state,id) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_ALLOW_AFTER(d,state,id) \
    BOOST_PP_IIF \
        ( \
        BOOST_VMD_DETAIL_IS_RETURN_AFTER(id), \
        BOOST_VMD_DETAIL_MODS_OP_CURRENT_AFT, \
        BOOST_PP_IIF \
            ( \
            BOOST_VMD_DETAIL_IS_RETURN_NO_AFTER(id), \
            BOOST_VMD_DETAIL_MODS_OP_CURRENT_NOAFT, \
            BOOST_PP_IIF \
                ( \
                BOOST_VMD_DETAIL_IS_RETURN_ONLY_AFTER(id), \
                BOOST_VMD_DETAIL_MODS_OP_CURRENT_ONLY_AFTER, \
                BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN \
                ) \
            ) \
        ) \
    (d,state,id) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_ALLOW_INDEX(d,state,id) \
    BOOST_PP_IIF \
        ( \
        BOOST_VMD_DETAIL_IS_RETURN_AFTER(id), \
        BOOST_VMD_DETAIL_MODS_OP_CURRENT_AFT, \
        BOOST_PP_IIF \
            ( \
            BOOST_VMD_DETAIL_IS_RETURN_NO_AFTER(id), \
            BOOST_VMD_DETAIL_MODS_OP_CURRENT_NOAFT, \
            BOOST_PP_IIF \
                ( \
                BOOST_VMD_DETAIL_IS_RETURN_ONLY_AFTER(id), \
                BOOST_VMD_DETAIL_MODS_OP_CURRENT_ONLY_AFTER, \
                BOOST_PP_IIF \
                    ( \
                    BOOST_VMD_DETAIL_IS_RETURN_INDEX(id), \
                    BOOST_VMD_DETAIL_MODS_OP_CURRENT_IND, \
                    BOOST_PP_IIF \
                        ( \
                        BOOST_VMD_DETAIL_IS_RETURN_NO_INDEX(id), \
                        BOOST_VMD_DETAIL_MODS_OP_CURRENT_NO_IND, \
                        BOOST_VMD_DETAIL_MODS_OP_CURRENT_UNKNOWN \
                        ) \
                    ) \
                ) \
            ) \
        ) \
    (d,state,id) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_ALLOW_UPDATE(d,state,id) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_UPDATE(d,state) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_ID(d,state,id) \
    BOOST_PP_IIF \
        ( \
        BOOST_VMD_DETAIL_MODS_STATE_IS_ALLOW_ALL(state), \
        BOOST_VMD_DETAIL_MODS_OP_CURRENT_ALLOW_ALL, \
        BOOST_PP_IIF \
            ( \
            BOOST_VMD_DETAIL_MODS_STATE_IS_ALLOW_RETURN(state), \
            BOOST_VMD_DETAIL_MODS_OP_CURRENT_ALLOW_RETURN, \
            BOOST_PP_IIF \
                ( \
                BOOST_VMD_DETAIL_MODS_STATE_IS_ALLOW_AFTER(state), \
                BOOST_VMD_DETAIL_MODS_OP_CURRENT_ALLOW_AFTER, \
                BOOST_PP_IIF \
                    ( \
                    BOOST_VMD_DETAIL_MODS_STATE_IS_ALLOW_INDEX(state), \
                    BOOST_VMD_DETAIL_MODS_OP_CURRENT_ALLOW_INDEX, \
                    BOOST_VMD_DETAIL_MODS_OP_CURRENT_ALLOW_UPDATE \
                    ) \
                ) \
            ) \
        ) \
    (d,state,id) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT_TUPLE(d,state,id) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT_UPDATE \
        ( \
        d, \
        BOOST_PP_TUPLE_REPLACE_D \
            ( \
            d, \
            state, \
            BOOST_VMD_DETAIL_MODS_DATA_RESULT, \
            BOOST_PP_TUPLE_REPLACE_D \
                ( \
                d, \
                BOOST_VMD_DETAIL_MODS_STATE_RESULT(state), \
                BOOST_VMD_DETAIL_MODS_TUPLE_OTHER, \
                id \
                ) \
            ) \
        ) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP_CURRENT(d,state,id) \
    BOOST_PP_IIF \
        ( \
        BOOST_PP_IS_BEGIN_PARENS(id), \
        BOOST_VMD_DETAIL_MODS_OP_CURRENT_TUPLE, \
        BOOST_VMD_DETAIL_MODS_OP_CURRENT_ID \
        ) \
    (d,state,id) \
/**/

#define BOOST_VMD_DETAIL_MODS_OP(d,state) \
    BOOST_VMD_DETAIL_MODS_OP_CURRENT(d,state,BOOST_VMD_DETAIL_MODS_STATE_CURRENT(state)) \
/**/

#define BOOST_VMD_DETAIL_MODS_LOOP(allow,tuple) \
    BOOST_PP_TUPLE_ELEM \
        ( \
        3, \
        BOOST_PP_WHILE \
            ( \
            BOOST_VMD_DETAIL_MODS_PRED, \
            BOOST_VMD_DETAIL_MODS_OP, \
                ( \
                tuple, \
                0, \
                BOOST_PP_TUPLE_SIZE(tuple), \
                (0,0,0,,0,), \
                allow \
                ) \
            ) \
        ) \
/**/

#define BOOST_VMD_DETAIL_MODS_LOOP_D(d,allow,tuple) \
    BOOST_PP_TUPLE_ELEM \
        ( \
        3, \
        BOOST_PP_WHILE_ ## d \
            ( \
            BOOST_VMD_DETAIL_MODS_PRED, \
            BOOST_VMD_DETAIL_MODS_OP, \
                ( \
                tuple, \
                0, \
                BOOST_PP_TUPLE_SIZE(tuple), \
                (0,0,0,,0,), \
                allow \
                ) \
            ) \
        ) \
/**/

#define BOOST_VMD_DETAIL_NEW_MODS_VAR(allow,tuple) \
    BOOST_VMD_DETAIL_MODS_LOOP \
        ( \
        allow, \
        BOOST_PP_TUPLE_POP_FRONT(tuple) \
        ) \
/**/

#define BOOST_VMD_DETAIL_NEW_MODS_VAR_D(d,allow,tuple) \
    BOOST_VMD_DETAIL_MODS_LOOP_D \
        ( \
        d, \
        allow, \
        BOOST_PP_TUPLE_POP_FRONT(tuple) \
        ) \
/**/

#define BOOST_VMD_DETAIL_NEW_MODS_IR(allow,tuple) \
    BOOST_VMD_IDENTITY_RESULT \
        ( \
        BOOST_PP_IIF \
            ( \
            BOOST_PP_EQUAL(BOOST_PP_TUPLE_SIZE(tuple),1), \
            BOOST_VMD_IDENTITY((0,0,0,,0,)), \
            BOOST_VMD_DETAIL_NEW_MODS_VAR \
            ) \
        (allow,tuple) \
        ) \
/**/

#define BOOST_VMD_DETAIL_NEW_MODS_IR_D(d,allow,tuple) \
    BOOST_VMD_IDENTITY_RESULT \
        ( \
        BOOST_PP_IIF \
            ( \
            BOOST_PP_EQUAL_D(d,BOOST_PP_TUPLE_SIZE(tuple),1), \
            BOOST_VMD_IDENTITY((0,0,0,,0,)), \
            BOOST_VMD_DETAIL_NEW_MODS_VAR_D \
            ) \
        (d,allow,tuple) \
        ) \
/**/

/*

  Returns a six-element tuple:

  First tuple element  = 0 No type return
                         1 Exact type return
                         2 General tuple type return
                         3 Array return
                         4 List return

  Second tuple element = 0 No after return
                         1 After return

  Third tuple element  = 0 No identifier index
                         1 Identifier Index

  Fourth tuple element = Tuple of other identifiers

  Fifth tuple element  = 0 No after only return
                         1 After only return

  Sixth tuple element  = Type identifier

  Input                = allow, either
                         BOOST_VMD_ALLOW_ALL
                         BOOST_VMD_ALLOW_RETURN
                         BOOST_VMD_ALLOW_AFTER
                         BOOST_VMD_ALLOW_INDEX

                           ..., modifiers, first variadic is discarded
                         Possible modifiers are:

                         BOOST_VMD_RETURN_NO_TYPE = (0,0)
                         BOOST_VMD_RETURN_TYPE = (1,0)
                         BOOST_VMD_RETURN_TYPE_TUPLE = (2,0)
                         BOOST_VMD_RETURN_TYPE_ARRAY = (3,0)
                         BOOST_VMD_RETURN_TYPE_LIST = (4,0)

                         BOOST_VMD_RETURN_NO_AFTER = (0,0)
                         BOOST_VMD_RETURN_AFTER = (0,1)

*/

#define BOOST_VMD_DETAIL_NEW_MODS(allow,...) \
    BOOST_VMD_DETAIL_NEW_MODS_IR(allow,BOOST_PP_VARIADIC_TO_TUPLE(__VA_ARGS__)) \
/**/

#define BOOST_VMD_DETAIL_NEW_MODS_D(d,allow,...) \
    BOOST_VMD_DETAIL_NEW_MODS_IR_D(d,allow,BOOST_PP_VARIADIC_TO_TUPLE(__VA_ARGS__)) \
/**/

#endif /* BOOST_VMD_DETAIL_MODS_HPP */