<commit_before>//Cody Grinstead
// CSCI 480
// Huffman Encode
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
#include <queue>

using namespace std;
const int totalchar = 128;
//phnz.jcnf.xmmd.nafp.xwna.rwfa.hfzn.cjpn

struct charFequ
{
public:
	char character;
	int frequency;

	bool operator<(const charFequ& c) const
	{
		return frequency > c.frequency;
	}
};

struct table
{
public:
	char c;
	string b;
};

struct HuffmanTree {
	char character;
	int frequency;
	struct HuffmanTree *left;
	struct HuffmanTree *right;
	HuffmanTree(char c, int f, struct HuffmanTree *left = NULL,
		struct HuffmanTree *right = NULL) :
		character(c), frequency(f), left(left), right(right) {
	}
	~HuffmanTree() {
		delete left, delete right;
	}
		class Compare {
	public:
		bool operator()(HuffmanTree *a, HuffmanTree *b) {
			return a->frequency > b->frequency;
		}
	};
};

void readin(deque<string> &s)
{
	ifstream inf;
	int lineCount = 0;
	string getl;
	inf.open("Text.txt");
	while (!inf.eof())
	{
		getline(inf, getl);
		s.push_back(getl);
	}
	inf.close();

}

void get_freq(deque<string> s,charFequ cf[],int &cf_elemnts)
{

	string current_line;
	int line_length;
	int elements_array = 0;
	bool doesExist = true;
	while (!s.empty())
	{
		current_line = s.front();
		s.pop_front();
		line_length = current_line.size();
		for (int i = 0; i < line_length; i++)
		{
			if (elements_array == 0)
			{
				cf[0].character = current_line[0];
				cf[0].frequency = 1;
				elements_array++;
				doesExist = true;
			}
			else
			{
				for (int j = 0; j < elements_array; j++)
				{
					if (cf[j].character == current_line[i])
					{
						cf[j].frequency++;
						doesExist = true;
						break;
					}
					else
						doesExist = false;
				}

			}
			if (!doesExist)
			{
				cf[elements_array].character = current_line[i];
				cf[elements_array].frequency = 1;
				elements_array++;
				doesExist=true;
			}
		}
	}
	cf_elemnts = elements_array;
}

void write_file()
{
	//Create file with exten.
	//print idenitfier
	//print array of char to compression value
}

HuffmanTree *build_tree(priority_queue<charFequ> &in)
{
	priority_queue<HuffmanTree *, vector<HuffmanTree *>, HuffmanTree::Compare> heap;
	charFequ xfer;
	while (!in.empty())
	{
		xfer = in.top();
		in.pop();
		HuffmanTree *leaf = new HuffmanTree(xfer.character, xfer.frequency);
		heap.push(leaf);
	}
	HuffmanTree *root = NULL;
	while (heap.size() > 1)
	{
		HuffmanTree *left, *right;
		left = heap.top();
		heap.pop();
		right = heap.top();
		heap.pop();
		root = new HuffmanTree('-', left->frequency + right->frequency, left, right);
		heap.push(root);
	}
	return root;
}

void print_tree(HuffmanTree *t) {
	deque< pair<HuffmanTree *, int> > q;

	q.push_back(make_pair(t, 0));
	int curlevel = -1;
	while (!q.empty()) {
		HuffmanTree *parent = q.front().first;
		int level = q.front().second;
		q.pop_front();
		if (curlevel != level) {
			curlevel = level;
			cout << "Level " << curlevel << endl;
		}
		cout << parent->frequency << " " << parent->character << endl;
		if (parent->left)
			q.push_back(make_pair(parent->left, level + 1));
		if (parent->right)
			q.push_back(make_pair(parent->right, level + 1));
	}
}

void create_table(HuffmanTree *t, table tab[],int elements)
{
	while (t->left != NULL)
	{

	}
}

int main(int argc, char *argv[])
{
	charFequ this_file[totalchar];
	deque<string> File_In;
	charFequ encode[totalchar];
	readin(File_In);
	/*ifstream inf;
	inf.open(argv[0]);
	int lineCount = 0;
	while (!inf.eof())
	{
		getline(inf, getl);
		File_In.push_back(getl);
	}
	inf.close();//*/
	priority_queue<charFequ> pq_file_in;
	int array_elements = 0, num_chars = 0;
	charFequ temp_xfer;

	get_freq(File_In, this_file,array_elements);
	for (int i = 0; i < array_elements; i++)
	{
		pq_file_in.push(this_file[i]);
	}
	HuffmanTree *root= build_tree(pq_file_in);
	//print_tree(root);
	/* testing count
	while (!pq_file_in.empty())
	{
		temp_xfer = pq_file_in.top();
		pq_file_in.pop();
		cout << temp_xfer.character <<" "<< temp_xfer.frequency << endl;
	}
	*/

	system("pause");
	return 0;
}<commit_msg>added string to bit output/working on table<commit_after>//Cody Grinstead
// CSCI 480
// Huffman Encode
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <bitset>

using namespace std;
const int totalchar = 128;
struct charFequ
{
public:
	char character;
	int frequency;

	bool operator<(const charFequ& c) const
	{
		return frequency > c.frequency;
	}
};

struct table
{
public:
	char c;
	string b;
};

struct HuffmanTree {
	char character;
	int frequency;
	string codetable;
	struct HuffmanTree *left;
	struct HuffmanTree *right;

	HuffmanTree(char c, int f, struct HuffmanTree *left = NULL,
		struct HuffmanTree *right = NULL) :
		character(c), frequency(f), left(left), right(right) {
	}

	class Compare {
	public:
		bool operator()(HuffmanTree *a, HuffmanTree *b) {
			return a->frequency > b->frequency;
		}

	};
};

void readin(deque<string> &s)
{
	ifstream inf;
	int lineCount = 0;
	string getl;
	inf.open("Text.txt");
	while (!inf.eof())
	{
		getline(inf, getl);
		s.push_back(getl);
	}
	inf.close();

}

void get_freq(deque<string> s,charFequ cf[],int &cf_elemnts)
{

	string current_line;
	int line_length;
	int elements_array = 0;
	bool doesExist = true;
	while (!s.empty())
	{
		current_line = s.front();
		s.pop_front();
		line_length = current_line.size();
		for (int i = 0; i < line_length; i++)
		{
			if (elements_array == 0)
			{
				cf[0].character = current_line[0];
				cf[0].frequency = 1;
				elements_array++;
				doesExist = true;
			}
			else
			{
				for (int j = 0; j < elements_array; j++)
				{
					if (cf[j].character == current_line[i])
					{
						cf[j].frequency++;
						doesExist = true;
						break;
					}
					else
						doesExist = false;
				}

			}
			if (!doesExist)
			{
				cf[elements_array].character = current_line[i];
				cf[elements_array].frequency = 1;
				elements_array++;
				doesExist=true;
			}
		}
	}
	cf_elemnts = elements_array;
}

bitset<8> string_to_bit(string byte)
{
	bitset<8> ans(byte);
	return ans;
}

void write_file(string docbit,ofstream &outf)
{
	int bit_mod = docbit.size() % 8;
	string bytes;

	for (int i = 0; i < docbit.size(); i += 8)
	{
		bytes = "";
		bytes += docbit[i];
		bytes += docbit[i + 1];
		bytes += docbit[i + 2];
		bytes += docbit[i + 3];
		bytes += docbit[i + 4];
		bytes += docbit[i + 5];
		bytes += docbit[i + 6];
		bytes += docbit[i + 7];
		outf << string_to_bit(bytes);
	}
	bytes = "";
	if (bit_mod == 1)
	{
		bytes = docbit[docbit.size() - 1];
		bytes += "0000000";
		outf << string_to_bit(bytes);
	}
	else if (bit_mod == 2)
	{
		bytes = docbit[docbit.size() - 2];
		bytes += docbit[docbit.size() - 1];
		bytes += "000000";
		outf << string_to_bit(bytes);
	}
	else if (bit_mod == 3)
	{
		bytes = docbit[docbit.size() - 3];
		bytes += docbit[docbit.size() - 2];
		bytes += docbit[docbit.size() - 1];
		bytes += "00000";
		outf << string_to_bit(bytes);
	}
	else if (bit_mod == 4)
	{
		bytes = docbit[docbit.size() - 4];
		bytes += docbit[docbit.size() - 3];
		bytes += docbit[docbit.size() - 2];
		bytes += docbit[docbit.size() - 1];
		bytes += "0000";
		outf << string_to_bit(bytes);
	}
	else if (bit_mod == 5)
	{
		bytes = docbit[docbit.size() - 5];
		bytes += docbit[docbit.size() - 4];
		bytes += docbit[docbit.size() - 3];
		bytes += docbit[docbit.size() - 2];
		bytes += docbit[docbit.size() - 1];
		bytes += "000";
		outf << string_to_bit(bytes);
	}
	else if (bit_mod == 6)
	{
		bytes = docbit[docbit.size() - 6];
		bytes += docbit[docbit.size() - 5];
		bytes += docbit[docbit.size() - 4];
		bytes += docbit[docbit.size() - 3];
		bytes += docbit[docbit.size() - 2];
		bytes += docbit[docbit.size() - 1];
		bytes += "00";
		outf << string_to_bit(bytes);
	}
	else
	{
		bytes = docbit[docbit.size() - 7];
		bytes += docbit[docbit.size() - 6];
		bytes += docbit[docbit.size() - 5];
		bytes += docbit[docbit.size() - 4];
		bytes += docbit[docbit.size() - 3];
		bytes += docbit[docbit.size() - 2];
		bytes += docbit[docbit.size() - 1];
		bytes += "0";
		outf << string_to_bit(bytes);
	}

}

void print_tree(HuffmanTree *t) {
	deque< pair<HuffmanTree *, int> > q;
	int i = 0;
	q.push_back(make_pair(t, 0));
	int curlevel = -1;
	while (!q.empty()) {
		HuffmanTree *parent = q.front().first;
		int level = q.front().second;
		q.pop_front();
		if (curlevel != level) {
			curlevel = level;
			cout << "Level " << curlevel << endl;

		}
		cout << parent->frequency << " " << parent->character << " " << parent->codetable << endl;

		if (parent->left)
			q.push_back(make_pair(parent->left, level + 1));
		if (parent->right)
			q.push_back(make_pair(parent->right, level + 1));
	}
}

void leafpad(HuffmanTree *left)
{
	//print_tree(left);
	HuffmanTree *newleaf, *newleft, *newright;
	while (left)
	{
		newleaf = left;
		newleft = newleaf->left;
		newright = newleaf->right;
		if (!newleft)break;
		cout << newright->character << " " << newleft->character << endl;
		system("pause");
		newleft->codetable += "0";
		newright->codetable += "1";

		leafpad(newleft);
		leafpad(newright);
		cout << "exitwhile" << endl;
	}
	//cout << "exit leafpad" << endl;
}

HuffmanTree *build_tree(priority_queue<charFequ> &in)
{
	priority_queue<HuffmanTree *, vector<HuffmanTree *>, HuffmanTree::Compare> heap;
	charFequ xfer;
	string leftc = "0", rightc = "1";
	while (!in.empty())
	{
		xfer = in.top();
		in.pop();
		HuffmanTree *leaf = new HuffmanTree(xfer.character, xfer.frequency);
		heap.push(leaf);
	}
	HuffmanTree *root = NULL;
	while (heap.size() > 1)
	{
		HuffmanTree *left, *right;
		HuffmanTree *newleft, *newright;
		left = heap.top();
		left->codetable = "0";
		heap.pop();
		leafpad(left);
		cout << "leaf left " << endl;
		right = heap.top();
		right->codetable = "1";
		heap.pop();
		leafpad(right);
		cout << "leaf right" << endl;
		root = new HuffmanTree('`', left->frequency + right->frequency, left, right);

		heap.push(root);
	}
	return root;
}

string table_bit(table t[], char l, int elements)
{
	for (int i = 0; i < elements; i++)
	{
		if (l == t[i].c)return t[i].b;
	}
}

string bit_stream(table t[], string doc, int elements)
{
	string doc_bit = "";
	char cl;
	for (int i = 0; i < doc.size(); i++)
	{
		cl = doc[i];
		doc_bit += table_bit(t, cl, elements);
	}
	return doc_bit;
}

string search_tree(HuffmanTree *t)
{
	string ans;

	return ans;
}

void create_table(HuffmanTree *t, table tab[],int elements,charFequ inl[])
{
	string code;
	int level;

	for (int i = 0; i < elements; i++)
	{
		tab[i].c = inl[i].character;
		tab[i].b = search_tree(t);
	}

}

int main(int argc, char *argv[])
{
	charFequ this_file[totalchar];
	deque<string> File_In;
	charFequ encode[totalchar];
	readin(File_In);
	string getl, document;
	ifstream inf;
	inf.open("Text.txt");
	int lineCount = 0;

	while (!inf.eof())
	{
		getline(inf, getl);
		document += getl;
		File_In.push_back(getl);
	}
	inf.close();//*/
	priority_queue<charFequ> pq_file_in;
	int array_elements = 0, num_chars = 0;
	charFequ temp_xfer;

	get_freq(File_In, this_file,array_elements);
	for (int i = 0; i < array_elements; i++)
	{
		pq_file_in.push(this_file[i]);
	}
	HuffmanTree *root= build_tree(pq_file_in);
	//print_tree(root);
	/* testing count
	while (!pq_file_in.empty())
	{
		temp_xfer = pq_file_in.top();
		pq_file_in.pop();
		cout << temp_xfer.character <<" "<< temp_xfer.frequency << endl;
	}
	*/
	cout << document.size() << endl;

	system("pause");
	return 0;
}<|endoftext|>


<commit_before>#include <math.h>
#include "WPILib.h"

// TODO Make sure all of the code is well commented

//
// This is the class for our robot. It builds off of the IterativeRobot
// class.
//
class Team316Robot : public IterativeRobot
{
private:
	DriverStation *ds;

	// Joysticks

	Joystick *driverStick;		// XBox controller for driver
	Joystick *operatorStick;	// Logitech joystick for operator

	// Motors

	RobotDrive *driveMotors; 	// robot drive system
	Jaguar *shooterMotor;		// motor for shooter
	Jaguar *turretMotor;		// motor for turret rotation

	// Solenoids

	Compressor *compressor;		// the compressor
	Solenoid *upperBallUp;		// upper ball lift solenoid (up channel)
	Solenoid *upperBallDown;	// upper ball lift solenoid (down channel)
	Solenoid *lowerBallUp;		// lower ball lift solenoid (up channel)
	Solenoid *lowerBallDown;	// lower ball lift solenoid (down channel)
	Solenoid *bridgeUp;			// bridge solenoid (up channel)
	Solenoid *bridgeDown;		// bridge solenoid (down channel)

	// Relays

	Relay *ballPickup;			// relay for ball pickup belt

	// Counters

	Counter *speedCounter;		// shooter speed counter

	// Digitial Inputs

	DigitalInput *turretLimitLeft;		// left limit switch for turret
	DigitalInput *turretLimitRight;		// right limit switch for turret
	DigitalInput *ballLoad;				// optical sensor for ball lift

	// Global data

	int autoMode;		// which autonomous mode are we running?
	int autoStep;		// which step in autonomous mode are we in?
	double startTime;	// used to record the starting time in autonomous

	// Camera data

	int maxWidth;
	int targetWd;
	int targetHt;
	int targetX;
	int targetY;

public:
	//
	// Team316Robot()
	//
	// The only constructor; allocates memory for the dynamic member variables.
	//
	Team316Robot(void)
	{
		ds = DriverStation::GetInstance();

		driverStick = new Joystick(1);
		operatorStick = new Joystick(2);

		driveMotors = new RobotDrive(1, 2);
		driveMotors->SetExpiration(0.75);
		shooterMotor = new Jaguar(5);
		turretMotor = new Jaguar(6);

		compressor = new Compressor(14, 1);
		upperBallUp = new Solenoid(1);
		upperBallDown = new Solenoid(2);
		lowerBallUp = new Solenoid(3);
		lowerBallDown = new Solenoid(4);
		bridgeUp = new Solenoid(5);
		bridgeDown = new Solenoid(6);

		ballPickup = new Relay(2);

		speedCounter = new Counter(8);

		turretLimitLeft = new DigitalInput(4);
		turretLimitRight = new DigitalInput(5);
		ballLoad = new DigitalInput(3);
	}

	//
	// RobotInit()
	//
	// Initialize the robot state
	//
	void RobotInit(void)
	{
		// Setup compressor and solenoids

		compressor->Start();

		upperBallUp->Set(false);
		upperBallDown->Set(true);
		lowerBallUp->Set(true);
		lowerBallDown->Set(false);
		bridgeUp->Set(false);
		bridgeDown->Set(true);

		// Start the counter

		speedCounter->Start();

		// Setup the camera

		AxisCamera &camera = AxisCamera::GetInstance();
		camera.WriteResolution(AxisCamera::kResolution_320x240);
		camera.WriteCompression(40);	// might want to try 10
		camera.WriteBrightness(50);		// might want to try lowering
	}

	//
	// DisabledInit()
	//
	// Called once upon entering a disabled state. All outputs should be
	// stopped here for safety.
	//
	void DisabledInit()
	{
		// Put any tasks here to be run when the robot is disabled
	}

	//
	// DisabledPeriodic()
	//
	// Called at a regular interval while the robot is disabled. Place tasks
	// such as updating/resetting sensor values
	//
	void DisablePeriodic() {}	// Nothing to be done here for now

	//
	// TeleopInit()
	//
	// Called once when entering teleop mode. Setup for teleop mode.
	//
	void TeleopInit()
	{
		compressor->Start();
	}

	//
	// TeleopPeriodic()
	//
	// Called at a regular interval (approx. 20ms) during teleop mode.
	// The majority of the teleop code goes here. It is important to
	// make sure this function is not delayed, so don't place any
	// wait statements or loops here.
	//
	void TeleopPeriodic()
	{
		// TODO Divide teleop into functions for each section

		// Drive Motors

		const float DEADBAND = 0.2;

		float drive_x = driverStick->GetX();
		float drive_y = driverStick->GetY();
		float drive_rot = driverStick->GetAxis(Joystick::kTwistAxis);

		if (fabs(drive_x) < DEADBAND)
		{
			drive_x = 0;
		}
		if (fabs(drive_y) < DEADBAND)
		{
			drive_y = 0;
		}
		if (fabs(drive_rot) < DEADBAND)
		{
			drive_rot = 0;
		}

		driveMotors->MecanumDrive_Cartesian(drive_x, drive_y, drive_rot);

		// Turret control

		float turretVal = operatorStick->GetX();
		turretVal *= -0.5;

		if (operatorStick->GetRawButton(2))
		{
			/*
			FindTarget();
			error = 160 - targetX;
			turretVal = error * kScaling;
			*/
		}

		if (turretLimitLeft->Get() && turretVal > 0)
		{
			turretVal = 0;
		}
		else if (turretLimitRight->Get() && turretVal < 0)
		{
			turretVal = 0;
		}

		turretMotor->Set(turretVal);

		// Ball pickup

		if (operatorStick->GetRawButton(2))
		{
			ballPickup->Set(Relay::kForward);
		}
		else
		{
			ballPickup->Set(Relay::kOff);
		}

		// Ball loading/firing

		if (operatorStick->GetRawButton(4))
		{
			lowerBallDown->Set(true);
			lowerBallUp->Set(false);
		}
		else if (operatorStick->GetRawButton(5) || ballLoad->Get())
		{
			lowerBallUp->Set(true);
			lowerBallDown->Set(false);
		}

		if (operatorStick->GetRawButton(1))
		{
			upperBallUp->Set(true);
			upperBallDown->Set(false);
		}
		else
		{
			upperBallDown->Set(true);
			upperBallUp->Set(true);
		}

		// Shooter

		if (operatorStick->GetRawButton(10))
		{
			shooterMotor->Set(-1.0);
		}

		// SAM Jack

		if (operatorStick->GetRawButton(6))
		{
			bridgeUp->Set(true);
			bridgeDown->Set(false);
		}
		else
		{
			bridgeUp->Set(false);
			bridgeDown->Set(true);
		}
	}

	//
	// AutonomousInit()
	//
	// Called right before entering autonomous mode. Setup the
	// robot for autonomous mode.
	//
	void AutonomousInit()
	{
		autoMode = (int) ds->GetAnalogIn(1);
		autoStep = 1;
		startTime = GetClock();
	}

	//
	// AutonomousPeriodic()
	//
	// Called at a regular interval (approx. 20ms) during autonomus mode.
	// Will call one of the autonomous routines below depending on the value of autoMode
	//
	void AutonomousPeriodic()
	{
		switch (autoMode)
		{
		case 0:
			break;
		case 1:
			AutonomousModeOne();	// run Autonomous routine 1
			break;
		default:

			break;
		}
	}

	void AutonomousModeOne()
	{
		// TODO Finish writing autonomous mode one
		if (autoStep == 1)
		{
			// Power motor and setup pistons

			shooterMotor->Set(-1.0);
			upperBallUp->Set(false);
			upperBallDown->Set(true);
			lowerBallUp->Set(true);
			lowerBallDown->Set(false);

			// Check if we're ready to advance to the next step

			if ((GetClock() - startTime) > 2.0)
			{
				autoStep = 2;
				startTime = GetClock();
			}
		}

		else if (autoStep == 2)
		{
			// Fire the first shot

			upperBallUp->Set(true);
			upperBallDown->Set(false);

			shooterMotor->Set(-1.0);

			if ((GetClock() - startTime) > 0.5)
			{
				autoStep++;
				startTime = GetClock();
			}
		}

		else if (autoStep == 3)
		{

		}
	}

	//
	// FindTarget()
	//
	// Analyzes a camera image and updates the position of the target
	//
	void FindTarget()
	{
		AxisCamera &camera = AxisCamera::GetInstance();
		if (camera.IsFreshImage())
		{
			ColorImage image(IMAQ_IMAGE_HSL);
			camera.GetImage(&image);

			// HSL Threshold

			BinaryImage *binImage;
			binImage = image.ThresholdHSL(128, 255, 13, 255, 249, 255);

			// Remove small objects

			BinaryImage *bigObjectsImage;
			bigObjectsImage = binImage->RemoveSmallObjects(false, 2);

			int size = binImage->GetNumberParticles();

			// Convex hull

			BinaryImage *convexHullImage;
			convexHullImage = bigObjectsImage->ConvexHull(false);

			// Particle analysis

			vector <ParticleAnalysisReport> *vPAR = convexHullImage->GetOrderedParticleAnalysisReports();

			if (size > 0)
			{
				for (int i = 0; i < (int) vPAR->size(); i++)
				{
					ParticleAnalysisReport *par = &(vPAR->at(i));

					int width = par->boundingRect.width;
					int height = par->boundingRect.height;
					float area = par->particleArea;

					if (i == 0)
					{
						maxWidth = 0;
						targetWd = 0;
						targetHt = 0;
						targetX = 320;
						targetY = 240;
					}

					if ((width > 40) && (area / (width*height)) > 0.75)
					{
						if (width > maxWidth) maxWidth = width;
						if (par->center_mass_y < targetY)
						{
							targetWd = width;
							targetHt = height;
							targetX = par->center_mass_x;
							targetY = par->center_mass_y;
						}

						printf("W = %d, H = %d, X = %d, Y = %d\n", targetWd, targetHt, targetX, targetY);
					}
				}

				printf("X = %d, Y = %d\n", targetX, targetY);
			}

			delete ℑ
			delete binImage;
			delete bigObjectsImage;
			delete vPAR;
		} /* camera.IsFreshImage() */
	}
};

START_ROBOT_CLASS(Team316Robot);

<commit_msg>Finish writing AutonomousModeOne<commit_after>#include <math.h>
#include "WPILib.h"

// TODO Make sure all of the code is well commented

//
// This is the class for our robot. It builds off of the IterativeRobot
// class.
//
class Team316Robot : public IterativeRobot
{
private:
	DriverStation *ds;

	// Joysticks

	Joystick *driverStick;		// XBox controller for driver
	Joystick *operatorStick;	// Logitech joystick for operator

	// Motors

	RobotDrive *driveMotors; 	// robot drive system
	Jaguar *shooterMotor;		// motor for shooter
	Jaguar *turretMotor;		// motor for turret rotation

	// Solenoids

	Compressor *compressor;		// the compressor
	Solenoid *upperBallUp;		// upper ball lift solenoid (up channel)
	Solenoid *upperBallDown;	// upper ball lift solenoid (down channel)
	Solenoid *lowerBallUp;		// lower ball lift solenoid (up channel)
	Solenoid *lowerBallDown;	// lower ball lift solenoid (down channel)
	Solenoid *bridgeUp;			// bridge solenoid (up channel)
	Solenoid *bridgeDown;		// bridge solenoid (down channel)

	// Relays

	Relay *ballPickup;			// relay for ball pickup belt

	// Counters

	Counter *speedCounter;		// shooter speed counter

	// Digitial Inputs

	DigitalInput *turretLimitLeft;		// left limit switch for turret
	DigitalInput *turretLimitRight;		// right limit switch for turret
	DigitalInput *ballLoad;				// optical sensor for ball lift

	// Global data

	int autoMode;		// which autonomous mode are we running?
	int autoStep;		// which step in autonomous mode are we in?
	double startTime;	// used to record the starting time in autonomous
	bool autoTimedOut;	// did autonomous mode timeout

	// Camera data

	int maxWidth;
	int targetWd;
	int targetHt;
	int targetX;
	int targetY;

public:
	//
	// Team316Robot()
	//
	// The only constructor; allocates memory for the dynamic member variables.
	//
	Team316Robot(void)
	{
		ds = DriverStation::GetInstance();

		driverStick = new Joystick(1);
		operatorStick = new Joystick(2);

		driveMotors = new RobotDrive(1, 2);
		driveMotors->SetExpiration(0.75);
		shooterMotor = new Jaguar(5);
		turretMotor = new Jaguar(6);

		compressor = new Compressor(14, 1);
		upperBallUp = new Solenoid(1);
		upperBallDown = new Solenoid(2);
		lowerBallUp = new Solenoid(3);
		lowerBallDown = new Solenoid(4);
		bridgeUp = new Solenoid(5);
		bridgeDown = new Solenoid(6);

		ballPickup = new Relay(2);

		speedCounter = new Counter(8);

		turretLimitLeft = new DigitalInput(4);
		turretLimitRight = new DigitalInput(5);
		ballLoad = new DigitalInput(3);
	}

	//
	// RobotInit()
	//
	// Initialize the robot state
	//
	void RobotInit(void)
	{
		// Setup compressor and solenoids

		compressor->Start();

		upperBallUp->Set(false);
		upperBallDown->Set(true);
		lowerBallUp->Set(true);
		lowerBallDown->Set(false);
		bridgeUp->Set(false);
		bridgeDown->Set(true);

		// Start the counter

		speedCounter->Start();

		// Setup the camera

		AxisCamera &camera = AxisCamera::GetInstance();
		camera.WriteResolution(AxisCamera::kResolution_320x240);
		camera.WriteCompression(40);	// might want to try 10
		camera.WriteBrightness(50);		// might want to try lowering
	}

	//
	// DisabledInit()
	//
	// Called once upon entering a disabled state. All outputs should be
	// stopped here for safety.
	//
	void DisabledInit()
	{
		// Put any tasks here to be run when the robot is disabled
	}

	//
	// DisabledPeriodic()
	//
	// Called at a regular interval while the robot is disabled. Place tasks
	// such as updating/resetting sensor values
	//
	void DisablePeriodic() {}	// Nothing to be done here for now

	//
	// TeleopInit()
	//
	// Called once when entering teleop mode. Setup for teleop mode.
	//
	void TeleopInit()
	{
		compressor->Start();
	}

	//
	// TeleopPeriodic()
	//
	// Called at a regular interval (approx. 20ms) during teleop mode.
	// The majority of the teleop code goes here. It is important to
	// make sure this function is not delayed, so don't place any
	// wait statements or loops here.
	//
	void TeleopPeriodic()
	{
		// TODO Divide teleop into functions for each section

		// Drive Motors

		const float DEADBAND = 0.2;

		float drive_x = driverStick->GetX();
		float drive_y = driverStick->GetY();
		float drive_rot = driverStick->GetAxis(Joystick::kTwistAxis);

		if (fabs(drive_x) < DEADBAND)
		{
			drive_x = 0;
		}
		if (fabs(drive_y) < DEADBAND)
		{
			drive_y = 0;
		}
		if (fabs(drive_rot) < DEADBAND)
		{
			drive_rot = 0;
		}

		driveMotors->MecanumDrive_Cartesian(drive_x, drive_y, drive_rot);

		// Turret control

		float turretVal = operatorStick->GetX();
		turretVal *= -0.5;

		if (operatorStick->GetRawButton(2))
		{
			// Examine camera image and adjust turret
			/*
			FindTarget();
			error = 160 - targetX;
			turretVal = error * kScaling;
			*/
		}

		if (turretLimitLeft->Get() && turretVal > 0)
		{
			turretVal = 0;
		}
		else if (turretLimitRight->Get() && turretVal < 0)
		{
			turretVal = 0;
		}

		turretMotor->Set(turretVal);

		// Ball pickup

		if (operatorStick->GetRawButton(2))
		{
			ballPickup->Set(Relay::kForward);
		}
		else
		{
			ballPickup->Set(Relay::kOff);
		}

		// Ball loading/firing

		if (operatorStick->GetRawButton(4))
		{
			lowerBallDown->Set(true);
			lowerBallUp->Set(false);
		}
		else if (operatorStick->GetRawButton(5) || ballLoad->Get())
		{
			lowerBallUp->Set(true);
			lowerBallDown->Set(false);
		}

		if (operatorStick->GetRawButton(1))
		{
			upperBallUp->Set(true);
			upperBallDown->Set(false);
		}
		else
		{
			upperBallDown->Set(true);
			upperBallUp->Set(true);
		}

		// Shooter

		if (operatorStick->GetRawButton(10))
		{
			shooterMotor->Set(-1.0);
		}

		// SAM Jack

		if (operatorStick->GetRawButton(6))
		{
			bridgeUp->Set(true);
			bridgeDown->Set(false);
		}
		else
		{
			bridgeUp->Set(false);
			bridgeDown->Set(true);
		}
	}

	//
	// AutonomousInit()
	//
	// Called right before entering autonomous mode. Setup the
	// robot for autonomous mode.
	//
	void AutonomousInit()
	{
		autoMode = (int) ds->GetAnalogIn(1);
		autoStep = 1;
		startTime = GetClock();
	}

	//
	// AutonomousPeriodic()
	//
	// Called at a regular interval (approx. 20ms) during autonomus mode.
	// Will call one of the autonomous routines below depending on the value of autoMode
	//
	void AutonomousPeriodic()
	{
		switch (autoMode)
		{
		case 0:
			// Do nothing
			break;
		case 1:
			AutonomousModeOne();	// run Autonomous routine 1
			break;
		default:

			break;
		}
	}

	//
	// AutonomousModeOne()
	//
	// Fire two shots without aiming
	//
	void AutonomousModeOne()
	{
		if (autoStep == 1)
		{
			// Power motor and setup pistons

			shooterMotor->Set(-1.0);
			upperBallUp->Set(false);
			upperBallDown->Set(true);
			lowerBallUp->Set(true);
			lowerBallDown->Set(false);

			// Check if we're ready to advance to the next step

			if ((GetClock() - startTime) >= 2.0)
			{
				autoStep = 2;
				startTime = GetClock();
			}
		}

		else if (autoStep == 2)
		{
			// Fire the first shot

			upperBallUp->Set(true);
			upperBallDown->Set(false);

			shooterMotor->Set(-1.0);

			if ((GetClock() - startTime) >= 0.5)
			{
				autoStep++;
				startTime = GetClock();
			}
		}

		else if (autoStep == 3)
		{
			// Wait for the next ball to load

			const float TIMEOUT = 1.25;
			autoTimedOut = ((GetClock() - startTime) >= TIMEOUT);

			if (ballLoad->Get() || autoTimedOut)
			{
				autoStep++;
				startTime = GetClock();
			}

			shooterMotor->Set(-1.0);	// update the shooter motor value so it doesn't time out
		}

		else if (autoStep == 4)
		{
			// If ball failed to load, rapidly fire the piston up and down
			// to try and free the ball

			if (!autoTimedOut)	// if the ball loaded skip to next step
			{
				autoStep++;
				startTime = GetClock();
			}

			else
			{
				// fire the lower piston up and down

				shooterMotor->Set(-1.0);	// update the shooter motor value so it doesn't time out

				bool state = true;		// state of the piston: up (true) or down (false)
				int stateCount = 0;		// how many times have we switched states?

				if (stateCount < 3)		// are we done yet?
				{
					if ((GetClock() - startTime) >= 0.2)	// switch every 200 ms
					{
						state = !state;				// toggle piston state
						startTime = GetClock();		// reset timer
						stateCount++;				// increment state switch count
					}

					lowerBallUp->Set(state);		// set the piston state
					lowerBallDown->Set(!state);		// opposite of the other solenoid
				}

				else	// 1 second delay
				{
					lowerBallUp->Set(false);		// lower piston so ball can roll in
					lowerBallDown->Set(true);

					if ((GetClock() - startTime) >= 1)	// move on after 1 second
					{
						autoStep++;
						startTime = GetClock();
					}
				}
			}
		}		/* autostep == 4 */

		else if (autoStep == 5)
		{
			// load the ball and give motor time to reach full speed

			lowerBallUp->Set(true);
			lowerBallDown->Set(false);

			if ((GetClock() - startTime) >= 2)
			{
				autoStep++;
				startTime = GetClock();
			}
		}

		else if (autoStep == 6)
		{
			// fire the second shot

			upperBallUp->Set(true);
			upperBallDown->Set(false);

			shooterMotor->Set(-1.0);

			if ((GetClock() - startTime) >= 0.5)
			{
				autoStep++;
				startTime = GetClock();
			}
		}

		else if (autoStep == 7)
		{
			// stop all outputs and prep pistons for teleop

			upperBallUp->Set(false);
			upperBallDown->Set(true);
			lowerBallUp->Set(true);
			lowerBallDown->Set(false);

			shooterMotor->Set(0.0);

			autoStep++;

			cout << "AutonomousModeOne finished!" << endl;
		}

		else if (autoStep == 8)
		{
			// Nothing to be done; autonomous routine is done finished
		}
	}		/* AutonomousModeOne */

	//
	// FindTarget()
	//
	// Analyzes a camera image and updates the position of the target
	//
	void FindTarget()
	{
		AxisCamera &camera = AxisCamera::GetInstance();
		if (camera.IsFreshImage())
		{
			ColorImage image(IMAQ_IMAGE_HSL);
			camera.GetImage(&image);

			// HSL Threshold

			BinaryImage *binImage;
			binImage = image.ThresholdHSL(128, 255, 13, 255, 249, 255);

			// Remove small objects

			BinaryImage *bigObjectsImage;
			bigObjectsImage = binImage->RemoveSmallObjects(false, 2);

			int size = binImage->GetNumberParticles();

			// Convex hull

			BinaryImage *convexHullImage;
			convexHullImage = bigObjectsImage->ConvexHull(false);

			// Particle analysis

			vector <ParticleAnalysisReport> *vPAR = convexHullImage->GetOrderedParticleAnalysisReports();

			if (size > 0)
			{
				for (int i = 0; i < (int) vPAR->size(); i++)
				{
					ParticleAnalysisReport *par = &(vPAR->at(i));

					int width = par->boundingRect.width;
					int height = par->boundingRect.height;
					float area = par->particleArea;

					if (i == 0)
					{
						maxWidth = 0;
						targetWd = 0;
						targetHt = 0;
						targetX = 320;
						targetY = 240;
					}

					if ((width > 40) && (area / (width*height)) > 0.75)
					{
						if (width > maxWidth) maxWidth = width;
						if (par->center_mass_y < targetY)
						{
							targetWd = width;
							targetHt = height;
							targetX = par->center_mass_x;
							targetY = par->center_mass_y;
						}

						printf("W = %d, H = %d, X = %d, Y = %d\n", targetWd, targetHt, targetX, targetY);
					}
				}

				printf("X = %d, Y = %d\n", targetX, targetY);
			}

			delete ℑ
			delete binImage;
			delete bigObjectsImage;
			delete vPAR;
		} /* camera.IsFreshImage() */
	}
};

START_ROBOT_CLASS(Team316Robot);

<|endoftext|>


<commit_before>/*=========================================================================

Program:   Visualization Toolkit
Module:    vtkASCIITextCodec.cxx

Copyright (c)
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2010 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include <vtkASCIITextCodec.h>

#include <vtkObjectFactory.h>
#include <vtkTextCodecFactory.h>

#include <stdexcept>

vtkStandardNewMacro(vtkASCIITextCodec);

vtkTextCodec* vtkASCIITextCodecFromCallback()
{
   return vtkASCIITextCodec::New() ;
}

class vtkASCIITextCodecRegister
{
  public:
    vtkASCIITextCodecRegister()
    {
      vtkTextCodecFactory::RegisterCreateCallback(vtkASCIITextCodecFromCallback) ;
    }
} ;

static vtkASCIITextCodecRegister foo ;

const char* vtkASCIITextCodec::Name() {return "US-ASCII" ;}

bool vtkASCIITextCodec::CanHandle(const char* NameStr)
{
  if (0 == strcmp(NameStr, "US-ASCII") || 0 == strcmp(NameStr, "ASCII"))
    return true ;
  else
    return false ;
}

bool vtkASCIITextCodec::IsValid(istream& InputStream)
{
  bool returnBool = true ;

  // get the position of the stream so we can restore it when we are done
  istream::pos_type StreamPos = InputStream.tellg() ;

  // check the code points for non-ascii characters
  while (!InputStream.eof())
    {
    vtkTypeUInt32 CodePoint = InputStream.get() ;

    if(!InputStream.eof() && CodePoint > 0x7f)
      {
      returnBool = false ;
      break ;
      }
    }

  // reset the stream
  InputStream.clear() ;
  InputStream.seekg(StreamPos) ;

  return returnBool ;
}

void vtkASCIITextCodec::ToUnicode(istream& InputStream, vtkTextCodec::OutputIterator& output)
{
  while (!InputStream.eof())
    {
    vtkTypeUInt32 CodePoint = InputStream.get() ;

    if(!InputStream.eof() && CodePoint > 0x7f)
      throw std::runtime_error("Detected a character that isn't valid US-ASCII.");

    *output++ = CodePoint;
    }
}

vtkUnicodeString::value_type vtkASCIITextCodec::NextUnicode(istream& InputStream)
{
  vtkTypeUInt32 CodePoint = InputStream.get() ;

  if (!InputStream.eof())
    {
    if(CodePoint > 0x7f)
      throw std::runtime_error("Detected a character that isn't valid US-ASCII.");

    return CodePoint ;
    }
  else
    return 0 ;
}

vtkASCIITextCodec::vtkASCIITextCodec() : vtkTextCodec()
{
}

vtkASCIITextCodec::~vtkASCIITextCodec()
{
}

void vtkASCIITextCodec::PrintSelf(ostream& os, vtkIndent indent)
{
  os << indent << "vtkASCIITextCodec (" << this << ") \n" ;
  indent = indent.GetNextIndent();
  this->Superclass::PrintSelf(os, indent.GetNextIndent()) ;
}
<commit_msg>Another boundary condition I missed...<commit_after>/*=========================================================================

Program:   Visualization Toolkit
Module:    vtkASCIITextCodec.cxx

Copyright (c)
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2010 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include <vtkASCIITextCodec.h>

#include <vtkObjectFactory.h>
#include <vtkTextCodecFactory.h>

#include <stdexcept>

vtkStandardNewMacro(vtkASCIITextCodec);

vtkTextCodec* vtkASCIITextCodecFromCallback()
{
   return vtkASCIITextCodec::New() ;
}

class vtkASCIITextCodecRegister
{
  public:
    vtkASCIITextCodecRegister()
    {
      vtkTextCodecFactory::RegisterCreateCallback(vtkASCIITextCodecFromCallback) ;
    }
} ;

static vtkASCIITextCodecRegister foo ;

const char* vtkASCIITextCodec::Name() {return "US-ASCII" ;}

bool vtkASCIITextCodec::CanHandle(const char* NameStr)
{
  if (0 == strcmp(NameStr, "US-ASCII") || 0 == strcmp(NameStr, "ASCII"))
    return true ;
  else
    return false ;
}

bool vtkASCIITextCodec::IsValid(istream& InputStream)
{
  bool returnBool = true ;

  // get the position of the stream so we can restore it when we are done
  istream::pos_type StreamPos = InputStream.tellg() ;

  // check the code points for non-ascii characters
  while (!InputStream.eof())
    {
    vtkTypeUInt32 CodePoint = InputStream.get() ;

    if(!InputStream.eof() && CodePoint > 0x7f)
      {
      returnBool = false ;
      break ;
      }
    }

  // reset the stream
  InputStream.clear() ;
  InputStream.seekg(StreamPos) ;

  return returnBool ;
}

void vtkASCIITextCodec::ToUnicode(istream& InputStream, vtkTextCodec::OutputIterator& output)
{
  while (!InputStream.eof())
    {
    vtkTypeUInt32 CodePoint = InputStream.get();

    if(!InputStream.eof())
      {
      if (CodePoint > 0x7f)
        throw std::runtime_error("Detected a character that isn't valid US-ASCII.");

      *output++ = CodePoint;
      }
    }
}

vtkUnicodeString::value_type vtkASCIITextCodec::NextUnicode(istream& InputStream)
{
  vtkTypeUInt32 CodePoint = InputStream.get();

  if (!InputStream.eof())
    {
    if(CodePoint > 0x7f)
      throw std::runtime_error("Detected a character that isn't valid US-ASCII.");

    return CodePoint ;
    }
  else
    return 0 ;
}

vtkASCIITextCodec::vtkASCIITextCodec() : vtkTextCodec()
{
}

vtkASCIITextCodec::~vtkASCIITextCodec()
{
}

void vtkASCIITextCodec::PrintSelf(ostream& os, vtkIndent indent)
{
  os << indent << "vtkASCIITextCodec (" << this << ") \n" ;
  indent = indent.GetNextIndent();
  this->Superclass::PrintSelf(os, indent.GetNextIndent()) ;
}
<|endoftext|>


<commit_before>#include "Execution/commandlineutil.h"
#include "Execution/compiler.h"
#include "Execution/interpreter.h"

#include "AST/ast.h"    // TODO: Refactoring to remove this include

using namespace Execution;

int main(int argc, char** argv)
{
    Compiler compiler;
    Interpreter interpreter;

    std::vector<std::string> args;
    for (size_t iArg = 0; iArg < argc; ++iArg)
        args.emplace_back(argv[iArg]);

    ExecutionInfo info = ParseCommandLine(args);

    switch (info.command)
    {
    case Execution::ExecutionCommand::COMPILE_CHIP16:
        return 0;
    case Execution::ExecutionCommand::COMPILE_LLVM:
        return 0;
    case Execution::ExecutionCommand::DUMP_AST:
        return 0;
    case Execution::ExecutionCommand::DUMP_CFG:
        return 0;
    case Execution::ExecutionCommand::DUMP_LLVM:
        return 0;
    case Execution::ExecutionCommand::INTERPRET:
    {
        auto programAST = compiler.ParseProgram(info.programFile);
        if (programAST != nullptr)
        {
            auto symTable = compiler.GetSymbolTable(programAST);
            if (symTable != nullptr)
            {
                interpreter.Run(programAST, symTable);
            }
        }
    }
        return 0;
    case Execution::ExecutionCommand::UNKNOWN:
        return 1;
    default:
        return 1;
    }
}<commit_msg>TosLang: Re-enabling the '-dump-ast' compiler command<commit_after>#include "Execution/commandlineutil.h"
#include "Execution/compiler.h"
#include "Execution/interpreter.h"

#include "AST/ast.h"    // TODO: Refactoring to remove this include

using namespace Execution;

int main(int argc, char** argv)
{
    Compiler compiler;
    Interpreter interpreter;

    std::vector<std::string> args;
    for (size_t iArg = 0; iArg < argc; ++iArg)
        args.emplace_back(argv[iArg]);

    ExecutionInfo info = ParseCommandLine(args);

    switch (info.command)
    {
    case Execution::ExecutionCommand::COMPILE_CHIP16:
        return 1;
    case Execution::ExecutionCommand::COMPILE_LLVM:
        return 1;
    case Execution::ExecutionCommand::DUMP_AST:
        compiler.DumpAST(info.programFile);
    case Execution::ExecutionCommand::DUMP_CFG:
        return 1;
    case Execution::ExecutionCommand::DUMP_LLVM:
        return 1;
    case Execution::ExecutionCommand::INTERPRET:
    {
        auto programAST = compiler.ParseProgram(info.programFile);
        if (programAST != nullptr)
        {
            auto symTable = compiler.GetSymbolTable(programAST);
            if (symTable != nullptr)
            {
                interpreter.Run(programAST, symTable);
            }
        }
    }
    default:
        return 1;
    }

    return 0;
}<|endoftext|>


<commit_before>#include <cassert>
#include <ctime>
#include <iostream>
#include <map>
#include <vector>

#include "Helper.h"
#include "Notation.h"

// The number of iterations to do the EM training.
#define NUMBER_ITERATIONS 5

using namespace std;

const string X = "X";
const string Y = "Y";
const string A = "A";
const string B = "B";
const vector<string> TAG_LIST{X, Y};
const vector<string> OBSERVED_DATA{A, B, A};

// Known probabilities:
Notation pX("P", {X}, {});  // "probability of x"
Notation pY("P", {Y}, {});
Notation pXGivenX("P", {X}, {X});
Notation pYGivenX("P", {Y}, {X});
Notation pXGivenY("P", {X}, {Y});
Notation pYGivenY("P", {Y}, {Y});
// Objectives:
Notation pABA("P", {A,B,A}, {});
Notation pAGivenX("P", {A}, {X});
Notation pAGivenY("P", {A}, {Y});
Notation pBGivenX("P", {B}, {X});
Notation pBGivenY("P", {B}, {Y});
Notation cXA("C", {X, A}, {});  // "count of x intersected with a"
Notation cXB("C", {X, B}, {});

void PrepareInitialData(map<string, double> *data) {
  // Given data.
  data->emplace(pX.repr(), .6);
  data->emplace(pY.repr(), .4);
  data->emplace(pXGivenX.repr(), .6);
  data->emplace(pYGivenX.repr(), .4);
  data->emplace(pXGivenY.repr(), .9);
  data->emplace(pYGivenY.repr(), .1);

  // Initial value for unknowns. We improve upon these.
  double initVal = .5;
  data->emplace(pAGivenX.repr(), initVal);
  data->emplace(pAGivenY.repr(), initVal);
  data->emplace(pBGivenX.repr(), initVal);
  data->emplace(pBGivenY.repr(), initVal);
}

void BruteForceCompute(map<string, double> *data) {
  // Enumerate all possible tag sequences.
  vector<string> tagSequences{
    X+X+X, X+X+Y, X+Y+X, X+Y+Y,
    Y+X+X, Y+X+Y, Y+Y+X, Y+Y+Y};
  for (int i = 0; i < NUMBER_ITERATIONS; ++i) {
    cout << "#" << i+1 << ":\n";
    // Get norm P(t,w) and counts.
    for (string seq : tagSequences) {
      vector<string> tags = NotationHelper::Individualize(seq);
      Notation pTW("P", OBSERVED_DATA, tags);
      double normalizedProb = Calculator::ComputeNormalizedProbability(pTW,
          *data, TAG_LIST.size(), OBSERVED_DATA.size());
      data->emplace(pTW.repr(), normalizedProb);
      // Get counts.
      (*data)[cXA.repr()] += Calculator::NormProbFactor(normalizedProb, pTW,
          cXA); (*data)[cXB.repr()] +=
        Calculator::NormProbFactor(normalizedProb, pTW, cXB);
    }
    // Update the unknown probabilities that we want to find. Use them in the
    // next iteration.
    (*data)[pAGivenX.repr()] = (*data)[cXA.repr()]/( (*data)[cXA.repr()] +
        (*data)[cXB.repr()] );
    (*data)[pBGivenX.repr()] = (*data)[cXB.repr()]/( (*data)[cXB.repr()] +
        (*data)[cXA.repr()] );

    // The ultimate value we want to maximize. This should increase with each
    // iteration.
    Calculator::UpdateProbOfObsDataSeq(pABA, data, tagSequences);
    cout << cXA << ": " << (*data)[cXA.repr()] << endl;
    cout << cXB << ": " << (*data)[cXB.repr()] << endl;
    cout << pABA << ": " << (*data)[pABA.repr()] << endl;
  }
}

struct Node {
  string name;
  vector<pair<Node, Edge> > parents;  // Incoming edges.
  vector<pair<Node, Edge> > children;  // Outgoing edges.
  Node(string name) {
    this->name = name;
  }
  string repr() {
    return name;
  }
};

struct Edge {
  Notation notation;
  Edge(Notation n) {
    this->notation = n;
  }
  string repr() {
    return notation.repr();
  }
}

void PrepareTrellis(vector<Node> *graph) {

}

void ForwardBackwardCompute(const vector<Node> &nodes, const Node &startNode,
    const Node &endNode, map<string, double> *data) {
  map<string, double> alpha;  // Sum of all paths from start state to this node.
  map<string, double> beta;  // Sum of all paths from this node to final state.

  alpha[startNode.repr()] = 1;

  // Forward pass.
  for (int i = 0; i < nodes.size(); ++i) {
    if (nodes[i] != startNode) {
      double sum = 0;
      for (Node parent : nodes[i].parents) {
        sum += alpha[parent.first.repr()] * data->at(parent.second.repr());
      }
      alpha[nodes[i].repr()] = sum;
    }
  }

  // Backward pass. TODO.

  // Counting pass.

}

int main() {
  map<string, double> data;  // Storage for probabilities and counts.
  PrepareInitialData(&data);
  BruteForceCompute(&data);

  cout << "--Results--\n";
  cout << cXA << ": " << data[cXA.repr()] << endl;
  cout << cXB << ": " << data[cXB.repr()] << endl;
  cout << pABA << ": " << data[pABA.repr()] << endl;
  return 0;
}
<commit_msg>further setup, mid-state<commit_after>#include <cassert>
#include <ctime>
#include <iostream>
#include <map>
#include <vector>

#include "Helper.h"
#include "Notation.h"

// The number of iterations to do the EM training.
#define NUMBER_ITERATIONS 5

using namespace std;

const string X = "X";
const string Y = "Y";
const string A = "A";
const string B = "B";
const vector<string> TAG_LIST{X, Y};
const vector<string> OBSERVED_DATA{A, B, A};

// Known probabilities:
Notation pX("P", {X}, {});  // "probability of x"
Notation pY("P", {Y}, {});
Notation pXGivenX("P", {X}, {X});
Notation pYGivenX("P", {Y}, {X});
Notation pXGivenY("P", {X}, {Y});
Notation pYGivenY("P", {Y}, {Y});
// Objectives:
Notation pABA("P", {A,B,A}, {});
Notation pAGivenX("P", {A}, {X});
Notation pAGivenY("P", {A}, {Y});
Notation pBGivenX("P", {B}, {X});
Notation pBGivenY("P", {B}, {Y});
Notation cXA("C", {X, A}, {});  // "count of x intersected with a"
Notation cXB("C", {X, B}, {});

void PrepareInitialData(map<string, double> *data) {
  // Given data.
  data->emplace(pX.repr(), .6);
  data->emplace(pY.repr(), .4);
  data->emplace(pXGivenX.repr(), .6);
  data->emplace(pYGivenX.repr(), .4);
  data->emplace(pXGivenY.repr(), .9);
  data->emplace(pYGivenY.repr(), .1);

  // Initial value for unknowns. We improve upon these.
  double initVal = .5;
  data->emplace(pAGivenX.repr(), initVal);
  data->emplace(pAGivenY.repr(), initVal);
  data->emplace(pBGivenX.repr(), initVal);
  data->emplace(pBGivenY.repr(), initVal);
}

void BruteForceCompute(map<string, double> *data) {
  // Enumerate all possible tag sequences.
  vector<string> tagSequences{
    X+X+X, X+X+Y, X+Y+X, X+Y+Y,
    Y+X+X, Y+X+Y, Y+Y+X, Y+Y+Y};
  for (int i = 0; i < NUMBER_ITERATIONS; ++i) {
    cout << "#" << i+1 << ":\n";
    // Get norm P(t,w) and counts.
    for (string seq : tagSequences) {
      vector<string> tags = NotationHelper::Individualize(seq);
      Notation pTW("P", OBSERVED_DATA, tags);
      double normalizedProb = Calculator::ComputeNormalizedProbability(pTW,
          *data, TAG_LIST.size(), OBSERVED_DATA.size());
      data->emplace(pTW.repr(), normalizedProb);
      // Get counts.
      (*data)[cXA.repr()] += Calculator::NormProbFactor(normalizedProb, pTW,
          cXA); (*data)[cXB.repr()] +=
        Calculator::NormProbFactor(normalizedProb, pTW, cXB);
    }
    // Update the unknown probabilities that we want to find. Use them in the
    // next iteration.
    (*data)[pAGivenX.repr()] = (*data)[cXA.repr()]/( (*data)[cXA.repr()] +
        (*data)[cXB.repr()] );
    (*data)[pBGivenX.repr()] = (*data)[cXB.repr()]/( (*data)[cXB.repr()] +
        (*data)[cXA.repr()] );

    // The ultimate value we want to maximize. This should increase with each
    // iteration.
    Calculator::UpdateProbOfObsDataSeq(pABA, data, tagSequences);
    cout << cXA << ": " << (*data)[cXA.repr()] << endl;
    cout << cXB << ": " << (*data)[cXB.repr()] << endl;
    cout << pABA << ": " << (*data)[pABA.repr()] << endl;
  }
}

struct Node {
  string name;
  vector<Edge> parent_edges;
  vector<Edge> child_edges;
  Node(string name) {
    this->name = name;
  }
  string repr() {
    return this->name;
  }
  void set_name(const string &other) {
    this->name = other;
  }
};

struct Edge {
  Notation notation;
  Node src, dest;
  Edge(const Notation &n, const Node &src, const Node &dest) {
    this->notation = n;
    this->src = src;
    this->dest = dest;
  }
  string repr() {
    return notation.repr();
  }
}

void LinkNodeAndEdge(Node *node, Edge *edge) {

}

// Warning: Creates data on heap. Call DestroyTrellis after done.
// Post: 'nodes' points to a vector where [0] is the start node, back() is the
// end. 'edges' points to a vector of corresponding edges.
void BuildTrellis(vector<Node> *nodes, Vector<Edge> *edges) {
  Node start_node = new Node("start");
  nodes->push_back(start_node);
  Node xa1first = new Node("xa1first");
  nodes->push_back(xa1first);
  Node xa2first = new Node("xa2first");
  nodes->push_back(xa2first);
  Node xb1second = new Node("xb1second");
  nodes->push_back(xb1second);
  Node xb2second = new Node("xb2second");
  nodes->push_back(xb2second);
  Node xa1third = new Node("xa1third");
  nodes->push_back(xa1third);
  Node xa2third = new Node("xa2third");
  nodes->push_back(xa2third);
  Node ya1first = new Node("ya1first");
  nodes->push_back(ya1first);
  Node ya2first = new Node("ya2first");
  nodes->push_back(ya2first);
  Node yb1second = new Node("yb1second");
  nodes->push_back(yb1second);
  Node yb2second = new Node("yb2second");
  nodes->push_back(yb2second);
  Node ya1third = new Node("ya1third");
  nodes->push_back(ya1third);
  Node ya2third = new Node("ya2third");
  nodes->push_back(ya2third);
  Node end_node = new Node("end");
  nodes->push_back(end_node);

  // TODONOW
}

void ForwardBackwardCompute(const vector<Node> &nodes, const Node &start_node,
                            const Node &end_node, const vector<Edge> &edges,
                            map<string, double> *data) {
  map<string, double> alpha;  // Sum of all paths from start state to this node.
  map<string, double> beta;  // Sum of all paths from this node to final state.

  alpha[start_node.repr()] = 1;

  // Forward pass.
  for (int i = 0; i < nodes.size(); ++i) {
    if (nodes[i] != start_node) {
      double sum = 0;
      for (Edge e : nodes[i].parent_edges) {
        sum += alpha[e.src.repr()] * data->at(e.repr());
      }
      alpha[nodes[i].repr()] = sum;
    }
  }

  // Backward pass. TODO.

  // Counting pass.
  for (int i = 0; i < edges.size(); ++i) {

  }

}

void RunBruteForceEM() {
  map<string, double> data;  // Storage for probabilities and counts.
  PrepareInitialData(&data);

  clock_t t;
  t = clock();
  BruteForceCompute(&data);
  t = clock() - t;

  cout << "--Results--\n";
  cout << cXA << ": " << data[cXA.repr()] << endl;
  cout << cXB << ": " << data[cXB.repr()] << endl;
  cout << pABA << ": " << data[pABA.repr()] << endl;
  printf("It took me %lu clicks (%f seconds).\n", t, ((float)t)/CLOCKS_PER_SEC);
}

void RunEfficientEM() {
  map<string, double> data;  // Storage for probabilities and counts.
  vector<Node> nodes;
  vector<Edge> edges;

  PrepareInitialData(&data);
  BuildTrellis(&nodes, &edges);

  clock_t t;
  t = clock();
  ForwardBackwardCompute(nodes, nodes[0], nodes.back(), edges, &data);
  t = clock() - t;

  cout << "--Results--\n";
  cout << cXA << ": " << data[cXA.repr()] << endl;
  cout << cXB << ": " << data[cXB.repr()] << endl;
  cout << pABA << ": " << data[pABA.repr()] << endl;
  printf("It took me %lu clicks (%f seconds).\n", t, ((float)t)/CLOCKS_PER_SEC);

  DestroyTrellis(&nodes, &edges);
}

int main() {
  RunBruteForceEM();
  RunEfficientEM();
  return 0;
}
<|endoftext|>


<commit_before>/*
 * UsbDk filter/redirector driver
 *
 * Copyright (c) 2013  Red Hat, Inc.
 *
 * Authors:
 *  Dmitry Fleytman  <dfleytma@redhat.com>
 *
 */

#include "driver.h"
#include "driver.tmh"

#ifdef ALLOC_PRAGMA
#pragma alloc_text (INIT, DriverEntry)
#endif

NTSTATUS
DriverEntry(
    _In_ PDRIVER_OBJECT  DriverObject,
    _In_ PUNICODE_STRING RegistryPath
    )
{
    WDF_DRIVER_CONFIG config;
    NTSTATUS status;
    WDF_OBJECT_ATTRIBUTES attributes;

    //
    // Initialize WPP Tracing
    //
    WPP_INIT_TRACING( DriverObject, RegistryPath );

    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry");

    //
    // Register a cleanup callback so that we can call WPP_CLEANUP when
    // the framework driver object is deleted during driver unload.
    //
    WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
    attributes.EvtCleanupCallback = UsbDkEvtDriverContextCleanup;

    WDF_DRIVER_CONFIG_INIT(&config,
                           UsbDkEvtDeviceAdd);

    config.EvtDriverUnload = DriverUnload;

    status = WdfDriverCreate(DriverObject,
                             RegistryPath,
                             &attributes,
                             &config,
                             WDF_NO_HANDLE);

    if (!NT_SUCCESS(status)) {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_DRIVER, "WdfDriverCreate failed %!STATUS!", status);
        WPP_CLEANUP(DriverObject);
        return status;
    }

    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Exit");

    return status;
}

VOID
DriverUnload(IN WDFDRIVER Driver)
{
    UNREFERENCED_PARAMETER(Driver);

    PAGED_CODE();

    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry");

    return;
}

NTSTATUS
UsbDkEvtDeviceAdd(
    _In_    WDFDRIVER       Driver,
    _Inout_ PWDFDEVICE_INIT DeviceInit
    )
{
    NTSTATUS status;

    UNREFERENCED_PARAMETER(Driver);

    PAGED_CODE();

    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry");

    status = UsbDkCreateDevice(DeviceInit);

    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Exit");

    return status;
}

VOID
UsbDkEvtDriverContextCleanup(
    _In_ WDFOBJECT DriverObject
    )
{
    UNREFERENCED_PARAMETER(DriverObject);

    PAGED_CODE ();

    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry");

    //
    // Stop WPP Tracing
    //
    WPP_CLEANUP( WdfGetDriver() );

}
<commit_msg>UsbDk: Create control device on load<commit_after>/*
 * UsbDk filter/redirector driver
 *
 * Copyright (c) 2013  Red Hat, Inc.
 *
 * Authors:
 *  Dmitry Fleytman  <dfleytma@redhat.com>
 *
 */

#include "driver.h"
#include "ControlDevice.h"
#include "driver.tmh"

#ifdef ALLOC_PRAGMA
#pragma alloc_text (INIT, DriverEntry)
#endif

static CUsbDkControlDevice* g_UsbDkControlDevice;

NTSTATUS
DriverEntry(
    _In_ PDRIVER_OBJECT  DriverObject,
    _In_ PUNICODE_STRING RegistryPath
    )
{
    WDF_DRIVER_CONFIG config;
    NTSTATUS status;
    WDF_OBJECT_ATTRIBUTES attributes;

    //
    // Initialize WPP Tracing
    //
    WPP_INIT_TRACING( DriverObject, RegistryPath );

    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry");

    //
    // Register a cleanup callback so that we can call WPP_CLEANUP when
    // the framework driver object is deleted during driver unload.
    //
    WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
    attributes.EvtCleanupCallback = UsbDkEvtDriverContextCleanup;

    WDF_DRIVER_CONFIG_INIT(&config,
                           UsbDkEvtDeviceAdd);

    config.EvtDriverUnload = DriverUnload;

    WDFDRIVER Driver;
    status = WdfDriverCreate(DriverObject,
                             RegistryPath,
                             &attributes,
                             &config,
                             &Driver);

    if (!NT_SUCCESS(status)) {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_DRIVER, "WdfDriverCreate failed %!STATUS!", status);
        WPP_CLEANUP(DriverObject);
        return status;
    }

    //TODO: Temporary, object not deleted
    g_UsbDkControlDevice = new CUsbDkControlDevice;
    g_UsbDkControlDevice->Create(Driver);

    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Exit");

    return status;
}

VOID
DriverUnload(IN WDFDRIVER Driver)
{
    UNREFERENCED_PARAMETER(Driver);

    PAGED_CODE();

    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry");

    return;
}

NTSTATUS
UsbDkEvtDeviceAdd(
    _In_    WDFDRIVER       Driver,
    _Inout_ PWDFDEVICE_INIT DeviceInit
    )
{
    NTSTATUS status;

    UNREFERENCED_PARAMETER(Driver);

    PAGED_CODE();

    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry");

    status = UsbDkCreateDevice(DeviceInit);

    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Exit");

    return status;
}

VOID
UsbDkEvtDriverContextCleanup(
    _In_ WDFOBJECT DriverObject
    )
{
    UNREFERENCED_PARAMETER(DriverObject);

    PAGED_CODE ();

    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DRIVER, "%!FUNC! Entry");

    //
    // Stop WPP Tracing
    //
    WPP_CLEANUP( WdfGetDriver() );

}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <iterator>

#include <sstream>
#include <vector>
#include <memory>

using namespace std;

typedef wstring Token;
const Token openParen = L"(";
const Token closeParen = L")";

vector<Token> tokenize(wistream& program)
{
	vector<Token> tokens;

	istreambuf_iterator<wchar_t> itr(program);
	istreambuf_iterator<wchar_t> eos;

	while(itr != eos)
	{
		tokens.emplace_back();

		if(*itr == '(')
		{
			tokens.back() = openParen;
			itr++;
		}
		else if(*itr == ')')
		{
			tokens.back() = closeParen;
			itr++;
		}
		else
		{
			while(itr != eos && !iswspace(*itr) && !(*itr == ')') && !(*itr == '('))
			{
				tokens.back().push_back(*itr);
				itr++;
			}
		}

		while(itr != eos && iswspace(*itr))
			itr++;
	}

	return tokens;
}

enum class Type
{
	NONE, FIXNUM, SYMBOL, LIST,
};

class Context;

struct ObjectImpl : public enable_shared_from_this<ObjectImpl>
{
	ObjectImpl(Type type):mType(type){};

	Type getType() const { return mType; }

	virtual	shared_ptr<ObjectImpl> evaluate(Context& context) = 0;

	virtual void print(wostream& os) const = 0;

private:
	const Type mType;
};

struct Int : public ObjectImpl
{
	Int(int value):ObjectImpl(Type::FIXNUM), mValue(value)
	{}

	shared_ptr<ObjectImpl> evaluate(Context& context) override
	{
		return shared_from_this();
	}

	virtual void print(wostream& os) const
	{
		os << mValue;
	}

private:
	int mValue;
};

struct Symbol : public ObjectImpl
{
	Symbol(wstring symbol) : ObjectImpl(Type::SYMBOL), mValue(symbol)
	{}

	shared_ptr<ObjectImpl> evaluate(Context& context) override
	{
		return shared_from_this();
	}

	void print(wostream& os) const override
	{
		os << mValue;
	}

private:
	const wstring mValue;
};

struct List : public ObjectImpl
{

	List(): ObjectImpl(Type::LIST){}

	shared_ptr<ObjectImpl> evaluate(Context& context) override
	{
		return nullptr;
	}

	void print(wostream& os) const override
	{
	}

private:
	vector<ObjectImpl> mList;
};

struct Object
{
	Object(Type type, Token valueToken)
	{
		switch(type)
		{
		case Type::FIXNUM:
			{
				wstringstream ss(valueToken);

				int value;

				ss >> value;

				if(ss.good())
				{
					mpImpl = make_shared<Int>(value);
				}
			}
			break;

		case Type::SYMBOL:
			mpImpl = make_shared<Symbol>(valueToken);
			break;

		case Type::LIST:
		case Type::NONE:
		default:
			break;
		}
	}

	Object(const Object& src):mpImpl(src.mpImpl)
	{}

	Type getType() const
	{
		return mpImpl->getType();
	}

	Object evaluate(Context& context)
	{
		return Object(mpImpl->evaluate(context));
	}

	void print(wostream& os) const
	{
		mpImpl->print(os);
	}

private:

	Object(shared_ptr<ObjectImpl> pValue)
	{
		mpImpl = pValue;
	}

	shared_ptr<ObjectImpl> mpImpl;
};

Object read(vector<Token> tokens)
{

	auto currentTokenItr = tokens.begin();

	if(*currentTokenItr == openParen)
	{
		auto listOfObjects = Object(Type::LIST, L"");

		currentTokenItr++;

		return Object(listOfObjects);

	}
	else
	{
		return Object(Type::FIXNUM, tokens.front());
	}
}

void print(Object)
{}

wstringstream program(L" 10 ( hello?) (hello -5) ( hi ( one two))  ");
wstringstream program_norwig(L"(begin (define r 10) (* pi (* r r)))");

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

	while(1)
	{
		wstring prog;

		getline(wcin, prog);

		wstringstream ss(prog);

		auto o = read(tokenize(ss));

		o.print(wcout);

		cout << '\n';
	}

	return 0;
}<commit_msg>Commit before switching to Expression-Atom-ExpressionList structure<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <iterator>

#include <sstream>
#include <vector>
#include <memory>
#include <regex>

using namespace std;

typedef wstring Token;
typedef vector<Token>::iterator TokenItr;

const Token openParen = L"(";
const Token closeParen = L")";

bool IsNumber(const Token& token)
{
	return regex_match(token, wregex(L"[(-|+)|][0-9]+"));
}

vector<Token> tokenize(wistream& program)
{
	vector<Token> tokens;

	istreambuf_iterator<wchar_t> itr(program);
	istreambuf_iterator<wchar_t> eos;

	while(itr != eos)
	{
		tokens.emplace_back();

		if(*itr == '(')
		{
			tokens.back() = openParen;
			itr++;
		}
		else if(*itr == ')')
		{
			tokens.back() = closeParen;
			itr++;
		}
		else
		{
			while(itr != eos && !iswspace(*itr) && !(*itr == ')') && !(*itr == '('))
			{
				tokens.back().push_back(*itr);
				itr++;
			}
		}

		while(itr != eos && iswspace(*itr))
			itr++;
	}

	return tokens;
}

enum class Type
{
	NONE, NUMBER, SYMBOL, LIST, PROC, LAMBDA
};

class Context;

struct ObjectImplBase : public enable_shared_from_this<ObjectImplBase>
{
	virtual Type getType() const = 0;

	virtual	shared_ptr<ObjectImplBase> evaluate(Context& context) = 0;

	virtual void print(wostream& os) const = 0;
};

struct Object
{
	Object(const TokenItr valueToken);

	Object(const Object& src):mpImpl(src.mpImpl)
	{}

	Type getType() const
	{
		return mpImpl->getType();
	}

	Object evaluate(Context& context)
	{
		return Object(mpImpl->evaluate(context));
	}

	void print(wostream& os) const
	{
		mpImpl->print(os);
	}

	static const Object gEmptyList;

private:

	Object(shared_ptr<ObjectImplBase> pValue)
	{
		mpImpl = pValue;
	}

	shared_ptr<ObjectImplBase> mpImpl;
};

const Object Object::gEmptyList = Object(nullptr);

template<Type T>
struct ObjectImpl : public ObjectImplBase
{
	Type getType() const override { return T; }
};

struct Int : public ObjectImpl<Type::NUMBER>
{
	Int(int value):mValue(value)
	{}

	shared_ptr<ObjectImplBase> evaluate(Context& context) override
	{
		return shared_from_this();
	}

	void print(wostream& os) const override
	{
		os << mValue;
	}

private:
	int mValue;
};

struct Symbol : public ObjectImpl<Type::SYMBOL>
{
	Symbol(wstring symbol) : mValue(symbol)
	{}

	shared_ptr<ObjectImplBase> evaluate(Context& context) override
	{
		return shared_from_this();
	}

	void print(wostream& os) const override
	{
		os << mValue;
	}

private:
	const wstring mValue;
};

struct List : public ObjectImpl<Type::LIST>
{

	List(){}

	shared_ptr<ObjectImplBase> evaluate(Context& context) override
	{
		return nullptr;
	}

	void print(wostream& os) const override
	{
	}

	void Add(Object object)
	{
		mList.push_back(object);
	}

	Object Car() const
	{
		if(mList.size() >= 1)
		{
			return mList.front();
		}
		else
		{
			return Object(make_shared<List>());
		}
	}

private:
	vector<Object> mList;
};

Object read(vector<Token> tokens)
{

	auto currentTokenItr = tokens.begin();

	if(*currentTokenItr == openParen)
	{
		auto listOfObjects = Object();

		currentTokenItr++;

		return Object(listOfObjects);

	}
	else
	{
		return Object(Type::NUMBER, tokens.front());
	}
}

void print(Object)
{}

wstringstream program(L" 10 ( hello?) (hello -5) ( hi ( one two))  ");
wstringstream program_norwig(L"(begin (define r 10) (* pi (* r r)))");

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

	while(1)
	{
		wstring prog;

		getline(wcin, prog);

		wstringstream ss(prog);

		auto o = read(tokenize(ss));

		o.print(wcout);

		cout << '\n';
	}

	return 0;
}

inline Object::Object(const TokenItr valueToken)
{
	if(IsNumber(*valueToken))
	{
		wstringstream ss(*valueToken);

		int value;

		ss >> value;

		if(ss.good())
		{
			mpImpl = make_shared<Int>(value);
		}
	}
	else if(*valueToken == openParen)
	{
		mpImpl = make_shared<List>();
	}
	else
	{
		mpImpl = make_shared<Symbol>(valueToken);
	}
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
$Log$
Revision 1.16  2003/01/14 10:50:18  alibrary
Cleanup of STEER coding conventions

Revision 1.15  2003/01/07 14:13:22  morsch
Communication between generators provising and requesting collision
geometries.

Revision 1.14  2002/02/08 16:50:50  morsch
Add name and title in constructor.

Revision 1.13  2001/10/21 18:35:56  hristov
Several pointers were set to zero in the default constructors to avoid memory management problems

Revision 1.12  2001/06/18 13:07:30  morsch
Forward kinematic ranges to entries only if not set by user.

Revision 1.11  2001/01/30 09:23:12  hristov
Streamers removed (R.Brun)

Revision 1.10  2001/01/26 19:55:49  hristov
Major upgrade of AliRoot code

Revision 1.9  2000/12/21 16:24:06  morsch
Coding convention clean-up

Revision 1.8  2000/10/27 13:53:29  morsch
AddGenerator: check testbit before setting the pT and momentum range
(D.Y. Peressounko)

Revision 1.7  2000/10/02 15:15:41  morsch
Use default streamer for AliGenCocktail

Revision 1.6  2000/09/07 17:04:31  morsch
In Streamer: TIter() after R__b << fEntries (Dmitri Yurevitch Peressounko)

Revision 1.5  2000/06/09 20:28:51  morsch
All coding rule violations except RS3 corrected (AM)

Revision 1.4  1999/09/29 09:24:12  fca
Introduction of the Copyright and cvs Log

*/

// Container class for AliGenerator through recursion.
// Container is itself an AliGenerator.
// What is stored are not the pointers to the generators directly but to objects of type
// AliGenCocktail entry.
// The class provides also iterator functionality.
// Author: andreas.morsch@cern.ch
//

#include <TList.h>
#include <TObjArray.h>

#include "AliGenCocktail.h"
#include "AliGenCocktailEntry.h"
#include "AliCollisionGeometry.h"
#include "AliRun.h"

ClassImp(AliGenCocktail)

AliGenCocktail::AliGenCocktail()
                 :AliGenerator()
{
// Constructor
    fName = "Cocktail";
    fTitle= "Particle Generator using cocktail of generators";
    fEntries = new TList;
    flnk1 = 0;
    flnk2 = 0;
    fNGenerators=0;
}

AliGenCocktail::AliGenCocktail(const AliGenCocktail & cocktail)
{
// copy constructor
}

AliGenCocktail::~AliGenCocktail()
{
// Destructor
    delete fEntries;
}

void AliGenCocktail::
AddGenerator(AliGenerator *Generator, char* Name, Float_t RateExp)
{
//
//  Forward parameters to the new generator
    if(TestBit(kPtRange) && !(Generator->TestBit(kPtRange)) && !(Generator->TestBit(kMomentumRange)))
	Generator->SetPtRange(fPtMin,fPtMax);
    if(TestBit(kMomentumRange) && !(Generator->TestBit(kPtRange)) && !(Generator->TestBit(kMomentumRange)))
	Generator->SetMomentumRange(fPMin,fPMax);

    if (!(Generator->TestBit(kYRange)))
	Generator->SetYRange(fYMin,fYMax);
    if (!(Generator->TestBit(kPhiRange)))
	Generator->SetPhiRange(fPhiMin*180/TMath::Pi(),fPhiMax*180/TMath::Pi());
    if (!(Generator->TestBit(kThetaRange)))
	Generator->SetThetaRange(fThetaMin*180/TMath::Pi(),fThetaMax*180/TMath::Pi());
    if (!(Generator->TestBit(kVertexRange)))
	Generator->SetOrigin(fOrigin[0], fOrigin[1], fOrigin[2]);
    Generator->
	SetSigma(fOsigma[0], fOsigma[1], fOsigma[2]);
    Generator->SetVertexSmear(fVertexSmear);
    Generator->SetTrackingFlag(fTrackIt);
//
//  Add generator to list

    AliGenCocktailEntry *entry =
	new AliGenCocktailEntry(Generator, Name, RateExp);
     fEntries->Add(entry);
     fNGenerators++;
 }

  void AliGenCocktail::Init()
{
// Initialisation
    TIter next(fEntries);
    AliGenCocktailEntry *entry;
    //
    // Loop over generators and initialize
    while((entry = (AliGenCocktailEntry*)next())) {
	entry->Generator()->Init();
    }
}

  void AliGenCocktail::FinishRun()
{
// Initialisation
    TIter next(fEntries);
    AliGenCocktailEntry *entry;
    //
    // Loop over generators and initialize
    while((entry = (AliGenCocktailEntry*)next())) {
	entry->Generator()->FinishRun();
    }
}

 void AliGenCocktail::Generate()
{
//
// Generate event
    TIter next(fEntries);
    AliGenCocktailEntry *entry = 0;
    AliGenCocktailEntry *preventry = 0;
    AliGenerator* gen = 0;

    TObjArray *partArray = gAlice->Particles();
    //
    // Loop over generators and generate events
    Int_t igen=0;

    while((entry = (AliGenCocktailEntry*)next())) {
	igen++;
	if (igen ==1) {
	    entry->SetFirst(0);
	} else {
	    entry->SetFirst((partArray->GetEntriesFast())+1);
	}
//
//      Handle case in which current generator needs collision geometry from previous generator
//
	gen = entry->Generator();
	if (gen->NeedsCollisionGeometry())
	{
	    if (preventry && preventry->Generator()->ProvidesCollisionGeometry())
	    {
		       (preventry->Generator()->CollisionGeometry())->NN());

		gen->SetCollisionGeometry(preventry->Generator()->CollisionGeometry());
	    } else {
		Fatal("Generate()", "No Collision Geometry Provided");
	    }
	}

	entry->Generator()->Generate();
	entry->SetLast(partArray->GetEntriesFast());
	preventry = entry;
    }
    next.Reset();
}

AliGenCocktailEntry *  AliGenCocktail::FirstGenerator()
{
// Iterator over generators: Initialisation
    flnk1 = fEntries->FirstLink();
    if (flnk1) {
	return (AliGenCocktailEntry*) (flnk1->GetObject());
    } else {
	return 0;
    }
}

AliGenCocktailEntry*  AliGenCocktail::NextGenerator()
{
// Iterator over generators: Increment
    flnk1 = flnk1->Next();
    if (flnk1) {
	return (AliGenCocktailEntry*) (flnk1->GetObject());
    } else {
	return 0;
    }
}

void AliGenCocktail::
FirstGeneratorPair(AliGenCocktailEntry*& e1, AliGenCocktailEntry*& e2)
{
// Iterator over generator pairs: Initialisation
    flnk2 = flnk1 = fEntries->FirstLink();
    if (flnk1) {
	e2 = e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
    } else {
	e2= e1 = 0;
    }
}

void AliGenCocktail::
NextGeneratorPair(AliGenCocktailEntry*& e1, AliGenCocktailEntry*& e2)
{
// Iterator over generators: Increment
    flnk2 = flnk2->Next();
    if (flnk2) {
	e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
	e2 = (AliGenCocktailEntry*) (flnk2->GetObject());
    } else {
	flnk2 = flnk1 = flnk1->Next();
	if (flnk1) {
	    e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
	    e2 = (AliGenCocktailEntry*) (flnk2->GetObject());
	} else {
	    e1=0;
	    e2=0;
	}
    }
}

AliGenCocktail& AliGenCocktail::operator=(const  AliGenCocktail& rhs)
{
// Assignment operator
    return *this;
}

<commit_msg>Bug corrected.<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
$Log$
Revision 1.17  2003/03/24 15:58:27  morsch
FinishRun() implemented.

Revision 1.16  2003/01/14 10:50:18  alibrary
Cleanup of STEER coding conventions

Revision 1.15  2003/01/07 14:13:22  morsch
Communication between generators provising and requesting collision
geometries.

Revision 1.14  2002/02/08 16:50:50  morsch
Add name and title in constructor.

Revision 1.13  2001/10/21 18:35:56  hristov
Several pointers were set to zero in the default constructors to avoid memory management problems

Revision 1.12  2001/06/18 13:07:30  morsch
Forward kinematic ranges to entries only if not set by user.

Revision 1.11  2001/01/30 09:23:12  hristov
Streamers removed (R.Brun)

Revision 1.10  2001/01/26 19:55:49  hristov
Major upgrade of AliRoot code

Revision 1.9  2000/12/21 16:24:06  morsch
Coding convention clean-up

Revision 1.8  2000/10/27 13:53:29  morsch
AddGenerator: check testbit before setting the pT and momentum range
(D.Y. Peressounko)

Revision 1.7  2000/10/02 15:15:41  morsch
Use default streamer for AliGenCocktail

Revision 1.6  2000/09/07 17:04:31  morsch
In Streamer: TIter() after R__b << fEntries (Dmitri Yurevitch Peressounko)

Revision 1.5  2000/06/09 20:28:51  morsch
All coding rule violations except RS3 corrected (AM)

Revision 1.4  1999/09/29 09:24:12  fca
Introduction of the Copyright and cvs Log

*/

// Container class for AliGenerator through recursion.
// Container is itself an AliGenerator.
// What is stored are not the pointers to the generators directly but to objects of type
// AliGenCocktail entry.
// The class provides also iterator functionality.
// Author: andreas.morsch@cern.ch
//

#include <TList.h>
#include <TObjArray.h>

#include "AliGenCocktail.h"
#include "AliGenCocktailEntry.h"
#include "AliCollisionGeometry.h"
#include "AliRun.h"

ClassImp(AliGenCocktail)

AliGenCocktail::AliGenCocktail()
                 :AliGenerator()
{
// Constructor
    fName = "Cocktail";
    fTitle= "Particle Generator using cocktail of generators";
    fEntries = new TList;
    flnk1 = 0;
    flnk2 = 0;
    fNGenerators=0;
}

AliGenCocktail::AliGenCocktail(const AliGenCocktail & cocktail)
{
// copy constructor
}

AliGenCocktail::~AliGenCocktail()
{
// Destructor
    delete fEntries;
}

void AliGenCocktail::
AddGenerator(AliGenerator *Generator, char* Name, Float_t RateExp)
{
//
//  Forward parameters to the new generator
    if(TestBit(kPtRange) && !(Generator->TestBit(kPtRange)) && !(Generator->TestBit(kMomentumRange)))
	Generator->SetPtRange(fPtMin,fPtMax);
    if(TestBit(kMomentumRange) && !(Generator->TestBit(kPtRange)) && !(Generator->TestBit(kMomentumRange)))
	Generator->SetMomentumRange(fPMin,fPMax);

    if (!(Generator->TestBit(kYRange)))
	Generator->SetYRange(fYMin,fYMax);
    if (!(Generator->TestBit(kPhiRange)))
	Generator->SetPhiRange(fPhiMin*180/TMath::Pi(),fPhiMax*180/TMath::Pi());
    if (!(Generator->TestBit(kThetaRange)))
	Generator->SetThetaRange(fThetaMin*180/TMath::Pi(),fThetaMax*180/TMath::Pi());
    if (!(Generator->TestBit(kVertexRange)))
	Generator->SetOrigin(fOrigin[0], fOrigin[1], fOrigin[2]);
    Generator->
	SetSigma(fOsigma[0], fOsigma[1], fOsigma[2]);
    Generator->SetVertexSmear(fVertexSmear);
    Generator->SetTrackingFlag(fTrackIt);
//
//  Add generator to list

    AliGenCocktailEntry *entry =
	new AliGenCocktailEntry(Generator, Name, RateExp);
     fEntries->Add(entry);
     fNGenerators++;
 }

  void AliGenCocktail::Init()
{
// Initialisation
    TIter next(fEntries);
    AliGenCocktailEntry *entry;
    //
    // Loop over generators and initialize
    while((entry = (AliGenCocktailEntry*)next())) {
	entry->Generator()->Init();
    }
}

  void AliGenCocktail::FinishRun()
{
// Initialisation
    TIter next(fEntries);
    AliGenCocktailEntry *entry;
    //
    // Loop over generators and initialize
    while((entry = (AliGenCocktailEntry*)next())) {
	entry->Generator()->FinishRun();
    }
}

 void AliGenCocktail::Generate()
{
//
// Generate event
    TIter next(fEntries);
    AliGenCocktailEntry *entry = 0;
    AliGenCocktailEntry *preventry = 0;
    AliGenerator* gen = 0;

    TObjArray *partArray = gAlice->Particles();
    //
    // Loop over generators and generate events
    Int_t igen=0;

    while((entry = (AliGenCocktailEntry*)next())) {
	igen++;
	if (igen ==1) {
	    entry->SetFirst(0);
	} else {
	    entry->SetFirst((partArray->GetEntriesFast())+1);
	}
//
//      Handle case in which current generator needs collision geometry from previous generator
//
	gen = entry->Generator();
	if (gen->NeedsCollisionGeometry())
	{
	    if (preventry && preventry->Generator()->ProvidesCollisionGeometry())
	    {
		gen->SetCollisionGeometry(preventry->Generator()->CollisionGeometry());
	    } else {
		Fatal("Generate()", "No Collision Geometry Provided");
	    }
	}

	entry->Generator()->Generate();
	entry->SetLast(partArray->GetEntriesFast());
	preventry = entry;
    }
    next.Reset();
}

AliGenCocktailEntry *  AliGenCocktail::FirstGenerator()
{
// Iterator over generators: Initialisation
    flnk1 = fEntries->FirstLink();
    if (flnk1) {
	return (AliGenCocktailEntry*) (flnk1->GetObject());
    } else {
	return 0;
    }
}

AliGenCocktailEntry*  AliGenCocktail::NextGenerator()
{
// Iterator over generators: Increment
    flnk1 = flnk1->Next();
    if (flnk1) {
	return (AliGenCocktailEntry*) (flnk1->GetObject());
    } else {
	return 0;
    }
}

void AliGenCocktail::
FirstGeneratorPair(AliGenCocktailEntry*& e1, AliGenCocktailEntry*& e2)
{
// Iterator over generator pairs: Initialisation
    flnk2 = flnk1 = fEntries->FirstLink();
    if (flnk1) {
	e2 = e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
    } else {
	e2= e1 = 0;
    }
}

void AliGenCocktail::
NextGeneratorPair(AliGenCocktailEntry*& e1, AliGenCocktailEntry*& e2)
{
// Iterator over generators: Increment
    flnk2 = flnk2->Next();
    if (flnk2) {
	e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
	e2 = (AliGenCocktailEntry*) (flnk2->GetObject());
    } else {
	flnk2 = flnk1 = flnk1->Next();
	if (flnk1) {
	    e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
	    e2 = (AliGenCocktailEntry*) (flnk2->GetObject());
	} else {
	    e1=0;
	    e2=0;
	}
    }
}

AliGenCocktail& AliGenCocktail::operator=(const  AliGenCocktail& rhs)
{
// Assignment operator
    return *this;
}

<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 *
 */

#include "webrtc/modules/video_coding/codecs/h264/include/h264.h"

#if defined(WEBRTC_USE_H264)
#include "webrtc/modules/video_coding/codecs/h264/h264_decoder_impl.h"
#include "webrtc/modules/video_coding/codecs/h264/h264_encoder_impl.h"
#endif
#if defined(WEBRTC_IOS)
#include "webrtc/modules/video_coding/codecs/h264/h264_video_toolbox_decoder.h"
#include "webrtc/modules/video_coding/codecs/h264/h264_video_toolbox_encoder.h"
#endif

#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"

namespace webrtc {

namespace {

#if defined(WEBRTC_USE_H264)
bool g_rtc_use_h264 = true;
#endif

}  // namespace

void DisableRtcUseH264() {
#if defined(WEBRTC_USE_H264)
  g_rtc_use_h264 = false;
#endif
}

// We need this file to be C++ only so it will compile properly for all
// platforms. In order to write ObjC specific implementations we use private
// externs. This function is defined in h264.mm.
#if defined(WEBRTC_IOS)
extern bool IsH264CodecSupportedObjC();
#endif

// If any H.264 codec is supported (iOS HW or OpenH264/FFmpeg).
bool IsH264CodecSupported() {
#if defined(WEBRTC_IOS)
  if (IsH264CodecSupportedObjC()) {
    return true;
  }
#endif
#if defined(WEBRTC_USE_H264)
  return g_rtc_use_h264;
#else
  return false;
#endif
}

H264Encoder* H264Encoder::Create() {
  RTC_DCHECK(H264Encoder::IsSupported());
#if defined(WEBRTC_IOS) && defined(WEBRTC_VIDEO_TOOLBOX_SUPPORTED)
  if (IsH264CodecSupportedObjC()) {
    LOG(LS_INFO) << "Creating H264VideoToolboxEncoder.";
    return new H264VideoToolboxEncoder();
  }
#endif
#if defined(WEBRTC_USE_H264)
  RTC_CHECK(g_rtc_use_h264);
  LOG(LS_INFO) << "Creating H264EncoderImpl.";
  return new H264EncoderImpl();
#else
  RTC_NOTREACHED();
  return nullptr;
#endif
}

bool H264Encoder::IsSupported() {
  return IsH264CodecSupported();
}

H264Decoder* H264Decoder::Create() {
  RTC_DCHECK(H264Decoder::IsSupported());
#if defined(WEBRTC_IOS) && defined(WEBRTC_VIDEO_TOOLBOX_SUPPORTED)
  if (IsH264CodecSupportedObjC()) {
    LOG(LS_INFO) << "Creating H264VideoToolboxDecoder.";
    return new H264VideoToolboxDecoder();
  }
#endif
#if defined(WEBRTC_USE_H264)
  RTC_CHECK(g_rtc_use_h264);
  LOG(LS_INFO) << "Creating H264DecoderImpl.";
  return new H264DecoderImpl();
#else
  RTC_NOTREACHED();
  return nullptr;
#endif
}

bool H264Decoder::IsSupported() {
  return IsH264CodecSupported();
}

}  // namespace webrtc
<commit_msg>Updated #if in IsH264CodecSupported to match H264[En/De]coder::Create.<commit_after>/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 *
 */

#include "webrtc/modules/video_coding/codecs/h264/include/h264.h"

#if defined(WEBRTC_USE_H264)
#include "webrtc/modules/video_coding/codecs/h264/h264_decoder_impl.h"
#include "webrtc/modules/video_coding/codecs/h264/h264_encoder_impl.h"
#endif
#if defined(WEBRTC_IOS)
#include "webrtc/modules/video_coding/codecs/h264/h264_video_toolbox_decoder.h"
#include "webrtc/modules/video_coding/codecs/h264/h264_video_toolbox_encoder.h"
#endif

#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"

namespace webrtc {

namespace {

#if defined(WEBRTC_USE_H264)
bool g_rtc_use_h264 = true;
#endif

}  // namespace

void DisableRtcUseH264() {
#if defined(WEBRTC_USE_H264)
  g_rtc_use_h264 = false;
#endif
}

// We need this file to be C++ only so it will compile properly for all
// platforms. In order to write ObjC specific implementations we use private
// externs. This function is defined in h264.mm.
#if defined(WEBRTC_IOS)
extern bool IsH264CodecSupportedObjC();
#endif

// If any H.264 codec is supported (iOS HW or OpenH264/FFmpeg).
bool IsH264CodecSupported() {
#if defined(WEBRTC_IOS) && defined(WEBRTC_VIDEO_TOOLBOX_SUPPORTED)
  if (IsH264CodecSupportedObjC()) {
    return true;
  }
#endif
#if defined(WEBRTC_USE_H264)
  return g_rtc_use_h264;
#else
  return false;
#endif
}

H264Encoder* H264Encoder::Create() {
  RTC_DCHECK(H264Encoder::IsSupported());
#if defined(WEBRTC_IOS) && defined(WEBRTC_VIDEO_TOOLBOX_SUPPORTED)
  if (IsH264CodecSupportedObjC()) {
    LOG(LS_INFO) << "Creating H264VideoToolboxEncoder.";
    return new H264VideoToolboxEncoder();
  }
#endif
#if defined(WEBRTC_USE_H264)
  RTC_CHECK(g_rtc_use_h264);
  LOG(LS_INFO) << "Creating H264EncoderImpl.";
  return new H264EncoderImpl();
#else
  RTC_NOTREACHED();
  return nullptr;
#endif
}

bool H264Encoder::IsSupported() {
  return IsH264CodecSupported();
}

H264Decoder* H264Decoder::Create() {
  RTC_DCHECK(H264Decoder::IsSupported());
#if defined(WEBRTC_IOS) && defined(WEBRTC_VIDEO_TOOLBOX_SUPPORTED)
  if (IsH264CodecSupportedObjC()) {
    LOG(LS_INFO) << "Creating H264VideoToolboxDecoder.";
    return new H264VideoToolboxDecoder();
  }
#endif
#if defined(WEBRTC_USE_H264)
  RTC_CHECK(g_rtc_use_h264);
  LOG(LS_INFO) << "Creating H264DecoderImpl.";
  return new H264DecoderImpl();
#else
  RTC_NOTREACHED();
  return nullptr;
#endif
}

bool H264Decoder::IsSupported() {
  return IsH264CodecSupported();
}

}  // namespace webrtc
<|endoftext|>