text:
//transforms_ex.cpp
/*
* the transforms from object to shadow and vice versa
* .implementation.
* (C) 2005 olegabr. All rights reserved.
*/
#include "transforms_ex.h"
#include "object3d.h"
#include "shadow2d.h"
#include <vector>
#include <algorithm>
#include <numeric>
#include <set>
#include <list>
#include <cmath>

#include <boost/lambda/lambda.hpp>

#include <iostream>
using std::cout; using std::endl;

shadow2d& create_mask(const shadow2d& sh, shadow2d& mask)
{
	shadow2d::const_iterator s = sh.begin(), send = sh.end();
	shadow2d::iterator m = mask.begin();
	for (; s != send; ++s, ++m)
	{
		size2d_t sz = m->get_size();
		projection2d::const_iterator ps = s->begin(), psend = s->end();
		int i1(0), i2(0), j1(0), j2(0);
		{
			projection1d::const_iterator pps = ps->begin(), ppsend = ps->end();
			for (; pps != ppsend; ++pps)
				if (*pps > 0.) break; else ++i1;
		}

		for (; ps != psend; ++ps)
			if (*(ps->end()-1) > 0.) break; else ++i2;

		for (ps = s->begin(); ps != psend; ++ps, ++j1)
			if (*(ps->begin()) > 0.) break;
		for (; ps != psend; ++ps, ++j1)
			if (*(ps->begin()) == 0.) break;

		{
			ps = psend-1;
			projection1d::const_iterator pps = ps->begin(), ppsend = ps->end();
			for (; pps != ppsend; ++pps, ++j2)
				if (*pps > 0.) break;
			for (; pps != ppsend; ++pps, ++j2)
				if (*pps == 0.) break;
		}

		{
			int offset = 2;
			projection2d::iterator pm = m->begin(), pmend = m->end();
			pixel2d px(0,0); //i,j
			for (; pm != pmend; ++pm, ++px.j)
			{
				projection1d::iterator ppm = pm->begin(), ppmend = pm->end();
				for (px.i = 0; ppm != ppmend; ++ppm, ++px.i)
				{
					if
					(
						(px.i == 0)||
						(px.i == (sz.height - 1))||
						((px.i+px.j) <= i1+offset)||
						((int(sz.height)+px.j-px.i-1) <= i2+offset)||
						((sz.width - 1 + px.i-px.j) <= sz.width - 1 - (j1-offset))||
						((sz.width - 1 + sz.height - 1 - px.i-px.j) <= sz.height - 1 - (j2-offset))
					) *ppm = 0.;
					else *ppm = 1.;
				}
			}
		}
	}

	return mask;
}

shadow2d& apply_mask(const shadow2d& mask, shadow2d& sh)
{
	//shadow2d::iterator s = sh.begin(), send = sh.end();
	//shadow2d::const_iterator m = mask.begin();
	//for (; s != send; ++s, ++m)
	//{
	//	projection2d::iterator ps = s->begin(), psend = s->end();
	//	projection2d::const_iterator pm = m->begin();
	//	for (; ps != psend; ++ps, ++pm)
	//	{
	//		projection1d::iterator pps = ps->begin(), ppsend = ps->end();
	//		projection1d::const_iterator ppm = pm->begin();
	//		for (; pps != ppsend; ++pps, ++ppm)
	//			//if (*ppm < 0.5) *pps = 0.;
	//			*pps *= *ppm;
	//	}
	//}
	return sh;
}

namespace {
	object3d::value_type calc_mean(const object3d& o, const pixel3d& px)
	{
		double k(1.1);
		object3d::value_type value(0);
		for (pixel3d d(-1,-1,-1); d.i <= 1; ++d.i)
			for (d.j = -1; d.j <= 1; ++d.j)
				for (d.k = -1; d.k <= 1; ++d.k)
					value += o(px+d);

		return k*( value )/27.;
	}

	bool is_hole(const object3d& o, const pixel3d& px)
	{
		const object3d::value_type z = 0.001;
		int n(0);
		for (pixel3d d(-1,-1,-1); d.i <= 1; ++d.i)
			for (d.j = -1; d.j <= 1; ++d.j)
				for (d.k = -1; d.k <= 1; ++d.k)
					n += ((o(px+d) > z) ? 1 : 0);
		return
		(
			o(px) < z && /* == 0.*/
			n >= (26 - 23)
		);
	}

	struct filled_area
	{
		typedef std::size_t hash_t;
		typedef std::set<hash_t> data_type;

		filled_area(const size3d_t& sz) : size_(sz)
		{
			//use size_.depth to store the multiplication for optimization purpose
			size_.depth = size_.width*size_.height;
		}
		filled_area& add_pixel(const pixel3d& px)
		{
			data_.insert(pixel2hash_(px));
			return *this;
		}
		filled_area& add_area(filled_area& ar)
		{
			assert(ar.size_ == size_);
			data_.insert(ar.data_.begin(), ar.data_.end());
			ar.data_.clear();
			return *this;
		}
		bool is_adjacent(const pixel3d& px)
		{
			for (pixel3d d(-1,-1,-1); d.i <= 1; ++d.i)
				for (d.j = -1; d.j <= 1; ++d.j)
					for (d.k = -1; d.k <= 1; ++d.k)
					{
						if (d == pixel3d()) continue;
						if ( find_pixel_(px+d) ) return true;
					}
			return false;
		}
		std::size_t size() const { return data_.size(); }
		void clear(object3d& o, object3d::value_type replace_val)
		{
			for (data_type::iterator i(data_.begin()); i != data_.end(); ++i)
				o(hash2pixel_(*i)) = replace_val;
			//data_.clear();
		}
	private :
		hash_t pixel2hash_(const pixel3d& px)
		{
			return (px.k*size_.height + px.i)*size_.width + px.j;//ind;
		}
		pixel3d hash2pixel_(hash_t ind)
		{
			pixel3d px;
			px.k = ind/size_.depth;
			px.i = (ind - px.k*size_.depth)/size_.width;
			px.j = ind - px.k*size_.depth - px.i*size_.width;
			return px;
		}
		bool find_pixel_(const pixel3d& px)
		{
			return data_.find(pixel2hash_(px)) != data_.end();
		}
		data_type data_;
		size3d_t size_;
	};

	bool operator < (const filled_area& lh, const filled_area& rh)
	{
		return lh.size() < rh.size();
	}

	void remove_small_areas(object3d& o, object3d::value_type search_val, object3d::value_type replace_val)
	{
		typedef std::list<filled_area> areas_type;
		typedef std::vector<areas_type::iterator> areas_ptrs_type;
		areas_type areas;
		size3d_t sz(o.get_size());
		long count(0), COUNT(norm(sz));
		for (pixel3d p(0, 0, 0); p.i < sz.height; ++p.i)
		{
			for (p.j = 0; p.j < sz.width; ++p.j)
			{
				for (p.k = 0; p.k < sz.depth; ++p.k)
				{ ++count;
					object3d::value_type v(o(p) - search_val);
					object3d::value_type absv(v>0 ? v : -v);
					if (absv < 0.0001)
					{
						areas_ptrs_type arp;
						for (areas_type::iterator a(areas.begin()); a != areas.end(); ++a)
							if ( a->is_adjacent(p) ) arp.push_back(a);

						if (arp.size() > 1)
						{
							//cout << "arp.size = " << arp.size() << "\n";
							//cout << count << '/' << COUNT << "\tareas.size = " << areas.size() << '\n';
							std::sort(arp.begin(), arp.end(), *boost::lambda::_1 < *boost::lambda::_2);
							areas_ptrs_type::iterator a(arp.begin()), big(arp.end()-1), aend(arp.end()-1);
							for (; a != aend; ++a)
							{
								(*big)->add_area(**a);
								areas.erase(*a);
							}

							(*big)->add_pixel(p);
						}
						else if (arp.empty())
						{
							//cout << "arp.empty" << "\n\n";
							filled_area a(sz);
							a.add_pixel(p);
							areas.push_back(a);
							cout << count << '/' << COUNT << "\tareas.size = " << areas.size() << '\n';
						}
						else /*arp.size() == 1*/
						{
							//cout << "add_pixel" << "\n\n";
							arp.front()->add_pixel(p);
						}
					}
				}
			}
		}
		cout << "areas.size() = " << areas.size() << endl;
		areas.sort();
		areas.reverse();
		areas.erase(areas.begin());
		for (areas_type::iterator a(areas.begin()); a != areas.end(); ++a)
			a->clear(o, replace_val);

	}
	void add_mass(object3d& o, object3d::value_type search_val, long V)
	{
		//filled_area area;
		//size3d_t sz(o.get_size());
		//long rV(0);
		//for (pixel3d p(0, 0, 0); p.i < sz.height; ++p.i)
		//	for (p.j = 0; p.j < sz.width; ++p.j)
		//		for (p.k = 0; p.k < sz.depth; ++p.k)
		//		{
		//			++rV;
		//			object3d::value_type v(o(p) - search_val);
		//			object3d::value_type absv(v>0 ? v : -v);
		//			if (absv < 0.0001) area.add_pixel(p);
		//		}
		//for(; rV < V; ++rV)
		//{
		//	area.add_pixel_to_border();
		//}
	}
} //unnamed namespace

/*
 * V = 427437 pixels
 * density = 1.85
 */
object3d& apply_filter(const object3d& obj, const point3d& center, object3d& result)
{
	assert(obj.get_size() == result.get_size());
	const pixel3d pc = obj.point2pixel(center);
	const long V = 216600;
	const double d = 1.85;
	double rd(d); // real density
	long rN(1); // number of pixels in count
	result(pc) = d;
	long rV(1); // number of pixels in new object
	const int rmax(38);
	for (int r(1); r <= rmax; ++r)
	{
		/*
		 * calc main volume
		 */
		{pixel3d dp(-r, -r, -r);
			for (; dp.j <= r; ++dp.j)
			{
				for (dp.k = -r; dp.k <= r; ++dp.k)
				{
					pixel3d px(pc);
					px += dp;
					rd += obj(px);
					++rN;
					if (calc_mean(obj, px) >= (rd/rN))
					{
						++rV;
						result(px) = d;
					}
				}
			}
		}
		{pixel3d dp(r, -r, -r);
			for (; dp.j <= r; ++dp.j)
			{
				for (dp.k = -r; dp.k <= r; ++dp.k)
				{
					pixel3d px(pc);
					px += dp;
					rd += obj(px);
					++rN;
					if (calc_mean(obj, px) >= (rd/rN))
					{
						++rV;
						result(px) = d;
					}
				}
			}
		}
		{pixel3d dp(1-r, -r, -r);
			for (; dp.i < r; ++dp.i)
			{
				for (dp.k = -r; dp.k <= r; ++dp.k)
				{
					pixel3d px(pc);
					px += dp;
					rd += obj(px);
					++rN;
					if (calc_mean(obj, px) >= (rd/rN))
					{
						++rV;
						result(px) = d;
					}
				}
			}
		}
		{pixel3d dp(1-r, r, -r);
			for (; dp.i < r; ++dp.i)
			{
				for (dp.k = -r; dp.k <= r; ++dp.k)
				{
					pixel3d px(pc);
					px += dp;
					rd += obj(px);
					++rN;
					if (calc_mean(obj, px) >= (rd/rN))
					{
						++rV;
						result(px) = d;
					}
				}
			}
		}
		{pixel3d dp(1-r, 1-r, -r);
			for (; dp.j < r; ++dp.j)
			{
				for (dp.i = 1-r; dp.i < r; ++dp.i)
				{
					pixel3d px(pc);
					px += dp;
					rd += obj(px);
					++rN;
					if (calc_mean(obj, px) >= (rd/rN))
					{
						++rV;
						result(px) = d;
					}
				}
			}
		}
		{pixel3d dp(1-r, 1-r, r);
			for (; dp.j < r; ++dp.j)
			{
				for (dp.i = 1-r; dp.i < r; ++dp.i)
				{
					pixel3d px(pc);
					px += dp;
					rd += obj(px);
					++rN;
					if (calc_mean(obj, px) >= (rd/rN))
					{
						++rV;
						result(px) = d;
					}
				}
			}
		}

		/*
		 * fill holes
		 */
		--r;
		{pixel3d dp(-r, -r, -r);
			for (; dp.j <= r; ++dp.j)
			{
				for (dp.k = 0; dp.k <= r; ++dp.k)
				{
					pixel3d px(pc);
					px += dp;
					if (is_hole(obj, px))
					{
						++rV;
						result(px) = d;
					}
				}
			}
		}
		{pixel3d dp(r, -r, -r);
			for (; dp.j <= r; ++dp.j)
			{
				for (dp.k = 0; dp.k <= r; ++dp.k)
				{
					pixel3d px(pc);
					px += dp;
					if (is_hole(obj, px))
					{
						++rV;
						result(px) = d;
					}
				}
			}
		}
		{pixel3d dp(1-r, -r, -r);
			for (; dp.i < r; ++dp.i)
			{
				for (dp.k = 0; dp.k <= r; ++dp.k)
				{
					pixel3d px(pc);
					px += dp;
					if (is_hole(obj, px))
					{
						++rV;
						result(px) = d;
					}
				}
			}
		}
		{pixel3d dp(1-r, r, -r);
			for (; dp.i < r; ++dp.i)
			{
				for (dp.k = 0; dp.k <= r; ++dp.k)
				{
					pixel3d px(pc);
					px += dp;
					if (is_hole(obj, px))
					{
						++rV;
						result(px) = d;
					}
				}
			}
		}
		{pixel3d dp(1-r, 1-r, -r);
			for (; dp.j < r; ++dp.j)
			{
				for (dp.i = 0; dp.i < r; ++dp.i)
				{
					pixel3d px(pc);
					px += dp;
					if (is_hole(obj, px))
					{
						++rV;
						result(px) = d;
					}
				}
			}
		}
		{pixel3d dp(1-r, 1-r, r);
			for (; dp.j < r; ++dp.j)
			{
				for (dp.i = 0; dp.i < r; ++dp.i)
				{
					pixel3d px(pc);
					px += dp;
					if (is_hole(obj, px))
					{
						++rV;
						result(px) = d;
					}
				}
			}
		}
		++r;
		/*
		 * end of fill holes
		 */
		if (rV >= V) break;
	}

	remove_small_areas(result, d, 0.);
	remove_small_areas(result, 0., d);
	//add_mass(result, d, V);
	//cout << "new Volume = " << rV << endl;

	return result;
}

point3d calc_center(const shadow2d& sh)
{
	point3d p;
	shadow2d::const_iterator pr = sh.begin(), epr = sh.end();
	for (; pr != epr; ++pr)
		if (abs(pr->get_angle()) <= angle_t(43)) break;
	point2d p1 = pr->get_mass_center();
	angle_t a1 = pr->get_angle();
	for (; pr != epr; ++pr)
		if (pr->get_angle() == angle_t(0)) break;
	point2d p2 = pr->get_mass_center();
	angle_t a2 = pr->get_angle();

	p.z = .5*(p1.x + p2.x);
	p.y = (p1.y*cos(a2) - p2.y*cos(a1))/(sin(a1)*cos(a2) - sin(a2)*cos(a1));
	p.x = (p1.y - p.y*sin(a1))/cos(a1);

	return p;
}

object3d& filter_object(object3d& object)
{
	const int mean = 167;
	object3d::iterator o2d(object.begin()), end1(object.end());
	for (; o2d != end1; ++o2d)
	{
		object2d::iterator o(o2d->begin()), end2(o2d->end());
		for (; o != end2; ++o)
		{
			double d(*o-mean);
			*o = std::pow((d>0?d:0.), 10.);
		}
	}
	return object;
}

void black_threshold(shadow2d& sh, double threshold)
{
	shadow2d::iterator s = sh.begin(), send = sh.end();
	for (; s != send; ++s)
	{
		projection2d::iterator ps = s->begin(), psend = s->end();
		for (; ps != psend; ++ps)
		{
			projection1d::iterator pps = ps->begin(), ppsend = ps->end();
			for (; pps != ppsend; ++pps)
			{
				projection1d::value_type val = *pps;
				*pps = (val >= threshold) ? val : 0.;
			}
		}
	}
}


text:
#include <boost/test/unit_test.hpp>
#include <boost/test/included/unit_test.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
#include "log4cxx/logger.h"
#include "log4cxx/basicconfigurator.h"
#include "log4cxx/propertyconfigurator.h"
#include "log4cxx/helpers/exception.h"

#include "cql-interface/cql-interface.h"

using namespace std;
using namespace cb;
namespace po = boost::program_options;

using namespace boost::unit_test;

using namespace log4cxx;
using namespace log4cxx::helpers;

unsigned nruns = 100;
unsigned nsize = 100;
unsigned npost = 8;
string src_dir;

namespace {

    class Cleaner
    {
        public:
            Cleaner() {}

            ~Cleaner()
            {
                sleep(1);
                LogBaseInfo::clean_up();
            }
    };
}

test_suite*
init_unit_test_suite( int argc, char* argv[] ) {

    framework::master_test_suite().p_name.value = "CQL Interface Tests";

    vector<string> cassandra_ips;
    bool debug_log_for_cassandra = false;
    cass_duration_t cassandra_timeout = 0;
    po::options_description desc("Allowed options");
    desc.add_options()
      ("nruns", po::value<unsigned>(&nruns)->default_value(10), "number of runs to make")
      ("nsize", po::value<unsigned>(&nsize)->default_value(100), "number of entries per posting list")
      ("src_dir",
            po::value<string>(&src_dir)->default_value("."),
            "source directory with supporting file for tests")
      ("cassandra_ip",
            po::value<vector<string>>(&cassandra_ips),
            "host ips for cassandra, defaults to localhost if not set")
      ("cassandra_timeout",
            po::value<cass_duration_t>(&cassandra_timeout)->default_value(20000000),
            "cassandra timeout in ms")
      ("debug_log_for_cassandra",
            po::value<bool>(&debug_log_for_cassandra)->default_value(0),
            "include debug logs for Cassandra")
      ("new_help", "produce help message")
      ;
    LogBaseInfo log_info(desc);

    po::variables_map vm;
    // po::store(po::parse_command_line(argc, argv, desc), vm);
    po::store(po::command_line_parser(argc, argv).options(desc).allow_unregistered().run(), vm);
    po::notify(vm);

    // use --my_help to see help message for this
    log_info.evaluate(vm, desc);

    if (!cassandra_ips.size())
    {
        cassandra_ips.push_back("127.0.0.1");
    }
    std::set<string> use_cass_ips(cassandra_ips.begin(), cassandra_ips.end());
    CassConn::static_init(use_cass_ips,
                          "cql_interface_test",
                          cassandra_timeout,
                          "",
                          "",
                          CASS_CONSISTENCY_LOCAL_QUORUM,
                          "",
                          4,
                          4,
                          4096,
                          (debug_log_for_cassandra ? CASS_LOG_DEBUG : CASS_LOG_INFO));

    BOOST_GLOBAL_FIXTURE( Cleaner );

    return 0;
}

ext: cpp

max_stars_repo_name: cbracher/cql-interface

max_issues_repo_name: cbracher/cql-interface

max_forks_repo_name: cbracher/cql-interface


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

#include <boost/format.hpp>

#include "slg/lights/mappointlight.h"

using namespace std;
using namespace luxrays;
using namespace slg;

//------------------------------------------------------------------------------
// MapPointLight
//------------------------------------------------------------------------------

MapPointLight::MapPointLight() : imageMap(NULL), func(NULL) {
}

MapPointLight::~MapPointLight() {
	delete func;
}

void MapPointLight::Preprocess() {
	PointLight::Preprocess();

	delete func;
	func = new SampleableSphericalFunction(new ImageMapSphericalFunction(imageMap));
}

void MapPointLight::GetPreprocessedData(float *localPosData, float *absolutePosData,
		float *emittedFactorData, const SampleableSphericalFunction **funcData) const {
	PointLight::GetPreprocessedData(localPosData, absolutePosData, emittedFactorData);

	if (funcData)
		*funcData = func;
}

float MapPointLight::GetPower(const Scene &scene) const {
	return imageMap->GetSpectrumMeanY() * PointLight::GetPower(scene);
}

Spectrum MapPointLight::Emit(const Scene &scene,
		const float u0, const float u1, const float u2, const float u3, const float passThroughEvent,
		Point *orig, Vector *dir,
		float *emissionPdfW, float *directPdfA, float *cosThetaAtLight) const {
	*orig = absolutePos;

	Vector localFromLight;
	func->Sample(u0, u1, &localFromLight, emissionPdfW);
	if (*emissionPdfW == 0.f)
		return Spectrum();

	*dir = Normalize(lightToWorld * localFromLight);

	if (directPdfA)
		*directPdfA = 1.f;
	if (cosThetaAtLight)
		*cosThetaAtLight = 1.f;

	return emittedFactor * ((SphericalFunction *)func)->Evaluate(localFromLight) /
			(4.f * M_PI * func->Average());
}

Spectrum MapPointLight::Illuminate(const Scene &scene, const Point &p,
		const float u0, const float u1, const float passThroughEvent,
        Vector *dir, float *distance, float *directPdfW,
		float *emissionPdfW, float *cosThetaAtLight) const {
	const Vector localFromLight = Normalize(Inverse(lightToWorld) * p - localPos);
	const float funcPdf = func->Pdf(localFromLight);
	if (funcPdf == 0.f)
		return Spectrum();

	const Vector toLight(absolutePos - p);
	const float centerDistanceSquared = toLight.LengthSquared();
	*distance = sqrtf(centerDistanceSquared);
	*dir = toLight / *distance;

	if (cosThetaAtLight)
		*cosThetaAtLight = 1.f;

	*directPdfW = centerDistanceSquared;

	if (emissionPdfW)
		*emissionPdfW = funcPdf;

	return emittedFactor * ((SphericalFunction *)func)->Evaluate(localFromLight) /
			(4.f * M_PI * func->Average());
}

Properties MapPointLight::ToProperties(const ImageMapCache &imgMapCache, const bool useRealFileName) const {
	const string prefix = "scene.lights." + GetName();
	Properties props = PointLight::ToProperties(imgMapCache, useRealFileName);

	props.Set(Property(prefix + ".type")("mappoint"));
	const string fileName = useRealFileName ?
		imageMap->GetName() : imgMapCache.GetSequenceFileName(imageMap);
	props.Set(Property(prefix + ".mapfile")(fileName));
	props.Set(imageMap->ToProperties(prefix, false));

	return props;
}

max_stars_repo_name: rebpdx/LuxCore

max_issues_repo_name: rebpdx/LuxCore

max_forks_repo_name: rebpdx/LuxCore


text:
#include <tesseract_common/macros.h>
TESSERACT_COMMON_IGNORE_WARNINGS_PUSH
#include <gtest/gtest.h>
#include <Eigen/Geometry>
TESSERACT_COMMON_IGNORE_WARNINGS_POP

#include <tesseract_urdf/inertial.h>
#include "tesseract_urdf_common_unit.h"

TEST(TesseractURDFUnit, parse_inertial)  // NOLINT
{
  {
    std::string str = R"(<inertial extra="0 0 0">
                           <origin xyz="0 0 0" rpy="0 0 0"/>
                           <mass value="1.0" extra="0 0 0"/>
                           <inertia ixx="1.0" ixy="2.0" ixz="3.0" iyy="4.0" iyz="5.0" izz="6.0" extra="0 0 0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_TRUE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
    EXPECT_NEAR(elem->mass, 1, 1e-8);
    EXPECT_NEAR(elem->ixx, 1, 1e-8);
    EXPECT_NEAR(elem->ixy, 2, 1e-8);
    EXPECT_NEAR(elem->ixz, 3, 1e-8);
    EXPECT_NEAR(elem->iyy, 4, 1e-8);
    EXPECT_NEAR(elem->iyz, 5, 1e-8);
    EXPECT_NEAR(elem->izz, 6, 1e-8);
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                           <inertia ixx="1.0" ixy="2.0" ixz="3.0" iyy="4.0" iyz="5.0" izz="6.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_TRUE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
    EXPECT_NEAR(elem->mass, 1, 1e-8);
    EXPECT_NEAR(elem->ixx, 1, 1e-8);
    EXPECT_NEAR(elem->ixy, 2, 1e-8);
    EXPECT_NEAR(elem->ixz, 3, 1e-8);
    EXPECT_NEAR(elem->iyy, 4, 1e-8);
    EXPECT_NEAR(elem->iyz, 5, 1e-8);
    EXPECT_NEAR(elem->izz, 6, 1e-8);
  }

  {
    std::string str = R"(<inertial extra="0 0 0">
                           <origin xyz="0 0 0 4" rpy="0 0 0"/>
                           <mass value="1.0" extra="0 0 0"/>
                           <inertia ixx="1.0" ixy="2.0" ixz="3.0" iyy="4.0" iyz="5.0" izz="6.0" extra="0 0 0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <inertia ixx="1.0" ixy="2.0" ixz="3.0" iyy="4.0" iyz="5.0" izz="6.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="a"/>
                           <inertia ixx="1.0" ixy="2.0" ixz="3.0" iyy="4.0" iyz="5.0" izz="6.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass />
                           <inertia ixx="1.0" ixy="2.0" ixz="3.0" iyy="4.0" iyz="5.0" izz="6.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                           <inertia ixx="a" ixy="2.0" ixz="3.0" iyy="4.0" iyz="5.0" izz="6.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                           <inertia ixx="1.0" ixy="a" ixz="3.0" iyy="4.0" iyz="5.0" izz="6.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                           <inertia ixx="1.0" ixy="2.0" ixz="a" iyy="4.0" iyz="5.0" izz="6.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                           <inertia ixx="1.0" ixy="2.0" ixz="3.0" iyy="a" iyz="5.0" izz="6.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                           <inertia ixx="1.0" ixy="2.0" ixz="3.0" iyy="4.0" iyz="a" izz="6.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                           <inertia ixx="1.0" ixy="2.0" ixz="3.0" iyy="4.0" iyz="5.0" izz="a"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                           <inertia ixy="2.0" ixz="3.0" iyy="4.0" iyz="5.0" izz="6.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                           <inertia ixx="1.0" ixz="3.0" iyy="4.0" iyz="5.0" izz="6.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                           <inertia ixx="1.0" ixy="2.0" iyy="4.0" iyz="5.0" izz="6.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                           <inertia ixx="1.0" ixy="2.0" ixz="3.0" iyz="5.0" izz="6.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                           <inertia ixx="1.0" ixy="2.0" ixz="3.0" iyy="4.0" izz="6.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                           <inertia ixx="1.0" ixy="2.0" ixz="3.0" iyy="4.0" iyz="5.0"/>
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }

  {
    std::string str = R"(<inertial>
                           <mass value="1.0"/>
                           <inertia />
                         </inertial>)";
    tesseract_scene_graph::Inertial::Ptr elem;
    EXPECT_FALSE(
        runTest<tesseract_scene_graph::Inertial::Ptr>(elem, &tesseract_urdf::parseInertial, str, "inertial", 2));
  }
}

max_stars_repo_name: jf---/tesseract

max_issues_repo_name: jf---/tesseract

max_forks_repo_name: jf---/tesseract


text:
#include <boost/functional/hash.hpp>
#include <boost/filesystem.hpp>

#include "../qikkDB/ColumnBase.h"
#include "../qikkDB/Database.h"
#include "../qikkDB/GpuSqlParser/GpuSqlCustomParser.h"
#include "../qikkDB/PointFactory.h"
#include "../qikkDB/QueryEngine/Context.h"
#include "../qikkDB/Table.h"
#include "../qikkDB/messages/QueryResponseMessage.pb.h"
#include "gtest/gtest.h"

class DispatcherAlterTests : public ::testing::Test
{
protected:
    const std::string path = Configuration::GetInstance().GetDatabaseDir();
    const std::string dbName = "AlterTestDb";
    const std::string tableName = "SimpleTable";
    const int32_t blockSize = 4; // length of a block

    std::shared_ptr<Database> alterDatabase;

    virtual void SetUp()
    {
        Context::getInstance();

        alterDatabase = std::make_shared<Database>(dbName.c_str(), blockSize);
        Database::AddToInMemoryDatabaseList(alterDatabase);
    }

    virtual void TearDown()
    {
        // clean up occurs when test completes or an exception is thrown
        Database::RemoveFromInMemoryDatabaseList(dbName.c_str());

        // clear directory to make sure, there are no old database files, but do not remove directory:
        boost::filesystem::path path_to_remove(path);
        for (boost::filesystem::directory_iterator end_dir_it, it(path_to_remove); it != end_dir_it; ++it)
        {
            boost::filesystem::remove_all(it->path());
        }
    }

    void AlterTableRenameColumnGenericTest(std::string newColName)
    {
        auto columns = std::unordered_map<std::string, DataType>();
        columns.insert(std::make_pair<std::string, DataType>("colA", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colB", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colC", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colD", DataType::COLUMN_INT));

        alterDatabase->CreateTable(columns, tableName.c_str());

        GpuSqlCustomParser parser(alterDatabase,
                                  "ALTER TABLE SimpleTable RENAME COLUMN colA TO " + newColName + ";");
        auto resultPtr = parser.Parse();

        // test in memory changes:
        ASSERT_TRUE(alterDatabase->GetTables().at("SimpleTable").GetColumns().find(newColName) !=
                    alterDatabase->GetTables().at("SimpleTable").GetColumns().end());
        ASSERT_TRUE(alterDatabase->GetTables().at("SimpleTable").GetColumns().find("colA") ==
                    alterDatabase->GetTables().at("SimpleTable").GetColumns().end());
        ASSERT_TRUE(alterDatabase->GetTables().at("SimpleTable").GetColumns().find("colB") !=
                    alterDatabase->GetTables().at("SimpleTable").GetColumns().end());
        ASSERT_TRUE(alterDatabase->GetTables().at("SimpleTable").GetColumns().find("colC") !=
                    alterDatabase->GetTables().at("SimpleTable").GetColumns().end());
        ASSERT_TRUE(alterDatabase->GetTables().at("SimpleTable").GetColumns().find("colD") !=
                    alterDatabase->GetTables().at("SimpleTable").GetColumns().end());

        // persist database, rename again, and test changes in memory and on disk
        alterDatabase->Persist();

        std::string newestColName = newColName + "_secondTry";

        GpuSqlCustomParser parser2(alterDatabase, "ALTER TABLE SimpleTable RENAME COLUMN " +
                                                      newColName + " TO " + newestColName + ";");
        resultPtr = parser2.Parse();

        // test in memory changes:
        ASSERT_TRUE(alterDatabase->GetTables().at("SimpleTable").GetColumns().find(newestColName) !=
                    alterDatabase->GetTables().at("SimpleTable").GetColumns().end());
        ASSERT_TRUE(alterDatabase->GetTables().at("SimpleTable").GetColumns().find("colA") ==
                    alterDatabase->GetTables().at("SimpleTable").GetColumns().end());
        ASSERT_TRUE(alterDatabase->GetTables().at("SimpleTable").GetColumns().find(newColName) ==
                    alterDatabase->GetTables().at("SimpleTable").GetColumns().end());
        ASSERT_TRUE(alterDatabase->GetTables().at("SimpleTable").GetColumns().find("colB") !=
                    alterDatabase->GetTables().at("SimpleTable").GetColumns().end());
        ASSERT_TRUE(alterDatabase->GetTables().at("SimpleTable").GetColumns().find("colC") !=
                    alterDatabase->GetTables().at("SimpleTable").GetColumns().end());
        ASSERT_TRUE(alterDatabase->GetTables().at("SimpleTable").GetColumns().find("colD") !=
                    alterDatabase->GetTables().at("SimpleTable").GetColumns().end());

        // test changes on disk:
        ASSERT_TRUE(boost::filesystem::exists(boost::filesystem::path(path + dbName + Database::DB_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colA" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + tableName + Database::SEPARATOR +
                                    newColName + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_TRUE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + tableName + Database::SEPARATOR +
                                    newestColName + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_TRUE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colB" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_TRUE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colC" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_TRUE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colD" + Database::COLUMN_DATA_EXTENSION)));

        // clear directory to make sure, there are no old database files, but do not remove directory:
        boost::filesystem::path path_to_remove(path);
        for (boost::filesystem::directory_iterator end_dir_it, it(path_to_remove); it != end_dir_it; ++it)
        {
            boost::filesystem::remove_all(it->path());
        }
    }

    void AlterTableRenameTableGenericTest(std::string newTableName)
    {
        auto columns = std::unordered_map<std::string, DataType>();
        columns.insert(std::make_pair<std::string, DataType>("colA", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colB", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colC", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colD", DataType::COLUMN_INT));

        alterDatabase->CreateTable(columns, tableName.c_str());

        GpuSqlCustomParser parser(alterDatabase, "ALTER TABLE SimpleTable RENAME TO " + newTableName + ";");
        auto resultPtr = parser.Parse();

        // test in memory changes:
        ASSERT_TRUE(alterDatabase->GetTables().find("SimpleTable") == alterDatabase->GetTables().end());
        ASSERT_TRUE(alterDatabase->GetTables().find(newTableName) != alterDatabase->GetTables().end());

        // persist database, rename again, and test changes in memory and on disk
        alterDatabase->Persist();
        std::string newestTableName = newTableName + "_secondTry";

        GpuSqlCustomParser parser2(alterDatabase, "ALTER TABLE " + newTableName + " RENAME TO " +
                                                      newestTableName + ";");
        resultPtr = parser2.Parse();

        // test in memory changes:
        ASSERT_TRUE(alterDatabase->GetTables().find(newTableName) == alterDatabase->GetTables().end());
        ASSERT_TRUE(alterDatabase->GetTables().find(newestTableName) != alterDatabase->GetTables().end());

        // test changes on disk:
        ASSERT_TRUE(boost::filesystem::exists(boost::filesystem::path(path + dbName + Database::DB_EXTENSION)));
        ASSERT_TRUE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + newestTableName +
                                    Database::SEPARATOR + "colA" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_TRUE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + newestTableName +
                                    Database::SEPARATOR + "colB" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_TRUE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + newestTableName +
                                    Database::SEPARATOR + "colC" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_TRUE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + newestTableName +
                                    Database::SEPARATOR + "colD" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + newTableName +
                                    Database::SEPARATOR + "colA" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + newTableName +
                                    Database::SEPARATOR + "colB" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + newTableName +
                                    Database::SEPARATOR + "colC" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + newTableName +
                                    Database::SEPARATOR + "colD" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + "SimpleTable" +
                                    Database::SEPARATOR + "colA" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + "SimpleTable" +
                                    Database::SEPARATOR + "colB" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + "SimpleTable" +
                                    Database::SEPARATOR + "colC" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + dbName + Database::SEPARATOR + "SimpleTable" +
                                    Database::SEPARATOR + "colD" + Database::COLUMN_DATA_EXTENSION)));

        // clear directory to make sure, there are no old database files, but do not remove directory:
        boost::filesystem::path path_to_remove(path);
        for (boost::filesystem::directory_iterator end_dir_it, it(path_to_remove); it != end_dir_it; ++it)
        {
            boost::filesystem::remove_all(it->path());
        }
    }

    void AlterTableRenameDatabaseGenericTest(std::string newDatabaseName)
    {
        auto columns = std::unordered_map<std::string, DataType>();
        columns.insert(std::make_pair<std::string, DataType>("colA", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colB", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colC", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colD", DataType::COLUMN_INT));

        alterDatabase->CreateTable(columns, tableName.c_str());

        GpuSqlCustomParser parser(nullptr, "ALTER DATABASE AlterTestDb RENAME TO " + newDatabaseName + ";");
        auto resultPtr = parser.Parse();

        // test in memory changes:
        ASSERT_FALSE(Database::Exists("AlterTestDb"));
        ASSERT_TRUE(Database::Exists(newDatabaseName));

        // persist database, rename again, and test changes in memory and on disk
        alterDatabase->Persist();
        std::string newestDatabaseName = newDatabaseName + "_secondTry";

        GpuSqlCustomParser parser2(nullptr, "ALTER DATABASE " + newDatabaseName + " RENAME TO " +
                                                newestDatabaseName + ";");
        resultPtr = parser2.Parse();

        // test in memory changes:
        ASSERT_FALSE(Database::Exists("AlterTestDb"));
        ASSERT_FALSE(Database::Exists(newDatabaseName));
        ASSERT_TRUE(Database::Exists(newestDatabaseName));

        // test changes on disk:
        ASSERT_TRUE(boost::filesystem::exists(
            boost::filesystem::path(path + newestDatabaseName + Database::DB_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + newDatabaseName + Database::DB_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + "AlterTestDb" + Database::DB_EXTENSION)));
        ASSERT_TRUE(boost::filesystem::exists(
            boost::filesystem::path(path + newestDatabaseName + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colA" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_TRUE(boost::filesystem::exists(
            boost::filesystem::path(path + newestDatabaseName + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colB" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_TRUE(boost::filesystem::exists(
            boost::filesystem::path(path + newestDatabaseName + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colC" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_TRUE(boost::filesystem::exists(
            boost::filesystem::path(path + newestDatabaseName + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colD" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + newDatabaseName + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colA" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + newDatabaseName + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colB" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + newDatabaseName + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colC" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + newDatabaseName + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colD" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + "AlterTestDb" + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colA" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + "AlterTestDb" + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colB" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + "AlterTestDb" + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colC" + Database::COLUMN_DATA_EXTENSION)));
        ASSERT_FALSE(boost::filesystem::exists(
            boost::filesystem::path(path + "AlterTestDb" + Database::SEPARATOR + tableName +
                                    Database::SEPARATOR + "colD" + Database::COLUMN_DATA_EXTENSION)));

        // clear directory to make sure, there are no old database files, but do not remove directory:
        boost::filesystem::path path_to_remove(path);
        for (boost::filesystem::directory_iterator end_dir_it, it(path_to_remove); it != end_dir_it; ++it)
        {
            boost::filesystem::remove_all(it->path());
        }
    }

    void AlterTableAlterBlockSizeGenericTest(int32_t newBlockSize)
    {
        auto columns = std::unordered_map<std::string, DataType>();
        columns.insert(std::make_pair<std::string, DataType>("colA", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colB", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colC", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colD", DataType::COLUMN_INT));

        alterDatabase->CreateTable(columns, tableName.c_str());

        ASSERT_NE(blockSize, newBlockSize);

        ASSERT_EQ(alterDatabase->GetTables().at(tableName).GetBlockSize(), blockSize);

        GpuSqlCustomParser parser(alterDatabase, "ALTER TABLE " + tableName + " ALTER BLOCK SIZE " +
                                                     std::to_string(newBlockSize) + ";");
        auto resultPtr = parser.Parse();

        ASSERT_EQ(alterDatabase->GetTables().at(tableName).GetBlockSize(), newBlockSize);
    }

    void AlterDatabaseAlterBlockSizeGenericTest(int32_t newBlockSize)
    {
        auto columns = std::unordered_map<std::string, DataType>();
        columns.insert(std::make_pair<std::string, DataType>("colA", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colB", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colC", DataType::COLUMN_INT));
        columns.insert(std::make_pair<std::string, DataType>("colD", DataType::COLUMN_INT));

        alterDatabase->CreateTable(columns, tableName.c_str());

        ASSERT_NE(blockSize, newBlockSize);

        ASSERT_EQ(alterDatabase->GetTables().at(tableName).GetBlockSize(), blockSize);
        ASSERT_EQ(alterDatabase->GetBlockSize(), blockSize);

        GpuSqlCustomParser parser(nullptr, "ALTER DATABASE " + dbName + " ALTER BLOCK SIZE " +
                                               std::to_string(newBlockSize) + ";");
        auto resultPtr = parser.Parse();

        ASSERT_EQ(alterDatabase->GetTables().at(tableName).GetBlockSize(), newBlockSize);
        ASSERT_EQ(alterDatabase->GetBlockSize(), newBlockSize);
    }
};

TEST_F(DispatcherAlterTests, RenameColumnTest)
{
    AlterTableRenameColumnGenericTest("colInteger1");
}

TEST_F(DispatcherAlterTests, RenameTableTest)
{
    AlterTableRenameTableGenericTest("TableA");
}

TEST_F(DispatcherAlterTests, RenameDatabaseTest)
{
    AlterTableRenameDatabaseGenericTest("RenamedDatabase");
}

TEST_F(DispatcherAlterTests, AlterTableBlockSizeTest)
{
    AlterTableAlterBlockSizeGenericTest(blockSize * 2);
}

TEST_F(DispatcherAlterTests, AlterDatabaseBlockSizeTest)
{
    AlterDatabaseAlterBlockSizeGenericTest(blockSize * 2);
}

max_stars_repo_name: veselyja/qikkdb-community

max_issues_repo_name: veselyja/qikkdb-community

max_forks_repo_name: qikkDB/qikkdb


text:
//  (C) Copyright Edward Diener 2012
//  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).

#include "test_has_data.hpp"
#include <boost/detail/lightweight_test.hpp>

int main()
  {

  BOOST_TEST((BOOST_TTI_HAS_DATA_GEN(AnInt)<AType,int>::value));
  BOOST_TEST((!BOOST_TTI_HAS_DATA_GEN(SomeStaticData)<AnotherType,float>::value));
  BOOST_TEST((BOOST_TTI_HAS_DATA_GEN(AnInt)<AnotherType,long>::value));
  BOOST_TEST((BOOST_TTI_HAS_DATA_GEN(DSMember)<AType,short>::value));
  BOOST_TEST((BOOST_TTI_HAS_DATA_GEN(aMember)<AnotherType,bool>::value));
  BOOST_TEST((!BOOST_TTI_HAS_DATA_GEN(aMember)<AnotherType,int>::value));
  BOOST_TEST((DCMember<AnotherType,bool>::value));
  BOOST_TEST((!BOOST_TTI_HAS_DATA_GEN(someDataMember)<AType,short>::value));
  BOOST_TEST((BOOST_TTI_HAS_DATA_GEN(IntBT)<AType,AType::BType>::value));
  BOOST_TEST((DStatName<AnotherType,AType::AStructType>::value));
  BOOST_TEST((DNestedData<AType,AType::BType::CType>::value));
  BOOST_TEST((BOOST_TTI_HAS_DATA_GEN(CIntValue)<AnotherType,const int>::value));
  BOOST_TEST((DAOther<AnotherType,AType>::value));
  BOOST_TEST((BOOST_TTI_HAS_DATA_GEN(ONestStr)<AnotherType,AType::AStructType>::value));

  // Passing non-class enclosing type will return false

  BOOST_TEST((!BOOST_TTI_HAS_DATA_GEN(IntBT)<unsigned long,AType::BType>::value));
  BOOST_TEST((!DCMember<AnotherType *,bool>::value));
  BOOST_TEST((!DCMember<AnotherType &,bool>::value));
  BOOST_TEST((!BOOST_TTI_HAS_DATA_GEN(AnInt)<int **,long>::value));

  return boost::report_errors();

  }


text:
#ifndef MLT_MODELS_PIPELINE_HPP
#define MLT_MODELS_PIPELINE_HPP

#include <Eigen/Core>

#include "transformers/transformer_mixin.hpp"

namespace mlt {
namespace models {

	// Forward declaration
	template <class... Ts>
	class Pipeline {
	};

namespace internal {
	template<size_t _Index, class _Pipline>
	struct sub_pipeline_element;

	template<size_t _Index>
	struct sub_pipeline_element<_Index, Pipeline<> >
	{
		static_assert(std::_Always_false<std::integral_constant<size_t, _Index> >::value, "pipeline index out of bounds");
	};

	template<class _This, class... _Rest>
	struct sub_pipeline_element<0, Pipeline<_This, _Rest...> >
	{
		typedef _This model_type;
		typedef Pipeline<_This, _Rest...> type;
	};

	template<size_t _Index, class _This, class... _Rest>
	struct sub_pipeline_element<_Index, Pipeline<_This, _Rest...> >
		: public sub_pipeline_element<_Index - 1, Pipeline<_Rest...> >
	{};

	template<size_t _Index, class _Pipline>
	struct sub_pipeline_element<_Index, const _Pipline>
		: public sub_pipeline_element<_Index, _Pipline>
	{
		typedef typename std::add_const<typename sub_pipeline_element<_Index, _Pipline>::model_type>::type model_type;
		typedef typename std::add_const<typename sub_pipeline_element<_Index, _Pipline>::type>::type type;
	};

	template<size_t _Index, class _Pipline>
	struct sub_pipeline_element<_Index, volatile _Pipline> : public sub_pipeline_element<_Index, _Pipline>
	{
		typedef typename std::add_volatile<typename sub_pipeline_element<_Index, _Pipline>::model_type>::type model_type;
		typedef typename std::add_volatile<typename sub_pipeline_element<_Index, _Pipline>::type>::type type;
	};

	template<size_t _Index, class _Pipline>
	struct sub_pipeline_element<_Index, const volatile _Pipline> : public sub_pipeline_element<_Index, _Pipline>
	{
		typedef typename std::add_cv<typename sub_pipeline_element<_Index, _Pipline>::model_type>::type model_type;
		typedef typename std::add_cv<typename sub_pipeline_element<_Index, _Pipline>::type>::type type;
	};
}
	template<>
	class Pipeline<> {
		Pipeline() = delete;
	};

	template <class T>
	class Pipeline<T> : public T {
	public:
		explicit Pipeline(T& estimator) : T(estimator) {}

		template<size_t _Index>
		using pipeline_model_t = typename internal::sub_pipeline_element<_Index, Pipeline<T>>::model_type;

		template<size_t _Index>
		using sub_pipeline_t = typename internal::sub_pipeline_element<_Index, Pipeline<T>>::type;

		T& top_estimator() { return *this; }

		template<size_t Index>
		inline sub_pipeline_t<Index>& get()
		{
			return static_cast<sub_pipeline_t<Index>&>(*this);
		}

		template<size_t Index>
		inline typename pipeline_model_t<Index>& get_model()
		{
			return static_cast<sub_pipeline_t<Index>&>(*this).top_estimator();
		}

	protected:

	};

	template <class T, class... Ts>
	class Pipeline<T, Ts...> : protected Pipeline<Ts...> {
	public:
		explicit Pipeline(T& estimator, Ts & ... following) : Pipeline<Ts...>(following...), _estimator(estimator) {}

		template<size_t _Index>
		using pipeline_model_t = typename internal::sub_pipeline_element<_Index, Pipeline<T, Ts...>>::model_type;

		template<size_t _Index>
		using sub_pipeline_t = typename internal::sub_pipeline_element<_Index, Pipeline<T, Ts...>>::type;

		Pipeline<T, Ts...>& fit(const Eigen::Ref<const Eigen::MatrixXd>& input, bool cold_start = true)
		{
			sub_pipeline_t<1>::fit(_estimator.fit_transform(input, cold_start), cold_start);
			return *this;
		}

		Pipeline<T, Ts...>& fit(const Eigen::Ref<const Eigen::MatrixXd>& input, const Eigen::Ref<const Eigen::MatrixXd>& target, bool cold_start = true)
		{
			sub_pipeline_t<1>::fit(_estimator.fit_transform(input, target, cold_start), target, cold_start);
			return *this;
		}

		Pipeline<T, Ts...>& fit(const Eigen::Ref<const Eigen::MatrixXd>& input, const Eigen::Ref<const Eigen::VectorXi>& classes, bool cold_start = true)
		{
			sub_pipeline_t<1>::fit(_estimator.fit_transform(input, classes, cold_start), classes, cold_start);
			return *this;
		}

		Eigen::MatrixXd transform(const Eigen::MatrixXd& input) const
		{
			return sub_pipeline_t<1>::transform(_estimator.transform(input));
		}

		Eigen::MatrixXi classify(const Eigen::MatrixXd& input) const
		{
			return sub_pipeline_t<1>::classify(_estimator.transform(input));
		}

		Eigen::MatrixXd predict(const Eigen::MatrixXd& input) const
		{
			return sub_pipeline_t<1>::predict(_estimator.transform(input));
		}

		Eigen::MatrixXi cluster(const Eigen::MatrixXd& input) const
		{
			return sub_pipeline_t<1>::cluster(_estimator.transform(input));
		}

		double score(const Eigen::Ref<const Eigen::MatrixXd>& input, const Eigen::Ref<const Eigen::MatrixXd>& target) const {
			return sub_pipeline_t<1>::score(_estimator.transform(input), target);
		}

		double score(const Eigen::Ref<const Eigen::MatrixXd>& input, const Eigen::Ref<const Eigen::VectorXi>& classes) const {
			return sub_pipeline_t<1>::score(_estimator.transform(input), classes);
		}

		T& top_estimator() { return _estimator; }

		template<size_t Index>
		inline sub_pipeline_t<Index>& get()
		{
			return static_cast<sub_pipeline_t<Index>&>(*this);
		}

		template<size_t Index>
		inline typename pipeline_model_t<Index>& get_model()
		{
			return static_cast<sub_pipeline_t<Index>&>(*this).top_estimator();
		}
	protected:
		T& _estimator;
	};

	template <class... Ts>
	Pipeline<Ts...> create_pipeline(Ts & ... models) {
		return Pipeline<Ts...>(models...);
	}
}
}
#endif

ext: hpp

max_stars_repo_name: fedeallocati/MachineLearningToolkit

max_issues_repo_name: fedeallocati/MachineLearningToolkit

max_forks_repo_name: fedeallocati/MachineLearningToolkit


text:
// Copyright 2014 Renato Tegon Forti, Antony Polukhin.
// Copyright 2015-2021 Antony Polukhin.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_DLL_DETAIL_POSIX_PROGRAM_LOCATION_IMPL_HPP
#define BOOST_DLL_DETAIL_POSIX_PROGRAM_LOCATION_IMPL_HPP

#include <boost/dll/config.hpp>
#include <boost/dll/detail/system_error.hpp>
#include <boost/predef/os.h>

#ifdef BOOST_HAS_PRAGMA_ONCE
# pragma once
#endif

#if BOOST_OS_MACOS || BOOST_OS_IOS

#include <mach-o/dyld.h>

namespace boost { namespace dll { namespace detail {
    inline boost::dll::fs::path program_location_impl(boost::dll::fs::error_code &ec) {
        ec.clear();

        char path[1024];
        uint32_t size = sizeof(path);
        if (_NSGetExecutablePath(path, &size) == 0)
            return boost::dll::fs::path(path);

        char *p = new char[size];
        if (_NSGetExecutablePath(p, &size) != 0) {
            ec = boost::dll::fs::make_error_code(
                boost::dll::fs::errc::bad_file_descriptor
            );
        }

        boost::dll::fs::path ret(p);
        delete[] p;
        return ret;
    }
}}} // namespace boost::dll::detail

#elif BOOST_OS_SOLARIS

#include <stdlib.h>
namespace boost { namespace dll { namespace detail {
    inline boost::dll::fs::path program_location_impl(boost::dll::fs::error_code& ec) {
        ec.clear();

        return boost::dll::fs::path(getexecname());
    }
}}} // namespace boost::dll::detail

#elif BOOST_OS_BSD_FREE

#include <sys/types.h>
#include <sys/sysctl.h>
#include <stdlib.h>

namespace boost { namespace dll { namespace detail {
    inline boost::dll::fs::path program_location_impl(boost::dll::fs::error_code& ec) {
        ec.clear();

        int mib[4];
        mib[0] = CTL_KERN;
        mib[1] = KERN_PROC;
        mib[2] = KERN_PROC_PATHNAME;
        mib[3] = -1;
        char buf[10240];
        size_t cb = sizeof(buf);
        sysctl(mib, 4, buf, &cb, NULL, 0);

        return boost::dll::fs::path(buf);
    }
}}} // namespace boost::dll::detail

#elif BOOST_OS_BSD_NET

namespace boost { namespace dll { namespace detail {
    inline boost::dll::fs::path program_location_impl(boost::dll::fs::error_code &ec) {
        return boost::dll::fs::read_symlink("/proc/curproc/exe", ec);
    }
}}} // namespace boost::dll::detail

#elif BOOST_OS_BSD_DRAGONFLY

namespace boost { namespace dll { namespace detail {
    inline boost::dll::fs::path program_location_impl(boost::dll::fs::error_code &ec) {
        return boost::dll::fs::read_symlink("/proc/curproc/file", ec);
    }
}}} // namespace boost::dll::detail

#elif BOOST_OS_QNX

#include <fstream>
#include <string> // for std::getline
namespace boost { namespace dll { namespace detail {
    inline boost::dll::fs::path program_location_impl(boost::dll::fs::error_code &ec) {
        ec.clear();

        std::string s;
        std::ifstream ifs("/proc/self/exefile");
        std::getline(ifs, s);

        if (ifs.fail() || s.empty()) {
            ec = boost::dll::fs::make_error_code(
                boost::dll::fs::errc::bad_file_descriptor
            );
        }

        return boost::dll::fs::path(s);
    }
}}} // namespace boost::dll::detail

#else  // BOOST_OS_LINUX || BOOST_OS_UNIX || BOOST_OS_HPUX || BOOST_OS_ANDROID

namespace boost { namespace dll { namespace detail {
    inline boost::dll::fs::path program_location_impl(boost::dll::fs::error_code &ec) {
        // We can not use
        // boost::dll::detail::path_from_handle(dlopen(NULL, RTLD_LAZY | RTLD_LOCAL), ignore);
        // because such code returns empty path.

        return boost::dll::fs::read_symlink("/proc/self/exe", ec);   // Linux specific
    }
}}} // namespace boost::dll::detail

#endif

#endif // BOOST_DLL_DETAIL_POSIX_PROGRAM_LOCATION_IMPL_HPP


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#include <algorithm>
#include <iterator>
#include <memory>
#include <string>
#include <thread>
#include <vector>

#include <boost/optional/optional.hpp>
#include <gflags/gflags_declare.h>
#include <glog/logging.h>
#include <gtest/gtest.h>

#include "kudu/client/client-internal.h"
#include "kudu/client/client.h"
#include "kudu/client/shared_ptr.h" // IWYU pragma: keep
#include "kudu/common/common.pb.h"
#include "kudu/common/wire_protocol.pb.h"
#include "kudu/consensus/replica_management.pb.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/master/master.h"
#include "kudu/master/master.pb.h"
#include "kudu/master/master.proxy.h"
#include "kudu/master/master_cert_authority.h"
#include "kudu/master/mini_master.h"
#include "kudu/mini-cluster/external_mini_cluster.h"
#include "kudu/mini-cluster/internal_mini_cluster.h"
#include "kudu/rpc/messenger.h"
#include "kudu/rpc/rpc_controller.h"
#include "kudu/security/ca/cert_management.h"
#include "kudu/security/cert.h"
#include "kudu/security/crypto.h"
#include "kudu/security/tls_context.h"
#include "kudu/util/countdown_latch.h"
#include "kudu/util/monotime.h"
#include "kudu/util/net/sockaddr.h"
#include "kudu/util/openssl_util.h"
#include "kudu/util/pb_util.h"
#include "kudu/util/scoped_cleanup.h"
#include "kudu/util/status.h"
#include "kudu/util/test_macros.h"
#include "kudu/util/test_util.h"
#include "kudu/util/user.h"

DECLARE_bool(raft_prepare_replacement_before_eviction);

using kudu::cluster::ExternalMiniCluster;
using kudu::cluster::ExternalMiniClusterOptions;
using kudu::cluster::InternalMiniCluster;
using kudu::cluster::InternalMiniClusterOptions;
using kudu::consensus::ReplicaManagementInfoPB;
using kudu::security::Cert;
using kudu::security::CertSignRequest;
using kudu::security::DataFormat;
using kudu::security::PrivateKey;
using kudu::security::ca::CertRequestGenerator;
using std::back_inserter;
using std::copy;
using std::string;
using std::vector;
using strings::Substitute;

namespace kudu {
namespace master {

class MasterCertAuthorityTest : public KuduTest {
 public:
  MasterCertAuthorityTest() {
    opts_.num_masters = 3;
  }

  void SetUp() override {
    KuduTest::SetUp();
    cluster_.reset(new InternalMiniCluster(env_, opts_));
    ASSERT_OK(cluster_->Start());

    rpc::MessengerBuilder bld("Client");
    ASSERT_OK(bld.Build(&messenger_));
  }

  Status RestartCluster() {
    cluster_->Shutdown();
    return cluster_->Start();
  }

  // Check the leader is found on the cluster.
  Status WaitForLeader() {
    return cluster_->GetLeaderMasterIndex(nullptr);
  }

  void GetCurrentCertAuthInfo(string* ca_pkey_str, string* ca_cert_str) {
    int leader_idx;
    ASSERT_OK(cluster_->GetLeaderMasterIndex(&leader_idx));
    MiniMaster* leader = cluster_->mini_master(leader_idx);
    Master* master = leader->master();

    auto ca_pkey = master->cert_authority()->ca_private_key_.get();
    ASSERT_NE(nullptr, ca_pkey);
    ASSERT_OK(ca_pkey->ToString(ca_pkey_str, DataFormat::PEM));

    auto ca_cert = master->cert_authority()->ca_cert_.get();
    ASSERT_NE(nullptr, ca_cert);
    ASSERT_OK(ca_cert->ToString(ca_cert_str, DataFormat::PEM));
  }

  void SendRegistrationHBs() {
    TSToMasterCommonPB common;
    common.mutable_ts_instance()->set_permanent_uuid(kFakeTsUUID);
    common.mutable_ts_instance()->set_instance_seqno(1);
    ServerRegistrationPB fake_reg;
    HostPortPB* pb = fake_reg.add_rpc_addresses();
    pb->set_host("localhost");
    pb->set_port(1000);
    pb = fake_reg.add_http_addresses();
    pb->set_host("localhost");
    pb->set_port(2000);

    // Information on the replica management scheme.
    ReplicaManagementInfoPB rmi;
    rmi.set_replacement_scheme(FLAGS_raft_prepare_replacement_before_eviction
        ? ReplicaManagementInfoPB::PREPARE_REPLACEMENT_BEFORE_EVICTION
        : ReplicaManagementInfoPB::EVICT_FIRST);

    for (int i = 0; i < cluster_->num_masters(); ++i) {
      TSHeartbeatRequestPB req;
      TSHeartbeatResponsePB resp;
      rpc::RpcController rpc;

      req.mutable_common()->CopyFrom(common);
      req.mutable_registration()->CopyFrom(fake_reg);
      req.mutable_replica_management_info()->CopyFrom(rmi);

      MiniMaster* m = cluster_->mini_master(i);
      if (!m->is_started()) {
        continue;
      }
      MasterServiceProxy proxy(messenger_, m->bound_rpc_addr(), m->bound_rpc_addr().host());

      // All masters (including followers) should accept the heartbeat.
      ASSERT_OK(proxy.TSHeartbeat(req, &resp, &rpc));
      SCOPED_TRACE(pb_util::SecureDebugString(resp));
      ASSERT_FALSE(resp.has_error());
    }
  }

  Status SendCertSignRequestHBs(const string& csr_str,
                                bool* has_signed_certificate,
                                string* signed_certificate) {
    TSToMasterCommonPB common;
    common.mutable_ts_instance()->set_permanent_uuid(kFakeTsUUID);
    common.mutable_ts_instance()->set_instance_seqno(1);

    string ts_cert_str;
    bool has_leader_master_response = false;
    for (int i = 0; i < cluster_->num_masters(); ++i) {
      TSHeartbeatRequestPB req;
      TSHeartbeatResponsePB resp;
      rpc::RpcController rpc;

      req.mutable_common()->CopyFrom(common);
      req.set_csr_der(csr_str);

      MiniMaster* m = cluster_->mini_master(i);
      if (!m->is_started()) {
        continue;
      }
      MasterServiceProxy proxy(messenger_, m->bound_rpc_addr(), m->bound_rpc_addr().host());

      // All masters (including followers) should accept the heartbeat.
      RETURN_NOT_OK(proxy.TSHeartbeat(req, &resp, &rpc));
      SCOPED_TRACE(pb_util::SecureDebugString(resp));
      if (resp.has_error()) {
        return Status::RuntimeError("RPC error", resp.error().ShortDebugString());
      }

      // Only the leader sends back the signed server certificate.
      if (resp.leader_master()) {
        has_leader_master_response = true;
        ts_cert_str = resp.signed_cert_der();
      } else {
        if (resp.has_signed_cert_der()) {
          return Status::RuntimeError("unexpected cert returned from non-leader");
        }
      }
    }
    if (has_leader_master_response) {
      *has_signed_certificate = !ts_cert_str.empty();
      *signed_certificate = ts_cert_str;
    }
    return Status::OK();
  }

 protected:
  static const char kFakeTsUUID[];

  InternalMiniClusterOptions opts_;
  std::unique_ptr<InternalMiniCluster> cluster_;
  std::shared_ptr<rpc::Messenger> messenger_;
};
const char MasterCertAuthorityTest::kFakeTsUUID[] = "fake-ts-uuid";

// If no certificate authority information is present, a new one is generated
// upon start of the cluster. So, check that the CA information is available
// upon start of the cluster and it stays the same after the cluster restarts.
TEST_F(MasterCertAuthorityTest, CertAuthorityPersistsUponRestart) {
  string ref_ca_pkey_str;
  string ref_ca_cert_str;
  NO_FATALS(GetCurrentCertAuthInfo(&ref_ca_pkey_str, &ref_ca_cert_str));

  ASSERT_OK(RestartCluster());

  string ca_pkey_str;
  string ca_cert_str;
  NO_FATALS(GetCurrentCertAuthInfo(&ca_pkey_str, &ca_cert_str));

  EXPECT_EQ(ref_ca_pkey_str, ca_pkey_str);
  EXPECT_EQ(ref_ca_cert_str, ca_cert_str);
}

// Check that current master leader posesses the CA private key and certificate
// and if the leader role switches to some other master server, the new leader
// provides the same information as the former one.
TEST_F(MasterCertAuthorityTest, CertAuthorityOnLeaderRoleSwitch) {
  string ref_pkey_str;
  string ref_cert_str;
  NO_FATALS(GetCurrentCertAuthInfo(&ref_pkey_str, &ref_cert_str));

  int leader_idx;
  ASSERT_OK(cluster_->GetLeaderMasterIndex(&leader_idx));
  MiniMaster* leader_master = cluster_->mini_master(leader_idx);
  leader_master->Shutdown();

  string new_leader_pkey_str;
  string new_leader_cert_str;
  NO_FATALS(GetCurrentCertAuthInfo(&new_leader_pkey_str, &new_leader_cert_str));

  EXPECT_EQ(ref_pkey_str, new_leader_pkey_str);
  EXPECT_EQ(ref_cert_str, new_leader_cert_str);
}

void GenerateCSR(const CertRequestGenerator::Config& gen_config,
                 string* csr_str) {
  PrivateKey key;
  int key_size = UseLargeKeys() ? 2048 : 512;
  ASSERT_OK(security::GeneratePrivateKey(key_size, &key));
  CertRequestGenerator gen(gen_config);
  ASSERT_OK(gen.Init());
  CertSignRequest csr;
  ASSERT_OK(gen.GenerateRequest(key, &csr));
  ASSERT_OK(csr.ToString(csr_str, DataFormat::DER));
}

TEST_F(MasterCertAuthorityTest, RefuseToSignInvalidCSR) {
  NO_FATALS(SendRegistrationHBs());
  string csr_str;
  {
    CertRequestGenerator::Config gen_config;
    gen_config.hostname = "ts.foo.com";
    gen_config.user_id = "joe-impostor";
    NO_FATALS(GenerateCSR(gen_config, &csr_str));
  }
  ASSERT_OK(WaitForLeader());
  {
    string ts_cert_str;
    bool has_ts_cert = false;
    Status s = SendCertSignRequestHBs(csr_str, &has_ts_cert, &ts_cert_str);
    ASSERT_STR_MATCHES(s.ToString(),
                       "Remote error: Not authorized: invalid CSR: CSR did not "
                       "contain expected username. "
                       "\\(CSR: 'joe-impostor' RPC: '.*'\\)");
  }
}

// Test that every master accepts heartbeats, but only the leader master
// responds with signed certificate if a heartbeat contains the CSR field.
TEST_F(MasterCertAuthorityTest, MasterLeaderSignsCSR) {
  NO_FATALS(SendRegistrationHBs());

  string csr_str;
  {
    CertRequestGenerator::Config gen_config;
    // The hostname is longer than permitted 255 characters and breaks other
    // restrictions on valid DNS hostnames, but it should not be an issue for
    // both the requestor and the signer.
    gen_config.hostname =
        "toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo."
        "looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
        "oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
        "oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
        "oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
        "oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
        "oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
        "ng.hostname.io";
    string test_user;
    ASSERT_OK(GetLoggedInUser(&test_user));
    gen_config.user_id = test_user;
    NO_FATALS(GenerateCSR(gen_config, &csr_str));
  }

  // Make sure a tablet server receives signed certificate from
  // the leader master.
  ASSERT_OK(WaitForLeader());
  {
    string ts_cert_str;
    bool has_ts_cert = false;
    NO_FATALS(SendCertSignRequestHBs(csr_str, &has_ts_cert, &ts_cert_str));
    ASSERT_TRUE(has_ts_cert);

    // Try to load the certificate to check that the data is not corrupted.
    Cert ts_cert;
    ASSERT_OK(ts_cert.FromString(ts_cert_str, DataFormat::DER));
  }

  // Shutdown the leader master and check the new leader signs
  // certificate request sent in a tablet server heartbeat.
  int leader_idx;
  ASSERT_OK(cluster_->GetLeaderMasterIndex(&leader_idx));
  MiniMaster* leader_master = cluster_->mini_master(leader_idx);
  leader_master->Shutdown();

  // Re-register with the new leader.
  ASSERT_OK(WaitForLeader());
  NO_FATALS(SendRegistrationHBs());
  {
    string ts_cert_str;
    bool has_ts_cert = false;
    NO_FATALS(SendCertSignRequestHBs(csr_str, &has_ts_cert, &ts_cert_str));
    ASSERT_TRUE(has_ts_cert);
    // Try to load the certificate to check that the data is not corrupted.
    Cert ts_cert;
    ASSERT_OK(ts_cert.FromString(ts_cert_str, DataFormat::DER));
  }
}

} // namespace master

namespace client {

class ConnectToClusterBaseTest : public KuduTest {
 public:
  ConnectToClusterBaseTest(int run_time_seconds,
                           int latency_ms,
                           int num_masters)
      : run_time_seconds_(run_time_seconds),
        latency_ms_(latency_ms) {
    cluster_opts_.num_masters = num_masters;
  }

  void SetUp() override {
    KuduTest::SetUp();
    cluster_.reset(new ExternalMiniCluster(cluster_opts_));
  }

  void ConnectToCluster() {
    const MonoDelta timeout(MonoDelta::FromSeconds(run_time_seconds_));
    KuduClientBuilder builder;
    builder.default_admin_operation_timeout(timeout);
    builder.default_rpc_timeout(timeout);
    client::sp::shared_ptr<KuduClient> client;
    ASSERT_OK(cluster_->CreateClient(&builder, &client));
    ASSERT_EQ(1, client->data_->messenger_->tls_context().trusted_cert_count_for_tests());
    ASSERT_NE(boost::none, client->data_->messenger_->authn_token());
  }

  void Run() {
    const MonoTime t_stop = MonoTime::Now() + MonoDelta::FromSeconds(run_time_seconds_);
    CountDownLatch stop_latch(1);
    std::thread clear_latency_thread([&]{
      // Allow the test client to connect to the cluster (avoid timing out).
      const MonoTime clear_latency = t_stop -
          MonoDelta::FromMilliseconds(1000L * run_time_seconds_ / 4);
      stop_latch.WaitUntil(clear_latency);
      for (auto i = 0; i < cluster_->num_masters(); ++i) {
        CHECK_OK(cluster_->SetFlag(cluster_->master(i),
            "catalog_manager_inject_latency_load_ca_info_ms", "0"));
      }
    });
    SCOPED_CLEANUP({
      clear_latency_thread.join();
    });
    while (MonoTime::Now() < t_stop) {
      NO_FATALS(ConnectToCluster());
    }
    stop_latch.CountDown();
    NO_FATALS(cluster_->AssertNoCrashes());
  }

 protected:
  const int run_time_seconds_;
  const int latency_ms_;
  ExternalMiniClusterOptions cluster_opts_;
  std::shared_ptr<ExternalMiniCluster> cluster_;
};

// Test for KUDU-1927 in single-master configuration: verify that Kudu client
// successfully connects to Kudu cluster and always have CA certificate and
// authn token once connected. The test injects random latency into the process
// of loading the CA record from the system table. There is a high chance that
// during start-up the master server responds with ServiceUnavailable to
// ConnectToCluster RPC sent by the client. The client should retry in that
// case, connecting to the cluster eventually. Once successfully connected,
// the client must have Kudu IPKI CA certificate and authn token.
class SingleMasterConnectToClusterTest : public ConnectToClusterBaseTest {
 public:
  SingleMasterConnectToClusterTest()
      : ConnectToClusterBaseTest(5, 2500, 1) {
    // Add master-only flags.
    cluster_opts_.extra_master_flags.push_back(Substitute(
        "--catalog_manager_inject_latency_load_ca_info_ms=$0", latency_ms_));
  }
};

// Test for KUDU-1927 in multi-master configuration: verify that Kudu client
// successfully connects to Kudu cluster and always has CA certificate and
// authn token once connected. The test injects random latency into the process
// of loading the CA record from the system table. In addition, it uses short
// timeouts for leader failure detection. Due to many re-election events,
// sometimes elected master servers respond with ServiceUnavailable to
// ConnectToCluster RPC sent by the client. The client should retry in that
// case, connecting to the cluster eventually. Once successfully connected,
// the client must have Kudu IPKI CA certificate and authn token.
class MultiMasterConnectToClusterTest : public ConnectToClusterBaseTest {
 public:
  MultiMasterConnectToClusterTest()
      : ConnectToClusterBaseTest(120, 2000, 3) {
    constexpr int kHbIntervalMs = 100;
    // Add master-only flags.
    const vector<string> master_flags = {
      Substitute("--catalog_manager_inject_latency_load_ca_info_ms=$0", latency_ms_),
      "--raft_enable_pre_election=false",
      Substitute("--leader_failure_exp_backoff_max_delta_ms=$0", kHbIntervalMs * 3),
      "--leader_failure_max_missed_heartbeat_periods=1.0",
      Substitute("--raft_heartbeat_interval_ms=$0", kHbIntervalMs),
    };
    copy(master_flags.begin(), master_flags.end(),
         back_inserter(cluster_opts_.extra_master_flags));
  }
};

TEST_F(SingleMasterConnectToClusterTest, ConnectToCluster) {
  ASSERT_OK(cluster_->Start());
  Run();
}

TEST_F(MultiMasterConnectToClusterTest, ConnectToCluster) {
  SKIP_IF_SLOW_NOT_ALLOWED();
  ASSERT_OK(cluster_->Start());
  Run();
}

} // namespace client
} // namespace kudu

ext: cc

max_stars_repo_name: Kekdeng/kudu

max_issues_repo_name: Kekdeng/kudu

max_forks_repo_name: Kekdeng/kudu


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_BITWISE_FUNCTIONS_SCALAR_CTZ_HPP_INCLUDED
#define BOOST_SIMD_BITWISE_FUNCTIONS_SCALAR_CTZ_HPP_INCLUDED

#include <boost/simd/bitwise/functions/ctz.hpp>
#include <boost/simd/include/functions/scalar/ffs.hpp>
#include <boost/simd/include/functions/scalar/bitwise_cast.hpp>
#include <boost/dispatch/meta/as_integer.hpp>
#include <boost/assert.hpp>

#ifdef BOOST_MSVC
#include <intrin.h>
#endif

namespace boost { namespace simd { namespace ext
{
  BOOST_DISPATCH_IMPLEMENT          ( ctz_, tag::cpu_
                                    , (A0)
                                    , (scalar_< type64_<A0> >)
                                    )
  {
    typedef typename dispatch::meta::as_integer<A0>::type result_type;

    BOOST_FORCEINLINE result_type operator()(A0 a0) const
    {
      result_type that = bitwise_cast<result_type>(a0);
      BOOST_ASSERT_MSG( that, "ctz not defined for 0" );

      #if defined __GNUC__
      return __builtin_ctzll(that);
      #else
      return boost::simd::ffs(that)-1;
      #endif
    }
  };

  BOOST_DISPATCH_IMPLEMENT          ( ctz_, tag::cpu_
                                    , (A0)
                                    , (scalar_< type32_<A0> >)
                                    )
  {
    typedef typename dispatch::meta::as_integer<A0>::type result_type;

    BOOST_FORCEINLINE result_type operator()(A0 a0) const
    {
      result_type that = bitwise_cast<result_type>(a0);
      BOOST_ASSERT_MSG( that, "ctz not defined for 0" );

      #if defined __GNUC__
      return __builtin_ctz(that);
      #else
      return boost::simd::ffs(that)-1;
      #endif
    }
  };

  BOOST_DISPATCH_IMPLEMENT          ( ctz_, tag::cpu_
                                    , (A0)
                                    , (scalar_< arithmetic_<A0> >)
                                    )
  {
    typedef typename dispatch::meta::as_integer<A0>::type result_type;

    BOOST_FORCEINLINE result_type operator()(A0 a0) const
    {
      return result_type(boost::simd::ctz(uint32_t(a0)));
    }
  };
} } }

#endif


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

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

#ifndef BOOST_HANA_FWD_PREPEND_HPP
#define BOOST_HANA_FWD_PREPEND_HPP

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

BOOST_HANA_NAMESPACE_BEGIN
    //! Prepend an element to a monadic structure.
    //! @ingroup group-MonadPlus
    //!
    //! Given a monadic structure `xs` and an element `x`, `prepend` returns
    //! a new monadic structure which is the result of lifting `x` into the
    //! monadic structure and then combining that (to the left) with `xs`.
    //! In other words,
    //! @code
    //!     prepend(xs, x) == concat(lift<Xs>(x), xs)
    //! @endcode
    //!
    //! For sequences, this has the intuitive behavior of simply prepending
    //! an element to the beginning of the sequence, hence the name.
    //!
    //! > #### Rationale for not calling this `push_front`
    //! > While `push_front` is the de-facto name used in the standard library,
    //! > it also strongly suggests mutation of the underlying sequence, which
    //! > is not the case here. The author also finds that `push_front`
    //! > suggests too strongly the sole interpretation of putting an
    //! > element to the front of a sequence, whereas `prepend` is slightly
    //! > more nuanced and bears its name better for e.g. `hana::optional`.
    //!
    //!
    //! Signature
    //! ---------
    //! Given a MonadPlus `M`, the signature is
    //! @f$ \mathtt{prepend} : M(T) \times T \to M(T) @f$.
    //!
    //! @param xs
    //! A monadic structure that will be combined to the right of the element.
    //!
    //! @param x
    //! An element to combine to the left of the monadic structure.
    //!
    //!
    //! Example
    //! -------
    //! @include example/prepend.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
    constexpr auto prepend = [](auto&& xs, auto&& x) {
        return tag-dispatched;
    };
#else
    template <typename M, typename = void>
    struct prepend_impl : prepend_impl<M, when<true>> { };

    struct prepend_t {
        template <typename Xs, typename X>
        constexpr auto operator()(Xs&& xs, X&& x) const;
    };

    constexpr prepend_t prepend{};
#endif
BOOST_HANA_NAMESPACE_END

#endif // !BOOST_HANA_FWD_PREPEND_HPP

max_stars_repo_name: EuroLine/nheqminer


text: #include <boost/spirit/include/classic_parser_context.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**
 * $Id$
 *
 * Copyright (C)
 * 2015 - $Date$
 *     Martin Wolf <ndhist@martin-wolf.org>
 *
 * This file is distributed under the BSD 2-Clause Open Source License
 * (See LICENSE file).
 *
 */
#ifndef NDHIST_STORAGE_HPP_INCLUDED
#define NDHIST_STORAGE_HPP_INCLUDED 1

#include <string>

#include <boost/shared_ptr.hpp>

#include <ndhist/ndhist.hpp>

namespace ndhist {

/**
 * Saves the given ndhist object to the given file.
 *
 * @param h The ndhist object that should get stored.
 *
 * @param f The name of the file, with a propper file extension, so the file
 *     format can be determined.
 *     The following file extensions are supported for HDF files:
 *
 *       - ``".hdf"``
 *       - ``".h5"``
 *
 * @param where The parent group/location within the file where the histogram
 *     should get stored to.
 *
 * @param name The name of the data group for this histogram.
 *
 * @param overwrite Flag if an existing histogram of the same name should get
 *     overwritten (``true``) or not (``false``).
 *
 * @internal This function calls the Python function ``histsave`` implemented in
 *     the storage.py python module of the ndhist python package.
 */
void
histsave(
    ndhist const & h
  , std::string const & f
  , std::string const & where
  , std::string const & name
  , bool const overwrite=false
);

/**
 * Loads a ndhist object, that is stored within the given group within the
 * given file. The loaded ndhist object will live on the heap.
 *
 * @param f The name of the file, in which the histogram is stored. It must
 *     contain a propper file extension, so the file format can be determined.
 *     The following file extensions are supported for HDF files:
 *
 *       - ``".hdf"``
 *       - ``".h5"``
 *
 * @param histgroup The data group name within the file where the histogram is
 *     stored in. It's the group created by the histsave function.
 *
 * @internal This function calls the Python function ``histload`` implemented in
 *     the storage.py python module of the ndhist python package.
 */
boost::shared_ptr<ndhist>
histload(
    std::string const & f
  , std::string const & histgroup
);

}// namespace ndhist

#endif // !NDHIST_STORAGE_HPP_INCLUDED

max_stars_repo_name: martwo/ndhist

max_issues_repo_name: martwo/ndhist

max_forks_repo_name: martwo/ndhist


text:
// Modifications copyright (C) 2017, Baidu.com, Inc.
// Copyright 2017 The Apache Software Foundation

// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#include <stdlib.h>
#include <stdio.h>
#include <iostream>

#include <boost/utility.hpp>
#include <gtest/gtest.h>
#include "util/bit_util.h"
#include "util/cpu_info.h"

namespace palo {

TEST(BitUtil, Ceil) {
    EXPECT_EQ(BitUtil::ceil(0, 1), 0);
    EXPECT_EQ(BitUtil::ceil(1, 1), 1);
    EXPECT_EQ(BitUtil::ceil(1, 2), 1);
    EXPECT_EQ(BitUtil::ceil(1, 8), 1);
    EXPECT_EQ(BitUtil::ceil(7, 8), 1);
    EXPECT_EQ(BitUtil::ceil(8, 8), 1);
    EXPECT_EQ(BitUtil::ceil(9, 8), 2);
}

TEST(BitUtil, Popcount) {
    EXPECT_EQ(BitUtil::popcount(BOOST_BINARY(0 1 0 1 0 1 0 1)), 4);
    EXPECT_EQ(BitUtil::popcount_no_hw(BOOST_BINARY(0 1 0 1 0 1 0 1)), 4);
    EXPECT_EQ(BitUtil::popcount(BOOST_BINARY(1 1 1 1 0 1 0 1)), 6);
    EXPECT_EQ(BitUtil::popcount_no_hw(BOOST_BINARY(1 1 1 1 0 1 0 1)), 6);
    EXPECT_EQ(BitUtil::popcount(BOOST_BINARY(1 1 1 1 1 1 1 1)), 8);
    EXPECT_EQ(BitUtil::popcount_no_hw(BOOST_BINARY(1 1 1 1 1 1 1 1)), 8);
    EXPECT_EQ(BitUtil::popcount(0), 0);
    EXPECT_EQ(BitUtil::popcount_no_hw(0), 0);
}

}

int main(int argc, char** argv) {
    std::string conffile = std::string(getenv("PALO_HOME")) + "/conf/be.conf";
    if (!palo::config::init(conffile.c_str(), false)) {
        fprintf(stderr, "error read config file. \n");
        return -1;
    }
    init_glog("be-test");
    ::testing::InitGoogleTest(&argc, argv);
    palo::CpuInfo::init();
    return RUN_ALL_TESTS();
}

max_stars_repo_name: mengqinghuan/Doris

max_issues_repo_name: rinack/palo

max_forks_repo_name: rinack/palo


text:
/**
 * @file timer_test.cpp
 * @author Matthew Amidon, Ryan Curtin
 *
 * Test for the timer class
 *
 * mlpack is free software; you may redistribute it and/or modify it under the
 * terms of the 3-clause BSD license.  You should have received a copy of the
 * 3-clause BSD license along with mlpack.  If not, see
 * http://www.opensource.org/licenses/BSD-3-Clause for more information.
 */
#ifndef _WIN32
  #include <sys/time.h>
#endif

// For Sleep().
#ifdef _WIN32
  #include <windows.h>
#endif

#include <mlpack/core.hpp>

#include <boost/test/unit_test.hpp>
#include "test_tools.hpp"

using namespace mlpack;

BOOST_AUTO_TEST_SUITE(TimerTest);

/**
 * We should be able to start and then stop a timer multiple times and it should
 * save the value.
 */
BOOST_AUTO_TEST_CASE(MultiRunTimerTest)
{
  Timer::Start("test_timer");

  // On Windows (or, at least, in Windows not using VS2010) we cannot use
  // usleep() because it is not provided.  Instead we will use Sleep() for a
  // number of milliseconds.
  #ifdef _WIN32
  Sleep(10);
  #else
  usleep(10000);
  #endif

  Timer::Stop("test_timer");

  BOOST_REQUIRE_GE(Timer::Get("test_timer").count(), 10000);

  // Restart it.
  Timer::Start("test_timer");

  #ifdef _WIN32
  Sleep(10);
  #else
  usleep(10000);
  #endif

  Timer::Stop("test_timer");

  BOOST_REQUIRE_GE(Timer::Get("test_timer").count(), 20000);

  // Just one more time, for good measure...
  Timer::Start("test_timer");

  #ifdef _WIN32
  Sleep(20);
  #else
  usleep(20000);
  #endif

  Timer::Stop("test_timer");

  BOOST_REQUIRE_GE(Timer::Get("test_timer").count(), 40000);
}

BOOST_AUTO_TEST_CASE(TwiceStopTimerTest)
{
  Timer::Start("test_timer");
  Timer::Stop("test_timer");

  BOOST_REQUIRE_THROW(Timer::Stop("test_timer"), std::runtime_error);
}

BOOST_AUTO_TEST_CASE(TwiceStartTimerTest)
{
  Timer::Start("test_timer");

  BOOST_REQUIRE_THROW(Timer::Start("test_timer"), std::runtime_error);
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: NaxAlpha/mlpack-build

max_issues_repo_name: kosmaz/Mlpack

max_forks_repo_name: kosmaz/Mlpack


text:
//
//  Copyright (C) 2009-2012 Artyom Beilis (Tonkikh)
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
#include "test.h"
#include <booster/aio/deadline_timer.h>
#include <booster/aio/aio_category.h>
#include <booster/system_error.h>
#include <booster/aio/io_service.h>

#include <iostream>

booster::ptime occured1_at;
booster::ptime occured2_at;

struct time1 {
	booster::aio::io_service *srv;
	booster::aio::deadline_timer *timer2;
	void operator()(booster::system::error_code const &e)
	{
		TEST(!e);
		occured1_at = booster::ptime::now();
		timer2->cancel();
	}
};

struct time2 {
	booster::aio::io_service *srv;
	void operator()(booster::system::error_code const &e)
	{
		TEST(e.value()==booster::aio::aio_error::canceled);
		occured2_at = booster::ptime::now();
		srv->stop();

	}
};

int main()
{
	try {
		using booster::ptime;
		booster::aio::deadline_timer timer;
		booster::ptime now=booster::ptime::now(),tmp;
		timer.expires_at(now + ptime::seconds(1));
		TEST(timer.expires_at() == now + ptime::seconds(1));
		TEST((tmp = timer.expires_from_now()) <= ptime::milliseconds(1000) && tmp >=ptime::milliseconds(900));
		timer.expires_from_now(ptime::milliseconds(2000));
		TEST((tmp = timer.expires_at()) >= now + ptime::seconds(2));
		TEST(tmp <= now + ptime::milliseconds(2100));
		TEST((tmp = timer.expires_from_now()) <= ptime::seconds(2) && tmp >= ptime::milliseconds(1900));

		now = booster::ptime::now();
		timer.expires_from_now(ptime::milliseconds(100));
		timer.wait();
		TEST( (tmp = (booster::ptime::now() - now)) >= ptime::milliseconds(100));
		TEST( tmp < ptime::milliseconds(300));

		booster::aio::io_service srv;
		timer.set_io_service(srv);
		booster::aio::deadline_timer t2(srv);

		now = booster::ptime::now();

		t2.expires_from_now(ptime::seconds(2));
		timer.expires_from_now(ptime::milliseconds(100));
		time1 exec1 = { &srv, &t2 };
		time2 exec2 = { &srv };
		timer.async_wait(exec1);
		t2.async_wait(exec2);
		srv.run();
		TEST(occured2_at >= occured1_at);
		TEST(occured1_at >= now + ptime::milliseconds(100));
		TEST(occured2_at < now + ptime::milliseconds(300));
	}
	catch(std::exception const &e)
	{
		std::cerr << "Fail: " <<e.what() << std::endl;
		return 1;
	}
	std::cout << "Ok" << std::endl;
	return 0;
}

max_stars_repo_name: gatehouse/cppcms

max_issues_repo_name: gatehouse/cppcms

max_forks_repo_name: gatehouse/cppcms


text:
#include "forward_kinematics.h"
#include <iostream>
#include <stdio.h>
#include <Eigen/Dense>
#include <unordered_map>
#include <bitset>
#include <string>
#include <utility>
//perform the forward kinematics of the robot to figure out where you are
wsState* fk (configState* c)
{
  double theta0 = tick_to_radians(c->theta[0]);
  double theta1 = tick_to_radians(c->theta[1]);
  double theta2 = tick_to_radians(c->theta[2]);
  double theta3 = tick_to_radians(c->theta[3]);
  double theta4 = tick_to_radians(c->theta[4]);
  /*  Eigen::Matrix4d T_01 = DH(M_PI/2 , 0, 26.5, theta0);
  Eigen::Matrix4d T_12 = DH(0, 150, 0 , M_PI/2+theta1);
  Eigen::Matrix4d T_23 = DH(0, 150, 0, theta2);
  Eigen::Matrix4d T_34 = DH(-M_PI/2, 0, 0, M_PI/2+theta3);
  Eigen::Matrix4d T_45 = DH(0,0,116.525, theta4);

  Eigen::Matrix4d T_05 = T_01*T_12*T_23*T_34*T_45;

  wsState* outstate = new wsState;
  outstate->x = T_05(0,3);
  outstate->y = T_05(1,3);
  outstate->z = T_05(2,3);
  outstate->alpha = tick_to_radians(c->theta[0]+c->theta[1]+
      c->theta[2]+c->theta[3]+c->theta[4]);
  //TODO calculate angles based on rotation matrix
  */
  double c0 = cos(theta0);
  double s0 = sin(theta0);
  double c1 = cos(theta1);
  double s1 = sin(theta1);
  double c12 = cos(theta1+theta2);
  double s12 = sin(theta1+theta2);
  double c123 = cos(theta1+theta2+theta3);
  double s123 = sin(theta1+theta2+theta3);

  wsState* outstate = new wsState;
  outstate->x = c0*(150*(c1+c12) + 116.525*s123);
  outstate->y = s0*(150*(c1+c12) + 116.525*s123);
  outstate->z = 150*(s12+s1) - 116.525*c123 + 26.5;
  outstate->alpha = theta1+ theta2+ theta3;

  return outstate;

}//end forward_kinematics

Eigen::Matrix4d DH(double alpha,double a,double d,double theta)
{
  Eigen::Matrix4d T;
  T << cos(theta),sin(theta)*cos(alpha),-sin(theta)*sin(alpha),a*cos(theta),
    sin(theta), cos(theta)*cos(alpha), -cos(theta)*sin(alpha),a*sin(theta),
    0,sin(alpha),cos(alpha),d,
    0,0,0,1;
  return T;
}

//calculate Euclidean ndistance between two states
double distance(wsState* s1,wsState* s2)
{
  return (pow(s1->x - s2->x,2)+pow(s1->y-s2->y,2)+pow(s1->z-s2->z,2)+pow(s1->alpha-s2->alpha,2));
}

configState* clone_configstate(configState* c){

  configState* clone = new configState;
  clone->theta[0] = c->theta[0];
  clone->theta[1] = c->theta[1];
  clone->theta[2] = c->theta[2];
  clone->theta[3] = c->theta[3];
  clone->theta[4] = c->theta[4];
  return clone;
}

double tick_to_radians(int i){
  return (M_PI/100)*i;
}

wsState* create_wsstate(){
   return (wsState*)malloc(sizeof(struct wsState));
}

configState* create_configstate(){
  return (configState*)malloc(sizeof(struct configState));
}

visData* create_visdata(){
  return (visData*)malloc(sizeof(struct visData));
}

void deallocate_wsstate(wsState* w){
  if(w != 0)
    free(w);
}

void deallocate_configstate(configState* c){
  if(c != 0)
    free(c);
}

void deallocate_visdata(visData* v){
  if(v != 0)
    free(v);
}

void wsstate_tostring(wsState* w){
    printf("Work Space State: x:%f, y:%f, z:%f\n",
      w->x, w->y, w->z);
}

void configstate_tostring(configState* c){
  printf("Theta1: %i, Theta2: %i, Theta3: %i, Theta4: %i, Theta5: %i\n"
      , c->theta[0], c->theta[1],c->theta[2], c->theta[3], c->theta[4]);
}