<commit_before>
// Blog: http://www.cnblogs.com/xiehongfeng100/p/4073867.html

// stack.hpp
#include <iostream>
#include <cassert>
using namespace std;

// const int CAPACITY = 1024;

template<class T, int defCapacity = 1024>
class Stack
{
public:
	Stack();
	virtual ~Stack();
	bool isEmpty();
	bool push(T val);	// ջջԪزջ
	T top();			// ȡջԪءջSǿգ򷵻ջԪأıջ״̬
	bool pop();			// ջջǿգջԪɾȥǷջɹı־
						// ûв÷رɾջԪصԭдһģ壬
						// ջΪյʱ򲻷㷵ءȻǿͨԻ
						// 쳣ġɸݾ
	int getSizeOfStack();

private:
	T stack[defCapacity];
	int sizeOfStack;

};

template<class T, int defCapacity>
Stack<T, defCapacity>::Stack()
{
	sizeOfStack = 0;
}

template<class T, int defCapacity>
Stack<T, defCapacity>::~Stack()
{

}

template<class T, int defCapacity>
bool Stack<T, defCapacity>::isEmpty()
{
	return sizeOfStack == 0;
}

template<class T, int defCapacity>
bool Stack<T, defCapacity>::push(T val)
{
	// assert(sizeOfStack < defCapacity);
	bool isSuccess = true;
	if (sizeOfStack == defCapacity)
	{
		cerr << "There is no space for new elements." << endl;
		isSuccess = false;
	}
	else
	{
		stack[sizeOfStack] = val;
		sizeOfStack++;
	}
	return isSuccess;
}

template<class T, int defCapacity>
T Stack<T, defCapacity>::top()
{
	return stack[sizeOfStack - 1];
}

template<class T, int defCapacity>
bool Stack<T, defCapacity>::pop()
{
	// assert(sizeOfStack > 0);
	bool isSuccess = true;
	if (sizeOfStack == 0)
	{
		cerr << "There is no element in stack." << endl;
		isSuccess = false;
	}
	else
	{
		sizeOfStack--;
	}
	return isSuccess;
}

template<class T, int defCapacity>
int Stack<T, defCapacity>::getSizeOfStack()
{
	return sizeOfStack;
}<commit_msg>Update stack.hpp<commit_after>
// Blog: http://www.cnblogs.com/xiehongfeng100/p/4073867.html

// stack.hpp
#include <iostream>
#include <cassert>
using namespace std;

// const int CAPACITY = 1024;

template<class T, int defCapacity = 1024>
class Stack
{
public:
	Stack();
	virtual ~Stack();
	bool isEmpty();
	bool push(T val);	// 进栈。若栈不满，则将元素插入栈顶。
	T top();		// 取栈顶元素。若栈S非空，则返回栈顶元素，但不改变栈的状态。
	bool pop();		// 退栈。若栈非空，则将栈顶元素删去，并返回是否退栈成功的标志。
				// 这里没有采用返回被删栈顶元素的原因在于这里写的是一个模板，
				// 当栈为空的时候不方便返回。当然，这个问题是可以通过断言或
				// 抛异常来解决的。具体做法可根据具体情况来定。
	int getSizeOfStack();

private:
	T stack[defCapacity];
	int sizeOfStack;

};

template<class T, int defCapacity>
Stack<T, defCapacity>::Stack()
{
	sizeOfStack = 0;
}

template<class T, int defCapacity>
Stack<T, defCapacity>::~Stack()
{

}

template<class T, int defCapacity>
bool Stack<T, defCapacity>::isEmpty()
{
	return sizeOfStack == 0;
}

template<class T, int defCapacity>
bool Stack<T, defCapacity>::push(T val)
{
	// assert(sizeOfStack < defCapacity);
	bool isSuccess = true;
	if (sizeOfStack == defCapacity)
	{
		cerr << "There is no space for new elements." << endl;
		isSuccess = false;
	}
	else
	{
		stack[sizeOfStack] = val;
		sizeOfStack++;
	}
	return isSuccess;
}

template<class T, int defCapacity>
T Stack<T, defCapacity>::top()
{
	return stack[sizeOfStack - 1];
}

template<class T, int defCapacity>
bool Stack<T, defCapacity>::pop()
{
	// assert(sizeOfStack > 0);
	bool isSuccess = true;
	if (sizeOfStack == 0)
	{
		cerr << "There is no element in stack." << endl;
		isSuccess = false;
	}
	else
	{
		sizeOfStack--;
	}
	return isSuccess;
}

template<class T, int defCapacity>
int Stack<T, defCapacity>::getSizeOfStack()
{
	return sizeOfStack;
}
<|endoftext|>


<commit_before>//
// main.cpp
// Projectname: amos-ss16-proj5
//
// Created on 21-05-2016.
// Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5
//
// This file is part of the AMOS Project 2016 @ FAU
// (Friedrich-Alexander University Erlangen-Nürnberg)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//

#include <iostream>
#include <sstream>
#include "frame_selector.h"
#include "image_view.h"
#include <vector>
#include "../ProcessControl/controller.h"

using namespace std;

int main(int argc, const char* argv[]) {

    if (argc > 3 || argc == 1){

        cerr << "Usage:  " << " FULL_PATH_TO_HDF5_FILE (optional: image index)" << endl;
        return -1;

    }

    if(argc == 2){

        // saves all images to disc
        Controller controller;
        controller.PlayHDFAsVideo(argv[1]);

    } else if(argc == 3){

        FrameSelector pipeline(argv[1]);
        // read one image
        unsigned int index = 0;
        stringstream string_index(argv[2]);
        string_index >> index;
        Image result_image = pipeline.ReadImage(index);

        ImageView image_viewer;
        image_viewer.ShowImage(result_image);
    }

    return 0;
}
<commit_msg>if main is called with index the one image will now be shown until a button is pressed<commit_after>//
// main.cpp
// Projectname: amos-ss16-proj5
//
// Created on 21-05-2016.
// Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5
//
// This file is part of the AMOS Project 2016 @ FAU
// (Friedrich-Alexander University Erlangen-Nürnberg)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//

#include <iostream>
#include <sstream>
#include "frame_selector.h"
#include "image_view.h"
#include <vector>
#include "../ProcessControl/controller.h"

using namespace std;

int main(int argc, const char* argv[]) {

    if (argc > 3 || argc == 1){

        cerr << "Usage:  " << " FULL_PATH_TO_HDF5_FILE (optional: image index)" << endl;
        return -1;

    }

    if(argc == 2){

        // saves all images to disc
        Controller controller;
        controller.PlayHDFAsVideo(argv[1]);

    } else if(argc == 3){

        FrameSelector pipeline(argv[1]);
        // read one image
        unsigned int index = 0;
        stringstream string_index(argv[2]);
        string_index >> index;
        Image result_image = pipeline.ReadImage(index);

        ImageView image_viewer;
        image_viewer.ShowImage(result_image, 0);
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "ToolBase.h"
#include "Exceptions.h"
#include "Helper.h"
#include "VcfFile.h"
#include <QFile>

class ConcreteTool: public ToolBase
{
    Q_OBJECT

public:
    ConcreteTool(int& argc, char *argv[])
        : ToolBase(argc, argv)
    {
    }

    virtual void setup()
    {
		setDescription("Breaks multi-allelic variants into several lines, making sure that allele-specific INFO/SAMPLE fields are still valid.");
        //optional
        addInfile("in", "Input VCF file. If unset, reads from STDIN.", true, true);
        addOutfile("out", "Output VCF list. If unset, writes to STDOUT.", true, true);

		changeLog(2018, 10, 18, "Initial implementation.");
    }

	///Return ID from FORMAT/INFO line
	QByteArray getId(const QByteArray& header)
	{
		int start = header.indexOf("ID=") + 3;
		int end = header.indexOf(',', start);
		return header.mid(start, end-start);
	}

	/*!
	 * \brief Searches a string for seperator before column n
	 * \param text - the text to search for
	 * \param seperator - the seperator to look for: usually ,
	 * \param colum - the column to look in e.g start looking for in the 4th colum
	 */
	bool includesSeperator(const QByteArray& text, const char& seperator, int column)
	{
		int current_col = 0;
		for (int i = 0; i < text.length(); ++i)
		{
			if (text[i] == '\t')
			{
				++current_col;
			}

			if (current_col == column)
			{
				if (text[i] == seperator)
				{
					return true;
				}
			}

			if (current_col > column) break;
		}

		return false;
	}

    virtual void main()
    {
        //open input/output streams
        QString in = getInfile("in");
        QString out = getOutfile("out");
        if(in!="" && in==out)
        {
            THROW(ArgumentException, "Input and output files must be different when streaming!");
        }
        QSharedPointer<QFile> in_p = Helper::openFileForReading(in, true);
		QSharedPointer<QFile> out_p = Helper::openFileForWriting(out, true);
		enum AnnotationType {R, A, OTHER};
		QHash<QByteArray, AnnotationType> info2type;
		QHash<QByteArray, AnnotationType> format2type;

        while(!in_p->atEnd())
        {
            QByteArray line = in_p->readLine();

            //skip empty lines
            if (line.trimmed().isEmpty()) continue;

			//header
            if (line.startsWith('#'))
			{
				if (line.startsWith("##INFO") && (line.contains("Number=R") || line.contains("Number=A")))
				{
					info2type[getId(line)] = line.contains("Number=R") ? R : A;
                }
                else if (line.startsWith("##FORMAT") && (line.contains("Number=R") || line.contains("Number=A")))
				{
					format2type[getId(line)] = line.contains("Number=R") ? R : A;
                }

				out_p->write(line);
                continue;
            }

			//single-allele variant > write out unchanged
			if (!includesSeperator(line, ',', VcfFile::ALT))
			{
                out_p->write(line);
				continue;
			}

			//split line and extract variant infos
			QByteArrayList parts = line.trimmed().split('\t');
			if (parts.length() < VcfFile::MIN_COLS) THROW(FileParseException, "VCF with too few columns: " + line);

			QByteArrayList alt = parts[VcfFile::ALT].split(',');
			QByteArrayList info = parts[VcfFile::INFO].split(';');
			bool has_samples = parts.count()> VcfFile::MIN_COLS;
			QByteArrayList format;
			if (has_samples) format = parts[VcfFile::FORMAT].split(':');

			// For each allele construct a separate info block
			QVector<QByteArray> new_infos_per_allele(alt.length());
			for (int i = 0; i < info.length(); ++i)
			{
				QByteArrayList info_parts = info[i].split('='); // split HEADER=VALUE
				const QByteArray& info_name = info_parts[0];

				// If type is ALT OR REF split by HEADER / VALUE and assign every line a different value (starting by 0-index)
				if (info2type.contains(info_name))
				{
					AnnotationType type = info2type[info_name];
					QByteArrayList info_value_per_allele = info_parts[1].split(',');

					int parts_expected = alt.size() + (type==R);
					if (info_value_per_allele.size() != parts_expected) THROW(FileParseException, "VCF INFO field '" + info_name + "' has wrong number of elements (expected " + QByteArray::number(parts_expected) + ", got " + QByteArray::number(info_value_per_allele.size()) + "): " + line);

					for (int j = 0; j < new_infos_per_allele.size(); ++j)
					{
						// appends a HEADER=VALUE; (with semicolon)
						if (!new_infos_per_allele[j].isEmpty()) new_infos_per_allele[j] += ";";
						if (type==R) // use INFO (ref), ALLELE (count)
						{
							new_infos_per_allele[j] += info_name + '=' + info_value_per_allele[0] + ',' + info_value_per_allele[j+1];
						}
						else // use ALLELE (count)
						{
							new_infos_per_allele[j] += info_name + '=' + info_value_per_allele[j];
						}
					}

				}
				else
				{
					for (int j = 0; j < new_infos_per_allele.size(); ++j)
					{
						if (!new_infos_per_allele[j].isEmpty()) new_infos_per_allele[j] += ";";
						new_infos_per_allele[j] += info[i];
					}
				}
			}

			QVector<QVector<QByteArray>> new_samples_per_allele;
			if (has_samples)
			{
				QVector<AnnotationType> format_types;
				for (int i = 0; i < format.length(); ++i)
				{
					if (format2type.contains(format[i]))
					{
						format_types.push_back(format2type[format[i]]);
					}
					else
					{
						format_types.push_back(OTHER);
					}
				}

				// For each sample, construct a new sample according to the format for every allele
				int samples_count = parts.length() - VcfFile::FORMAT - 1;
				for (int i = 0; i < alt.length(); ++i)
				{
					new_samples_per_allele.push_back(QVector<QByteArray>(samples_count));
				}

				// for every sample part in the specific sample process REF or ALT
				// then append to new_samples_per_allele[ALLEL][SAMPLE_INDEX]
				for (int i = 0; i < samples_count; ++i)
				{
					int sample_column = VcfFile::FORMAT + i + 1;
					QByteArrayList sample_values = parts[sample_column].split(':');

					for (int j = 0; j < sample_values.length(); ++j)
					{
						if (j==0 && format[j]=="GT") //special handling GT entry (must be first entry if present!)
						{
							if (sample_values[j].contains(',') || sample_values[j].count()!=3) THROW(FileParseException, "VCF contains invalid GT entry for sample #" + QByteArray::number(i+1) + " (expected 1): " + line);

							for (int a = 0; a < alt.length(); ++a)
							{
								int allele_count = sample_values[j].count(QByteArray::number(a+1));
								int wt_count = sample_values[j].count('0');
								if (allele_count==0 && wt_count==2)
								{
									new_samples_per_allele[a][i] = "0/0";
								}
								else if (allele_count==0 && wt_count==1)
								{
									new_samples_per_allele[a][i] = "./0";
								}
								else if (allele_count==0 && wt_count==0)
								{
									new_samples_per_allele[a][i] = "./.";
								}
								else if (allele_count==1 && wt_count==1)
								{
									new_samples_per_allele[a][i] = "0/1";
								}
								else if (allele_count==1 && wt_count==0)
								{
									new_samples_per_allele[a][i] = "./1";
								}
								else //allele_count==2 && wt_count==0
								{
									new_samples_per_allele[a][i] = "1/1";
								}
							}
						}
						else if (format_types.at(j) == R || format_types.at(j) == A) //special handling A/R entries
						{
							QByteArrayList sample_value_parts = sample_values[j].split(',');

							int parts_expected = alt.size() + (format_types.at(j)==R);
							if (sample_value_parts.size() != parts_expected) THROW(FileParseException, "VCF contains invalid element count in format entry " + format[j] + " for sample #" + QByteArray::number(i+1) + " (expected " + QByteArray::number(parts_expected) + ", got " + QByteArray::number(sample_value_parts.size()) + "): " + line);

							for (int a = 0; a < alt.length(); ++a)
							{
								if (!new_samples_per_allele[a][i].isEmpty()) new_samples_per_allele[a][i] += ":";

								// appends a VALUE: (with seperator)
								if (format_types[j] == R)
								{
									new_samples_per_allele[a][i] += sample_value_parts[0];
									new_samples_per_allele[a][i] += ',';
									new_samples_per_allele[a][i] += sample_value_parts[a+1];
								}
								else
								{
									new_samples_per_allele[a][i] += sample_value_parts[a];
								}
							}
						}
						else //other entries > write out unchanged
						{
							for (int a = 0; a < alt.length(); ++a)
							{
								if (!new_samples_per_allele[a][i].isEmpty()) new_samples_per_allele[a][i] += ":";
								new_samples_per_allele[a][i] += sample_values[j];
							}
						}
					}
				}
			}

			// Iterate through alleles and construct a new QByteArrayList from the parts and designated constructedInfos
			// Then join to a QByteArray and write
			for (int a = 0; a < alt.size(); ++a)
			{
				parts[VcfFile::ALT] = alt[a];
				parts[VcfFile::INFO] = new_infos_per_allele[a];
				if (has_samples)
				{
					for (int i = 0; i < new_samples_per_allele[a].size(); ++i)
					{
						int part_index = VcfFile::FORMAT + 1 + i;
						parts[part_index] = new_samples_per_allele[a][i];
					}
				}
				out_p->write(parts.join('\t').append('\n'));
			}
		}
    }
};

#include "main.moc"

int main(int argc, char *argv[])
{
    ConcreteTool tool(argc, argv);
    return tool.execute();
}
<commit_msg>VcfBreakMulti: Added 'no_error' flag.<commit_after>#include "ToolBase.h"
#include "Exceptions.h"
#include "Helper.h"
#include "VcfFile.h"
#include <QFile>

class ConcreteTool: public ToolBase
{
    Q_OBJECT

public:
    ConcreteTool(int& argc, char *argv[])
        : ToolBase(argc, argv)
    {
    }

    virtual void setup()
    {
		setDescription("Breaks multi-allelic variants into several lines, making sure that allele-specific INFO/SAMPLE fields are still valid.");
        //optional
        addInfile("in", "Input VCF file. If unset, reads from STDIN.", true, true);
        addOutfile("out", "Output VCF list. If unset, writes to STDOUT.", true, true);
		addFlag("no_errors", "Ignore VCF format errors is possible.");

		changeLog(2018, 10, 18, "Initial implementation.");
    }

	///Return ID from FORMAT/INFO line
	QByteArray getId(const QByteArray& header)
	{
		int start = header.indexOf("ID=") + 3;
		int end = header.indexOf(',', start);
		return header.mid(start, end-start);
	}

	/*!
	 * \brief Searches a string for seperator before column n
	 * \param text - the text to search for
	 * \param seperator - the seperator to look for: usually ,
	 * \param colum - the column to look in e.g start looking for in the 4th colum
	 */
	bool includesSeperator(const QByteArray& text, const char& seperator, int column)
	{
		int current_col = 0;
		for (int i = 0; i < text.length(); ++i)
		{
			if (text[i] == '\t')
			{
				++current_col;
			}

			if (current_col == column)
			{
				if (text[i] == seperator)
				{
					return true;
				}
			}

			if (current_col > column) break;
		}

		return false;
	}

    virtual void main()
    {
        //open input/output streams
        QString in = getInfile("in");
        QString out = getOutfile("out");
		bool no_errors = getFlag("no_errors");
        if(in!="" && in==out)
        {
            THROW(ArgumentException, "Input and output files must be different when streaming!");
        }
        QSharedPointer<QFile> in_p = Helper::openFileForReading(in, true);
		QSharedPointer<QFile> out_p = Helper::openFileForWriting(out, true);
		enum AnnotationType {R, A, OTHER};
		QHash<QByteArray, AnnotationType> info2type;
		QHash<QByteArray, AnnotationType> format2type;

        while(!in_p->atEnd())
        {
            QByteArray line = in_p->readLine();

            //skip empty lines
            if (line.trimmed().isEmpty()) continue;

			//header
            if (line.startsWith('#'))
			{
				if (line.startsWith("##INFO") && (line.contains("Number=R") || line.contains("Number=A")))
				{
					info2type[getId(line)] = line.contains("Number=R") ? R : A;
                }
                else if (line.startsWith("##FORMAT") && (line.contains("Number=R") || line.contains("Number=A")))
				{
					format2type[getId(line)] = line.contains("Number=R") ? R : A;
                }

				out_p->write(line);
                continue;
            }

			//single-allele variant > write out unchanged
			if (!includesSeperator(line, ',', VcfFile::ALT))
			{
                out_p->write(line);
				continue;
			}

			//split line and extract variant infos
			QByteArrayList parts = line.trimmed().split('\t');
			if (parts.length() < VcfFile::MIN_COLS) THROW(FileParseException, "VCF with too few columns: " + line);

			QByteArrayList alt = parts[VcfFile::ALT].split(',');
			QByteArrayList info = parts[VcfFile::INFO].split(';');
			bool has_samples = parts.count()> VcfFile::MIN_COLS;
			QByteArrayList format;
			if (has_samples) format = parts[VcfFile::FORMAT].split(':');

			// For each allele construct a separate info block
			QVector<QByteArray> new_infos_per_allele(alt.length());
			for (int i = 0; i < info.length(); ++i)
			{
				QByteArrayList info_parts = info[i].split('='); // split HEADER=VALUE
				const QByteArray& info_name = info_parts[0];

				// If type is ALT OR REF split by HEADER / VALUE and assign every line a different value (starting by 0-index)
				if (info2type.contains(info_name))
				{
					AnnotationType type = info2type[info_name];
					QByteArrayList info_value_per_allele = info_parts[1].split(',');

					int parts_expected = alt.size() + (type==R);
					if (info_value_per_allele.size() != parts_expected)
					{
						if (no_errors)
						{
							for (int j = 0; j < new_infos_per_allele.size(); ++j)
							{
								if (!new_infos_per_allele[j].isEmpty()) new_infos_per_allele[j] += ";";
								new_infos_per_allele[j] += info_parts[1];
							}

						}
						else
						{
							THROW(FileParseException, "VCF INFO field '" + info_name + "' has wrong number of elements (expected " + QByteArray::number(parts_expected) + ", got " + QByteArray::number(info_value_per_allele.size()) + "): " + line);
						}
					}
					else
					{
						for (int j = 0; j < new_infos_per_allele.size(); ++j)
						{
							// appends a HEADER=VALUE; (with semicolon)
							if (!new_infos_per_allele[j].isEmpty()) new_infos_per_allele[j] += ";";
							if (type==R) // use INFO (ref), ALLELE (count)
							{
								new_infos_per_allele[j] += info_name + '=' + info_value_per_allele[0] + ',' + info_value_per_allele[j+1];
							}
							else // use ALLELE (count)
							{
								new_infos_per_allele[j] += info_name + '=' + info_value_per_allele[j];
							}
						}
					}

				}
				else
				{
					for (int j = 0; j < new_infos_per_allele.size(); ++j)
					{
						if (!new_infos_per_allele[j].isEmpty()) new_infos_per_allele[j] += ";";
						new_infos_per_allele[j] += info[i];
					}
				}
			}

			QVector<QVector<QByteArray>> new_samples_per_allele;
			if (has_samples)
			{
				QVector<AnnotationType> format_types;
				for (int i = 0; i < format.length(); ++i)
				{
					if (format2type.contains(format[i]))
					{
						format_types.push_back(format2type[format[i]]);
					}
					else
					{
						format_types.push_back(OTHER);
					}
				}

				// For each sample, construct a new sample according to the format for every allele
				int samples_count = parts.length() - VcfFile::FORMAT - 1;
				for (int i = 0; i < alt.length(); ++i)
				{
					new_samples_per_allele.push_back(QVector<QByteArray>(samples_count));
				}

				// for every sample part in the specific sample process REF or ALT
				// then append to new_samples_per_allele[ALLEL][SAMPLE_INDEX]
				for (int i = 0; i < samples_count; ++i)
				{
					int sample_column = VcfFile::FORMAT + i + 1;
					QByteArrayList sample_values = parts[sample_column].split(':');

					for (int j = 0; j < sample_values.length(); ++j)
					{
						if (j==0 && format[j]=="GT") //special handling GT entry (must be first entry if present!)
						{
							if (sample_values[j].contains(',') || sample_values[j].count()!=3) THROW(FileParseException, "VCF contains invalid GT entry for sample #" + QByteArray::number(i+1) + " (expected 1): " + line);

							for (int a = 0; a < alt.length(); ++a)
							{
								int allele_count = sample_values[j].count(QByteArray::number(a+1));
								int wt_count = sample_values[j].count('0');
								if (allele_count==0 && wt_count==2)
								{
									new_samples_per_allele[a][i] = "0/0";
								}
								else if (allele_count==0 && wt_count==1)
								{
									new_samples_per_allele[a][i] = "./0";
								}
								else if (allele_count==0 && wt_count==0)
								{
									new_samples_per_allele[a][i] = "./.";
								}
								else if (allele_count==1 && wt_count==1)
								{
									new_samples_per_allele[a][i] = "0/1";
								}
								else if (allele_count==1 && wt_count==0)
								{
									new_samples_per_allele[a][i] = "./1";
								}
								else //allele_count==2 && wt_count==0
								{
									new_samples_per_allele[a][i] = "1/1";
								}
							}
						}
						else if (format_types.at(j) == R || format_types.at(j) == A) //special handling A/R entries
						{
							QByteArrayList sample_value_parts = sample_values[j].split(',');

							int parts_expected = alt.size() + (format_types.at(j)==R);
							if (sample_value_parts.size() != parts_expected)
							{
								if (no_errors)
								{
									for (int a = 0; a < alt.length(); ++a)
									{
										if (!new_samples_per_allele[a][i].isEmpty()) new_samples_per_allele[a][i] += ":";
										new_samples_per_allele[a][i] += sample_values[j];
									}
								}
								else
								{
									THROW(FileParseException, "VCF contains invalid element count in format entry " + format[j] + " for sample #" + QByteArray::number(i+1) + " (expected " + QByteArray::number(parts_expected) + ", got " + QByteArray::number(sample_value_parts.size()) + "): " + line);
								}
							}
							else
							{
								for (int a = 0; a < alt.length(); ++a)
								{
									if (!new_samples_per_allele[a][i].isEmpty()) new_samples_per_allele[a][i] += ":";

									// appends a VALUE: (with seperator)
									if (format_types[j] == R)
									{
										new_samples_per_allele[a][i] += sample_value_parts[0];
										new_samples_per_allele[a][i] += ',';
										new_samples_per_allele[a][i] += sample_value_parts[a+1];
									}
									else
									{
										new_samples_per_allele[a][i] += sample_value_parts[a];
									}
								}
							}
						}
						else //other entries > write out unchanged
						{
							for (int a = 0; a < alt.length(); ++a)
							{
								if (!new_samples_per_allele[a][i].isEmpty()) new_samples_per_allele[a][i] += ":";
								new_samples_per_allele[a][i] += sample_values[j];
							}
						}
					}
				}
			}

			// Iterate through alleles and construct a new QByteArrayList from the parts and designated constructedInfos
			// Then join to a QByteArray and write
			for (int a = 0; a < alt.size(); ++a)
			{
				parts[VcfFile::ALT] = alt[a];
				parts[VcfFile::INFO] = new_infos_per_allele[a];
				if (has_samples)
				{
					for (int i = 0; i < new_samples_per_allele[a].size(); ++i)
					{
						int part_index = VcfFile::FORMAT + 1 + i;
						parts[part_index] = new_samples_per_allele[a][i];
					}
				}
				out_p->write(parts.join('\t').append('\n'));
			}
		}
    }
};

#include "main.moc"

int main(int argc, char *argv[])
{
    ConcreteTool tool(argc, argv);
    return tool.execute();
}
<|endoftext|>


<commit_before>#include "Humblesoft_ILI9341.h"

VerticalScrollArea::VerticalScrollArea(Humblesoft_ILI9341 *parent):
  Adafruit_GFX(ILI9341_TFTWIDTH, 80), m_fontx(this)
{
  m_parent = parent;
}

void VerticalScrollArea::drawPixel(int16_t x, int16_t y, uint16_t color)
{
  if(x >= 0 && y < _width && y >= 0 && y < _height){
    if(this == &m_parent->tfa){
      m_parent->drawPixel(x, y, color);
    } else if(this == &m_parent->vsa){
      m_parent->drawPixel(x, m_parent->m_y0 + y, color);
    } else if(this == &m_parent->bfa){
      m_parent->drawPixel(x, m_parent->m_y1 + y, color);
    }
  }
}

size_t VerticalScrollArea::write(uint8_t c)
{
  return m_fontx.write(c, textsize, wrap, textcolor, textbgcolor, gfxFont);
}

void VerticalScrollArea::fillRect(int16_t x, int16_t y, int16_t w, int16_t h,
				  uint16_t color)
{
  for(int16_t i=0; i<h; i++)
    drawFastHLine(x, y++, w, color);
}

void VerticalScrollArea::drawFastHLine(int16_t x, int16_t y, int16_t w,
				       uint16_t color)
{
  if(y >= 0 && y < _height){
    if(this == &m_parent->tfa){
      m_parent->drawFastHLine(x, y, w,color);
    } else if(this == &m_parent->vsa){
      int16_t s = m_parent->m_nScrollPos;
      if(s < m_parent->m_y0) s = m_parent->m_y0;
      int16_t yy = y + s;
      if(yy >= m_parent->m_y1) yy += -m_parent->m_y1 + m_parent->m_y0;
      m_parent->drawFastHLine(x, yy, w, color);
    } else if(this == &m_parent->bfa){
      m_parent->drawFastHLine(x, m_parent->m_y1 + y, w,color);
    }
  }
}

FontxGfxVs::FontxGfxVs(Adafruit_GFX *pGfx) : FontxGfx(pGfx)
{
}

void FontxGfxVs::lineFeedHook(int16_t *pX, int16_t *pY, int16_t h)
{
  VerticalScrollArea *vsa = (VerticalScrollArea *)m_pGfx;
  vsa->lineFeedHook(pX,pY,h);
}

void VerticalScrollArea::lineFeedHook(int16_t *pX, int16_t *pY, int16_t h)
{
  if(this == &m_parent->vsa){
    *pX = 2;

    if(m_parent->m_nScrollPos < m_parent->m_y0)
      m_parent->m_nScrollPos = m_parent->m_y0;

    if(*pY + h > m_parent->m_y1 - m_parent->m_y0){
      int ss = *pY + h - m_parent->m_y1 + m_parent->m_y0;
      for(int i=0; i<ss; i++){
	m_parent->drawFastHLine(0, m_parent->m_nScrollPos, _width,
				m_parent->m_cScrollBg);
	m_parent->setScrollPos(m_parent->m_nScrollPos + 1);
	delay(m_parent->m_nScrollDelay);
      }
      *pY -= ss;
    }
  }
}

<commit_msg>fix bug text now drawed after scroll when size=1<commit_after>#include "Humblesoft_ILI9341.h"

VerticalScrollArea::VerticalScrollArea(Humblesoft_ILI9341 *parent):
  Adafruit_GFX(ILI9341_TFTWIDTH, 80), m_fontx(this)
{
  m_parent = parent;
}

void VerticalScrollArea::drawPixel(int16_t x, int16_t y, uint16_t color)
{
  if(x >= 0 && x < _width && y >= 0 && y < _height){
    if(this == &m_parent->tfa){
      m_parent->drawPixel(x, y, color);
    } else if(this == &m_parent->vsa){
      int16_t s = m_parent->m_nScrollPos;
      if(s < m_parent->m_y0) s = m_parent->m_y0;
      int16_t yy = y + s;
      if(yy >= m_parent->m_y1) yy += -m_parent->m_y1 + m_parent->m_y0;
      m_parent->drawPixel(x, yy, color);
    } else if(this == &m_parent->bfa){
      m_parent->drawPixel(x, m_parent->m_y1 + y, color);
    }
  }
}

size_t VerticalScrollArea::write(uint8_t c)
{
  return m_fontx.write(c, textsize, wrap, textcolor, textbgcolor, gfxFont);
}

void VerticalScrollArea::fillRect(int16_t x, int16_t y, int16_t w, int16_t h,
				  uint16_t color)
{
  for(int16_t i=0; i<h; i++)
    drawFastHLine(x, y++, w, color);
}

void VerticalScrollArea::drawFastHLine(int16_t x, int16_t y, int16_t w,
				       uint16_t color)
{
  if(y >= 0 && y < _height){
    if(this == &m_parent->tfa){
      m_parent->drawFastHLine(x, y, w,color);
    } else if(this == &m_parent->vsa){
      int16_t s = m_parent->m_nScrollPos;
      if(s < m_parent->m_y0) s = m_parent->m_y0;
      int16_t yy = y + s;
      if(yy >= m_parent->m_y1) yy += -m_parent->m_y1 + m_parent->m_y0;
      m_parent->drawFastHLine(x, yy, w, color);
    } else if(this == &m_parent->bfa){
      m_parent->drawFastHLine(x, m_parent->m_y1 + y, w,color);
    }
  }
}

FontxGfxVs::FontxGfxVs(Adafruit_GFX *pGfx) : FontxGfx(pGfx)
{
}

void FontxGfxVs::lineFeedHook(int16_t *pX, int16_t *pY, int16_t h)
{
  VerticalScrollArea *vsa = (VerticalScrollArea *)m_pGfx;
  vsa->lineFeedHook(pX,pY,h);
}

void VerticalScrollArea::lineFeedHook(int16_t *pX, int16_t *pY, int16_t h)
{
  if(this == &m_parent->vsa){
    *pX = 2;

    if(m_parent->m_nScrollPos < m_parent->m_y0)
      m_parent->m_nScrollPos = m_parent->m_y0;

    if(*pY + h > m_parent->m_y1 - m_parent->m_y0){
      int ss = *pY + h - m_parent->m_y1 + m_parent->m_y0;
      for(int i=0; i<ss; i++){
	m_parent->drawFastHLine(0, m_parent->m_nScrollPos, _width,
				m_parent->m_cScrollBg);
	m_parent->setScrollPos(m_parent->m_nScrollPos + 1);
	delay(m_parent->m_nScrollDelay);
      }
      *pY -= ss;
    }
  }
}

<|endoftext|>


<commit_before>/// \file urbi/uvalue.hxx

// This file is part of UObject Component Architecture
// Copyright (c) 2009 Gostai S.A.S.
//
// Permission to use, copy, modify, and redistribute this software for
// non-commercial use is hereby granted.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// For more information, comments, bug reports: http://www.urbiforge.com

#ifndef URBI_UVALUE_HXX
# define URBI_UVALUE_HXX

# include <urbi/uvalue.hh>

namespace urbi
{

  /*--------.
  | UList.  |
  `--------*/

# define ULIST_NTH(Const)                       \
  inline                                        \
  Const UValue&                                 \
  UList::operator[](size_t i) Const             \
  {                                             \
    i += offset;                                \
    if (i < size())                             \
      return *array[i];                         \
    else                                        \
      return UValue::error();                   \
  }

  ULIST_NTH(const)
  ULIST_NTH(/* const */)

# undef ULIST_NTH

  inline
  size_t
  UList::size() const
  {
    return array.size();
  }

  inline
  void
  UList::setOffset(size_t n)
  {
    offset = n;
  }

  /*--------------.
  | UNamedValue.  |
  `--------------*/

  inline
  UNamedValue::UNamedValue(const std::string& n, UValue* v)
    : name(n)
    , val(v)
  {}

  inline
  UNamedValue&
  UNamedValue::error()
  {
    static UNamedValue instance("<<UNamedValue::error (denotes an error)>>");
    return instance;
  }

  /*----------------.
  | UObjectStruct.  |
  `----------------*/

# define UOBJECTSTRUCT_NTH(Const)               \
  inline                                        \
  Const UNamedValue&                            \
  UObjectStruct::operator[](size_t i) Const     \
  {                                             \
    if (i < size())                             \
      return array[i];                          \
    else                                        \
      return UNamedValue::error();              \
  }

  UOBJECTSTRUCT_NTH(const)
  UOBJECTSTRUCT_NTH(/* const */)

# undef UOBJECTSTRUCT_NTH

  inline
  size_t
  UObjectStruct::size() const
  {
    return array.size();
  }

  /*---------.
  | UValue.  |
  `---------*/

  /// We use an operator , that behaves like an assignment.  The
  /// only difference is when the rhs is void, in which case it is
  /// the regular comma which is used.  This allows to write "uval,
  /// expr" to mean "compute expr and assign its result to uval,
  /// unless expr is void".
  inline
  UValue&
  UValue::operator, (const UValue &b)
  {
    return *this = b;
  }

#define CTOR_AND_ASSIGN_AND_COMMA(Type)		\
  inline                                        \
  UValue& UValue::operator, (Type rhs)          \
  {						\
    return *this = rhs;                         \
  }

  // UFloats.
  CTOR_AND_ASSIGN_AND_COMMA(ufloat);
  CTOR_AND_ASSIGN_AND_COMMA(int);
  CTOR_AND_ASSIGN_AND_COMMA(long);
  CTOR_AND_ASSIGN_AND_COMMA(unsigned int);
  CTOR_AND_ASSIGN_AND_COMMA(unsigned long);

  // Strings.
  CTOR_AND_ASSIGN_AND_COMMA(const char*);
  CTOR_AND_ASSIGN_AND_COMMA(const void*);
  CTOR_AND_ASSIGN_AND_COMMA(const std::string&);

  // Others.
  CTOR_AND_ASSIGN_AND_COMMA(const UBinary&);
  CTOR_AND_ASSIGN_AND_COMMA(const UList&);
  CTOR_AND_ASSIGN_AND_COMMA(const UObjectStruct&);
  CTOR_AND_ASSIGN_AND_COMMA(const USound&);
  CTOR_AND_ASSIGN_AND_COMMA(const UImage&);

#undef CTOR_AND_ASSIGN_AND_COMMA

  inline
  UValue::operator int() const
  {
    return static_cast<int>(static_cast<ufloat>((*this)));
  }

  inline
  UValue::operator unsigned int() const
  {
    return static_cast<unsigned int>(static_cast<ufloat>((*this)));
  }

  inline
  UValue::operator long() const
  {
    return static_cast<long>(static_cast<ufloat>((*this)));
  }

  inline
  UValue::operator unsigned long() const
  {
    return static_cast<unsigned long>(static_cast<ufloat>((*this)));
  }

  inline
  UValue::operator bool() const
  {
    return static_cast<int>(static_cast<ufloat>((*this))) != 0;
  }

  inline
  UValue&
  UValue::operator()()
  {
    return *this;
  }

  inline
  std::ostream&
  operator<<(std::ostream& s, const UValue& v)
  {
    // Looks bizarre, but might happen without have the "print" die
    // (it *has* happened).
    assert(&v);
    return v.print(s);
  }

  /*----------.
  | Casters.  |
  `----------*/

  // Run the uvalue_caster<Type> on v.
  template <typename Type>
  typename uvar_ref_traits<typename libport::unref_traits<Type>::type>::type
  uvalue_cast(UValue& v)
  {
    return uvalue_caster<typename libport::unref_traits<Type>::type>()(v);
  }

# define UVALUE_CASTER_DEFINE(Type)		\
  template <>					\
  struct uvalue_caster <Type>			\
  {						\
    Type operator() (UValue& v)			\
    {						\
      return v;					\
    }						\
  };

  UVALUE_CASTER_DEFINE(int);
  UVALUE_CASTER_DEFINE(unsigned int);
  UVALUE_CASTER_DEFINE(long);
  UVALUE_CASTER_DEFINE(unsigned long);
  UVALUE_CASTER_DEFINE(ufloat);
  UVALUE_CASTER_DEFINE(std::string);
  UVALUE_CASTER_DEFINE(const std::string);
  UVALUE_CASTER_DEFINE(bool);
  UVALUE_CASTER_DEFINE(UImage);
  UVALUE_CASTER_DEFINE(USound);

#undef UVALUE_CASTER_DEFINE

  template <>
  struct uvalue_caster<const UValue&>
  {
    const UValue& operator()(UValue& v)
      {
        return v;
      }
  };

  template <>
  struct uvalue_caster<UValue&>
  {
    UValue& operator()(UValue& v)
      {
        return v;
      }
  };

  template <>
  struct uvalue_caster<UValue>
  {
    UValue operator()(UValue& v)
      {
        return v;
      }
  };

  template <>
  struct uvalue_caster<const UValue>
  {
    const UValue operator()(UValue& v)
      {
        return v;
      }
  };

  // The following ones are defined in uvalue-common.cc.
  template <>
  struct URBI_SDK_API uvalue_caster<UVar>
  {
    UVar& operator () (UValue& v);
  };

# define UVALUE_CASTER_DECLARE(Type)		\
  template <>					\
  struct URBI_SDK_API uvalue_caster<Type>       \
  {                                             \
    Type operator () (UValue& v);		\
  }

  UVALUE_CASTER_DECLARE(UBinary);
  UVALUE_CASTER_DECLARE(UList);
  UVALUE_CASTER_DECLARE(UObjectStruct);
  UVALUE_CASTER_DECLARE(const char*);

# undef UVALUE_CASTER_DECLARE

# ifndef UOBJECT_NO_LIST_CAST
  template<typename I>
  struct uvalue_caster <std::list<I> >
  {
    std::list<I> operator()(UValue& v)
      {
        std::list<I> res;
        if (v.type != DATA_LIST)
          // Cast just the element.
          res.push_back(uvalue_cast<I*>(v));
        else
          for (int i = 0; i < v.list->size(); ++i)
            res.push_back(uvalue_cast<I*>(*v.list->array[i]));
        return res;
      }
  };
# endif

} // namespace urbi

#endif // ! URBI_UVALUE_HXX
<commit_msg>Add missing include.<commit_after>/// \file urbi/uvalue.hxx

// This file is part of UObject Component Architecture
// Copyright (c) 2009 Gostai S.A.S.
//
// Permission to use, copy, modify, and redistribute this software for
// non-commercial use is hereby granted.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// For more information, comments, bug reports: http://www.urbiforge.com

#ifndef URBI_UVALUE_HXX
# define URBI_UVALUE_HXX

# include <urbi/uvalue.hh>
# include <libport/assert.hh>

namespace urbi
{

  /*--------.
  | UList.  |
  `--------*/

# define ULIST_NTH(Const)                       \
  inline                                        \
  Const UValue&                                 \
  UList::operator[](size_t i) Const             \
  {                                             \
    i += offset;                                \
    if (i < size())                             \
      return *array[i];                         \
    else                                        \
      return UValue::error();                   \
  }

  ULIST_NTH(const)
  ULIST_NTH(/* const */)

# undef ULIST_NTH

  inline
  size_t
  UList::size() const
  {
    return array.size();
  }

  inline
  void
  UList::setOffset(size_t n)
  {
    offset = n;
  }

  /*--------------.
  | UNamedValue.  |
  `--------------*/

  inline
  UNamedValue::UNamedValue(const std::string& n, UValue* v)
    : name(n)
    , val(v)
  {}

  inline
  UNamedValue&
  UNamedValue::error()
  {
    static UNamedValue instance("<<UNamedValue::error (denotes an error)>>");
    return instance;
  }

  /*----------------.
  | UObjectStruct.  |
  `----------------*/

# define UOBJECTSTRUCT_NTH(Const)               \
  inline                                        \
  Const UNamedValue&                            \
  UObjectStruct::operator[](size_t i) Const     \
  {                                             \
    if (i < size())                             \
      return array[i];                          \
    else                                        \
      return UNamedValue::error();              \
  }

  UOBJECTSTRUCT_NTH(const)
  UOBJECTSTRUCT_NTH(/* const */)

# undef UOBJECTSTRUCT_NTH

  inline
  size_t
  UObjectStruct::size() const
  {
    return array.size();
  }

  /*---------.
  | UValue.  |
  `---------*/

  /// We use an operator , that behaves like an assignment.  The
  /// only difference is when the rhs is void, in which case it is
  /// the regular comma which is used.  This allows to write "uval,
  /// expr" to mean "compute expr and assign its result to uval,
  /// unless expr is void".
  inline
  UValue&
  UValue::operator, (const UValue &b)
  {
    return *this = b;
  }

#define CTOR_AND_ASSIGN_AND_COMMA(Type)		\
  inline                                        \
  UValue& UValue::operator, (Type rhs)          \
  {						\
    return *this = rhs;                         \
  }

  // UFloats.
  CTOR_AND_ASSIGN_AND_COMMA(ufloat);
  CTOR_AND_ASSIGN_AND_COMMA(int);
  CTOR_AND_ASSIGN_AND_COMMA(long);
  CTOR_AND_ASSIGN_AND_COMMA(unsigned int);
  CTOR_AND_ASSIGN_AND_COMMA(unsigned long);

  // Strings.
  CTOR_AND_ASSIGN_AND_COMMA(const char*);
  CTOR_AND_ASSIGN_AND_COMMA(const void*);
  CTOR_AND_ASSIGN_AND_COMMA(const std::string&);

  // Others.
  CTOR_AND_ASSIGN_AND_COMMA(const UBinary&);
  CTOR_AND_ASSIGN_AND_COMMA(const UList&);
  CTOR_AND_ASSIGN_AND_COMMA(const UObjectStruct&);
  CTOR_AND_ASSIGN_AND_COMMA(const USound&);
  CTOR_AND_ASSIGN_AND_COMMA(const UImage&);

#undef CTOR_AND_ASSIGN_AND_COMMA

  inline
  UValue::operator int() const
  {
    return static_cast<int>(static_cast<ufloat>((*this)));
  }

  inline
  UValue::operator unsigned int() const
  {
    return static_cast<unsigned int>(static_cast<ufloat>((*this)));
  }

  inline
  UValue::operator long() const
  {
    return static_cast<long>(static_cast<ufloat>((*this)));
  }

  inline
  UValue::operator unsigned long() const
  {
    return static_cast<unsigned long>(static_cast<ufloat>((*this)));
  }

  inline
  UValue::operator bool() const
  {
    return static_cast<int>(static_cast<ufloat>((*this))) != 0;
  }

  inline
  UValue&
  UValue::operator()()
  {
    return *this;
  }

  inline
  std::ostream&
  operator<<(std::ostream& s, const UValue& v)
  {
    // Looks bizarre, but might happen without have the "print" die
    // (it *has* happened).
    assert(&v);
    return v.print(s);
  }

  /*----------.
  | Casters.  |
  `----------*/

  // Run the uvalue_caster<Type> on v.
  template <typename Type>
  typename uvar_ref_traits<typename libport::unref_traits<Type>::type>::type
  uvalue_cast(UValue& v)
  {
    return uvalue_caster<typename libport::unref_traits<Type>::type>()(v);
  }

# define UVALUE_CASTER_DEFINE(Type)		\
  template <>					\
  struct uvalue_caster <Type>			\
  {						\
    Type operator() (UValue& v)			\
    {						\
      return v;					\
    }						\
  };

  UVALUE_CASTER_DEFINE(int);
  UVALUE_CASTER_DEFINE(unsigned int);
  UVALUE_CASTER_DEFINE(long);
  UVALUE_CASTER_DEFINE(unsigned long);
  UVALUE_CASTER_DEFINE(ufloat);
  UVALUE_CASTER_DEFINE(std::string);
  UVALUE_CASTER_DEFINE(const std::string);
  UVALUE_CASTER_DEFINE(bool);
  UVALUE_CASTER_DEFINE(UImage);
  UVALUE_CASTER_DEFINE(USound);

#undef UVALUE_CASTER_DEFINE

  template <>
  struct uvalue_caster<const UValue&>
  {
    const UValue& operator()(UValue& v)
      {
        return v;
      }
  };

  template <>
  struct uvalue_caster<UValue&>
  {
    UValue& operator()(UValue& v)
      {
        return v;
      }
  };

  template <>
  struct uvalue_caster<UValue>
  {
    UValue operator()(UValue& v)
      {
        return v;
      }
  };

  template <>
  struct uvalue_caster<const UValue>
  {
    const UValue operator()(UValue& v)
      {
        return v;
      }
  };

  // The following ones are defined in uvalue-common.cc.
  template <>
  struct URBI_SDK_API uvalue_caster<UVar>
  {
    UVar& operator () (UValue& v);
  };

# define UVALUE_CASTER_DECLARE(Type)		\
  template <>					\
  struct URBI_SDK_API uvalue_caster<Type>       \
  {                                             \
    Type operator () (UValue& v);		\
  }

  UVALUE_CASTER_DECLARE(UBinary);
  UVALUE_CASTER_DECLARE(UList);
  UVALUE_CASTER_DECLARE(UObjectStruct);
  UVALUE_CASTER_DECLARE(const char*);

# undef UVALUE_CASTER_DECLARE

# ifndef UOBJECT_NO_LIST_CAST
  template<typename I>
  struct uvalue_caster <std::list<I> >
  {
    std::list<I> operator()(UValue& v)
      {
        std::list<I> res;
        if (v.type != DATA_LIST)
          // Cast just the element.
          res.push_back(uvalue_cast<I*>(v));
        else
          for (int i = 0; i < v.list->size(); ++i)
            res.push_back(uvalue_cast<I*>(*v.list->array[i]));
        return res;
      }
  };
# endif

} // namespace urbi

#endif // ! URBI_UVALUE_HXX
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2006-2010, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/*! \file swig_python.hh
 * Python binding.
 */
#ifndef SWIG_PYTHON_H
# define SWIG_PYTHON_H

# ifndef SWIGPYTHON
#  error "This file must be compiled with SWIG in python mode."
# endif /* !SWIGPYTHON */

# include <object.h>
# include <uclient.h>

namespace urbi
{
  /*!
   * Pseudo-callback to bind a C callback
   * to a python function.
   */
  class Callback : public UCallbackWrapper
    {
    public:
      Callback(PyObject* obj) :
	UCallbackWrapper(),
	obj_ (obj)
	{
	  if (!obj_ || !PyFunction_Check(obj_) || !PyCallable_Check(obj_))
	    {
	      PyErr_SetString (PyExc_TypeError, "Need a callable object!");
	      return;
	    }
	  Py_INCREF(obj_);
	}

      virtual UCallbackAction operator () (const UMessage& msg)
	{
 	  FILE *fp = fopen("/tmp/foo.txt","w");
 	  PyObject_Print(obj_,fp,Py_PRINT_RAW);
 	  fclose(fp);

	  PyObject_CallFunction(obj_,"s", msg.message.c_str());
	  return URBI_CONTINUE;
	}

      virtual ~Callback()
	{
	  Py_DECREF(obj_);
	}

    private:
      PyObject* obj_;
    };
};

#endif /* !SWIG_PYTHON_H */
<commit_msg>Swig: Formatting changes.<commit_after>/*
 * Copyright (C) 2006-2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/*! \file swig_python.hh
 * Python binding.
 */
#ifndef SWIG_PYTHON_H
# define SWIG_PYTHON_H

# ifndef SWIGPYTHON
#  error "This file must be compiled with SWIG in python mode."
# endif /* !SWIGPYTHON */

# include <object.h>
# include <uclient.h>

namespace urbi
{
  /*!
   * Pseudo-callback to bind a C callback
   * to a python function.
   */
  class Callback : public UCallbackWrapper
    {
    public:
      Callback(PyObject* obj) :
	UCallbackWrapper(),
	obj_ (obj)
	{
	  if (!obj_ || !PyFunction_Check(obj_) || !PyCallable_Check(obj_))
	    {
	      PyErr_SetString (PyExc_TypeError, "Need a callable object!");
	      return;
	    }
	  Py_INCREF(obj_);
	}

      virtual UCallbackAction operator () (const UMessage& msg)
	{
	  FILE *fp = fopen("/tmp/foo.txt","w");
	  PyObject_Print(obj_,fp,Py_PRINT_RAW);
	  fclose(fp);

	  PyObject_CallFunction(obj_,"s", msg.message.c_str());
	  return URBI_CONTINUE;
	}

      virtual ~Callback()
	{
	  Py_DECREF(obj_);
	}

    private:
      PyObject* obj_;
    };
};

#endif /* !SWIG_PYTHON_H */
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(FUNCTIONNAME_HEADER_GUARD_1357924680)
#define FUNCTIONNAME_HEADER_GUARD_1357924680

// Base header file.  Must be first.
#include <XPath/XPathDefinitions.hpp>

#include <cassert>

#include <XalanDOM/XalanNode.hpp>
#include <XalanDOM/XalanAttr.hpp>
#include <XalanDOM/XalanDOMString.hpp>

// Base class header file...
#include <XPath/Function.hpp>

#include <XPath/NodeRefListBase.hpp>
#include <XPath/XObject.hpp>
#include <XPath/XObjectFactory.hpp>
#include <XPath/XPathExecutionContext.hpp>

/**
 * XPath implementation of "name" function.
 */
//
// These are all inline, even though
// there are virtual functions, because we expect that they will only be
// needed by the XPath class.
class XALAN_XPATH_EXPORT FunctionName : public Function
{
public:

	// These methods are inherited from Function ...

	virtual XObject*
	execute(
			XPathExecutionContext&			executionContext,
			XalanNode*						context,
			int								/* opPos */,
			const XObjectArgVectorType&		args)
	{
		const XObjectArgVectorType::size_type	theSize = args.size();

		XalanDOMString							theResult;

		if(theSize == 0)
		{
			if (context == 0)
			{
				executionContext.error("The name() function requires a non-null context node!",
									   context);
			}
			else
			{
				// Make a temporary XObject from the context node.
				XObjectFactory&						theFactory =
							executionContext.getXObjectFactory();

				FactoryObjectAutoPointer<XObject>	theXObject(&theFactory,
															   theFactory.createNodeSet(*context));

				theResult = getNameFromNodeList(theXObject->nodeset());
			}
		}
		else if (theSize == 1)
		{
			theResult = getNameFromNodeList(args[0]->nodeset());
		}
		else
		{
			executionContext.error("The name() function takes either zero arguments or one argument!",
								   context);
		}

		return executionContext.getXObjectFactory().createString(theResult);
	}

#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
	virtual Function*
#else
	virtual FunctionName*
#endif
	clone() const
	{
		return new FunctionName(*this);
	}

protected:

	/**
	 * Retrieve the name of the first element in the nodelist
	 *
	 * @param theNodeList node list
	 * @return name string of node, or an empty string if node list is empty
	 */
	virtual XalanDOMString
	getNameFromNodeList(const NodeRefListBase&	theNodeList) const
	{
		XalanDOMString	theResult;

		if (theNodeList.getLength() > 0)
		{
			const XalanNode* const	theNode	= theNodeList.item(0);
			assert(theNode != 0);

			if (XalanNode::ATTRIBUTE_NODE == theNode->getNodeType())
			{
				const XalanAttr* const	theAttributeNode =
					reinterpret_cast<const XalanAttr*>(theNode);

				theResult = theAttributeNode->getName();
			}
			else
			{
				theResult = theNode->getNodeName();
			}
		}

		return theResult;
	}

private:

	// Not implemented...
	FunctionName&
	operator=(const FunctionName&);

	bool
	operator==(const FunctionName&) const;
};

#endif	// FUNCTIONNAME_HEADER_GUARD_1357924680
<commit_msg>Fixed default argument code and updated code for certain types of nodes.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(FUNCTIONNAME_HEADER_GUARD_1357924680)
#define FUNCTIONNAME_HEADER_GUARD_1357924680

// Base header file.  Must be first.
#include <XPath/XPathDefinitions.hpp>

#include <cassert>

#include <XalanDOM/XalanNode.hpp>
#include <XalanDOM/XalanAttr.hpp>
#include <XalanDOM/XalanDOMString.hpp>

// Base class header file...
#include <XPath/Function.hpp>

#include <XPath/NodeRefListBase.hpp>
#include <XPath/XObject.hpp>
#include <XPath/XObjectFactory.hpp>
#include <XPath/XPathExecutionContext.hpp>

/**
 * XPath implementation of "name" function.
 */
//
// These are all inline, even though
// there are virtual functions, because we expect that they will only be
// needed by the XPath class.
class XALAN_XPATH_EXPORT FunctionName : public Function
{
public:

	// These methods are inherited from Function ...

	virtual XObject*
	execute(
			XPathExecutionContext&			executionContext,
			XalanNode*						context,
			int								/* opPos */,
			const XObjectArgVectorType&		args)
	{
		const XObjectArgVectorType::size_type	theSize = args.size();

		XalanDOMString							theResult;

		if(theSize == 0)
		{
			if (context == 0)
			{
				executionContext.error("The name() function requires a non-null context node!",
									   context);
			}
			else
			{
				theResult = getNameFromNode(*context);
			}
		}
		else if (theSize == 1)
		{
			assert(args[0] != 0);

			const NodeRefListBase&	theNodeList = args[0]->nodeset();

			if (theNodeList.getLength() != 0)
			{
				assert(theNodeList.item(0) != 0);

				theResult = getNameFromNode(*theNodeList.item(0));
			}
		}
		else
		{
			executionContext.error("The name() function takes either zero arguments or one argument!",
								   context);
		}

		return executionContext.getXObjectFactory().createString(theResult);
	}

#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
	virtual Function*
#else
	virtual FunctionName*
#endif
	clone() const
	{
		return new FunctionName(*this);
	}

protected:

	/**
	 * Retrieve the name of the first element in the nodelist
	 *
	 * @param theNodeList node list
	 * @return name string of node, or an empty string if node list is empty
	 */
	virtual XalanDOMString
	getNameFromNode(const XalanNode&	theNode) const
	{
		XalanDOMString	theResult;

		const XalanNode::NodeType	theNodeType =
				theNode.getNodeType();

		if (theNodeType == XalanNode::ATTRIBUTE_NODE)
		{
			const XalanAttr&	theAttributeNode =
					reinterpret_cast<const XalanAttr&>(theNode);

			theResult = theAttributeNode.getName();
		}
		else if (theNodeType == XalanNode::ELEMENT_NODE ||
				 theNodeType == XalanNode::PROCESSING_INSTRUCTION_NODE)
		{
			theResult = theNode.getNodeName();
		}

		return theResult;
	}

private:

	// Not implemented...
	FunctionName&
	operator=(const FunctionName&);

	bool
	operator==(const FunctionName&) const;
};

#endif	// FUNCTIONNAME_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>//=====================================================================//
/*!	@file
	@brief	MAX6675・メイン
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2016 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RL78/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/port_utils.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/itimer.hpp"
#include "common/format.hpp"
#include "common/delay.hpp"
#include "common/csi_io.hpp"
#include "chip/max6675.hpp"

namespace {

	// 送信、受信バッファの定義
	typedef utils::fifo<uint8_t, 32> BUFFER;
	// UART の定義（SAU02、SAU03）
	typedef device::uart_io<device::SAU02, device::SAU03, BUFFER, BUFFER> UART;
	UART	uart_;

	typedef device::itimer<uint8_t> ITM;
	ITM		itm_;

	// CSI(SPI) の定義、CSI20 の通信では、「SAU10」を利用、１ユニット、チャネル０
	typedef device::csi_io<device::SAU10> SPI;
	SPI		spi_;

	// MAX6675 インターフェースの定義
	typedef device::PORT<device::port_no::P5, device::bitpos::B5> MAX_CS;	///< MAX7765 選択信号

	typedef chip::MAX6675<SPI, MAX_CS> MAX6675;
	MAX6675	max6675_(spi_);
}

extern "C" {

	void sci_putch(char ch)
	{
		uart_.putch(ch);
	}

	void sci_puts(const char* str)
	{
		uart_.puts(str);
	}

	char sci_getch(void)
	{
		return uart_.getch();
	}

	uint16_t sci_length()
	{
		return uart_.recv_length();
	}

	void UART1_TX_intr(void)
	{
		uart_.send_task();
	}

	void UART1_RX_intr(void)
	{
		uart_.recv_task();
	}

	void UART1_ER_intr(void)
	{
		uart_.error_task();
	}

	void ITM_intr(void)
	{
		itm_.task();
	}
};

int main(int argc, char* argv[])
{
	using namespace device;

	utils::port::pullup_all();  ///< 安全の為、全ての入力をプルアップ

	// インターバル・タイマー開始
	{
		uint8_t intr_level = 1;
		itm_.start(60, intr_level);
	}

	// UART 開始
	{
		uint8_t intr_level = 1;
		uart_.start(115200, intr_level);
	}

	utils::format("Start RL78/G13 MAX6675 sample\n");

	// SPI 開始
	{
		uint8_t intr_level = 0;
		if(!spi_.start(8000000, SPI::PHASE::TYPE4, intr_level)) {
			uart_.puts("SPI Start fail...\n");
		}
	}

	// MAX6675 開始
	max6675_.start();

	PM4.B3 = 0;  // output

	uint8_t n = 0;
	uint8_t cnt = 0;
	while(1) {
		itm_.sync();

		++cnt;
		if(cnt >= 30) {
			cnt = 0;

			auto v = max6675_.get_temp();
			utils::format("%6.3f\n") % v;
		}

		++n;
		if(n >= 30) n = 0;
		P4.B3 = n < 10 ? false : true;
	}
}
<commit_msg>cleanup<commit_after>//=====================================================================//
/*!	@file
	@brief	MAX6675・メイン
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2016 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RL78/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/port_utils.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/itimer.hpp"
#include "common/format.hpp"
#include "common/delay.hpp"
#include "common/csi_io.hpp"
#include "chip/MAX6675.hpp"

namespace {

	// 送信、受信バッファの定義
	typedef utils::fifo<uint8_t, 32> BUFFER;
	// UART の定義（SAU02、SAU03）
	typedef device::uart_io<device::SAU02, device::SAU03, BUFFER, BUFFER> UART;
	UART	uart_;

	typedef device::itimer<uint8_t> ITM;
	ITM		itm_;

	// CSI(SPI) の定義、CSI20 の通信では、「SAU10」を利用、１ユニット、チャネル０
	typedef device::csi_io<device::SAU10> SPI;
	SPI		spi_;

	// MAX6675 インターフェースの定義
	typedef device::PORT<device::port_no::P5, device::bitpos::B5> MAX_CS;	///< MAX7765 選択信号

	typedef chip::MAX6675<SPI, MAX_CS> MAX6675;
	MAX6675	max6675_(spi_);
}

extern "C" {

	void sci_putch(char ch)
	{
		uart_.putch(ch);
	}

	void sci_puts(const char* str)
	{
		uart_.puts(str);
	}

	char sci_getch(void)
	{
		return uart_.getch();
	}

	uint16_t sci_length()
	{
		return uart_.recv_length();
	}

	void UART1_TX_intr(void)
	{
		uart_.send_task();
	}

	void UART1_RX_intr(void)
	{
		uart_.recv_task();
	}

	void UART1_ER_intr(void)
	{
		uart_.error_task();
	}

	void ITM_intr(void)
	{
		itm_.task();
	}
};

int main(int argc, char* argv[])
{
	using namespace device;

	utils::port::pullup_all();  ///< 安全の為、全ての入力をプルアップ

	// インターバル・タイマー開始
	{
		uint8_t intr_level = 1;
		itm_.start(60, intr_level);
	}

	// UART 開始
	{
		uint8_t intr_level = 1;
		uart_.start(115200, intr_level);
	}

	utils::format("Start RL78/G13 MAX6675 sample\n");

	// SPI 開始
	{
		uint8_t intr_level = 0;
		if(!spi_.start(8000000, SPI::PHASE::TYPE4, intr_level)) {
			uart_.puts("SPI Start fail...\n");
		}
	}

	// MAX6675 開始
	max6675_.start();

	PM4.B3 = 0;  // output

	uint8_t n = 0;
	uint8_t cnt = 0;
	while(1) {
		itm_.sync();

		++cnt;
		if(cnt >= 30) {
			cnt = 0;

			auto v = max6675_.get_temp();
			utils::format("%6.3f\n") % v;
		}

		++n;
		if(n >= 30) n = 0;
		P4.B3 = n < 10 ? false : true;
	}
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <time.h>

#include "../Neural_Networks.h"

void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **target_output) {
	ifstream file(training_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
	}

	file.open(training_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
	}

	file.open(test_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
	}

	file.open(test_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
	}
}

int main() {
	int batch_size		= 60;
	int number_iterations = 50;
	int number_threads;
	int number_training = 60000;
	int number_test		= 10000;

	float **input = new float*[number_training + number_test];
	float **target_output = new float*[number_training + number_test];

	double epsilon		 = 0.001;
	double learning_rate = 0.005;
	double decay_rate	 = 0.977;

	string path;

	vector<int> number_nodes = { 784, 10 };

	vector<Layer*> layer;

	// train from scratch *****************
	Neural_Networks NN = Neural_Networks();

	layer.push_back(NN.Add(new Layer("MNIST", 784)));
	layer.push_back(NN.Add(new Layer("BN,ReLU", 400)));		// batch normalization, ReLU activation
	layer.push_back(NN.Add(new Layer("BN,ReLU", 400)));		// batch normalization, ReLU activation
	layer.push_back(NN.Add(new Layer("CE,softmax", 10)));	// cross-entropy loss, softmax activation

	layer[1]->Connect(layer[0], "W"); // fully connected
	layer[2]->Connect(layer[1], "W"); // fully connected
	layer[3]->Connect(layer[2], "W"); // fully connected

	srand(0); NN.Initialize(0.01);
	// ************************************

	// or load pretrained model
	// Neural_Networks NN = Neural_Networks("MNIST_MLP.txt");

	cout << "The number of threads : ";
	cin >> number_threads;
	cin.ignore();

	omp_set_num_threads(number_threads);

	cout << "path where MNIST handwritten digits dataset is : ";
	getline(cin, path);

	for (int h = 0; h < number_training + number_test; h++) {
		input[h] = new float[number_nodes.front()];
		target_output[h] = new float[number_nodes.back()];
	}
	Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, input, target_output);

	for (int g = 0, time = clock(); g < number_iterations; g++) {
		int score[2] = { 0, };

		float **output = new float*[batch_size];

		double loss = NN.Train(batch_size, number_training, input, target_output, learning_rate, epsilon);

		for (int h = 0; h < batch_size; h++) {
			output[h] = new float[number_nodes.back()];
		}
		for (int i = 0, h = 0; i < number_training + number_test; i++) {
			if (++h == batch_size || i == number_training + number_test - 1) {
				NN.Test(h, &input[i - h + 1], output);

				for (int g = 0, argmax; g < h; g++) {
					double max = 0;

					for (int j = 0; j < number_nodes.back(); j++) {
						if (max < output[g][j]) {
							max = output[g][argmax = j];
						}
					}
					score[(i - h + g + 1 < number_training) ? (0) : (1)] += (int)target_output[i - h + g + 1][argmax];
				}
				h = 0;
			}
		}
		printf("."); NN.Save("NN.txt");

		printf("score: %d / %d, %d / %d  loss: %lf  step %d  %.2lf sec\n", score[0], number_training, score[1], number_test, loss, g + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
		learning_rate *= decay_rate;

		for (int h = 0; h < batch_size; h++) {
			delete[] output[h];
		}
		delete[] output;
	}

	for (int h = 0; h < number_training + number_test; h++) {
		delete[] input[h];
		delete[] target_output[h];
	}
	delete[] input;
	delete[] target_output;

	return 0;
}
<commit_msg>Update MNIST_MLP.cpp<commit_after>#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <time.h>

#include "../Neural_Networks.h"

using namespace NNCPU;

void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **target_output) {
	ifstream file(training_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
	}

	file.open(training_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
	}

	file.open(test_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
	}

	file.open(test_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
	}
}

int main() {
	int batch_size		= 60;
	int number_iterations = 50;
	int number_threads;
	int number_training = 60000;
	int number_test		= 10000;

	float **input = new float*[number_training + number_test];
	float **target_output = new float*[number_training + number_test];

	double epsilon		 = 0.001;
	double learning_rate = 0.005;
	double decay_rate	 = 0.977;

	string path;

	vector<int> number_nodes = { 784, 10 };

	vector<Layer*> layer;

	// train from scratch *****************
	Neural_Networks NN = Neural_Networks();

	layer.push_back(NN.Add(new Layer("MNIST", 784)));
	layer.push_back(NN.Add(new Layer("BN,ReLU", 400)));		// batch normalization, ReLU activation
	layer.push_back(NN.Add(new Layer("BN,ReLU", 400)));		// batch normalization, ReLU activation
	layer.push_back(NN.Add(new Layer("CE,softmax", 10)));	// cross-entropy loss, softmax activation

	layer[1]->Connect(layer[0], "W"); // fully connected
	layer[2]->Connect(layer[1], "W"); // fully connected
	layer[3]->Connect(layer[2], "W"); // fully connected

	srand(0); NN.Initialize(0.01);
	// ************************************

	// or load pretrained model
	// Neural_Networks NN = Neural_Networks("MNIST_MLP.txt");

	cout << "The number of threads : ";
	cin >> number_threads;
	cin.ignore();

	omp_set_num_threads(number_threads);

	cout << "path where MNIST handwritten digits dataset is : ";
	getline(cin, path);

	for (int h = 0; h < number_training + number_test; h++) {
		input[h] = new float[number_nodes.front()];
		target_output[h] = new float[number_nodes.back()];
	}
	Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, input, target_output);

	for (int g = 0, time = clock(); g < number_iterations; g++) {
		int score[2] = { 0, };

		float **output = new float*[batch_size];

		double loss = NN.Train(batch_size, number_training, input, target_output, learning_rate, epsilon);

		for (int h = 0; h < batch_size; h++) {
			output[h] = new float[number_nodes.back()];
		}
		for (int i = 0, h = 0; i < number_training + number_test; i++) {
			if (++h == batch_size || i == number_training + number_test - 1) {
				NN.Test(h, &input[i - h + 1], output);

				for (int g = 0, argmax; g < h; g++) {
					double max = 0;

					for (int j = 0; j < number_nodes.back(); j++) {
						if (max < output[g][j]) {
							max = output[g][argmax = j];
						}
					}
					score[(i - h + g + 1 < number_training) ? (0) : (1)] += (int)target_output[i - h + g + 1][argmax];
				}
				h = 0;
			}
		}
		printf("."); NN.Save("NN.txt");

		printf("score: %d / %d, %d / %d  loss: %lf  step %d  %.2lf sec\n", score[0], number_training, score[1], number_test, loss, g + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
		learning_rate *= decay_rate;

		for (int h = 0; h < batch_size; h++) {
			delete[] output[h];
		}
		delete[] output;
	}

	for (int h = 0; h < number_training + number_test; h++) {
		delete[] input[h];
		delete[] target_output[h];
	}
	delete[] input;
	delete[] target_output;

	return 0;
}
<|endoftext|>


<commit_before>#include "RoutineListModel.h"

int RoutineListModel::rowCount(const QModelIndex& parent) const
{
    if (parent.isValid()) {
        return 0;
    } else {
        return routineList.count();
    }
}

int RoutineListModel::columnCount(const QModelIndex&) const
{
    return 4;
}

QVariant RoutineListModel::data(const QModelIndex &idx, int role) const
{
    RoutineListEntry *rle = routineList[idx.row()];
    if (role != Qt::DisplayRole && role != Qt::UserRole) {
        return QVariant();
    }
    if (role == Qt::UserRole && idx.column() == 2) {
        return rle->inclusiveTimePercent;
    }
    if (role == Qt::UserRole && idx.column() == 3) {
        return rle->exclusiveTimePercent;
    }
    switch (idx.column()) {
    case 0:
        return rle->name + " (" + rle->file + ":" + QString::number(rle->line) + ")";
        break;
    case 1:
        return rle->entries;
        break;
    case 2:
        return QString::number(rle->inclusiveTimePercent)
            + "% (" + QString::number(rle->inclusiveTime) + "ms)";
        break;
    case 3:
        return QString::number(rle->exclusiveTimePercent)
            + "% (" + QString::number(rle->exclusiveTime) + "ms)";
        break;
    default:
        return QVariant();
    }
}

QVariant RoutineListModel::headerData(int section, Qt::Orientation orientation, int role)
    const
{
    if (role != Qt::DisplayRole) {
        return QVariant();
    }
    if (orientation != Qt::Horizontal) {
        return QVariant();
    }
    return QString("Routine,Entries,Inclusive time,Exclusive time").split(",")[section];
}
<commit_msg>sort by time, not percentage<commit_after>#include "RoutineListModel.h"

int RoutineListModel::rowCount(const QModelIndex& parent) const
{
    if (parent.isValid()) {
        return 0;
    } else {
        return routineList.count();
    }
}

int RoutineListModel::columnCount(const QModelIndex&) const
{
    return 4;
}

QVariant RoutineListModel::data(const QModelIndex &idx, int role) const
{
    RoutineListEntry *rle = routineList[idx.row()];
    if (role != Qt::DisplayRole && role != Qt::UserRole) {
        return QVariant();
    }
    if (role == Qt::UserRole && idx.column() == 2) {
        return rle->inclusiveTime;
    }
    if (role == Qt::UserRole && idx.column() == 3) {
        return rle->exclusiveTime;
    }
    switch (idx.column()) {
    case 0:
        return rle->name + " (" + rle->file + ":" + QString::number(rle->line) + ")";
        break;
    case 1:
        return rle->entries;
        break;
    case 2:
        return QString::number(rle->inclusiveTimePercent)
            + "% (" + QString::number(rle->inclusiveTime) + "ms)";
        break;
    case 3:
        return QString::number(rle->exclusiveTimePercent)
            + "% (" + QString::number(rle->exclusiveTime) + "ms)";
        break;
    default:
        return QVariant();
    }
}

QVariant RoutineListModel::headerData(int section, Qt::Orientation orientation, int role)
    const
{
    if (role != Qt::DisplayRole) {
        return QVariant();
    }
    if (orientation != Qt::Horizontal) {
        return QVariant();
    }
    return QString("Routine,Entries,Inclusive time,Exclusive time").split(",")[section];
}
<|endoftext|>


<commit_before>/* * This file is part of Maliit framework *
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * Contact: maliit-discuss@lists.maliit.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "connectionfactory.h"

#ifndef MALIIT_DISABLE_DBUS
#ifdef HAVE_GLIB_DBUS
#include "glibdbusimserverproxy.h"
#include "minputcontextglibdbusconnection.h"
#else
#include "dbusserverconnection.h"
#include "dbusinputcontextconnection.h"
#endif
#endif
#include "mimdirectserverconnection.h"

namespace Maliit {
#ifndef MALIIT_DISABLE_DBUS
namespace DBus {

MImServerConnection *createServerConnectionWithDynamicAddress()
{
    const QSharedPointer<Maliit::InputContext::DBus::Address> address(new Maliit::InputContext::DBus::DynamicAddress);
#ifdef HAVE_GLIB_DBUS
    return new GlibDBusIMServerProxy(address);
#else
    return new DBusServerConnection(address);
#endif
}

MImServerConnection *createServerConnectionWithFixedAddress(const QString &fixedAddress)
{
    const QSharedPointer<Maliit::InputContext::DBus::Address> address(new Maliit::InputContext::DBus::FixedAddress(fixedAddress));
#ifdef HAVE_GLIB_DBUS
    return new GlibDBusIMServerProxy(address);
#else
    return new DBusServerConnection(address);
#endif
}

MInputContextConnection *createInputContextConnectionWithDynamicAddress()
{
#ifdef HAVE_GLIB_DBUS
    std::tr1::shared_ptr<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::DynamicAddress);
    return new MInputContextGlibDBusConnection(address, false);
#else
    QSharedPointer<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::DynamicAddress);
    return new DBusInputContextConnection(address);
#endif
}

MInputContextConnection *createInputContextConnectionWithFixedAddress(const QString &fixedAddress, bool allowAnonymous)
{
#ifdef HAVE_GLIB_DBUS
    std::tr1::shared_ptr<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::FixedAddress(fixedAddress));
    return new MInputContextGlibDBusConnection(address, allowAnonymous);
#else
    Q_UNUSED(allowAnonymous);
    QSharedPointer<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::FixedAddress(fixedAddress));
    return new DBusInputContextConnection(address);
#endif
}

} // namespace DBus
#endif // MALIIT_DISABLE_DBUS

QSharedPointer<MImServerConnection> createServerConnection(const QString &connectionType)
{
    typedef QSharedPointer<MImServerConnection> ConnectionPtr;
    static QWeakPointer<MImServerConnection> cached_connection;

    if (ConnectionPtr connection = cached_connection.toStrongRef())
        return connection;
    if (connectionType.isEmpty()) {
        qCritical() << "Empty connection type name. Refusing to connect to Maliit server."
                    << "\nHave you checked the environment variables for loading input method"
                    << "modules ([QT|GTK]_IM_MODULE)?";
        return ConnectionPtr();
    }

    if (connectionType == MALIIT_INPUTCONTEXT_NAME) {
#ifndef MALIIT_DISABLE_DBUS
        const QByteArray overriddenAddress = qgetenv("MALIIT_SERVER_ADDRESS");
        ConnectionPtr connection;

        if (overriddenAddress.isEmpty()) {
            cached_connection = connection = ConnectionPtr(Maliit::DBus::createServerConnectionWithDynamicAddress());
        } else {
            cached_connection = connection = ConnectionPtr(Maliit::DBus::createServerConnectionWithFixedAddress(overriddenAddress));
        }

        return connection;
#else
        qCritical("This connection type to Maliit server is not available since DBus support is disabled");
#endif
    } else if (connectionType == MALIIT_INPUTCONTEXT_NAME"Direct") {
        ConnectionPtr connection(new MImDirectServerConnection);

        cached_connection = connection;

        return connection;
    } else {
        qCritical() << __PRETTY_FUNCTION__ << "Invalid connection type (" + connectionType + "), unable to create connection to Maliit server";

        return ConnectionPtr();
    }
}

} // namespace Maliit
<commit_msg>Fix coding style in connection factory<commit_after>/* * This file is part of Maliit framework *
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * Contact: maliit-discuss@lists.maliit.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "connectionfactory.h"

#ifndef MALIIT_DISABLE_DBUS
#ifdef HAVE_GLIB_DBUS
#include "glibdbusimserverproxy.h"
#include "minputcontextglibdbusconnection.h"
#else
#include "dbusserverconnection.h"
#include "dbusinputcontextconnection.h"
#endif
#endif
#include "mimdirectserverconnection.h"

namespace Maliit {
#ifndef MALIIT_DISABLE_DBUS
namespace DBus {

MImServerConnection *createServerConnectionWithDynamicAddress()
{
    const QSharedPointer<Maliit::InputContext::DBus::Address> address(new Maliit::InputContext::DBus::DynamicAddress);
#ifdef HAVE_GLIB_DBUS
    return new GlibDBusIMServerProxy(address);
#else
    return new DBusServerConnection(address);
#endif
}

MImServerConnection *createServerConnectionWithFixedAddress(const QString &fixedAddress)
{
    const QSharedPointer<Maliit::InputContext::DBus::Address> address(new Maliit::InputContext::DBus::FixedAddress(fixedAddress));
#ifdef HAVE_GLIB_DBUS
    return new GlibDBusIMServerProxy(address);
#else
    return new DBusServerConnection(address);
#endif
}

MInputContextConnection *createInputContextConnectionWithDynamicAddress()
{
#ifdef HAVE_GLIB_DBUS
    std::tr1::shared_ptr<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::DynamicAddress);
    return new MInputContextGlibDBusConnection(address, false);
#else
    QSharedPointer<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::DynamicAddress);
    return new DBusInputContextConnection(address);
#endif
}

MInputContextConnection *createInputContextConnectionWithFixedAddress(const QString &fixedAddress, bool allowAnonymous)
{
#ifdef HAVE_GLIB_DBUS
    std::tr1::shared_ptr<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::FixedAddress(fixedAddress));
    return new MInputContextGlibDBusConnection(address, allowAnonymous);
#else
    Q_UNUSED(allowAnonymous);
    QSharedPointer<Maliit::Server::DBus::Address> address(new Maliit::Server::DBus::FixedAddress(fixedAddress));
    return new DBusInputContextConnection(address);
#endif
}

} // namespace DBus
#endif // MALIIT_DISABLE_DBUS

QSharedPointer<MImServerConnection> createServerConnection(const QString &connectionType)
{
    typedef QSharedPointer<MImServerConnection> ConnectionPtr;
    static QWeakPointer<MImServerConnection> cached_connection;

    if (ConnectionPtr connection = cached_connection.toStrongRef()) {
        return connection;
    }

    if (connectionType.isEmpty()) {
        qCritical() << "Empty connection type name. Refusing to connect to Maliit server."
                    << "\nHave you checked the environment variables for loading input method"
                    << "modules ([QT|GTK]_IM_MODULE)?";
        return ConnectionPtr();
    }

    if (connectionType == MALIIT_INPUTCONTEXT_NAME) {
#ifndef MALIIT_DISABLE_DBUS
        const QByteArray overriddenAddress = qgetenv("MALIIT_SERVER_ADDRESS");
        ConnectionPtr connection = ConnectionPtr(overriddenAddress.isEmpty()
                                                 ? Maliit::DBus::createServerConnectionWithDynamicAddress()
                                                 : Maliit::DBus::createServerConnectionWithFixedAddress(overriddenAddress));
        cached_connection = connection;

        return connection;
#else
        qCritical("This connection type to Maliit server is not available since DBus support is disabled");
#endif
    } else if (connectionType == MALIIT_INPUTCONTEXT_NAME"Direct") {
        ConnectionPtr connection(new MImDirectServerConnection);

        cached_connection = connection;

        return connection;
    } else {
        qCritical() << __PRETTY_FUNCTION__
                    << "Invalid connection type (" + connectionType + "),"
                    << "unable to create connection to Maliit server";
        return ConnectionPtr();
    }
}

} // namespace Maliit
<|endoftext|>


<commit_before>#pragma once

#include <utility>
#include <supermarx/id_t.hpp>

#include <supermarx/data/product.hpp>
#include <supermarx/data/productdetails.hpp>

#include <boost/optional.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

namespace supermarx
{
namespace data
{
struct productclass;
}

namespace message
{

struct product_summary
{
	std::string identifier; // Internal reference as used by scrapers
	std::string name;

	reference<data::productclass> productclass_id;

	uint64_t volume;
	measure volume_measure;

	uint64_t orig_price; // In (euro)cents
	uint64_t price; // In (euro)cents, with discount applied
	uint64_t discount_amount;

	datetime valid_on;

	boost::optional<id_t> imagecitation_id;

	static product_summary merge(data::product const& p, data::productdetails const& pd)
	{
		return product_summary({
			p.identifier,
			p.name,
			p.productclass_id,
			p.volume,
			p.volume_measure,
			pd.orig_price,
			pd.price,
			pd.discount_amount,
			pd.valid_on
		});
	}
};

}
}

BOOST_FUSION_ADAPT_STRUCT(
			supermarx::message::product_summary,
			(std::string, identifier)
			(std::string, name)
			(supermarx::reference<supermarx::data::productclass>, productclass_id)
			(uint64_t, volume)
			(supermarx::measure, volume_measure)
			(uint64_t, orig_price)
			(uint64_t, price)
			(uint64_t, discount_amount)
			(supermarx::datetime, valid_on)
			(boost::optional<supermarx::id_t>, imagecitation_id)
)
<commit_msg>Fixed imagecitation_id not being set<commit_after>#pragma once

#include <utility>
#include <supermarx/id_t.hpp>

#include <supermarx/data/product.hpp>
#include <supermarx/data/productdetails.hpp>

#include <boost/optional.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

namespace supermarx
{
namespace data
{
struct productclass;
}

namespace message
{

struct product_summary
{
	std::string identifier; // Internal reference as used by scrapers
	std::string name;

	reference<data::productclass> productclass_id;

	uint64_t volume;
	measure volume_measure;

	uint64_t orig_price; // In (euro)cents
	uint64_t price; // In (euro)cents, with discount applied
	uint64_t discount_amount;

	datetime valid_on;

	boost::optional<reference<data::imagecitation>> imagecitation_id;

	static product_summary merge(data::product const& p, data::productdetails const& pd)
	{
		return product_summary({
			p.identifier,
			p.name,
			p.productclass_id,
			p.volume,
			p.volume_measure,
			pd.orig_price,
			pd.price,
			pd.discount_amount,
			pd.valid_on,
			p.imagecitation_id
		});
	}
};

}
}

BOOST_FUSION_ADAPT_STRUCT(
			supermarx::message::product_summary,
			(std::string, identifier)
			(std::string, name)
			(supermarx::reference<supermarx::data::productclass>, productclass_id)
			(uint64_t, volume)
			(supermarx::measure, volume_measure)
			(uint64_t, orig_price)
			(uint64_t, price)
			(uint64_t, discount_amount)
			(supermarx::datetime, valid_on)
			(boost::optional<supermarx::id_t>, imagecitation_id)
)
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include "yy.h"

void yyerror(const char *str) {
  fprintf(stderr, "%s:%d %s: near '%s'\n", yyfilename, chplLineno, str, yytext);
  exit(1);
}

int yywrap() {
  return 1;
}
<commit_msg><commit_after>#include <stdio.h>
#include <stdlib.h>
#include "yy.h"

void yyerror(const char *str) {
  fprintf(stderr, "%s:%d %s", yyfilename, chplLineno, str);
  if (strlen(yytext) > 0) {
    fprintf(stderr, ": near '%s'", yytext);
  }
  fprintf(stderr, "\n");
  exit(1);
}

int yywrap() {
  return 1;
}
<|endoftext|>