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

//ROS libraries
#include <tf/transform_datatypes.h>

//ROS messages
#include <std_msgs/Float32.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Quaternion.h>
#include <geometry_msgs/QuaternionStamped.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/Range.h>

//Package include
#include <usbSerial.h>

using namespace std;

//aBridge functions
void cmdHandler(const geometry_msgs::Twist::ConstPtr& message);
void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle);
void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle);
void serialActivityTimer(const ros::TimerEvent& e);
void publishRosTopics();
void parseData(string data);

//Globals
geometry_msgs::QuaternionStamped fingerAngle;
geometry_msgs::QuaternionStamped wristAngle;
sensor_msgs::Imu imu;
nav_msgs::Odometry odom;
sensor_msgs::Range sonarLeft;
sensor_msgs::Range sonarCenter;
sensor_msgs::Range sonarRight;
USBSerial usb;
const int baud = 115200;
char dataCmd[] = "d\n";
char moveCmd[16];
char host[128];
char delimiter = ',';
vector<string> dataSet;
float linearSpeed = 0.;
float turnSpeed = 0.;
const float deltaTime = 0.1;

//Publishers
ros::Publisher fingerAnglePublish;
ros::Publisher wristAnglePublish;
ros::Publisher imuPublish;
ros::Publisher odomPublish;
ros::Publisher sonarLeftPublish;
ros::Publisher sonarCenterPublish;
ros::Publisher sonarRightPublish;

//Subscribers
ros::Subscriber velocitySubscriber;
ros::Subscriber fingerAngleSubscriber;
ros::Subscriber wristAngleSubscriber;

//Timers
ros::Timer publishTimer;

int main(int argc, char **argv) {

    gethostname(host, sizeof (host));
    string hostname(host);
    string publishedName;
    ros::init(argc, argv, (hostname + "_ABRIDGE"));

    ros::NodeHandle param("~");
    string devicePath;
    param.param("device", devicePath, string("/dev/ttyUSB0"));
    usb.openUSBPort(devicePath, baud);

    sleep(5);

    ros::NodeHandle aNH;

    if (argc >= 2) {
        publishedName = argv[1];
        cout << "Welcome to the world of tomorrow " << publishedName << "!  ABridge module started." << endl;
    } else {
        publishedName = hostname;
        cout << "No Name Selected. Default is: " << publishedName << endl;
    }

    fingerAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/fingerAngle/prev_cmd"), 10);
    wristAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/wristAngle/prev_cmd"), 10);
    imuPublish = aNH.advertise<sensor_msgs::Imu>((publishedName + "/imu"), 10);
    odomPublish = aNH.advertise<nav_msgs::Odometry>((publishedName + "/odom"), 10);
    sonarLeftPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarLeft"), 10);
    sonarCenterPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarCenter"), 10);
    sonarRightPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarRight"), 10);

    velocitySubscriber = aNH.subscribe((publishedName + "/velocity"), 10, cmdHandler);
    fingerAngleSubscriber = aNH.subscribe((publishedName + "/fingerAngle/cmd"), 1, fingerAngleHandler);
    wristAngleSubscriber = aNH.subscribe((publishedName + "/wristAngle/cmd"), 1, wristAngleHandler);

    publishTimer = aNH.createTimer(ros::Duration(deltaTime), serialActivityTimer);

    imu.header.frame_id = publishedName+"/base_link";

    odom.header.frame_id = publishedName+"/odom";
    odom.child_frame_id = publishedName+"/base_link";

    ros::spin();

    return EXIT_SUCCESS;
}

void cmdHandler(const geometry_msgs::Twist::ConstPtr& message) {
    // remove artificial factor that was multiplied for simulation. this scales it back down to -1.0 to +1.0
  linearSpeed = (message->linear.x); // / 1.5;
  turnSpeed = (message->angular.z); // / 8;

    if (linearSpeed != 0.) {
        sprintf(moveCmd, "m,%d\n", (int) (linearSpeed * 255));
        usb.sendData(moveCmd);
    } else if (turnSpeed != 0.) {
        sprintf(moveCmd, "t,%d\n", (int) (turnSpeed * 255));
        usb.sendData(moveCmd);
    } else {
        sprintf(moveCmd, "s\n");
        usb.sendData(moveCmd);
    }

    memset(&moveCmd, '\0', sizeof (moveCmd));
}

// The finger and wrist handlers receive gripper angle commands in floating point
// radians, write them to a string and send that to the arduino
// for processing.
void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle) {
  char cmd[16]={'\0'};

  // Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small
  if (angle->data < 0.01) {
    // 'f' indicates this is a finger command to the arduino
    sprintf(cmd, "f,0\n");
  } else {
    sprintf(cmd, "f,%.4g\n", angle->data);
  }
  usb.sendData(cmd);
  memset(&cmd, '\0', sizeof (cmd));
}

void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle) {
    char cmd[16]={'\0'};

    // Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small
  if (angle->data < 0.01) {
    // 'w' indicates this is a wrist command to the arduino
    sprintf(cmd, "w,0\n");
  } else {
    sprintf(cmd, "w,%.4g\n", angle->data);
  }
  usb.sendData(cmd);
  memset(&cmd, '\0', sizeof (cmd));
}

void serialActivityTimer(const ros::TimerEvent& e) {
    usb.sendData(dataCmd);
    parseData(usb.readData());
    publishRosTopics();
}

void publishRosTopics() {
    fingerAnglePublish.publish(fingerAngle);
    wristAnglePublish.publish(wristAngle);
    imuPublish.publish(imu);
    odomPublish.publish(odom);
    sonarLeftPublish.publish(sonarLeft);
    sonarCenterPublish.publish(sonarCenter);
    sonarRightPublish.publish(sonarRight);
}

void parseData(string str) {
    istringstream oss(str);
    string sentence;

    while (getline(oss, sentence, '\n')) {
		istringstream wss(sentence);
		string word;

		vector<string> dataSet;
		while (getline(wss, word, ',')) {
			dataSet.push_back(word);
		}

		if (dataSet.size() >= 3 && dataSet.at(1) == "1") {

			if (dataSet.at(0) == "GRF") {
				fingerAngle.header.stamp = ros::Time::now();
				fingerAngle.quaternion = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(2).c_str()), 0.0, 0.0);
			}
			else if (dataSet.at(0) == "GRW") {
				wristAngle.header.stamp = ros::Time::now();
				wristAngle.quaternion = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(2).c_str()), 0.0, 0.0);
			}
			else if (dataSet.at(0) == "IMU") {
				imu.header.stamp = ros::Time::now();
				imu.linear_acceleration.x = atof(dataSet.at(2).c_str());
				imu.linear_acceleration.y = atof(dataSet.at(3).c_str());
				imu.linear_acceleration.z = atof(dataSet.at(4).c_str());
				imu.angular_velocity.x = atof(dataSet.at(5).c_str());
				imu.angular_velocity.y = atof(dataSet.at(6).c_str());
				imu.angular_velocity.z = atof(dataSet.at(7).c_str());
				imu.orientation = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(8).c_str()), atof(dataSet.at(9).c_str()), atof(dataSet.at(10).c_str()));
			}
			else if (dataSet.at(0) == "ODOM") {
				odom.header.stamp = ros::Time::now();
				odom.pose.pose.position.x += atof(dataSet.at(2).c_str()) / 100.0;
				odom.pose.pose.position.y += atof(dataSet.at(3).c_str()) / 100.0;
				odom.pose.pose.position.z = 0.0;
				odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(atof(dataSet.at(4).c_str()));
				odom.twist.twist.linear.x = atof(dataSet.at(5).c_str()) / 100.0;
				odom.twist.twist.linear.y = atof(dataSet.at(6).c_str()) / 100.0;
				odom.twist.twist.angular.z = atof(dataSet.at(7).c_str());
			}
			else if (dataSet.at(0) == "USL") {
				sonarLeft.header.stamp = ros::Time::now();
				sonarLeft.range = atof(dataSet.at(2).c_str()) / 100.0;
			}
			else if (dataSet.at(0) == "USC") {
				sonarCenter.header.stamp = ros::Time::now();
				sonarCenter.range = atof(dataSet.at(2).c_str()) / 100.0;
			}
			else if (dataSet.at(0) == "USR") {
				sonarRight.header.stamp = ros::Time::now();
				sonarRight.range = atof(dataSet.at(2).c_str()) / 100.0;
			}

		}
	}
}
<commit_msg>Delete unused variables from abridge package<commit_after>#include <ros/ros.h>

//ROS libraries
#include <tf/transform_datatypes.h>

//ROS messages
#include <std_msgs/Float32.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Quaternion.h>
#include <geometry_msgs/QuaternionStamped.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/Range.h>

//Package include
#include <usbSerial.h>

using namespace std;

//aBridge functions
void cmdHandler(const geometry_msgs::Twist::ConstPtr& message);
void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle);
void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle);
void serialActivityTimer(const ros::TimerEvent& e);
void publishRosTopics();
void parseData(string data);

//Globals
geometry_msgs::QuaternionStamped fingerAngle;
geometry_msgs::QuaternionStamped wristAngle;
sensor_msgs::Imu imu;
nav_msgs::Odometry odom;
sensor_msgs::Range sonarLeft;
sensor_msgs::Range sonarCenter;
sensor_msgs::Range sonarRight;
USBSerial usb;
const int baud = 115200;
char dataCmd[] = "d\n";
char moveCmd[16];
char host[128];
float linearSpeed = 0.;
float turnSpeed = 0.;
const float deltaTime = 0.1;

//Publishers
ros::Publisher fingerAnglePublish;
ros::Publisher wristAnglePublish;
ros::Publisher imuPublish;
ros::Publisher odomPublish;
ros::Publisher sonarLeftPublish;
ros::Publisher sonarCenterPublish;
ros::Publisher sonarRightPublish;

//Subscribers
ros::Subscriber velocitySubscriber;
ros::Subscriber fingerAngleSubscriber;
ros::Subscriber wristAngleSubscriber;

//Timers
ros::Timer publishTimer;

int main(int argc, char **argv) {

    gethostname(host, sizeof (host));
    string hostname(host);
    string publishedName;
    ros::init(argc, argv, (hostname + "_ABRIDGE"));

    ros::NodeHandle param("~");
    string devicePath;
    param.param("device", devicePath, string("/dev/ttyUSB0"));
    usb.openUSBPort(devicePath, baud);

    sleep(5);

    ros::NodeHandle aNH;

    if (argc >= 2) {
        publishedName = argv[1];
        cout << "Welcome to the world of tomorrow " << publishedName << "!  ABridge module started." << endl;
    } else {
        publishedName = hostname;
        cout << "No Name Selected. Default is: " << publishedName << endl;
    }

    fingerAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/fingerAngle/prev_cmd"), 10);
    wristAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/wristAngle/prev_cmd"), 10);
    imuPublish = aNH.advertise<sensor_msgs::Imu>((publishedName + "/imu"), 10);
    odomPublish = aNH.advertise<nav_msgs::Odometry>((publishedName + "/odom"), 10);
    sonarLeftPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarLeft"), 10);
    sonarCenterPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarCenter"), 10);
    sonarRightPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarRight"), 10);

    velocitySubscriber = aNH.subscribe((publishedName + "/velocity"), 10, cmdHandler);
    fingerAngleSubscriber = aNH.subscribe((publishedName + "/fingerAngle/cmd"), 1, fingerAngleHandler);
    wristAngleSubscriber = aNH.subscribe((publishedName + "/wristAngle/cmd"), 1, wristAngleHandler);

    publishTimer = aNH.createTimer(ros::Duration(deltaTime), serialActivityTimer);

    imu.header.frame_id = publishedName+"/base_link";

    odom.header.frame_id = publishedName+"/odom";
    odom.child_frame_id = publishedName+"/base_link";

    ros::spin();

    return EXIT_SUCCESS;
}

void cmdHandler(const geometry_msgs::Twist::ConstPtr& message) {
    // remove artificial factor that was multiplied for simulation. this scales it back down to -1.0 to +1.0
  linearSpeed = (message->linear.x); // / 1.5;
  turnSpeed = (message->angular.z); // / 8;

    if (linearSpeed != 0.) {
        sprintf(moveCmd, "m,%d\n", (int) (linearSpeed * 255));
        usb.sendData(moveCmd);
    } else if (turnSpeed != 0.) {
        sprintf(moveCmd, "t,%d\n", (int) (turnSpeed * 255));
        usb.sendData(moveCmd);
    } else {
        sprintf(moveCmd, "s\n");
        usb.sendData(moveCmd);
    }

    memset(&moveCmd, '\0', sizeof (moveCmd));
}

// The finger and wrist handlers receive gripper angle commands in floating point
// radians, write them to a string and send that to the arduino
// for processing.
void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle) {
  char cmd[16]={'\0'};

  // Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small
  if (angle->data < 0.01) {
    // 'f' indicates this is a finger command to the arduino
    sprintf(cmd, "f,0\n");
  } else {
    sprintf(cmd, "f,%.4g\n", angle->data);
  }
  usb.sendData(cmd);
  memset(&cmd, '\0', sizeof (cmd));
}

void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle) {
    char cmd[16]={'\0'};

    // Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small
  if (angle->data < 0.01) {
    // 'w' indicates this is a wrist command to the arduino
    sprintf(cmd, "w,0\n");
  } else {
    sprintf(cmd, "w,%.4g\n", angle->data);
  }
  usb.sendData(cmd);
  memset(&cmd, '\0', sizeof (cmd));
}

void serialActivityTimer(const ros::TimerEvent& e) {
    usb.sendData(dataCmd);
    parseData(usb.readData());
    publishRosTopics();
}

void publishRosTopics() {
    fingerAnglePublish.publish(fingerAngle);
    wristAnglePublish.publish(wristAngle);
    imuPublish.publish(imu);
    odomPublish.publish(odom);
    sonarLeftPublish.publish(sonarLeft);
    sonarCenterPublish.publish(sonarCenter);
    sonarRightPublish.publish(sonarRight);
}

void parseData(string str) {
    istringstream oss(str);
    string sentence;

    while (getline(oss, sentence, '\n')) {
		istringstream wss(sentence);
		string word;

		vector<string> dataSet;
		while (getline(wss, word, ',')) {
			dataSet.push_back(word);
		}

		if (dataSet.size() >= 3 && dataSet.at(1) == "1") {

			if (dataSet.at(0) == "GRF") {
				fingerAngle.header.stamp = ros::Time::now();
				fingerAngle.quaternion = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(2).c_str()), 0.0, 0.0);
			}
			else if (dataSet.at(0) == "GRW") {
				wristAngle.header.stamp = ros::Time::now();
				wristAngle.quaternion = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(2).c_str()), 0.0, 0.0);
			}
			else if (dataSet.at(0) == "IMU") {
				imu.header.stamp = ros::Time::now();
				imu.linear_acceleration.x = atof(dataSet.at(2).c_str());
				imu.linear_acceleration.y = atof(dataSet.at(3).c_str());
				imu.linear_acceleration.z = atof(dataSet.at(4).c_str());
				imu.angular_velocity.x = atof(dataSet.at(5).c_str());
				imu.angular_velocity.y = atof(dataSet.at(6).c_str());
				imu.angular_velocity.z = atof(dataSet.at(7).c_str());
				imu.orientation = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(8).c_str()), atof(dataSet.at(9).c_str()), atof(dataSet.at(10).c_str()));
			}
			else if (dataSet.at(0) == "ODOM") {
				odom.header.stamp = ros::Time::now();
				odom.pose.pose.position.x += atof(dataSet.at(2).c_str()) / 100.0;
				odom.pose.pose.position.y += atof(dataSet.at(3).c_str()) / 100.0;
				odom.pose.pose.position.z = 0.0;
				odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(atof(dataSet.at(4).c_str()));
				odom.twist.twist.linear.x = atof(dataSet.at(5).c_str()) / 100.0;
				odom.twist.twist.linear.y = atof(dataSet.at(6).c_str()) / 100.0;
				odom.twist.twist.angular.z = atof(dataSet.at(7).c_str());
			}
			else if (dataSet.at(0) == "USL") {
				sonarLeft.header.stamp = ros::Time::now();
				sonarLeft.range = atof(dataSet.at(2).c_str()) / 100.0;
			}
			else if (dataSet.at(0) == "USC") {
				sonarCenter.header.stamp = ros::Time::now();
				sonarCenter.range = atof(dataSet.at(2).c_str()) / 100.0;
			}
			else if (dataSet.at(0) == "USR") {
				sonarRight.header.stamp = ros::Time::now();
				sonarRight.range = atof(dataSet.at(2).c_str()) / 100.0;
			}

		}
	}
}
<|endoftext|>


<commit_before>/*
Copyright (C) 2016 - Gbor "Razzie" Grzsny

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
*/

#pragma once

#include <array>
#include <cstdint>
#include <iosfwd>
#include <random>
#include <type_traits>

namespace raz
{
	/*
	 * RandomGenerator is based on the xorshift128+ algorithm
	 * https://en.wikipedia.org/wiki/Xorshift
	 */
	class RandomGenerator
	{
	public:
		typedef uint64_t result_type;
		static constexpr result_type default_seed = 1;

		RandomGenerator(result_type value = default_seed)
		{
			seed(value);
		}

		template<class Sseq>
		RandomGenerator(Sseq& seq)
		{
			seed(seq);
		}

		RandomGenerator(const RandomGenerator& other) :
			m_state(other.m_state)
		{
		}

		RandomGenerator& operator=(const RandomGenerator& other)
		{
			m_state = other.m_state;
			return *this;
		}

		void seed(result_type value = default_seed)
		{
			m_state[0] = value;
			m_state[1] = 0;
		}

		template<class Sseq>
		void seed(Sseq& seq)
		{
			seq.generate(m_state.begin(), m_state.end());
		}

		result_type operator()()
		{
			uint64_t x = m_state[0];
			uint64_t const y = m_state[1];
			m_state[0] = y;
			x ^= x << 23; // a
			m_state[1] = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c
			return (m_state[1] + y);
		}

		void discard(unsigned long long z)
		{
			for (unsigned long long i = 0; i < z; ++i)
			{
				uint64_t x = m_state[0];
				uint64_t const y = m_state[1];
				m_state[0] = y;
				x ^= x << 23; // a
				m_state[1] = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c
			}
		}

		bool operator==(const RandomGenerator& other) const
		{
			return (m_state == other.m_state);
		}

		bool operator!=(const RandomGenerator& other) const
		{
			return (m_state != other.m_state);
		}

		template<class Serializer>
		void operator()(Serializer& serializer)
		{
			serializer(m_state[0])(m_state[1]);
		}

#pragma push_macro("__raz")
#undef min
#undef max
		static constexpr result_type min()
		{
			return (0);
		}

		static constexpr result_type max()
		{
			return ((result_type)-1);
		}
#pragma pop_macro("__raz")

		template<class CharT, class Traits>
		friend std::basic_ostream<CharT, Traits>&
			operator<<(std::basic_ostream<CharT, Traits>& ost, const RandomGenerator& gen)
		{
			return (ost << gen.m_state[0] << " " << gen.m_state[1]);
		}

		template<class CharT, class Traits>
		friend std::basic_istream<CharT, Traits>&
			operator>>(std::basic_istream<CharT, Traits>& ist, RandomGenerator& gen)
		{
			return (ist >> gen.m_state[0] >> gen.m_state[1]);
		}

	private:
		std::array<uint64_t, 2> m_state;
	};

	template<class Generator>
	class RandomDistributor
	{
	public:
		RandomDistributor(Generator& generator) :
			m_generator(&generator)
		{
		}

		RandomDistributor(const RandomDistributor& other) :
			m_generator(other.m_generator)
		{
		}

		RandomDistributor& operator=(const RandomDistributor& other) = default;

		template<class IntType>
		std::enable_if_t<std::is_integral<IntType>::value, IntType>
			operator()(IntType min_value, IntType max_value)
		{
			std::uniform_int_distribution<IntType> dist(min_value, max_value);
			return dist(*m_generator);
		}

		template<class RealType>
		std::enable_if_t<std::is_floating_point<RealType>::value, RealType>
			operator()(RealType min_value, RealType max_value)
		{
			std::uniform_real_distribution<RealType> dist(min_value, max_value);
			return dist(*m_generator);
		}

	private:
		Generator* m_generator;
	};

	class Random : public RandomGenerator, public RandomDistributor<RandomGenerator>
	{
	public:
		Random(result_type value = default_seed) :
			RandomGenerator(value),
			RandomDistributor<RandomGenerator>(*this)
		{
		}

		template<class Sseq>
		Random(Sseq& seq) :
			RandomGenerator(seq),
			RandomDistributor<RandomGenerator>(*this)
		{
		}

		Random(const RandomGenerator& gen) :
			RandomGenerator(gen),
			RandomDistributor<RandomGenerator>(*this)
		{
		}

		Random& operator=(const Random& other)
		{
			RandomGenerator::operator=(other);
			return *this;
		}
	};
}
<commit_msg>Changed copy assignment operator of Random<commit_after>/*
Copyright (C) 2016 - Gbor "Razzie" Grzsny

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
*/

#pragma once

#include <array>
#include <cstdint>
#include <iosfwd>
#include <random>
#include <type_traits>

namespace raz
{
	/*
	 * RandomGenerator is based on the xorshift128+ algorithm
	 * https://en.wikipedia.org/wiki/Xorshift
	 */
	class RandomGenerator
	{
	public:
		typedef uint64_t result_type;
		static constexpr result_type default_seed = 1;

		RandomGenerator(result_type value = default_seed)
		{
			seed(value);
		}

		template<class Sseq>
		RandomGenerator(Sseq& seq)
		{
			seed(seq);
		}

		RandomGenerator(const RandomGenerator& other) :
			m_state(other.m_state)
		{
		}

		RandomGenerator& operator=(const RandomGenerator& other)
		{
			m_state = other.m_state;
			return *this;
		}

		void seed(result_type value = default_seed)
		{
			m_state[0] = value;
			m_state[1] = 0;
		}

		template<class Sseq>
		void seed(Sseq& seq)
		{
			seq.generate(m_state.begin(), m_state.end());
		}

		result_type operator()()
		{
			uint64_t x = m_state[0];
			uint64_t const y = m_state[1];
			m_state[0] = y;
			x ^= x << 23; // a
			m_state[1] = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c
			return (m_state[1] + y);
		}

		void discard(unsigned long long z)
		{
			for (unsigned long long i = 0; i < z; ++i)
			{
				uint64_t x = m_state[0];
				uint64_t const y = m_state[1];
				m_state[0] = y;
				x ^= x << 23; // a
				m_state[1] = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c
			}
		}

		bool operator==(const RandomGenerator& other) const
		{
			return (m_state == other.m_state);
		}

		bool operator!=(const RandomGenerator& other) const
		{
			return (m_state != other.m_state);
		}

		template<class Serializer>
		void operator()(Serializer& serializer)
		{
			serializer(m_state[0])(m_state[1]);
		}

#pragma push_macro("__raz")
#undef min
#undef max
		static constexpr result_type min()
		{
			return (0);
		}

		static constexpr result_type max()
		{
			return ((result_type)-1);
		}
#pragma pop_macro("__raz")

		template<class CharT, class Traits>
		friend std::basic_ostream<CharT, Traits>&
			operator<<(std::basic_ostream<CharT, Traits>& ost, const RandomGenerator& gen)
		{
			return (ost << gen.m_state[0] << " " << gen.m_state[1]);
		}

		template<class CharT, class Traits>
		friend std::basic_istream<CharT, Traits>&
			operator>>(std::basic_istream<CharT, Traits>& ist, RandomGenerator& gen)
		{
			return (ist >> gen.m_state[0] >> gen.m_state[1]);
		}

	private:
		std::array<uint64_t, 2> m_state;
	};

	template<class Generator>
	class RandomDistributor
	{
	public:
		RandomDistributor(Generator& generator) :
			m_generator(&generator)
		{
		}

		RandomDistributor(const RandomDistributor& other) :
			m_generator(other.m_generator)
		{
		}

		RandomDistributor& operator=(const RandomDistributor& other) = default;

		template<class IntType>
		std::enable_if_t<std::is_integral<IntType>::value, IntType>
			operator()(IntType min_value, IntType max_value)
		{
			std::uniform_int_distribution<IntType> dist(min_value, max_value);
			return dist(*m_generator);
		}

		template<class RealType>
		std::enable_if_t<std::is_floating_point<RealType>::value, RealType>
			operator()(RealType min_value, RealType max_value)
		{
			std::uniform_real_distribution<RealType> dist(min_value, max_value);
			return dist(*m_generator);
		}

	private:
		Generator* m_generator;
	};

	class Random : public RandomGenerator, public RandomDistributor<RandomGenerator>
	{
	public:
		Random(result_type value = default_seed) :
			RandomGenerator(value),
			RandomDistributor<RandomGenerator>(*this)
		{
		}

		template<class Sseq>
		Random(Sseq& seq) :
			RandomGenerator(seq),
			RandomDistributor<RandomGenerator>(*this)
		{
		}

		Random(const RandomGenerator& gen) :
			RandomGenerator(gen),
			RandomDistributor<RandomGenerator>(*this)
		{
		}

		Random& operator=(const RandomGenerator& other)
		{
			RandomGenerator::operator=(other);
			return *this;
		}
	};
}
<|endoftext|>


<commit_before>/*
Copyright (C) Gbor "Razzie" Grzsny

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
*/

#pragma once

#include <iosfwd>
#include <locale>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>

namespace raz
{
	template<class T>
	class HasStreamInserter
	{
		template<class U>
		static constexpr auto test() -> decltype(bool(std::declval<std::ostream&>() << std::declval<const U&>()))
		{
			return true;
		}

		template<class U>
		static constexpr bool test(...)
		{
			return false;
		}

	public:
		constexpr static bool value = test<T>();
	};

	template<class T>
	class HasStreamExtractor
	{
		template<class U>
		static constexpr auto test() -> decltype(bool(std::declval<std::ostream&>() >> std::declval<U&>()))
		{
			return true;
		}

		template<class U>
		static constexpr bool test(...)
		{
			return false;
		}

	public:
		constexpr static bool value = test<T>();
	};

	struct __FallbackType
	{
		template<class T>
		__FallbackType(const T&) : type(&typeid(T))
		{
		}

		friend std::ostream& operator<< (std::ostream& os, const __FallbackType& t)
		{
			os << t.type->name();
			return os;
		}

		friend std::istream& operator>> (std::istream& is, __FallbackType&)
		{
			return is;
		}

		const std::type_info* type;
	};

	template<class T>
	std::conditional_t<HasStreamInserter<T>::value, const T&, __FallbackType> insert(const T& t)
	{
		return { t };
	}

	template<class T>
	std::conditional_t<HasStreamExtractor<T>::value, T&, __FallbackType> extract(T& t)
	{
		return { t };
	}

	template<class To, class From>
	To lexical_cast(const From& from)
	{
		To to;
		std::sstream ss;
		ss << from;
		ss >> to;
		return to;
	}

	template<class T>
	class StreamManipulator
	{
	public:
		typedef std::ios&(*Manipulator)(std::ios&, T);

		explicit StreamManipulator(Manipulator m, T t) :
			m_manip(m), m_value(t)
		{
		}

		friend std::ios& operator<< (std::ios& io, const StreamManipulator<T>& m)
		{
			return m.m_manip(io, m.m_value);
		}

	private:
		Manipulator m_manip;
		T m_value;
	};

	template<class T>
	class IstreamManipulator
	{
	public:
		typedef std::istream&(*Manipulator)(std::istream&, T);

		explicit IstreamManipulator(Manipulator m, T t) :
			m_manip(m), m_value(t)
		{
		}

		friend std::istream& operator<< (std::istream& io, const IstreamManipulator<T>& m)
		{
			return m.m_manip(io, m.m_value);
		}

	private:
		Manipulator m_manip;
		T m_value;
	};

	template<class T>
	class OstreamManipulator
	{
	public:
		typedef std::ostream&(*Manipulator)(std::ostream&, T);

		explicit OstreamManipulator(Manipulator m, T t) :
			m_manip(m), m_value(t)
		{
		}

		friend std::ostream& operator<< (std::ostream& io, const OstreamManipulator<T>& m)
		{
			return m.m_manip(io, m.m_value);
		}

	private:
		Manipulator m_manip;
		T m_value;
	};

	template<class T>
	OstreamManipulator<T> hex(T t)
	{
		OstreamManipulator<T>::Manipulator m =
			[](std::ostream& o, T t) -> std::ostream&
			{
				const char map[] = "0123456789abcdef";
				const unsigned char* ptr = reinterpret_cast<const unsigned char*>(&t);
				for (size_t i = 0; i < sizeof(T); ++i)
				{
					unsigned first = ptr[i] / 16;
					unsigned second = ptr[i] - (first * 16);
					o << map[first] << map[second];
				}
				return o;
			};

		return OstreamManipulator<T>(m, t);
	}

	inline OstreamManipulator<const char*> format(const char* f)
	{
		OstreamManipulator<const char*>::Manipulator m =
			[](std::ostream& os, const char* fmt) -> std::ostream&
			{
				std::locale& loc = os.getloc();
				int i = 0;
				while (fmt[i] != 0)
				{
					if (fmt[i] != '%')
					{
						os << fmt[i];
						i++;
					}
					else
					{
						i++;
						if (fmt[i] == '%')
						{
							os << fmt[i];
							i++;
						}
						else
						{
							bool ok = true;
							int istart = i;
							bool more = true;
							int width = 0;
							int precision = 6;
							std::ios_base::fmtflags flags;
							char fill = ' ';
							bool alternate = false;
							while (more)
							{
								switch (fmt[i])
								{
								case '+':
									flags |= std::ios::showpos;
									break;
								case '-':
									flags |= std::ios::left;
									break;
								case '0':
									flags |= std::ios::internal;
									fill = '0';
									break;
								case '#':
									alternate = true;
									break;
								case ' ':
									break;
								default:
									more = false;
									break;
								}
								if (more) i++;
							}
							if (std::isdigit(fmt[i], loc))
							{
								width = std::atoi(fmt + i);
								do i++;
								while (std::isdigit(fmt[i], loc));
							}
							if (fmt[i] == '.')
							{
								i++;
								precision = std::atoi(fmt + i);
								while (std::isdigit(fmt[i], loc)) i++;
							}
							switch (fmt[i])
							{
							case 'd':
								flags |= std::ios::dec;
								break;
							case 'x':
								flags |= std::ios::hex;
								if (alternate) flags |= std::ios::showbase;
								break;
							case 'X':
								flags |= std::ios::hex | std::ios::uppercase;
								if (alternate) flags |= std::ios::showbase;
								break;
							case 'o':
								flags |= std::ios::hex;
								if (alternate) flags |= std::ios::showbase;
								break;
							case 'f':
								flags |= std::ios::fixed;
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'e':
								flags |= std::ios::scientific;
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'E':
								flags |= std::ios::scientific | std::ios::uppercase;
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'g':
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'G':
								flags |= std::ios::uppercase;
								if (alternate) flags |= std::ios::showpoint;
								break;
							default:
								ok = false;
								break;
							}
							i++;
							if (fmt[i] != 0) ok = false;
							if (ok)
							{
								os.unsetf(std::ios::adjustfield | std::ios::basefield |
									std::ios::floatfield);
								os.setf(flags);
								os.width(width);
								os.precision(precision);
								os.fill(fill);
							}
							else i = istart;
						}
					}
				}
				return os;
			};

		return OstreamManipulator<const char*>(m, f);
	}

	inline IstreamManipulator<char> delimiter(char d)
	{
		struct CustomLocale : std::ctype<char>
		{
			std::ctype_base::mask m_rc[table_size];

			CustomLocale(char delim) :
				std::ctype<char>(get_table(static_cast<unsigned char>(delim)))
			{
			}

			const std::ctype_base::mask* get_table(unsigned char delim)
			{
				memset(m_rc, 0, sizeof(std::ctype_base::mask) * table_size);
				m_rc[delim] = std::ctype_base::space;
				m_rc['\n'] = std::ctype_base::space;
				return &m_rc[0];
			}
		};

		IstreamManipulator<char>::Manipulator m =
			[](std::istream& i, char d) -> std::istream&
			{
				i.imbue(std::locale(i.getloc(), new CustomLocale(d)));
				return i;
			};

		return IstreamManipulator<char>(m, d);
	}

	inline IstreamManipulator<char> next(char d)
	{
		IstreamManipulator<char>::Manipulator m =
			[](std::istream& i, char d) -> std::istream&
			{
#pragma push_macro("__raz")
#undef max
				i.ignore(std::numeric_limits<std::streamsize>::max(), d);
#pragma pop_macro("__raz")
				return i;
			};

		return IstreamManipulator<char>(m, d);
	}

	inline std::istream& nextLine(std::istream& i)
	{
		return (i << next('\n'));
	}

	template<class Param>
	std::tuple<Param> parse(std::istream& i, char* d = nullptr)
	{
		Param p;
		if (d) i << delimiter(*d);
		if (!static_cast<bool>(i >> extract(p)))
			throw std::logic_error("parse error: " + typeid(Param).name());
		return std::tuple<Param> { p };
	}

	template<class Param1, class Param2, class... Params>
	std::tuple<Param1, Param2, Params...> parse(std::istream& i, char* d = nullptr)
	{
		if (d) i << delimiter(*d);
		auto a = parse<Param1>(i);
		auto b = parse<Param2, Params...>(i);
		return std::tuple_cat(a, b);
	}

	template<class... Params>
	std::tuple<Params...> parse(std::string str, char* d = nullptr)
	{
		std::stringstream ss(str);
		if (d) ss << delimiter(*d);
		return parse<Params...>(ss);
	}
};
<commit_msg>Added raz::extract(std::string)<commit_after>/*
Copyright (C) Gbor "Razzie" Grzsny

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
*/

#pragma once

#include <iosfwd>
#include <locale>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>

namespace raz
{
	template<class T>
	class HasStreamInserter
	{
		template<class U>
		static constexpr auto test() -> decltype(bool(std::declval<std::ostream&>() << std::declval<const U&>()))
		{
			return true;
		}

		template<class U>
		static constexpr bool test(...)
		{
			return false;
		}

	public:
		constexpr static bool value = test<T>();
	};

	template<class T>
	class HasStreamExtractor
	{
		template<class U>
		static constexpr auto test() -> decltype(bool(std::declval<std::ostream&>() >> std::declval<U&>()))
		{
			return true;
		}

		template<class U>
		static constexpr bool test(...)
		{
			return false;
		}

	public:
		constexpr static bool value = test<T>();
	};

	struct __FallbackType
	{
		template<class T>
		__FallbackType(const T&) : type(typeid(T))
		{
		}

		friend std::ostream& operator<< (std::ostream& os, const __FallbackType& t)
		{
			os << t.type.name();
			return os;
		}

		friend std::istream& operator>> (std::istream& is, __FallbackType&)
		{
			return is;
		}

		const std::type_info& type;
	};

	struct __StringFallbackType
	{
		__StringFallbackType(std::string& _str) : str(_str)
		{
		}

		friend std::istream& operator>> (std::istream& is, __StringFallbackType& str)
		{
			std::getline(is, str.str);
			return is;
		}

		std::string& str;
	};

	template<class T>
	std::conditional_t<HasStreamInserter<T>::value, const T&, __FallbackType> insert(const T& t)
	{
		return { t };
	}

	template<class T>
	std::conditional_t<HasStreamExtractor<T>::value, T&, __FallbackType> extract(T& t)
	{
		return { t };
	}

	__StringFallbackType extract(std::string& str)
	{
		return { str };
	}

	template<class To, class From>
	To lexical_cast(const From& from)
	{
		To to;
		std::sstream ss;
		ss << from;
		ss >> to;
		return to;
	}

	template<class T>
	class StreamManipulator
	{
	public:
		typedef std::ios&(*Manipulator)(std::ios&, T);

		explicit StreamManipulator(Manipulator m, T t) :
			m_manip(m), m_value(t)
		{
		}

		friend std::ios& operator<< (std::ios& io, const StreamManipulator<T>& m)
		{
			return m.m_manip(io, m.m_value);
		}

	private:
		Manipulator m_manip;
		T m_value;
	};

	template<class T>
	class IstreamManipulator
	{
	public:
		typedef std::istream&(*Manipulator)(std::istream&, T);

		explicit IstreamManipulator(Manipulator m, T t) :
			m_manip(m), m_value(t)
		{
		}

		friend std::istream& operator<< (std::istream& io, const IstreamManipulator<T>& m)
		{
			return m.m_manip(io, m.m_value);
		}

	private:
		Manipulator m_manip;
		T m_value;
	};

	template<class T>
	class OstreamManipulator
	{
	public:
		typedef std::ostream&(*Manipulator)(std::ostream&, T);

		explicit OstreamManipulator(Manipulator m, T t) :
			m_manip(m), m_value(t)
		{
		}

		friend std::ostream& operator<< (std::ostream& io, const OstreamManipulator<T>& m)
		{
			return m.m_manip(io, m.m_value);
		}

	private:
		Manipulator m_manip;
		T m_value;
	};

	template<class T>
	OstreamManipulator<T> hex(T t)
	{
		OstreamManipulator<T>::Manipulator m =
			[](std::ostream& o, T t) -> std::ostream&
			{
				const char map[] = "0123456789abcdef";
				const unsigned char* ptr = reinterpret_cast<const unsigned char*>(&t);
				for (size_t i = 0; i < sizeof(T); ++i)
				{
					unsigned first = ptr[i] / 16;
					unsigned second = ptr[i] - (first * 16);
					o << map[first] << map[second];
				}
				return o;
			};

		return OstreamManipulator<T>(m, t);
	}

	inline OstreamManipulator<const char*> format(const char* f)
	{
		OstreamManipulator<const char*>::Manipulator m =
			[](std::ostream& os, const char* fmt) -> std::ostream&
			{
				std::locale& loc = os.getloc();
				int i = 0;
				while (fmt[i] != 0)
				{
					if (fmt[i] != '%')
					{
						os << fmt[i];
						i++;
					}
					else
					{
						i++;
						if (fmt[i] == '%')
						{
							os << fmt[i];
							i++;
						}
						else
						{
							bool ok = true;
							int istart = i;
							bool more = true;
							int width = 0;
							int precision = 6;
							std::ios_base::fmtflags flags;
							char fill = ' ';
							bool alternate = false;
							while (more)
							{
								switch (fmt[i])
								{
								case '+':
									flags |= std::ios::showpos;
									break;
								case '-':
									flags |= std::ios::left;
									break;
								case '0':
									flags |= std::ios::internal;
									fill = '0';
									break;
								case '#':
									alternate = true;
									break;
								case ' ':
									break;
								default:
									more = false;
									break;
								}
								if (more) i++;
							}
							if (std::isdigit(fmt[i], loc))
							{
								width = std::atoi(fmt + i);
								do i++;
								while (std::isdigit(fmt[i], loc));
							}
							if (fmt[i] == '.')
							{
								i++;
								precision = std::atoi(fmt + i);
								while (std::isdigit(fmt[i], loc)) i++;
							}
							switch (fmt[i])
							{
							case 'd':
								flags |= std::ios::dec;
								break;
							case 'x':
								flags |= std::ios::hex;
								if (alternate) flags |= std::ios::showbase;
								break;
							case 'X':
								flags |= std::ios::hex | std::ios::uppercase;
								if (alternate) flags |= std::ios::showbase;
								break;
							case 'o':
								flags |= std::ios::hex;
								if (alternate) flags |= std::ios::showbase;
								break;
							case 'f':
								flags |= std::ios::fixed;
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'e':
								flags |= std::ios::scientific;
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'E':
								flags |= std::ios::scientific | std::ios::uppercase;
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'g':
								if (alternate) flags |= std::ios::showpoint;
								break;
							case 'G':
								flags |= std::ios::uppercase;
								if (alternate) flags |= std::ios::showpoint;
								break;
							default:
								ok = false;
								break;
							}
							i++;
							if (fmt[i] != 0) ok = false;
							if (ok)
							{
								os.unsetf(std::ios::adjustfield | std::ios::basefield |
									std::ios::floatfield);
								os.setf(flags);
								os.width(width);
								os.precision(precision);
								os.fill(fill);
							}
							else i = istart;
						}
					}
				}
				return os;
			};

		return OstreamManipulator<const char*>(m, f);
	}

	inline IstreamManipulator<char> delimiter(char d)
	{
		struct CustomLocale : std::ctype<char>
		{
			std::ctype_base::mask m_rc[table_size];

			CustomLocale(char delim) :
				std::ctype<char>(get_table(static_cast<unsigned char>(delim)))
			{
			}

			const std::ctype_base::mask* get_table(unsigned char delim)
			{
				memset(m_rc, 0, sizeof(std::ctype_base::mask) * table_size);
				m_rc[delim] = std::ctype_base::space;
				m_rc['\n'] = std::ctype_base::space;
				return &m_rc[0];
			}
		};

		IstreamManipulator<char>::Manipulator m =
			[](std::istream& i, char d) -> std::istream&
			{
				i.imbue(std::locale(i.getloc(), new CustomLocale(d)));
				return i;
			};

		return IstreamManipulator<char>(m, d);
	}

	inline IstreamManipulator<char> next(char d)
	{
		IstreamManipulator<char>::Manipulator m =
			[](std::istream& i, char d) -> std::istream&
			{
#pragma push_macro("__raz")
#undef max
				i.ignore(std::numeric_limits<std::streamsize>::max(), d);
#pragma pop_macro("__raz")
				return i;
			};

		return IstreamManipulator<char>(m, d);
	}

	inline std::istream& nextLine(std::istream& i)
	{
		return (i << next('\n'));
	}

	template<class Param>
	std::tuple<Param> parse(std::istream& i, char* d = nullptr)
	{
		Param p;
		if (d) i << delimiter(*d);
		if (!static_cast<bool>(i >> extract(p)))
			throw std::logic_error("parse error: " + typeid(Param).name());
		return std::tuple<Param> { p };
	}

	template<class Param1, class Param2, class... Params>
	std::tuple<Param1, Param2, Params...> parse(std::istream& i, char* d = nullptr)
	{
		if (d) i << delimiter(*d);
		auto a = parse<Param1>(i);
		auto b = parse<Param2, Params...>(i);
		return std::tuple_cat(a, b);
	}

	template<class... Params>
	std::tuple<Params...> parse(std::string str, char* d = nullptr)
	{
		std::stringstream ss(str);
		if (d) ss << delimiter(*d);
		return parse<Params...>(ss);
	}
};
<|endoftext|>


<commit_before>#include "Runtime/World/CWorldLight.hpp"

#include <cfloat>

namespace urde {
CWorldLight::CWorldLight(CInputStream& in)
: x0_type(EWorldLightType(in.readUint32Big()))
, x4_color(zeus::CVector3f::ReadBig(in))
, x10_position(zeus::CVector3f::ReadBig(in))
, x1c_direction(zeus::CVector3f::ReadBig(in))
, x28_q(in.readFloatBig())
, x2c_cutoffAngle(in.readFloatBig())
, x30_(in.readFloatBig())
, x34_castShadows(in.readBool())
, x38_(in.readFloatBig())
, x3c_falloff(EFalloffType(in.readUint32Big()))
, x40_(in.readFloatBig()) {}

std::tuple<float, float, float> CalculateLightFalloff(EFalloffType falloff, float q) {
  float constant = 0.f;
  float linear = 0.f;
  float quadratic = 0.f;

  if (falloff == EFalloffType::Constant)
    constant = 2.f / q;
  else if (falloff == EFalloffType::Linear)
    linear = 250.f / q;
  else if (falloff == EFalloffType::Quadratic)
    quadratic = 25000.f / q;

  return {constant, linear, quadratic};
}

CLight CWorldLight::GetAsCGraphicsLight() const {
  zeus::CVector3f float_color = x4_color;
  float q = x28_q;
  if (q < FLT_EPSILON)
    q = 0.000001f;

  if (x0_type == EWorldLightType::LocalAmbient) {
    float_color *= zeus::CVector3f(q);
    if (float_color.x() >= 1.f)
      float_color.x() = 1.f;

    if (float_color.y() >= 1.f)
      float_color.y() = 1.f;

    if (float_color.z() >= 1.f)
      float_color.z() = 1.f;

    return CLight::BuildLocalAmbient(x10_position,
                                     zeus::CColor(float_color.x(), float_color.y(), float_color.z(), 1.f));
  } else if (x0_type == EWorldLightType::Directional) {
    return CLight::BuildDirectional(x1c_direction, zeus::CColor{x4_color.x(), x4_color.y(), x4_color.z(), 1.f});
  } else if (x0_type == EWorldLightType::Spot) {
    CLight light =
        CLight::BuildSpot(x10_position, x1c_direction.normalized(),
                          zeus::CColor{x4_color.x(), x4_color.y(), x4_color.z(), 1.f}, x2c_cutoffAngle * .5f);

    float c, l, q;
    std::tie(c, l, q) = CalculateLightFalloff(x3c_falloff, x28_q);

    light.SetAttenuation(c, l, q);
    return light;
  }
  float distC, distL, distQ;
  std::tie(distC, distL, distQ) = CalculateLightFalloff(x3c_falloff, x28_q);
  return CLight::BuildCustom(x10_position, zeus::CVector3f{0.f, 1.f, 0.f},
                             zeus::CColor{x4_color.x(), x4_color.y(), x4_color.z(), 1.f}, distC, distL, distQ, 1.f, 0.f,
                             0.f);
}
} // namespace urde
<commit_msg>CWorldLight: Eliminate variable shadowing<commit_after>#include "Runtime/World/CWorldLight.hpp"

#include <cfloat>

namespace urde {
CWorldLight::CWorldLight(CInputStream& in)
: x0_type(EWorldLightType(in.readUint32Big()))
, x4_color(zeus::CVector3f::ReadBig(in))
, x10_position(zeus::CVector3f::ReadBig(in))
, x1c_direction(zeus::CVector3f::ReadBig(in))
, x28_q(in.readFloatBig())
, x2c_cutoffAngle(in.readFloatBig())
, x30_(in.readFloatBig())
, x34_castShadows(in.readBool())
, x38_(in.readFloatBig())
, x3c_falloff(EFalloffType(in.readUint32Big()))
, x40_(in.readFloatBig()) {}

std::tuple<float, float, float> CalculateLightFalloff(EFalloffType falloff, float q) {
  float constant = 0.f;
  float linear = 0.f;
  float quadratic = 0.f;

  if (falloff == EFalloffType::Constant)
    constant = 2.f / q;
  else if (falloff == EFalloffType::Linear)
    linear = 250.f / q;
  else if (falloff == EFalloffType::Quadratic)
    quadratic = 25000.f / q;

  return {constant, linear, quadratic};
}

CLight CWorldLight::GetAsCGraphicsLight() const {
  zeus::CVector3f float_color = x4_color;
  float q = x28_q;
  if (q < FLT_EPSILON)
    q = 0.000001f;

  if (x0_type == EWorldLightType::LocalAmbient) {
    float_color *= zeus::CVector3f(q);
    if (float_color.x() >= 1.f)
      float_color.x() = 1.f;

    if (float_color.y() >= 1.f)
      float_color.y() = 1.f;

    if (float_color.z() >= 1.f)
      float_color.z() = 1.f;

    return CLight::BuildLocalAmbient(x10_position,
                                     zeus::CColor(float_color.x(), float_color.y(), float_color.z(), 1.f));
  } else if (x0_type == EWorldLightType::Directional) {
    return CLight::BuildDirectional(x1c_direction, zeus::CColor{x4_color.x(), x4_color.y(), x4_color.z(), 1.f});
  } else if (x0_type == EWorldLightType::Spot) {
    CLight light =
        CLight::BuildSpot(x10_position, x1c_direction.normalized(),
                          zeus::CColor{x4_color.x(), x4_color.y(), x4_color.z(), 1.f}, x2c_cutoffAngle * .5f);

    const auto [constant, linear, quadratic] = CalculateLightFalloff(x3c_falloff, x28_q);
    light.SetAttenuation(constant, linear, quadratic);
    return light;
  }

  const auto [distC, distL, distQ] = CalculateLightFalloff(x3c_falloff, x28_q);
  return CLight::BuildCustom(x10_position, zeus::CVector3f{0.f, 1.f, 0.f},
                             zeus::CColor{x4_color.x(), x4_color.y(), x4_color.z(), 1.f}, distC, distL, distQ, 1.f, 0.f,
                             0.f);
}
} // namespace urde
<|endoftext|>


<commit_before>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. 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 "fnord-json/jsonutil.h"

namespace fnord {
namespace json {

Option<String> JSONUtil::objectGetString(
    JSONObject::const_iterator begin,
    JSONObject::const_iterator end,
    const std::string& key) {
  auto iter = objectLookup(begin, end, key);

  if (iter != end && iter->type == JSON_STRING) {
    return Some(iter->data);
  } else {
    return None<String>();
  }
}

Option<uint64_t> JSONUtil::objectGetUInt64(
    JSONObject::const_iterator begin,
    JSONObject::const_iterator end,
    const std::string& key) {
  auto iter = objectLookup(begin, end, key);

  if (iter != end && (iter->type == JSON_STRING || iter->type == JSON_NUMBER)) {
    return Some<uint64_t>(std::stoul(iter->data));
  } else {
    return None<uint64_t>();
  }
}

JSONObject::const_iterator JSONUtil::objectLookup(
    JSONObject::const_iterator begin,
    JSONObject::const_iterator end,
    const std::string& key) {
  if (begin == end) {
    return end;
  }

  if (begin->type != json::JSON_OBJECT_BEGIN) {
    RAISEF(kParseError, "expected JSON_OBJECT_BEGIN, got: $0", begin->type);
  }

  auto oend = begin + begin->size;
  if (oend > end) {
    return end;
  }

  for (++begin; begin < end;) {
    switch (begin->type) {
      case json::JSON_STRING:
        if (begin->data == key) {
          return ++begin;
        }

      default:
        break;
    }

    if (++begin == oend) {
      break;
    } else {
      begin += begin->size;
    }
  }

  return end;
}

size_t JSONUtil::arrayLength(
    JSONObject::const_iterator begin,
    JSONObject::const_iterator end) {
  if (begin->type != json::JSON_ARRAY_BEGIN) {
    RAISEF(kParseError, "expected JSON_OBJECT_BEGIN, got: $0", begin->type);
  }

  auto aend = begin + begin->size - 1;
  if (aend > end) {
    RAISE(kIndexError);
  }

  size_t length = 0;
  for (++begin; begin < aend; begin += begin->size) {
    length++;
  }

  return length;
}

JSONObject::const_iterator JSONUtil::arrayLookup(
    JSONObject::const_iterator begin,
    JSONObject::const_iterator end,
    size_t index) {
  if (begin->type != json::JSON_ARRAY_BEGIN) {
    RAISEF(kParseError, "expected JSON_OBJECT_BEGIN, got: $0", begin->type);
  }

  auto aend = begin + begin->size - 1;
  if (aend > end || begin == aend) {
    RAISE(kIndexError);
  }

  size_t idx = 0;
  for (++begin; begin < aend; begin += begin->size) {
    if (idx++ == index) {
      return begin;
    }
  }

  RAISEF(kIndexError, "invalid index: $0", index);
  return end;
}

Option<String> JSONUtil::arrayGetString(
    JSONObject::const_iterator begin,
    JSONObject::const_iterator end,
    size_t index) {
  auto iter = arrayLookup(begin, end, index);

  if (iter != end && iter->type == JSON_STRING) {
    return Some(iter->data);
  } else {
    return None<String>();
  }
}

}
}

<commit_msg>solved merge conflict<commit_after>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. 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 "fnord-json/jsonutil.h"

namespace fnord {
namespace json {

Option<String> JSONUtil::objectGetString(
    JSONObject::const_iterator begin,
    JSONObject::const_iterator end,
    const std::string& key) {
  auto iter = objectLookup(begin, end, key);

  if (iter != end && iter->type == JSON_STRING) {
    return Some(iter->data);
  } else {
    return None<String>();
  }
}

Option<uint64_t> JSONUtil::objectGetUInt64(
    JSONObject::const_iterator begin,
    JSONObject::const_iterator end,
    const std::string& key) {
  auto iter = objectLookup(begin, end, key);

  if (iter != end && (iter->type == JSON_STRING || iter->type == JSON_NUMBER)) {
    return Some<uint64_t>(std::stoul(iter->data));
  } else {
    return None<uint64_t>();
  }
}

JSONObject::const_iterator JSONUtil::objectLookup(
    JSONObject::const_iterator begin,
    JSONObject::const_iterator end,
    const std::string& key) {
  if (begin == end) {
    return end;
  }

  if (begin->type != json::JSON_OBJECT_BEGIN) {
    RAISEF(kParseError, "expected JSON_OBJECT_BEGIN, got: $0", begin->type);
  }

  auto oend = begin + begin->size;
  if (oend > end) {
    return end;
  }

  for (++begin; begin < end;) {
    switch (begin->type) {
      case json::JSON_STRING:
        if (begin->data == key) {
          return ++begin;
        }

      default:
        break;
    }

    if (++begin == oend) {
      break;
    } else {
      begin += begin->size;
    }
  }

  return end;
}

size_t JSONUtil::arrayLength(
    JSONObject::const_iterator begin,
    JSONObject::const_iterator end) {
  if (begin == end) {
    return 0;
  }

  if (begin->type != json::JSON_ARRAY_BEGIN) {
    RAISEF(kParseError, "expected JSON_OBJECT_BEGIN, got: $0", begin->type);
  }

  auto aend = begin + begin->size - 1;
  if (aend > end) {
    RAISE(kIndexError);
  }

  size_t length = 0;
  for (++begin; begin < aend; begin += begin->size) {
    length++;
  }

  return length;
}

JSONObject::const_iterator JSONUtil::arrayLookup(
    JSONObject::const_iterator begin,
    JSONObject::const_iterator end,
    size_t index) {
  if (begin == end) {
    return end;
  }

  if (begin->type != json::JSON_ARRAY_BEGIN) {
    RAISEF(kParseError, "expected JSON_OBJECT_BEGIN, got: $0", begin->type);
  }

  auto aend = begin + begin->size - 1;
  if (aend > end || begin == aend) {
    RAISE(kIndexError);
  }

  size_t idx = 0;
  for (++begin; begin < aend; begin += begin->size) {
    if (idx++ == index) {
      return begin;
    }
  }

  RAISEF(kIndexError, "invalid index: $0", index);
  return end;
}

Option<String> JSONUtil::arrayGetString(
    JSONObject::const_iterator begin,
    JSONObject::const_iterator end,
    size_t index) {
  auto iter = arrayLookup(begin, end, index);

  if (iter != end && iter->type == JSON_STRING) {
    return Some(iter->data);
  } else {
    return None<String>();
  }
}

}
}

<|endoftext|>


<commit_before>
//
//  EventBus.hpp
//  CatchLib
//
//  Created by Jesper Persson and Sebastian Odbjer on 2/10-12.
//  Copyright (c) 2012 Catch22. All rights reserved.
//

class EventBus
{
public:
	static EventBus getSharedInstance();
	void publishEvent();
	void addEventHandler();
	void removeEventHandler();
private:
	~EventBus();
	EventBus();
};
<commit_msg>added struct EventListenerArray<commit_after>//
//  EventBus.hpp
//  CatchLib
//
//  Created by Jesper Persson and Sebastian Odbjer on 2/10-12.
//  Copyright (c) 2012 Catch22. All rights reserved.
//
#include "EEvent.hpp"
#include "IEventListener.hpp"

struct EventListenerArray
{
	IEventListener** m_eventListeners;
	int m_size;
	int m_incrementBy;
	int m_index;
	EventListenerArray()
	{
		m_incrementBy = 5;
		m_index = 0;
		m_size = 0;
		m_eventListeners = 0;
	}
};

class EventBus
{
public:
	static EventBus* getSharedInstance();
	void publishEvent(EEvent event, void* source);
	void addEventListener(IEventListener* listener);
	void removeEventListener(IEventListener* listener);
private:
	EventListenerArray* m_listeners;
	~EventBus();
	EventBus();
};
<|endoftext|>


<commit_before>#ifndef SLIC3R_FIELD_HPP
#define SLIC3R_FIELD_HPP

#include <functional>
#include <string>
#include <limits>
#include <regex>
#include <tuple>

#include <boost/any.hpp>
#include "ConfigBase.hpp"
#include "Log.hpp"

#include "wx/spinctrl.h"
#include "wx/checkbox.h"
#include "wx/textctrl.h"
#include "wx/combobox.h"
#include "wx/arrstr.h"
#include "wx/stattext.h"
#include "wx/sizer.h"

namespace Slic3r { namespace GUI {

using namespace std::string_literals;

class UI_Field {
public:
    UI_Field(wxWindow* _parent, Slic3r::ConfigOptionDef _opt) : parent(_parent), opt(_opt) { };
    virtual ~UI_Field() = default;

    /// Don't trigger on_change when this is true.
    bool disable_change_event {false};

    /// Set the underlying control to the value (cast it and throw bad_any_cast if there are problems).
    virtual void set_value(boost::any value) = 0;

    /// Enables the underlying UI widget.
    virtual void enable() { this->window->Enable(); }

    /// Disables the underlying UI widget.
    virtual void disable() { this->window->Disable(); }

    /// Set the underlying widget to either enabled or disabled.
    virtual void toggle(bool enable = true) { enable ? this->enable() : this->disable(); }

    /// Getter functions for UI_Window items.
    virtual bool get_bool() { Slic3r::Log::warn(this->LogChannel(), "get_bool does not exist"s); return false; } //< return false all the time if this is not implemented.
    virtual double get_double() { Slic3r::Log::warn(this->LogChannel(), "get_double does not exist"s); return 0.0; } //< return 0.0 all the time if this is not implemented.
    virtual int get_int() { Slic3r::Log::warn(this->LogChannel(), "get_int does not exist"s); return 0; } //< return 0 all the time if this is not implemented.
    virtual std::string get_string() { Slic3r::Log::warn(this->LogChannel(), "get_string does not exist"s); return 0; } //< return 0 all the time if this is not implemented.

    virtual Slic3r::Pointf get_point() { Slic3r::Log::warn(this->LogChannel(), "get_point does not exist"s); return Slic3r::Pointf(); } //< return 0 all the time if this is not implemented.
    virtual Slic3r::Pointf3 get_point3() { Slic3r::Log::warn(this->LogChannel(), "get_point3 does not exist"s); return Slic3r::Pointf3(); } //< return 0 all the time if this is not implemented.

    /// Provide access in a generic fashion to the underlying Window.
    virtual wxWindow* get_window() { return this->window; }

    /// Provide access in a generic fashion to the underlying Sizer.
    virtual wxSizer* get_sizer() { return this->sizer; }

    /// Function to call when focus leaves.
    std::function<void (const std::string&)> on_kill_focus {nullptr};

protected:
    wxWindow* parent {nullptr}; //< Cached copy of the parent object
    wxWindow* window {nullptr}; //< Pointer copy of the derived classes
    wxSizer* sizer {nullptr}; //< Pointer copy of the derived classes

    const Slic3r::ConfigOptionDef opt; //< Reference to the UI-specific bits of this option

    virtual std::string LogChannel() { return "UI_Field"s; }

    virtual void _on_change(std::string opt_id) = 0;

    /// Define a default size for derived classes.
    wxSize _default_size() { return wxSize((opt.width >= 0 ? opt.width : 60), (opt.height != -1 ? opt.height : -1)); }
};

/// Organizing class for single-part UI elements.
class UI_Window : public UI_Field {
public:
    UI_Window(wxWindow* _parent, Slic3r::ConfigOptionDef _opt) : UI_Field(_parent, _opt) {};
    virtual ~UI_Window() = default;
    virtual std::string LogChannel() override { return "UI_Window"s; }
};

/// Organizing class for multi-part UI elements.
class UI_Sizer : public UI_Field {
public:
    UI_Sizer(wxWindow* _parent, Slic3r::ConfigOptionDef _opt) : UI_Field(_parent, _opt) {};
    virtual ~UI_Sizer() = default;
    virtual std::string LogChannel() override { return "UI_Sizer"s; }
};

class UI_Checkbox : public UI_Window {
public:
    UI_Checkbox(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID checkid = wxID_ANY) : UI_Window(parent, _opt) {
        _check = new wxCheckBox(parent, checkid, "");
        this->window = _check;

        // Set some defaults.
        if (this->opt.readonly) { this->_check->Disable(); }
        if (this->opt.default_value != nullptr) { this->_check->SetValue(this->opt.default_value->getBool()); }

        // Set up event handlers
        _check->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& e) { this->_on_change(""); e.Skip(); });
        _check->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { if (this->on_kill_focus != nullptr) {this->on_kill_focus("");} e.Skip(); });
    }

    ~UI_Checkbox() { _check->Destroy(); }

    /// Returns a bare pointer to the underlying checkbox, usually for test interface
    wxCheckBox* check() { return _check; }

    /// Returns the value of the enclosed checkbox.
    /// Implements get_bool
    virtual bool get_bool() override { return _check->GetValue();}

    /// Casts the containing value to boolean and sets the built-in checkbox appropriately.
    /// implements set_value
    virtual void set_value(boost::any value) override { this->_check->SetValue(boost::any_cast<bool>(value)); }

    /// Function to call when the contents of this change.
    std::function<void (const std::string&, bool value)> on_change {nullptr};

protected:
    virtual std::string LogChannel() override { return "UI_Checkbox"s; }

    void _on_change(std::string opt_id) {
        if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) {
            this->on_change(opt_id, this->get_bool());
        }
    }
private:
    wxCheckBox* _check {nullptr};

};

class UI_SpinCtrl : public UI_Window {
public:
    UI_SpinCtrl(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID spinid = wxID_ANY) : UI_Window(parent, _opt) {

        /// Initialize and set defaults, if available.
        _spin = new wxSpinCtrl(parent, spinid, "", wxDefaultPosition, _default_size(), 0,
            (opt.min > 0 ? opt.min : 0),
            (opt.max > 0 ? opt.max : std::numeric_limits<int>::max()),
            (opt.default_value != NULL ? opt.default_value->getInt() : 0));

        window = _spin;

        // Set up event handlers
        _spin->Bind(wxEVT_SPINCTRL, [this](wxCommandEvent& e) { this->_on_change(""); e.Skip(); });
        _spin->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { if (this->on_kill_focus != nullptr) { this->_on_change(""); this->on_kill_focus("");} e.Skip(); });
    }
    ~UI_SpinCtrl() { _spin->Destroy();}
    int get_int() { return this->_spin->GetValue(); }
    void set_value(boost::any value) { this->_spin->SetValue(boost::any_cast<int>(value)); }

    /// Access method for the underlying SpinCtrl
    wxSpinCtrl* spinctrl() { return _spin; }

    /// Function to call when the contents of this change.
    std::function<void (const std::string&, int value)> on_change {nullptr};

protected:
    virtual std::string LogChannel() { return "UI_SpinCtrl"s; }

    void _on_change(std::string opt_id) {
        if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) {
            this->on_change(opt_id, this->get_int());
        }
    }

private:
    wxSpinCtrl* _spin {nullptr};
};

class UI_TextCtrl : public UI_Window {
public:
    UI_TextCtrl(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID id = wxID_ANY) : UI_Window(parent, _opt) {
        int style {0};
        if (opt.multiline) {
            style |= wxHSCROLL;
            style |= wxTE_MULTILINE;
        } else {
            style |= wxTE_PROCESS_ENTER;
        }
        /// Initialize and set defaults, if available.
        _text = new wxTextCtrl(parent, id,
            (opt.default_value != NULL ? wxString(opt.default_value->getString()) : wxString()),
            wxDefaultPosition,
            _default_size(),
            style);

        window = _text;

        // Set up event handlers
        if (!opt.multiline) {
            _text->Bind(wxEVT_TEXT_ENTER, [this](wxCommandEvent& e) { this->_on_change(""); e.Skip(); });
        }
        _text->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { if (this->on_kill_focus != nullptr) {this->on_kill_focus(""); this->_on_change("");} e.Skip(); });
    }
    ~UI_TextCtrl() { _text->Destroy(); }
    std::string get_string() { return this->_text->GetValue().ToStdString(); }
    void set_value(boost::any value) { this->_text->SetValue(boost::any_cast<std::string>(value)); }

    /// Access method for the underlying TextCtrl
    wxTextCtrl* textctrl() { return _text; }

    /// Function to call when the contents of this change.
    std::function<void (const std::string&, std::string value)> on_change {nullptr};

protected:
    virtual std::string LogChannel() { return "UI_TextCtrl"s; }

    void _on_change(std::string opt_id) {
        if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) {
            this->on_change(opt_id, this->get_string());
        }
    }

private:
    wxTextCtrl* _text {nullptr};
};

class UI_Choice : public UI_Window {
public:
    UI_Choice(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID id = wxID_ANY);
    ~UI_Choice() { _choice->Destroy(); }

    std::string get_string() override;

    void set_value(boost::any value) override;

    /// Function to call when the contents of this change.
    std::function<void (const std::string&, std::string value)> on_change {nullptr};

    /// Returns a bare pointer to the underlying combobox, usually for test interface
    wxComboBox* choice() { return this->_choice; }
protected:
    virtual std::string LogChannel() override { return "UI_Choice"s; }

    void _on_change(std::string opt_id) {
        if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) {
            this->on_change(opt_id, this->get_string());
        }
    }
private:
    wxComboBox* _choice {nullptr};
};

class UI_NumChoice : public UI_Window {
public:
    UI_NumChoice(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID id = wxID_ANY);
    ~UI_NumChoice() { _choice->Destroy(); }

    /// Returns the underlying value for the selected value (defined by enum_values). If there are labels, this may not
    /// match the underlying combobox->GetValue().
    std::string get_string() override;

    /// Returns the item in the value field of the associated option as an integer.
    int get_int() override { return std::stoi(this->get_string()); }

    /// Returns the item in the value field of the associated option as a double.
    double get_double() override { return std::stod(this->get_string()); }

    /// Returns a bare pointer to the underlying combobox, usually for test interface
    wxComboBox* choice() { return this->_choice; }

    /// For NumChoice, value can be the actual input value or an index into the value.
    void set_value(boost::any value) override;

    /// Function to call when the contents of this change.
    std::function<void (const std::string&, std::string value)> on_change {nullptr};

protected:
    virtual std::string LogChannel() override { return "UI_NumChoice"s; }

    void _set_value(int value, bool show_value = false);
    void _set_value(double value, bool show_value = false);
    void _set_value(std::string value);

    void _on_change(std::string opt_id) {
        if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) {
            this->on_change(opt_id, this->get_string());
        }
    }
private:
    wxComboBox* _choice {nullptr};
    std::regex show_value_flag {"\bshow_value\b"};
};

class UI_Point : public UI_Sizer {
public:

    UI_Point(wxWindow* _parent, Slic3r::ConfigOptionDef _opt);
    ~UI_Point() { _lbl_x->Destroy(); _lbl_y->Destroy(); _ctrl_x->Destroy(); _ctrl_y->Destroy(); }
    std::string get_string();

    void set_value(boost::any value) override; //< Implements set_value

    Slic3r::Pointf get_point() override; //< return a Slic3r::Pointf corresponding to the textctrl contents.
    Slic3r::Pointf3 get_point3() override; //< return a Slic3r::Pointf3 corresponding to the textctrl contents.

    /// Function to call when the contents of this change.
    std::function<void (const std::string&, std::tuple<std::string, std::string> value)> on_change {nullptr};

    void enable() override { _ctrl_x->Enable(); _ctrl_y->Enable(); }
    void disable() override { _ctrl_x->Disable(); _ctrl_y->Disable(); }

    /// Local-access items
    wxTextCtrl* ctrl_x() { return _ctrl_x;}
    wxTextCtrl* ctrl_y() { return _ctrl_y;}

    wxStaticText* lbl_x() { return _lbl_x;}
    wxStaticText* lbl_y() { return _lbl_y;}

protected:
    virtual std::string LogChannel() override { return "UI_Point"s; }

    void _on_change(std::string opt_id) override {
        if (!this->disable_change_event && this->_ctrl_x->IsEnabled() && this->on_change != nullptr) {
            this->on_change(opt_id, std::make_pair<std::string, std::string>(_ctrl_x->GetValue().ToStdString(), _ctrl_y->GetValue().ToStdString()));
        }
    }

private:
    wxSize field_size {40, 1};
    wxStaticText* _lbl_x {nullptr};
    wxStaticText* _lbl_y {nullptr};

    wxTextCtrl* _ctrl_x {nullptr};
    wxTextCtrl* _ctrl_y {nullptr};

    wxBoxSizer* _sizer {nullptr};

    void _set_value(Slic3r::Pointf value);
    void _set_value(Slic3r::Pointf3 value);
    void _set_value(std::string value);

    }

};

} } // Namespace Slic3r::GUI

#endif // SLIC3R_FIELD_HPP
<commit_msg>use make_tuple instead of make_pair<commit_after>#ifndef SLIC3R_FIELD_HPP
#define SLIC3R_FIELD_HPP

#include <functional>
#include <string>
#include <limits>
#include <regex>
#include <tuple>

#include <boost/any.hpp>
#include "ConfigBase.hpp"
#include "Log.hpp"

#include "wx/spinctrl.h"
#include "wx/checkbox.h"
#include "wx/textctrl.h"
#include "wx/combobox.h"
#include "wx/arrstr.h"
#include "wx/stattext.h"
#include "wx/sizer.h"

namespace Slic3r { namespace GUI {

using namespace std::string_literals;

class UI_Field {
public:
    UI_Field(wxWindow* _parent, Slic3r::ConfigOptionDef _opt) : parent(_parent), opt(_opt) { };
    virtual ~UI_Field() = default;

    /// Don't trigger on_change when this is true.
    bool disable_change_event {false};

    /// Set the underlying control to the value (cast it and throw bad_any_cast if there are problems).
    virtual void set_value(boost::any value) = 0;

    /// Enables the underlying UI widget.
    virtual void enable() { this->window->Enable(); }

    /// Disables the underlying UI widget.
    virtual void disable() { this->window->Disable(); }

    /// Set the underlying widget to either enabled or disabled.
    virtual void toggle(bool enable = true) { enable ? this->enable() : this->disable(); }

    /// Getter functions for UI_Window items.
    virtual bool get_bool() { Slic3r::Log::warn(this->LogChannel(), "get_bool does not exist"s); return false; } //< return false all the time if this is not implemented.
    virtual double get_double() { Slic3r::Log::warn(this->LogChannel(), "get_double does not exist"s); return 0.0; } //< return 0.0 all the time if this is not implemented.
    virtual int get_int() { Slic3r::Log::warn(this->LogChannel(), "get_int does not exist"s); return 0; } //< return 0 all the time if this is not implemented.
    virtual std::string get_string() { Slic3r::Log::warn(this->LogChannel(), "get_string does not exist"s); return 0; } //< return 0 all the time if this is not implemented.

    virtual Slic3r::Pointf get_point() { Slic3r::Log::warn(this->LogChannel(), "get_point does not exist"s); return Slic3r::Pointf(); } //< return 0 all the time if this is not implemented.
    virtual Slic3r::Pointf3 get_point3() { Slic3r::Log::warn(this->LogChannel(), "get_point3 does not exist"s); return Slic3r::Pointf3(); } //< return 0 all the time if this is not implemented.

    /// Provide access in a generic fashion to the underlying Window.
    virtual wxWindow* get_window() { return this->window; }

    /// Provide access in a generic fashion to the underlying Sizer.
    virtual wxSizer* get_sizer() { return this->sizer; }

    /// Function to call when focus leaves.
    std::function<void (const std::string&)> on_kill_focus {nullptr};

protected:
    wxWindow* parent {nullptr}; //< Cached copy of the parent object
    wxWindow* window {nullptr}; //< Pointer copy of the derived classes
    wxSizer* sizer {nullptr}; //< Pointer copy of the derived classes

    const Slic3r::ConfigOptionDef opt; //< Reference to the UI-specific bits of this option

    virtual std::string LogChannel() { return "UI_Field"s; }

    virtual void _on_change(std::string opt_id) = 0;

    /// Define a default size for derived classes.
    wxSize _default_size() { return wxSize((opt.width >= 0 ? opt.width : 60), (opt.height != -1 ? opt.height : -1)); }
};

/// Organizing class for single-part UI elements.
class UI_Window : public UI_Field {
public:
    UI_Window(wxWindow* _parent, Slic3r::ConfigOptionDef _opt) : UI_Field(_parent, _opt) {};
    virtual ~UI_Window() = default;
    virtual std::string LogChannel() override { return "UI_Window"s; }
};

/// Organizing class for multi-part UI elements.
class UI_Sizer : public UI_Field {
public:
    UI_Sizer(wxWindow* _parent, Slic3r::ConfigOptionDef _opt) : UI_Field(_parent, _opt) {};
    virtual ~UI_Sizer() = default;
    virtual std::string LogChannel() override { return "UI_Sizer"s; }
};

class UI_Checkbox : public UI_Window {
public:
    UI_Checkbox(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID checkid = wxID_ANY) : UI_Window(parent, _opt) {
        _check = new wxCheckBox(parent, checkid, "");
        this->window = _check;

        // Set some defaults.
        if (this->opt.readonly) { this->_check->Disable(); }
        if (this->opt.default_value != nullptr) { this->_check->SetValue(this->opt.default_value->getBool()); }

        // Set up event handlers
        _check->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& e) { this->_on_change(""); e.Skip(); });
        _check->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { if (this->on_kill_focus != nullptr) {this->on_kill_focus("");} e.Skip(); });
    }

    ~UI_Checkbox() { _check->Destroy(); }

    /// Returns a bare pointer to the underlying checkbox, usually for test interface
    wxCheckBox* check() { return _check; }

    /// Returns the value of the enclosed checkbox.
    /// Implements get_bool
    virtual bool get_bool() override { return _check->GetValue();}

    /// Casts the containing value to boolean and sets the built-in checkbox appropriately.
    /// implements set_value
    virtual void set_value(boost::any value) override { this->_check->SetValue(boost::any_cast<bool>(value)); }

    /// Function to call when the contents of this change.
    std::function<void (const std::string&, bool value)> on_change {nullptr};

protected:
    virtual std::string LogChannel() override { return "UI_Checkbox"s; }

    void _on_change(std::string opt_id) {
        if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) {
            this->on_change(opt_id, this->get_bool());
        }
    }
private:
    wxCheckBox* _check {nullptr};

};

class UI_SpinCtrl : public UI_Window {
public:
    UI_SpinCtrl(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID spinid = wxID_ANY) : UI_Window(parent, _opt) {

        /// Initialize and set defaults, if available.
        _spin = new wxSpinCtrl(parent, spinid, "", wxDefaultPosition, _default_size(), 0,
            (opt.min > 0 ? opt.min : 0),
            (opt.max > 0 ? opt.max : std::numeric_limits<int>::max()),
            (opt.default_value != NULL ? opt.default_value->getInt() : 0));

        window = _spin;

        // Set up event handlers
        _spin->Bind(wxEVT_SPINCTRL, [this](wxCommandEvent& e) { this->_on_change(""); e.Skip(); });
        _spin->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { if (this->on_kill_focus != nullptr) { this->_on_change(""); this->on_kill_focus("");} e.Skip(); });
    }
    ~UI_SpinCtrl() { _spin->Destroy();}
    int get_int() { return this->_spin->GetValue(); }
    void set_value(boost::any value) { this->_spin->SetValue(boost::any_cast<int>(value)); }

    /// Access method for the underlying SpinCtrl
    wxSpinCtrl* spinctrl() { return _spin; }

    /// Function to call when the contents of this change.
    std::function<void (const std::string&, int value)> on_change {nullptr};

protected:
    virtual std::string LogChannel() { return "UI_SpinCtrl"s; }

    void _on_change(std::string opt_id) {
        if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) {
            this->on_change(opt_id, this->get_int());
        }
    }

private:
    wxSpinCtrl* _spin {nullptr};
};

class UI_TextCtrl : public UI_Window {
public:
    UI_TextCtrl(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID id = wxID_ANY) : UI_Window(parent, _opt) {
        int style {0};
        if (opt.multiline) {
            style |= wxHSCROLL;
            style |= wxTE_MULTILINE;
        } else {
            style |= wxTE_PROCESS_ENTER;
        }
        /// Initialize and set defaults, if available.
        _text = new wxTextCtrl(parent, id,
            (opt.default_value != NULL ? wxString(opt.default_value->getString()) : wxString()),
            wxDefaultPosition,
            _default_size(),
            style);

        window = _text;

        // Set up event handlers
        if (!opt.multiline) {
            _text->Bind(wxEVT_TEXT_ENTER, [this](wxCommandEvent& e) { this->_on_change(""); e.Skip(); });
        }
        _text->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { if (this->on_kill_focus != nullptr) {this->on_kill_focus(""); this->_on_change("");} e.Skip(); });
    }
    ~UI_TextCtrl() { _text->Destroy(); }
    std::string get_string() { return this->_text->GetValue().ToStdString(); }
    void set_value(boost::any value) { this->_text->SetValue(boost::any_cast<std::string>(value)); }

    /// Access method for the underlying TextCtrl
    wxTextCtrl* textctrl() { return _text; }

    /// Function to call when the contents of this change.
    std::function<void (const std::string&, std::string value)> on_change {nullptr};

protected:
    virtual std::string LogChannel() { return "UI_TextCtrl"s; }

    void _on_change(std::string opt_id) {
        if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) {
            this->on_change(opt_id, this->get_string());
        }
    }

private:
    wxTextCtrl* _text {nullptr};
};

class UI_Choice : public UI_Window {
public:
    UI_Choice(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID id = wxID_ANY);
    ~UI_Choice() { _choice->Destroy(); }

    std::string get_string() override;

    void set_value(boost::any value) override;

    /// Function to call when the contents of this change.
    std::function<void (const std::string&, std::string value)> on_change {nullptr};

    /// Returns a bare pointer to the underlying combobox, usually for test interface
    wxComboBox* choice() { return this->_choice; }
protected:
    virtual std::string LogChannel() override { return "UI_Choice"s; }

    void _on_change(std::string opt_id) {
        if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) {
            this->on_change(opt_id, this->get_string());
        }
    }
private:
    wxComboBox* _choice {nullptr};
};

class UI_NumChoice : public UI_Window {
public:
    UI_NumChoice(wxWindow* parent, Slic3r::ConfigOptionDef _opt, wxWindowID id = wxID_ANY);
    ~UI_NumChoice() { _choice->Destroy(); }

    /// Returns the underlying value for the selected value (defined by enum_values). If there are labels, this may not
    /// match the underlying combobox->GetValue().
    std::string get_string() override;

    /// Returns the item in the value field of the associated option as an integer.
    int get_int() override { return std::stoi(this->get_string()); }

    /// Returns the item in the value field of the associated option as a double.
    double get_double() override { return std::stod(this->get_string()); }

    /// Returns a bare pointer to the underlying combobox, usually for test interface
    wxComboBox* choice() { return this->_choice; }

    /// For NumChoice, value can be the actual input value or an index into the value.
    void set_value(boost::any value) override;

    /// Function to call when the contents of this change.
    std::function<void (const std::string&, std::string value)> on_change {nullptr};

protected:
    virtual std::string LogChannel() override { return "UI_NumChoice"s; }

    void _set_value(int value, bool show_value = false);
    void _set_value(double value, bool show_value = false);
    void _set_value(std::string value);

    void _on_change(std::string opt_id) {
        if (!this->disable_change_event && this->window->IsEnabled() && this->on_change != nullptr) {
            this->on_change(opt_id, this->get_string());
        }
    }
private:
    wxComboBox* _choice {nullptr};
    std::regex show_value_flag {"\bshow_value\b"};
};

class UI_Point : public UI_Sizer {
public:

    UI_Point(wxWindow* _parent, Slic3r::ConfigOptionDef _opt);
    ~UI_Point() { _lbl_x->Destroy(); _lbl_y->Destroy(); _ctrl_x->Destroy(); _ctrl_y->Destroy(); }
    std::string get_string();

    void set_value(boost::any value) override; //< Implements set_value

    Slic3r::Pointf get_point() override; //< return a Slic3r::Pointf corresponding to the textctrl contents.
    Slic3r::Pointf3 get_point3() override; //< return a Slic3r::Pointf3 corresponding to the textctrl contents.

    /// Function to call when the contents of this change.
    std::function<void (const std::string&, std::tuple<std::string, std::string> value)> on_change {nullptr};

    void enable() override { _ctrl_x->Enable(); _ctrl_y->Enable(); }
    void disable() override { _ctrl_x->Disable(); _ctrl_y->Disable(); }

    /// Local-access items
    wxTextCtrl* ctrl_x() { return _ctrl_x;}
    wxTextCtrl* ctrl_y() { return _ctrl_y;}

    wxStaticText* lbl_x() { return _lbl_x;}
    wxStaticText* lbl_y() { return _lbl_y;}

protected:
    virtual std::string LogChannel() override { return "UI_Point"s; }

    void _on_change(std::string opt_id) override {
        if (!this->disable_change_event && this->_ctrl_x->IsEnabled() && this->on_change != nullptr) {
            this->on_change(opt_id, std::make_tuple<std::string, std::string>(_ctrl_x->GetValue().ToStdString(), _ctrl_y->GetValue().ToStdString()));
        }
    }

private:
    wxSize field_size {40, 1};
    wxStaticText* _lbl_x {nullptr};
    wxStaticText* _lbl_y {nullptr};

    wxTextCtrl* _ctrl_x {nullptr};
    wxTextCtrl* _ctrl_y {nullptr};

    wxBoxSizer* _sizer {nullptr};

    void _set_value(Slic3r::Pointf value);
    void _set_value(Slic3r::Pointf3 value);
    void _set_value(std::string value);

    }

};

} } // Namespace Slic3r::GUI

#endif // SLIC3R_FIELD_HPP
<|endoftext|>


<commit_before>// Higher-order functions (HOFs) are functions that take other functions as their arguments.
// A basic example of a HOF is map which takes a function and a list as its arguments, applies
// the function to all elements of the list, and returns the list of its results.
// For instance, we can write a function that subtracts 2 from all elements of
// a list without using loops or recursion:

// subtractTwoFromList l = map (\x -> x - 2) l
//
//

#include<algorithm>

//The typename function should be a function object
//The typename sequence should be a sequence type
namespace fool{
  template<typename function, typename sequence>
  sequence& FMap(function &f,sequence &s)
  {
    std::for_each(s.begin(),s.end(),
        [&f](typename sequence::value_type& v) {
          f(v);
        });
    return s;
  }
}
<commit_msg>added terms and conditions along with examples as comment<commit_after>// This file is distributed under the MIT License. See http://www.opensource.org/licenses/mit-license.php
// for terms and conditions.
//
// Higher-order functions (HOFs) are functions that take other functions as their arguments.
// A basic example of a HOF is map which takes a function and a list as its arguments, applies
// the function to all elements of the list, and returns the list of its results.
// For instance, we can write a function that subtracts 2 from all elements of
// a list without using loops or recursion:

// subtractTwoFromList l = map (\x -> x - 2) l
//sample use case
//#include "hof.hpp"
//#include<iostream>
//#include<vector>
//using namespace fool;
//int main()
//{
//  std::vector<int> vi{1,2,3,4};
//  auto f = [](int& i){i+=2;};
//  FMap(f,vi);
//  for(auto v = vi.begin(); v != vi.end(); ++v)
//  {
//    std::cout<<*v<<"\t";
//  }
//  return 0;
//}

#include<algorithm>

//The typename function should be a function object
//The typename sequence should be a sequence type
namespace fool{
  template<typename function, typename sequence>
  sequence& FMap(function &f,sequence &s)
  {
    std::for_each(s.begin(),s.end(),
        [&f](typename sequence::value_type& v) {
          f(v);
        });
    return s;
  }
}
<|endoftext|>


<commit_before>#include "hash.hpp"

Hash::Hash() : prev(nullptr), flag(EMPTY) {}

Hash::~Hash() {
	clean();
}

bool Hash::back() {
	if(prev) {
		if(!prev->empty()) {
			move = prev->top();
			prev->pop();

			return true;
		}
	}

	return false;
}

void Hash::recordPrev() {
	if(flag == EXACT) {
		if(!prev) {
			prev = new std::stack<BitMove>();
		}

		prev->push(move);
	}
}

void Hash::clean() {
	if(prev) {
		while(!prev->empty()) {
			prev->pop();
		}

		delete prev;
		prev = nullptr;
	}

	//flag = EMPTY;
}
<commit_msg>cancelled experemental<commit_after>#include "hash.hpp"

Hash::Hash() : prev(nullptr), flag(EMPTY) {}

Hash::~Hash() {
	clean();
}

bool Hash::back() {
	if(prev) {
		if(!prev->empty()) {
			move = prev->top();
			prev->pop();

			return true;
		}
	}

	return false;
}

void Hash::recordPrev() {
	if(flag == EXACT) {
		if(!prev) {
			prev = new std::stack<BitMove>();
		}

		prev->push(move);
	}
}

void Hash::clean() {
	if(prev) {
		while(!prev->empty()) {
			prev->pop();
		}

		delete prev;
		prev = nullptr;
	}

	flag = EMPTY;
}
<|endoftext|>


<commit_before>// ***************************************************************************
// bamtools.cpp (c) 2010 Derek Barnett, Erik Garrison
// Marth Lab, Department of Biology, Boston College
// All rights reserved.
// ---------------------------------------------------------------------------
// Last modified: 22 July 2010
// ---------------------------------------------------------------------------
// Integrates a number of BamTools functionalities into a single executable.
// ***************************************************************************

// Std C/C++ includes
#include <iostream>

// BamTools includes
#include "bamtools_convert.h"
#include "bamtools_count.h"
#include "bamtools_coverage.h"
#include "bamtools_filter.h"
#include "bamtools_header.h"
#include "bamtools_index.h"
#include "bamtools_merge.h"
#include "bamtools_random.h"
#include "bamtools_sort.h"
#include "bamtools_stats.h"

using namespace std;
using namespace BamTools;

// ------------------------------------------
// bamtools subtool names
static const string CONVERT  = "convert";
static const string COUNT    = "count";
static const string COVERAGE = "coverage";
static const string FILTER   = "filter";
static const string HEADER   = "header";
static const string INDEX    = "index";
static const string MERGE    = "merge";
static const string RANDOM   = "random";
static const string SORT     = "sort";
static const string STATS    = "stats";

// ------------------------------------------
// bamtools help/version names
static const string HELP       = "help";
static const string LONG_HELP  = "--help";
static const string SHORT_HELP = "-h";

static const string VERSION       = "version";
static const string LONG_VERSION  = "--version";
static const string SHORT_VERSION = "-v";

// ------------------------------------------
// Print help info
int Help(int argc, char* argv[]) {

    // 'bamtools help COMMAND'
    if (argc > 2) {

        AbstractTool* tool(0);
        if ( argv[2] == CONVERT )  tool = new ConvertTool;
        if ( argv[2] == COUNT )    tool = new CountTool;
        if ( argv[2] == COVERAGE ) tool = new CoverageTool;
        if ( argv[2] == FILTER )   tool = new FilterTool;
        if ( argv[2] == HEADER )   tool = new HeaderTool;
        if ( argv[2] == INDEX )    tool = new IndexTool;
        if ( argv[2] == MERGE )    tool = new MergeTool;
        if ( argv[2] == RANDOM )   tool = new RandomTool;
        if ( argv[2] == SORT )     tool = new SortTool;
        if ( argv[2] == STATS )    tool = new StatsTool;

        // if tool known, print its help screen
        if ( tool ) return tool->Help();
    }

    // either 'bamtools help' or unrecognized argument after 'help'
    cerr << endl;
    cerr << "usage: bamtools [--help] COMMAND [ARGS]" << endl;
    cerr << endl;
    cerr << "Available bamtools commands:" << endl;
    cerr << "\tconvert   Converts between BAM and a number of other formats" << endl;
    cerr << "\tcount     Prints number of alignments in BAM file" << endl;
    cerr << "\tcoverage  Prints coverage statistics from the input BAM file" << endl;
    cerr << "\tfilter    Filters BAM file(s) by user-specified criteria" << endl;
    cerr << "\theader    Prints BAM header information" << endl;
    cerr << "\tindex     Generates index for BAM file" << endl;
    cerr << "\tmerge     Merge multiple BAM files into single file" << endl;
    cerr << "\trandom    Grab a random subset of alignments" << endl;
    cerr << "\tsort      Sorts the BAM file according to some criteria" << endl;
    cerr << "\tstats     Prints some basic statistics from the input BAM file" << endl;
    cerr << endl;
    cerr << "See 'bamtools help COMMAND' for more information on a specific command." << endl;
    cerr << endl;
    return 0;
}

// ------------------------------------------
// Print version info
int Version(void) {
    cout << endl;
    cout << "bamtools v0.8.xx" << endl;
    cout << "Part of BamTools API and toolkit" << endl;
    cout << "Primary authors: Derek Barnett, Erik Garrison, Michael Stromberg" << endl;
    cout << "(c) 2009-2010 Marth Lab, Biology Dept., Boston College" << endl;
    cout << endl;
    return 0;
}

// ------------------------------------------
// toolkit entry point
int main(int argc, char* argv[]) {

    // just 'bamtools'
    if ( (argc == 1) ) return Help(argc, argv);

    // 'bamtools help', 'bamtools --help', or 'bamtools -h'
    if ( (argv[1] == HELP) || (argv[1] == LONG_HELP) || (argv[1] == SHORT_HELP) ) return Help(argc, argv);

    // 'bamtools version', 'bamtools --version', or 'bamtools -v'
    if ( (argv[1] == VERSION) || (argv[1] == LONG_VERSION) || (argv[1] == SHORT_VERSION) ) return Version();

    // determine desired sub-tool
    AbstractTool* tool(0);
    if ( argv[1] == CONVERT )  tool = new ConvertTool;
    if ( argv[1] == COUNT )    tool = new CountTool;
    if ( argv[1] == COVERAGE ) tool = new CoverageTool;
    if ( argv[1] == FILTER )   tool = new FilterTool;
    if ( argv[1] == HEADER )   tool = new HeaderTool;
    if ( argv[1] == INDEX )    tool = new IndexTool;
    if ( argv[1] == MERGE )    tool = new MergeTool;
    if ( argv[1] == RANDOM )   tool = new RandomTool;
    if ( argv[1] == SORT )     tool = new SortTool;
    if ( argv[1] == STATS )    tool = new StatsTool;

    // if found, run tool
    if ( tool ) return tool->Run(argc, argv);
    // no match found, show help
    else return Help(argc, argv);
}
<commit_msg>Reworded bamtools stats general help description<commit_after>// ***************************************************************************
// bamtools.cpp (c) 2010 Derek Barnett, Erik Garrison
// Marth Lab, Department of Biology, Boston College
// All rights reserved.
// ---------------------------------------------------------------------------
// Last modified: 22 July 2010
// ---------------------------------------------------------------------------
// Integrates a number of BamTools functionalities into a single executable.
// ***************************************************************************

// Std C/C++ includes
#include <iostream>

// BamTools includes
#include "bamtools_convert.h"
#include "bamtools_count.h"
#include "bamtools_coverage.h"
#include "bamtools_filter.h"
#include "bamtools_header.h"
#include "bamtools_index.h"
#include "bamtools_merge.h"
#include "bamtools_random.h"
#include "bamtools_sort.h"
#include "bamtools_stats.h"

using namespace std;
using namespace BamTools;

// ------------------------------------------
// bamtools subtool names
static const string CONVERT  = "convert";
static const string COUNT    = "count";
static const string COVERAGE = "coverage";
static const string FILTER   = "filter";
static const string HEADER   = "header";
static const string INDEX    = "index";
static const string MERGE    = "merge";
static const string RANDOM   = "random";
static const string SORT     = "sort";
static const string STATS    = "stats";

// ------------------------------------------
// bamtools help/version names
static const string HELP       = "help";
static const string LONG_HELP  = "--help";
static const string SHORT_HELP = "-h";

static const string VERSION       = "version";
static const string LONG_VERSION  = "--version";
static const string SHORT_VERSION = "-v";

// ------------------------------------------
// Print help info
int Help(int argc, char* argv[]) {

    // 'bamtools help COMMAND'
    if (argc > 2) {

        AbstractTool* tool(0);
        if ( argv[2] == CONVERT )  tool = new ConvertTool;
        if ( argv[2] == COUNT )    tool = new CountTool;
        if ( argv[2] == COVERAGE ) tool = new CoverageTool;
        if ( argv[2] == FILTER )   tool = new FilterTool;
        if ( argv[2] == HEADER )   tool = new HeaderTool;
        if ( argv[2] == INDEX )    tool = new IndexTool;
        if ( argv[2] == MERGE )    tool = new MergeTool;
        if ( argv[2] == RANDOM )   tool = new RandomTool;
        if ( argv[2] == SORT )     tool = new SortTool;
        if ( argv[2] == STATS )    tool = new StatsTool;

        // if tool known, print its help screen
        if ( tool ) return tool->Help();
    }

    // either 'bamtools help' or unrecognized argument after 'help'
    cerr << endl;
    cerr << "usage: bamtools [--help] COMMAND [ARGS]" << endl;
    cerr << endl;
    cerr << "Available bamtools commands:" << endl;
    cerr << "\tconvert   Converts between BAM and a number of other formats" << endl;
    cerr << "\tcount     Prints number of alignments in BAM file" << endl;
    cerr << "\tcoverage  Prints coverage statistics from the input BAM file" << endl;
    cerr << "\tfilter    Filters BAM file(s) by user-specified criteria" << endl;
    cerr << "\theader    Prints BAM header information" << endl;
    cerr << "\tindex     Generates index for BAM file" << endl;
    cerr << "\tmerge     Merge multiple BAM files into single file" << endl;
    cerr << "\trandom    Grab a random subset of alignments" << endl;
    cerr << "\tsort      Sorts the BAM file according to some criteria" << endl;
    cerr << "\tstats     Prints general alignment statistics" << endl;
    cerr << endl;
    cerr << "See 'bamtools help COMMAND' for more information on a specific command." << endl;
    cerr << endl;
    return 0;
}

// ------------------------------------------
// Print version info
int Version(void) {
    cout << endl;
    cout << "bamtools v0.8.xx" << endl;
    cout << "Part of BamTools API and toolkit" << endl;
    cout << "Primary authors: Derek Barnett, Erik Garrison, Michael Stromberg" << endl;
    cout << "(c) 2009-2010 Marth Lab, Biology Dept., Boston College" << endl;
    cout << endl;
    return 0;
}

// ------------------------------------------
// toolkit entry point
int main(int argc, char* argv[]) {

    // just 'bamtools'
    if ( (argc == 1) ) return Help(argc, argv);

    // 'bamtools help', 'bamtools --help', or 'bamtools -h'
    if ( (argv[1] == HELP) || (argv[1] == LONG_HELP) || (argv[1] == SHORT_HELP) ) return Help(argc, argv);

    // 'bamtools version', 'bamtools --version', or 'bamtools -v'
    if ( (argv[1] == VERSION) || (argv[1] == LONG_VERSION) || (argv[1] == SHORT_VERSION) ) return Version();

    // determine desired sub-tool
    AbstractTool* tool(0);
    if ( argv[1] == CONVERT )  tool = new ConvertTool;
    if ( argv[1] == COUNT )    tool = new CountTool;
    if ( argv[1] == COVERAGE ) tool = new CoverageTool;
    if ( argv[1] == FILTER )   tool = new FilterTool;
    if ( argv[1] == HEADER )   tool = new HeaderTool;
    if ( argv[1] == INDEX )    tool = new IndexTool;
    if ( argv[1] == MERGE )    tool = new MergeTool;
    if ( argv[1] == RANDOM )   tool = new RandomTool;
    if ( argv[1] == SORT )     tool = new SortTool;
    if ( argv[1] == STATS )    tool = new StatsTool;

    // if found, run tool
    if ( tool ) return tool->Run(argc, argv);
    // no match found, show help
    else return Help(argc, argv);
}
<|endoftext|>