<commit_before>#include "GameWorld.h"

GameWorld::GameWorld (ApplicationMode mode)
{
	// Creates a CubeAsset in the asset manager
	asset_manager = std::make_shared<GameAssetManager>(mode);

	// Starting point for cube (0,0,0)
	std::shared_ptr<CubeAsset> tmp_obj = std::make_shared<CubeAsset>(glm::vec3(0.0, 0.0, 0.0));
	asset_manager->AddAsset(tmp_obj);
}

/**
* Handles the keyboard inputs passed from main.
* 1 = W, 2 = A, 3 = S, 4 = D (Player Movement)
* 5 = I, 6 = J, 7 = K, 8 = L (Camera Look)
* 9 = R, 10= F (Move on Y axis)
* This could likely be handled better, but it works.
*
* @param k (int) - ID of action to perform
*/
void GameWorld::CameraController(int k)
{
	/* Slow collision checker
	std::vector<std::shared_ptr<CubeAsset>> asset_list = asset_manager->GetAssets();
	for(int i = 0; i < asset_list.size(); i++)
	{
		CubeAsset c = *asset_list[i];
		if(CheckCollision(c.GetVec3()))
		{
			std::cout << "[P]Detected collision with cube at: (X: " << position.x << ", Y: " << position.y << ", Z: " << position.z << ")" << std::endl;
			std::cout << "[C]Detected collision with cube at: (X: " << c.GetVec3().x << ", Y: " << c.GetVec3().y << ", Z: " << c.GetVec3().z << ")" << std::endl;
		}
	}*/

	// For W A S D
	if(k == 1)
		position += z_direction * camera_speed;
	if(k == 2)
		position -= x_direction * camera_speed;
	if(k == 3)
		position -= z_direction * camera_speed;
	if(k == 4)
		position += x_direction * camera_speed;

	// I K
	if(k == 5)
		camera_y += 0.5f * camera_speed;
	if(k == 7)
		camera_y -= 0.5f * camera_speed;

	// J L
	if(k == 6)
		camera_x += 0.5f * camera_speed;
	if(k == 8)
		camera_x -= 0.5f * camera_speed;

	// For R F
	if(k == 9)
		position.y += 0.5f * camera_speed;
	if(k == 10)
		position.y -= 0.5f * camera_speed;

	// Resetting camera position X
	if(camera_x >= 6.298)
		camera_x = 0.1;
	if(camera_x <= 0)
		camera_x = 6.297;

	// Resetting camera position Y
	if(camera_y >= 1.5f)
		camera_y = 1.5;
	if(camera_y <= -1.5f)
		camera_y = -1.5;
}

// test
void GameWorld::MoveCamera(int x, int y)
{
	camera_y -= y * camera_speed / 10.0f;
	camera_x += x * camera_speed / 10.0f;
}

/**
 * Calculates the camera facing direction
 */
void GameWorld::UpdateFacingDirection()
{
	if(camera_x <= point && camera_x >= 0.0 && f_pos != "N")
	{
		f_pos = "N";
		std::cout << "[N]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point && camera_x <= point*3 && f_pos != "NW")
	{
		f_pos = "NW";
		std::cout << "[NW]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point*3 && camera_x <= point*5 && f_pos != "W")
	{
		f_pos = "W";
		std::cout << "[W]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point*5 && camera_x <= point*7 && f_pos != "SW")
	{
		f_pos = "SW";
		std::cout << "[SW]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point*7 && camera_x <= point*9 && f_pos != "S")
	{
		f_pos = "S";
		std::cout << "[S]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point*9 && camera_x <= point*11 && f_pos != "SE")
	{
		f_pos = "SE";
		std::cout << "[SE]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point*11 && camera_x <= point*13 && f_pos != "E")
	{
		f_pos = "E";
		std::cout << "[E]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point*13 && camera_x <= point*15 && f_pos != "NE")
	{
		f_pos = "NE";
		std::cout << "[NE]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point*15 && camera_x <= point*16 && f_pos != "NE")
	{
		f_pos = "NE";
		std::cout << "[NE]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
}

/**
 * Returns an offset for the space in front of the camera
 */
glm::vec3 GameWorld::GetOffset()
{
	UpdateFacingDirection();
	int x = 0, y = 0, z = 0;
	if(f_pos == "N")
	{
		z += 1;
	}
	if(f_pos == "NE")
	{
		z += 1;
		x -= 1;
	}
	if(f_pos == "E")
	{
		x -= 1;
	}
	if(f_pos == "SE")
	{
		z -= 1;
		x -= 1;
	}
	if(f_pos == "S")
	{
		z -= 1;
	}
	if(f_pos == "SW")
	{
		z -= 1;
		x += 1;
	}
	if(f_pos == "W")
	{
		x += 2;
	}
	if(f_pos == "NW")
	{
		z += 1;
		x += 1;
	}

	// JUST A TEST, NEEDS UPDATING
	if(camera_y > 0.5)
	{
		y += 1;
	}
	if(camera_y < -0.5)
	{
		y -= 1;
	}

	return glm::vec3(x,y,z);
}

/**
 * Draws a grid in 3D space
 */
void GameWorld::DrawGrid()
{
	for(float i = -500; i <= 500; i += 0.5)
	{
		glBegin(GL_LINES);
		glVertex3f(-500, -0.5, i);
		glVertex3f(500, -0.5, i);
		glVertex3f(i, -0.5, -500);
		glVertex3f(i, -0.5, 500);
		glEnd();
	}
}

/**
 * Handles action codes passed from main
 * @param a (int) ID of action to perform
 */
void GameWorld::DoAction(int a)
{
	if(a == 1)
	{
		glm::vec3 offset_pos = GetOffset();
		std::shared_ptr<CubeAsset> new_cube = std::make_shared<CubeAsset>(glm::vec3(0.0f + int(round(position.x)) + offset_pos.x, 0.0f + int(round(position.y)) + offset_pos.y, 0.0f + int(round(position.z)) + offset_pos.z)); // Cube to make
		asset_manager->AddAsset(new_cube);
	}
	if(a == 2)
	{
		glm::vec3 offset_pos = GetOffset();
		asset_manager->RemoveAsset(position, offset_pos);
	}
	if(a == 3)
	{
		asset_manager->RemoveAll();
		CreateFloor(rand() % 19 + 1, rand() % 19 + 1, rand() % 19 + 1);
	}
}

/**
 * Handles drawing of the camera and game world assets
 */
void GameWorld::Draw()
{
	glm::vec3 direction(
		cos(camera_y) * sin(camera_x),
		sin(camera_y),
		cos(camera_y) * cos(camera_x)
	);

	glm::vec3 move_direction(
		cos(camera_y) * sin(camera_x),
		0,
		cos(camera_y) * cos(camera_x)
	);
	z_direction = move_direction;

	x_direction = glm::vec3(
		sin(camera_x - 3.14f/2.0f),
		0,
		cos(camera_x - 3.14f/2.0f)
	);

	glm::vec3 vup = glm::cross(x_direction, direction);
	glm::mat4 cam_proj = glm::perspective(75.0f, 4.0f / 3.0f, 0.1f, 100.0f);
	cam_view = glm::lookAt(
		position,
		position + direction,
		vup
	);
	glm::mat4 cam_mod(1.0f);

	glUniformMatrix4fv(0, 1, GL_FALSE, &cam_proj[0][0]);
	glUniformMatrix4fv(1, 1, GL_FALSE, &cam_view[0][0]);
	glUniformMatrix4fv(2, 1, GL_FALSE, &cam_mod[0][0]);

	// Calls draw from the asset manager
	asset_manager->Draw();

	// Draws our grid
	DrawGrid();
}

/**
 * Generates a floor from 0,0 to X and Y specified
 */
void GameWorld::CreateFloor(int x, int y, int z)
{
	for(int i = 0; i < x; i++)
	{
		for(int o = 0; o < y; o++)
		{
			for(int p = 0; p < z; p++)
			{
				if((rand() % 18 + 2) > 15)
				{
					asset_manager->AddAsset(std::make_shared<CubeAsset>(glm::vec3(0.0+i, 0.0+p, 0.0+o)));
				}
			}
		}
	}
}

/**
 * Returns true if the position passed is already filled with a block
 */
bool GameWorld::CheckCollision(glm::vec3 point)
{
	if(point == glm::vec3(int(position.x), int(position.y), int(position.z)))
		return true;

	return false;
}<commit_msg>Change block place distance<commit_after>#include "GameWorld.h"

GameWorld::GameWorld (ApplicationMode mode)
{
	// Creates a CubeAsset in the asset manager
	asset_manager = std::make_shared<GameAssetManager>(mode);

	// Starting point for cube (0,0,0)
	std::shared_ptr<CubeAsset> tmp_obj = std::make_shared<CubeAsset>(glm::vec3(0.0, 0.0, 0.0));
	asset_manager->AddAsset(tmp_obj);
}

/**
* Handles the keyboard inputs passed from main.
* 1 = W, 2 = A, 3 = S, 4 = D (Player Movement)
* 5 = I, 6 = J, 7 = K, 8 = L (Camera Look)
* 9 = R, 10= F (Move on Y axis)
* This could likely be handled better, but it works.
*
* @param k (int) - ID of action to perform
*/
void GameWorld::CameraController(int k)
{
	/* Slow collision checker
	std::vector<std::shared_ptr<CubeAsset>> asset_list = asset_manager->GetAssets();
	for(int i = 0; i < asset_list.size(); i++)
	{
		CubeAsset c = *asset_list[i];
		if(CheckCollision(c.GetVec3()))
		{
			std::cout << "[P]Detected collision with cube at: (X: " << position.x << ", Y: " << position.y << ", Z: " << position.z << ")" << std::endl;
			std::cout << "[C]Detected collision with cube at: (X: " << c.GetVec3().x << ", Y: " << c.GetVec3().y << ", Z: " << c.GetVec3().z << ")" << std::endl;
		}
	}*/

	// For W A S D
	if(k == 1)
		position += z_direction * camera_speed;
	if(k == 2)
		position -= x_direction * camera_speed;
	if(k == 3)
		position -= z_direction * camera_speed;
	if(k == 4)
		position += x_direction * camera_speed;

	// I K
	if(k == 5)
		camera_y += 0.5f * camera_speed;
	if(k == 7)
		camera_y -= 0.5f * camera_speed;

	// J L
	if(k == 6)
		camera_x += 0.5f * camera_speed;
	if(k == 8)
		camera_x -= 0.5f * camera_speed;

	// For R F
	if(k == 9)
		position.y += 0.5f * camera_speed;
	if(k == 10)
		position.y -= 0.5f * camera_speed;

	// Resetting camera position X
	if(camera_x >= 6.298)
		camera_x = 0.1;
	if(camera_x <= 0)
		camera_x = 6.297;

	// Resetting camera position Y
	if(camera_y >= 1.5f)
		camera_y = 1.5;
	if(camera_y <= -1.5f)
		camera_y = -1.5;
}

// test
void GameWorld::MoveCamera(int x, int y)
{
	camera_y -= y * camera_speed / 10.0f;
	camera_x += x * camera_speed / 10.0f;
}

/**
 * Calculates the camera facing direction
 */
void GameWorld::UpdateFacingDirection()
{
	if(camera_x <= point && camera_x >= 0.0 && f_pos != "N")
	{
		f_pos = "N";
		std::cout << "[N]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point && camera_x <= point*3 && f_pos != "NW")
	{
		f_pos = "NW";
		std::cout << "[NW]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point*3 && camera_x <= point*5 && f_pos != "W")
	{
		f_pos = "W";
		std::cout << "[W]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point*5 && camera_x <= point*7 && f_pos != "SW")
	{
		f_pos = "SW";
		std::cout << "[SW]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point*7 && camera_x <= point*9 && f_pos != "S")
	{
		f_pos = "S";
		std::cout << "[S]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point*9 && camera_x <= point*11 && f_pos != "SE")
	{
		f_pos = "SE";
		std::cout << "[SE]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point*11 && camera_x <= point*13 && f_pos != "E")
	{
		f_pos = "E";
		std::cout << "[E]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point*13 && camera_x <= point*15 && f_pos != "NE")
	{
		f_pos = "NE";
		std::cout << "[NE]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
	if(camera_x >= point*15 && camera_x <= point*16 && f_pos != "NE")
	{
		f_pos = "NE";
		std::cout << "[NE]" << "X " << camera_x << ", Y " << camera_y << std::endl;
	}
}

/**
 * Returns an offset for the space in front of the camera
 */
glm::vec3 GameWorld::GetOffset()
{
	UpdateFacingDirection();
	int x = 0, y = 0, z = 0;
	if(f_pos == "N")
	{
		z += 1;
	}
	if(f_pos == "NE")
	{
		z += 1;
		x -= 1;
	}
	if(f_pos == "E")
	{
		x -= 1;
	}
	if(f_pos == "SE")
	{
		z -= 1;
		x -= 1;
	}
	if(f_pos == "S")
	{
		z -= 1;
	}
	if(f_pos == "SW")
	{
		z -= 1;
		x += 1;
	}
	if(f_pos == "W")
	{
		x += 1;
	}
	if(f_pos == "NW")
	{
		z += 1;
		x += 1;
	}

	// JUST A TEST, NEEDS UPDATING
	if(camera_y > 0.5)
	{
		y += 1;
	}
	if(camera_y < -0.5)
	{
		y -= 1;
	}

	return glm::vec3(x,y,z);
}

/**
 * Draws a grid in 3D space
 */
void GameWorld::DrawGrid()
{
	for(float i = -500; i <= 500; i += 0.5)
	{
		glBegin(GL_LINES);
		glVertex3f(-500, -0.5, i);
		glVertex3f(500, -0.5, i);
		glVertex3f(i, -0.5, -500);
		glVertex3f(i, -0.5, 500);
		glEnd();
	}
}

/**
 * Handles action codes passed from main
 * @param a (int) ID of action to perform
 */
void GameWorld::DoAction(int a)
{
	if(a == 1)
	{
		glm::vec3 offset_pos = GetOffset();
		std::shared_ptr<CubeAsset> new_cube = std::make_shared<CubeAsset>(glm::vec3(0.0f + int(round(position.x)) + offset_pos.x, 0.0f + int(round(position.y)) + offset_pos.y, 0.0f + int(round(position.z)) + offset_pos.z)); // Cube to make
		asset_manager->AddAsset(new_cube);
	}
	if(a == 2)
	{
		glm::vec3 offset_pos = GetOffset();
		asset_manager->RemoveAsset(position, offset_pos);
	}
	if(a == 3)
	{
		asset_manager->RemoveAll();
		CreateFloor(rand() % 19 + 1, rand() % 19 + 1, rand() % 19 + 1);
	}
}

/**
 * Handles drawing of the camera and game world assets
 */
void GameWorld::Draw()
{
	glm::vec3 direction(
		cos(camera_y) * sin(camera_x),
		sin(camera_y),
		cos(camera_y) * cos(camera_x)
	);

	glm::vec3 move_direction(
		cos(camera_y) * sin(camera_x),
		0,
		cos(camera_y) * cos(camera_x)
	);
	z_direction = move_direction;

	x_direction = glm::vec3(
		sin(camera_x - 3.14f/2.0f),
		0,
		cos(camera_x - 3.14f/2.0f)
	);

	glm::vec3 vup = glm::cross(x_direction, direction);
	glm::mat4 cam_proj = glm::perspective(75.0f, 4.0f / 3.0f, 0.1f, 100.0f);
	cam_view = glm::lookAt(
		position,
		position + direction,
		vup
	);
	glm::mat4 cam_mod(1.0f);

	glUniformMatrix4fv(0, 1, GL_FALSE, &cam_proj[0][0]);
	glUniformMatrix4fv(1, 1, GL_FALSE, &cam_view[0][0]);
	glUniformMatrix4fv(2, 1, GL_FALSE, &cam_mod[0][0]);

	// Calls draw from the asset manager
	asset_manager->Draw();

	// Draws our grid
	DrawGrid();
}

/**
 * Generates a floor from 0,0 to X and Y specified
 */
void GameWorld::CreateFloor(int x, int y, int z)
{
	for(int i = 0; i < x; i++)
	{
		for(int o = 0; o < y; o++)
		{
			for(int p = 0; p < z; p++)
			{
				if((rand() % 18 + 2) > 15)
				{
					asset_manager->AddAsset(std::make_shared<CubeAsset>(glm::vec3(0.0+i, 0.0+p, 0.0+o)));
				}
			}
		}
	}
}

/**
 * Returns true if the position passed is already filled with a block
 */
bool GameWorld::CheckCollision(glm::vec3 point)
{
	if(point == glm::vec3(int(position.x), int(position.y), int(position.z)))
		return true;

	return false;
}<|endoftext|>


<commit_before>#include <Rcpp.h>
#include <ncbi-vdb/NGS.hpp>
#include <ngs-bam/ngs-bam.hpp>
#include <ngs/ErrorMsg.hpp>
#include <ngs/ReadCollection.hpp>
#include <ngs/ReadIterator.hpp>
#include <ngs/Read.hpp>

#include <math.h>
#include <iostream>

using namespace ngs;
using namespace std;
using namespace Rcpp;

//' The readCount in the read collection.
//'
//' This simply returns the full read count.
//'
//' @param acc An accession or a path to an actual SRA file (with .sra suffix)
//' @return the number of reads in the collection
//' @export
//' @examples
//' getFastqCount('SRR000123')
// [[Rcpp::export]]
long getFastqCount(Rcpp::String acc) {
  try {
    ReadCollection run = ncbi::NGS::openReadCollection ( acc );
    long MAX_ROW = run.getReadCount ();
    return MAX_ROW;
  } catch(std::exception &ex) {
    forward_exception_to_r(ex);
    return -1;
  } catch(...) {
    ::Rf_error("c++ exception (unknown reason)");
    return -1;
  }
}

//' The reads in the read collection.
//'
//' This returns the all reads.
//'
//' @param acc An accession or a path to an actual SRA file (with .sra suffix)
//' @param n The number of reads to return
//' @return the reads in the collection
//' @export
//' @examples
//' getFastqReads('SRR000123')
// [[Rcpp::export]]
Rcpp::List getFastqReads(Rcpp::String acc) {
  try {
    ReadCollection run = ncbi::NGS::openReadCollection ( acc );
    long MAX_ROW = run.getReadCount ();

    ReadIterator rgi = run.getReads( Read::all );

    vector<std::string> out;
    for(int i = 0; rgi.nextRead() ; i++) {
      while ( rgi.nextFragment() ) {
        out.push_back(rgi.getFragmentBases().toString());
      }
    }
    return List::create (
        _["reads"] = out
    );
  } catch(std::exception &ex) {
    forward_exception_to_r(ex);
    return -1;
  } catch(...) {
    ::Rf_error("c++ exception (unknown reason)");
    return -1;
  }
}

//' The reads in the read collection.
//'
//' This returns the all reads.
//'
//' @param acc An accession or a path to an actual SRA file (with .sra suffix)
//' @param n The number of reads to return
//' @return the reads in the collection
//' @export
//' @examples
//' getFastqReadsWithQuality('SRR000123')
// [[Rcpp::export]]
Rcpp::List getFastqReadsWithQuality(Rcpp::String acc) {
  try {
    ReadCollection run = ncbi::NGS::openReadCollection ( acc );
    long MAX_ROW = run.getReadCount ();

    ReadIterator rgi = run.getReads( Read::all );
    CharacterVector reads(MAX_ROW);
    CharacterVector qualities(MAX_ROW);

    for(int i = 0; rgi.nextRead() && ( i < MAX_ROW ) ; i++) {
      while ( rgi.nextFragment() ) {
        reads[i] = rgi.getFragmentBases().toString();
        qualities[i] = rgi.getFragmentQualities().toString();
      }
    }

    List fastqRead = Rcpp::List::create(Rcpp::Named("read") = reads,
                                        Rcpp::Named("quality") = qualities);
    return fastqRead;
  } catch(std::exception &ex) {
    forward_exception_to_r(ex);
    return -1;
  } catch(...) {
    ::Rf_error("c++ exception (unknown reason)");
    return -1;
  }
}

//' The reads in the specified region.
//'
//' This returns the all reads in the specified region.
//'
//' @param acc An accession or a path to an actual SRA file (with .sra suffix)
//' @param ref The reference name
//' @param start Start position (inclusive)
//' @param stop End position (inclusive)
//' @return the reads in the collection
//' @export
//' @examples
//' getFastqReadsWithRegion('SRR789392','NC_000020.10', 62926240, 62958722)
// [[Rcpp::export]]
Rcpp::List getFastqReadsWithRegion(Rcpp::String acc, Rcpp::String refname, long start, long stop) {
  try {
    ReadCollection run = ncbi::NGS::openReadCollection ( acc );

    //testing whether there is alignment
    try {
      long alignmentCount = run.getAlignmentCount();
      if (alignmentCount==0) {
        throw std::range_error("no aligned reads availabe");
        return(Rcpp::List());
      }
    } catch (ngs::ErrorMsg ngsErr){
      forward_exception_to_r(ngsErr);
      return(Rcpp::List());
    }

    try {
      // get requested reference
      ngs::Reference ref = run.getReference ( refname );

      long referenceLength = ref.getLength();
      if (stop<start || stop>referenceLength || start<1) {
        throw std::range_error("wrong reference range, reference length = " + toString(referenceLength));
        return(Rcpp::List());
      }

      long count = stop - start + 1;
      AlignmentIterator alignit = ref.getAlignmentSlice ( start, count, Alignment::primaryAlignment );
      vector<std::string> reads;
      vector<std::string> qualities;

      while( alignit.nextAlignment() ) {
        reads.push_back(alignit.getFragmentBases().toString());
      }
      return List::create (
          _["reads"] = reads
      );

    } catch (ngs::ErrorMsg ngsErr){
      forward_exception_to_r(ngsErr);
      return(Rcpp::List());
    }
  } catch(std::exception &ex) {
    forward_exception_to_r(ex);
    return(Rcpp::List());
  } catch(...) {
    ::Rf_error("c++ exception (unknown reason)");
    return(Rcpp::List());
  } //try ReadCollection run

}
<commit_msg>got refname error message working<commit_after>#include <Rcpp.h>
#include <ncbi-vdb/NGS.hpp>
#include <ngs-bam/ngs-bam.hpp>
#include <ngs/ErrorMsg.hpp>
#include <ngs/ReadCollection.hpp>
#include <ngs/ReadIterator.hpp>
#include <ngs/Read.hpp>

#include <math.h>
#include <iostream>

using namespace ngs;
using namespace std;
using namespace Rcpp;

//' The readCount in the read collection.
//'
//' This simply returns the full read count.
//'
//' @param acc An accession or a path to an actual SRA file (with .sra suffix)
//' @return the number of reads in the collection
//' @export
//' @examples
//' getFastqCount('SRR000123')
// [[Rcpp::export]]
long getFastqCount(Rcpp::String acc) {
  try {
    ReadCollection run = ncbi::NGS::openReadCollection ( acc );
    long MAX_ROW = run.getReadCount ();
    return MAX_ROW;
  } catch(std::exception &ex) {
    forward_exception_to_r(ex);
    return -1;
  } catch(...) {
    ::Rf_error("c++ exception (unknown reason)");
    return -1;
  }
}

//' The reads in the read collection.
//'
//' This returns the all reads.
//'
//' @param acc An accession or a path to an actual SRA file (with .sra suffix)
//' @param n The number of reads to return
//' @return the reads in the collection
//' @export
//' @examples
//' getFastqReads('SRR000123')
// [[Rcpp::export]]
Rcpp::List getFastqReads(Rcpp::String acc) {
  try {
    ReadCollection run = ncbi::NGS::openReadCollection ( acc );
    long MAX_ROW = run.getReadCount ();

    ReadIterator rgi = run.getReads( Read::all );

    vector<std::string> out;
    for(int i = 0; rgi.nextRead() ; i++) {
      while ( rgi.nextFragment() ) {
        out.push_back(rgi.getFragmentBases().toString());
      }
    }
    return List::create (
        _["reads"] = out
    );
  } catch(std::exception &ex) {
    forward_exception_to_r(ex);
    return -1;
  } catch(...) {
    ::Rf_error("c++ exception (unknown reason)");
    return -1;
  }
}

//' The reads in the read collection.
//'
//' This returns the all reads.
//'
//' @param acc An accession or a path to an actual SRA file (with .sra suffix)
//' @param n The number of reads to return
//' @return the reads in the collection
//' @export
//' @examples
//' getFastqReadsWithQuality('SRR000123')
// [[Rcpp::export]]
Rcpp::List getFastqReadsWithQuality(Rcpp::String acc) {
  try {
    ReadCollection run = ncbi::NGS::openReadCollection ( acc );
    long MAX_ROW = run.getReadCount ();

    ReadIterator rgi = run.getReads( Read::all );
    CharacterVector reads(MAX_ROW);
    CharacterVector qualities(MAX_ROW);

    for(int i = 0; rgi.nextRead() && ( i < MAX_ROW ) ; i++) {
      while ( rgi.nextFragment() ) {
        reads[i] = rgi.getFragmentBases().toString();
        qualities[i] = rgi.getFragmentQualities().toString();
      }
    }

    List fastqRead = Rcpp::List::create(Rcpp::Named("read") = reads,
                                        Rcpp::Named("quality") = qualities);
    return fastqRead;
  } catch(std::exception &ex) {
    forward_exception_to_r(ex);
    return -1;
  } catch(...) {
    ::Rf_error("c++ exception (unknown reason)");
    return -1;
  }
}

//' The reads in the specified region.
//'
//' This returns the all reads in the specified region.
//'
//' @param acc An accession or a path to an actual SRA file (with .sra suffix)
//' @param ref The reference name
//' @param start Start position (inclusive)
//' @param stop End position (inclusive)
//' @return the reads in the collection
//' @export
//' @examples
//' getFastqReadsWithRegion('SRR789392','NC_000020.10', 62926240, 62958722)
// [[Rcpp::export]]
Rcpp::List getFastqReadsWithRegion(Rcpp::String acc, Rcpp::String refname, long start, long stop) {
  try {
    ReadCollection run = ncbi::NGS::openReadCollection ( acc );

    //testing whether there is alignment
    try {
      long alignmentCount = run.getAlignmentCount();
      if (alignmentCount==0) {
        throw std::range_error("no aligned reads availabe");
        return(Rcpp::List());
      }
    } catch (ngs::ErrorMsg ngsErr){
      forward_exception_to_r(ngsErr);
      return(Rcpp::List());
    }

    try {
       if (!run.hasReference ( refname )) {
        std::string errorAndRefNames = "The accession id does not have the reference, the options are:";
        ReferenceIterator refIter = run.getReferences();
        while( refIter.nextReference() ) {
          errorAndRefNames += refIter.getCanonicalName();
        }
        throw std::range_error(errorAndRefNames);
       }
    } catch (ngs::ErrorMsg ngsErr){
      forward_exception_to_r(ngsErr);
      return(Rcpp::List());
    }

    try {
      // get requested reference
      ngs::Reference ref = run.getReference ( refname );

      long referenceLength = ref.getLength();
      if (stop<start || stop>referenceLength || start<1) {
        throw std::range_error("wrong reference range, reference length = " + toString(referenceLength));
        return(Rcpp::List());
      }

      long count = stop - start + 1;
      AlignmentIterator alignit = ref.getAlignmentSlice ( start, count, Alignment::primaryAlignment );
      vector<std::string> reads;
      vector<std::string> qualities;

      while( alignit.nextAlignment() ) {
        reads.push_back(alignit.getFragmentBases().toString());
      }
      return List::create (
          _["reads"] = reads
      );

    } catch (ngs::ErrorMsg ngsErr){
      forward_exception_to_r(ngsErr);
      return(Rcpp::List());
    }
  } catch(std::exception &ex) {
    forward_exception_to_r(ex);
    return(Rcpp::List());
  } catch(...) {
    ::Rf_error("c++ exception (unknown reason)");
    return(Rcpp::List());
  } //try ReadCollection run

}
<|endoftext|>


<commit_before>/*
 * HashUil.cpp
 *
 *  Created on: 30 Aug 2013
 *      Author: nicholas
 */

#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <cstdio>

namespace po = boost::program_options;
namespace fs = boost::filesystem;

using namespace std;

bool isVaidPath(string path) {
	fs::path p(path);
	return fs::exists(p) && fs::is_directory(p);
}

int main(int argc, char* argv[]) {
	po::options_description desc = po::options_description("Allowed options");
	po::options_description hidden("Hidden options");
	po::options_description allOptions;

	po::positional_options_description pos;
	pos.add("path", -1);

	desc.add_options()
			("help", "Display this help message")
			("filter", po::value<string>(), "Add files in the directory and subdirectories into filter list")
			("prune", "Remove non-existing file paths from the database")
	;

	hidden.add_options()
		("path", po::value<vector<string> >()->multitoken(), "Paths to process")
	;

	allOptions.add(desc).add(hidden);

	po::variables_map vm;
	po::store(po::command_line_parser(argc,argv).options(allOptions).positional(pos).run(), vm);
	po::notify(vm);

	if(vm.count("help") > 0) {
		cout << desc << "\n";
		exit(0);
	}else if(vm.count("path") == 0){
		cout << "No paths given, aborting.\n";
		exit(1);
	}else if((vm.count("filter") == 0) && (vm.count("prune") == 0)){
	cout << "No operation selected, aborting.\n";
		exit(2);
	}

	if(vm.count("filter")){
		cout << "Adding files to filter with reason \"" << vm["filter"].as<string>() << "\"\n";
	}

	if(vm.count("prune")) {
		cout << "Pruning database.\n";
	}

//	cout << "Folders to process:\n" << vm["path"].as<vector<string> >() << "\n";

	// workaround for printing paths
	cout << "Folders to process:\n";
	vector<string> paths = vm["path"].as<vector<string> >();

	for (vector<string>::iterator ite = paths.begin(); ite != paths.end(); ++ite) {
		if (isVaidPath(*ite)) {
			cout << *ite << " - OK" << "\n";
		} else {
			cout << *ite << " - INVALID" << "\n";
		}
	}
}
<commit_msg>Replaced cstdio with iostream - Removed unused code<commit_after>/*
 * HashUil.cpp
 *
 *  Created on: 30 Aug 2013
 *      Author: nicholas
 */

#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <iostream>

namespace po = boost::program_options;
namespace fs = boost::filesystem;

using namespace std;

bool isVaidPath(string path) {
	fs::path p(path);
	return fs::exists(p) && fs::is_directory(p);
}

int main(int argc, char* argv[]) {
	po::options_description desc = po::options_description("Allowed options");
	po::options_description hidden("Hidden options");
	po::options_description allOptions;

	po::positional_options_description pos;
	pos.add("path", -1);

	desc.add_options()
			("help", "Display this help message")
			("filter", po::value<string>(), "Add files in the directory and subdirectories into filter list")
			("prune", "Remove non-existing file paths from the database")
	;

	hidden.add_options()
		("path", po::value<vector<string> >()->multitoken(), "Paths to process")
	;

	allOptions.add(desc).add(hidden);

	po::variables_map vm;
	po::store(po::command_line_parser(argc,argv).options(allOptions).positional(pos).run(), vm);
	po::notify(vm);

	if(vm.count("help") > 0) {
		cout << desc << "\n";
		exit(0);
	}else if(vm.count("path") == 0){
		cout << "No paths given, aborting.\n";
		exit(1);
	}else if((vm.count("filter") == 0) && (vm.count("prune") == 0)){
	cout << "No operation selected, aborting.\n";
		exit(2);
	}

	if(vm.count("filter")){
		cout << "Adding files to filter with reason \"" << vm["filter"].as<string>() << "\"\n";
	}

	if(vm.count("prune")) {
		cout << "Pruning database.\n";
	}

	cout << "Folders to process:\n";
	vector<string> paths = vm["path"].as<vector<string> >();

	for (vector<string>::iterator ite = paths.begin(); ite != paths.end(); ++ite) {
		if (isVaidPath(*ite)) {
			cout << *ite << " - OK" << "\n";
		} else {
			cout << *ite << " - INVALID" << "\n";
		}
	}
}
<|endoftext|>


<commit_before>#ifndef KEYBOARDMANAGER_HPP
#define KEYBOARDMANAGER_HPP

#include <map>
#include <string>
#include <functional>

#include <SFML/Window/Event.hpp>
#include <SFML/Window/Keyboard.hpp>

namespace swift
{
	class KeyboardManager
	{
		public:
			KeyboardManager() {};
			~KeyboardManager() {};

			void newBinding(const std::string& n, sf::Keyboard::Key k, std::function<void()> f = [](){return true;}, bool onPress = false)
			{
				bindings.emplace(std::make_pair(n, KeyBinding(k, f, onPress)));
			}

			void call(const std::string& k)
			{
				if(bindings.find(k) != bindings.end())
					bindings.at(k).call();
			}

			bool operator()(sf::Event& e)
			{
				for(auto& k : bindings)
				{
					if(k.second(e))
						return k.second.call();
				}

				return false;
			}

		private:
			class KeyBinding
			{
				public:
					explicit KeyBinding(sf::Keyboard::Key k, std::function<void()> f, bool p)
						:	key(k),
							func(f),
							onPress(p)
					{
					}

					~KeyBinding()
					{
					}

					sf::Keyboard::Key getKey() const
					{
						return key;
					}

					bool operator()(sf::Event& e)
					{
						return ((e.type == sf::Event::KeyPressed && onPress) || (e.type == sf::Event::KeyReleased && !onPress)) && e.key.code == key;
					}

					bool call()
					{
						if(!func)
							return false;

						func();

						return true;
					}

				private:
					sf::Keyboard::Key key;

					std::function<void()> func;

					bool onPress;	// if true, means if key is pressed, if false, means if key is released
			};

			std::map<std::string, KeyBinding> bindings;
	};
}

#endif // KEYBOARDMANAGER_HPP
<commit_msg>Started beginnings of multi key presses.<commit_after>#ifndef KEYBOARDMANAGER_HPP
#define KEYBOARDMANAGER_HPP

#include <map>
#include <string>
#include <functional>

#include <SFML/Window/Event.hpp>
#include <SFML/Window/Keyboard.hpp>

namespace swift
{
	class KeyboardManager
	{
		public:
			KeyboardManager() {};
			~KeyboardManager() {};

			void newBinding(const std::string& n, sf::Keyboard::Key k, std::function<void()> f = [](){return true;}, bool onPress = false)
			{
				bindings.emplace(std::make_pair(n, KeyBinding(k, f, onPress)));
			}

			void call(const std::string& k)
			{
				if(bindings.find(k) != bindings.end())
					bindings.at(k).call();
			}

			bool operator()(sf::Event& e)
			{
				if(e.type == sf::Event::KeyPressed)
				{
					if(e.key.code == sf::Keyboard::LShift || e.key.code == sf::Keyboard::RShift)
					{
						shiftPressed = true;
					}
					else if(e.key.code == sf::Keyboard::LControl || e.key.code == sf::Keyboard::RControl)
					{
						ctrlPressed = true;
					}
					else if(e.key.code == sf::Keyboard::LAlt || e.key.code == sf::Keyboard::RAlt)
					{
						altPressed = true;
					}
				}
				else if(e.type == sf::Event::KeyReleased)
				{
					if(e.key.code == sf::Keyboard::LShift || e.key.code == sf::Keyboard::RShift)
					{
						shiftPressed = false;
					}
					else if(e.key.code == sf::Keyboard::LControl || e.key.code == sf::Keyboard::RControl)
					{
						ctrlPressed = false;
					}
					else if(e.key.code == sf::Keyboard::LAlt || e.key.code == sf::Keyboard::RAlt)
					{
						altPressed = false;
					}
				}

				for(auto& k : bindings)
				{
					if(k.second(e))
						return k.second.call();
				}

				return false;
			}

		private:
			class KeyBinding
			{
				public:
					explicit KeyBinding(sf::Keyboard::Key k, std::function<void()> f, bool p)
						:	key(k),
							func(f),
							onPress(p)
					{
					}

					~KeyBinding()
					{
					}

					sf::Keyboard::Key getKey() const
					{
						return key;
					}

					bool operator()(sf::Event& e)
					{
						return ((e.type == sf::Event::KeyPressed && onPress) || (e.type == sf::Event::KeyReleased && !onPress)) && e.key.code == key;
					}

					bool call()
					{
						if(!func)
							return false;

						func();

						return true;
					}

				private:
					sf::Keyboard::Key key;

					std::function<void()> func;

					bool onPress;	// if true, means if key is pressed, if false, means if key is released
			};

			std::map<std::string, KeyBinding> bindings;

			bool shiftPressed;
			bool ctrlPressed;
			bool altPressed;
	};
}

#endif // KEYBOARDMANAGER_HPP
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <chrono>
#include <thread>
#include <signal.h>

#include "PointGenerator.h"
#include "Game.h"

/*
 * Idle Game
 *
 *  Created on: Aug 14, 2017
 *      Author: EmergencyTemporalShift
 *
 *      The purpose of this is to make a simple iteration/idle game
 *      that can be used with some form of machine learning and do
 *      cool stuff.
 */

// For Interrupts (Doesn't work)
static volatile sig_atomic_t flag = 0;
void sigint(int sig) { // can be called asynchronously
	flag = 1; // set flag
}

// Define the game
Game game = Game();

int main(int argc, char** argv) {
	// This causes a segfault in bash and does nothing in eclipse
	signal(SIGINT, sigint);
	// Define the first generator
	PointGenerator p(16, 1, 0);

	/* Give a free generator to get started out.
	 * After all, manual collection is silly because it just
	 * would be as fast as the computer could trigger it
	 */
	p.Add();
	// Infinite loop. Turns out you can just skip the test in a for loop
	for (int i; i<1000; i++) {
		// Figure out deltaTime
		game.updateDelta();

		/*
		 * Prints how many points are generated (by generating them) and
		 * how many gamePoints there are every ten loops.
		 * TODO: Make dependent on time (Event driven?)
		 */
		if(i%10==0) {
			printf("New Points: %i, ", (int) p.GeneratePoints( ));
			/*
			 * %f shows 0.000000, but %g shows really small numbers like 1.97626e-323
			 * Does this have to do with the way doubles are stored?
			 * TODO: Find a way to display globalPoints properly
			 */
			printf("Total Points: %g\n", game.getPoints());

			/*
			 * Buy as many PointGenerators as it can and prints how many it bought
			 * (It's broken into two lines do to weird run order.)
			 */
			if(i%100==0) {
				printf("Bought %i PointGenerators for a total of ", p.BuyPartMax(0.1));
				printf("%i\n", p.getAmount());
			}
		}
			if(flag) {
						printf("\b\bInterupt Detected, finishing.\n");
						break;
					}
		// TODO: Find out how to take an input while spamming the console with junk.
		// Save a string maybe?

		// Sleep for a tenth of a seconds
		std::this_thread::sleep_for(std::chrono::milliseconds (100));
		//printf("%li\n", deltaTime); // TODO: Find out how to print durations
	}
	// Broken out of the loop, finish up.
	printf("There are %i PointGenerators.\n", p.getAmount());
	printf("There are %f gamePoints.\n", game.getPoints());

	if(flag) {
		printf("Control C pressed");
		return 1;
	}
	return 0;
}

<commit_msg>Fixed indentation<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <chrono>
#include <thread>
#include <signal.h>

#include "PointGenerator.h"
#include "Game.h"

/*
 * Idle Game
 *
 *  Created on: Aug 14, 2017
 *      Author: EmergencyTemporalShift
 *
 *      The purpose of this is to make a simple iteration/idle game
 *      that can be used with some form of machine learning and do
 *      cool stuff.
 */

// For Interrupts (Doesn't work)
static volatile sig_atomic_t flag = 0;
void sigint(int sig) { // can be called asynchronously
	flag = 1; // set flag
}

// Define the game
Game game = Game();

int main(int argc, char** argv) {
	// This causes a segfault in bash and does nothing in eclipse
	signal(SIGINT, sigint);
	// Define the first generator
	PointGenerator p(16, 1, 0);

	/* Give a free generator to get started out.
	 * After all, manual collection is silly because it just
	 * would be as fast as the computer could trigger it
	 */
	p.Add();
	// Infinite loop. Turns out you can just skip the test in a for loop
	for (int i; i<1000; i++) {
		// Figure out deltaTime
		game.updateDelta();

		/*
		 * Prints how many points are generated (by generating them) and
		 * how many gamePoints there are every ten loops.
		 * TODO: Make dependent on time (Event driven?)
		 */
		if(i%10==0) {
			printf("New Points: %i, ", (int) p.GeneratePoints( ));
			/*
			 * %f shows 0.000000, but %g shows really small numbers like 1.97626e-323
			 * Does this have to do with the way doubles are stored?
			 * TODO: Find a way to display globalPoints properly
			 */
			printf("Total Points: %g\n", game.getPoints());

			/*
			 * Buy as many PointGenerators as it can and prints how many it bought
			 * (It's broken into two lines do to weird run order.)
			 */
			if(i%100==0) {
				printf("Bought %i PointGenerators for a total of ", p.BuyPartMax(0.1));
				printf("%i\n", p.getAmount());
			}
		}
			if(flag) {
				// '\b\b' Removes the ^C it adds.
				printf("\b\bInterupt Detected, finishing.\n");
				break;
			}
		// TODO: Find out how to take an input while spamming the console with junk.
		// Save a string maybe?

		// Sleep for a tenth of a seconds
		std::this_thread::sleep_for(std::chrono::milliseconds (100));
		//printf("%li\n", deltaTime); // TODO: Find out how to print durations
	}
	// Broken out of the loop, finish up.
	printf("There are %i PointGenerators.\n", p.getAmount());
	printf("There are %f gamePoints.\n", game.getPoints());

	if(flag) {
		printf("Control C pressed");
		return 1;
	}
	return 0;
}

<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexCrontab.cxx
 ** Lexer to use with extended crontab files used by a powerful
 ** Windows scheduler/event monitor/automation manager nnCron.
 ** (http://nemtsev.eserv.ru/)
 **/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

bool is_whitespace(int ch){
    return ch == '\n' || ch == '\r' || ch == '\t' || ch == ' ';
}

bool is_blank(int ch){
    return ch == '\t' || ch == ' ';
}
//#define FORTH_DEBUG
#ifdef FORTH_DEBUG
static FILE *f_debug;
#define log(x)  fputs(f_debug,x);
#else
#define log(x)
#endif

#define STATE_LOCALE
#define BL ' '

static Accessor *st;
static int cur_pos,pos1,pos2,pos0,lengthDoc;
char *buffer;

char getChar(bool is_bl){
    char ch=st->SafeGetCharAt(cur_pos);
    if(is_bl) if(is_whitespace(ch)) ch=BL;
    return ch;
}

char getCharBL(){
    char ch=st->SafeGetCharAt(cur_pos);
    return ch;
}
bool is_eol(char ch){
    return ch=='\n' || ch=='\r';
}

int parse(char ch, bool skip_eol){
// pos1 - start pos of word
// pos2 - pos after of word
// pos0 - start pos
    char c=0;
    int len;
    bool is_bl=ch==BL;
    pos0=pos1=pos2=cur_pos;
    for(;cur_pos<lengthDoc && (c=getChar(is_bl))==ch; cur_pos++){
        if(is_eol(c) && !skip_eol){
            pos2=pos1;
            return 0;
        }
    }
    pos1=cur_pos;
    pos2=pos1;
    if(cur_pos==lengthDoc) return 0;
    for(len=0;cur_pos<lengthDoc && (c=getChar(is_bl))!=ch; cur_pos++){
        if(is_eol(c) && !skip_eol) break;
        pos2++;
        buffer[len++]=c;
    }
    if(c==ch) pos2--;
    buffer[len]='\0';
#ifdef FORTH_DEBUG
    fprintf(f_debug,"parse: %c %s\n",ch,buffer);
#endif
    return len;
}

bool _is_number(char *s,int base){
    for(;*s;s++){
        int digit=((int)*s)-(int)'0';
#ifdef FORTH_DEBUG
    fprintf(f_debug,"digit: %c %d\n",*s,digit);
#endif
        if(digit>9 && base>10) digit-=7;
        if(digit<0) return false;
        if(digit>=base) return false;
    }
    return true;
}

bool is_number(char *s){
    if(strncmp(s,"0x",2)==0) return _is_number(s+2,16);
    return _is_number(s,10);
}

static void ColouriseForthDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler)
{
    st=&styler;
    cur_pos=startPos;
    lengthDoc = startPos + length;
    buffer = new char[length];

#ifdef FORTH_DEBUG
    f_debug=fopen("c:\\sci.log","at");
#endif

    WordList &control = *keywordLists[0];
    WordList &keyword = *keywordLists[1];
    WordList &defword = *keywordLists[2];
    WordList &preword1 = *keywordLists[3];
    WordList &preword2 = *keywordLists[4];
    WordList &strings = *keywordLists[5];

    // go through all provided text segment
    // using the hand-written state machine shown below
    styler.StartAt(startPos);
    styler.StartSegment(startPos);
    while(parse(BL,true)!=0){
        if(pos0!=pos1){
            styler.ColourTo(pos0,SCE_FORTH_DEFAULT);
            styler.ColourTo(pos1-1,SCE_FORTH_DEFAULT);
        }
        if(strcmp("\\",buffer)==0){
            styler.ColourTo(pos1,SCE_FORTH_COMMENT);
            parse(1,false);
            styler.ColourTo(pos2,SCE_FORTH_COMMENT);
        }else if(strcmp("(",buffer)==0){
            styler.ColourTo(pos1,SCE_FORTH_COMMENT);
            parse(')',true);
            if(cur_pos<lengthDoc) cur_pos++;
            styler.ColourTo(cur_pos,SCE_FORTH_COMMENT);
        }else if(strcmp("[",buffer)==0){
            styler.ColourTo(pos1,SCE_FORTH_STRING);
            parse(']',true);
            if(cur_pos<lengthDoc) cur_pos++;
            styler.ColourTo(cur_pos,SCE_FORTH_STRING);
        }else if(strcmp("{",buffer)==0){
            styler.ColourTo(pos1,SCE_FORTH_LOCALE);
            parse('}',false);
            if(cur_pos<lengthDoc) cur_pos++;
            styler.ColourTo(cur_pos,SCE_FORTH_LOCALE);
        }else if(strings.InList(buffer)) {
            styler.ColourTo(pos1,SCE_FORTH_STRING);
            parse('"',false);
            if(cur_pos<lengthDoc) cur_pos++;
            styler.ColourTo(cur_pos,SCE_FORTH_STRING);
        }else if(control.InList(buffer)) {
            styler.ColourTo(pos1,SCE_FORTH_CONTROL);
            styler.ColourTo(pos2,SCE_FORTH_CONTROL);
        }else if(keyword.InList(buffer)) {
            styler.ColourTo(pos1,SCE_FORTH_KEYWORD);
            styler.ColourTo(pos2,SCE_FORTH_KEYWORD);
        }else if(defword.InList(buffer)) {
            styler.ColourTo(pos1,SCE_FORTH_KEYWORD);
            styler.ColourTo(pos2,SCE_FORTH_KEYWORD);
            parse(BL,false);
            styler.ColourTo(pos1-1,SCE_FORTH_DEFAULT);
            styler.ColourTo(pos1,SCE_FORTH_DEFWORD);
            styler.ColourTo(pos2,SCE_FORTH_DEFWORD);
        }else if(preword1.InList(buffer)) {
            styler.ColourTo(pos1,SCE_FORTH_PREWORD1);
            parse(BL,false);
            styler.ColourTo(pos2,SCE_FORTH_PREWORD1);
        }else if(preword2.InList(buffer)) {
            styler.ColourTo(pos1,SCE_FORTH_PREWORD2);
            parse(BL,false);
            styler.ColourTo(pos2,SCE_FORTH_PREWORD2);
            parse(BL,false);
            styler.ColourTo(pos1,SCE_FORTH_STRING);
            styler.ColourTo(pos2,SCE_FORTH_STRING);
        }else if(is_number(buffer)){
            styler.ColourTo(pos1,SCE_FORTH_NUMBER);
            styler.ColourTo(pos2,SCE_FORTH_NUMBER);
        }
    }
#ifdef FORTH_DEBUG
    fclose(f_debug);
#endif
    delete []buffer;
    return;
/*
                        if(control.InList(buffer)) {
                            styler.ColourTo(i,SCE_FORTH_CONTROL);
                        } else if(keyword.InList(buffer)) {
                            styler.ColourTo(i-1,SCE_FORTH_KEYWORD );
                        } else if(defword.InList(buffer)) {
                            styler.ColourTo(i-1,SCE_FORTH_DEFWORD );
//                            prev_state=SCE_FORTH_DEFWORD
                        } else if(preword1.InList(buffer)) {
                            styler.ColourTo(i-1,SCE_FORTH_PREWORD1 );
//                            state=SCE_FORTH_PREWORD1;
                        } else if(preword2.InList(buffer)) {
                            styler.ColourTo(i-1,SCE_FORTH_PREWORD2 );
                         } else {
                            styler.ColourTo(i-1,SCE_FORTH_DEFAULT);
                        }
*/
/*
    chPrev=' ';
    for (int i = startPos; i < lengthDoc; i++) {
        char ch = chNext;
        chNext = styler.SafeGetCharAt(i + 1);
        if(i!=startPos) chPrev=styler.SafeGetCharAt(i - 1);

        if (styler.IsLeadByte(ch)) {
            chNext = styler.SafeGetCharAt(i + 2);
            i++;
            continue;
        }
#ifdef FORTH_DEBUG
        fprintf(f_debug,"%c %d ",ch,state);
#endif
        switch(state) {
            case SCE_FORTH_DEFAULT:
                if(is_whitespace(ch)) {
                    // whitespace is simply ignored here...
                    styler.ColourTo(i,SCE_FORTH_DEFAULT);
                    break;
                } else if( ch == '\\' && is_blank(chNext)) {
                    // signals the start of an one line comment...
                    state = SCE_FORTH_COMMENT;
                    styler.ColourTo(i,SCE_FORTH_COMMENT);
                } else if( is_whitespace(chPrev) &&  ch == '(' &&  is_whitespace(chNext)) {
                    // signals the start of a plain comment...
                    state = SCE_FORTH_COMMENT_ML;
                    styler.ColourTo(i,SCE_FORTH_COMMENT_ML);
                } else if( isdigit(ch) ) {
                    // signals the start of a number
                    bufferCount = 0;
                    buffer[bufferCount++] = ch;
                    state = SCE_FORTH_NUMBER;
                } else if( !is_whitespace(ch)) {
                    // signals the start of an identifier
                    bufferCount = 0;
                    buffer[bufferCount++] = ch;
                    state = SCE_FORTH_IDENTIFIER;
                } else {
                    // style it the default style..
                    styler.ColourTo(i,SCE_FORTH_DEFAULT);
                }
                break;

            case SCE_FORTH_COMMENT:
                // if we find a newline here,
                // we simply go to default state
                // else continue to work on it...
                if( ch == '\n' || ch == '\r' ) {
                    state = SCE_FORTH_DEFAULT;
                } else {
                    styler.ColourTo(i,SCE_FORTH_COMMENT);
                }
                break;

            case SCE_FORTH_COMMENT_ML:
                if( ch == ')') {
                    state = SCE_FORTH_DEFAULT;
                } else {
                    styler.ColourTo(i+1,SCE_FORTH_COMMENT_ML);
                }
                break;

            case SCE_FORTH_IDENTIFIER:
                // stay  in CONF_IDENTIFIER state until we find a non-alphanumeric
                if( !is_whitespace(ch) ) {
                    buffer[bufferCount++] = ch;
                } else {
                    state = SCE_FORTH_DEFAULT;
                    buffer[bufferCount] = '\0';
#ifdef FORTH_DEBUG
        fprintf(f_debug,"\nid %s\n",buffer);
#endif

                    // check if the buffer contains a keyword,
                    // and highlight it if it is a keyword...
//                    switch(prev_state)
//                    case SCE_FORTH_DEFAULT:
                        if(control.InList(buffer)) {
                            styler.ColourTo(i,SCE_FORTH_CONTROL);
                        } else if(keyword.InList(buffer)) {
                            styler.ColourTo(i-1,SCE_FORTH_KEYWORD );
                        } else if(defword.InList(buffer)) {
                            styler.ColourTo(i-1,SCE_FORTH_DEFWORD );
//                            prev_state=SCE_FORTH_DEFWORD
                        } else if(preword1.InList(buffer)) {
                            styler.ColourTo(i-1,SCE_FORTH_PREWORD1 );
//                            state=SCE_FORTH_PREWORD1;
                        } else if(preword2.InList(buffer)) {
                            styler.ColourTo(i-1,SCE_FORTH_PREWORD2 );
                         } else {
                            styler.ColourTo(i-1,SCE_FORTH_DEFAULT);
                        }
//                        break;
//                    case

                    // push back the faulty character
                    chNext = styler[i--];
                }
                break;

            case SCE_FORTH_NUMBER:
                // stay  in CONF_NUMBER state until we find a non-numeric
                if( isdigit(ch) ) {
                    buffer[bufferCount++] = ch;
                } else {
                    state = SCE_FORTH_DEFAULT;
                    buffer[bufferCount] = '\0';
                    // Colourize here... (normal number)
                    styler.ColourTo(i-1,SCE_FORTH_NUMBER);
                    // push back a character
                    chNext = styler[i--];
                }
                break;
        }
    }
#ifdef FORTH_DEBUG
    fclose(f_debug);
#endif
    delete []buffer;
*/
}

static void FoldForthDoc(unsigned int, int, int, WordList *[],
                       Accessor &) {
}

static const char * const forthWordLists[] = {
            "control keywords",
            "keywords",
            "definition words",
            "prewords with one argument",
            "prewords with two arguments",
            "string definition keywords",
            0,
        };

LexerModule lmForth(SCLEX_FORTH, ColouriseForthDoc, "forth",FoldForthDoc,forthWordLists);
<commit_msg>New FORTH lexer from bug #2804894.<commit_after>// Scintilla source code edit control
/** @file LexForth.cxx
 ** Lexer for FORTH
 **/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static inline bool IsAWordChar(int ch) {
	return (ch < 0x80) && (isalnum(ch) || ch == '.' ||
		ch == '_' || ch == '?' || ch == '"' || ch == '@' ||
		ch == '!' || ch == '[' || ch == ']' || ch == '/' ||
		ch == '+' || ch == '-' || ch == '*' || ch == '<' ||
		ch == '>' || ch == '=' || ch == ';' || ch == '(' ||
		ch == ')' );
}

static inline bool IsAWordStart(int ch) {
	return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.');
}

static inline bool IsANumChar(int ch) {
	return (ch < 0x80) && (isxdigit(ch) || ch == '.' || ch == 'e' || ch == 'E' );
}

static inline bool IsASpaceChar(int ch) {
	return (ch < 0x80) && isspace(ch);
}

static void ColouriseForthDoc(unsigned int startPos, int length, int initStyle, WordList *keywordLists[],
                            Accessor &styler) {

    WordList &control = *keywordLists[0];
    WordList &keyword = *keywordLists[1];
    WordList &defword = *keywordLists[2];
    WordList &preword1 = *keywordLists[3];
    WordList &preword2 = *keywordLists[4];
    WordList &strings = *keywordLists[5];

	StyleContext sc(startPos, length, initStyle, styler);

	for (; sc.More(); sc.Forward())
	{
		// Determine if the current state should terminate.
		if (sc.state == SCE_FORTH_COMMENT) {
			if (sc.atLineEnd) {
				sc.SetState(SCE_FORTH_DEFAULT);
			}
		}else if (sc.state == SCE_FORTH_COMMENT_ML) {
			if (sc.ch == ')') {
				sc.ForwardSetState(SCE_FORTH_DEFAULT);
			}
		}else if (sc.state == SCE_FORTH_IDENTIFIER || sc.state == SCE_FORTH_NUMBER) {
			// handle numbers here too, because what we thought was a number might
			// turn out to be a keyword e.g. 2DUP
			if (IsASpaceChar(sc.ch) ) {
				char s[100];
				sc.GetCurrentLowered(s, sizeof(s));
				int newState = sc.state == SCE_FORTH_NUMBER ? SCE_FORTH_NUMBER : SCE_FORTH_DEFAULT;
				if (control.InList(s)) {
					sc.ChangeState(SCE_FORTH_CONTROL);
				} else if (keyword.InList(s)) {
					sc.ChangeState(SCE_FORTH_KEYWORD);
				} else if (defword.InList(s)) {
					sc.ChangeState(SCE_FORTH_DEFWORD);
				}  else if (preword1.InList(s)) {
					sc.ChangeState(SCE_FORTH_PREWORD1);
				} else if (preword2.InList(s)) {
					sc.ChangeState(SCE_FORTH_PREWORD2);
				} else if (strings.InList(s)) {
					sc.ChangeState(SCE_FORTH_STRING);
					newState = SCE_FORTH_STRING;
				}
				sc.SetState(newState);
			}
			if (sc.state == SCE_FORTH_NUMBER) {
				if (IsASpaceChar(sc.ch)) {
					sc.SetState(SCE_FORTH_DEFAULT);
				}
			}
		}else if (sc.state == SCE_FORTH_STRING) {
			if (sc.ch == '\"') {
				sc.ForwardSetState(SCE_FORTH_DEFAULT);
			}
		}else if (sc.state == SCE_FORTH_LOCALE) {
			if (sc.ch == '}') {
				sc.ForwardSetState(SCE_FORTH_DEFAULT);
			}
		}else if (sc.state == SCE_FORTH_DEFWORD) {
			if (IsASpaceChar(sc.ch)) {
				sc.SetState(SCE_FORTH_DEFAULT);
			}
		}

		// Determine if a new state should be entered.
		if (sc.state == SCE_FORTH_DEFAULT) {
			if (sc.ch == '\\'){
				sc.SetState(SCE_FORTH_COMMENT);
			} else if (sc.ch == '(' &&
					(sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
					(sc.atLineEnd   || IsASpaceChar(sc.chNext))) {
				sc.SetState(SCE_FORTH_COMMENT_ML);
			} else if (	(sc.ch == '$' && (isascii(sc.chNext) && isxdigit(sc.chNext))) ) {
				// number starting with $ is a hex number
				sc.SetState(SCE_FORTH_NUMBER);
				while(sc.More() && isascii(sc.chNext) && isxdigit(sc.chNext))
					sc.Forward();
			} else if ( (sc.ch == '%' && (isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == '1'))) ) {
				// number starting with % is binary
				sc.SetState(SCE_FORTH_NUMBER);
				while(sc.More() && isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == '1'))
					sc.Forward();
			} else if (	isascii(sc.ch) &&
						(isxdigit(sc.ch) || ((sc.ch == '.' || sc.ch == '-') && isascii(sc.chNext) && isxdigit(sc.chNext)) )
					){
				sc.SetState(SCE_FORTH_NUMBER);
			} else if (IsAWordStart(sc.ch)) {
				sc.SetState(SCE_FORTH_IDENTIFIER);
			} else if (sc.ch == '{') {
				sc.SetState(SCE_FORTH_LOCALE);
			} else if (sc.ch == ':' && isascii(sc.chNext) && isspace(sc.chNext)) {
				// highlight word definitions e.g.  : GCD ( n n -- n ) ..... ;
				//                                  ^ ^^^
				sc.SetState(SCE_FORTH_DEFWORD);
				while(sc.More() && isascii(sc.chNext) && isspace(sc.chNext))
					sc.Forward();
			} else if (sc.ch == ';' &&
					(sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
					(sc.atLineEnd   || IsASpaceChar(sc.chNext))	) {
				// mark the ';' that ends a word
				sc.SetState(SCE_FORTH_DEFWORD);
				sc.ForwardSetState(SCE_FORTH_DEFAULT);
			}
		}

	}
	sc.Complete();
}

static void FoldForthDoc(unsigned int, int, int, WordList *[],
						Accessor &) {
}

static const char * const forthWordLists[] = {
			"control keywords",
			"keywords",
			"definition words",
			"prewords with one argument",
			"prewords with two arguments",
			"string definition keywords",
			0,
		};

LexerModule lmForth(SCLEX_FORTH, ColouriseForthDoc, "forth", FoldForthDoc, forthWordLists);

<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>
#include <cassert>

#include "Litteral.hpp"

#include "StringPool.hpp"
#include "Variable.hpp"

#include "il/IntermediateProgram.hpp"
#include "il/Operands.hpp"

using namespace eddic;

void Litteral::checkStrings(StringPool& pool) {
    m_label = pool.label(m_litteral);
}

bool Litteral::isConstant() {
    return true;
}

bool Litteral::isImmediate() {
    return true;
}

std::string Litteral::getStringValue() {
    return m_litteral;
}

std::string Litteral::getStringLabel(){
    return m_label;
}

int Litteral::getStringSize(){
    return m_litteral.size() - 2;
}

void Litteral::assignTo(std::shared_ptr<Variable> variable, IntermediateProgram& program){
    std::pair<std::shared_ptr<Operand>, std::shared_ptr<Operand>> operands = variable->toStringOperand();

    program.addInstruction(
        program.factory().createMove(
            createImmediateOperand(getStringLabel()),
            operands.first
        )
    );

    program.addInstruction(
        program.factory().createMove(
            createImmediateOperand(getStringSize()),
            operands.second
        )
    );
}

void Litteral::assignTo(std::shared_ptr<Operand>, IntermediateProgram&){
    assert(false); //Cannot assign a string to a single operand
}

void Litteral::push(IntermediateProgram& program){
    //TODO Verify that it is corresponding to pushl $label
    program.addInstruction(
        program.factory().createPush(
            createImmediateOperand(getStringLabel())
        )
    );

    program.addInstruction(
        program.factory().createPush(
            createImmediateOperand(getStringSize())
        )
    );
}
<commit_msg>Remove old TODO<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>
#include <cassert>

#include "Litteral.hpp"

#include "StringPool.hpp"
#include "Variable.hpp"

#include "il/IntermediateProgram.hpp"
#include "il/Operands.hpp"

using namespace eddic;

void Litteral::checkStrings(StringPool& pool) {
    m_label = pool.label(m_litteral);
}

bool Litteral::isConstant() {
    return true;
}

bool Litteral::isImmediate() {
    return true;
}

std::string Litteral::getStringValue() {
    return m_litteral;
}

std::string Litteral::getStringLabel(){
    return m_label;
}

int Litteral::getStringSize(){
    return m_litteral.size() - 2;
}

void Litteral::assignTo(std::shared_ptr<Variable> variable, IntermediateProgram& program){
    std::pair<std::shared_ptr<Operand>, std::shared_ptr<Operand>> operands = variable->toStringOperand();

    program.addInstruction(
        program.factory().createMove(
            createImmediateOperand(getStringLabel()),
            operands.first
        )
    );

    program.addInstruction(
        program.factory().createMove(
            createImmediateOperand(getStringSize()),
            operands.second
        )
    );
}

void Litteral::assignTo(std::shared_ptr<Operand>, IntermediateProgram&){
    assert(false); //Cannot assign a string to a single operand
}

void Litteral::push(IntermediateProgram& program){
    program.addInstruction(
        program.factory().createPush(
            createImmediateOperand(getStringLabel())
        )
    );

    program.addInstruction(
        program.factory().createPush(
            createImmediateOperand(getStringSize())
        )
    );
}
<|endoftext|>


<commit_before>/*
 * Qumulus UML editor
 * Author: Frank Erens
 * Author: Randy Thiemann
 *
 */

#include "SideBar.h"
#include <Gui/Widgets/MainWindow.h>

#include <QtWidgets/QHeaderView>

#include <iostream>

QUML_BEGIN_NAMESPACE_GW

SideBar::SideBar(MainWindow* parent, QuGD::Diagram* d) :
        QTreeView(parent),
        mDiagram(d),
        mModel(new QuGC::SideBarModel(mDiagram)){
#ifdef Q_OS_MAC
    setStyleType(StyleType::Active);
    setAttribute(Qt::WA_MacShowFocusRect, false);
#endif
    setMinimumWidth(100);
    QSizePolicy sideBarSizePolicy = sizePolicy();
    sideBarSizePolicy.setHorizontalPolicy(QSizePolicy::Minimum);
    setSizePolicy(sideBarSizePolicy);
    setModel(mModel);
    header()->close();
#ifndef Q_OS_WIN
    mDiagram->diagramChanged += [this] {
        collapseAll();
        expandAll();
    };
#endif
#ifdef Q_OS_WIN
    setEnabled(false);
#endif
}

SideBar::~SideBar() {
    delete mModel;
}

MainWindow* SideBar::window() {
    return static_cast<MainWindow*>(parent());
}

#ifdef Q_OS_MAC
void SideBar::setStyleType(StyleType s) {
    switch(s) {
    case StyleType::Active:
        setStyleSheet(
            "background-color: qlineargradient("
                    "spread:pad, x1:0, y1:0, x2:0, y2:1,"
                    "stop:0 rgba(232, 236, 241, 255),"
                    "stop:1 rgba(209,216,226, 255));"
            "selection-color: white;"
            "selection-background-color: qlineargradient("
                    "x1: 0, y1: 0, x2: 0, y2: 1,"
                    "stop: 0 rgb(110, 165, 218),"
                    "stop: 1 rgb(33, 108, 183));"
            "border-top: 1px solid silver;"
            "border-bottom: 1px solid silver;"
            "font-size: 11pt;"
        );
        break;
    case StyleType::Inactive:
        setStyleSheet(
            "background-color: qlineargradient("
            "spread:pad, x1:0, y1:0, x2:0, y2:1,"
            "stop:0 rgba(247, 247, 247, 255),"
            "stop:1 rgba(235, 235, 235, 255));"
            "selection-color: white;"
            "selection-background-color: qlineargradient("
                    "x1: 0, y1: 0, x2: 0, y2: 1,"
                    "stop: 0 rgb(110, 165, 218),"
                    "stop: 1 rgb(33, 108, 183));"
            "border-top: 1px solid silver;"
            "border-bottom: 1px solid silver;"
            "font-size: 11pt;"
        );
        break;
    }

}
#endif

QUML_END_NAMESPACE_GW

<commit_msg>Remove workaround that disables sidebar on Windows.<commit_after>/*
 * Qumulus UML editor
 * Author: Frank Erens
 * Author: Randy Thiemann
 *
 */

#include "SideBar.h"
#include <Gui/Widgets/MainWindow.h>

#include <QtWidgets/QHeaderView>

#include <iostream>

QUML_BEGIN_NAMESPACE_GW

SideBar::SideBar(MainWindow* parent, QuGD::Diagram* d) :
        QTreeView(parent),
        mDiagram(d),
        mModel(new QuGC::SideBarModel(mDiagram)){
#ifdef Q_OS_MAC
    setStyleType(StyleType::Active);
    setAttribute(Qt::WA_MacShowFocusRect, false);
#endif
    setMinimumWidth(100);
    QSizePolicy sideBarSizePolicy = sizePolicy();
    sideBarSizePolicy.setHorizontalPolicy(QSizePolicy::Minimum);
    setSizePolicy(sideBarSizePolicy);
    setModel(mModel);
    header()->close();

    mDiagram->diagramChanged += [this] {
        collapseAll();
        expandAll();
    };
}

SideBar::~SideBar() {
    delete mModel;
}

MainWindow* SideBar::window() {
    return static_cast<MainWindow*>(parent());
}

#ifdef Q_OS_MAC
void SideBar::setStyleType(StyleType s) {
    switch(s) {
    case StyleType::Active:
        setStyleSheet(
            "background-color: qlineargradient("
                    "spread:pad, x1:0, y1:0, x2:0, y2:1,"
                    "stop:0 rgba(232, 236, 241, 255),"
                    "stop:1 rgba(209,216,226, 255));"
            "selection-color: white;"
            "selection-background-color: qlineargradient("
                    "x1: 0, y1: 0, x2: 0, y2: 1,"
                    "stop: 0 rgb(110, 165, 218),"
                    "stop: 1 rgb(33, 108, 183));"
            "border-top: 1px solid silver;"
            "border-bottom: 1px solid silver;"
            "font-size: 11pt;"
        );
        break;
    case StyleType::Inactive:
        setStyleSheet(
            "background-color: qlineargradient("
            "spread:pad, x1:0, y1:0, x2:0, y2:1,"
            "stop:0 rgba(247, 247, 247, 255),"
            "stop:1 rgba(235, 235, 235, 255));"
            "selection-color: white;"
            "selection-background-color: qlineargradient("
                    "x1: 0, y1: 0, x2: 0, y2: 1,"
                    "stop: 0 rgb(110, 165, 218),"
                    "stop: 1 rgb(33, 108, 183));"
            "border-top: 1px solid silver;"
            "border-bottom: 1px solid silver;"
            "font-size: 11pt;"
        );
        break;
    }

}
#endif

QUML_END_NAMESPACE_GW

<|endoftext|>


<commit_before>// -*- mode: c++, coding: utf-8 -*-
/**
 * tbrpg – Text based roll playing game
 *
 * Copyright © 2012  Mattias Andrée (maandree@kth.se)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "QuestItem.hpp"

/**
 * Text based roll playing game
 *
 * DD2387 Program construction with C++
 * Laboration 3
 *
 * @author  Mattias Andrée <maandree@kth.se>
 */
namespace tbrpg
{
  /**
   * Constructor
   */
  QuestItem::QuestItem()
  {
    this->class_inheritance.push_back(17);
    this->id = 0;
  }

  /**
   * Copy constructor
   *
   * @param  original  The object to clone
   */
  QuestItem::QuestItem(const QuestItem& original)
  {
    this->id = original.id;
  }

  /**
   * Copy constructor
   *
   * @param  original  The object to clone
   */
  QuestItem::QuestItem(QuestItem& original)
  {
    this->id = original.id;
  }

  /**
   * Move constructor
   *
   * @param  original  The object to clone
   */
  QuestItem::QuestItem(QuestItem&& original)
  {
    std::swap(this->id, original.id);
  }

  /**
   * Destructor
   */
  QuestItem::~QuestItem()
  {
    // do nothing
  }

  /**
   * Assignment operator
   *
   * @param   original  The reference object
   * @return            The invoked object
   */
  QuestItem& QuestItem::operator =(const QuestItem& original)
  {
    this->id = original.id;
    return *this;
  }

  /**
   * Assignment operator
   *
   * @param   original  The reference object
   * @return            The invoked object
   */
  QuestItem& QuestItem::operator =(QuestItem& original)
  {
    this->id = original.id;
    return *this;
  }

  /**
   * Move operator
   *
   * @param   original  The moved object, its resourced will be moved
   * @return            The invoked object
   */
  QuestItem& QuestItem::operator =(QuestItem&& original)
  {
    std::swap(this->id, original.id);
    return *this;
  }

  /**
   * Equality evaluator
   *
   * @param   other  The other comparand
   * @return         Whether the instances are equal
   */
  bool QuestItem::operator ==(const QuestItem& other) const
  {
    if (this->id != other.id)  return false;
    return true;
  }

  /**
   * Inequality evaluator
   *
   * @param   other  The other comparand
   * @return         Whether the instances are not equal
   */
  bool QuestItem::operator !=(const QuestItem& other) const
  {
    return (*this == other) == false;
  }

  /**
   * Copy method
   *
   * @param  self      The object to modify
   * @param  original  The reference object
   */
  void QuestItem::__copy__(QuestItem& self, const QuestItem& original)
  {
    self = original;
  }

  /**
   * Hash method
   *
   * @return  The object's hash code
   */
  size_t QuestItem::hash() const
  {
    size_t rc = 0;
    rc = (rc * 3) ^ ((rc >> (sizeof(size_t) << 2)) * 3);
    rc += std::hash<int>()(this->id);
    return rc;
  }

}

<commit_msg>...<commit_after>// -*- mode: c++, coding: utf-8 -*-
/**
 * tbrpg – Text based roll playing game
 *
 * Copyright © 2012  Mattias Andrée (maandree@kth.se)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "QuestItem.hpp"

/**
 * Text based roll playing game
 *
 * DD2387 Program construction with C++
 * Laboration 3
 *
 * @author  Mattias Andrée <maandree@kth.se>
 */
namespace tbrpg
{
  /**
   * Constructor
   */
  QuestItem::QuestItem()
  {
    this->id = 0;
  }

  /**
   * Copy constructor
   *
   * @param  original  The object to clone
   */
  QuestItem::QuestItem(const QuestItem& original)
  {
    this->id = original.id;
  }

  /**
   * Copy constructor
   *
   * @param  original  The object to clone
   */
  QuestItem::QuestItem(QuestItem& original)
  {
    this->id = original.id;
  }

  /**
   * Move constructor
   *
   * @param  original  The object to clone
   */
  QuestItem::QuestItem(QuestItem&& original)
  {
    std::swap(this->id, original.id);
  }

  /**
   * Destructor
   */
  QuestItem::~QuestItem()
  {
    // do nothing
  }

  /**
   * Assignment operator
   *
   * @param   original  The reference object
   * @return            The invoked object
   */
  QuestItem& QuestItem::operator =(const QuestItem& original)
  {
    this->id = original.id;
    return *this;
  }

  /**
   * Assignment operator
   *
   * @param   original  The reference object
   * @return            The invoked object
   */
  QuestItem& QuestItem::operator =(QuestItem& original)
  {
    this->id = original.id;
    return *this;
  }

  /**
   * Move operator
   *
   * @param   original  The moved object, its resourced will be moved
   * @return            The invoked object
   */
  QuestItem& QuestItem::operator =(QuestItem&& original)
  {
    std::swap(this->id, original.id);
    return *this;
  }

  /**
   * Equality evaluator
   *
   * @param   other  The other comparand
   * @return         Whether the instances are equal
   */
  bool QuestItem::operator ==(const QuestItem& other) const
  {
    if (this->id != other.id)  return false;
    return true;
  }

  /**
   * Inequality evaluator
   *
   * @param   other  The other comparand
   * @return         Whether the instances are not equal
   */
  bool QuestItem::operator !=(const QuestItem& other) const
  {
    return (*this == other) == false;
  }

  /**
   * Copy method
   *
   * @param  self      The object to modify
   * @param  original  The reference object
   */
  void QuestItem::__copy__(QuestItem& self, const QuestItem& original)
  {
    self = original;
  }

  /**
   * Hash method
   *
   * @return  The object's hash code
   */
  size_t QuestItem::hash() const
  {
    size_t rc = 0;
    rc = (rc * 3) ^ ((rc >> (sizeof(size_t) << 2)) * 3);
    rc += std::hash<int>()(this->id);
    return rc;
  }

}

<|endoftext|>


<commit_before>// Reselect.cpp
// Copyright (c) 2010, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.

#include "stdafx.h"
#include "Reselect.h"
#include "interface/PropertyString.h"
#include "interface/PropertyInt.h"
#include "interface/ObjList.h"

static bool GetSketches(std::list<int>& sketches )
{
	// check for at least one sketch selected

	const std::list<HeeksObj*>& list = heeksCAD->GetMarkedList();
	for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++)
	{
		HeeksObj* object = *It;
		if(object->GetType() == SketchType)
		{
			sketches.push_back(object->m_id);
		}
	}

	if(sketches.size() == 0)return false;

	return true;
}

void ReselectSketches::Run()
{
	std::list<int> sketches;
	heeksCAD->PickObjects(_("Select Sketches"), MARKING_FILTER_SKETCH);
	if(GetSketches( sketches ))
	{
		heeksCAD->CreateUndoPoint();
		m_sketches->clear();
		*m_sketches = sketches;
		((ObjList*)m_object)->Clear();
		m_object->ReloadPointers();
		heeksCAD->Changed();
	}
	else
	{
		wxMessageBox(_("Select cancelled. No sketches were selected!"));
	}

	// get back to the operation's properties
	heeksCAD->ClearMarkedList();
	heeksCAD->Mark(m_object);
}

static bool GetSolids(std::list<int>& solids )
{
	// check for at least one sketch selected

	const std::list<HeeksObj*>& list = heeksCAD->GetMarkedList();
	for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++)
	{
		HeeksObj* object = *It;
		if(object->GetType() == SolidType || object->GetType() == StlSolidType)
		{
			solids.push_back(object->m_id);
		}
	}

	if(solids.size() == 0)return false;

	return true;
}

void ReselectSolids::Run()
{
	std::list<int> solids;
	heeksCAD->PickObjects(_("Select Solids"), MARKING_FILTER_SOLID | MARKING_FILTER_STL_SOLID);
	if(GetSolids( solids ))
	{
		m_solids->clear();
		*m_solids = solids;
	}
	else
	{
		wxMessageBox(_("Select cancelled. No solids were selected!"));
	}

	// get back to the operation's properties
	heeksCAD->ClearMarkedList();
	heeksCAD->Mark(m_object);
}

wxString GetIntListString(const std::list<int> &list)
{
	wxString str;
	int i = 0;
	for(std::list<int>::const_iterator It = list.begin(); It != list.end(); It++, i++)
	{
		if(i > 0)str.Append(_T(" "));
		if(i > 8)
		{
			str.Append(_T("..."));
			break;
		}
		str.Append(wxString::Format(_T("%d"), *It));
	}

	return str;
}

void AddSolidsProperties(std::list<Property *> *list, HeeksObj* object)
{
	std::list<int> solids;
	for(HeeksObj* child = object->GetFirstChild(); child; child = object->GetNextChild())
	{
		if(child->GetIDGroupType() == SolidType)solids.push_back(child->GetID());
	}
	if(solids.size() == 0)list->push_back(new PropertyString(_("solids"), _("None"), NULL));
	else if(solids.size() == 1)list->push_back(new PropertyInt(_("solid id"), solids.front(), NULL));
	else list->push_back(new PropertyString(_("solids"), GetIntListString(solids), NULL));
}

void AddSketchesProperties(std::list<Property *> *list, HeeksObj* object)
{
	std::list<int> sketches;
	for(HeeksObj* child = object->GetFirstChild(); child; child = object->GetNextChild())
	{
		if(child->GetIDGroupType() == SketchType)sketches.push_back(child->GetID());
	}
	if(sketches.size() == 0)list->push_back(new PropertyString(_("sketches"), _("None"), NULL));
	else if(sketches.size() == 1)list->push_back(new PropertyInt(_("sketch id"), sketches.front(), NULL));
	else list->push_back(new PropertyString(_("sketches"), GetIntListString(sketches), NULL));
}

<commit_msg>Fixed ReselectSolids. It wasn't changing the solids for the zigzag operation ( for example ).<commit_after>// Reselect.cpp
// Copyright (c) 2010, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.

#include "stdafx.h"
#include "Reselect.h"
#include "interface/PropertyString.h"
#include "interface/PropertyInt.h"
#include "interface/ObjList.h"

static bool GetSketches(std::list<int>& sketches )
{
	// check for at least one sketch selected

	const std::list<HeeksObj*>& list = heeksCAD->GetMarkedList();
	for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++)
	{
		HeeksObj* object = *It;
		if(object->GetType() == SketchType)
		{
			sketches.push_back(object->m_id);
		}
	}

	if(sketches.size() == 0)return false;

	return true;
}

void ReselectSketches::Run()
{
	std::list<int> sketches;
	heeksCAD->PickObjects(_("Select Sketches"), MARKING_FILTER_SKETCH);
	if(GetSketches( sketches ))
	{
		heeksCAD->CreateUndoPoint();
		m_sketches->clear();
		*m_sketches = sketches;
		((ObjList*)m_object)->Clear();
		m_object->ReloadPointers();
		heeksCAD->Changed();
	}
	else
	{
		wxMessageBox(_("Select cancelled. No sketches were selected!"));
	}

	// get back to the operation's properties
	heeksCAD->ClearMarkedList();
	heeksCAD->Mark(m_object);
}

static bool GetSolids(std::list<int>& solids )
{
	// check for at least one sketch selected

	const std::list<HeeksObj*>& list = heeksCAD->GetMarkedList();
	for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++)
	{
		HeeksObj* object = *It;
		if(object->GetType() == SolidType || object->GetType() == StlSolidType)
		{
			solids.push_back(object->m_id);
		}
	}

	if(solids.size() == 0)return false;

	return true;
}

void ReselectSolids::Run()
{
	std::list<int> solids;
	heeksCAD->PickObjects(_("Select Solids"), MARKING_FILTER_SOLID | MARKING_FILTER_STL_SOLID);
	if(GetSolids( solids ))
	{
		heeksCAD->CreateUndoPoint();
		m_solids->clear();
		*m_solids = solids;
		((ObjList*)m_object)->Clear();
		m_object->ReloadPointers();
		heeksCAD->Changed();
	}
	else
	{
		wxMessageBox(_("Select cancelled. No solids were selected!"));
	}

	// get back to the operation's properties
	heeksCAD->ClearMarkedList();
	heeksCAD->Mark(m_object);
}

wxString GetIntListString(const std::list<int> &list)
{
	wxString str;
	int i = 0;
	for(std::list<int>::const_iterator It = list.begin(); It != list.end(); It++, i++)
	{
		if(i > 0)str.Append(_T(" "));
		if(i > 8)
		{
			str.Append(_T("..."));
			break;
		}
		str.Append(wxString::Format(_T("%d"), *It));
	}

	return str;
}

void AddSolidsProperties(std::list<Property *> *list, HeeksObj* object)
{
	std::list<int> solids;
	for(HeeksObj* child = object->GetFirstChild(); child; child = object->GetNextChild())
	{
		if(child->GetIDGroupType() == SolidType)solids.push_back(child->GetID());
	}
	if(solids.size() == 0)list->push_back(new PropertyString(_("solids"), _("None"), NULL));
	else if(solids.size() == 1)list->push_back(new PropertyInt(_("solid id"), solids.front(), NULL));
	else list->push_back(new PropertyString(_("solids"), GetIntListString(solids), NULL));
}

void AddSketchesProperties(std::list<Property *> *list, HeeksObj* object)
{
	std::list<int> sketches;
	for(HeeksObj* child = object->GetFirstChild(); child; child = object->GetNextChild())
	{
		if(child->GetIDGroupType() == SketchType)sketches.push_back(child->GetID());
	}
	if(sketches.size() == 0)list->push_back(new PropertyString(_("sketches"), _("None"), NULL));
	else if(sketches.size() == 1)list->push_back(new PropertyInt(_("sketch id"), sketches.front(), NULL));
	else list->push_back(new PropertyString(_("sketches"), GetIntListString(sketches), NULL));
}

<|endoftext|>


<commit_before>
// Resource.cpp
#include "Resource.h"

int Resource::nextID_ = 0;

// Database table for resources
Table *Resource::resource_table = new Table("Resources");
Table *Resource::resource_type_table = new Table("Resource Types");

Resource::Resource() {
  ID_ = nextID_++;
  MLOG(LEV_DEBUG4) << "Resource ID=" << ID_ << ", ptr=" << this << " created.";
}

Resource::~Resource() {
  MLOG(LEV_DEBUG4) << "Resource ID=" << ID_ << ", ptr=" << this << " deleted.";
}

bool Resource::checkEquality(rsrc_ptr other) {
  bool toRet;
  (this->checkQuality(other) && this->checkQuantityEqual(other)) ? toRet = true : toRet = false;
  return toRet;
}

// -------------------------------------------------------------
/*!
  output database related members
*/

// Specific resources
void Resource::define_table(){
  // declare the table columns
  column id("ID","INTEGER");
  column type("Type","INTEGER");
  column amt("Quantity","REAL");
  column creator("OriginatorID","INTEGER");
  // declare the table's primary key
  resource_table->setPrimaryKey(id);
  // add columns to the table
  resource_table->addColumn(id);
  resource_table->addColumn(type);
  resource_table->addColumn(amt);
  resource_table->addColumn(creator);
  // we've now defined the table
  resource_table->tableDefined();
}

void Resource::addToTable(){
  // if we haven't logged the resource type yet, do so
  if ( !this->is_resource_type_logged() ){
    Resource::logNewType();
    this->type_logged();
  }
  // if we haven't yet, define the table
  if ( !resource_table->defined() )
    Resource::define_table();

  // make a row
  // declare data
  data an_id( this->ID() ), a_type( (int)this->type() ),
    an_amt( this->quantity() ), a_creator( this->originatorID() );
  // declare entries
  entry id("ID",an_id), type("Type",a_type), amt("Quantity", an_amt), creator("OriginatorID",a_creator);
  // declare row
  row aRow;
  aRow.push_back(id), aRow.push_back(type), aRow.push_back(amt), aRow.push_back(creator);
  // add the row
  resource_table->addRow(aRow);
  // record this primary key
  pkref_.push_back(id);
}

// Generic Resource Types
void Resource::define_type_table(){
  // declare the table columns
  column type("Type","INTEGER");
  column type_name("Name","VARCHAR(128)");
  column units("Units","VARCHAR(32)");
  // declare the table's primary key
  resource_type_table->setPrimaryKey(type);
  // add columns to the table
  resource_type_table->addColumn(type);
  resource_type_table->addColumn(type_name);
  resource_type_table->addColumn(units);
  // we've now defined the table
  resource_type_table->tableDefined();
}

void Resource::logNewType(){
  // if we haven't yet, define the table
  if ( !resource_type_table->defined() )
    Resource::define_type_table();

  // make a row
  // declare data
  data a_type( (int)this->type() ), a_name( this->type_name() ), a_unit( this->units() );
  // declare entries
  entry type("Type",a_type), name("Name", a_name), units("Units", a_unit);
  // declare row
  row aRow;
  aRow.push_back(type), aRow.push_back(name), aRow.push_back(units);
  // add the row
  resource_type_table->addRow(aRow);
  // record this primary key
  type_pkref_.push_back(type);
}
<commit_msg>added foreign key to resource table<commit_after>
// Resource.cpp
#include "Resource.h"

int Resource::nextID_ = 0;

// Database table for resources
Table *Resource::resource_table = new Table("Resources");
Table *Resource::resource_type_table = new Table("Resource Types");

Resource::Resource() {
  ID_ = nextID_++;
  MLOG(LEV_DEBUG4) << "Resource ID=" << ID_ << ", ptr=" << this << " created.";
}

Resource::~Resource() {
  MLOG(LEV_DEBUG4) << "Resource ID=" << ID_ << ", ptr=" << this << " deleted.";
}

bool Resource::checkEquality(rsrc_ptr other) {
  bool toRet;
  (this->checkQuality(other) && this->checkQuantityEqual(other)) ? toRet = true : toRet = false;
  return toRet;
}

// -------------------------------------------------------------
/*!
  output database related members
*/

// Specific resources
void Resource::define_table(){
  // declare the table columns
  column id("ID","INTEGER");
  column type("Type","INTEGER");
  column amt("Quantity","REAL");
  column creator("OriginatorID","INTEGER");
  // declare the table's primary key
  resource_table->setPrimaryKey(id);
  // add columns to the table
  resource_table->addColumn(id);
  resource_table->addColumn(type);
  resource_table->addColumn(amt);
  resource_table->addColumn(creator);
  // add foreign keys
  foreign_key_ref *fkref;
  foreign_key *fk;
  key myk, theirk;
  //    Resource Types table foreign keys
  theirk.push_back("Type");
  fkref = new foreign_key_ref("Resource Types",theirk);
  //      the resource id
  myk.push_back("Type");
  fk = new foreign_key(myk, (*fkref) );
  resource_table->addForeignKey( (*fk) ); // type references Resource Types' type
  // we've now defined the table
  resource_table->tableDefined();
}

void Resource::addToTable(){
  // if we haven't logged the resource type yet, do so
  if ( !this->is_resource_type_logged() ){
    Resource::logNewType();
    this->type_logged();
  }
  // if we haven't yet, define the table
  if ( !resource_table->defined() )
    Resource::define_table();

  // make a row
  // declare data
  data an_id( this->ID() ), a_type( (int)this->type() ),
    an_amt( this->quantity() ), a_creator( this->originatorID() );
  // declare entries
  entry id("ID",an_id), type("Type",a_type), amt("Quantity", an_amt), creator("OriginatorID",a_creator);
  // declare row
  row aRow;
  aRow.push_back(id), aRow.push_back(type), aRow.push_back(amt), aRow.push_back(creator);
  // add the row
  resource_table->addRow(aRow);
  // record this primary key
  pkref_.push_back(id);
}

// Generic Resource Types
void Resource::define_type_table(){
  // declare the table columns
  column type("Type","INTEGER");
  column type_name("Name","VARCHAR(128)");
  column units("Units","VARCHAR(32)");
  // declare the table's primary key
  resource_type_table->setPrimaryKey(type);
  // add columns to the table
  resource_type_table->addColumn(type);
  resource_type_table->addColumn(type_name);
  resource_type_table->addColumn(units);
  // we've now defined the table
  resource_type_table->tableDefined();
}

void Resource::logNewType(){
  // if we haven't yet, define the table
  if ( !resource_type_table->defined() )
    Resource::define_type_table();

  // make a row
  // declare data
  data a_type( (int)this->type() ), a_name( this->type_name() ), a_unit( this->units() );
  // declare entries
  entry type("Type",a_type), name("Name", a_name), units("Units", a_unit);
  // declare row
  row aRow;
  aRow.push_back(type), aRow.push_back(name), aRow.push_back(units);
  // add the row
  resource_type_table->addRow(aRow);
  // record this primary key
  type_pkref_.push_back(type);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/search/search.h>
#include <pcl/search/kdtree.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/filters/passthrough.h>
#include <pcl/segmentation/region_growing_rgb.h>

int
main (int argc, char** argv)
{
  pcl::search::Search <pcl::PointXYZRGB>::Ptr tree = boost::shared_ptr<pcl::search::Search<pcl::PointXYZRGB> > (new pcl::search::KdTree<pcl::PointXYZRGB>);

  pcl::PointCloud <pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud <pcl::PointXYZRGB>);
  if ( pcl::io::loadPCDFile <pcl::PointXYZRGB> ("region_growing_rgb_tutorial.pcd", *cloud) == -1 )
  {
    std::cout << "Cloud reading failed." << std::endl;
    return (-1);
  }

  pcl::IndicesPtr indices (new std::vector <int>);
  pcl::PassThrough<pcl::PointXYZ> pass;
  pass.setInputCloud (cloud);
  pass.setFilterFieldName ("z");
  pass.setFilterLimits (0.0, 1.0);
  pass.filter (*indices);

  pcl::RegionGrowingRGB<pcl::PointXYZRGB> reg;
  reg.setInputCloud (cloud);
  reg.setIndices (indices);
  reg.setSearchMethod (tree);
  reg.setDistanceThreshold (10);
  reg.setPointColorThreshold (6);
  reg.setRegionColorThreshold (5);
  reg.setMinClusterSize (600);

  std::vector <pcl::PointIndices> clusters;
  reg.extract (clusters);

  pcl::PointCloud <pcl::PointXYZRGB>::Ptr colored_cloud = reg.getColoredCloud ();
  pcl::visualization::CloudViewer viewer ("Cluster viewer");
  viewer.showCloud(colored_cloud);
  while (!viewer.wasStopped ())
  {
  }

  return (0);
}<commit_msg>fixed a compiler error<commit_after>#include <iostream>
#include <vector>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/search/search.h>
#include <pcl/search/kdtree.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/filters/passthrough.h>
#include <pcl/segmentation/region_growing_rgb.h>

int
main (int argc, char** argv)
{
  pcl::search::Search <pcl::PointXYZRGB>::Ptr tree = boost::shared_ptr<pcl::search::Search<pcl::PointXYZRGB> > (new pcl::search::KdTree<pcl::PointXYZRGB>);

  pcl::PointCloud <pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud <pcl::PointXYZRGB>);
  if ( pcl::io::loadPCDFile <pcl::PointXYZRGB> ("region_growing_rgb_tutorial.pcd", *cloud) == -1 )
  {
    std::cout << "Cloud reading failed." << std::endl;
    return (-1);
  }

  pcl::IndicesPtr indices (new std::vector <int>);
  pcl::PassThrough<pcl::PointXYZRGB> pass;
  pass.setInputCloud (cloud);
  pass.setFilterFieldName ("z");
  pass.setFilterLimits (0.0, 1.0);
  pass.filter (*indices);

  pcl::RegionGrowingRGB<pcl::PointXYZRGB> reg;
  reg.setInputCloud (cloud);
  reg.setIndices (indices);
  reg.setSearchMethod (tree);
  reg.setDistanceThreshold (10);
  reg.setPointColorThreshold (6);
  reg.setRegionColorThreshold (5);
  reg.setMinClusterSize (600);

  std::vector <pcl::PointIndices> clusters;
  reg.extract (clusters);

  pcl::PointCloud <pcl::PointXYZRGB>::Ptr colored_cloud = reg.getColoredCloud ();
  pcl::visualization::CloudViewer viewer ("Cluster viewer");
  viewer.showCloud (colored_cloud);
  while (!viewer.wasStopped ())
  {
    boost::this_thread::sleep (boost::posix_time::microseconds (100));
  }

  return (0);
}
<|endoftext|>