text:
//=======================================================================
// Copyright Baptiste Wicht 2011-2016.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef SPIRIT_PARSER_ERROR_HANDLER_H
#define SPIRIT_PARSER_ERROR_HANDLER_H

#include <string>
#include <memory>
#include <iostream> //Temporary

#include "boost_cfg.hpp"

#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/variant.hpp>
#include <boost/spirit/home/x3/support/ast/position_tagged.hpp>

#include <boost/fusion/adapted/boost_tuple.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

#include "parser_x3/error_reporting.hpp"

namespace boost { namespace spirit { namespace x3 {

struct file_position_tagged : position_tagged {
    int id_file = -1;

    bool operator==(const x3::file_position_tagged& rhs) const {
        return id_first == rhs.id_first && id_last == rhs.id_last && id_file == rhs.id_file;
    }

    bool operator!=(const x3::file_position_tagged& rhs) const {
        return id_first != rhs.id_first || id_last != rhs.id_last || id_file != rhs.id_file;
    }
};

}}}

/* Error handling */

namespace x3_grammar {
    template <typename Iterator>
    using error_handler = boost::spirit::x3::error_handler<Iterator>;

    typedef std::string::const_iterator iterator_type;
    typedef boost::spirit::x3::phrase_parse_context<boost::spirit::x3::ascii::space_type>::type phrase_context_type;
    typedef error_handler<iterator_type> error_handler_type;

    struct global_error_handler {
        void register_handler(iterator_type it, iterator_type end, std::string file){
            error_handlers.emplace_back(it, end, std::cerr, std::move(file));
        }

        error_handler_type& current(){
            return error_handlers.back();
        }

        template<typename AST, std::enable_if_t<std::is_base_of<boost::spirit::x3::file_position_tagged, AST>::value, int> = 42>
        void tag(AST& t, iterator_type it, iterator_type end){
            t.id_file = error_handlers.size() - 1;
            error_handlers[t.id_file].tag(t, it, end);
        }

        template<typename AST, std::enable_if_t<!std::is_base_of<boost::spirit::x3::file_position_tagged, AST>::value, int> = 42>
        void tag(AST&, iterator_type, iterator_type){
            //Nothing to do here
        }

        void operator()(iterator_type err_pos, const std::string& message);
        void operator()(iterator_type err_pos, iterator_type err_last, const std::string& message);
        void operator()(const boost::spirit::x3::file_position_tagged& t, const std::string& message);

        std::string to_string(const boost::spirit::x3::file_position_tagged& t, const std::string& message = "");

        void semantical_exception(const std::string& message, const boost::spirit::x3::file_position_tagged& t);

    private:
        std::vector<error_handler_type> error_handlers;
    };

    // tag used to get our error handler from the context
    using error_handler_tag = boost::spirit::x3::error_handler_tag;

    struct error_handler_base {
        template <typename Iterator, typename Exception, typename Context>
        boost::spirit::x3::error_handler_result on_error(Iterator& /*first*/, Iterator const& /*last*/, Exception const& x, Context const& context){
            std::string message = "Error! Expecting: " + x.which() + " here:";
            auto& error_handler = boost::spirit::x3::get<error_handler_tag>(context).get();
            error_handler(x.where(), message);
            return boost::spirit::x3::error_handler_result::fail;
        }
    };

    // Used to annotate
    struct annotation_base {
        template <typename T, typename Iterator, typename Context>
        inline void on_success(Iterator const& first, Iterator const& last, T& ast, Context const& context){
            auto& error_handler = boost::spirit::x3::get<error_handler_tag>(context).get();
            error_handler.tag(ast, first, last);
        }
    };

} //end of namespace x3_grammar

#endif

max_stars_repo_name: wichtounet/eddic

max_issues_repo_name: wichtounet/eddic

max_forks_repo_name: wichtounet/eddic


text:
#include <stdio.h>
#include <boost/multi_array.hpp>
#include <map>
#include <string>
#include <iostream>
#include <matio.h>
#include "matStor.h"

// state was stored in a sqlite table --
// but it would be better for backup & introspection purposes
// to store it in a matlab file.
// therefore the task is to emulate sql.h and sql.cpp

#define MATIOTYP size_t

#define max(a,b) (a > b ? a : b)

using namespace std;

MatStor::MatStor(const char *fname)
{
	m_name = string(fname);
}
MatStor::~MatStor() {}
void MatStor::load()
{
	mat_t *matfp = Mat_Open(m_name.c_str(), MAT_ACC_RDWR);
	if (matfp == 0) {
		printf("MatStor: %s: nothing to load\n", m_name.c_str());
		return;
	}

	//need to read the matrices in.
	matvar_t *var = Mat_VarReadNext(matfp);
	while (var != NULL) {
		string nam = string(var->name);

		if (var->rank == 3) {
			if (var->class_type == MAT_C_SINGLE) {
				// switch from matlab order to C order.
				arrayf3 r(boost::extents[var->dims[2]][var->dims[1]][var->dims[0]]);
				float *w = (float *)var->data;
				for (MATIOTYP a=0; a<var->dims[2]; a++) {
					for (MATIOTYP b=0; b<var->dims[1]; b++) {
						for (MATIOTYP c=0; c<var->dims[0]; c++) {
							r[a][b][c] = *w++;
						}
					}
				}
				m_datf3.insert(pair<string,arrayf3>(nam,r));
			} else if (var->class_type == MAT_C_DOUBLE) {
				arrayd3 r(boost::extents[var->dims[2]][var->dims[1]][var->dims[0]]);
				double *w = (double *)var->data;
				for (MATIOTYP a=0; a<var->dims[2]; a++) {
					for (MATIOTYP b=0; b<var->dims[1]; b++) {
						for (MATIOTYP c=0; c<var->dims[0]; c++) {
							r[a][b][c] = *w++;
						}
					}
				}
				m_datd3.insert(pair<string,arrayd3>(nam,r));
			} else {
				cout << "unknown data class for matlab variable " << nam << endl;
			}
		} else if (var->rank == 2) {
			if (var->dims[1] > 1) {
				if (var->class_type == MAT_C_SINGLE) {
					arrayf2 r(boost::extents[var->dims[1]][var->dims[0]]);
					float *w = (float *)var->data;
					for (MATIOTYP a=0; a<var->dims[1]; a++) {
						for (MATIOTYP b=0; b<var->dims[0]; b++) {
							r[a][b] = *w++;
						}
					}
					m_datf2.insert(pair<string,arrayf2>(nam,r));
				} else if (var->class_type == MAT_C_DOUBLE) {
					arrayd2 r(boost::extents[var->dims[1]][var->dims[0]]);
					double *w = (double *)var->data;
					for (MATIOTYP a=0; a<var->dims[1]; a++) {
						for (MATIOTYP b=0; b<var->dims[0]; b++) {
							r[a][b] = *w++;
						}
					}
					m_datd2.insert(pair<string,arrayd2>(nam,r));
				} else {
					cout << "unknown data class for matlab variable " << nam << endl;
				}
			} else { // RANK IS 1
				if (var->class_type == MAT_C_INT32) {
					vector<int> r(var->dims[0]);
					int *w = (int *)var->data;
					for (MATIOTYP a=0; a<var->dims[0]; a++) {
						r[a] = *w++;
					}
					m_dati1.insert( pair_int_1(nam,r) );
				} else if (var->class_type == MAT_C_SINGLE) {
					vector<float> r(var->dims[0]);
					float *w = (float *)var->data;
					for (MATIOTYP a=0; a<var->dims[0]; a++) {
						r[a] = *w++;
					}
					m_datf1.insert(pair_float_1(nam,r));
				} else if (var->class_type == MAT_C_DOUBLE) {
					vector<double> r(var->dims[0]);
					double *w = (double *)var->data;
					for (MATIOTYP a=0; a<var->dims[0]; a++) {
						r[a] = *w++;
					}
					m_datd1.insert(pair<string,vector<double> >(nam,r));
				} else if (var->class_type == MAT_C_STRUCT) {
					map_float_1 fm;
					int n = Mat_VarGetNumberOfFields(var);
					char *const *f = Mat_VarGetStructFieldnames(var);
					for (int i=0; i<n; i++) {
						matvar_t *v = Mat_VarGetStructFieldByName(var,f[i],0);
						if (v->rank == 2 && v->class_type == MAT_C_SINGLE) {
							string fs = string(v->name);
							vector<float> r(v->dims[0]);
							float *w = (float *)v->data;
							for (MATIOTYP a=0; a<v->dims[0]; a++) {
								r[a] = *w++;
							}
							fm.insert(pair_float_1(fs,r));
						}
					}
					if (!fm.empty()) {
						m_struct1.insert(pair<string,map_float_1>(nam,fm));
					}
				} else {
					cout << "unknown data class for matlab variable " << nam << endl;
				}
			}
		}
		Mat_VarFree(var);
		var = Mat_VarReadNext(matfp);
	}
	Mat_Close(matfp);
}
void MatStor::save(bool append)
{
	mat_t *matfp = 0;

	if (append) {
		matfp = Mat_Open(m_name.c_str(), MAT_ACC_RDWR);
	}

	if (matfp == 0) {
		printf("MatStor: will create/overwrite %s\n", m_name.c_str());
		matfp = Mat_CreateVer(m_name.c_str(),NULL, MAT_FT_MAT73);
	}

	for (auto &x : m_datf3) {
		string nam = x.first;
		arrayf3 dat = x.second;
		const arrayf3::size_type *dims = dat.shape();
		MATIOTYP matdims[3];
		matdims[0] = dims[2];
		matdims[1] = dims[1];
		matdims[2] = dims[0];
		matvar_t *var = Mat_VarCreate(nam.c_str(), MAT_C_SINGLE, MAT_T_SINGLE,
		                              3, matdims, dat.data(), 0);
		Mat_VarWrite(matfp, var, MAT_COMPRESSION_NONE);
		Mat_VarFree(var);
	}
	for (auto &x : m_datd3) {
		string nam = x.first;
		arrayd3 dat = x.second;
		const arrayd3::size_type *dims = dat.shape();
		MATIOTYP matdims[3];
		matdims[0] = dims[2];
		matdims[1] = dims[1];
		matdims[2] = dims[0];
		matvar_t *var = Mat_VarCreate(nam.c_str(), MAT_C_DOUBLE, MAT_T_DOUBLE,
		                              3, matdims, dat.data(), 0);
		Mat_VarWrite(matfp, var, MAT_COMPRESSION_NONE);
		Mat_VarFree(var);
	}
	for (auto &x : m_datf2) {
		string nam = x.first;
		arrayf2 dat = x.second;
		const arrayf2::size_type *dims = dat.shape();
		MATIOTYP matdims[2];
		matdims[0] = dims[1];
		matdims[1] = dims[0];
		matvar_t *var = Mat_VarCreate(nam.c_str(), MAT_C_SINGLE, MAT_T_SINGLE,
		                              2, matdims, dat.data(), 0);
		Mat_VarWrite(matfp, var, MAT_COMPRESSION_NONE);
		Mat_VarFree(var);
	}
	for (auto &x : m_datd2) {
		string nam = x.first;
		arrayd2 dat = x.second;
		const arrayd2::size_type *dims = dat.shape();
		MATIOTYP matdims[2];
		matdims[0] = dims[1];
		matdims[1] = dims[0];
		matvar_t *var = Mat_VarCreate(nam.c_str(), MAT_C_DOUBLE, MAT_T_DOUBLE,
		                              2, matdims, dat.data(), 0);
		Mat_VarWrite(matfp, var, MAT_COMPRESSION_NONE);
		Mat_VarFree(var);
	}
	for (auto &x : m_dati1) {
		string nam = x.first;
		vector<int> dat = x.second;
		MATIOTYP dims[2] = {1,1};
		dims[0] = (size_t)dat.size();
		matvar_t *var = Mat_VarCreate(nam.c_str(), MAT_C_INT32, MAT_T_INT32,
		                              2, dims, dat.data(), 0);
		Mat_VarWrite(matfp, var, MAT_COMPRESSION_NONE);
		Mat_VarFree(var);
	}
	for (auto &x : m_datf1) {
		string nam = x.first;
		vector<float> dat = x.second;
		MATIOTYP dims[2] = {1,1};
		dims[0] = (size_t)dat.size();
		matvar_t *var = Mat_VarCreate(nam.c_str(), MAT_C_SINGLE, MAT_T_SINGLE,
		                              2, dims, dat.data(), 0);
		Mat_VarWrite(matfp, var, MAT_COMPRESSION_NONE);
		Mat_VarFree(var);
	}
	for (auto &x : m_datd1) {
		string nam = x.first;
		vector<double> dat = x.second;
		MATIOTYP dims[2] = {1,1};
		dims[0] = (size_t)dat.size();
		matvar_t *var = Mat_VarCreate(nam.c_str(), MAT_C_DOUBLE, MAT_T_DOUBLE,
		                              2, dims, dat.data(), 0);
		Mat_VarWrite(matfp, var, MAT_COMPRESSION_NONE);
		Mat_VarFree(var);
	}
	for (auto &x : m_struct1) {
		string nam = x.first;
		map_float_1 *f = &(x.second);
		vector<const char *> fields;
		for (auto &y : *f)
			fields.push_back(y.first.c_str());
		MATIOTYP dims[2] = {1,1};
		matvar_t *var = Mat_VarCreateStruct(nam.c_str(), 2, dims, &fields[0], fields.size());
		for (auto &y : *f) {
			string fieldnam = y.first;
			vector<float> dat = y.second;
			dims[0] = (size_t)dat.size();
			matvar_t *field = Mat_VarCreate(NULL,MAT_C_SINGLE,MAT_T_SINGLE,
			                                2, dims, dat.data(), 0);
			Mat_VarSetStructFieldByName(var, fieldnam.c_str(), 0, field);
		}
		Mat_VarWrite(matfp, var, MAT_COMPRESSION_NONE);
		Mat_VarFree(var);
	}
	Mat_Close(matfp);
}
void MatStor::save()
{
	save(false);
}
void MatStor::clear()
{
	// 1-d
	m_dati1.clear();
	m_datf1.clear();
	m_datd1.clear();

	// 2-d
	m_dati16_2.clear();
	m_datf2.clear();
	m_datd2.clear();

	// 3-d
	m_datf3.clear();
	m_datd3.clear();

	// structs
	m_struct1.clear();
}
void MatStor::setInt(int ch, const char *name, int val)
{
	map_int_1::iterator it = m_dati1.find(string(name));
	if (it != m_dati1.end()) {
		vector<int> *r = &((*it).second);
		if (ch+1 > (int)(r->size()))
			r->resize(ch+1, val);
		(*r)[ch] = val;
	} else {
		vector<int> r(ch+1);
		r[ch] = val;
		m_dati1.insert(pair_int_1(string(name),r));
	}
}
void MatStor::setInt(const char *name, vector<int> v)
{
	map_int_1::iterator it = m_dati1.find(string(name));
	if (it != m_dati1.end()) {
		vector<int> *r = &((*it).second);
		(*r) = v;
	} else {
		m_dati1.insert(pair_int_1(string(name),v));
	}
}
int MatStor::getInt(int ch, const char *name, int def)
{
	map_int_1::iterator it = m_dati1.find(string(name));
	if (it != m_dati1.end()) {
		vector<int> *r = &((*it).second);
		if (ch < (int)r->size())
			return (*it).second[ch];
	}
	return def;
}
void MatStor::setValue(int ch, const char *name, float val)
{
	map_float_1::iterator it = m_datf1.find(string(name));
	if (it != m_datf1.end()) {
		vector<float> *r = &((*it).second);
		if (ch+1 > (int)(r->size()))
			r->resize(ch+1, val);
		(*r)[ch] = val;
	} else {
		vector<float> r(ch+1);
		r[ch] = val;
		m_datf1.insert(pair_float_1(string(name),r));
	}
}
void MatStor::setValue(const char *name, vector<float> v)
{
	map_float_1::iterator it = m_datf1.find(string(name));
	if (it != m_datf1.end()) {
		vector<float> *r = &((*it).second);
		(*r) = v;
	} else {
		m_datf1.insert(pair_float_1(string(name),v));
	}
}
float MatStor::getValue(int ch, const char *name, float def)
{
	map_float_1::iterator it = m_datf1.find(string(name));
	if (it != m_datf1.end()) {
		vector<float> *r = &((*it).second);
		if (ch < (int)r->size())
			return (*it).second[ch];
	}
	return def;
}
void MatStor::setDouble(int ch, const char *name, double val)
{
	map<string, vector<double> >::iterator it = m_datd1.find(string(name));
	if (it != m_datd1.end()) {
		vector<double> *r = &((*it).second);
		if (ch+1 > (int)(r->size()))
			r->resize(ch+1, val);
		(*r)[ch] = val;
	} else {
		vector<double> r(ch+1);
		r[ch] = val;
		m_datd1.insert(pair<string,vector<double> >(string(name),r));
	}
}
double MatStor::getDouble(int ch, const char *name, double def)
{
	map<string, vector<double> >::iterator it = m_datd1.find(string(name));
	if (it != m_datd1.end()) {
		vector<double> *r = &((*it).second);
		if (ch < (int)r->size())
			return (*it).second[ch];
	}
	return def;
}
void MatStor::set_i16_2(int m, int n, const char *name, i16 val)
{
	// n increments faster than m.
	map<string, arrayi16_2>::iterator it = m_dati16_2.find(string(name));
	if (it != m_dati16_2.end()) {
		arrayi16_2 *r = &((*it).second);
		const arrayi16_2::size_type *dims = r->shape();
		if (m+1 > (int)dims[0] || n+1 > (int)dims[1])
			r->resize(boost::extents[max(m+1,(int)dims[0])][max(n+1,(int)dims[1])]);
		(*r)[m][n] = val;
	} else {
		arrayi16_2 r(boost::extents[m+1][n+1]);
		r[m][n] = val;
		m_dati16_2.insert(pair<string,arrayi16_2>(string(name), r));
	}
}
i16 MatStor::get_i16_2(int m, int n, const char *name, i16 def)
{
	map<string, arrayi16_2>::iterator it = m_dati16_2.find(string(name));
	if (it != m_dati16_2.end()) {
		arrayi16_2 *r = &((*it).second);
		const arrayi16_2::size_type *dims = r->shape();
		if (m < (int)dims[0] && n < (int)dims[1])
			return (*it).second[m][n];
	}
	return def;
}
void MatStor::setValue2(int ch, int un, const char *name, float val)
{
	// un increments faster than ch.
	map<string, arrayf2>::iterator it = m_datf2.find(string(name));
	if (it != m_datf2.end()) {
		arrayf2 *r = &((*it).second);
		const arrayf2::size_type *dims = r->shape();
		if (ch+1 > (int)dims[0] || un+1 > (int)dims[1])
			r->resize(boost::extents[max(ch+1,(int)dims[0])][max(un+1,(int)dims[1])]);
		(*r)[ch][un] = val;
	} else {
		arrayf2 r(boost::extents[ch+1][un+1]);
		r[ch][un] = val;
		m_datf2.insert(pair<string,arrayf2>(string(name), r));
	}
}
void MatStor::setDouble2(int ch, int un, const char *name, double val)
{
	// un increments faster than ch.
	map<string, arrayd2>::iterator it = m_datd2.find(string(name));
	if (it != m_datd2.end()) {
		arrayd2 *r = &((*it).second);
		const arrayd2::size_type *dims = r->shape();
		if (ch+1 > (int)dims[0] || un+1 > (int)dims[1])
			r->resize(boost::extents[max(ch+1,(int)dims[0])][max(un+1,(int)dims[1])]);
		(*r)[ch][un] = val;
	} else {
		arrayd2 r(boost::extents[ch+1][un+1]);
		r[ch][un] = val;
		m_datd2.insert(pair<string,arrayd2>(string(name), r));
	}
}
void MatStor::setValue3(int ch, int un, const char *name, float *val, int siz)
{
	// [ch][un][siz]
	map<string, arrayf3>::iterator it = m_datf3.find(string(name));
	if (it != m_datf3.end()) {
		arrayf3 *r = &((*it).second);
		const arrayf3::size_type *dims = r->shape();
		if (ch+1 > (int)dims[0] || un+1 > (int)dims[1] || siz > (int)dims[2])
			r->resize(boost::extents[max(ch+1,(int)dims[0])][max(un+1,(int)dims[1])][max(siz,(int)dims[2])]);
		for (int i=0; i<siz; i++)
			(*r)[ch][un][i] = *val++;
	} else {
		arrayf3 r(boost::extents[ch+1][un+1][siz]);
		for (int i=0; i<siz; i++)
			r[ch][un][i] = *val++;
		m_datf3.insert(pair<string,arrayf3>(string(name), r));
	}
}
void MatStor::setDouble3(int ch, int un, const char *name, double *val, int siz)
{
	// [ch][un][siz]
	map<string, arrayd3>::iterator it = m_datd3.find(string(name));
	if (it != m_datd3.end()) {
		arrayd3 *r = &((*it).second);
		const arrayd3::size_type *dims = r->shape();
		if (ch+1 > (int)dims[0] || un+1 > (int)dims[1] || siz > (int)dims[2])
			r->resize(boost::extents[max(ch+1,(int)dims[0])][max(un+1,(int)dims[1])][max(siz,(int)dims[2])]);
		for (int i=0; i<siz; i++)
			(*r)[ch][un][i] = *val++;
	} else {
		arrayd3 r(boost::extents[ch+1][un+1][siz]);
		for (int i=0; i<siz; i++)
			r[ch][un][i] = *val++;
		m_datd3.insert(pair<string,arrayd3>(string(name), r));
	}
}
void MatStor::setStructValue(const char *name, const char *field, size_t idx, float val)
{
	map<string, map_float_1>::iterator it = m_struct1.find(string(name));
	if (it != m_struct1.end()) {
		map_float_1 *f = &((*it).second);
		map_float_1::iterator it2 = f->find(string(field));
		if (it2 != f->end()) {
			vector<float> *r = &((*it2).second);
			if (idx+1 > r->size())
				r->resize(idx+1);
			(*r)[idx] = val;
		} else {
			vector<float> r(idx+1);
			r[idx] = val;
			f->insert(pair_float_1(string(field),r));
		}
	} else {
		vector<float> r(idx+1);
		r[idx] = val;
		map_float_1 f;
		f.insert(pair_float_1(string(field),r));
		m_struct1.insert(pair<string,map_float_1>(string(name),f));
	}
}
float MatStor::getValue2(int ch, int un, const char *name, float def)
{
	map<string, arrayf2>::iterator it = m_datf2.find(string(name));
	if (it != m_datf2.end()) {
		arrayf2 *r = &((*it).second);
		const arrayf2::size_type *dims = r->shape();
		if (ch < (int)dims[0] && un < (int)dims[1])
			return (*it).second[ch][un];
	}
	return def;
}
double MatStor::getDouble2(int ch, int un, const char *name, double def)
{
	map<string, arrayd2>::iterator it = m_datd2.find(string(name));
	if (it != m_datd2.end()) {
		arrayd2 *r = &((*it).second);
		const arrayd2::size_type *dims = r->shape();
		if (ch < (int)dims[0] && un < (int)dims[1])
			return (*it).second[ch][un];
	}
	return def;
}
void MatStor::getValue3(int ch, int un, const char *name, float *val, int siz)
{
	map<string, arrayf3>::iterator it = m_datf3.find(string(name));
	if (it != m_datf3.end()) {
		arrayf3 *r = &((*it).second);
		const arrayf3::size_type *dims = r->shape();
		if (ch < (int)dims[0] && un < (int)dims[1] && siz <= (int)dims[2]) {
			for (int i=0; i<siz; i++) {
				*val++ = (*r)[ch][un][i];
			}
		}
	}
}
void MatStor::getDouble3(int ch, int un, const char *name, double *val, int siz)
{
	map<string, arrayd3>::iterator it = m_datd3.find(string(name));
	if (it != m_datd3.end()) {
		arrayd3 *r = &((*it).second);
		const arrayd3::size_type *dims = r->shape();
		if (ch < (int)dims[0] && un < (int)dims[1] && siz <= (int)dims[2]) {
			for (int i=0; i<siz; i++) {
				*val++ = (*r)[ch][un][i];
			}
		}
	}
}
float MatStor::getStructValue(const char *name, const char *field, size_t idx, float def)
{
	map<string, map_float_1>::iterator it = m_struct1.find(string(name));
	if (it != m_struct1.end()) {
		map_float_1 *f = &((*it).second);
		map_float_1::iterator it2 = f->find(string(field));
		if (it2 != f->end()) {
			vector<float> *r = &((*it2).second);
			if (idx < r->size()) {
#ifdef DEBUG
				printf("loaded %s.%s: %f\n", name, field, r->at(idx));
#endif
				return (*r)[idx];
			}
		}
	}
#ifdef DEBUG
	printf("failed to load %s.%s (default: %f)\n", name, field, def);
#endif
	return def;
}

void MatStor::printStructs()
{
	for (map<string, map_float_1>::iterator it = m_struct1.begin(); it != m_struct1.end(); it++) {
		string struct_name = (*it).first;
		map_float_1 f = (*it).second;
		for (map_float_1::iterator it2 = f.begin(); it2 != f.end(); it2++) {
			string field_name = (*it2).first;
			vector<float> v = (*it2).second;
			printf("%s.%s = [ ", struct_name.c_str(), field_name.c_str());
			for (vector<float>::iterator it3 = v.begin(); it3 != v.end(); it3++) {
				printf("%f ", (*it3));
			}
			printf("]\n");
		}
	}
}

#ifdef TEST
//compile with:
// g++ -g -std=c++11 -DTEST matStor.cpp -lmatio -lhdf5_serial -o matio_test
int main(void)
{
	MatStor ms("test.mat");
	ms.load();
	if (1) {
		int err = 0;
		//verify, test.mat already created.

		// int32 (a)
		for (int i=0; i<10; i++) {
			int v;
			v = ms.getInt(i, "i1a", 0);
			if (v != (float)i) err++;
			v = ms.getInt(i, "i1b", 0);
			if (v != (float)i) err++;
		}

		for (int i=0; i<10; i++) {
			float v;
			v = ms.getValue(i, "f1a", 0.f);
			if (v != (float)i) err++;
			v = ms.getValue(i, "f1b", 0.f);
			if (v != (float)i) err++;
		}
		float f = 0.f;
		for (int b=8; b>=0; b--) {
			for (int a=9; a>=0; a--) {
				float v = ms.getValue2(b, a, "f2", 0.0);
				if (v != f) err++;
				f += 1.f;
			}
		}
		f = 0.f;
		for (int c=7; c>=0; c--) {
			for (int b=8; b>=0; b--) {
				float r[10];
				ms.getValue3(c, b, "f3", &r[0], 10);
				for (int i=0; i<10; i++) {
					if (r[i] != f) err++;
					f += 1.f;
				}
			}
		}
		// test loading structs
		float v;
		v = ms.getStructValue("foo","bar",0,0);
		if (v != 1) err++;
		v = ms.getStructValue("foo","bar",1,0);
		if (v != 2) err++;
		v = ms.getStructValue("foo","bar",2,0);
		if (v != 3) err++;
		v = ms.getStructValue("foo","baz",0,0);
		if (fabs(v-3.14) > 1e-6) err++;

		cout << err << " errors " << endl;
	}

	// make 1d int32 vector
	for (int i=0; i<10; i++)
		ms.setInt(i, "i1a", (int)i);

	// make 1d int32 vector (std::vector interface)
	vector<int> i1b {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
	ms.setInt("i1b", i1b);

	// make a 1d float vector
	for (int i=9; i>=0; i--)
		ms.setValue(i, "f1a", (float)i);

	// make a 1d float vector (std::vector interface)
	vector<float> f1b {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};
	ms.setValue("f1b", f1b);

	// make 2d float vector.
	float f = 0.f;
	for (int b=8; b>=0; b--) {
		for (int a=9; a>=0; a--) {
			ms.setValue2(b, a, "f2", f);
			f += 1.f;
		}
	}
	//3d vector.
	f = 0.f;
	for (int c=7; c>=0; c--) {
		for (int b=8; b>=0; b--) {
			vector<float> r(10);
			for (int i=0; i<10; i++) {
				r[i] = f;
				f += 1.f;
			}
			ms.setValue3(c, b, "f3", r.data(), 10);
		}
	}
	// test saving struct
	ms.setStructValue("foo","bar",0,1);
	ms.setStructValue("foo","bar",1,2);
	ms.setStructValue("foo","bar",2,3);
	ms.setStructValue("foo","baz",0,3.14);

	// need testcase for vector insertion (and reading)routines

	ms.save();
}
#endif

ext: cpp

max_stars_repo_name: joeyo/spk

max_issues_repo_name: joeyo/spk

max_forks_repo_name: joeyo/spk


text:
// Boost result_of library

//  Copyright Douglas Gregor 2003-2004. Use, modification and
//  distribution is subject to the Boost Software License, Version
//  1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#include <boost/config.hpp>

// For more information, see http://www.boost.org/libs/utility
#include <boost/utility/result_of.hpp>
#include <utility>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>

struct int_result_type
{
  typedef int result_type;
  result_type operator()(float);
};

struct int_result_of
{
  template<typename F> struct result { typedef int type; };
  result<int_result_of(double)>::type operator()(double);
  result<const int_result_of(double)>::type operator()(double) const;
  result<int_result_of()>::type operator()();
  result<volatile int_result_of()>::type operator()() volatile;
};

struct int_result_type_and_float_result_of_and_char_return
{
  typedef int result_type;
  template<typename F> struct result { typedef float type; };
  char operator()(char);
};

template<typename T>
struct int_result_type_template
{
  typedef int result_type;
  result_type operator()(float);
};

template<typename T>
struct int_result_of_template
{
  template<typename F> struct result;
  template<typename This, typename That> struct result<This(That)> { typedef int type; };
  typename result<int_result_of_template<T>(double)>::type operator()(double);
  typename result<const int_result_of_template<T>(double)>::type operator()(double) const;
  typename result<int_result_of_template<T>(double)>::type operator()();
  typename result<volatile int_result_of_template<T>(double)>::type operator()() volatile;
};

template<typename T>
struct int_result_type_and_float_result_of_and_char_return_template
{
  typedef int result_type;
  template<typename F> struct result;
  template<typename This, typename That> struct result<This(That)> { typedef float type; };
  char operator()(char);
};

template<typename T>
struct cv_overload_check {};

struct result_of_member_function_template
{
  template<typename F> struct result;

  template<typename This, typename That> struct result<This(That)> { typedef That type; };
  template<class T> typename result<result_of_member_function_template(T)>::type operator()(T);

  template<typename This, typename That> struct result<const This(That)> { typedef cv_overload_check<const That> type; };
  template<class T> typename result<const result_of_member_function_template(T)>::type operator()(T) const;

  template<typename This, typename That> struct result<volatile This(That)> { typedef cv_overload_check<volatile That> type; };
  template<class T> typename result<volatile result_of_member_function_template(T)>::type operator()(T) volatile;

  template<typename This, typename That> struct result<const volatile This(That)> { typedef cv_overload_check<const volatile That> type; };
  template<class T> typename result<const volatile result_of_member_function_template(T)>::type operator()(T) const volatile;

  template<typename This, typename That> struct result<This(That &, That)> { typedef That & type; };
  template<class T> typename result<result_of_member_function_template(T &, T)>::type operator()(T &, T);

  template<typename This, typename That> struct result<This(That const &, That)> { typedef That const & type; };
  template<class T> typename result<result_of_member_function_template(T const &, T)>::type operator()(T const &, T);

  template<typename This, typename That> struct result<This(That volatile &, That)> { typedef That volatile & type; };
  template<class T> typename result<result_of_member_function_template(T volatile &, T)>::type operator()(T volatile &, T);

  template<typename This, typename That> struct result<This(That const volatile &, That)> { typedef That const volatile & type; };
  template<class T> typename result<result_of_member_function_template(T const volatile &, T)>::type operator()(T const volatile &, T);
};

struct no_result_type_or_result
{
  short operator()(double);
  cv_overload_check<const short> operator()(double) const;
  cv_overload_check<volatile short> operator()(double) volatile;
  cv_overload_check<const volatile short> operator()(double) const volatile;
  int operator()();
  cv_overload_check<const int> operator()() const;
  cv_overload_check<volatile int> operator()() volatile;
  cv_overload_check<const volatile int> operator()() const volatile;
#if !defined(BOOST_NO_RVALUE_REFERENCES)
  short operator()(int&&);
  int operator()(int&);
  long operator()(int const&);
#endif
};

template<typename T>
struct no_result_type_or_result_template
{
  short operator()(double);
  cv_overload_check<const short> operator()(double) const;
  cv_overload_check<volatile short> operator()(double) volatile;
  cv_overload_check<const volatile short> operator()(double) const volatile;
  int operator()();
  cv_overload_check<const int> operator()() const;
  cv_overload_check<volatile int> operator()() volatile;
  cv_overload_check<const volatile int> operator()() const volatile;
#if !defined(BOOST_NO_RVALUE_REFERENCES)
  short operator()(int&&);
  int operator()(int&);
  long operator()(int const&);
#endif
};

// sfinae_tests are derived from example code from Joel de Guzman,
// which demonstrated the interaction between result_of and SFINAE.
template <typename F, typename Arg>
typename boost::result_of<F(Arg const&)>::type
sfinae_test(F f, Arg const& arg)
{
    return f(arg);
}

template <typename F, typename Arg>
typename boost::result_of<F(Arg&)>::type
sfinae_test(F f, Arg& arg)
{
    return f(arg);
}

int sfinae_test_f(int& i)
{
    return i;
}

struct X {};

int main()
{
  using namespace boost;

  typedef int (*func_ptr)(float, double);
  typedef int (&func_ref)(float, double);
  typedef int (*func_ptr_0)();
  typedef int (&func_ref_0)();
  typedef void (*func_ptr_void)(float, double);
  typedef void (&func_ref_void)(float, double);
  typedef void (*func_ptr_void_0)();
  typedef void (&func_ref_void_0)();
  typedef int (X::*mem_func_ptr)(float);
  typedef int (X::*mem_func_ptr_c)(float) const;
  typedef int (X::*mem_func_ptr_v)(float) volatile;
  typedef int (X::*mem_func_ptr_cv)(float) const volatile;
  typedef int (X::*mem_func_ptr_0)();

  BOOST_STATIC_ASSERT((is_same<result_of<int_result_type(float)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<int_result_of(double)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<const int_result_of(double)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<int_result_type_template<void>(float)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<int_result_of_template<void>(double)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<const int_result_of_template<void>(double)>::type, int>::value));

  BOOST_STATIC_ASSERT((is_same<tr1_result_of<int_result_type(float)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<int_result_of(double)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<const int_result_of(double)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<int_result_type_template<void>(float)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<int_result_of_template<void>(double)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<const int_result_of_template<void>(double)>::type, int>::value));

  BOOST_STATIC_ASSERT((is_same<tr1_result_of<int_result_of(void)>::type, void>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<volatile int_result_of(void)>::type, void>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<int_result_of_template<void>(void)>::type, void>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<volatile int_result_of_template<void>(void)>::type, void>::value));

  // Prior to decltype, result_of could not deduce the return type
  // nullary function objects unless they exposed a result_type.
#if defined(BOOST_RESULT_OF_USE_DECLTYPE)
  BOOST_STATIC_ASSERT((is_same<result_of<int_result_of(void)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<volatile int_result_of(void)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<int_result_of_template<void>(void)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<volatile int_result_of_template<void>(void)>::type, int>::value));
#else
  BOOST_STATIC_ASSERT((is_same<result_of<int_result_of(void)>::type, void>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<volatile int_result_of(void)>::type, void>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<int_result_of_template<void>(void)>::type, void>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<volatile int_result_of_template<void>(void)>::type, void>::value));
#endif

  // Prior to decltype, result_of ignored a nested result<> if
  // result_type was defined. After decltype, result_of deduces the
  // actual return type of the function object, ignoring both
  // result<> and result_type.
#if defined(BOOST_RESULT_OF_USE_DECLTYPE)
  BOOST_STATIC_ASSERT((is_same<result_of<int_result_type_and_float_result_of_and_char_return(char)>::type, char>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<int_result_type_and_float_result_of_and_char_return_template<void>(char)>::type, char>::value));
#else
  BOOST_STATIC_ASSERT((is_same<result_of<int_result_type_and_float_result_of_and_char_return(char)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<int_result_type_and_float_result_of_and_char_return_template<void>(char)>::type, int>::value));
#endif

  BOOST_STATIC_ASSERT((is_same<tr1_result_of<int_result_type_and_float_result_of_and_char_return(char)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<int_result_type_and_float_result_of_and_char_return_template<void>(char)>::type, int>::value));

  BOOST_STATIC_ASSERT((is_same<result_of<func_ptr(char, float)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<func_ref(char, float)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<func_ptr_0()>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<func_ref_0()>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<func_ptr_void(char, float)>::type, void>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<func_ref_void(char, float)>::type, void>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<func_ptr_void_0()>::type, void>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<func_ref_void_0()>::type, void>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<mem_func_ptr(X,char)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<mem_func_ptr_c(X,char)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<mem_func_ptr_v(X,char)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<mem_func_ptr_cv(X,char)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<mem_func_ptr_0(X)>::type, int>::value));

  BOOST_STATIC_ASSERT((is_same<tr1_result_of<func_ptr(char, float)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<func_ref(char, float)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<func_ptr_0()>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<func_ref_0()>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<func_ptr_void(char, float)>::type, void>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<func_ref_void(char, float)>::type, void>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<func_ptr_void_0()>::type, void>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<func_ref_void_0()>::type, void>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<mem_func_ptr(X,char)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<mem_func_ptr_c(X,char)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<mem_func_ptr_v(X,char)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<mem_func_ptr_cv(X,char)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<mem_func_ptr_0(X)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<func_ptr(void)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<func_ref(void)>::type, int>::value));

  BOOST_STATIC_ASSERT((is_same<result_of<result_of_member_function_template(double)>::type, double>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<const result_of_member_function_template(double)>::type, cv_overload_check<const double> >::value));
  BOOST_STATIC_ASSERT((is_same<result_of<volatile result_of_member_function_template(double)>::type, cv_overload_check<volatile double> >::value));
  BOOST_STATIC_ASSERT((is_same<result_of<const volatile result_of_member_function_template(double)>::type, cv_overload_check<const volatile double> >::value));
  BOOST_STATIC_ASSERT((is_same<result_of<result_of_member_function_template(int &, int)>::type, int &>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<result_of_member_function_template(int const &, int)>::type, int const &>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<result_of_member_function_template(int volatile &, int)>::type, int volatile &>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<result_of_member_function_template(int const volatile &, int)>::type, int const volatile &>::value));

  BOOST_STATIC_ASSERT((is_same<tr1_result_of<result_of_member_function_template(double)>::type, double>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<const result_of_member_function_template(double)>::type, cv_overload_check<const double> >::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<volatile result_of_member_function_template(double)>::type, cv_overload_check<volatile double> >::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<const volatile result_of_member_function_template(double)>::type, cv_overload_check<const volatile double> >::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<result_of_member_function_template(int &, int)>::type, int &>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<result_of_member_function_template(int const &, int)>::type, int const &>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<result_of_member_function_template(int volatile &, int)>::type, int volatile &>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<result_of_member_function_template(int const volatile &, int)>::type, int const volatile &>::value));

  typedef int (*pf_t)(int);
  BOOST_STATIC_ASSERT((is_same<result_of<pf_t(int)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<pf_t const(int)>::type,int>::value));

  BOOST_STATIC_ASSERT((is_same<tr1_result_of<pf_t(int)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<tr1_result_of<pf_t const(int)>::type,int>::value));

#if defined(BOOST_RESULT_OF_USE_DECLTYPE)
  BOOST_STATIC_ASSERT((is_same<result_of<no_result_type_or_result(double)>::type, short>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<const no_result_type_or_result(double)>::type, cv_overload_check<const short> >::value));
  BOOST_STATIC_ASSERT((is_same<result_of<volatile no_result_type_or_result(double)>::type, cv_overload_check<volatile short> >::value));
  BOOST_STATIC_ASSERT((is_same<result_of<const volatile no_result_type_or_result(double)>::type, cv_overload_check<const volatile short> >::value));
  BOOST_STATIC_ASSERT((is_same<result_of<no_result_type_or_result(void)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<const no_result_type_or_result(void)>::type, cv_overload_check<const int> >::value));
  BOOST_STATIC_ASSERT((is_same<result_of<volatile no_result_type_or_result(void)>::type, cv_overload_check<volatile int> >::value));
  BOOST_STATIC_ASSERT((is_same<result_of<const volatile no_result_type_or_result(void)>::type, cv_overload_check<const volatile int> >::value));

  BOOST_STATIC_ASSERT((is_same<result_of<no_result_type_or_result_template<void>(double)>::type, short>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<const no_result_type_or_result_template<void>(double)>::type, cv_overload_check<const short> >::value));
  BOOST_STATIC_ASSERT((is_same<result_of<volatile no_result_type_or_result_template<void>(double)>::type, cv_overload_check<volatile short> >::value));
  BOOST_STATIC_ASSERT((is_same<result_of<const volatile no_result_type_or_result_template<void>(double)>::type, cv_overload_check<const volatile short> >::value));
  BOOST_STATIC_ASSERT((is_same<result_of<no_result_type_or_result_template<void>(void)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<const no_result_type_or_result_template<void>(void)>::type, cv_overload_check<const int> >::value));
  BOOST_STATIC_ASSERT((is_same<result_of<volatile no_result_type_or_result_template<void>(void)>::type, cv_overload_check<volatile int> >::value));
  BOOST_STATIC_ASSERT((is_same<result_of<const volatile no_result_type_or_result_template<void>(void)>::type, cv_overload_check<const volatile int> >::value));
#if !defined(BOOST_NO_RVALUE_REFERENCES)
  BOOST_STATIC_ASSERT((is_same<result_of<no_result_type_or_result(int&&)>::type, short>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<no_result_type_or_result(int&)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<no_result_type_or_result(int const&)>::type, long>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<no_result_type_or_result_template<void>(int&&)>::type, short>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<no_result_type_or_result_template<void>(int&)>::type, int>::value));
  BOOST_STATIC_ASSERT((is_same<result_of<no_result_type_or_result_template<void>(int const&)>::type, long>::value));
#endif
#endif

#if defined(BOOST_RESULT_OF_USE_DECLTYPE)
  int i = 123;
  sfinae_test(sfinae_test_f, i);
#endif // defined(BOOST_RESULT_OF_USE_DECLTYPE)

  return 0;
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


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

#include "../../src/shared/state/Skill.h"

#include "../../src/shared/state/SkillFactory.h"

using namespace ::state;

BOOST_AUTO_TEST_CASE(TestSkill)
{

	Skill s {};
	BOOST_CHECK_EQUAL(s.getDamage(), 0);
	s.setDamage(99);
	BOOST_CHECK_EQUAL(s.getDamage(), 99);

	std::pair<int,int> testRange = {1,9};
	s.setRange(testRange);
	BOOST_CHECK_EQUAL(s.getRange().first, testRange.first );
	BOOST_CHECK_EQUAL(s.getRange().second, testRange.second );

	std::vector<std::pair<int,int>> testArea = {{0,1},{0,2},{2,3}};
	s.setArea(testArea);
	for(size_t i=0; i<testArea.size(); i++){
		BOOST_CHECK_EQUAL(s.getArea()[i].second, testArea[i].second );
		BOOST_CHECK_EQUAL(s.getArea()[i].first, testArea[i].first );
	}

	/*std::vector<std::tuple<EffectId,int,int>> testEffect = {{BURN_CHAR,1,90},{HEAL_LOW,2,100},{MOVE_FOE,-1,20}};
	s.setEffect(testEffect);
	for(size_t i=0; i<testArea.size(); i++){
		BOOST_CHECK_EQUAL(std::get<0>(s.getEffect()[i]), std::get<0>(testEffect[i]));
		BOOST_CHECK_EQUAL(std::get<1>(s.getEffect()[i]), std::get<1>(testEffect[i]));
		BOOST_CHECK_EQUAL(std::get<2>(s.getEffect()[i]), std::get<2>(testEffect[i]));
	}*/

	BOOST_CHECK_EQUAL(s.getPrecision(), 0);
	s.setPrecision(99);
	BOOST_CHECK_EQUAL(s.getPrecision(), 99);

	BOOST_CHECK_EQUAL(s.getCooldown(), 0);
	s.setCooldown(99);
	BOOST_CHECK_EQUAL(s.getCooldown(), 99);

	BOOST_CHECK_EQUAL(s.getSpecial(), 0);
	s.setSpecial(1);
	BOOST_CHECK_EQUAL(s.getSpecial(), 1);

	SkillFactory skfa;
	Skill* skill;
	skill = skfa.createSkill(FRAPPE);
	skill = skfa.createSkill(ARC);
	skill = skfa.createSkill(BOULE_DE_FEU);
	skill = skfa.createSkill(SAUT_PIQUE);
	skill = skfa.createSkill(ARC_EN_CIEL);
	skill = skfa.createSkill(SOIN);
	skill = skfa.createSkill(SOIN_LEGER);
	skill = skfa.createSkill(ENTAILLE);
	skill = skfa.createSkill(TRANCHARGE);
	skill = skfa.createSkill(PIETINEMENT);
	skill = skfa.createSkill(FEU_D_ENFER);
	skill = skfa.createSkill(DOUBLE_LAME);
	skill = skfa.createSkill(FOUDRE);
	skill = skfa.createSkill(LANCER_DE_HACHE);
	skill = skfa.createSkill(COUP_DE_BOULE);
	/*
	std::tuple<EffectId,int,int> CDBeffect = {FEAR_CHAR, 1, 90};
	std::vector<std::tuple<EffectId,int,int>> effect = skill->getEffect();
	BOOST_CHECK_EQUAL(std::get<0>(effect[0]), std::get<0>(CDBeffect));
	BOOST_CHECK_EQUAL(std::get<1>(effect[0]), std::get<1>(CDBeffect));
	BOOST_CHECK_EQUAL(std::get<2>(effect[0]), std::get<2>(CDBeffect));
	*/
	BOOST_CHECK_EQUAL(skill->getSkillId(), COUP_DE_BOULE);

	skill->setCooldownBase(8);
	BOOST_CHECK_EQUAL(skill->getCooldownBase(), 8);

}

max_stars_repo_name: StevenEnsea/plt

max_issues_repo_name: StevenEnsea/plt

max_forks_repo_name: StevenEnsea/plt


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

// Copyright 2017 Xilinx, Inc. All rights reserved.

#include <CL/opencl.h>

#include "xocl/config.h"
#include "xocl/core/platform.h"
#include "xocl/core/kernel.h"
#include "xocl/core/program.h"
#include "xocl/core/device.h"
#include "xocl/core/error.h"

#include "detail/program.h"
#include "api.h"
#include "xrt/util/memory.h"

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>

#include <fstream>
#include "plugin/xdp/profile.h"

namespace bfs = boost::filesystem;

namespace {

XRT_UNUSED static size_t
getDeviceMaxWorkGroupSize(cl_device_id device)
{
  static size_t size = 0;
  if (size)
    return size;
  xocl::api::clGetDeviceInfo(device,CL_DEVICE_MAX_WORK_GROUP_SIZE,sizeof(size_t),&size,nullptr);
  return size;
}

}

namespace xocl {

static void
validOrError(cl_program      program,
             const char *    kernel_name,
             cl_int *        errcode_ret)
{
  if( !xocl::config::api_checks())
    return;

  // CL_INVALID_PROGRAM if program is not a valid program object.
  detail::program::validOrError(program);

  // CL_INVALID_VALUE if kernel_name is NULL.
  if (!kernel_name)
    throw xocl::error(CL_INVALID_VALUE,"kernel_name == nullptr");

  // CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built
  // executable for program.
  detail::program::validExecutableOrError(program);

  // CL_INVALID_KERNEL_NAME if kernel_name is not found in program.
  if (!xocl(program)->has_kernel(kernel_name))
    throw xocl::error(CL_INVALID_KERNEL_NAME,"kernel '" + std::string(kernel_name) + "' not found");

  // CL_INVALID_KERNEL_DEFINITION if the function definition for
  // __kernel function given by kernel_name such as the number of
  // arguments, the argument types are not the same for all devices
  // for which the program executable has been built.

}

static cl_kernel
clCreateKernel(cl_program      program,
               const char *    kernel_name,
               cl_int *        errcode_ret)
{
  validOrError(program,kernel_name,errcode_ret);

  // XCL_CONFORMANCECOLLECT mode
  // write out the kernel sources in clCreateKernel and fail quickly in clEnqueueNDRange
  // skip build in clBuildProgram
  bool xcl_conformancecollectmode=(std::getenv("XCL_CONFORMANCECOLLECT"));
  bool xcl_conformancemode=(std::getenv("XCL_CONFORMANCE"));
  if (xcl_conformancecollectmode) {
    // Generate mykernel_0/_1/_2.cl source file name
    // Find first index not already used by a file
    std::string fnm;
    for (unsigned int idx=0; ; ++idx) {
      char ext[4];
      sprintf(ext,"%03u",idx);
      auto path = bfs::path(kernel_name);
      // path.append("_").append(ext).append(".cl");
      // Changed to use /= since boost 1.53.0 path::append() which
      // comes packaged with CentOS/RHEL 7.X requires two arguments
      path /= "_";
      path /= ext;
      path /= "cl";
      if (!bfs::exists(path)) {
        fnm = path.string();
        break;
      }
    }

    // Replace original kernel name with new kernel name in program source
    std::string newsrc = xocl(program)->get_source();
    auto newknm = fnm.substr(0,fnm.length()-3); // strip ".cl"
    auto pos = newsrc.find(kernel_name);
    if (pos!=std::string::npos)
      newsrc.replace(pos,strlen(kernel_name),newknm);
    else
      XOCL_DEBUG(std::cout,"clCreateKernel : string replace failed\n");
    std::ofstream ostr(fnm);
    ostr << newsrc;

    //fake kernel
    XRT_UNUSED auto platform = xocl::get_global_platform();
    auto kernel = xocl::xocl(program)->create_kernel("");
    assert(kernel->get_wg_size()==getDeviceMaxWorkGroupSize(platform->get_device_range()[0].get()));
    return kernel.release();
  }

  if (xcl_conformancemode) {
    // find program with matching hash containing kernel it may be not
    // be the program passed to this API
    for (auto gprogram : xocl::get_global_programs()) {
      auto xprogram = xocl::xocl(gprogram);
      if(xprogram->conformance_binaryhash==xocl::xocl(program)->conformance_binaryhash)
        if (xprogram->has_kernel(kernel_name))
          program=xprogram;
    }
  }

  auto pkernel = xocl::xocl(program)->create_kernel(kernel_name);
  xocl::assign(errcode_ret,CL_SUCCESS);
  return pkernel.release();
}

namespace api {

cl_kernel
clCreateKernel(cl_program      program,
               const char *    kernel_name,
               cl_int *        errcode_ret)
{
  return ::xocl::clCreateKernel(program,kernel_name,errcode_ret);
}

} // api

} // xocl

cl_kernel
clCreateKernel(cl_program      program,
               const char *    kernel_name,
               cl_int *        errcode_ret)
{
  try {
    PROFILE_LOG_FUNCTION_CALL;
    return xocl::clCreateKernel(program,kernel_name,errcode_ret);
  }
  catch (const xocl::error& ex) {
    xocl::send_exception_message(ex.what());
    xocl::assign(errcode_ret,ex.get_code());
  }
  catch (const std::exception& ex) {
    xocl::send_exception_message(ex.what());
    xocl::assign(errcode_ret,CL_OUT_OF_HOST_MEMORY);
  }
  return nullptr;
}


text:
#include "bal_problem_stereo.h"

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include <Eigen/Core>
#include <ceres/rotation.h>
//#include <glog/logging.h>

namespace optim {

namespace {
typedef Eigen::Map<Eigen::VectorXd> VectorRef;
typedef Eigen::Map<const Eigen::VectorXd> ConstVectorRef;

inline double RandDouble() {
  double r = static_cast<double>(rand());
  return r / RAND_MAX;
}

// Box-Muller algorithm for normal random number generation.
// http://en.wikipedia.org/wiki/Box-Muller_transform
inline double RandNormal() {
  double x1, x2, w;
  do {
    x1 = 2.0 * RandDouble() - 1.0;
    x2 = 2.0 * RandDouble() - 1.0;
    w = x1 * x1 + x2 * x2;
  } while ( w >= 1.0 || w == 0.0 );

  w = sqrt((-2.0 * log(w)) / w);
  return x1 * w;
}

template<typename T>
void FscanfOrDie(FILE* fptr, const char* format, T* value) {
  int num_scanned = fscanf(fptr, format, value);
  if (num_scanned != 1) {
    //LOG(FATAL) << "Invalid UW data file.";
    throw "Invalid UW data file.";
  }
}

void PerturbPoint3(const double sigma, double* point) {
  for (int i = 0; i < 3; ++i) {
    point[i] += RandNormal() * sigma;
  }
}

double Median(std::vector<double>* data) {
  int n = data->size();
  std::vector<double>::iterator mid_point = data->begin() + n / 2;
  std::nth_element(data->begin(), mid_point, data->end());
  return *mid_point;
}

}  // namespace

BALProblemStereo::BALProblemStereo(bool use_quaternions) : use_quaternions_(use_quaternions)
{}

BALProblemStereo::BALProblemStereo(const std::string& filename, bool use_quaternions)
                                  : use_quaternions_(use_quaternions)
{
  FILE* fptr = fopen(filename.c_str(), "r");

  if (fptr == NULL) {
    //LOG(FATAL) << "Error: unable to open file " << filename;
    std::cout << "Error: unable to open file " << filename;
    return;
  };

  num_intr_ = 5;
  cam_intrinsics_ = new double[num_intr_];
  for(int i = 0; i < num_intr_; i++) {
    FscanfOrDie(fptr, "%lf", &cam_intrinsics_[i]);
    std::cout << cam_intrinsics_[i] << " - cam_intrinsics_\n";
  }

  // This wil die horribly on invalid files. Them's the breaks.
  FscanfOrDie(fptr, "%d", &num_cameras_);
  FscanfOrDie(fptr, "%d", &num_points_);
  FscanfOrDie(fptr, "%d", &num_observations_);

  std::cout << "Header: " << num_cameras_
          << " " << num_points_
          << " " << num_observations_;

  point_index_ = new int[num_observations_];
  camera_index_ = new int[num_observations_];
  observations_ = new double[4 * num_observations_];

  num_parameters_ = camera_block_size() * num_cameras_ + point_block_size() * num_points_;
  parameters_ = new double[num_parameters_];

  for (int i = 0; i < num_observations_; ++i) {
    FscanfOrDie(fptr, "%d", camera_index_ + i);
    FscanfOrDie(fptr, "%d", point_index_ + i);
    for (int j = 0; j < 4; ++j) {
      FscanfOrDie(fptr, "%lf", observations_ + 4*i + j);
    }
  }

  for (int i = 0; i < num_parameters_; ++i) {
    FscanfOrDie(fptr, "%lf", parameters_ + i);
  }

  fclose(fptr);

  if (use_quaternions) {
    // Switch the angle-axis rotations to quaternions.
    num_parameters_ = camera_block_size() * num_cameras_ + point_block_size() * num_points_;
    double* quaternion_parameters = new double[num_parameters_];
    double* original_cursor = parameters_;
    double* quaternion_cursor = quaternion_parameters;
    for (int i = 0; i < num_cameras_; ++i) {
      ceres::AngleAxisToQuaternion(original_cursor, quaternion_cursor);
      quaternion_cursor += 4;
      original_cursor += 3;
      for (int j = 4; j < camera_block_size(); ++j) {
       *quaternion_cursor++ = *original_cursor++;
      }
    }
    // Copy the rest of the points.
    for (int i = 0; i < point_block_size() * num_points_; ++i) {
      *quaternion_cursor++ = *original_cursor++;
    }
    // Swap in the quaternion parameters.
    delete[] parameters_;
    parameters_ = quaternion_parameters;
  }
}

// This function writes the problem to a file in the same format that
// is read by the constructor.
void BALProblemStereo::WriteToFile(const std::string& filename) const {
  FILE* fptr = fopen(filename.c_str(), "w");

  if (fptr == NULL) {
    std::cout << "Error: unable to open file " << filename;
    return;
  };

  for(int i = 0; i < num_intr_; i++)
    fprintf(fptr, "%g ", cam_intrinsics_[i]);
  fprintf(fptr, "\n");

  fprintf(fptr, "%d %d %d\n", num_cameras_, num_points_, num_observations_);

  for (int i = 0; i < num_observations_; ++i) {
    fprintf(fptr, "%d %d", camera_index_[i], point_index_[i]);
    for (int j = 0; j < 4; ++j) {
      fprintf(fptr, " %g", observations_[4 * i + j]);
    }
    fprintf(fptr, "\n");
  }

  for (int i = 0; i < num_cameras(); ++i) {
    double angleaxis[6];
    if (use_quaternions_) {
      // Output in angle-axis format.
      ceres::QuaternionToAngleAxis(parameters_ + camera_block_size() * i, angleaxis);
      memcpy(angleaxis + 3, parameters_ + camera_block_size() * i + 4, (camera_block_size()-4) * sizeof(double));
    } else {
      memcpy(angleaxis, parameters_ + camera_block_size() * i, camera_block_size() * sizeof(double));
    }
    for (int j = 0; j < camera_block_size(); ++j) {
      fprintf(fptr, "%.16g\n", angleaxis[j]);
    }
  }

  const double* points = parameters_ + camera_block_size() * num_cameras_;
  for (int i = 0; i < num_points(); ++i) {
    const double* point = points + i * point_block_size();
    for (int j = 0; j < point_block_size(); ++j) {
      fprintf(fptr, "%.16g\n", point[j]);
    }
  }

  fclose(fptr);
}

void BALProblemStereo::CameraToAngleAxisAndCenter(const double* camera,
                                            double* angle_axis,
                                            double* center) {
  VectorRef angle_axis_ref(angle_axis, 3);
  if (use_quaternions_) {
    ceres::QuaternionToAngleAxis(camera, angle_axis);
  } else {
    angle_axis_ref = ConstVectorRef(camera, 3);
  }

  int point_pos = (use_quaternions_ ? 4 : 3);
  // c = -R't
  Eigen::VectorXd inverse_rotation = -angle_axis_ref;
  ceres::AngleAxisRotatePoint(inverse_rotation.data(), camera + point_pos, center);
  VectorRef(center, 3) *= -1.0;
}

void BALProblemStereo::AngleAxisAndCenterToCamera(const double* angle_axis,
                                            const double* center,
                                            double* camera) {
  ConstVectorRef angle_axis_ref(angle_axis, 3);
  if (use_quaternions_) {
    ceres::AngleAxisToQuaternion(angle_axis, camera);
  } else {
    VectorRef(camera, 3) = angle_axis_ref;
  }

  int point_pos = (use_quaternions_ ? 4 : 3);
  // t = -R * c
  ceres::AngleAxisRotatePoint(angle_axis,
                       center,
                       camera + point_pos);
  VectorRef(camera + point_pos, 3) *= -1.0;
}

void BALProblemStereo::Normalize() {
  // Compute the marginal median of the geometry.
  std::vector<double> tmp(num_points_);
  Eigen::Vector3d median;
  double* points = mutable_points();
  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < num_points_; ++j) {
      tmp[j] = points[3 * j + i];
    }
    median(i) = Median(&tmp);
  }

  for (int i = 0; i < num_points_; ++i) {
    VectorRef point(points + 3 * i, 3);
    tmp[i] = (point - median).lpNorm<1>();
  }

  const double median_absolute_deviation = Median(&tmp);

  // Scale so that the median absolute deviation of the resulting
  // reconstruction is 100.
  const double scale = 100.0 / median_absolute_deviation;

  std::cout << "median: " << median.transpose();
  std::cout << "median absolute deviation: " << median_absolute_deviation;
  std::cout  << "scale: " << scale;

  // X = scale * (X - median)
  for (int i = 0; i < num_points_; ++i) {
    VectorRef point(points + 3 * i, 3);
    point = scale * (point - median);
  }

  double* cameras = mutable_cameras();
  double angle_axis[3];
  double center[3];
  for (int i = 0; i < num_cameras_; ++i) {
    double* camera = cameras + camera_block_size() * i;
    CameraToAngleAxisAndCenter(camera, angle_axis, center);
    // center = scale * (center - median)
    VectorRef(center, 3) = scale * (VectorRef(center, 3) - median);
    AngleAxisAndCenterToCamera(angle_axis, center, camera);
  }
}

void BALProblemStereo::Perturb(const double rotation_sigma,
                               const double translation_sigma,
                               const double point_sigma)
{
  CHECK_GE(point_sigma, 0.0);
  CHECK_GE(rotation_sigma, 0.0);
  CHECK_GE(translation_sigma, 0.0);

  double* points = mutable_points();
  if (point_sigma > 0) {
    for (int i = 0; i < num_points_; ++i) {
      PerturbPoint3(point_sigma, points + 3 * i);
    }
  }

  for (int i = 0; i < num_cameras_; ++i) {
    double* camera = mutable_cameras() + camera_block_size() * i;

    double angle_axis[3];
    double center[3];
    // Perturb in the rotation of the camera in the angle-axis
    // representation.
    CameraToAngleAxisAndCenter(camera, angle_axis, center);
    if (rotation_sigma > 0.0) {
      PerturbPoint3(rotation_sigma, angle_axis);
    }
    AngleAxisAndCenterToCamera(angle_axis, center, camera);

    int point_pos = (use_quaternions_ ? 4 : 3);
    if (translation_sigma > 0.0) {
      PerturbPoint3(translation_sigma, camera + point_pos);
    }
  }
}

BALProblemStereo::~BALProblemStereo() {
  delete[] point_index_;
  delete[] camera_index_;
  delete[] observations_;
  delete[] parameters_;
  delete[] cam_intrinsics_;
}

}  // namespace optim

ext: cc


text:
//----------------------------------------------------------------------------
//Yume Engine
//Copyright (C) 2015  arkenthera
//This program is free software; you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation; either version 2 of the License, or
//(at your option) any later version.
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//You should have received a copy of the GNU General Public License along
//with this program; if not, write to the Free Software Foundation, Inc.,
//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.*/
//----------------------------------------------------------------------------
//
// File : <Filename>
// Date : <Date>
// Comments :
//
//----------------------------------------------------------------------------
#include "YumeHeaders.h"
#include "YumeGLShader.h"

#include "Renderer/YumeRHI.h"
#include "YumeGLRenderer.h"
#include "YumeGLShaderVariation.h"

#include "Core/YumeDefaults.h"

#include "Core/YumeIO.h"
#include "Engine/YumeEngine.h"

#include <boost/algorithm/string.hpp>

namespace YumeEngine
{
	void CommentOutFunction(YumeString& code,const YumeString& signature)
	{
		unsigned startPos = code.find(signature);
		unsigned braceLevel = 0;
		if(startPos == std::string::npos)
			return;

		code.Insert(startPos,"/*");

		for(unsigned i = startPos + 2 + signature.length(); i < code.length(); ++i)
		{
			if(code[i] == '{')
				++braceLevel;
			else if(code[i] == '}')
			{
				--braceLevel;
				if(braceLevel == 0)
				{
					code.Insert(i + 1,"*/");
					return;
				}
			}
		}
	}
	YumeGLShader::YumeGLShader()
	{
	}

	YumeGLShader::~YumeGLShader()
	{
	}

	bool YumeGLShader::BeginLoad(YumeFile& source)
	{
		YumeRHI* graphics_ = gYume->pRHI;

		if(!graphics_)
			return false;

		timeStamp_ = 0;
		YumeString shaderCode;
		if(!ProcessSource(shaderCode,source))
			return false;

		vsSourceCode_ = shaderCode;
		psSourceCode_ = shaderCode;
		CommentOutFunction(vsSourceCode_,"void PS(");
		CommentOutFunction(psSourceCode_,"void VS(");

		vsSourceCode_.Replace("void VS(","void main(");
		psSourceCode_.Replace("void PS(","void main(");

		RefreshMemoryUse();
		return true;
	}

	bool YumeGLShader::EndLoad()
	{
		for(YumeMap<YumeHash,SharedPtr<YumeGLShaderVariation> >::iterator i = vsVariations_.begin(); i != vsVariations_.end(); ++i)
			i->second->Release();
		for(YumeMap<YumeHash,SharedPtr<YumeGLShaderVariation> >::iterator i = psVariations_.begin(); i != psVariations_.end(); ++i)
			i->second->Release();

		return true;
	}

	YumeShaderVariation* YumeGLShader::GetVariation(ShaderType type,const YumeString& defines)
	{
		return GetVariation(type,defines.c_str());
	}

	YumeShaderVariation* YumeGLShader::GetVariation(ShaderType type,const char* defines)
	{
		YumeHash definesHash = (defines);
		typedef YumeMap<YumeHash,SharedPtr<YumeGLShaderVariation> > ShaderMap;
		ShaderMap::type& variations = (type == VS ? vsVariations_ : psVariations_);

		ShaderMap::iterator i = variations.find(definesHash);

		if(i == variations.end())
		{
			// If shader not found, normalize the defines (to prevent duplicates) and check again. In that case make an alias
			// so that further queries are faster
			YumeString normalizedDefines = NormalizeDefines(defines);
			YumeHash normalizedHash = (normalizedDefines);

			i = variations.find(normalizedHash);
			if(i != variations.end())
				variations.insert(MakePair(definesHash,i->second));
			else
			{
				YumeGLShaderVariation* shr_ = YumeAPINew YumeGLShaderVariation(this,type);
				i = variations.insert(MakePair(normalizedHash,SharedPtr<YumeGLShaderVariation>(shr_)));
				if(definesHash != normalizedHash)
					variations.insert(MakePair(definesHash,i->second));

				i->second->SetName(GetFileName(GetName()));
				i->second->SetDefines(normalizedDefines);
				++numVariations_;
				RefreshMemoryUse();

				return (i->second).Get();
			}
		}
		return i->second.Get();
	}

	void YumeGLShader::RefreshMemoryUse()
	{
		SetMemoryUsage(
			(unsigned)(sizeof(YumeGLShader) + vsSourceCode_.length() + psSourceCode_.length() + numVariations_ * sizeof(YumeGLShaderVariation)));
	}
}

max_stars_repo_name: rodrigobmg/YumeEngine

max_issues_repo_name: rodrigobmg/YumeEngine

max_forks_repo_name: rodrigobmg/YumeEngine


text:
/*

Copyright (c) 2005-2020, University of Oxford.
All rights reserved.

University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.

This file is part of Chaste.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 * Neither the name of the University of Oxford nor the names of its
   contributors may be used to endorse or promote products derived from this
   software without specific prior written permission.

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

*/

#ifndef _ABSTRACTLINEARELLIPTICPDE_HPP_
#define _ABSTRACTLINEARELLIPTICPDE_HPP_

#include "ChasteSerialization.hpp"
#include <boost/serialization/base_object.hpp>

#include "AbstractLinearPde.hpp"
#include "UblasCustomFunctions.hpp"
#include "ChastePoint.hpp"
#include "Node.hpp"
#include "Element.hpp"
#include <petscvec.h>

/**
 * AbstractLinearEllipticPde class.
 *
 * A general PDE of the form:
 * 0 =   Grad.(DiffusionTerm(x)*Grad(u))
 *     + ComputeConstantInUSourceTerm(x)
 *     + ComputeLinearInUCoeffInSourceTerm(x, u)
 *
 * Parabolic PDEs are be derived from this (AbstractLinearParabolicPde)
 */
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM>
class AbstractLinearEllipticPde : public AbstractLinearPde<ELEMENT_DIM, SPACE_DIM>
{
private:

    /** Needed for serialization. */
    friend class boost::serialization::access;
    /**
     * Serialize the PDE object.
     *
     * @param archive the archive
     * @param version the current version of this class
     */
    template<class Archive>
    void serialize(Archive & archive, const unsigned int version)
    {
        archive & boost::serialization::base_object<AbstractLinearPde<ELEMENT_DIM, SPACE_DIM> >(*this);
    }

public:

    /**
     * Constructor.
     */
    AbstractLinearEllipticPde()
        : AbstractLinearPde<ELEMENT_DIM, SPACE_DIM>()
    {}

    /**
     * Destructor.
     */
    virtual ~AbstractLinearEllipticPde()
    {}

    /**
     * @return computed constant in u part of the source term, i.e g(x) in
     * Div(D Grad u)  +  f(x)u + g(x) = 0, at a given point.
     *
     * @param rX The point in space
     * @param pElement The element
     */
    virtual double ComputeConstantInUSourceTerm(const ChastePoint<SPACE_DIM>& rX,
                                                Element<ELEMENT_DIM,SPACE_DIM>* pElement)=0;

    /**
     * @return computed coefficient of u in the linear part of the source term, i.e f(x) in
     * Div(D Grad u)  +  f(x)u + g(x) = 0, at a given point in space.
     *
     * @param rX The point in space
     * @param pElement
     */
    virtual double ComputeLinearInUCoeffInSourceTerm(const ChastePoint<SPACE_DIM>& rX,
                                                     Element<ELEMENT_DIM,SPACE_DIM>* pElement)=0;

    /**
     * @return computed diffusion term at a given point. The diffusion tensor should be symmetric and positive definite
     *
     * @param rX The point in space at which the diffusion term is computed.
     * @return A matrix.
     */
    virtual c_matrix<double, SPACE_DIM, SPACE_DIM> ComputeDiffusionTerm(const ChastePoint<SPACE_DIM>& rX)=0;

    /**
     * @return computed constant in u part of the source term, i.e g(x) in
     * Div(D Grad u)  +  f(x)u + g(x) = 0, at a given node.
     *
     * @param rNode the node
     */
    virtual double ComputeConstantInUSourceTermAtNode(const Node<SPACE_DIM>& rNode);

    /**
     * @return computed coefficient of u in the linear part of the source term, i.e f(x) in
     * Div(D Grad u)  +  f(x)u + g(x) = 0, at a given node.
     *
     * @param rNode the node
     */
    virtual double ComputeLinearInUCoeffInSourceTermAtNode(const Node<SPACE_DIM>& rNode);
};

template <unsigned ELEMENT_DIM, unsigned SPACE_DIM>
double AbstractLinearEllipticPde<ELEMENT_DIM, SPACE_DIM>::ComputeConstantInUSourceTermAtNode(const Node<SPACE_DIM>& rNode)
{
    return ComputeConstantInUSourceTerm(rNode.GetPoint(), nullptr);
}

template <unsigned ELEMENT_DIM, unsigned SPACE_DIM>
double AbstractLinearEllipticPde<ELEMENT_DIM, SPACE_DIM>::ComputeLinearInUCoeffInSourceTermAtNode(const Node<SPACE_DIM>& rNode)
{
    return ComputeLinearInUCoeffInSourceTerm(rNode.GetPoint(), nullptr);
}

#endif //_ABSTRACTLINEARELLIPTICPDE_HPP_

ext: hpp

max_stars_repo_name: SoftMatterMechanics/ApicalStressFibers

max_issues_repo_name: SoftMatterMechanics/ApicalStressFibers

max_forks_repo_name: SoftMatterMechanics/ApicalStressFibers


text:
#include "snapconfig.hpp"

#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <memory>
#include <sstream>
#include <vector>

#include "snapdata/snapcsvbase.hpp"

#include "util/calcdltfile.hpp"
#include "util/errdef.h"
#include "util/recordstream.hpp"
#include "util/snapregex.hpp"

using namespace LINZ;
using namespace DelimitedTextFile;
using namespace SNAP;

/////////////////////////////////////////////////////////////////
// CsvValue

SnapCsvBase::CsvValue::~CsvValue()
{
}

void SnapCsvBase::CsvValue::setName(const std::string name)
{
    _name = name;
    if (_column != 0)
        _column->setName(name);
}

void SnapCsvBase::CsvValue::attach(CalcReader *reader)
{
    _column = reader ? &reader->addColumn(_name, _value) : 0;
}

/////////////////////////////////////////////////////////////////
// SnapCsvBase

SnapCsvBase::SnapCsvBase(const std::string &name, const OptionString &config) : _definitionLoaded(false),
                                                                                _name(name),
                                                                                _format(new CsvFormat()),
                                                                                _config(config),
                                                                                _checkColumnEnabled(false),
                                                                                _reader(0)
{
}

SnapCsvBase::~SnapCsvBase()
{
}

void SnapCsvBase::initiallizeLoadDefinition()
{
}

void SnapCsvBase::terminateLoadDefinition()
{
}

void SnapCsvBase::loadDefinition()
{
    if (!_definitionLoaded)
    {
        RecordStream rs(_name);
        try
        {
            _defstream = &rs;
            rs.setLeadingComment('!');
            initiallizeLoadDefinition();
            loadDefinition(rs);
            terminateLoadDefinition();
            _definitionLoaded = true;
            _definitionFilename = rs.filename();
        }
        catch (...)
        {
            _defstream = 0;
            throw;
        }
    }
}

void SnapCsvBase::loadDefinition(RecordStream &rs)
{
    while (rs.readRecord())
    {
        string command;
        rs.record() >> command;
        boost::to_lower(command);

        if (command == "format_name")
        {
            string name;
            std::getline(rs.record(), name);
            boost::trim(name);
            _name = name;
        }
        else if (command == "format")
        {
            string formatStr;
            std::getline(rs.record(), formatStr);
            loadFormatDefinition(formatStr);
        }
        else if (command == "columns")
        {
            loadColumnsDefinition(rs, _columns);
        }
        else if (command == "required_columns")
        {
            loadColumnsDefinition(rs, _requiredColumns);
            disableColumnCheck();
        }
        else if (command == "required_configuration")
        {
            std::string item;
            while (rs.record() >> item)
            {
                if (!_config.defines(item))
                {
                    definitionError(string("Require CSV configuration item ") + item);
                }
            }
        }
        else if (command == "skip_lines")
        {
            int nskip;
            if (rs.record() >> nskip)
            {
                setNSkipLines(nskip);
            }
        }
        else if (command == "lookup")
        {
            string lookupName;
            rs.record() >> lookupName;
            loadLookupDefinition(rs, lookupName);
        }
        else
        {
            continue;
        }
    }
    rs.restart();
    while (rs.readRecord())
    {
        string command;
        rs.record() >> command;
        boost::to_lower(command);

        if (command == "format_name" || command == "format" || command == "columns" || command == "required_columns" || command == "required_configuration" || command == "skip_lines")
        {
            continue;
        }
        else if (command == "lookup")
        {
            string lookupName;
            rs.record() >> lookupName;
            loadLookupDefinition(rs, lookupName, true);
        }
        else
        {
            loadDefinitionCommand(command, rs);
        }
    }
}

bool SnapCsvBase::load(const std::string &filename)
{
    IstreamRecordInput is(filename);
    return load(is);
}

void SnapCsvBase::attachReader(CalcReader *reader)
{
    _reader = reader;

    readerAttached();

    if (_reader)
        checkColumns();
}

bool SnapCsvBase::checkColumns()
{
    bool ok = true;
    if (!_reader)
        return ok;
    std::vector<std::string> *cols = _checkColumnEnabled ? &_usedColumns : &_requiredColumns;

    std::vector<std::string> checkedCols;
    for (auto col = cols->begin(); col < cols->end(); col++)
    {
        std::string ucol = *col;
        boost::to_upper(ucol);
        if (std::find(checkedCols.begin(), checkedCols.end(), ucol) != checkedCols.end())
        {
            continue;
        }
        if (!_reader->findColumn(*col))
        {
            _reader->runtimeError(std::string("Column ") + *col + " is not defined");
            ok = false;
        }
    }
    return ok;
}

void SnapCsvBase::normaliseColumnNames(CalcReader *reader)
{
    std::vector<std::string> columnNames;
    RGX::regex re("[^A-Za-z0-9]+");
    for (int i = 0; i < reader->columnCount(); i++)
    {
        std::string colName = reader->column(i).name();
        boost::trim(colName);
        columnNames.push_back(RGX::regex_replace(colName, re, string("_")));
    }
    reader->setColumnNames(columnNames);
}

bool SnapCsvBase::load(RecordInputBase &input)
{
    try
    {
        loadDefinition();
        CalcReader reader(input, *_format, _options);
        normaliseColumnNames(&reader);
        attachReader(&reader);

        if (!checkColumns())
        {
            attachReader(0);
            return false;
        }

        if (!_options.useHeader() && _columns.size() > 0)
        {
            reader.setColumnNames(_columns);
        }
        initiallizeLoadData();

        while (reader.readRecord())
        {
            loadRecord();
        }
        terminateLoadData();
        _loadedFilename = input.name();

        attachReader(0);
    }
    catch (RecordError &error)
    {
        attachReader(0);
        runtimeError(error.message());
        return false;
    }
    catch (...)
    {
        attachReader(0);
        throw;
    }
    return true;
}

void SnapCsvBase::initiallizeLoadData()
{
}

void SnapCsvBase::terminateLoadData()
{
}

void SnapCsvBase::definitionError(const std::string &message, RecordErrorType errortype)
{
    std::string filename = "";
    std::string fullmessage = message;
    int lineno = -1;
    if (_defstream)
    {
        filename = _defstream->filename();
        lineno = _defstream->lineNo();
        fullmessage += ": " + filename + ":" + std::to_string(lineno);
    }
    if (errortype == Warning)
    {
        // Unsatisfactory handling of warnings
        handle_error(INFO_ERROR, fullmessage.c_str(), NULL);
        return;
    }
    throw RecordError(errortype, fullmessage, filename, lineno);
}

void SnapCsvBase::runtimeError(const string &message)
{

    // May want to route this through data file handler to get line number etc
    if (_reader != 0)
    {
        _reader->runtimeError(message);
    }
    else
    {
        throw RecordError(message);
    }
}

void SnapCsvBase::loadValueDefinition(RecordStream &rs, CsvValue &value)
{
    string valuestr;
    std::getline(rs.record(), valuestr);
    loadValueDefinition(valuestr, value);
}

void SnapCsvBase::recordUsedColumn(const std::string &colname)
{
    _usedColumns.push_back(colname);
}

void SnapCsvBase::loadValueDefinition(const std::string &valuestr, CsvValue &value)
{
    ConcatValue *cvalue = &(value.cvalue());
    cvalue->clear();
    RGX::regex re(
        "\\s*(?:"
        "(default)|"                           // Start of default (1)
        "(\\-?\\d+\\.?\\d*)|"                  // A number (2)
        "\\\"((?:[^\\\"]|\\\"\\\")*)\\\"|"     // Literal string (3)
        "(?:\\$(\\w+))|"                       // Config item (4)
        "(?:\\@(\\w+)|([a-z_]\\w*))|"          // Column name (5,6)
        "([a-z_]\\w*)\\(\\s*"                  // Start of lookup (7)
        "(?:\\$(\\w+)|\\@(\\w+)|([a-z_]\\w*))" // Lookup config/column (8)(9)(10)
        "\\s*\\)|"                             // End of lookup
        "(\\S+)"                               // Other random string (11)
        ")(?:\\s|$)",                          // Terminating space or end
        RGX::regex_constants::icase);
    RGX::sregex_iterator imatch(valuestr.begin(), valuestr.end(), re);
    RGX::sregex_iterator end;
    for (; imatch != end; imatch++)
    {
        auto match = *imatch;
        // default ...
        if (match[1].length() > 0)
        {
            ConcatValue *owner = cvalue;
            cvalue = new ConcatValue();
            owner->setDefault(cvalue);
        }
        // Numeric value
        else if (match[2].length() > 0)
        {
            cvalue->add(StringValue(match[2].str()));
        }
        // Literal text
        else if (match[3].length() > 0)
        {
            string text = RGX::regex_replace(match[3].str(), RGX::regex("\\\"\\\""), string("\""));
            cvalue->add(text);
        }
        // Config item
        else if (match[4].length() > 0)
        {
            std::string value = _config.valueOf(match[4].str());
            cvalue->add(value);
        }

        // Column based value.
        else if (match[5].length() > 0 || match[6].length() > 0)
        {
            if (match[6].length() > 0)
            {
                definitionError(std::string("Column name ") + match[6].str() + " for " + value.name() + "should start with @", Warning);
            }
            std::string colname = match[5].str() + match[6].str();
            recordUsedColumn(colname);
            NamedValue col(colname, "");
            cvalue->add(col);
        }
        // Lookup value ..
        else if (match[7].length() > 0)
        {
            std::string lookupname = match[7].str();
            LookupMap &map = lookup(lookupname);
            if (match[8].length() > 0)
            {
                std::string key = match[8].str();
                const string *kval = map.lookup(_config.valueOf(key));
                if (!kval)
                {
                    definitionError(std::string("Value ") + lookupname + "(" + key + ") is not defined for " + value.name());
                }
                else
                {
                    cvalue->add(*kval);
                }
            }
            else
            {
                if (match[10].length() > 0)
                {
                    definitionError(std::string("Column name ") + match[10].str() + " for " + value.name() + "should start with @", Warning);
                }
                LookupValue *lv = new LookupValue();
                lv->setMap(map);
                std::string colname = match[9].str() + match[10].str();
                recordUsedColumn(colname);
                lv->setSource(new NamedValue(colname, ""));
                cvalue->add(lv);
            }
        }
        // Any other value is treated as literal text (previously it
        // was considered invalid.  Change for forward compatibility of non data value
        // definitions
        else if (match[11].length() > 0)
        {
            string bad(match[11].first, valuestr.end());
            definitionError(string("Invalid value for ") + value.name() + ": " + bad);
            break;
        }
    }
    if (!value.cvalue().hasValue())
    {
        definitionError(string("Value not defined for ") + value.name());
    }
}

const string SnapCsvBase::getConfigValue(const std::string &name, RecordStream &rs)
{
    string valuestr;
    getline(rs.record(), valuestr);
    return getConfigValue(name, valuestr);
}

const string SnapCsvBase::getConfigValue(const std::string &name, const string &valuestr)
{
    string value("");
    RGX::regex re(
        "\\s*(?:"
        "(default)|"                       // Start of default (1)
        "(\\-?\\d+\\.?\\d*)|"              // A number (2)
        "\\\"((?:[^\\\"]|\\\"\\\")*)\\\"|" // Literal string (3)
        "(?:\\$(\\w+))|"                   // Config item (4)
        "(?:\\@(\\w+))|"                   // Column name (5)
        "([a-z_]\\w*)\\(\\s*"              // Start of lookup (6)
        "(?:\\$(\\w+)|\\@(\\w+))"          // Lookup config/column (7)(8)
        "\\s*\\)|"                         // End of lookup
        "(\\S+)"                           // Other random string (9)
        ")(?:\\s|$)",                      // Terminating space or end
        RGX::regex_constants::icase);
    RGX::sregex_iterator imatch(valuestr.begin(), valuestr.end(), re);
    RGX::sregex_iterator end;
    for (; imatch != end; imatch++)
    {
        auto match = *imatch;
        string nextpart("");
        // default ...
        if (match[1].length() > 0)
        {
            if (value.length() > 0)
                break;
        }
        // Numeric value
        else if (match[2].length() > 0)
        {
            nextpart = match[2].str();
        }
        // Literal text
        else if (match[3].length() > 0)
        {
            nextpart = RGX::regex_replace(match[3].str(), RGX::regex("\\\"\\\""), string("\""));
        }
        // Config item
        else if (match[4].length() > 0)
        {
            nextpart = _config.valueOf(match[4].str());
        }

        // Column based value.
        else if (match[5].length() > 0)
        {
            string colname = match[5].str();
            definitionError(string("Column value ") + colname + " is not valid in definition of " + colname);
            break;
        }
        // Lookup value ..
        else if (match[6].length() > 0)
        {
            std::string lookupname = match[6].str();
            LookupMap &map = lookup(lookupname);
            if (match[7].length() > 0)
            {
                std::string key = _config.valueOf(match[7].str());
                const std::string *keyval = map.lookup(key);
                if (keyval)
                {
                    nextpart = *keyval;
                }
                else
                {
                    definitionError(std::string("Value ") + lookupname + "(" + key + ") is not defined for " + name);
                }
            }
            else
            {
                string colname = match[8].str();
                definitionError(string("Column value ") + colname + " is not valid in definition of " + name);
            }
        }
        // Any other value is treated as literal text
        else if (match[9].length() > 0)
        {
            definitionError(std::string("String value ") + match[9].str() + " for " + name + " should be enclosed in \"\"", Warning);
            nextpart = match[9];
        }
        if (nextpart.length() > 0)
        {
            if (value.length() > 0)
                value += " ";
            value += nextpart;
        }
    }
    return value;
}

void SnapCsvBase::loadLookupDefinition(RecordStream &rs, const string &lookupName, bool skip)
{
    LookupMap &map = lookup(lookupName);
    string key;
    string value;
    bool finished = false;
    while (!finished && rs.readRecord())
    {
        rs.record() >> key;
        boost::to_lower(key);
        if (key == "end_lookup")
        {
            finished = true;
        }
        else if (!skip)
        {
            std::getline(rs.record(), value);
            boost::trim(value);
            if (key == "default")
            {
                map.setDefault(value);
            }
            else
            {
                map.add(key, value);
            }
        }
    }
    if (!finished)
    {
        definitionError("Lookup definition not terminated");
    }
}

void SnapCsvBase::loadColumnsDefinition(RecordStream &rs, std::vector<std::string> &cols)
{

    std::string colname;
    while (rs.record() >> colname)
    {
        cols.push_back(colname);
    }
}

static char getChar(const std::string &chardef)
{
    char c = 0;
    if (boost::iequals(chardef, string("tab")))
        c = '\t';
    else if (boost::iequals(chardef, string("space")))
        c = ' ';
    else if (chardef.size() == 1)
        c = chardef[0];
    return c;
}

void SnapCsvBase::loadFormatDefinition(const std::string &formatstr)
{
    RGX::regex re(
        "^\\s*"
        "(?:"
        "(csv)|"                      // CSV format
        "(delimiter\\=whitespace)|"   // Whitespace delimited
        "delimiter\\=(\\S|tab|space)" // Custom delimited parser
        "(?:\\s+quote=(\\S|tab|space))?"
        "(?:\\s+escape=(\\S|tab|space))?"
        ")"
        "(?:\\s+header=(?:y|(n)))?$", // Read headers? Default is Y,
        RGX::regex_constants::icase);
    RGX::smatch match;
    if (RGX::regex_match(formatstr.begin(), formatstr.end(), match, re))
    {
        if (match[1].length() > 0)
        {
            _format.reset(new CsvFormat());
        }
        else if (match[2].length() > 0)
        {
            _format.reset(new WhitespaceFormat());
        }
        else
        {
            char delim = getChar(match[3].str());
            char quote = getChar(match[4].str());
            char escape = getChar(match[5].str());
            _format.reset(new CsvFormat(delim, escape, quote));
        }
        if (match[6].length() > 0)
            _options.setUseHeader(false);
    }
    else
    {
        definitionError(string("Invalid format specification: ") + formatstr);
    }
}

LookupMap &SnapCsvBase::lookup(const std::string &lookupName)
{
    std::string name(lookupName);
    boost::to_lower(name);
    if (!_lookups.count(name))
    {
        _lookups.insert(pair<string, LookupMap>(name, LookupMap(false)));
    }
    return _lookups[name];
}

max_stars_repo_name: linz/snap

max_issues_repo_name: linz/snap

max_forks_repo_name: linz/snap