<commit_before>/* Jim Viebke
Jun 3 2015 */

#include "non_player_character.h"

void NPC::a_star_pathfind(const int & x_dest, const int & y_dest, World & world)
{
	cout << "\nSearching for path from " << x << "," << y << " to " << x_dest << "," << y_dest << ".\n";

	/* F = G + H

	G: actual cost to reach a certain room
	H: estimated cost to reach destination from a certain room

	f-cost = g + h */

	vector<Node> open_list, closed_list;

	// Add current room to open list.
	open_list.push_back(Node(this->x, this->y, ""));
	// calculate current room's costs. G cost starts at 0.
	open_list[0].set_g_h_f(0, R::diagonal_distance(x_dest, y_dest, this->x, this->y));

	// Do
	do
	{
		/*// -- Find lowest f-cost room on open list
		// -- Move it to closed list
		Node current_room = move_and_get_lowest_f_cost(open_list, closed_list); */

		// work through every open room
		Node current_room = open_list[0]; // copy
		closed_list.push_back(current_room); // move to closed
		open_list.erase(open_list.begin()); // erase original

		// -- For each adjacent room to current
		for (const string & direction : C::direction_ids)
		{
			if (direction == C::UP || direction == C::DOWN) { continue; } // only pathfinding in 2D now

			// calculate the location deltas
			int dx = 0, dy = 0, dz = 0;
			R::assign_movement_deltas(direction, dx, dy, dz);

			// skip if the room is out of bounds
			if (!R::bounds_check(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX)) { continue; }
			// skip the room if it is not loaded
			if (world.room_at(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX) == nullptr) { continue; }
			// skip the room if it is not within view distance
			if (!world.room_at(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX)->is_observed_by(this->name)) { continue; }

			// create a node to select the next adjacent room
			Node adjacent_room(current_room.x + dx, current_room.y + dy, direction);

			// -- -- pass if it is on the closed list
			if (room_in_node_list(adjacent_room.x, adjacent_room.y, closed_list)) { continue; }

			// -- -- pass if we can not travel to it from the current room
			if (validate_movement(current_room.x, current_room.y, C::GROUND_INDEX, direction, dx, dy, 0, world) != C::GOOD_SIGNAL) { continue; }

			// -- -- if room is not on open list
			if (!room_in_node_list(adjacent_room.x, adjacent_room.y, open_list))
			{
				// -- -- -- Make current room the parent of adjacent
				adjacent_room.parent_x = current_room.x;
				adjacent_room.parent_y = current_room.y;
				// -- -- -- Record F, G, H costs of room
				adjacent_room.set_g_h_f(
					current_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL), // check if the movement is non-diagonal or diagonal
					R::diagonal_distance(x_dest, y_dest, adjacent_room.x, adjacent_room.y));
			}
			// -- -- (else room is on open list)
			else
			{
				// pull adjacent_room out of open_list
				for (unsigned i = 0; i < open_list.size(); ++i) // for each node in the open list
				{
					if (open_list[i].x == adjacent_room.x && open_list[i].y == adjacent_room.y) // if the node is the current room
					{
						adjacent_room = get_node_at(adjacent_room.x, adjacent_room.y, open_list); // save it
						open_list.erase(open_list.begin() + i); // erase the original
						break; // adjacent_room is now the one from the list
					}
				}

				// -- -- if this g-cost to room is less than current g-cost to room
				if (current_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL) < adjacent_room.g)
				{
					// -- -- -- update current room to new parent of room
					adjacent_room.parent_x = current_room.x;
					adjacent_room.parent_y = current_room.y;
					// -- -- -- update costs
					adjacent_room.set_g_h_f(
						current_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL), // check if the movement is non-diagonal or diagonal
						R::diagonal_distance(x_dest, y_dest, adjacent_room.x, adjacent_room.y));
				}
			}

			// -- -- -- Add room to open list
			open_list.push_back(adjacent_room);

		} // end for each adjacent room

		// keep searching if we have not reached the destination OR there are still rooms to search
	} while (!room_in_node_list(x_dest, y_dest, closed_list) || open_list.size() > 0);

	// Starting from target room, continue finding parent until the current room is found
	// (this represents the path in reverse)

	// get the target room
	Node current_room = get_node_at(x_dest, y_dest, closed_list);

	// if there is no target room in the closed list, a path could not be found
	if (current_room.x == -1 || current_room.y == -1) { return; }

	do
	{
		// get the parent room
		Node parent_room = get_node_at(current_room.parent_x, current_room.parent_y, closed_list);

		cout << "\nI can get to " << current_room.x << "," << current_room.y << " from " << parent_room.x << "," << parent_room.y << ".";

		// if the parent of current_room is our location, move to current_room
		if (parent_room.x == this->x && parent_room.y == this->y)
		{
			// move to current
			//this->move(C::opposite_direction_id.find(current_room.direction_from_parent)->second, world);
			move(current_room.direction_from_parent, world);

			// debugging
			cout << endl;
			for (const Node & node : closed_list)
			{
				cout << "Parent of " << node.x << "," << node.y << " is " << node.parent_x << "," << node.parent_y << endl <<
					"Actual cost to reach this node: " << node.g << ". Estimated cost to target: " << node.h << endl << endl;
			}

			return; // we're done here
		}
		// if there is no parent room in the closed list (?!)
		else if (parent_room.x == -1 || parent_room.y == -1)
		{
			return; // something went horribly wrong
		}

		// move up the path by one room
		current_room = parent_room;

	} while (true);
}
<commit_msg>comment out debug code<commit_after>/* Jim Viebke
Jun 3 2015 */

#include "non_player_character.h"

void NPC::a_star_pathfind(const int & x_dest, const int & y_dest, World & world)
{
	// leave this for debugging
	// cout << "\nSearching for path from " << x << "," << y << " to " << x_dest << "," << y_dest << ".\n";

	/* F = G + H

	G: actual cost to reach a certain room
	H: estimated cost to reach destination from a certain room

	f-cost = g + h */

	vector<Node> open_list, closed_list;

	// Add current room to open list.
	open_list.push_back(Node(this->x, this->y, ""));
	// calculate current room's costs. G cost starts at 0.
	open_list[0].set_g_h_f(0, R::diagonal_distance(x_dest, y_dest, this->x, this->y));

	// Do
	do
	{
		/*// -- Find lowest f-cost room on open list
		// -- Move it to closed list
		Node current_room = move_and_get_lowest_f_cost(open_list, closed_list); */

		// work through every open room
		Node current_room = open_list[0]; // copy
		closed_list.push_back(current_room); // move to closed
		open_list.erase(open_list.begin()); // erase original

		// -- For each adjacent room to current
		for (const string & direction : C::direction_ids)
		{
			if (direction == C::UP || direction == C::DOWN) { continue; } // only pathfinding in 2D now

			// calculate the location deltas
			int dx = 0, dy = 0, dz = 0;
			R::assign_movement_deltas(direction, dx, dy, dz);

			// skip if the room is out of bounds
			if (!R::bounds_check(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX)) { continue; }
			// skip the room if it is not loaded
			if (world.room_at(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX) == nullptr) { continue; }
			// skip the room if it is not within view distance
			if (!world.room_at(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX)->is_observed_by(this->name)) { continue; }

			// create a node to select the next adjacent room
			Node adjacent_room(current_room.x + dx, current_room.y + dy, direction);

			// -- -- pass if it is on the closed list
			if (room_in_node_list(adjacent_room.x, adjacent_room.y, closed_list)) { continue; }

			// -- -- pass if we can not travel to it from the current room
			if (validate_movement(current_room.x, current_room.y, C::GROUND_INDEX, direction, dx, dy, 0, world) != C::GOOD_SIGNAL) { continue; }

			// -- -- if room is not on open list
			if (!room_in_node_list(adjacent_room.x, adjacent_room.y, open_list))
			{
				// -- -- -- Make current room the parent of adjacent
				adjacent_room.parent_x = current_room.x;
				adjacent_room.parent_y = current_room.y;
				// -- -- -- Record F, G, H costs of room
				adjacent_room.set_g_h_f(
					current_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL), // check if the movement is non-diagonal or diagonal
					R::diagonal_distance(x_dest, y_dest, adjacent_room.x, adjacent_room.y));
			}
			// -- -- (else room is on open list)
			else
			{
				// pull adjacent_room out of open_list
				for (unsigned i = 0; i < open_list.size(); ++i) // for each node in the open list
				{
					if (open_list[i].x == adjacent_room.x && open_list[i].y == adjacent_room.y) // if the node is the current room
					{
						adjacent_room = get_node_at(adjacent_room.x, adjacent_room.y, open_list); // save it
						open_list.erase(open_list.begin() + i); // erase the original
						break; // adjacent_room is now the one from the list
					}
				}

				// -- -- if this g-cost to room is less than current g-cost to room
				if (current_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL) < adjacent_room.g)
				{
					// -- -- -- update current room to new parent of room
					adjacent_room.parent_x = current_room.x;
					adjacent_room.parent_y = current_room.y;
					// -- -- -- update costs
					adjacent_room.set_g_h_f(
						current_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL), // check if the movement is non-diagonal or diagonal
						R::diagonal_distance(x_dest, y_dest, adjacent_room.x, adjacent_room.y));
				}
			}

			// -- -- -- Add room to open list
			open_list.push_back(adjacent_room);

		} // end for each adjacent room

		// keep searching if we have not reached the destination OR there are still rooms to search
	} while (/*!room_in_node_list(x_dest, y_dest, closed_list) ||*/ open_list.size() > 0);

	// Starting from target room, continue finding parent until the current room is found
	// (this represents the path in reverse)

	// get the target room
	Node current_room = get_node_at(x_dest, y_dest, closed_list);

	// if there is no target room in the closed list, a path could not be found
	if (current_room.x == -1 || current_room.y == -1) { return; }

	do
	{
		// get the parent room
		Node parent_room = get_node_at(current_room.parent_x, current_room.parent_y, closed_list);

		// leave this here for debugging
		// cout << "\nI can get to " << current_room.x << "," << current_room.y << " from " << parent_room.x << "," << parent_room.y << ".";

		// if the parent of current_room is our location, move to current_room
		if (parent_room.x == this->x && parent_room.y == this->y)
		{
			// move to current
			//this->move(C::opposite_direction_id.find(current_room.direction_from_parent)->second, world);
			move(current_room.direction_from_parent, world);

			/* leave this here for debugging
			cout << endl;
			for (const Node & node : closed_list)
			{
				cout << "Parent of " << node.x << "," << node.y << " is " << node.parent_x << "," << node.parent_y << endl <<
					"Actual cost to reach this node: " << node.g << ". Estimated cost to target: " << node.h << endl << endl;
			}*/

			return; // we're done here
		}
		// if there is no parent room in the closed list (?!)
		else if (parent_room.x == -1 || parent_room.y == -1)
		{
			return; // something went horribly wrong
		}

		// move up the path by one room
		current_room = parent_room;

	} while (true);
}
<|endoftext|>


<commit_before>/*
 * examples/matrices.C
 *
 * Copyright (C) 2017  D. Saunders, Z. Wang, J-G Dumas
 * ========LICENCE========
 * This file is part of the library LinBox.
 *
 * LinBox is free software: you can redistribute it and/or modify
 * it under the terms of the  GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * ========LICENCE========
 */

/** \file examples/matrices.C
 * @example  examples/matrices.C
 \brief example matrices that were chosen for Smith form testing.
 \ingroup examples

 \author bds & zw

 Various Smith form algorithms may be used for matrices over the
 integers or over Z_m.  Moduli greater than 2^32 are not supported here.
 Several types of example matrices may be constructed or the matrix be read from a file.
 Run the program with no arguments for a synopsis of the command line parameters.

 For the "adaptive" method, the matrix must be over the integers.
 This is expected to work best for large matrices.

 For the "2local" method, the computation is done mod 2^32.

 For the "local" method, the modulus must be a prime power.

 For the "ilio" method, the modulus may be arbitrary composite.
 If the modulus is a multiple of the integer determinant, the integer Smith form is obtained.
 Determinant plus ilio may be best for smaller matrices.

 This example was used during the design process of the adaptive algorithm.
*/

#include <linbox/linbox-config.h>
#include <iostream>
#include <string>

using namespace std;

#include <linbox/util/timer.h>
#include <linbox/matrix/dense-matrix.h>

#include "matrices.h"

template <class PIR>
void Mat(LinBox::DenseMatrix<PIR>& M, PIR& R, int & n, string src) ;

int main(int argc, char* argv[])
{
	if (argc < 3 or argc > 4) {

		cout << "usage: " << argv[0] << " type n [filename]"  << endl;

		cout << " type = `random', `random-rough', `tref', or `fib',"
			 << " and n is the dimension" << endl;
		cout  << " If filename is present, matrix is written there, else to cout." << endl;

		return 0;
	}

	string type = argv[1];

	int n = atoi(argv[2]);

// place B: Edit here and at place A for ring change
	//typedef PIRModular<int32_t> PIR;
	typedef Givaro::ZRing<Givaro::Integer> PIR;
	PIR R;
	LinBox::DenseMatrix<PIR> M(R);

	Mat(M,R,n,type);

    if (M.rowdim() <= 20 && M.coldim() <= 20) {
        M.write(std::clog, LinBox::Tag::FileFormat::Maple) << std::endl;
    }

	if (argc == 4) {
		ofstream out(argv[3]);
		M.write(out) << endl;
	} else {
		M.write(cout) << endl;
	}
}// main

/** Output matrix is determined by src which may be:
  "random-rough"
  This mat will have s, near sqrt(n), distinct invariant factors,
  each repeated twice), involving the s primes 101, 103, ...
  "random"
  This mat will have the same nontrivial invariant factors as
  diag(1,2,3,5,8, ... 999, 0, 1, 2, ...).
  "fib"
  This mat will have the same nontrivial invariant factors as
  diag(1,2,3,5,8, ... fib(k)), where k is about sqrt(n).
  The basic matrix is block diagonal with i-th block of order i and
  being a tridiagonal {-1,0,1} matrix whose snf = diag(i-1 1's, fib(i)),
  where fib(1) = 1, fib(2) = 2.  But note that, depending on n,
  the last block may be truncated, thus repeating an earlier fibonacci number.
  "file" (or any other string)
  Also "tref" and file with format "kdense"
  */
template <class PIR>
void Mat(LinBox::DenseMatrix<PIR>& M, PIR& R, int & n,
         string src) {

	if (src == "random-rough") RandomRoughMat(M, R, n);

	else if (src == "random") RandomFromDiagMat(M, R, n);

	else if (src == "fib") RandomFibMat(M, R, n);

	else if (src == "tref") TrefMat(M, R, n);

	else if (src == "krat") KratMat(M, R, n);

	else { // from cin, mostly pointless, but may effect a file format change.

			M.read(cin);
		n = M.rowdim();
	}

} // Mat
<commit_msg>add moler redheffer<commit_after>/*
 * examples/matrices.C
 *
 * Copyright (C) 2017  D. Saunders, Z. Wang, J-G Dumas
 * ========LICENCE========
 * This file is part of the library LinBox.
 *
 * LinBox is free software: you can redistribute it and/or modify
 * it under the terms of the  GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * ========LICENCE========
 */

/** \file examples/matrices.C
 * @example  examples/matrices.C
 \brief example matrices that were chosen for Smith form testing.
 \ingroup examples

 \author bds & zw

 Various Smith form algorithms may be used for matrices over the
 integers or over Z_m.  Moduli greater than 2^32 are not supported here.
 Several types of example matrices may be constructed or the matrix be read from a file.
 Run the program with no arguments for a synopsis of the command line parameters.

 For the "adaptive" method, the matrix must be over the integers.
 This is expected to work best for large matrices.

 For the "2local" method, the computation is done mod 2^32.

 For the "local" method, the modulus must be a prime power.

 For the "ilio" method, the modulus may be arbitrary composite.
 If the modulus is a multiple of the integer determinant, the integer Smith form is obtained.
 Determinant plus ilio may be best for smaller matrices.

 This example was used during the design process of the adaptive algorithm.
*/

#include <linbox/linbox-config.h>
#include <iostream>
#include <string>

using namespace std;

#include <linbox/util/timer.h>
#include <linbox/matrix/dense-matrix.h>

#include "matrices.h"

template <class PIR>
void Mat(LinBox::DenseMatrix<PIR>& M, PIR& R, int & n, string src) ;

int main(int argc, char* argv[])
{
	if (argc < 3 or argc > 4) {

		cout << "usage: " << argv[0] << " type n [filename]"  << endl;

		cout << " type = `random', `random-rough', `tref',"
             << " 'moler', 'redheffer', "
             << " or `fib',"
			 << " and n is the dimension" << endl;
		cout  << " If filename is present, matrix is written there, else to cout." << endl;

		return 0;
	}

	string type = argv[1];

	int n = atoi(argv[2]);

// place B: Edit here and at place A for ring change
	//typedef PIRModular<int32_t> PIR;
	typedef Givaro::ZRing<Givaro::Integer> PIR;
	PIR R;
	LinBox::DenseMatrix<PIR> M(R);

	Mat(M,R,n,type);

    if (M.rowdim() <= 20 && M.coldim() <= 20) {
        M.write(std::clog, LinBox::Tag::FileFormat::Maple) << std::endl;
    }

	if (argc == 4) {
		ofstream out(argv[3]);
		M.write(out) << endl;
	} else {
		M.write(cout) << endl;
	}
}// main

/** Output matrix is determined by src which may be:
  "random-rough"
  This mat will have s, near sqrt(n), distinct invariant factors,
  each repeated twice), involving the s primes 101, 103, ...
  "random"
  This mat will have the same nontrivial invariant factors as
  diag(1,2,3,5,8, ... 999, 0, 1, 2, ...).
  "fib"
  This mat will have the same nontrivial invariant factors as
  diag(1,2,3,5,8, ... fib(k)), where k is about sqrt(n).
  The basic matrix is block diagonal with i-th block of order i and
  being a tridiagonal {-1,0,1} matrix whose snf = diag(i-1 1's, fib(i)),
  where fib(1) = 1, fib(2) = 2.  But note that, depending on n,
  the last block may be truncated, thus repeating an earlier fibonacci number.
  "file" (or any other string)
  Also "tref" and file with format "kdense"
  */
template <class PIR>
void Mat(LinBox::DenseMatrix<PIR>& M, PIR& R, int & n,
         string src) {

	if (src == "random-rough") RandomRoughMat(M, R, n);

	else if (src == "random") RandomFromDiagMat(M, R, n);

	else if (src == "fib") RandomFibMat(M, R, n);

	else if (src == "tref") TrefMat(M, R, n);

	else if (src == "krat") KratMat(M, R, n);

	else if (src == "moler") MolerMat(M, R, n);

	else if (src == "redheffer") RedhefferMat(M, R, n);

	else { // from cin, mostly pointless, but may effect a file format change.

			M.read(cin);
		n = M.rowdim();
	}

} // Mat
<|endoftext|>


<commit_before>#include "serial.h"

speed_t baud = 4800;
std::string port = "/dev/ttyUSB0";
Serial gps(baud, port, false);

void readGPS()
{
	for(int i = 0; i < 4; ++i) {

		while(gps.serialRead(1)) {
			if (gps.getData() == "\n") break;
			std::cout << gps.getData();
		}
		std::cout << std::endl;
	}
}

void printConfig()
{
	termios cur_config = gps.getConfig();
	std::cout << "c_cflag: " << cur_config.c_cflag << std::endl;
	std::cout << "c_iflag: " << cur_config.c_iflag << std::endl;
	std::cout << "c_oflag: " << cur_config.c_oflag << std::endl;
	std::cout << "c_lflag: " << cur_config.c_lflag << std::endl;
}

int main()
{
	printConfig();
	std::cout << "Baud 1: " << gps.getBaud() << std::endl;
	std::cout << "Applying change: " << gps.applyNewConfig() << std::endl;

	baud = 9600;
	std::cout << "Setting Baud to " << baud << ": " << gps.setBaud(baud) << std::endl;
	std::cout << "Applying change: " << gps.applyNewConfig() << std::endl;
	std::cout << "Baud 2: " << gps.getBaud() << std::endl;

	baud = 4800;
	std::cout << "Setting Baud to " << baud << ": " << gps.setBaud(baud) << std::endl;
	std::cout << "Applying change: " << gps.applyNewConfig() << std::endl;
	readGPS();

	baud = 4800;
	std::cout << "Restoring baud to " << baud << ": "  << gps.setBaud(baud) << std::endl;
	std::cout << "Applying change: " << gps.applyNewConfig() << std::endl;
        std::cout << "Baud 2: " << gps.getBaud() << std::endl;
        readGPS();

	return 0;
}
<commit_msg>Delete noCanon.cpp<commit_after><|endoftext|>


<commit_before>#include "catch.hpp"

#include "../statemachine.hpp"

using namespace fsm11;

using StateMachine_t = fsm11::StateMachine<>;
using State_t = StateMachine_t::state_type;

TEST_CASE("construct a state", "[state]")
{
    State_t s("name");

    REQUIRE(s.childMode() == State_t::Exclusive);
    REQUIRE(!std::strcmp(s.name(), "name"));
    REQUIRE(s.parent() == 0);
    REQUIRE(s.isAtomic());
    REQUIRE(!s.isCompound());
    REQUIRE(!s.isParallel());
    REQUIRE(s.stateMachine() == 0);
    REQUIRE(!s.isActive());

    REQUIRE(s.beginTransitions() == s.endTransitions());
    REQUIRE(s.cbeginTransitions() == s.cendTransitions());
}

TEST_CASE("set the parent of a state", "[state]")
{
    State_t p1("p1");
    State_t p2("p2");

    State_t c("c", &p1);
    REQUIRE(&p1 == c.parent());
    REQUIRE(!p1.isAtomic());
    REQUIRE(p2.isAtomic());

    c.setParent(&p2);
    REQUIRE(&p2 == c.parent());
    REQUIRE(p1.isAtomic());
    REQUIRE(!p2.isAtomic());

    c.setParent(&p1);
    REQUIRE(&p1 == c.parent());
    REQUIRE(!p1.isAtomic());
    REQUIRE(p2.isAtomic());
}

TEST_CASE("change the child mode", "[state]")
{
    State_t s("s");
    State_t c("c", &s);

    REQUIRE(State_t::Exclusive == s.childMode());
    REQUIRE(s.isCompound());
    REQUIRE(!s.isParallel());

    s.setChildMode(State_t::Parallel);
    REQUIRE(State_t::Parallel == s.childMode());
    REQUIRE(!s.isCompound());
    REQUIRE(s.isParallel());

    s.setChildMode(State_t::Exclusive);
    REQUIRE(State_t::Exclusive == s.childMode());
    REQUIRE(s.isCompound());
    REQUIRE(!s.isParallel());
}

#if 0
TEST_CASE("find a child", "[state]")
{
    State_t p("p");
    State_t c1("c1", &p);
    State_t c2("c2", &p);
    State_t c3("c3", &p);
    State_t c11("c11", &c1);
    State_t c12("c12", &c1);
    State_t c31("c31", &c3);
    State_t c32("c32", &c3);

    State_t* found = p.findChild("c1");
    REQUIRE(found != 0);
    REQUIRE(!std::strcmp("c1", found->name()));

    found = p.findChild("c1", "c12");
    REQUIRE(found != 0);
    REQUIRE(!std::strcmp("c12", found->name()));
}
#endif
TEST_CASE("hierarchy properties", "[state]")
{
    State_t p("p");
    State_t c1("c1", &p);
    State_t c2("c2", &p);
    State_t c3("c3", &p);
    State_t c11("c11", &c1);
    State_t c12("c12", &c1);
    State_t c31("c31", &c3);
    State_t c32("c32", &c3);

    REQUIRE(isAncestor(&p, &p));
    REQUIRE(isDescendant(&p, &p));

    REQUIRE(isAncestor(&p, &c1));
    REQUIRE(isAncestor(&p, &c2));
    REQUIRE(isAncestor(&p, &c3));
    REQUIRE(isAncestor(&p, &c11));
    REQUIRE(isAncestor(&p, &c12));
    REQUIRE(isAncestor(&p, &c31));
    REQUIRE(isAncestor(&p, &c32));

    REQUIRE(isAncestor(&c1, &c11));
    REQUIRE(isAncestor(&c1, &c12));
    REQUIRE(!isAncestor(&c1, &c31));
    REQUIRE(!isAncestor(&c1, &c32));
}
<commit_msg>More tests for the setters of State.<commit_after>#include "catch.hpp"

#include "../statemachine.hpp"

using namespace fsm11;

using StateMachine_t = fsm11::StateMachine<>;
using State_t = StateMachine_t::state_type;

TEST_CASE("construct a state", "[state]")
{
    State_t s("name");

    REQUIRE(s.childMode() == State_t::Exclusive);
    REQUIRE(!std::strcmp(s.name(), "name"));
    REQUIRE(s.parent() == 0);
    REQUIRE(s.isAtomic());
    REQUIRE(!s.isCompound());
    REQUIRE(!s.isParallel());
    REQUIRE(s.stateMachine() == 0);
    REQUIRE(!s.isActive());

    REQUIRE(s.beginTransitions() == s.endTransitions());
    REQUIRE(s.cbeginTransitions() == s.cendTransitions());
}

TEST_CASE("set the parent of a state", "[state]")
{
    State_t p1("p1");
    State_t p2("p2");

    State_t c("c", &p1);
    REQUIRE(&p1 == c.parent());
    REQUIRE(!p1.isAtomic());
    REQUIRE(p2.isAtomic());

    c.setParent(&p2);
    REQUIRE(&p2 == c.parent());
    REQUIRE(p1.isAtomic());
    REQUIRE(!p2.isAtomic());

    c.setParent(&p1);
    REQUIRE(&p1 == c.parent());
    REQUIRE(!p1.isAtomic());
    REQUIRE(p2.isAtomic());
}

TEST_CASE("set the state machine", "[state]")
{
    StateMachine_t sm1;
    State_t s1("s1", &sm1);
    State_t s2("s2");
    State_t s3("s3", &s2);

    REQUIRE(s1.stateMachine() == &sm1);
    REQUIRE(s2.stateMachine() == 0);
    REQUIRE(s3.stateMachine() == 0);
    s2.setParent(&s1);
    REQUIRE(s1.stateMachine() == &sm1);
    REQUIRE(s2.stateMachine() == &sm1);
    REQUIRE(s3.stateMachine() == &sm1);

    State_t s4("s4", &s2);
    REQUIRE(s4.stateMachine() == &sm1);

    REQUIRE(!s1.isAtomic());

    StateMachine_t sm2;
    s2.setParent(&sm2);

    REQUIRE(s1.stateMachine() == &sm1);
    REQUIRE(s2.stateMachine() == &sm2);
    REQUIRE(s3.stateMachine() == &sm2);
    REQUIRE(s4.stateMachine() == &sm2);

    REQUIRE(s1.isAtomic());
}

TEST_CASE("change the child mode", "[state]")
{
    State_t s("s");
    State_t c("c", &s);

    REQUIRE(State_t::Exclusive == s.childMode());
    REQUIRE(s.isCompound());
    REQUIRE(!s.isParallel());

    s.setChildMode(State_t::Parallel);
    REQUIRE(State_t::Parallel == s.childMode());
    REQUIRE(!s.isCompound());
    REQUIRE(s.isParallel());

    s.setChildMode(State_t::Exclusive);
    REQUIRE(State_t::Exclusive == s.childMode());
    REQUIRE(s.isCompound());
    REQUIRE(!s.isParallel());
}

#if 0
TEST_CASE("find a child", "[state]")
{
    State_t p("p");
    State_t c1("c1", &p);
    State_t c2("c2", &p);
    State_t c3("c3", &p);
    State_t c11("c11", &c1);
    State_t c12("c12", &c1);
    State_t c31("c31", &c3);
    State_t c32("c32", &c3);

    State_t* found = p.findChild("c1");
    REQUIRE(found != 0);
    REQUIRE(!std::strcmp("c1", found->name()));

    found = p.findChild("c1", "c12");
    REQUIRE(found != 0);
    REQUIRE(!std::strcmp("c12", found->name()));
}
#endif
TEST_CASE("state relationship", "[state]")
{
    State_t p("p");
    State_t c1("c1", &p);
    State_t c2("c2", &p);
    State_t c3("c3", &p);
    State_t c11("c11", &c1);
    State_t c12("c12", &c1);
    State_t c31("c31", &c3);
    State_t c32("c32", &c3);

    REQUIRE(isAncestor(&p, &p));
    REQUIRE(isDescendant(&p, &p));

    REQUIRE(isAncestor(&p, &c1));
    REQUIRE(isAncestor(&p, &c2));
    REQUIRE(isAncestor(&p, &c3));
    REQUIRE(isAncestor(&p, &c11));
    REQUIRE(isAncestor(&p, &c12));
    REQUIRE(isAncestor(&p, &c31));
    REQUIRE(isAncestor(&p, &c32));

    REQUIRE(isAncestor(&c1, &c11));
    REQUIRE(isAncestor(&c1, &c12));
    REQUIRE(!isAncestor(&c1, &c31));
    REQUIRE(!isAncestor(&c1, &c32));

    REQUIRE(!isProperAncestor(&p, &p));
    REQUIRE(!isProperAncestor(&c1, &p));
    REQUIRE(isProperAncestor(&p, &c1));
    REQUIRE(isProperAncestor(&p, &c11));
}
<|endoftext|>


<commit_before>#include "notepad.h"
#include "ui_notepad.h"
#include <QFileDialog>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
#include <QListWidget>
#include <QtPrintSupport>
#include <QListView>
#include <fileviewmodel.h>

Notepad::Notepad(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Notepad)
{
    // TODO, not sure where to organize instantiating methods
    // Temporarily changing to a directory
    working_dir = QDir("/Users/pybae/Documents");
    QStringList files = working_dir.entryList();

    ui->setupUi(this);

    FileViewModel *fileModel = new FileViewModel(files, 0);
    ui->listView->setModel(fileModel);
    ui->listView->show();

    printf("%d\n", fileModel->rowCount());
}

Notepad::~Notepad()
{
    delete ui;
}

// A helper method to save a file, given a fileName in the current working directory
void Notepad::saveFile(QString fileName)
{
    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (!file.open(QIODevice::WriteOnly)) {
            // error message
            return;
        } else {
            QTextStream stream(&file);
            stream << ui->mainTextEdit->toPlainText() << "\n";
            stream.flush();
            file.close();
        }
    }
    else {
        printf("File does not exist\n");
    }
}

// Called when the "New" option is triggered by C-n or menu
void Notepad::on_actionNew_triggered()
{
    QString newFileName = QFileDialog::getSaveFileName(this, tr("New File"), working_dir.absolutePath(),
            tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
    saveFile(newFileName);
    working_file_name = newFileName;
}

// Called when the "Open" option is triggered by C-o or menu
void Notepad::on_actionOpen_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), working_dir.absolutePath(),
            tr("All Files (*.*);;Text Files (*.txt);;RTF Filess(*.rtf);;C++ Files (*.cpp *.h)"));

    if (!fileName.isEmpty()) {
        QFile file(fileName);
        working_file_name = file.fileName();

        if (!file.open(QIODevice::ReadOnly)) {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
            return;
        }
        QTextStream in(&file);
        ui->mainTextEdit->setText(in.readAll());
        file.close();
    }
}

// Called when the "Save" option is triggered by C-s or menu
void Notepad::on_actionSave_triggered()
{
    saveFile(working_file_name);
}

// Called when the "Save As" option is triggered by C-S (Ctrl shift s) or menu
void Notepad::on_actionSaveAs_triggered()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), QString(),
            tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
    saveFile(fileName);
}

// Called when the "Print" option is triggered by C-p or menu
void Notepad::on_actionPrint_triggered()
{
//     QPrinter printer;

//     QPrintDialog dialog(&printer, this);
//     dialog.setWindowTitle(tr("Print Document"));
//     if (dialog.exec() != QDialog::Accepted) {
//         return;
//     }
}

// Called when the "Exit" option is triggered by C-q or menu
void Notepad::on_actionExit_triggered()
{
    // TODO need to check if there are any unsaved buffers
    qApp->quit();
}

// Triggered when the mainTextEdit region has its text changed
// TODO figure out how frequently this method is called
void Notepad::on_mainTextEdit_textChanged()
{
    // Save the current buffer
    // Notepad::on_actionSave_triggered();
}
<commit_msg>Fixed typo<commit_after>#include "notepad.h"
#include "ui_notepad.h"
#include <QFileDialog>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
#include <QListWidget>
#include <QtPrintSupport>
#include <QListView>
#include <fileviewmodel.h>

Notepad::Notepad(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Notepad)
{
    // TODO, not sure where to organize instantiating methods
    // Temporarily changing to a directory
    working_dir = QDir("/Users/pybae/Documents");
    QStringList files = working_dir.entryList();

    ui->setupUi(this);

    FileViewModel *fileModel = new FileViewModel(files, 0);
    ui->listView->setModel(fileModel);
    ui->listView->show();
}

Notepad::~Notepad()
{
    delete ui;
}

// A helper method to save a file, given a fileName in the current working directory
void Notepad::saveFile(QString fileName)
{
    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (!file.open(QIODevice::WriteOnly)) {
            // error message
            return;
        } else {
            QTextStream stream(&file);
            stream << ui->mainTextEdit->toPlainText() << "\n";
            stream.flush();
            file.close();
        }
    }
    else {
        printf("File does not exist\n");
    }
}

// Called when the "New" option is triggered by C-n or menu
void Notepad::on_actionNew_triggered()
{
    QString newFileName = QFileDialog::getSaveFileName(this, tr("New File"), working_dir.absolutePath(),
            tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
    saveFile(newFileName);
    working_file_name = newFileName;
}

// Called when the "Open" option is triggered by C-o or menu
void Notepad::on_actionOpen_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), working_dir.absolutePath(),
            tr("All Files (*.*);;Text Files (*.txt);;RTF Files(*.rtf);;C++ Files (*.cpp *.h)"));

    if (!fileName.isEmpty()) {
        QFile file(fileName);
        working_file_name = file.fileName();

        if (!file.open(QIODevice::ReadOnly)) {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
            return;
        }
        QTextStream in(&file);
        ui->mainTextEdit->setText(in.readAll());
        file.close();
    }
}

// Called when the "Save" option is triggered by C-s or menu
void Notepad::on_actionSave_triggered()
{
    saveFile(working_file_name);
}

// Called when the "Save As" option is triggered by C-S (Ctrl shift s) or menu
void Notepad::on_actionSaveAs_triggered()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), QString(),
            tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
    saveFile(fileName);
}

// Called when the "Print" option is triggered by C-p or menu
void Notepad::on_actionPrint_triggered()
{
//     QPrinter printer;

//     QPrintDialog dialog(&printer, this);
//     dialog.setWindowTitle(tr("Print Document"));
//     if (dialog.exec() != QDialog::Accepted) {
//         return;
//     }
}

// Called when the "Exit" option is triggered by C-q or menu
void Notepad::on_actionExit_triggered()
{
    // TODO need to check if there are any unsaved buffers
    qApp->quit();
}

// Triggered when the mainTextEdit region has its text changed
// TODO figure out how frequently this method is called
void Notepad::on_mainTextEdit_textChanged()
{
    // Save the current buffer
    // Notepad::on_actionSave_triggered();
}
<|endoftext|>


<commit_before>#include "PrivateQGraphicsItem.h"

#include "MapInfoManager.h"
#include "MapGraphicsScene.h"

#include <QGraphicsSceneContextMenuEvent>
#include <QGraphicsSceneMouseEvent>

PrivateQGraphicsItem::PrivateQGraphicsItem(PrivateQGraphicsItemParent * user) : user(user)
{
    this->setZValue(1.0);
}

QRectF PrivateQGraphicsItem::boundingRect() const
{
    return this->user->boundingRect();
}

void PrivateQGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->save();
    this->user->paint(painter,option,widget);
    painter->restore();
    if (option->state & QStyle::State_Selected)
    {
        const qreal penWidth = 0; // cosmetic pen

        const QColor fgcolor = option->palette.windowText().color();
        const QColor bgcolor( // ensure good contrast against fgcolor
                              fgcolor.red()   > 127 ? 0 : 255,
                              fgcolor.green() > 127 ? 0 : 255,
                              fgcolor.blue()  > 127 ? 0 : 255);

        painter->setPen(QPen(bgcolor, penWidth, Qt::SolidLine));
        painter->setBrush(Qt::NoBrush);
        const qreal pad = 0.2;
        painter->drawRect(this->boundingRect().adjusted(-pad, -pad, pad, pad));

        painter->setPen(QPen(option->palette.windowText(), penWidth, Qt::DashLine));
        painter->setBrush(Qt::NoBrush);
        painter->drawRect(this->boundingRect().adjusted(-pad, -pad, pad, pad));
    }
}

void PrivateQGraphicsItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
    QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();
    if (source.isNull())
        return;
    QGraphicsItem::contextMenuEvent(event);

    /*
    Then we can mangle the coordinates to geographic ones, but we have to mangle it back
    when we're done because this event may be used again
    */
    event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),
                                                        this->user->scene()->getZoomLevel()));
    this->user->contextMenuEvent(event);
    event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),
                                                        this->user->scene()->getZoomLevel()));
}

void PrivateQGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();
    if (source.isNull())
        return;

    //Send the event to the parent class before we mangle the coordinates
    QGraphicsItem::mousePressEvent(event);

    /*
    Then we can mangle the coordinates to geographic ones, but we have to mangle it back
    when we're done because this event may be used again
    */
    event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),
                                                        this->user->scene()->getZoomLevel()));
    this->user->mousePressEvent(event);
    event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),
                                                        this->user->scene()->getZoomLevel()));
}

void PrivateQGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();
    if (source.isNull())
        return;

    //Send the event to the parent class before we mangle the coordinates
    QGraphicsItem::mouseReleaseEvent(event);

    /*
    Then we can mangle the coordinates to geographic ones, but we have to mangle it back
    when we're done because this event may be used again
    */
    event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),
                                                        this->user->scene()->getZoomLevel()));
    this->user->mouseReleaseEvent(event);
    event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),
                                                        this->user->scene()->getZoomLevel()));
}

//protected
QVariant PrivateQGraphicsItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
    return this->user->itemChange(change,value);
}

<commit_msg>Temporarily removed selection rectangle padding from PrivateQGraphicsItem. I like the idea of having padding but I need to make it respect different zoom levels before I put it back.<commit_after>#include "PrivateQGraphicsItem.h"

#include "MapInfoManager.h"
#include "MapGraphicsScene.h"

#include <QGraphicsSceneContextMenuEvent>
#include <QGraphicsSceneMouseEvent>

PrivateQGraphicsItem::PrivateQGraphicsItem(PrivateQGraphicsItemParent * user) : user(user)
{
    this->setZValue(1.0);
}

QRectF PrivateQGraphicsItem::boundingRect() const
{
    return this->user->boundingRect();
}

void PrivateQGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->save();
    this->user->paint(painter,option,widget);
    painter->restore();

    if (option->state & QStyle::State_Selected)
    {
        const qreal penWidth = 0; // cosmetic pen

        const QColor fgcolor = option->palette.windowText().color();
        const QColor bgcolor( // ensure good contrast against fgcolor
                              fgcolor.red()   > 127 ? 0 : 255,
                              fgcolor.green() > 127 ? 0 : 255,
                              fgcolor.blue()  > 127 ? 0 : 255);

        painter->setPen(QPen(bgcolor, penWidth, Qt::SolidLine));
        painter->setBrush(Qt::NoBrush);
        const qreal pad = 0.0;
        painter->drawRect(this->boundingRect().adjusted(-pad, -pad, pad, pad));

        painter->setPen(QPen(option->palette.windowText(), penWidth, Qt::DashLine));
        painter->setBrush(Qt::NoBrush);
        painter->drawRect(this->boundingRect().adjusted(-pad, -pad, pad, pad));
    }
}

void PrivateQGraphicsItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
    QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();
    if (source.isNull())
        return;
    QGraphicsItem::contextMenuEvent(event);

    /*
    Then we can mangle the coordinates to geographic ones, but we have to mangle it back
    when we're done because this event may be used again
    */
    event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),
                                                        this->user->scene()->getZoomLevel()));
    this->user->contextMenuEvent(event);
    event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),
                                                        this->user->scene()->getZoomLevel()));
}

void PrivateQGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();
    if (source.isNull())
        return;

    //Send the event to the parent class before we mangle the coordinates
    QGraphicsItem::mousePressEvent(event);

    /*
    Then we can mangle the coordinates to geographic ones, but we have to mangle it back
    when we're done because this event may be used again
    */
    event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),
                                                        this->user->scene()->getZoomLevel()));
    this->user->mousePressEvent(event);
    event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),
                                                        this->user->scene()->getZoomLevel()));
}

void PrivateQGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();
    if (source.isNull())
        return;

    //Send the event to the parent class before we mangle the coordinates
    QGraphicsItem::mouseReleaseEvent(event);

    /*
    Then we can mangle the coordinates to geographic ones, but we have to mangle it back
    when we're done because this event may be used again
    */
    event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),
                                                        this->user->scene()->getZoomLevel()));
    this->user->mouseReleaseEvent(event);
    event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),
                                                        this->user->scene()->getZoomLevel()));
}

//protected
QVariant PrivateQGraphicsItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
    return this->user->itemChange(change,value);
}

<|endoftext|>


<commit_before>#include <ruby.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "ewah.h"

typedef VALUE (ruby_method)(...);

typedef struct ewah {
  EWAHBoolArray<uword64> *bits;
} EWAH;

extern "C" void ewah_free(EWAH *bits) {
  delete(bits->bits);
  free(bits);
}

extern "C" VALUE ewah_new(VALUE klass) {
  EWAH *b = ALLOC(EWAH);
  b->bits = new EWAHBoolArray<uword64>();
  VALUE bitset = Data_Wrap_Struct(klass, 0, ewah_free, b);
  rb_obj_call_init(bitset, 0, 0);
  return bitset;
}

extern "C" VALUE ewah_init(VALUE self) {
  return self;
}

/* Core API */
extern "C" VALUE ewah_set(VALUE self, VALUE position) {
  if (position == Qnil) {
    rb_raise(rb_eRuntimeError, "Position to set not specified");
  }

  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);
  bitset->bits->set(FIX2INT(position));

  return self;
}

extern "C" VALUE ewah_each(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);

  for(EWAHBoolArray<uword64>::const_iterator i = bitset->bits->begin(); i != bitset->bits->end(); ++i)
    rb_yield(INT2FIX(*i));

  return Qnil;
}

extern "C" VALUE ewah_each_word(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);

  EWAHBoolArrayIterator<uword64> i = bitset->bits->uncompress();

  while(i.hasNext()) {
    rb_yield(INT2FIX(i.next()));
  }

  return Qnil;
}

extern "C" VALUE ewah_each_word_sparse(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);

  EWAHBoolArraySparseIterator<uword64> i = bitset->bits->sparse_uncompress();

  while(i.hasNext()) {
    rb_yield(INT2FIX(i.next()));
  }

  return Qnil;
}

extern "C" VALUE ewah_swap(VALUE self, VALUE other) {
  EWAH *bitset;
  EWAH *obitset;
  Data_Get_Struct(self, EWAH, bitset);
  Data_Get_Struct(other, EWAH, obitset);

  bitset->bits->swap(*(obitset->bits));

  return self;
}

extern "C" VALUE ewah_reset(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);
  bitset->bits->reset();
  return self;
}

/* Set Operations */
extern "C" VALUE ewah_logical_or(VALUE self, VALUE other) {
  EWAH *bitset;
  EWAH *obitset;
  Data_Get_Struct(self, EWAH, bitset);
  Data_Get_Struct(other, EWAH, obitset);

  VALUE newBitset = ewah_new(rb_path2class("EwahBitset"));

  EWAH *newBits;
  Data_Get_Struct(newBitset, EWAH, newBits);
  bitset->bits->logicalor(*(obitset->bits), *(newBits->bits));

  return newBitset;
}

extern "C" VALUE ewah_logical_and(VALUE self, VALUE other) {
  EWAH *bitset;
  EWAH *obitset;
  Data_Get_Struct(self, EWAH, bitset);
  Data_Get_Struct(other, EWAH, obitset);

  VALUE newBitset = ewah_new(rb_path2class("EwahBitset"));

  EWAH *newBits;
  Data_Get_Struct(newBitset, EWAH, newBits);
  bitset->bits->logicaland(*(obitset->bits), *(newBits->bits));

  return newBitset;
}

extern "C" VALUE ewah_logical_not(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);

  VALUE newBitset = ewah_new(rb_path2class("EwahBitset"));

  EWAH *newBits;
  Data_Get_Struct(newBitset, EWAH, newBits);
  bitset->bits->logicalnot(*(newBits->bits));

  return newBitset;
}

extern "C" VALUE ewah_eq(VALUE self, VALUE other) {
  EWAH *bitset;
  EWAH *obitset;
  Data_Get_Struct(self, EWAH, bitset);
  Data_Get_Struct(other, EWAH, obitset);

  if(*(bitset->bits) == *(obitset->bits)) {
    return Qtrue;
  } else {
    return Qfalse;
  }
}

extern "C" VALUE ewah_neq(VALUE self, VALUE other) {
  EWAH *bitset;
  EWAH *obitset;
  Data_Get_Struct(self, EWAH, bitset);
  Data_Get_Struct(other, EWAH, obitset);

  if(*(bitset->bits) != *(obitset->bits)) {
    return Qtrue;
  } else {
    return Qfalse;
  }
}

/* Information & Serialization */
extern "C" VALUE ewah_size_in_bits(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);
  return INT2FIX(bitset->bits->sizeInBits());
}

extern "C" VALUE ewah_size_in_bytes(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);
  return INT2FIX(bitset->bits->sizeInBytes());
}

extern "C" VALUE ewah_to_binary_s(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);

  stringstream ss;
  bitset->bits->printout(ss);

  return rb_str_new(ss.str().c_str(), ss.str().size());
}

extern "C" VALUE ewah_serialize(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);

  stringstream ss;
  bitset->bits->write(ss);

  return rb_str_new(ss.str().c_str(), ss.str().size());
}

extern "C" VALUE ewah_deserialize(VALUE self, VALUE bytes) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);

  stringstream ss;
  ss.write(RSTRING_PTR(bytes), RSTRING_LEN(bytes));
  bitset->bits->read(ss, true);

  return self;
}

static VALUE rb_cC;
extern "C" void Init_ewahbitset() {
  rb_cC = rb_define_class("EwahBitset", rb_cObject);
  rb_define_singleton_method(rb_cC, "new", (ruby_method*) &ewah_new, 0);
  rb_define_method(rb_cC, "initialize", (ruby_method*) &ewah_init, 0);

  rb_define_method(rb_cC, "set", (ruby_method*) &ewah_set, 1);
  rb_define_method(rb_cC, "each", (ruby_method*) &ewah_each, 0);
  rb_define_method(rb_cC, "swap", (ruby_method*) &ewah_swap, 1);
  rb_define_method(rb_cC, "reset", (ruby_method*) &ewah_reset, 0);

  rb_define_method(rb_cC, "each_word64", (ruby_method*) &ewah_each_word, 0);
  rb_define_method(rb_cC, "each_word64_sparse", (ruby_method*) &ewah_each_word_sparse, 0);

  rb_define_method(rb_cC, "==", (ruby_method*) &ewah_eq, 1);
  rb_define_method(rb_cC, "!=", (ruby_method*) &ewah_neq, 1);

  rb_define_method(rb_cC, "logical_or", (ruby_method*) &ewah_logical_or, 1);
  rb_define_method(rb_cC, "logical_and", (ruby_method*) &ewah_logical_and, 1);
  rb_define_method(rb_cC, "logical_not", (ruby_method*) &ewah_logical_not, 1);

  rb_define_method(rb_cC, "to_binary_s", (ruby_method*) &ewah_to_binary_s, 0);
  rb_define_method(rb_cC, "serialize", (ruby_method*) &ewah_serialize, 0);
  rb_define_method(rb_cC, "deserialize", (ruby_method*) &ewah_deserialize, 1);
  rb_define_method(rb_cC, "size_in_bits", (ruby_method*) ewah_size_in_bits, 0);
  rb_define_method(rb_cC, "size_in_bytes", (ruby_method*) ewah_size_in_bytes, 0);
}<commit_msg>add to_s<commit_after>#include <ruby.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "ewah.h"

typedef VALUE (ruby_method)(...);

typedef struct ewah {
  EWAHBoolArray<uword64> *bits;
} EWAH;

extern "C" void ewah_free(EWAH *bits) {
  delete(bits->bits);
  free(bits);
}

extern "C" VALUE ewah_new(VALUE klass) {
  EWAH *b = ALLOC(EWAH);
  b->bits = new EWAHBoolArray<uword64>();
  VALUE bitset = Data_Wrap_Struct(klass, 0, ewah_free, b);
  rb_obj_call_init(bitset, 0, 0);
  return bitset;
}

extern "C" VALUE ewah_init(VALUE self) {
  return self;
}

/* Core API */
extern "C" VALUE ewah_set(VALUE self, VALUE position) {
  if (position == Qnil) {
    rb_raise(rb_eRuntimeError, "Position to set not specified");
  }

  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);
  bitset->bits->set(FIX2INT(position));

  return self;
}

extern "C" VALUE ewah_each(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);

  for(EWAHBoolArray<uword64>::const_iterator i = bitset->bits->begin(); i != bitset->bits->end(); ++i)
    rb_yield(INT2FIX(*i));

  return Qnil;
}

extern "C" VALUE ewah_each_word(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);

  EWAHBoolArrayIterator<uword64> i = bitset->bits->uncompress();

  while(i.hasNext()) {
    rb_yield(INT2FIX(i.next()));
  }

  return Qnil;
}

extern "C" VALUE ewah_each_word_sparse(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);

  EWAHBoolArraySparseIterator<uword64> i = bitset->bits->sparse_uncompress();

  while(i.hasNext()) {
    rb_yield(INT2FIX(i.next()));
  }

  return Qnil;
}

extern "C" VALUE ewah_swap(VALUE self, VALUE other) {
  EWAH *bitset;
  EWAH *obitset;
  Data_Get_Struct(self, EWAH, bitset);
  Data_Get_Struct(other, EWAH, obitset);

  bitset->bits->swap(*(obitset->bits));

  return self;
}

extern "C" VALUE ewah_reset(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);
  bitset->bits->reset();
  return self;
}

/* Set Operations */
extern "C" VALUE ewah_logical_or(VALUE self, VALUE other) {
  EWAH *bitset;
  EWAH *obitset;
  Data_Get_Struct(self, EWAH, bitset);
  Data_Get_Struct(other, EWAH, obitset);

  VALUE newBitset = ewah_new(rb_path2class("EwahBitset"));

  EWAH *newBits;
  Data_Get_Struct(newBitset, EWAH, newBits);
  bitset->bits->logicalor(*(obitset->bits), *(newBits->bits));

  return newBitset;
}

extern "C" VALUE ewah_logical_and(VALUE self, VALUE other) {
  EWAH *bitset;
  EWAH *obitset;
  Data_Get_Struct(self, EWAH, bitset);
  Data_Get_Struct(other, EWAH, obitset);

  VALUE newBitset = ewah_new(rb_path2class("EwahBitset"));

  EWAH *newBits;
  Data_Get_Struct(newBitset, EWAH, newBits);
  bitset->bits->logicaland(*(obitset->bits), *(newBits->bits));

  return newBitset;
}

extern "C" VALUE ewah_logical_not(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);

  VALUE newBitset = ewah_new(rb_path2class("EwahBitset"));

  EWAH *newBits;
  Data_Get_Struct(newBitset, EWAH, newBits);
  bitset->bits->logicalnot(*(newBits->bits));

  return newBitset;
}

extern "C" VALUE ewah_eq(VALUE self, VALUE other) {
  EWAH *bitset;
  EWAH *obitset;
  Data_Get_Struct(self, EWAH, bitset);
  Data_Get_Struct(other, EWAH, obitset);

  if(*(bitset->bits) == *(obitset->bits)) {
    return Qtrue;
  } else {
    return Qfalse;
  }
}

extern "C" VALUE ewah_neq(VALUE self, VALUE other) {
  EWAH *bitset;
  EWAH *obitset;
  Data_Get_Struct(self, EWAH, bitset);
  Data_Get_Struct(other, EWAH, obitset);

  if(*(bitset->bits) != *(obitset->bits)) {
    return Qtrue;
  } else {
    return Qfalse;
  }
}

/* Information & Serialization */
extern "C" VALUE ewah_size_in_bits(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);
  return INT2FIX(bitset->bits->sizeInBits());
}

extern "C" VALUE ewah_size_in_bytes(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);
  return INT2FIX(bitset->bits->sizeInBytes());
}

extern "C" VALUE ewah_to_binary_s(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);

  stringstream ss;
  bitset->bits->printout(ss);

  return rb_str_new(ss.str().c_str(), ss.str().size());
}

extern "C" VALUE ewah_serialize(VALUE self) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);

  stringstream ss;
  bitset->bits->write(ss);

  return rb_str_new(ss.str().c_str(), ss.str().size());
}

extern "C" VALUE ewah_deserialize(VALUE self, VALUE bytes) {
  EWAH *bitset;
  Data_Get_Struct(self, EWAH, bitset);

  stringstream ss;
  ss.write(RSTRING_PTR(bytes), RSTRING_LEN(bytes));
  bitset->bits->read(ss, true);

  return self;
}

static VALUE rb_cC;
extern "C" void Init_ewahbitset() {
  rb_cC = rb_define_class("EwahBitset", rb_cObject);
  rb_define_singleton_method(rb_cC, "new", (ruby_method*) &ewah_new, 0);
  rb_define_method(rb_cC, "initialize", (ruby_method*) &ewah_init, 0);

  rb_define_method(rb_cC, "set", (ruby_method*) &ewah_set, 1);
  rb_define_method(rb_cC, "each", (ruby_method*) &ewah_each, 0);
  rb_define_method(rb_cC, "swap", (ruby_method*) &ewah_swap, 1);
  rb_define_method(rb_cC, "reset", (ruby_method*) &ewah_reset, 0);

  rb_define_method(rb_cC, "each_word64", (ruby_method*) &ewah_each_word, 0);
  rb_define_method(rb_cC, "each_word64_sparse", (ruby_method*) &ewah_each_word_sparse, 0);

  rb_define_method(rb_cC, "==", (ruby_method*) &ewah_eq, 1);
  rb_define_method(rb_cC, "!=", (ruby_method*) &ewah_neq, 1);

  rb_define_method(rb_cC, "logical_or", (ruby_method*) &ewah_logical_or, 1);
  rb_define_method(rb_cC, "logical_and", (ruby_method*) &ewah_logical_and, 1);
  rb_define_method(rb_cC, "logical_not", (ruby_method*) &ewah_logical_not, 1);

  rb_define_method(rb_cC, "to_s", (ruby_method*) &ewah_to_binary_s, 0);
  rb_define_method(rb_cC, "to_binary_s", (ruby_method*) &ewah_to_binary_s, 0);
  rb_define_method(rb_cC, "serialize", (ruby_method*) &ewah_serialize, 0);
  rb_define_method(rb_cC, "deserialize", (ruby_method*) &ewah_deserialize, 1);
  rb_define_method(rb_cC, "size_in_bits", (ruby_method*) ewah_size_in_bits, 0);
  rb_define_method(rb_cC, "size_in_bytes", (ruby_method*) ewah_size_in_bytes, 0);
}<|endoftext|>


<commit_before>/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "gm.h"
#include "Resources.h"
#include "SkCanvas.h"
#include "SkStream.h"
#include "SkSurface.h"
#include "SkTypeface.h"

class DFTextGM : public skiagm::GM {
public:
    DFTextGM() {
        this->setBGColor(0xFFFFFFFF);
    }

protected:
    void onOnceBeforeDraw() override {
        sk_tool_utils::emoji_typeface(&fEmojiTypeface);
        fEmojiText = sk_tool_utils::emoji_sample_text();
    }

    SkString onShortName() override {
        SkString name("dftext");
        name.append(sk_tool_utils::platform_os_emoji());
        return name;
    }

    SkISize onISize() override {
        return SkISize::Make(1024, 768);
    }

    static void rotate_about(SkCanvas* canvas,
        SkScalar degrees,
        SkScalar px, SkScalar py) {
        canvas->translate(px, py);
        canvas->rotate(degrees);
        canvas->translate(-px, -py);
    }

    virtual void onDraw(SkCanvas* inputCanvas) override {
#ifdef SK_BUILD_FOR_ANDROID
        SkScalar textSizes[] = { 9.0f, 9.0f*2.0f, 9.0f*5.0f, 9.0f*2.0f*5.0f };
#else
        SkScalar textSizes[] = { 11.0f, 11.0f*2.0f, 11.0f*5.0f, 11.0f*2.0f*5.0f };
#endif
        SkScalar scales[] = { 2.0f*5.0f, 5.0f, 2.0f, 1.0f };

        // set up offscreen rendering with distance field text
#if SK_SUPPORT_GPU
        GrContext* ctx = inputCanvas->getGrContext();
        SkImageInfo info = SkImageInfo::MakeN32Premul(onISize());
        SkSurfaceProps props(SkSurfaceProps::kUseDistanceFieldFonts_Flag,
                             SkSurfaceProps::kLegacyFontHost_InitType);
        SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTarget(ctx, SkSurface::kNo_Budgeted,
                                                                   info, 0, &props));
        SkCanvas* canvas = surface.get() ? surface->getCanvas() : inputCanvas;
        // init our new canvas with the old canvas's matrix
        canvas->setMatrix(inputCanvas->getTotalMatrix());
#else
        SkCanvas* canvas = inputCanvas;
#endif
        // apply global scale to test glyph positioning
        canvas->scale(1.05f, 1.05f);
        canvas->clear(0xffffffff);

        SkPaint paint;
        paint.setAntiAlias(true);
        paint.setSubpixelText(true);

        sk_tool_utils::set_portable_typeface_always(&paint, "serif", SkTypeface::kNormal);

        const char* text = "Hamburgefons";
        const size_t textLen = strlen(text);

        // check scaling up
        SkScalar x = SkIntToScalar(0);
        SkScalar y = SkIntToScalar(78);
        for (size_t i = 0; i < SK_ARRAY_COUNT(textSizes); ++i) {
            SkAutoCanvasRestore acr(canvas, true);
            canvas->translate(x, y);
            canvas->scale(scales[i], scales[i]);
            paint.setTextSize(textSizes[i]);
            canvas->drawText(text, textLen, 0, 0, paint);
            y += paint.getFontMetrics(NULL)*scales[i];
        }

        // check rotation
        for (size_t i = 0; i < 5; ++i) {
            SkScalar rotX = SkIntToScalar(10);
            SkScalar rotY = y;

            SkAutoCanvasRestore acr(canvas, true);
            canvas->translate(SkIntToScalar(10 + i * 200), -80);
            rotate_about(canvas, SkIntToScalar(i * 5), rotX, rotY);
            for (int ps = 6; ps <= 32; ps += 3) {
                paint.setTextSize(SkIntToScalar(ps));
                canvas->drawText(text, textLen, rotX, rotY, paint);
                rotY += paint.getFontMetrics(NULL);
            }
        }

        // check scaling down
        paint.setLCDRenderText(true);
        x = SkIntToScalar(680);
        y = SkIntToScalar(20);
        size_t arraySize = SK_ARRAY_COUNT(textSizes);
        for (size_t i = 0; i < arraySize; ++i) {
            SkAutoCanvasRestore acr(canvas, true);
            canvas->translate(x, y);
            SkScalar scaleFactor = SkScalarInvert(scales[arraySize - i - 1]);
            canvas->scale(scaleFactor, scaleFactor);
            paint.setTextSize(textSizes[i]);
            canvas->drawText(text, textLen, 0, 0, paint);
            y += paint.getFontMetrics(NULL)*scaleFactor;
        }

        // check pos text
        {
            SkAutoCanvasRestore acr(canvas, true);

            canvas->scale(2.0f, 2.0f);

            SkAutoTArray<SkPoint>  pos(SkToInt(textLen));
            SkAutoTArray<SkScalar> widths(SkToInt(textLen));
            paint.setTextSize(textSizes[0]);

            paint.getTextWidths(text, textLen, &widths[0]);

            SkScalar x = SkIntToScalar(340);
            SkScalar y = SkIntToScalar(75);
            for (unsigned int i = 0; i < textLen; ++i) {
                pos[i].set(x, y);
                x += widths[i];
            }

            canvas->drawPosText(text, textLen, &pos[0], paint);
        }

        // check gamma-corrected blending
        const SkColor fg[] = {
            0xFFFFFFFF,
            0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF,
            0xFFFF0000, 0xFF00FF00, 0xFF0000FF,
            0xFF000000,
        };

        paint.setColor(0xFFF7F3F7);
        SkRect r = SkRect::MakeLTRB(670, 250, 820, 460);
        canvas->drawRect(r, paint);

        x = SkIntToScalar(680);
        y = SkIntToScalar(270);
#ifdef SK_BUILD_FOR_ANDROID
        paint.setTextSize(SkIntToScalar(19));
#else
        paint.setTextSize(SkIntToScalar(22));
#endif
        for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {
            paint.setColor(fg[i]);

            canvas->drawText(text, textLen, x, y, paint);
            y += paint.getFontMetrics(NULL);
        }

        paint.setColor(0xFF181C18);
        r = SkRect::MakeLTRB(820, 250, 970, 460);
        canvas->drawRect(r, paint);

        x = SkIntToScalar(830);
        y = SkIntToScalar(270);
#ifdef SK_BUILD_FOR_ANDROID
        paint.setTextSize(SkIntToScalar(19));
#else
        paint.setTextSize(SkIntToScalar(22));
#endif
        for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {
            paint.setColor(fg[i]);

            canvas->drawText(text, textLen, x, y, paint);
            y += paint.getFontMetrics(NULL);
        }

        // check skew
        {
            paint.setLCDRenderText(false);
            SkAutoCanvasRestore acr(canvas, true);
            canvas->skew(0.0f, 0.151515f);
            paint.setTextSize(SkIntToScalar(32));
            canvas->drawText(text, textLen, 745, 70, paint);
        }
        {
            paint.setLCDRenderText(true);
            SkAutoCanvasRestore acr(canvas, true);
            canvas->skew(0.5f, 0.0f);
            paint.setTextSize(SkIntToScalar(32));
            canvas->drawText(text, textLen, 580, 230, paint);
        }

        // check color emoji
        if (fEmojiTypeface) {
            paint.setTypeface(fEmojiTypeface);
            paint.setTextSize(SkIntToScalar(19));
            canvas->drawText(fEmojiText, strlen(fEmojiText), 670, 100, paint);
        }
#if SK_SUPPORT_GPU
        // render offscreen buffer
        if (surface) {
            SkAutoCanvasRestore acr(inputCanvas, true);
            // since we prepended this matrix already, we blit using identity
            inputCanvas->resetMatrix();
            SkImage* image = surface->newImageSnapshot();
            inputCanvas->drawImage(image, 0, 0, NULL);
            image->unref();
        }
#endif
    }

private:
    SkAutoTUnref<SkTypeface> fEmojiTypeface;
    const char* fEmojiText;

    typedef skiagm::GM INHERITED;
};

DEF_GM( return SkNEW(DFTextGM); )
<commit_msg>make dftext the same on Linux and Android<commit_after>/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "gm.h"
#include "Resources.h"
#include "SkCanvas.h"
#include "SkStream.h"
#include "SkSurface.h"
#include "SkTypeface.h"

class DFTextGM : public skiagm::GM {
public:
    DFTextGM() {
        this->setBGColor(0xFFFFFFFF);
    }

protected:
    void onOnceBeforeDraw() override {
        sk_tool_utils::emoji_typeface(&fEmojiTypeface);
        fEmojiText = sk_tool_utils::emoji_sample_text();
    }

    SkString onShortName() override {
        SkString name("dftext");
        name.append(sk_tool_utils::platform_os_emoji());
        return name;
    }

    SkISize onISize() override {
        return SkISize::Make(1024, 768);
    }

    static void rotate_about(SkCanvas* canvas,
        SkScalar degrees,
        SkScalar px, SkScalar py) {
        canvas->translate(px, py);
        canvas->rotate(degrees);
        canvas->translate(-px, -py);
    }

    virtual void onDraw(SkCanvas* inputCanvas) override {
        SkScalar textSizes[] = { 9.0f, 9.0f*2.0f, 9.0f*5.0f, 9.0f*2.0f*5.0f };
        SkScalar scales[] = { 2.0f*5.0f, 5.0f, 2.0f, 1.0f };

        // set up offscreen rendering with distance field text
#if SK_SUPPORT_GPU
        GrContext* ctx = inputCanvas->getGrContext();
        SkImageInfo info = SkImageInfo::MakeN32Premul(onISize());
        SkSurfaceProps props(SkSurfaceProps::kUseDistanceFieldFonts_Flag,
                             SkSurfaceProps::kLegacyFontHost_InitType);
        SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTarget(ctx, SkSurface::kNo_Budgeted,
                                                                   info, 0, &props));
        SkCanvas* canvas = surface.get() ? surface->getCanvas() : inputCanvas;
        // init our new canvas with the old canvas's matrix
        canvas->setMatrix(inputCanvas->getTotalMatrix());
#else
        SkCanvas* canvas = inputCanvas;
#endif
        // apply global scale to test glyph positioning
        canvas->scale(1.05f, 1.05f);
        canvas->clear(0xffffffff);

        SkPaint paint;
        paint.setAntiAlias(true);
        paint.setSubpixelText(true);

        sk_tool_utils::set_portable_typeface_always(&paint, "serif", SkTypeface::kNormal);

        const char* text = "Hamburgefons";
        const size_t textLen = strlen(text);

        // check scaling up
        SkScalar x = SkIntToScalar(0);
        SkScalar y = SkIntToScalar(78);
        for (size_t i = 0; i < SK_ARRAY_COUNT(textSizes); ++i) {
            SkAutoCanvasRestore acr(canvas, true);
            canvas->translate(x, y);
            canvas->scale(scales[i], scales[i]);
            paint.setTextSize(textSizes[i]);
            canvas->drawText(text, textLen, 0, 0, paint);
            y += paint.getFontMetrics(NULL)*scales[i];
        }

        // check rotation
        for (size_t i = 0; i < 5; ++i) {
            SkScalar rotX = SkIntToScalar(10);
            SkScalar rotY = y;

            SkAutoCanvasRestore acr(canvas, true);
            canvas->translate(SkIntToScalar(10 + i * 200), -80);
            rotate_about(canvas, SkIntToScalar(i * 5), rotX, rotY);
            for (int ps = 6; ps <= 32; ps += 3) {
                paint.setTextSize(SkIntToScalar(ps));
                canvas->drawText(text, textLen, rotX, rotY, paint);
                rotY += paint.getFontMetrics(NULL);
            }
        }

        // check scaling down
        paint.setLCDRenderText(true);
        x = SkIntToScalar(680);
        y = SkIntToScalar(20);
        size_t arraySize = SK_ARRAY_COUNT(textSizes);
        for (size_t i = 0; i < arraySize; ++i) {
            SkAutoCanvasRestore acr(canvas, true);
            canvas->translate(x, y);
            SkScalar scaleFactor = SkScalarInvert(scales[arraySize - i - 1]);
            canvas->scale(scaleFactor, scaleFactor);
            paint.setTextSize(textSizes[i]);
            canvas->drawText(text, textLen, 0, 0, paint);
            y += paint.getFontMetrics(NULL)*scaleFactor;
        }

        // check pos text
        {
            SkAutoCanvasRestore acr(canvas, true);

            canvas->scale(2.0f, 2.0f);

            SkAutoTArray<SkPoint>  pos(SkToInt(textLen));
            SkAutoTArray<SkScalar> widths(SkToInt(textLen));
            paint.setTextSize(textSizes[0]);

            paint.getTextWidths(text, textLen, &widths[0]);

            SkScalar x = SkIntToScalar(340);
            SkScalar y = SkIntToScalar(75);
            for (unsigned int i = 0; i < textLen; ++i) {
                pos[i].set(x, y);
                x += widths[i];
            }

            canvas->drawPosText(text, textLen, &pos[0], paint);
        }

        // check gamma-corrected blending
        const SkColor fg[] = {
            0xFFFFFFFF,
            0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF,
            0xFFFF0000, 0xFF00FF00, 0xFF0000FF,
            0xFF000000,
        };

        paint.setColor(0xFFF7F3F7);
        SkRect r = SkRect::MakeLTRB(670, 250, 820, 460);
        canvas->drawRect(r, paint);

        x = SkIntToScalar(680);
        y = SkIntToScalar(270);
        paint.setTextSize(SkIntToScalar(19));
        for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {
            paint.setColor(fg[i]);

            canvas->drawText(text, textLen, x, y, paint);
            y += paint.getFontMetrics(NULL);
        }

        paint.setColor(0xFF181C18);
        r = SkRect::MakeLTRB(820, 250, 970, 460);
        canvas->drawRect(r, paint);

        x = SkIntToScalar(830);
        y = SkIntToScalar(270);
        paint.setTextSize(SkIntToScalar(19));
        for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {
            paint.setColor(fg[i]);

            canvas->drawText(text, textLen, x, y, paint);
            y += paint.getFontMetrics(NULL);
        }

        // check skew
        {
            paint.setLCDRenderText(false);
            SkAutoCanvasRestore acr(canvas, true);
            canvas->skew(0.0f, 0.151515f);
            paint.setTextSize(SkIntToScalar(32));
            canvas->drawText(text, textLen, 745, 70, paint);
        }
        {
            paint.setLCDRenderText(true);
            SkAutoCanvasRestore acr(canvas, true);
            canvas->skew(0.5f, 0.0f);
            paint.setTextSize(SkIntToScalar(32));
            canvas->drawText(text, textLen, 580, 230, paint);
        }

        // check color emoji
        if (fEmojiTypeface) {
            paint.setTypeface(fEmojiTypeface);
            paint.setTextSize(SkIntToScalar(19));
            canvas->drawText(fEmojiText, strlen(fEmojiText), 670, 100, paint);
        }
#if SK_SUPPORT_GPU
        // render offscreen buffer
        if (surface) {
            SkAutoCanvasRestore acr(inputCanvas, true);
            // since we prepended this matrix already, we blit using identity
            inputCanvas->resetMatrix();
            SkImage* image = surface->newImageSnapshot();
            inputCanvas->drawImage(image, 0, 0, NULL);
            image->unref();
        }
#endif
    }

private:
    SkAutoTUnref<SkTypeface> fEmojiTypeface;
    const char* fEmojiText;

    typedef skiagm::GM INHERITED;
};

DEF_GM( return SkNEW(DFTextGM); )
<|endoftext|>


<commit_before>// ---------------------------------------------------------------------
//
// Copyright (C) 1998 - 2016 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------

#include "../tests.h"
#include "../testmatrix.h"
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/vector.h>
#include <deal.II/lac/vector_memory.h>
#include <deal.II/lac/solver_control.h>
#include <deal.II/lac/eigen.h>
#include <deal.II/lac/precondition.h>

int main()
{
  std::ofstream logfile("output");
//  logfile.setf(std::ios::fixed);
  deallog << std::setprecision(4);
  deallog.attach(logfile);

  GrowingVectorMemory<> mem;
  SolverControl control(1000, 1.e-5);

  const unsigned int size = 10;
  const unsigned int dim = (size-1)*(size-1);

  /*
   * Compute minimal and maximal
   * eigenvalues of the 5-point
   * stencil matrix
   * (Hackbusch:Iterative Lsung...,
   * Satz 4.1.1)
   */
  const double h = 1./size;
  const double s = std::sin(numbers::PI*h/2.);
  const double c = std::cos(numbers::PI*h/2.);
  const double lambda_max = 8.*c*c;
  const double lambda_min = 8.*s*s;

  FDMatrix testproblem(size, size);
  SparsityPattern structure(dim, dim, 5);
  testproblem.five_point_structure(structure);
  structure.compress();
  SparseMatrix<double>  A(structure);
  testproblem.five_point(A);

  Vector<double> u(dim);
  u = 1.;
  double lambda;

  EigenPower<> mises(control, mem);
  mises.solve(lambda, A, u);
  deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl;

  double lambda2;
  u = 1.;

  EigenPower<> mises2(control, mem, -1.5*lambda);
  mises2.solve(lambda2, A, u);
  deallog << "Eigenvalue " << lambda2 << " Error " << lambda2-lambda_min << std::endl;

  u = 1.;
  lambda = 0.;
  EigenInverse<> wieland(control, mem);
  wieland.solve(lambda, A, u);
  deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_min << std::endl;

  u = 1.;
  lambda = 10.;
  wieland.solve(lambda, A, u);
  deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl;

  u = 1.;
  lambda = 10.;
  EigenInverse<> wieland2(control, mem, .2);
  wieland2.solve(lambda, A, u);
  deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl;
}
<commit_msg>fix illegal character (<F6> instead of oe)<commit_after>// ---------------------------------------------------------------------
//
// Copyright (C) 1998 - 2016 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------

#include "../tests.h"
#include "../testmatrix.h"
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/vector.h>
#include <deal.II/lac/vector_memory.h>
#include <deal.II/lac/solver_control.h>
#include <deal.II/lac/eigen.h>
#include <deal.II/lac/precondition.h>

int main()
{
  std::ofstream logfile("output");
//  logfile.setf(std::ios::fixed);
  deallog << std::setprecision(4);
  deallog.attach(logfile);

  GrowingVectorMemory<> mem;
  SolverControl control(1000, 1.e-5);

  const unsigned int size = 10;
  const unsigned int dim = (size-1)*(size-1);

  /*
   * Compute minimal and maximal
   * eigenvalues of the 5-point
   * stencil matrix
   * (Hackbusch:Iterative Loesung...,
   * Satz 4.1.1)
   */
  const double h = 1./size;
  const double s = std::sin(numbers::PI*h/2.);
  const double c = std::cos(numbers::PI*h/2.);
  const double lambda_max = 8.*c*c;
  const double lambda_min = 8.*s*s;

  FDMatrix testproblem(size, size);
  SparsityPattern structure(dim, dim, 5);
  testproblem.five_point_structure(structure);
  structure.compress();
  SparseMatrix<double>  A(structure);
  testproblem.five_point(A);

  Vector<double> u(dim);
  u = 1.;
  double lambda;

  EigenPower<> mises(control, mem);
  mises.solve(lambda, A, u);
  deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl;

  double lambda2;
  u = 1.;

  EigenPower<> mises2(control, mem, -1.5*lambda);
  mises2.solve(lambda2, A, u);
  deallog << "Eigenvalue " << lambda2 << " Error " << lambda2-lambda_min << std::endl;

  u = 1.;
  lambda = 0.;
  EigenInverse<> wieland(control, mem);
  wieland.solve(lambda, A, u);
  deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_min << std::endl;

  u = 1.;
  lambda = 10.;
  wieland.solve(lambda, A, u);
  deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl;

  u = 1.;
  lambda = 10.;
  EigenInverse<> wieland2(control, mem, .2);
  wieland2.solve(lambda, A, u);
  deallog << "Eigenvalue " << lambda << " Error " << lambda-lambda_max << std::endl;
}
<|endoftext|>


<commit_before>#include <boost/make_shared.hpp>
#include <gtest/gtest.h>
#include <yamail/resource_pool.hpp>

namespace {

using namespace testing;
using namespace yamail::resource_pool;
using namespace yamail::resource_pool::sync;

using boost::make_shared;

struct resource {};

typedef boost::shared_ptr<resource> resource_ptr;
typedef pool<resource_ptr> resource_pool;
typedef resource_pool::handle_ptr resource_handle_ptr;

const boost::function<resource_ptr ()> make_resource = make_shared<resource>;

class my_resource_handle : public handle_facade<resource_pool> {
public:
    my_resource_handle(const resource_handle_ptr& handle)
            : handle_facade<resource_pool>(handle) {}
};

struct sync_resource_pool : Test {};

TEST(sync_resource_pool, dummy_create) {
    resource_pool pool;
}

TEST(sync_resource_pool, dummy_create_not_empty) {
    resource_pool pool(42);
}

TEST(sync_resource_pool, dummy_create_not_empty_with_factory) {
    resource_pool pool(42, make_resource);
}

TEST(sync_resource_pool, check_metrics_for_empty) {
    resource_pool pool;
    EXPECT_EQ(pool.capacity(), 0);
    EXPECT_EQ(pool.size(), 0);
    EXPECT_EQ(pool.used(), 0);
    EXPECT_EQ(pool.available(), 0);
}

TEST(sync_resource_pool, check_capacity) {
    const std::size_t capacity = 42;
    resource_pool pool(capacity);
    EXPECT_EQ(pool.capacity(), capacity);
}

TEST(sync_resource_pool, dummy_get_auto_recylce_handle) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_recycle();
}

TEST(sync_resource_pool, dummy_get_auto_waste_handle) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_waste();
}

TEST(sync_resource_pool, check_metrics_for_not_empty) {
    const std::size_t capacity = 42;
    resource_pool pool(capacity, make_resource);
    EXPECT_EQ(pool.size(), 0);
    EXPECT_EQ(pool.used(), 0);
    EXPECT_EQ(pool.available(), 0);
    {
        resource_handle_ptr handle = pool.get_auto_recycle();
        EXPECT_EQ(pool.size(), 1);
        EXPECT_EQ(pool.used(), 1);
        EXPECT_EQ(pool.available(), 0);
    }
    EXPECT_EQ(pool.size(), 1);
    EXPECT_EQ(pool.used(), 0);
    EXPECT_EQ(pool.available(), 1);
    {
        resource_handle_ptr handle1 = pool.get_auto_recycle();
        resource_handle_ptr handle2 = pool.get_auto_recycle();
        EXPECT_EQ(pool.size(), 2);
        EXPECT_EQ(pool.used(), 2);
        EXPECT_EQ(pool.available(), 0);
    }
    EXPECT_EQ(pool.size(), 2);
    EXPECT_EQ(pool.used(), 0);
    EXPECT_EQ(pool.available(), 2);
    {
        resource_handle_ptr handle = pool.get_auto_waste();
        EXPECT_EQ(pool.size(), 2);
        EXPECT_EQ(pool.used(), 1);
        EXPECT_EQ(pool.available(), 1);
    }
    EXPECT_EQ(pool.size(), 1);
    EXPECT_EQ(pool.used(), 0);
    EXPECT_EQ(pool.available(), 1);
}

TEST(sync_resource_pool, get_auto_recylce_handle_and_recycle) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_recycle();
    handle->recycle();
}

TEST(sync_resource_pool, get_auto_recylce_handle_and_waste) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_recycle();
    handle->waste();
}

TEST(sync_resource_pool, get_auto_waste_handle_and_recycle) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_waste();
    handle->recycle();
}

TEST(sync_resource_pool, get_auto_waste_handle_and_waste) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_waste();
    handle->waste();
}

TEST(sync_resource_pool, get_auto_recycle_handle_check_empty) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_recycle();
    EXPECT_FALSE(handle->empty());
    handle->recycle();
    EXPECT_TRUE(handle->empty());
}

TEST(sync_resource_pool, get_auto_recycle_handle_and_get_recycled_expect_exception) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_recycle();
    handle->recycle();
    EXPECT_THROW(handle->get(), error::empty_handle);
}

TEST(sync_resource_pool, get_auto_recycle_handle_and_recycle_recycled_expect_exception) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_recycle();
    handle->recycle();
    EXPECT_THROW(handle->recycle(), error::empty_handle);
}

TEST(sync_resource_pool, get_auto_recycle_handle_from_empty_pool_returns_empty_handle) {
    resource_pool pool(0, make_resource);
    resource_handle_ptr handle = pool.get_auto_recycle();
    EXPECT_EQ(handle->error(), error::get_resource_timeout);
}

TEST(sync_resource_pool, dummy_create_my_resoure_handle) {
    resource_pool pool(1, make_resource);
    my_resource_handle handle(pool.get_auto_recycle());
}

TEST(sync_resource_pool, check_pool_lifetime) {
    resource_handle_ptr handle;
    {
        resource_pool pool(1, make_resource);
        handle = pool.get_auto_recycle();
    }
}

}
<commit_msg>Fix warnings<commit_after>#include <boost/make_shared.hpp>
#include <gtest/gtest.h>
#include <yamail/resource_pool.hpp>

namespace {

using namespace testing;
using namespace yamail::resource_pool;
using namespace yamail::resource_pool::sync;

using boost::make_shared;

struct resource {};

typedef boost::shared_ptr<resource> resource_ptr;
typedef pool<resource_ptr> resource_pool;
typedef resource_pool::handle_ptr resource_handle_ptr;

const boost::function<resource_ptr ()> make_resource = make_shared<resource>;

class my_resource_handle : public handle_facade<resource_pool> {
public:
    my_resource_handle(const resource_handle_ptr& handle)
            : handle_facade<resource_pool>(handle) {}
};

struct sync_resource_pool : Test {};

TEST(sync_resource_pool, dummy_create) {
    resource_pool pool;
}

TEST(sync_resource_pool, dummy_create_not_empty) {
    resource_pool pool(42);
}

TEST(sync_resource_pool, dummy_create_not_empty_with_factory) {
    resource_pool pool(42, make_resource);
}

TEST(sync_resource_pool, check_metrics_for_empty) {
    resource_pool pool;
    EXPECT_EQ(pool.capacity(), 0ul);
    EXPECT_EQ(pool.size(), 0ul);
    EXPECT_EQ(pool.used(), 0ul);
    EXPECT_EQ(pool.available(), 0ul);
}

TEST(sync_resource_pool, check_capacity) {
    const std::size_t capacity = 42;
    resource_pool pool(capacity);
    EXPECT_EQ(pool.capacity(), capacity);
}

TEST(sync_resource_pool, dummy_get_auto_recylce_handle) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_recycle();
}

TEST(sync_resource_pool, dummy_get_auto_waste_handle) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_waste();
}

TEST(sync_resource_pool, check_metrics_for_not_empty) {
    const std::size_t capacity = 42;
    resource_pool pool(capacity, make_resource);
    EXPECT_EQ(pool.size(), 0ul);
    EXPECT_EQ(pool.used(), 0ul);
    EXPECT_EQ(pool.available(), 0ul);
    {
        resource_handle_ptr handle = pool.get_auto_recycle();
        EXPECT_EQ(pool.size(), 1ul);
        EXPECT_EQ(pool.used(), 1ul);
        EXPECT_EQ(pool.available(), 0ul);
    }
    EXPECT_EQ(pool.size(), 1ul);
    EXPECT_EQ(pool.used(), 0ul);
    EXPECT_EQ(pool.available(), 1ul);
    {
        resource_handle_ptr handle1 = pool.get_auto_recycle();
        resource_handle_ptr handle2 = pool.get_auto_recycle();
        EXPECT_EQ(pool.size(), 2ul);
        EXPECT_EQ(pool.used(), 2ul);
        EXPECT_EQ(pool.available(), 0ul);
    }
    EXPECT_EQ(pool.size(), 2ul);
    EXPECT_EQ(pool.used(), 0ul);
    EXPECT_EQ(pool.available(), 2ul);
    {
        resource_handle_ptr handle = pool.get_auto_waste();
        EXPECT_EQ(pool.size(), 2ul);
        EXPECT_EQ(pool.used(), 1ul);
        EXPECT_EQ(pool.available(), 1ul);
    }
    EXPECT_EQ(pool.size(), 1ul);
    EXPECT_EQ(pool.used(), 0ul);
    EXPECT_EQ(pool.available(), 1ul);
}

TEST(sync_resource_pool, get_auto_recylce_handle_and_recycle) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_recycle();
    handle->recycle();
}

TEST(sync_resource_pool, get_auto_recylce_handle_and_waste) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_recycle();
    handle->waste();
}

TEST(sync_resource_pool, get_auto_waste_handle_and_recycle) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_waste();
    handle->recycle();
}

TEST(sync_resource_pool, get_auto_waste_handle_and_waste) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_waste();
    handle->waste();
}

TEST(sync_resource_pool, get_auto_recycle_handle_check_empty) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_recycle();
    EXPECT_FALSE(handle->empty());
    handle->recycle();
    EXPECT_TRUE(handle->empty());
}

TEST(sync_resource_pool, get_auto_recycle_handle_and_get_recycled_expect_exception) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_recycle();
    handle->recycle();
    EXPECT_THROW(handle->get(), error::empty_handle);
}

TEST(sync_resource_pool, get_auto_recycle_handle_and_recycle_recycled_expect_exception) {
    resource_pool pool(1, make_resource);
    resource_handle_ptr handle = pool.get_auto_recycle();
    handle->recycle();
    EXPECT_THROW(handle->recycle(), error::empty_handle);
}

TEST(sync_resource_pool, get_auto_recycle_handle_from_empty_pool_returns_empty_handle) {
    resource_pool pool(0, make_resource);
    resource_handle_ptr handle = pool.get_auto_recycle();
    EXPECT_EQ(handle->error(), error::get_resource_timeout);
}

TEST(sync_resource_pool, dummy_create_my_resoure_handle) {
    resource_pool pool(1, make_resource);
    my_resource_handle handle(pool.get_auto_recycle());
}

TEST(sync_resource_pool, check_pool_lifetime) {
    resource_handle_ptr handle;
    {
        resource_pool pool(1, make_resource);
        handle = pool.get_auto_recycle();
    }
}

}
<|endoftext|>


<commit_before>#include <tiramisu/tiramisu.h>

using namespace tiramisu;

void gen(std::string name, int size, int val0, int val1)
{
    tiramisu::init(name);

    tiramisu::function *function0 = global::get_implicit_function();

    tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, function0);

    tiramisu::var i("i", 0, N), j("j", 0, N);
    tiramisu::var i0("i0"), j0("j0"), i1("i1"), j1("j1");

    tiramisu::computation S0(tiramisu::expr((uint8_t) (val0 + val1)), i, j);

    S0.tile(i, j, 2, 2, i0, j0, i1, j1);
    S0.tag_parallel_level(i0);

    tiramisu::buffer buf0("buf0", {size, size}, tiramisu::p_uint8, a_output, function0);
    S0.store_in(&buf0, {i ,j});

    function0->codegen({&buf0}, "build/generated_fct_test_116.o");
}

int main(int argc, char **argv)
{
    gen("func", 10, 3, 4);

    return 0;
}
<commit_msg>Fix test<commit_after>#include <tiramisu/tiramisu.h>

using namespace tiramisu;

void gen(std::string name, int size, int val0, int val1)
{
    tiramisu::init(name);

    tiramisu::function *function0 = global::get_implicit_function();

    tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, function0);

    tiramisu::var i("i", 0, N), j("j", 0, N);
    tiramisu::var i0("i0"), j0("j0"), i1("i1"), j1("j1");

    tiramisu::computation S0({i, j}, tiramisu::expr((uint8_t) (val0 + val1)));

    S0.tile(i, j, 2, 2, i0, j0, i1, j1);
    S0.tag_parallel_level(i0);

    tiramisu::buffer buf0("buf0", {size, size}, tiramisu::p_uint8, a_output, function0);
    S0.store_in(&buf0, {i ,j});

    function0->codegen({&buf0}, "build/generated_fct_test_116.o");
}

int main(int argc, char **argv)
{
    gen("func", 10, 3, 4);

    return 0;
}
<|endoftext|>


<commit_before>#include <catch.hpp>

#include <ecs.hpp>

enum class ColumnNames
{
    Surname,
    Age,
    Height
};

template <ColumnNames Name, class T>
using mycolumn = helene::column_description<ColumnNames, Name, T>;

TEST_CASE("", "")
{
    helene::table<ColumnNames,
                  mycolumn<ColumnNames::Surname, std::string>,
                  mycolumn<ColumnNames::Age, int>,
                  mycolumn<ColumnNames::Height, float>>
        tb;

    const auto first_row = tb.insert_row("Bergesen", 35, 1.83f);
    const auto second_row = tb.insert_row("Lund-Hansen", 70, 1.80f);

    CHECK(tb.get<ColumnNames::Surname>(first_row) == "Bergesen");
    CHECK(tb.get<ColumnNames::Surname>(second_row) == "Lund-Hansen");
    CHECK(tb.get<ColumnNames::Age>(first_row) == 35);
    CHECK(tb.get<ColumnNames::Age>(second_row) == 70);

    CHECK(tb.size() == 2);

    SECTION("erase first row")
    {
        tb.erase_row(first_row);

        CHECK(tb.get<ColumnNames::Surname>(second_row) == "Lund-Hansen");
        CHECK(tb.get<ColumnNames::Age>(second_row) == 70);

        CHECK(tb.size() == 1);
    }

    SECTION("erase second row")
    {
        tb.erase_row(second_row);

        CHECK(tb.get<ColumnNames::Surname>(first_row) == "Bergesen");
        CHECK(tb.get<ColumnNames::Age>(first_row) == 35);

        CHECK(tb.size() == 1);
    }

    SECTION("get iterator range to Surname column")
    {
        auto it_beg = tb.column_begin<ColumnNames::Surname>();
        auto it_end = tb.column_end<ColumnNames::Surname>();
    }
}
<commit_msg>Add unit test for iterators. 	modified:   tests/test_ecs.cpp<commit_after>#include <iterator>

#include <catch.hpp>

#include <ecs.hpp>

enum class ColumnNames
{
    Surname,
    Age,
    Height
};

template <ColumnNames Name, class T>
using mycolumn = helene::column_description<ColumnNames, Name, T>;

TEST_CASE("", "")
{
    helene::table<ColumnNames,
                  mycolumn<ColumnNames::Surname, std::string>,
                  mycolumn<ColumnNames::Age, int>,
                  mycolumn<ColumnNames::Height, float>>
        tb;

    const auto first_row = tb.insert_row("Bergesen", 35, 1.83f);
    const auto second_row = tb.insert_row("Lund-Hansen", 70, 1.80f);

    CHECK(tb.get<ColumnNames::Surname>(first_row) == "Bergesen");
    CHECK(tb.get<ColumnNames::Surname>(second_row) == "Lund-Hansen");
    CHECK(tb.get<ColumnNames::Age>(first_row) == 35);
    CHECK(tb.get<ColumnNames::Age>(second_row) == 70);

    CHECK(tb.size() == 2);

    SECTION("erase first row")
    {
        tb.erase_row(first_row);

        CHECK(tb.get<ColumnNames::Surname>(second_row) == "Lund-Hansen");
        CHECK(tb.get<ColumnNames::Age>(second_row) == 70);

        CHECK(tb.size() == 1);
    }

    SECTION("erase second row")
    {
        tb.erase_row(second_row);

        CHECK(tb.get<ColumnNames::Surname>(first_row) == "Bergesen");
        CHECK(tb.get<ColumnNames::Age>(first_row) == 35);

        CHECK(tb.size() == 1);
    }

    SECTION("get iterator range to Surname column")
    {
        auto it_beg = tb.column_begin<ColumnNames::Surname>();
        auto it_end = tb.column_end<ColumnNames::Surname>();

        std::vector<std::string> surnames(it_beg, it_end);

        CHECK(std::distance(it_beg, it_end) == 2);
        CHECK_THAT(surnames, Catch::VectorContains(std::string("Bergesen")));
        CHECK_THAT(surnames, Catch::VectorContains(std::string("Lund-Hansen")));
    }
}
<|endoftext|>