text:
#include "ocl/Types/impl/TypesFactoryImpl.hpp"

#include <cassert>

#include "abstractDataTypes/SubsetUnion.hpp"
#include "ecore/EClass.hpp"
#include "ocl/Types/impl/AnyTypeImpl.hpp"
#include "ocl/Types/impl/BagTypeImpl.hpp"
#include "ocl/Types/impl/CollectionTypeImpl.hpp"
#include "ocl/Types/impl/InvalidTypeImpl.hpp"
#include "ocl/Types/impl/MessageTypeImpl.hpp"
#include "ocl/Types/impl/NameTypeBindingImpl.hpp"
#include "ocl/Types/impl/OrderedSetTypeImpl.hpp"
#include "ocl/Types/impl/SequenceTypeImpl.hpp"
#include "ocl/Types/impl/SetTypeImpl.hpp"
#include "ocl/Types/impl/TemplateParameterTypeImpl.hpp"
#include "ocl/Types/impl/TupleTypeImpl.hpp"
#include "ocl/Types/impl/VoidTypeImpl.hpp"

#include "ecore/ecorePackage.hpp"
#include "ecore/EPackage.hpp"

using namespace ocl::Types;

//*********************************
// Constructor / Destructor
//*********************************

TypesFactoryImpl::TypesFactoryImpl()
{
	m_idMap.insert(std::make_pair("ocl::Types::AnyType", TypesPackage::ANYTYPE_CLASS));
	m_idMap.insert(std::make_pair("ocl::Types::BagType", TypesPackage::BAGTYPE_CLASS));
	m_idMap.insert(std::make_pair("ocl::Types::CollectionType", TypesPackage::COLLECTIONTYPE_CLASS));
	m_idMap.insert(std::make_pair("ocl::Types::InvalidType", TypesPackage::INVALIDTYPE_CLASS));
	m_idMap.insert(std::make_pair("ocl::Types::MessageType", TypesPackage::MESSAGETYPE_CLASS));
	m_idMap.insert(std::make_pair("ocl::Types::NameTypeBinding", TypesPackage::NAMETYPEBINDING_CLASS));
	m_idMap.insert(std::make_pair("ocl::Types::OrderedSetType", TypesPackage::ORDEREDSETTYPE_CLASS));
	m_idMap.insert(std::make_pair("ocl::Types::SequenceType", TypesPackage::SEQUENCETYPE_CLASS));
	m_idMap.insert(std::make_pair("ocl::Types::SetType", TypesPackage::SETTYPE_CLASS));
	m_idMap.insert(std::make_pair("ocl::Types::TemplateParameterType", TypesPackage::TEMPLATEPARAMETERTYPE_CLASS));
	m_idMap.insert(std::make_pair("ocl::Types::TupleType", TypesPackage::TUPLETYPE_CLASS));
	m_idMap.insert(std::make_pair("ocl::Types::VoidType", TypesPackage::VOIDTYPE_CLASS));
}

TypesFactoryImpl::~TypesFactoryImpl()
{
}

TypesFactory* TypesFactoryImpl::create()
{
	return new TypesFactoryImpl();
}

//*********************************
// creators
//*********************************

std::shared_ptr<ecore::EObject> TypesFactoryImpl::create(const int metaElementID, std::shared_ptr<ecore::EObject> container /*= nullptr*/, const int referenceID/* = -1*/) const
{
	switch(metaElementID)
	{
		case TypesPackage::ANYTYPE_CLASS:
		{
			if (nullptr == container)
			{
				return this->createAnyType(metaElementID);
			}
			else
			{
				switch(referenceID)
				{
					//AnyType has eClassifiers as a containment
					case  ecore::ecorePackage::EPACKAGE_ATTRIBUTE_ECLASSIFIERS:
					{
						std::weak_ptr<ecore::EPackage> castedContainer = std::dynamic_pointer_cast<ecore::EPackage> (container);
						return this->createAnyType_as_eClassifiers_in_EPackage(castedContainer,metaElementID);
					}
					//AnyType has elementType as a containment
					case  ocl::Types::TypesPackage::COLLECTIONTYPE_ATTRIBUTE_ELEMENTTYPE:
					{
						std::shared_ptr<ocl::Types::CollectionType> castedContainer = std::dynamic_pointer_cast<ocl::Types::CollectionType> (container);;
						return this->createAnyType_as_elementType_in_CollectionType(castedContainer,metaElementID);
					}
					default:
						std::cerr << __PRETTY_FUNCTION__ << "ERROR: Reference type not found." << std::endl;
				}
			}
			break;
		}
		case TypesPackage::BAGTYPE_CLASS:
		{
			if (nullptr == container)
			{
				return this->createBagType(metaElementID);
			}
			else
			{
				std::shared_ptr<ocl::Types::CollectionType> castedContainer = std::dynamic_pointer_cast<ocl::Types::CollectionType>(container);
				assert(castedContainer);
				return std::shared_ptr<ocl::Types::BagType>(this->createBagType_as_elementType_in_CollectionType(castedContainer,metaElementID));
			}
			break;
		}
		case TypesPackage::COLLECTIONTYPE_CLASS:
		{
			if (nullptr == container)
			{
				return this->createCollectionType(metaElementID);
			}
			else
			{
				switch(referenceID)
				{
					//CollectionType has eClassifiers as a containment
					case  ecore::ecorePackage::EPACKAGE_ATTRIBUTE_ECLASSIFIERS:
					{
						std::weak_ptr<ecore::EPackage> castedContainer = std::dynamic_pointer_cast<ecore::EPackage> (container);
						return this->createCollectionType_as_eClassifiers_in_EPackage(castedContainer,metaElementID);
					}
					//CollectionType has elementType as a containment
					case  ocl::Types::TypesPackage::COLLECTIONTYPE_ATTRIBUTE_ELEMENTTYPE:
					{
						std::shared_ptr<ocl::Types::CollectionType> castedContainer = std::dynamic_pointer_cast<ocl::Types::CollectionType> (container);;
						return this->createCollectionType_as_elementType_in_CollectionType(castedContainer,metaElementID);
					}
					default:
						std::cerr << __PRETTY_FUNCTION__ << "ERROR: Reference type not found." << std::endl;
				}
			}
			break;
		}
		case TypesPackage::INVALIDTYPE_CLASS:
		{
			if (nullptr == container)
			{
				return this->createInvalidType(metaElementID);
			}
			else
			{
				switch(referenceID)
				{
					//InvalidType has eClassifiers as a containment
					case  ecore::ecorePackage::EPACKAGE_ATTRIBUTE_ECLASSIFIERS:
					{
						std::weak_ptr<ecore::EPackage> castedContainer = std::dynamic_pointer_cast<ecore::EPackage> (container);
						return this->createInvalidType_as_eClassifiers_in_EPackage(castedContainer,metaElementID);
					}
					//InvalidType has elementType as a containment
					case  ocl::Types::TypesPackage::COLLECTIONTYPE_ATTRIBUTE_ELEMENTTYPE:
					{
						std::shared_ptr<ocl::Types::CollectionType> castedContainer = std::dynamic_pointer_cast<ocl::Types::CollectionType> (container);;
						return this->createInvalidType_as_elementType_in_CollectionType(castedContainer,metaElementID);
					}
					default:
						std::cerr << __PRETTY_FUNCTION__ << "ERROR: Reference type not found." << std::endl;
				}
			}
			break;
		}
		case TypesPackage::MESSAGETYPE_CLASS:
		{
			if (nullptr == container)
			{
				return this->createMessageType(metaElementID);
			}
			else
			{
				switch(referenceID)
				{
					//MessageType has eClassifiers as a containment
					case  ecore::ecorePackage::EPACKAGE_ATTRIBUTE_ECLASSIFIERS:
					{
						std::weak_ptr<ecore::EPackage> castedContainer = std::dynamic_pointer_cast<ecore::EPackage> (container);
						return this->createMessageType_as_eClassifiers_in_EPackage(castedContainer,metaElementID);
					}
					//MessageType has elementType as a containment
					case  ocl::Types::TypesPackage::COLLECTIONTYPE_ATTRIBUTE_ELEMENTTYPE:
					{
						std::shared_ptr<ocl::Types::CollectionType> castedContainer = std::dynamic_pointer_cast<ocl::Types::CollectionType> (container);;
						return this->createMessageType_as_elementType_in_CollectionType(castedContainer,metaElementID);
					}
					default:
						std::cerr << __PRETTY_FUNCTION__ << "ERROR: Reference type not found." << std::endl;
				}
			}
			break;
		}
		case TypesPackage::NAMETYPEBINDING_CLASS:
		{
				return this->createNameTypeBinding(metaElementID);

			break;
		}
		case TypesPackage::ORDEREDSETTYPE_CLASS:
		{
			if (nullptr == container)
			{
				return this->createOrderedSetType(metaElementID);
			}
			else
			{
				std::shared_ptr<ocl::Types::CollectionType> castedContainer = std::dynamic_pointer_cast<ocl::Types::CollectionType>(container);
				assert(castedContainer);
				return std::shared_ptr<ocl::Types::OrderedSetType>(this->createOrderedSetType_as_elementType_in_CollectionType(castedContainer,metaElementID));
			}
			break;
		}
		case TypesPackage::SEQUENCETYPE_CLASS:
		{
			if (nullptr == container)
			{
				return this->createSequenceType(metaElementID);
			}
			else
			{
				std::shared_ptr<ocl::Types::CollectionType> castedContainer = std::dynamic_pointer_cast<ocl::Types::CollectionType>(container);
				assert(castedContainer);
				return std::shared_ptr<ocl::Types::SequenceType>(this->createSequenceType_as_elementType_in_CollectionType(castedContainer,metaElementID));
			}
			break;
		}
		case TypesPackage::SETTYPE_CLASS:
		{
			if (nullptr == container)
			{
				return this->createSetType(metaElementID);
			}
			else
			{
				std::shared_ptr<ocl::Types::CollectionType> castedContainer = std::dynamic_pointer_cast<ocl::Types::CollectionType>(container);
				assert(castedContainer);
				return std::shared_ptr<ocl::Types::SetType>(this->createSetType_as_elementType_in_CollectionType(castedContainer,metaElementID));
			}
			break;
		}
		case TypesPackage::TEMPLATEPARAMETERTYPE_CLASS:
		{
			if (nullptr == container)
			{
				return this->createTemplateParameterType(metaElementID);
			}
			else
			{
				switch(referenceID)
				{
					//TemplateParameterType has eClassifiers as a containment
					case  ecore::ecorePackage::EPACKAGE_ATTRIBUTE_ECLASSIFIERS:
					{
						std::weak_ptr<ecore::EPackage> castedContainer = std::dynamic_pointer_cast<ecore::EPackage> (container);
						return this->createTemplateParameterType_as_eClassifiers_in_EPackage(castedContainer,metaElementID);
					}
					//TemplateParameterType has elementType as a containment
					case  ocl::Types::TypesPackage::COLLECTIONTYPE_ATTRIBUTE_ELEMENTTYPE:
					{
						std::shared_ptr<ocl::Types::CollectionType> castedContainer = std::dynamic_pointer_cast<ocl::Types::CollectionType> (container);;
						return this->createTemplateParameterType_as_elementType_in_CollectionType(castedContainer,metaElementID);
					}
					default:
						std::cerr << __PRETTY_FUNCTION__ << "ERROR: Reference type not found." << std::endl;
				}
			}
			break;
		}
		case TypesPackage::TUPLETYPE_CLASS:
		{
			if (nullptr == container)
			{
				return this->createTupleType(metaElementID);
			}
			else
			{
				switch(referenceID)
				{
					//TupleType has eClassifiers as a containment
					case  ecore::ecorePackage::EPACKAGE_ATTRIBUTE_ECLASSIFIERS:
					{
						std::weak_ptr<ecore::EPackage> castedContainer = std::dynamic_pointer_cast<ecore::EPackage> (container);
						return this->createTupleType_as_eClassifiers_in_EPackage(castedContainer,metaElementID);
					}
					//TupleType has elementType as a containment
					case  ocl::Types::TypesPackage::COLLECTIONTYPE_ATTRIBUTE_ELEMENTTYPE:
					{
						std::shared_ptr<ocl::Types::CollectionType> castedContainer = std::dynamic_pointer_cast<ocl::Types::CollectionType> (container);;
						return this->createTupleType_as_elementType_in_CollectionType(castedContainer,metaElementID);
					}
					default:
						std::cerr << __PRETTY_FUNCTION__ << "ERROR: Reference type not found." << std::endl;
				}
			}
			break;
		}
		case TypesPackage::VOIDTYPE_CLASS:
		{
			if (nullptr == container)
			{
				return this->createVoidType(metaElementID);
			}
			else
			{
				switch(referenceID)
				{
					//VoidType has eClassifiers as a containment
					case  ecore::ecorePackage::EPACKAGE_ATTRIBUTE_ECLASSIFIERS:
					{
						std::weak_ptr<ecore::EPackage> castedContainer = std::dynamic_pointer_cast<ecore::EPackage> (container);
						return this->createVoidType_as_eClassifiers_in_EPackage(castedContainer,metaElementID);
					}
					//VoidType has elementType as a containment
					case  ocl::Types::TypesPackage::COLLECTIONTYPE_ATTRIBUTE_ELEMENTTYPE:
					{
						std::shared_ptr<ocl::Types::CollectionType> castedContainer = std::dynamic_pointer_cast<ocl::Types::CollectionType> (container);;
						return this->createVoidType_as_elementType_in_CollectionType(castedContainer,metaElementID);
					}
					default:
						std::cerr << __PRETTY_FUNCTION__ << "ERROR: Reference type not found." << std::endl;
				}
			}
			break;
		}
	default:
	   	    std::cerr << __PRETTY_FUNCTION__ << " ID " << metaElementID <<" not found" << std::endl;
	}
	return nullptr;
}

std::shared_ptr<ecore::EObject> TypesFactoryImpl::create(std::shared_ptr<ecore::EClass> _class, std::shared_ptr<ecore::EObject> container /*= nullptr*/, const int referenceID/* = -1*/) const
{
	if(_class->isAbstract())
    {
    	return nullptr;
   	}
	int _elementID = _class->getMetaElementID();
	return create(_elementID, container, referenceID);
}

std::shared_ptr<ecore::EObject> TypesFactoryImpl::create(std::string _className, std::shared_ptr<ecore::EObject> container /*= nullptr*/, const int referenceID/* = -1*/) const
{
	auto iter = m_idMap.find(_className);
	if(iter != m_idMap.end())
    {
		//get the ID
        int id = iter->second;
		return create(id,container,referenceID);
    }
    return nullptr;
}

std::shared_ptr<ocl::Types::AnyType> TypesFactoryImpl::createAnyType(const int metaElementID/*=-1*/) const
{
	std::shared_ptr<ocl::Types::AnyTypeImpl> element(new ocl::Types::AnyTypeImpl());
	element->setMetaElementID(metaElementID);
	element->setThisAnyTypePtr(element);
	return element;
}
std::shared_ptr<ocl::Types::AnyType> TypesFactoryImpl::createAnyType_as_eClassifiers_in_EPackage(std::weak_ptr<ecore::EPackage> par_EPackage, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::AnyTypeImpl> element(new ocl::Types::AnyTypeImpl(par_EPackage));
	element->setMetaElementID(metaElementID);
	if(auto wp = par_EPackage.lock())
	{
		wp->getEClassifiers()->push_back(element);
	}

	element->setThisAnyTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::AnyType> TypesFactoryImpl::createAnyType_as_elementType_in_CollectionType(std::shared_ptr<ocl::Types::CollectionType> par_CollectionType, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::AnyTypeImpl> element(new ocl::Types::AnyTypeImpl());
	element->setMetaElementID(metaElementID);
	if(nullptr != par_CollectionType)
	{
		par_CollectionType->setElementType(element);
	}

	element->setThisAnyTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::BagType> TypesFactoryImpl::createBagType(const int metaElementID/*=-1*/) const
{
	std::shared_ptr<ocl::Types::BagTypeImpl> element(new ocl::Types::BagTypeImpl());
	element->setMetaElementID(metaElementID);
	element->setThisBagTypePtr(element);
	return element;
}
std::shared_ptr<ocl::Types::BagType> TypesFactoryImpl::createBagType_as_elementType_in_CollectionType(std::shared_ptr<ocl::Types::CollectionType> par_CollectionType, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::BagTypeImpl> element(new ocl::Types::BagTypeImpl());
	element->setMetaElementID(metaElementID);
	if(nullptr != par_CollectionType)
	{
		par_CollectionType->setElementType(element);
	}

	element->setThisBagTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::CollectionType> TypesFactoryImpl::createCollectionType(const int metaElementID/*=-1*/) const
{
	std::shared_ptr<ocl::Types::CollectionTypeImpl> element(new ocl::Types::CollectionTypeImpl());
	element->setMetaElementID(metaElementID);
	element->setThisCollectionTypePtr(element);
	return element;
}
std::shared_ptr<ocl::Types::CollectionType> TypesFactoryImpl::createCollectionType_as_eClassifiers_in_EPackage(std::weak_ptr<ecore::EPackage> par_EPackage, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::CollectionTypeImpl> element(new ocl::Types::CollectionTypeImpl(par_EPackage));
	element->setMetaElementID(metaElementID);
	if(auto wp = par_EPackage.lock())
	{
		wp->getEClassifiers()->push_back(element);
	}

	element->setThisCollectionTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::CollectionType> TypesFactoryImpl::createCollectionType_as_elementType_in_CollectionType(std::shared_ptr<ocl::Types::CollectionType> par_CollectionType, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::CollectionTypeImpl> element(new ocl::Types::CollectionTypeImpl());
	element->setMetaElementID(metaElementID);
	if(nullptr != par_CollectionType)
	{
		par_CollectionType->setElementType(element);
	}

	element->setThisCollectionTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::InvalidType> TypesFactoryImpl::createInvalidType(const int metaElementID/*=-1*/) const
{
	std::shared_ptr<ocl::Types::InvalidTypeImpl> element(new ocl::Types::InvalidTypeImpl());
	element->setMetaElementID(metaElementID);
	element->setThisInvalidTypePtr(element);
	return element;
}
std::shared_ptr<ocl::Types::InvalidType> TypesFactoryImpl::createInvalidType_as_eClassifiers_in_EPackage(std::weak_ptr<ecore::EPackage> par_EPackage, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::InvalidTypeImpl> element(new ocl::Types::InvalidTypeImpl(par_EPackage));
	element->setMetaElementID(metaElementID);
	if(auto wp = par_EPackage.lock())
	{
		wp->getEClassifiers()->push_back(element);
	}

	element->setThisInvalidTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::InvalidType> TypesFactoryImpl::createInvalidType_as_elementType_in_CollectionType(std::shared_ptr<ocl::Types::CollectionType> par_CollectionType, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::InvalidTypeImpl> element(new ocl::Types::InvalidTypeImpl());
	element->setMetaElementID(metaElementID);
	if(nullptr != par_CollectionType)
	{
		par_CollectionType->setElementType(element);
	}

	element->setThisInvalidTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::MessageType> TypesFactoryImpl::createMessageType(const int metaElementID/*=-1*/) const
{
	std::shared_ptr<ocl::Types::MessageTypeImpl> element(new ocl::Types::MessageTypeImpl());
	element->setMetaElementID(metaElementID);
	element->setThisMessageTypePtr(element);
	return element;
}
std::shared_ptr<ocl::Types::MessageType> TypesFactoryImpl::createMessageType_as_eClassifiers_in_EPackage(std::weak_ptr<ecore::EPackage> par_EPackage, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::MessageTypeImpl> element(new ocl::Types::MessageTypeImpl(par_EPackage));
	element->setMetaElementID(metaElementID);
	if(auto wp = par_EPackage.lock())
	{
		wp->getEClassifiers()->push_back(element);
	}

	element->setThisMessageTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::MessageType> TypesFactoryImpl::createMessageType_as_elementType_in_CollectionType(std::shared_ptr<ocl::Types::CollectionType> par_CollectionType, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::MessageTypeImpl> element(new ocl::Types::MessageTypeImpl());
	element->setMetaElementID(metaElementID);
	if(nullptr != par_CollectionType)
	{
		par_CollectionType->setElementType(element);
	}

	element->setThisMessageTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::NameTypeBinding> TypesFactoryImpl::createNameTypeBinding(const int metaElementID/*=-1*/) const
{
	std::shared_ptr<ocl::Types::NameTypeBindingImpl> element(new ocl::Types::NameTypeBindingImpl());
	element->setMetaElementID(metaElementID);
	element->setThisNameTypeBindingPtr(element);
	return element;
}
std::shared_ptr<ocl::Types::OrderedSetType> TypesFactoryImpl::createOrderedSetType(const int metaElementID/*=-1*/) const
{
	std::shared_ptr<ocl::Types::OrderedSetTypeImpl> element(new ocl::Types::OrderedSetTypeImpl());
	element->setMetaElementID(metaElementID);
	element->setThisOrderedSetTypePtr(element);
	return element;
}
std::shared_ptr<ocl::Types::OrderedSetType> TypesFactoryImpl::createOrderedSetType_as_elementType_in_CollectionType(std::shared_ptr<ocl::Types::CollectionType> par_CollectionType, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::OrderedSetTypeImpl> element(new ocl::Types::OrderedSetTypeImpl());
	element->setMetaElementID(metaElementID);
	if(nullptr != par_CollectionType)
	{
		par_CollectionType->setElementType(element);
	}

	element->setThisOrderedSetTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::SequenceType> TypesFactoryImpl::createSequenceType(const int metaElementID/*=-1*/) const
{
	std::shared_ptr<ocl::Types::SequenceTypeImpl> element(new ocl::Types::SequenceTypeImpl());
	element->setMetaElementID(metaElementID);
	element->setThisSequenceTypePtr(element);
	return element;
}
std::shared_ptr<ocl::Types::SequenceType> TypesFactoryImpl::createSequenceType_as_elementType_in_CollectionType(std::shared_ptr<ocl::Types::CollectionType> par_CollectionType, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::SequenceTypeImpl> element(new ocl::Types::SequenceTypeImpl());
	element->setMetaElementID(metaElementID);
	if(nullptr != par_CollectionType)
	{
		par_CollectionType->setElementType(element);
	}

	element->setThisSequenceTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::SetType> TypesFactoryImpl::createSetType(const int metaElementID/*=-1*/) const
{
	std::shared_ptr<ocl::Types::SetTypeImpl> element(new ocl::Types::SetTypeImpl());
	element->setMetaElementID(metaElementID);
	element->setThisSetTypePtr(element);
	return element;
}
std::shared_ptr<ocl::Types::SetType> TypesFactoryImpl::createSetType_as_elementType_in_CollectionType(std::shared_ptr<ocl::Types::CollectionType> par_CollectionType, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::SetTypeImpl> element(new ocl::Types::SetTypeImpl());
	element->setMetaElementID(metaElementID);
	if(nullptr != par_CollectionType)
	{
		par_CollectionType->setElementType(element);
	}

	element->setThisSetTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::TemplateParameterType> TypesFactoryImpl::createTemplateParameterType(const int metaElementID/*=-1*/) const
{
	std::shared_ptr<ocl::Types::TemplateParameterTypeImpl> element(new ocl::Types::TemplateParameterTypeImpl());
	element->setMetaElementID(metaElementID);
	element->setThisTemplateParameterTypePtr(element);
	return element;
}
std::shared_ptr<ocl::Types::TemplateParameterType> TypesFactoryImpl::createTemplateParameterType_as_eClassifiers_in_EPackage(std::weak_ptr<ecore::EPackage> par_EPackage, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::TemplateParameterTypeImpl> element(new ocl::Types::TemplateParameterTypeImpl(par_EPackage));
	element->setMetaElementID(metaElementID);
	if(auto wp = par_EPackage.lock())
	{
		wp->getEClassifiers()->push_back(element);
	}

	element->setThisTemplateParameterTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::TemplateParameterType> TypesFactoryImpl::createTemplateParameterType_as_elementType_in_CollectionType(std::shared_ptr<ocl::Types::CollectionType> par_CollectionType, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::TemplateParameterTypeImpl> element(new ocl::Types::TemplateParameterTypeImpl());
	element->setMetaElementID(metaElementID);
	if(nullptr != par_CollectionType)
	{
		par_CollectionType->setElementType(element);
	}

	element->setThisTemplateParameterTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::TupleType> TypesFactoryImpl::createTupleType(const int metaElementID/*=-1*/) const
{
	std::shared_ptr<ocl::Types::TupleTypeImpl> element(new ocl::Types::TupleTypeImpl());
	element->setMetaElementID(metaElementID);
	element->setThisTupleTypePtr(element);
	return element;
}
std::shared_ptr<ocl::Types::TupleType> TypesFactoryImpl::createTupleType_as_eClassifiers_in_EPackage(std::weak_ptr<ecore::EPackage> par_EPackage, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::TupleTypeImpl> element(new ocl::Types::TupleTypeImpl(par_EPackage));
	element->setMetaElementID(metaElementID);
	if(auto wp = par_EPackage.lock())
	{
		wp->getEClassifiers()->push_back(element);
	}

	element->setThisTupleTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::TupleType> TypesFactoryImpl::createTupleType_as_elementType_in_CollectionType(std::shared_ptr<ocl::Types::CollectionType> par_CollectionType, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::TupleTypeImpl> element(new ocl::Types::TupleTypeImpl());
	element->setMetaElementID(metaElementID);
	if(nullptr != par_CollectionType)
	{
		par_CollectionType->setElementType(element);
	}

	element->setThisTupleTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::VoidType> TypesFactoryImpl::createVoidType(const int metaElementID/*=-1*/) const
{
	std::shared_ptr<ocl::Types::VoidTypeImpl> element(new ocl::Types::VoidTypeImpl());
	element->setMetaElementID(metaElementID);
	element->setThisVoidTypePtr(element);
	return element;
}
std::shared_ptr<ocl::Types::VoidType> TypesFactoryImpl::createVoidType_as_eClassifiers_in_EPackage(std::weak_ptr<ecore::EPackage> par_EPackage, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::VoidTypeImpl> element(new ocl::Types::VoidTypeImpl(par_EPackage));
	element->setMetaElementID(metaElementID);
	if(auto wp = par_EPackage.lock())
	{
		wp->getEClassifiers()->push_back(element);
	}

	element->setThisVoidTypePtr(element);
	return element;

}
std::shared_ptr<ocl::Types::VoidType> TypesFactoryImpl::createVoidType_as_elementType_in_CollectionType(std::shared_ptr<ocl::Types::CollectionType> par_CollectionType, const int metaElementID) const
{
	std::shared_ptr<ocl::Types::VoidTypeImpl> element(new ocl::Types::VoidTypeImpl());
	element->setMetaElementID(metaElementID);
	if(nullptr != par_CollectionType)
	{
		par_CollectionType->setElementType(element);
	}

	element->setThisVoidTypePtr(element);
	return element;

}


text:
a {
    filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://test/test.png',sizingMethod=crop);
    filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://test/test.png');
    filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src="//a/b/test/test2/wFPs-e1B3wMRud8TzGw7YHjS08I.png",sizingMethod=crop);
    filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src="//a/b/test/test2/wFPs-e1B3wMRud8TzGw7YHjS08I.png");
}

redpajama_set_name: RedPajamaGithub


text:
require 'parse-cron'

module ElectricSheep
  module Metadata
    module Schedule
      class Base < Metadata::Base
        attr_reader :scheduled_at

        def initialize(*args)
          super
          update!
        end

        def expired?
          Time.now >= scheduled_at
        end

        def update!; end
      end

      class Hourly < Base
        option :past

        def update!
          @scheduled_at = Time.now.at_beginning_of_hour.in(1.hour)
          return unless option(:past)
          @scheduled_at = @scheduled_at.in(option(:past).to_i.minutes)
        end
      end

      class Timed < Base
        option :at

        protected

        def at_time(time)
          at = (option(:at) || '').split(':')
          time.change(hour: at[0].to_i, min: at[1].to_i, sec: 0)
        end
      end

      class Daily < Timed
        def update!
          @scheduled_at = at_time(Time.now)
          @scheduled_at = @scheduled_at.in(1.day) if @scheduled_at < Time.now
        end
      end

      class Weekly < Timed
        option :on, required: true

        DAYS = %w(sunday monday tuesday wednesday thursday friday saturday)
               .freeze

        def update!
          bow = Time.now.at_beginning_of_week(:sunday)
          @scheduled_at = at_time(bow).in(DAYS.find_index(option(:on)).days)
          @scheduled_at = @scheduled_at.in(1.week) if @scheduled_at < Time.now
        end
      end

      class Monthly < Timed
        option :every

        def days_in_month(time)
          Time.days_in_month(time.month, time.year)
        end

        def update!
          day = option(:every) || 1
          basetime = at_time(Time.now)
          @scheduled_at = adjust(basetime, day)
          return unless @scheduled_at < Time.now
          @scheduled_at = adjust(basetime.in(1.month), day)
        end

        protected

        def adjust(time, day)
          time.change(day: [day.to_i, days_in_month(time)].min)
        end
      end

      class Cron < Base
        option :expression, required: true

        def update!
          @parser ||= CronParser.new(expression)
          @scheduled_at = @parser.next(Time.now)
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
  ~ Copyright (C) 2016 Jacob Klinker
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<merge xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:app="http://schemas.android.com/apk/res-auto">

    <View
        android:id="@+id/photo_background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone"/>

    <ImageView
        android:id="@+id/photo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="false"
        android:scaleType="centerCrop" />
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/header_content_container">

    </FrameLayout>

    <View
        android:id="@+id/photo_touch_intercept_overlay"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <View
        android:id="@+id/title_gradient"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom" />
    <View
        android:id="@+id/action_bar_gradient"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top" />

    <android.support.v7.widget.Toolbar
        android:layout_width="wrap_content"
        android:layout_gravity="end|top"
        android:layout_height="?android:attr/actionBarSize"
        android:background="@android:color/transparent"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="?popup_theme"
        android:id="@+id/toolbar"/>

</merge>


text:
import * as React from 'react';

export interface ButtonRect {
  height: number;
  width: number;
  left: number;
  top: number;
}

export interface State {
  isOpen: boolean;
  closingWithClick: boolean;
  selectionIndex: number;
  buttonRect: undefined | ButtonRect;
  buttonId: string;
}

export interface MenuProps {
  children?: React.ReactNode;
}

export const Menu: React.FC<MenuProps>;

export type MenuButtonProps = {
  onClick?: (e: React.MouseEvent<HTMLElement>) => void;
  onKeyDown?: (e: React.KeyboardEvent<HTMLElement>) => void;
  children?: React.ReactNode;
} & React.HTMLProps<HTMLButtonElement>;

export const MenuButton: React.FC<MenuButtonProps>;

export type MenuListProps = JSX.IntrinsicElements["div"] & {
  children?: React.ReactNode;
};

export const MenuList: React.FC<MenuListProps>;

export type ResolvedMenuLinkProps<T> = T extends keyof JSX.IntrinsicElements
  ? JSX.IntrinsicElements[T]
  : T;

export type ResolvedMenuLinkComponent<T> = T extends keyof JSX.IntrinsicElements
  ? T
  : React.ComponentType<T>;

export type MenuLinkProps<
  T extends SupportedMenuLinkComponent
> = ResolvedMenuLinkProps<T> & {
  as?: string;
  to?: string;
  onKeyDown?: (e: React.KeyboardEvent<HTMLElement>) => void;
  onClick?: (e: React.MouseEvent<HTMLElement>) => void;
  component?: ResolvedMenuLinkComponent<T>;
  index?: number;
  style?: React.CSSProperties;
  setState?: (s: State) => Partial<State>;
  state?: State;
  _ref?: (node: HTMLElement) => void;
};

export type SupportedMenuLinkComponent = object | keyof JSX.IntrinsicElements;

export function MenuLink<T extends SupportedMenuLinkComponent>(
  props: MenuLinkProps<T>
): React.ReactElement<MenuLinkProps<T>>;

export type MenuItemProps = {
  onSelect?: () => void;
  onClick?: (e: React.MouseEvent<HTMLElement>) => void;
  onKeyDown?: (e: React.KeyboardEvent<HTMLElement>) => void;
  onMouseMove?: (e: React.MouseEvent<HTMLElement>) => void;
  role?: string;
  state?: State;
  setState?: (s: State) => Partial<State>;
  index?: number;
  _ref?: (node: HTMLElement) => void;
} & React.HTMLProps<HTMLDivElement>;

export const MenuItem: React.FC<MenuItemProps>;


text:
double KalmanFilter(double inData, PKALMAN_STATE state)
{

	//Kalman filter function start*******************************
	state->p = state->p + state->q;
	state->kGain = state->p / (state->p + state->r);

	inData = state->prevData + (state->kGain*(inData - state->prevData));

	state->p = (1 - state->kGain)*state->p;

	state->prevData = inData;
	//Kalman filter function stop********************************

	return inData;
}


text:
saved = environment
if (environment.nil?)
  environment = :development
else
  environment = saved
end

source_dir = "src"
sass_dir = source_dir + "/sass"

output_dir = "dist"
css_dir = output_dir + "/css"
javascripts_dir = output_dir + "/js"
images_dir = output_dir + "/images"
generated_images_dir = images_dir + "/generated"

# Require any additional compass plugins installed on your system.
require 'compass-normalize'
require 'rgbapng'
require 'toolkit'
require 'breakpoint'
# require 'susy'
require 'singularitygs'
require 'sass-globbing'

##
## You probably don't need to edit anything below this.
##

# You can select your preferred output style here (:expanded, :nested, :compact
# or :compressed).
output_style = (environment == :production) ? :compressed : :nested

# To enable relative paths to assets via compass helper functions.
relative_assets = true

# Conditionally enable line comments when in development mode.
line_comments = (environment == :production) ? false : true

# Output debugging info in development mode.
sass_options = (environment == :production) ? {} : {:debug_info => true}


text:
typedef void (^SuccessBlock)(AFHTTPRequestOperation *, id);
typedef void (^FailureBlock)(AFHTTPRequestOperation *, NSError *);

@implementation CLMNetworkingClient

#pragma mark - Initializer

- (instancetype)initWithManager:(AFHTTPRequestOperationManager *)manager
{
    NSParameterAssert(manager);

    self = [super init];

    if (self) {
        _manager = manager;
        _filter = [CLMFilter new];
    }

    return self;
}

#pragma mark - Public - GET

- (BFTask *)GET:(NSString *)URLString parameters:(id)parameters
{
    return [self requestTaskWithHTTPMethod:@"GET" URLString:URLString parameters:parameters constructingBodyWithBlock:nil];
}

#pragma mark - Public - HEAD

- (BFTask *)HEAD:(NSString *)URLString parameters:(id)parameters
{
    return [self requestTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters constructingBodyWithBlock:nil];
}

#pragma mark - Public - POST

- (BFTask *)POST:(NSString *)URLString parameters:(id)parameters
{
    return [self requestTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters constructingBodyWithBlock:nil];
}

- (BFTask *)POST:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(CLMConstructingBodyWithBlock)block
{
    return [self requestTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters constructingBodyWithBlock:block];
}

#pragma mark - Public - PUT

- (BFTask *)PUT:(NSString *)URLString parameters:(id)parameters
{
    return [self requestTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters constructingBodyWithBlock:nil];
}

- (BFTask *)PUT:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(CLMConstructingBodyWithBlock)block
{
    return [self requestTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters constructingBodyWithBlock:block];
}

#pragma mark - Public - PATCH

- (BFTask *)PATCH:(NSString *)URLString parameters:(id)parameters
{
    return [self requestTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters constructingBodyWithBlock:nil];
}

- (BFTask *)PATCH:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(CLMConstructingBodyWithBlock)block
{
    return [self requestTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters constructingBodyWithBlock:block];
}

#pragma mark - Public - DELETE

- (BFTask *)DELETE:(NSString *)URLString parameters:(id)parameters
{
    return [self requestTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters constructingBodyWithBlock:nil];
}

#pragma mark - Public

- (void)cancelAll
{
    [self.manager.operationQueue cancelAllOperations];
}

- (BFTask *)requestTaskWithHTTPMethod:(NSString *)method
                            URLString:(NSString *)URLString
                           parameters:(id)parameters
            constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
{
    NSParameterAssert(method);
    NSParameterAssert(self.filter);

    parameters = [self.filter filter:parameters];

    NSError *serializationError = nil;

    NSMutableURLRequest *request = [self requestWithMethod:method URLString:URLString parameters:parameters constructingBodyWithBlock:block error:&serializationError];

    if (serializationError) {
        return [BFTask taskWithError:serializationError];
    }

    BFTask *task = [self operationTaskWithRequest:request];

    return [task continueWithSuccessBlock:^id(BFTask *task) {
        AFHTTPRequestOperation *operation = task.result;

        id responseObject = [self.filter filter:operation.responseObject];

        CLMNetworkingResult *result = [[CLMNetworkingResult alloc] initWithResponseObject:responseObject request:operation.request response:operation.response];

        return [BFTask taskWithResult:result];
    }];
}

#pragma mark - Private

- (BFTask *)operationTaskWithRequest:(NSURLRequest *)request
{
    NSParameterAssert(request);

    BFTaskCompletionSource *completionSource = [BFTaskCompletionSource taskCompletionSource];

    SuccessBlock success = ^(AFHTTPRequestOperation *operation, id responseObject) {
        [completionSource setResult:operation];
    };

    FailureBlock failure = ^(AFHTTPRequestOperation *operation, NSError *error) {
        error = [NSError CLMNetworkingErrorWithOperation:operation error:error];

        if (error.cancelled) {
            [completionSource cancel];
        } else {
            [completionSource setError:error];
        }
    };

    [self operationWithRequest:request success:success failure:failure];

    return completionSource.task;
}

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
                                 URLString:(NSString *)URLString
                                parameters:(NSDictionary *)parameters
                 constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
                                     error:(NSError *__autoreleasing *)error
{
    NSMutableURLRequest *request;

    if (block) {
        request = [self.manager.requestSerializer multipartFormRequestWithMethod:method
                                                                       URLString:[[NSURL URLWithString:URLString relativeToURL:self.manager.baseURL] absoluteString]
                                                                      parameters:parameters
                                                       constructingBodyWithBlock:block
                                                                           error:error];
    } else {
        request = [self.manager.requestSerializer requestWithMethod:method
                                                          URLString:[[NSURL URLWithString:URLString relativeToURL:self.manager.baseURL] absoluteString]
                                                         parameters:parameters
                                                              error:error];
    }

    return request;
}

- (AFHTTPRequestOperation *)operationWithRequest:(NSURLRequest *)request
                                         success:(SuccessBlock)success
                                         failure:(FailureBlock)failure
{
    AFHTTPRequestOperation *operation = [self.manager HTTPRequestOperationWithRequest:request success:success failure:failure];

    [self.manager.operationQueue addOperation:operation];

    return operation;
}

@end


text:
<?php

	// Reglas
	$_miNombre  // válido
	$miNombre   // válido
	$__variable // valido
	$variable21 // válido
	$_1Grande   // inválido - carácter de subrayado debe estar seguido de una letra al principio
	$1Grande    // inválido - se debe empezar con letra o carácter de subrayado
	$_er-t      // inválido - contiene un guión

?>


text:
'use strict'
var path = require('path')
var validate = require('aproba')

module.exports = function inflateBundled (parent, children) {
  validate('OA', arguments)
  children.forEach(function (child) {
    child.fromBundle = true
    child.parent = parent
    child.path = path.join(parent.path, child.package.name)
    child.realpath = path.resolve(parent.realpath, child.package.name)
    child.isLink = child.isLink || parent.isLink || parent.target
    inflateBundled(child, child.children)
  })
}


text:
package com.company;

import java.util.Scanner;

public class CakeIngredients {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String input = scanner.nextLine();
        int br = 0;

        while (!input.equals("Bake!")) {
            System.out.printf("Adding ingredient %s.%n", input);
            input = scanner.nextLine();
            br++;
        }
        System.out.printf("Preparing cake with %d ingredients.", br);
    }
}


text:
<?php
namespace CodingBeard\Chess;

use CodingBeard\Chess\Board\Move;
use CodingBeard\Chess\Board\Piece;
use CodingBeard\Chess\Board\Square;
use models\Games;
use models\Players;
use Phalcon\Mvc\User\Component;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Websocket extends Component implements MessageComponentInterface
{
    /**
     * Array of clients, keys are their players model IDs
     * @var array
     */
    public $clients = [];

    /**
     * Array of games, keys are their games model IDs
     * @var array
     */
    public $games = [];

    /**
     * When a client Connects
     * @param ConnectionInterface $client
     */
    public function onOpen(ConnectionInterface $client)
    {

    }

    /**
     * When we receive a message
     * @param ConnectionInterface $client
     * @param string $msg
     */
    public function onMessage(ConnectionInterface $client, $msg)
    {
        $json = json_decode($msg);
        if ($json) {
            if (!isset($client->player) && $json->action != 'connect') {
                return $client->send(json_encode([
                    ['type' => 'alert', 'params' => [
                        'type' => 'modal',
                        'You must first auth before using any other functions'
                    ]]
                ]));
            }
            if (method_exists($this, $json->action)) {
                $this->{$json->action}($client, $json->params);
            }
        }
    }

    /**
     * When a client disconnects
     * @param ConnectionInterface $client
     */
    public function onClose(ConnectionInterface $client)
    {
        if (isset($client->player)) {
            unset($this->clients[$client->player->id]);
            echo "Player ({$client->player->id}) has disconnected\n";
        }
        else {
            echo "An unauthenticated client has disconnected\n";
        }
    }

    /**
     * When an error occurs
     * @param ConnectionInterface $client
     * @param \Exception $e
     */
    public function onError(ConnectionInterface $client, \Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";
        $client->close();
    }

    /**
     * On the initial connection set their player ID and add them to our clients
     * @param ConnectionInterface $client
     * @param $params
     * @return string
     */
    public function connect(ConnectionInterface $client, $params)
    {
        $player = Players::findFirstByToken($params->token);
        if (!$player) {
            $player = new Players();
            $player->token = $params->token;
            $player->save();
        }

        $client->player = $player;

        $this->clients[$player->id] = $client;
        echo "Player ({$player->id}) has connected\n";
        $client->send(json_encode([
            ['type' => 'alert', 'params' => [
                'type' => 'toast',
                'message' => 'Connected'
            ]]
        ]));
    }

    /**
     * Start a new game type
     * @param ConnectionInterface $client
     * @param $params
     * @return string
     */
    public function newGame(ConnectionInterface $client, $params)
    {
        switch ($params->type) {
            case "multiLocal":
                return $this->newMutiLocal($client, $params);
            case "aiLocal":

        }
    }

    /**
     * Start a new Multiplayer local game
     * @param ConnectionInterface $client
     * @param $params
     * @return string
     */
    public function newMutiLocal(ConnectionInterface $client, $params)
    {
        $gameModel = new Games();
        $gameModel->type = "multiLocal";
        $gameModel->turn = Piece::WHITE;
        $gameModel->playerW_id = $client->player->id;
        $gameModel->playerB_id = $client->player->id;
        $gameModel->save();

        $board = new Board();
        $board->setDefaults();
        $game = new Game($board);

        $gameModel->game = $game;

        $this->games[$gameModel->id] = $gameModel;

        $client->send(json_encode([
            ['type' => 'alert', 'params' => [
                'type' => 'toast',
                'message' => 'New game started, white to go first',
            ]],
            ['type' => 'addPieces', 'params' => [
                'pieces' => $board->toArray()
            ]],
            ['type' => 'setGame', 'params' => [
                'id' => $gameModel->id,
                'turn' => $gameModel->turn
            ]]
        ]));
    }

    /**
     * Find the game from the gamdId
     * @param ConnectionInterface $client
     * @param $params
     * @return bool|Games
     */
    public function getGameModel(ConnectionInterface $client, $params)
    {
        /** @var Games $gameModel */
        $gameModel = $this->games[$params->gameId];
        if (!$gameModel) {
            $gameModel = Games::findFirstById($params->gameId);
        }
        /* No gameId matching a game we have, send an error */
        if (!$gameModel) {
            $client->send(json_encode([
                ['type' => 'alert', 'params' => [
                    'type' => 'modal',
                    'message' => 'You do not have a game to check a move for.' . $params->get,
                ]]
            ]));
            return false;
        }
        return $gameModel;
    }

    /**
     * Check that it is their turn, and the move is within the pieces moves, send error and revert if not
     * @param ConnectionInterface $client
     * @param Game $game
     * @param Move $move
     * @return bool
     */
    public function checkBasicMove(ConnectionInterface $client, $game, $move)
    {
        $response = $game->checkMove($move);
        if ($response != Ai::VALID_MOVE) {
            if ($response == Ai::NOT_TURN) {
                $toast = "Not your turn";
            }
            else if ($response == Ai::INVALID_MOVE) {
                $toast = "Invalid move";
            }
            $client->send(json_encode([
                ['type' => 'alert', 'params' => [
                    'type' => 'toast',
                    'message' => $toast,
                ]],
                ['type' => 'invalidMove'],
            ]));
            return false;
        }
        return true;
    }

    /**
     * Check if a move is legal, if not send an invalid notice and move the piece back
     * @param ConnectionInterface $client
     * @param $params
     * @return bool|string
     */
    public function checkMove(ConnectionInterface $client, $params)
    {
        /* Make sure the client has a game */
        if (!($gameModel = $this->getGameModel($client, $params))) {
            return false;
        }

        /** @var \CodingBeard\Chess\Game $game */
        $game = $gameModel->game;
        $move = $this->moveToPhp($params->move);

        /* Make sure the move is basically correct */
        if (!$this->checkBasicMove($client, $game, $move)) {
            return false;
        }

        /* If the current player is in check, we need to make sure they move to get out of check, otherwise error */
        $currentTurn = $game->getTurn();
        if ($game->isCheck($currentTurn)) {
            $toast = "You must escape Check";
        }
        /* We also need to make sure they don't put themselves in check */
        else {
            $toast = "You cannot enter Check";
        }

        /* Make the proposed move */
        $game->getBoard()->makeMove($move);

        /* See if the move they made put them in check, if so undo move and send error */
        if ($game->isCheck($currentTurn)) {
            $game->getBoard()->undoMove($move);
            return $client->send(json_encode([
                ['type' => 'alert', 'params' => [
                    'type' => 'toast',
                    'message' => $toast,
                ]],
                ['type' => 'invalidMove'],
            ]));
        }

        /* They weren't in check, nor did they put themselves in check. But they have put the other player in check */
        if ($game->isCheck($game->getTurn())) {
            if (!$game->isCheckMate($game->getTurn())) {
                $client->send(json_encode([
                    ['type' => 'alert', 'params' => [
                        'type' => 'toast',
                        'message' => 'Check!',
                    ]]
                ]));
            }
            else {
                $client->send(json_encode([
                    ['type' => 'alert', 'params' => [
                        'type' => 'toast',
                        'message' => 'Checkmate!',
                    ]]
                ]));
            }
        }

        if ($game->getTurn() == Piece::WHITE) {
            $toast = "White's turn";
        }
        else {
            $toast = "Black's turn";
        }

        $gameModel->save();

        return $client->send(json_encode([
            ['type' => 'alert', 'params' => [
                'type' => 'toast',
                'message' => $toast,
            ]],
            ['type' => 'setGame', 'params' => [
                'id' => $gameModel->id,
                'turn' => $game->getTurn()
            ]]
        ]));
    }

    /**
     * Convert a json move to a Move object
     * @param $jsMove
     * @return Move
     */
    public function moveToPhp($jsMove)
    {
        if ($jsMove->to->piece) {
            return new Move(
                new Square(
                    $jsMove->from->x - 1,
                    $jsMove->from->y - 1,
                    Piece::fromString(json_encode($jsMove->from->piece))
                ),
                new Square(
                    $jsMove->to->x - 1,
                    $jsMove->to->y - 1,
                    Piece::fromString(json_encode($jsMove->to->piece))
                )
            );
        }
        else {
            return new Move(
                new Square(
                    $jsMove->from->x - 1,
                    $jsMove->from->y - 1,
                    Piece::fromString(json_encode($jsMove->from->piece))
                ),
                new Square(
                    $jsMove->to->x - 1,
                    $jsMove->to->y - 1
                )
            );
        }
    }

    /**
     * Get the available moves to a piece on the board
     * @param ConnectionInterface $client
     * @param $params
     * @return bool|string
     */
    public function getMoves(ConnectionInterface $client, $params)
    {
        /* Make sure the client has a game */
        if (!($gameModel = $this->getGameModel($client, $params))) {
            return false;
        }
        $game = $gameModel->game;
        $moves = $game->getBoard()->getMoves($params->location->x - 1, $params->location->y - 1);

        $toLocations = [];
        if ($moves) {
            /** @var Move $move */
            foreach ($moves as $move) {
                $toLocations[] = ['x' => $move->getTo()->getX() + 1, 'y' => $move->getTo()->getY() + 1];
            }
        }

        $client->send(json_encode([[
            'type' => 'highlightSquares',
            'params' => $toLocations
        ]]));
    }
}


text:
/**
Author: MI
Description: Collection of all Clients specifying the model
Used in: Clients Controller
*/
define([
  'backbone',
  'ag/m/client',  // defining the model to be used to populate the collection
  'backbone.pageable'

], function(Backbone, Model) {
  'use strict';

  return Backbone.PageableCollection.extend({
    mode: 'client',
    state: {
      pageSize: 5, // Items per page
      sortKey: 'Name',
      order: -1
    },
    url: 'a/cli/ent',
    model: Model
  });
});


text:
package com.cloudray.scalapress.media

import java.io.InputStream

/** @author Stephen Samuel */
trait AssetLifecycleListener {
  def onStore(key: String, input: InputStream): (String, InputStream)
  def onDelete(key: String): Boolean = true
}


text:
/**
 * Container for a track
 *
 * @author ab
 */
package btools.router;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import btools.mapaccess.MatchedWaypoint;
import btools.mapaccess.OsmPos;
import btools.util.CompactLongMap;
import btools.util.FrozenLongMap;
import btools.util.StringUtils;

public final class OsmTrack {
  final public static String version = "1.6.3";
  final public static String versionDate = "21122021";

  // csv-header-line
  private static final String MESSAGES_HEADER = "Longitude\tLatitude\tElevation\tDistance\tCostPerKm\tElevCost\tTurnCost\tNodeCost\tInitialCost\tWayTags\tNodeTags\tTime\tEnergy";

  public MatchedWaypoint endPoint;
  public long[] nogoChecksums;
  public long profileTimestamp;
  public boolean isDirty;

  public boolean showspeed;
  public boolean showSpeedProfile;

  public List<OsmNodeNamed> pois = new ArrayList<OsmNodeNamed>();

  private static class OsmPathElementHolder {
    public OsmPathElement node;
    public OsmPathElementHolder nextHolder;
  }

  public List<OsmPathElement> nodes = new ArrayList<OsmPathElement>();

  private CompactLongMap<OsmPathElementHolder> nodesMap;

  private CompactLongMap<OsmPathElementHolder> detourMap;

  private VoiceHintList voiceHints;

  public String message = null;
  public List<String> messageList = null;

  public String name = "unset";

  protected List<MatchedWaypoint> matchedWaypoints;
  public boolean exportWaypoints = false;

  public void addNode(OsmPathElement node) {
    nodes.add(0, node);
  }

  public void registerDetourForId(long id, OsmPathElement detour) {
    if (detourMap == null) {
      detourMap = new CompactLongMap<OsmPathElementHolder>();
    }
    OsmPathElementHolder nh = new OsmPathElementHolder();
    nh.node = detour;
    OsmPathElementHolder h = detourMap.get(id);
    if (h != null) {
      while (h.nextHolder != null) {
        h = h.nextHolder;
      }
      h.nextHolder = nh;
    } else {
      detourMap.fastPut(id, nh);
    }
  }

  public void copyDetours(OsmTrack source) {
    detourMap = source.detourMap == null ? null : new FrozenLongMap<OsmPathElementHolder>(source.detourMap);
  }

  public void buildMap() {
    nodesMap = new CompactLongMap<OsmPathElementHolder>();
    for (OsmPathElement node : nodes) {
      long id = node.getIdFromPos();
      OsmPathElementHolder nh = new OsmPathElementHolder();
      nh.node = node;
      OsmPathElementHolder h = nodesMap.get(id);
      if (h != null) {
        while (h.nextHolder != null) {
          h = h.nextHolder;
        }
        h.nextHolder = nh;
      } else {
        nodesMap.fastPut(id, nh);
      }
    }
    nodesMap = new FrozenLongMap<OsmPathElementHolder>(nodesMap);
  }

  private List<String> aggregateMessages() {
    ArrayList<String> res = new ArrayList<String>();
    MessageData current = null;
    for (OsmPathElement n : nodes) {
      if (n.message != null && n.message.wayKeyValues != null) {
        MessageData md = n.message.copy();
        if (current != null) {
          if (current.nodeKeyValues != null || !current.wayKeyValues.equals(md.wayKeyValues)) {
            res.add(current.toMessage());
          } else {
            md.add(current);
          }
        }
        current = md;
      }
    }
    if (current != null) {
      res.add(current.toMessage());
    }
    return res;
  }

  private List<String> aggregateSpeedProfile() {
    ArrayList<String> res = new ArrayList<String>();
    int vmax = -1;
    int vmaxe = -1;
    int vmin = -1;
    int extraTime = 0;
    for (int i = nodes.size() - 1; i > 0; i--) {
      OsmPathElement n = nodes.get(i);
      MessageData m = n.message;
      int vnode = getVNode(i);
      if (m != null && (vmax != m.vmax || vmin != m.vmin || vmaxe != m.vmaxExplicit || vnode < m.vmax || extraTime != m.extraTime)) {
        vmax = m.vmax;
        vmin = m.vmin;
        vmaxe = m.vmaxExplicit;
        extraTime = m.extraTime;
        res.add(i + "," + vmaxe + "," + vmax + "," + vmin + "," + vnode + "," + extraTime);
      }
    }
    return res;
  }

  /**
   * writes the track in binary-format to a file
   *
   * @param filename the filename to write to
   */
  public void writeBinary(String filename) throws Exception {
    DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));

    endPoint.writeToStream(dos);
    dos.writeInt(nodes.size());
    for (OsmPathElement node : nodes) {
      node.writeToStream(dos);
    }
    dos.writeLong(nogoChecksums[0]);
    dos.writeLong(nogoChecksums[1]);
    dos.writeLong(nogoChecksums[2]);
    dos.writeBoolean(isDirty);
    dos.writeLong(profileTimestamp);
    dos.close();
  }

  public static OsmTrack readBinary(String filename, OsmNodeNamed newEp, long[] nogoChecksums, long profileChecksum, StringBuilder debugInfo) {
    OsmTrack t = null;
    if (filename != null) {
      File f = new File(filename);
      if (f.exists()) {
        try {
          DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(f)));
          MatchedWaypoint ep = MatchedWaypoint.readFromStream(dis);
          int dlon = ep.waypoint.ilon - newEp.ilon;
          int dlat = ep.waypoint.ilat - newEp.ilat;
          boolean targetMatch = dlon < 20 && dlon > -20 && dlat < 20 && dlat > -20;
          if (debugInfo != null) {
            debugInfo.append("target-delta = " + dlon + "/" + dlat + " targetMatch=" + targetMatch);
          }
          if (targetMatch) {
            t = new OsmTrack();
            t.endPoint = ep;
            int n = dis.readInt();
            OsmPathElement last_pe = null;
            for (int i = 0; i < n; i++) {
              OsmPathElement pe = OsmPathElement.readFromStream(dis);
              pe.origin = last_pe;
              last_pe = pe;
              t.nodes.add(pe);
            }
            t.cost = last_pe.cost;
            t.buildMap();

            // check cheecksums, too
            long[] al = new long[3];
            long pchecksum = 0;
            try {
              al[0] = dis.readLong();
              al[1] = dis.readLong();
              al[2] = dis.readLong();
            } catch (EOFException eof) { /* kind of expected */ }
            try {
              t.isDirty = dis.readBoolean();
            } catch (EOFException eof) { /* kind of expected */ }
            try {
              pchecksum = dis.readLong();
            } catch (EOFException eof) { /* kind of expected */ }
            boolean nogoCheckOk = Math.abs(al[0] - nogoChecksums[0]) <= 20
              && Math.abs(al[1] - nogoChecksums[1]) <= 20
              && Math.abs(al[2] - nogoChecksums[2]) <= 20;
            boolean profileCheckOk = pchecksum == profileChecksum;

            if (debugInfo != null) {
              debugInfo.append(" nogoCheckOk=" + nogoCheckOk + " profileCheckOk=" + profileCheckOk);
              debugInfo.append(" al=" + formatLongs(al) + " nogoChecksums=" + formatLongs(nogoChecksums));
            }
            if (!(nogoCheckOk && profileCheckOk)) return null;
          }
          dis.close();
        } catch (Exception e) {
          throw new RuntimeException("Exception reading rawTrack: " + e);
        }
      }
    }
    return t;
  }

  private static String formatLongs(long[] al) {
    StringBuilder sb = new StringBuilder();
    sb.append('{');
    for (long l : al) {
      sb.append(l);
      sb.append(' ');
    }
    sb.append('}');
    return sb.toString();
  }

  public void addNodes(OsmTrack t) {
    for (OsmPathElement n : t.nodes)
      addNode(n);
    buildMap();
  }

  public boolean containsNode(OsmPos node) {
    return nodesMap.contains(node.getIdFromPos());
  }

  public OsmPathElement getLink(long n1, long n2) {
    OsmPathElementHolder h = nodesMap.get(n2);
    while (h != null) {
      OsmPathElement e1 = h.node.origin;
      if (e1 != null && e1.getIdFromPos() == n1) {
        return h.node;
      }
      h = h.nextHolder;
    }
    return null;
  }

  public void appendTrack(OsmTrack t) {
    int ourSize = nodes.size();
    float t0 = ourSize > 0 ? nodes.get(ourSize - 1).getTime() : 0;
    float e0 = ourSize > 0 ? nodes.get(ourSize - 1).getEnergy() : 0;
    for (int i = 0; i < t.nodes.size(); i++) {
      if (i > 0 || ourSize == 0) {
        OsmPathElement e = t.nodes.get(i);
        e.setTime(e.getTime() + t0);
        e.setEnergy(e.getEnergy() + e0);
        nodes.add(e);
      }
    }

    if (t.voiceHints != null) {
      if (ourSize > 0) {
        for (VoiceHint hint : t.voiceHints.list) {
          hint.indexInTrack = hint.indexInTrack + ourSize - 1;
        }
      }
      if (voiceHints == null) {
        voiceHints = t.voiceHints;
      } else {
        voiceHints.list.addAll(t.voiceHints.list);
      }
    }

    distance += t.distance;
    ascend += t.ascend;
    plainAscend += t.plainAscend;
    cost += t.cost;
    energy += t.energy;

    showspeed |= t.showspeed;
    showSpeedProfile |= t.showSpeedProfile;
  }

  public int distance;
  public int ascend;
  public int plainAscend;
  public int cost;
  public int energy;

  /**
   * writes the track in gpx-format to a file
   *
   * @param filename the filename to write to
   */
  public void writeGpx(String filename) throws Exception {
    BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
    formatAsGpx(bw);
    bw.close();
  }

  public String formatAsGpx() {
    try {
      StringWriter sw = new StringWriter(8192);
      BufferedWriter bw = new BufferedWriter(sw);
      formatAsGpx(bw);
      bw.close();
      return sw.toString();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public String formatAsGpx(BufferedWriter sb) throws IOException {
    int turnInstructionMode = voiceHints != null ? voiceHints.turnInstructionMode : 0;

    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    for (int i = messageList.size() - 1; i >= 0; i--) {
      String message = messageList.get(i);
      if (i < messageList.size() - 1)
        message = "(alt-index " + i + ": " + message + " )";
      if (message != null)
        sb.append("<!-- ").append(message).append(" -->\n");
    }

    if (turnInstructionMode == 4) // comment style
    {
      sb.append("<!-- $transport-mode$").append(voiceHints.getTransportMode()).append("$ -->\n");
      sb.append("<!--          cmd    idx        lon        lat d2next  geometry -->\n");
      sb.append("<!-- $turn-instruction-start$\n");
      for (VoiceHint hint : voiceHints.list) {
        sb.append(String.format("     $turn$%6s;%6d;%10s;%10s;%6d;%s$\n", hint.getCommandString(), hint.indexInTrack,
          formatILon(hint.ilon), formatILat(hint.ilat), (int) (hint.distanceToNext), hint.formatGeometry()));
      }
      sb.append("    $turn-instruction-end$ -->\n");
    }
    sb.append("<gpx \n");
    sb.append(" xmlns=\"http://www.topografix.com/GPX/1/1\" \n");
    sb.append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n");
    if (turnInstructionMode == 2) // locus style
    {
      sb.append(" xmlns:locus=\"http://www.locusmap.eu\" \n");
    }
    sb.append(" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\" \n");

    if (turnInstructionMode == 3) {
      sb.append(" creator=\"OsmAndRouter\" version=\"1.1\">\n");
    } else {
      sb.append(" creator=\"BRouter-" + version + "\" version=\"1.1\">\n");
    }

    if (turnInstructionMode == 3) // osmand style
    {
      float lastRteTime = 0;

      sb.append(" <rte>\n");

      sb.append("  <rtept lat=\"").append(formatILat(nodes.get(0).getILat())).append("\" lon=\"")
        .append(formatILon(nodes.get(0).getILon())).append("\">\n")
        .append("   <desc>start</desc>\n   <extensions>\n");

      float rteTime = getVoiceHintTime(0);

      if (rteTime != lastRteTime) // add timing only if available
      {
        double t = rteTime - lastRteTime;
        sb.append("    <time>").append("" + (int) (t + 0.5)).append("</time>\n");
        lastRteTime = rteTime;
      }
      sb.append("    <offset>0</offset>\n  </extensions>\n </rtept>\n");

      for (int i = 0; i < voiceHints.list.size(); i++) {
        VoiceHint hint = voiceHints.list.get(i);
        sb.append("  <rtept lat=\"").append(formatILat(hint.ilat)).append("\" lon=\"")
          .append(formatILon(hint.ilon)).append("\">\n")
          .append("   <desc>").append(hint.getMessageString()).append("</desc>\n   <extensions>\n");

        rteTime = getVoiceHintTime(i + 1);

        if (rteTime != lastRteTime) // add timing only if available
        {
          double t = rteTime - lastRteTime;
          sb.append("    <time>").append("" + (int) (t + 0.5)).append("</time>\n");
          lastRteTime = rteTime;
        }
        sb.append("    <turn>").append(hint.getCommandString()).append("</turn>\n    <turn-angle>").append("" + (int) hint.angle)
          .append("</turn-angle>\n    <offset>").append("" + hint.indexInTrack).append("</offset>\n  </extensions>\n </rtept>\n");
      }
      sb.append("  <rtept lat=\"").append(formatILat(nodes.get(nodes.size() - 1).getILat())).append("\" lon=\"")
        .append(formatILon(nodes.get(nodes.size() - 1).getILon())).append("\">\n")
        .append("   <desc>destination</desc>\n   <extensions>\n");
      sb.append("    <time>0</time>\n");
      sb.append("    <offset>").append("" + (nodes.size() - 1)).append("</offset>\n  </extensions>\n </rtept>\n");

      sb.append("</rte>\n");
    }

    if (turnInstructionMode == 2) // locus style
    {
      float lastRteTime = getVoiceHintTime(0);

      for (int i = 0; i < voiceHints.list.size(); i++) {
        VoiceHint hint = voiceHints.list.get(i);
        sb.append(" <wpt lon=\"").append(formatILon(hint.ilon)).append("\" lat=\"")
          .append(formatILat(hint.ilat)).append("\">")
          .append(hint.selev == Short.MIN_VALUE ? "" : "<ele>" + (hint.selev / 4.) + "</ele>")
          .append("<name>").append(hint.getMessageString()).append("</name>")
          .append("<extensions><locus:rteDistance>").append("" + hint.distanceToNext).append("</locus:rteDistance>");
        float rteTime = getVoiceHintTime(i + 1);
        if (rteTime != lastRteTime) // add timing only if available
        {
          double t = rteTime - lastRteTime;
          double speed = hint.distanceToNext / t;
          sb.append("<locus:rteTime>").append("" + t).append("</locus:rteTime>")
            .append("<locus:rteSpeed>").append("" + speed).append("</locus:rteSpeed>");
          lastRteTime = rteTime;
        }
        sb.append("<locus:rtePointAction>").append("" + hint.getLocusAction()).append("</locus:rtePointAction></extensions>")
          .append("</wpt>\n");
      }
    }
    if (turnInstructionMode == 5) // gpsies style
    {
      for (VoiceHint hint : voiceHints.list) {
        sb.append(" <wpt lon=\"").append(formatILon(hint.ilon)).append("\" lat=\"")
          .append(formatILat(hint.ilat)).append("\">")
          .append("<name>").append(hint.getMessageString()).append("</name>")
          .append("<sym>").append(hint.getSymbolString().toLowerCase()).append("</sym>")
          .append("<type>").append(hint.getSymbolString()).append("</type>")
          .append("</wpt>\n");
      }
    }

    if (turnInstructionMode == 6) // orux style
    {
      for (VoiceHint hint : voiceHints.list) {
        sb.append(" <wpt lat=\"").append(formatILat(hint.ilat)).append("\" lon=\"")
          .append(formatILon(hint.ilon)).append("\">")
          .append(hint.selev == Short.MIN_VALUE ? "" : "<ele>" + (hint.selev / 4.) + "</ele>")
          .append("<extensions>\n" +
            "<om:oruxmapsextensions xmlns:om=\"http://www.oruxmaps.com/oruxmapsextensions/1/0\">\n" +
            "<om:ext type=\"ICON\" subtype=\"0\">").append("" + hint.getOruxAction())
          .append("</om:ext>\n" +
            "</om:oruxmapsextensions>\n" +
            "</extensions>\n" +
            "</wpt>");
      }
    }

    for (int i = 0; i <= pois.size() - 1; i++) {
      OsmNodeNamed poi = pois.get(i);
      sb.append(" <wpt lon=\"").append(formatILon(poi.ilon)).append("\" lat=\"")
        .append(formatILat(poi.ilat)).append("\">\n")
        .append("  <name>").append(StringUtils.escapeXml10(poi.name)).append("</name>\n")
        .append(" </wpt>\n");
    }

    if (exportWaypoints) {
      for (int i = 0; i <= matchedWaypoints.size() - 1; i++) {
        MatchedWaypoint wt = matchedWaypoints.get(i);
        sb.append(" <wpt lon=\"").append(formatILon(wt.waypoint.ilon)).append("\" lat=\"")
          .append(formatILat(wt.waypoint.ilat)).append("\">\n")
          .append("  <name>").append(StringUtils.escapeXml10(wt.name)).append("</name>\n");
        if (i == 0) {
          sb.append("  <type>from</type>\n");
        } else if (i == matchedWaypoints.size() - 1) {
          sb.append("  <type>to</type>\n");
        } else {
          sb.append("  <type>via</type>\n");
        }
        sb.append(" </wpt>\n");
      }
    }
    sb.append(" <trk>\n");
    sb.append("  <name>").append(name).append("</name>\n");
    if (turnInstructionMode == 1) // trkpt/sym style
    {
      sb.append("  <type>").append(voiceHints.getTransportMode()).append("</type>\n");
    }

    if (turnInstructionMode == 2) {
      sb.append("  <extensions>\n");
      sb.append("   <locus:rteComputeType>").append("" + voiceHints.getLocusRouteType()).append("</locus:rteComputeType>\n");
      sb.append("   <locus:rteSimpleRoundabouts>1</locus:rteSimpleRoundabouts>\n");
      sb.append("  </extensions>\n");
    }

    sb.append("  <trkseg>\n");

    for (int idx = 0; idx < nodes.size(); idx++) {
      OsmPathElement n = nodes.get(idx);
      String sele = n.getSElev() == Short.MIN_VALUE ? "" : "<ele>" + n.getElev() + "</ele>";
      if (turnInstructionMode == 1) // trkpt/sym style
      {
        for (VoiceHint hint : voiceHints.list) {
          if (hint.indexInTrack == idx) {
            sele += "<sym>" + hint.getCommandString() + "</sym>";
          }
        }
      }
      sb.append("   <trkpt lon=\"").append(formatILon(n.getILon())).append("\" lat=\"")
        .append(formatILat(n.getILat())).append("\">").append(sele).append("</trkpt>\n");
    }

    sb.append("  </trkseg>\n");
    sb.append(" </trk>\n");
    sb.append("</gpx>\n");

    return sb.toString();
  }

  public void writeKml(String filename) throws Exception {
    BufferedWriter bw = new BufferedWriter(new FileWriter(filename));

    bw.write(formatAsKml());
    bw.close();
  }

  public String formatAsKml() {
    StringBuilder sb = new StringBuilder(8192);

    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");

    sb.append("<kml xmlns=\"http://earth.google.com/kml/2.0\">\n");
    sb.append("  <Document>\n");
    sb.append("    <name>KML Samples</name>\n");
    sb.append("    <open>1</open>\n");
    sb.append("    <distance>3.497064</distance>\n");
    sb.append("    <traveltime>872</traveltime>\n");
    sb.append("    <description>To enable simple instructions add: 'instructions=1' as parameter to the URL</description>\n");
    sb.append("    <Folder>\n");
    sb.append("      <name>Paths</name>\n");
    sb.append("      <visibility>0</visibility>\n");
    sb.append("      <description>Examples of paths.</description>\n");
    sb.append("      <Placemark>\n");
    sb.append("        <name>Tessellated</name>\n");
    sb.append("        <visibility>0</visibility>\n");
    sb.append("        <description><![CDATA[If the <tessellate> tag has a value of 1, the line will contour to the underlying terrain]]></description>\n");
    sb.append("        <LineString>\n");
    sb.append("          <tessellate>1</tessellate>\n");
    sb.append("         <coordinates>");

    for (OsmPathElement n : nodes) {
      sb.append(formatILon(n.getILon())).append(",").append(formatILat(n.getILat())).append("\n");
    }

    sb.append("          </coordinates>\n");
    sb.append("        </LineString>\n");
    sb.append("      </Placemark>\n");
    sb.append("    </Folder>\n");
    if (exportWaypoints || !pois.isEmpty()) {
      if (!pois.isEmpty()) {
        sb.append("    <Folder>\n");
        sb.append("      <name>poi</name>\n");
        for (int i = 0; i < pois.size(); i++) {
          OsmNodeNamed poi = pois.get(i);
          createPlaceMark(sb, poi.name, poi.ilat, poi.ilon);
        }
        sb.append("    </Folder>\n");
      }

      if (exportWaypoints) {
        int size = matchedWaypoints.size();
        createFolder(sb, "start", matchedWaypoints.subList(0, 1));
        if (matchedWaypoints.size() > 2) {
          createFolder(sb, "via", matchedWaypoints.subList(1, size - 1));
        }
        createFolder(sb, "end", matchedWaypoints.subList(size - 1, size));
      }
    }
    sb.append("  </Document>\n");
    sb.append("</kml>\n");

    return sb.toString();
  }

  private void createFolder(StringBuilder sb, String type, List<MatchedWaypoint> waypoints) {
    sb.append("    <Folder>\n");
    sb.append("      <name>" + type + "</name>\n");
    for (int i = 0; i < waypoints.size(); i++) {
      MatchedWaypoint wp = waypoints.get(i);
      createPlaceMark(sb, wp.name, wp.waypoint.ilat, wp.waypoint.ilon);
    }
    sb.append("    </Folder>\n");
  }

  private void createPlaceMark(StringBuilder sb, String name, int ilat, int ilon) {
    sb.append("      <Placemark>\n");
    sb.append("        <name>" + StringUtils.escapeXml10(name) + "</name>\n");
    sb.append("        <Point>\n");
    sb.append("         <coordinates>" + formatILon(ilon) + "," + formatILat(ilat) + "</coordinates>\n");
    sb.append("        </Point>\n");
    sb.append("      </Placemark>\n");
  }

  public List<String> iternity;

  public void writeJson(String filename) throws Exception {
    BufferedWriter bw = new BufferedWriter(new FileWriter(filename));

    bw.write(formatAsGeoJson());
    bw.close();
  }

  public String formatAsGeoJson() {
    int turnInstructionMode = voiceHints != null ? voiceHints.turnInstructionMode : 0;

    StringBuilder sb = new StringBuilder(8192);

    sb.append("{\n");
    sb.append("  \"type\": \"FeatureCollection\",\n");
    sb.append("  \"features\": [\n");
    sb.append("    {\n");
    sb.append("      \"type\": \"Feature\",\n");
    sb.append("      \"properties\": {\n");
    sb.append("        \"creator\": \"BRouter-" + version + "\",\n");
    sb.append("        \"name\": \"").append(name).append("\",\n");
    sb.append("        \"track-length\": \"").append(distance).append("\",\n");
    sb.append("        \"filtered ascend\": \"").append(ascend).append("\",\n");
    sb.append("        \"plain-ascend\": \"").append(plainAscend).append("\",\n");
    sb.append("        \"total-time\": \"").append(getTotalSeconds()).append("\",\n");
    sb.append("        \"total-energy\": \"").append(energy).append("\",\n");
    sb.append("        \"cost\": \"").append(cost).append("\",\n");
    if (voiceHints != null && !voiceHints.list.isEmpty()) {
      sb.append("        \"voicehints\": [\n");
      for (VoiceHint hint : voiceHints.list) {
        sb.append("          [");
        sb.append(hint.indexInTrack);
        sb.append(',').append(hint.getCommand());
        sb.append(',').append(hint.getExitNumber());
        sb.append(',').append(hint.distanceToNext);
        sb.append(',').append((int) hint.angle);

        // not always include geometry because longer and only needed for comment style
        if (turnInstructionMode == 4) // comment style
        {
          sb.append(",\"").append(hint.formatGeometry()).append("\"");
        }

        sb.append("],\n");
      }
      sb.deleteCharAt(sb.lastIndexOf(","));
      sb.append("        ],\n");
    }
    if (showSpeedProfile) // set in profile
    {
      List<String> sp = aggregateSpeedProfile();
      if (sp.size() > 0) {
        sb.append("        \"speedprofile\": [\n");
        for (int i = sp.size() - 1; i >= 0; i--) {
          sb.append("          [").append(sp.get(i)).append(i > 0 ? "],\n" : "]\n");
        }
        sb.append("        ],\n");
      }
    }
    //  ... traditional message list
    {
      sb.append("        \"messages\": [\n");
      sb.append("          [\"").append(MESSAGES_HEADER.replaceAll("\t", "\", \"")).append("\"],\n");
      for (String m : aggregateMessages()) {
        sb.append("          [\"").append(m.replaceAll("\t", "\", \"")).append("\"],\n");
      }
      sb.deleteCharAt(sb.lastIndexOf(","));
      sb.append("        ],\n");
    }

    if (getTotalSeconds() > 0) {
      sb.append("        \"times\": [");
      DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH);
      decimalFormat.applyPattern("0.###");
      for (OsmPathElement n : nodes) {
        sb.append(decimalFormat.format(n.getTime())).append(",");
      }
      sb.deleteCharAt(sb.lastIndexOf(","));
      sb.append("]\n");
    } else {
      sb.deleteCharAt(sb.lastIndexOf(","));
    }

    sb.append("      },\n");

    if (iternity != null) {
      sb.append("      \"iternity\": [\n");
      for (String s : iternity) {
        sb.append("        \"").append(s).append("\",\n");
      }
      sb.deleteCharAt(sb.lastIndexOf(","));
      sb.append("        ],\n");
    }
    sb.append("      \"geometry\": {\n");
    sb.append("        \"type\": \"LineString\",\n");
    sb.append("        \"coordinates\": [\n");

    OsmPathElement nn = null;
    for (OsmPathElement n : nodes) {
      String sele = n.getSElev() == Short.MIN_VALUE ? "" : ", " + n.getElev();
      if (showspeed) // hack: show speed instead of elevation
      {
        double speed = 0;
        if (nn != null) {
          int dist = n.calcDistance(nn);
          float dt = n.getTime() - nn.getTime();
          if (dt != 0.f) {
            speed = ((3.6f * dist) / dt + 0.5);
          }
        }
        sele = ", " + (((int) (speed * 10)) / 10.f);
      }
      sb.append("          [").append(formatILon(n.getILon())).append(", ").append(formatILat(n.getILat()))
        .append(sele).append("],\n");
      nn = n;
    }
    sb.deleteCharAt(sb.lastIndexOf(","));

    sb.append("        ]\n");
    sb.append("      }\n");
    if (exportWaypoints || !pois.isEmpty()) {
      sb.append("    },\n");
      for (int i = 0; i <= pois.size() - 1; i++) {
        OsmNodeNamed poi = pois.get(i);
        addFeature(sb, "poi", poi.name, poi.ilat, poi.ilon);
        if (i < matchedWaypoints.size() - 1) {
          sb.append(",");
        }
        sb.append("    \n");
      }
      if (exportWaypoints) {
        for (int i = 0; i <= matchedWaypoints.size() - 1; i++) {
          String type;
          if (i == 0) {
            type = "from";
          } else if (i == matchedWaypoints.size() - 1) {
            type = "to";
          } else {
            type = "via";
          }

          MatchedWaypoint wp = matchedWaypoints.get(i);
          addFeature(sb, type, wp.name, wp.waypoint.ilat, wp.waypoint.ilon);
          if (i < matchedWaypoints.size() - 1) {
            sb.append(",");
          }
          sb.append("    \n");
        }
      }
    } else {
      sb.append("    }\n");
    }
    sb.append("  ]\n");
    sb.append("}\n");

    return sb.toString();
  }

  private void addFeature(StringBuilder sb, String type, String name, int ilat, int ilon) {
    sb.append("    {\n");
    sb.append("      \"type\": \"Feature\",\n");
    sb.append("      \"properties\": {\n");
    sb.append("        \"name\": \"" + StringUtils.escapeJson(name) + "\",\n");
    sb.append("        \"type\": \"" + type + "\"\n");
    sb.append("      },\n");
    sb.append("      \"geometry\": {\n");
    sb.append("        \"type\": \"Point\",\n");
    sb.append("        \"coordinates\": [\n");
    sb.append("          " + formatILon(ilon) + ",\n");
    sb.append("          " + formatILat(ilat) + "\n");
    sb.append("        ]\n");
    sb.append("      }\n");
    sb.append("    }");
  }

  private int getVNode(int i) {
    MessageData m1 = i + 1 < nodes.size() ? nodes.get(i + 1).message : null;
    MessageData m0 = i < nodes.size() ? nodes.get(i).message : null;
    int vnode0 = m1 == null ? 999 : m1.vnode0;
    int vnode1 = m0 == null ? 999 : m0.vnode1;
    return vnode0 < vnode1 ? vnode0 : vnode1;
  }

  private int getTotalSeconds() {
    float s = nodes.size() < 2 ? 0 : nodes.get(nodes.size() - 1).getTime() - nodes.get(0).getTime();
    return (int) (s + 0.5);
  }

  public String getFormattedTime() {
    return format1(getTotalSeconds() / 60.) + "m";
  }

  public String getFormattedTime2() {
    int seconds = (int) (getTotalSeconds() + 0.5);
    int hours = seconds / 3600;
    int minutes = (seconds - hours * 3600) / 60;
    seconds = seconds - hours * 3600 - minutes * 60;
    String time = "";
    if (hours != 0)
      time = "" + hours + "h ";
    if (minutes != 0)
      time = time + minutes + "m ";
    if (seconds != 0)
      time = time + seconds + "s";
    return time;
  }

  public String getFormattedEnergy() {
    return format1(energy / 3600000.) + "kwh";
  }

  private static String formatILon(int ilon) {
    return formatPos(ilon - 180000000);
  }

  private static String formatILat(int ilat) {
    return formatPos(ilat - 90000000);
  }

  private static String formatPos(int p) {
    boolean negative = p < 0;
    if (negative)
      p = -p;
    char[] ac = new char[12];
    int i = 11;
    while (p != 0 || i > 3) {
      ac[i--] = (char) ('0' + (p % 10));
      p /= 10;
      if (i == 5)
        ac[i--] = '.';
    }
    if (negative)
      ac[i--] = '-';
    return new String(ac, i + 1, 11 - i);
  }

  private String format1(double n) {
    String s = "" + (long) (n * 10 + 0.5);
    int len = s.length();
    return s.substring(0, len - 1) + "." + s.charAt(len - 1);
  }

  public void dumpMessages(String filename, RoutingContext rc) throws Exception {
    BufferedWriter bw = filename == null ? null : new BufferedWriter(new FileWriter(filename));
    writeMessages(bw, rc);
  }

  public void writeMessages(BufferedWriter bw, RoutingContext rc) throws Exception {
    dumpLine(bw, MESSAGES_HEADER);
    for (String m : aggregateMessages()) {
      dumpLine(bw, m);
    }
    if (bw != null)
      bw.close();
  }

  private void dumpLine(BufferedWriter bw, String s) throws Exception {
    if (bw == null) {
      System.out.println(s);
    } else {
      bw.write(s);
      bw.write("\n");
    }
  }

  public void readGpx(String filename) throws Exception {
    File f = new File(filename);
    if (!f.exists())
      return;
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));

    for (; ; ) {
      String line = br.readLine();
      if (line == null)
        break;

      int idx0 = line.indexOf("<trkpt lon=\"");
      if (idx0 >= 0) {
        idx0 += 12;
        int idx1 = line.indexOf('"', idx0);
        int ilon = (int) ((Double.parseDouble(line.substring(idx0, idx1)) + 180.) * 1000000. + 0.5);
        int idx2 = line.indexOf(" lat=\"");
        if (idx2 < 0)
          continue;
        idx2 += 6;
        int idx3 = line.indexOf('"', idx2);
        int ilat = (int) ((Double.parseDouble(line.substring(idx2, idx3)) + 90.) * 1000000. + 0.5);
        nodes.add(OsmPathElement.create(ilon, ilat, (short) 0, null, false));
      }
    }
    br.close();
  }

  public boolean equalsTrack(OsmTrack t) {
    if (nodes.size() != t.nodes.size())
      return false;
    for (int i = 0; i < nodes.size(); i++) {
      OsmPathElement e1 = nodes.get(i);
      OsmPathElement e2 = t.nodes.get(i);
      if (e1.getILon() != e2.getILon() || e1.getILat() != e2.getILat())
        return false;
    }
    return true;
  }

  public void prepareSpeedProfile(RoutingContext rc) {
    // sendSpeedProfile = rc.keyValues != null && rc.keyValues.containsKey( "vmax" );
  }

  public void processVoiceHints(RoutingContext rc) {
    voiceHints = new VoiceHintList();
    voiceHints.setTransportMode(rc.carMode, rc.bikeMode);
    voiceHints.turnInstructionMode = rc.turnInstructionMode;

    if (detourMap == null) {
      return;
    }
    int nodeNr = nodes.size() - 1;
    OsmPathElement node = nodes.get(nodeNr);
    List<VoiceHint> inputs = new ArrayList<VoiceHint>();
    while (node != null) {
      if (node.origin != null) {
        VoiceHint input = new VoiceHint();
        inputs.add(input);
        input.ilat = node.origin.getILat();
        input.ilon = node.origin.getILon();
        input.selev = node.origin.getSElev();
        input.indexInTrack = --nodeNr;
        input.goodWay = node.message;
        input.oldWay = node.origin.message == null ? node.message : node.origin.message;

        OsmPathElementHolder detours = detourMap.get(node.origin.getIdFromPos());
        if (detours != null) {
          OsmPathElementHolder h = detours;
          while (h != null) {
            OsmPathElement e = h.node;
            input.addBadWay(startSection(e, node.origin));
            h = h.nextHolder;
          }
        }
      }
      node = node.origin;
    }

    VoiceHintProcessor vproc = new VoiceHintProcessor(rc.turnInstructionCatchingRange, rc.turnInstructionRoundabouts);
    List<VoiceHint> results = vproc.process(inputs);
    for (VoiceHint hint : results) {
      voiceHints.list.add(hint);
    }
  }

  private float getVoiceHintTime(int i) {
    if (voiceHints.list.isEmpty()) {
      return 0f;
    }
    if (i < voiceHints.list.size()) {
      return voiceHints.list.get(i).getTime();
    }
    if (nodes.isEmpty()) {
      return 0f;
    }
    return nodes.get(nodes.size() - 1).getTime();
  }

  private MessageData startSection(OsmPathElement element, OsmPathElement root) {
    OsmPathElement e = element;
    int cnt = 0;
    while (e != null && e.origin != null) {
      if (e.origin.getILat() == root.getILat() && e.origin.getILon() == root.getILon()) {
        return e.message;
      }
      e = e.origin;
      if (cnt++ == 1000000) {
        throw new IllegalArgumentException("ups: " + root + "->" + element);
      }
    }
    return null;
  }
}


text:
/**
 * Contains data model for package txml.database.
 * Only for inner use TXml library.
 *
 */
package txml.database.model;


text:
Neste projeto está sendo utilizado as seguintes tecnologias/linguagens:

* ASP.NET MVC: documentação disponível em https://www.asp.net/mvc;
* C#: disponível em https://docs.microsoft.com/pt-br/dotnet/csharp/csharp;
* HTML5: documentação disponível em https://www.w3schools.com/html/html5_intro.asp;
* Framework Bootstrap: download e documentação disponíveis em http://getbootstrap.com/;
* CSS3: documentação disponível em https://www.w3schools.com/css/default.asp;
* Javascript: documentação disponível em https://www.w3schools.com/js/default.asp;
* MYSQL: download e documentação disponíveis em https://www.mysql.com/.

# Instalação

Execução no visual studio:

1 - Clone o projeto https://github.com/ThamiresMancilio/TCC.git

2 - Execute o script de banco de dados que consta na pasta raíz do projeto (sysagropec.sql)

3 - Abra a solução (arquivo .sln), encontrado na pasta SysAgropec.


text:
require("iuplua")
require("iupluaimglib")

--********************************** Utilities *****************************************

function str_find(str, str_to_find, casesensitive, start)
  if (not casesensitive) then
    return str_find(string.lower(str), string.lower(str_to_find), true, start)
  end

  return string.find(str, str_to_find, start, true)
end

function read_file(filename)
  local ifile = io.open(filename, "r")
  if (not ifile) then
    iup.Message("Error", "Can't open file: " .. filename)
    return nil
  end

  local str = ifile:read("*a")
  if (not str) then
    iup.Message("Error", "Fail when reading from file: " .. filename)
    return nil
  end

  ifile:close()
  return str
end

function write_file(filename, str)
  local ifile = io.open(filename, "w")
  if (not ifile) then
    iup.Message("Error", "Can't open file: " .. filename)
    return false
  end

  if (not ifile:write(str)) then
    iup.Message("Error", "Fail when writing to file: " .. filename)
  end

  ifile:close()
  return true
end

--********************************** Main (Part 1/2) *****************************************

config = iup.config{}
config.app_name = "simple_notepad"
config:Load()

lbl_statusbar = iup.label{title = "Lin 1, Col 1", expand = "HORIZONTAL", padding = "10x5"}

multitext = iup.text{
  multiline = "YES",
  expand = "YES"
}

font = config:GetVariable("MainWindow", "Font")
if (font) then
  multitext.font = font
end

item_open = iup.item{title = "&Open...\tCtrl+O"}
item_saveas = iup.item{title="Save &As...\tCtrl+S"}
item_font = iup.item{title="&Font..."}
item_about = iup.item{title="&About..."}
item_find = iup.item{title="&Find...\tCtrl+F"}
item_goto = iup.item{title="&Go To..."}
item_exit = iup.item{title="E&xit"}

--********************************** Callbacks *****************************************

function config:recent_cb()
  local filename = self.title
  local str = read_file(filename)
  if (str) then
    multitext.value = str
  end
end

function multitext:caret_cb(lin, col)
  lbl_statusbar.title = "Lin "..lin..", Col "..col
end

function item_open:action()
  local filedlg = iup.filedlg{
    dialogtype = "OPEN",
    filter = "*.txt",
    filterinfo = "Text Files",
    parentdialog=iup.GetDialog(self)
    }

  filedlg:popup(iup.CENTERPARENT, iup.CENTERPARENT)

  if (tonumber(filedlg.status) ~= -1) then
    local filename = filedlg.value
    local str = read_file(filename)
    if (str) then
      config:RecentUpdate(filename)
      multitext.value = str
    end
  end
  filedlg:destroy()
end

function item_saveas:action()
  local filedlg = iup.filedlg{
    dialogtype = "SAVE",
    filter = "*.txt",
    filterinfo = "Text Files",
    parentdialog=iup.GetDialog(self)
    }

  filedlg:popup(iup.CENTERPARENT, iup.CENTERPARENT)

  if (tonumber(filedlg.status) ~= -1) then
    local filename = filedlg.value
    if (write_file(filename, multitext.value)) then
      config:RecentUpdate(filename)
    end
  end
  filedlg:destroy()
end

function item_exit:action()
  config:DialogClosed(iup.GetDialog(self), "MainWindow")
  config:Save()
  config:destroy()
  return iup.CLOSE
end

function item_goto:action()
  local line_count = multitext.linecount
  local lbl_goto = iup.label{title = "Line Number [1-"..line_count.."]:"}
  local txt_goto = iup.text{mask = iup.MASK_UINT, visiblecolumns = 20} --unsigned integer numbers only

  local bt_goto_ok = iup.button{title = "OK", text_linecount = 0, padding = "10x2"}
  bt_goto_ok.text_linecount = line_count
  function bt_goto_ok:action()
    local line_count = tonumber(self.text_linecount)
    local line = tonumber(txt_goto.value)
    if (line < 1 or line >= line_count) then
      iup.Message("Error", "Invalid line number.")
      return
    end
    goto_dlg.status = 1
    return iup.CLOSE
  end

  local bt_goto_cancel = iup.button{title = "Cancel", padding = "10x2"}
  function bt_goto_cancel:action()
    goto_dlg.status = 0
    return iup.CLOSE
  end

  local box = iup.vbox{
    lbl_goto,
    txt_goto,
    iup.hbox{
      iup.fill{},
      bt_goto_ok,
      bt_goto_cancel,
      normalizesize="HORIZONTAL",
    },
    margin = "10x10",
    gap = "5",
  }
  goto_dlg = iup.dialog{
    box,
    title = "Go To Line",
    dialogframe = "Yes",
    defaultenter = bt_goto_ok,
    defaultesc = bt_goto_cancel,
    parentdialog = iup.GetDialog(self)
  }

  goto_dlg:popup(iup.CENTERPARENT, iup.CENTERPARENT)

  if (tonumber(goto_dlg.status) == 1) then
    local line = txt_goto.value
    local pos = iup.TextConvertLinColToPos(multitext, line, 0)
    multitext.caretpos = pos
    multitext.scrolltopos = pos
  end

  goto_dlg:destroy()
end

function item_find:action()
  local find_dlg = self.find_dialog
  if (not find_dlg) then
    local find_txt = iup.text{visiblecolumns = "20"}
    local find_case = iup.toggle{title = "Case Sensitive"}
    local bt_find_next = iup.button{title = "Find Next", padding = "10x2"}
    local bt_find_close = iup.button{title = "Close", padding = "10x2"}

    function bt_find_next:action()
      local find_pos = tonumber(find_dlg.find_pos)
      local str_to_find = find_txt.value

      local casesensitive = (find_case.value == "ON")

      -- test again, because it can be called from the hot key
      if (not str_to_find or str_to_find:len()==0) then
        return
      end

      if (not find_pos) then
        find_pos = 1
      end

      local str = multitext.value

      local pos, end_pos = str_find(str, str_to_find, casesensitive, find_pos)
      if (not pos) then
        pos, end_pos = str_find(str, str_to_find, casesensitive, 1)  -- try again from the start
      end

      if (pos) and (pos > 0) then
        pos = pos - 1
        find_dlg.find_pos = end_pos

        iup.SetFocus(multitext)
        multitext.selectionpos = pos..":"..end_pos

        local lin, col = iup.TextConvertPosToLinCol(multitext, pos)
        local pos = iup.TextConvertLinColToPos(multitext, lin, 0)  -- position at col=0, just scroll lines
        multitext.scrolltopos = pos
      else
        find_dlg.find_pos = nil
        iup.Message("Warning", "Text not found.")
      end
    end

    function bt_find_close:action()
      iup.Hide(iup.GetDialog(self))  -- do not destroy, just hide
    end

    box = iup.vbox{
      iup.label{title = "Find What:"},
      find_txt,
      find_case,
      iup.hbox{
        iup.fill{},
        bt_find_next,
        bt_find_close,
        normalizesize="HORIZONTAL",
      },
      margin = "10x10",
      gap = "5",
    }

    find_dlg = iup.dialog{
      box,
      title = "Find",
      dialogframe = "Yes",
      defaultenter = bt_next,
      defaultesc = bt_close,
      parentdialog = iup.GetDialog(self)
      }

    -- Save the dialog to reuse it
    self.find_dialog = find_dlg -- from the main dialog */
  end

  -- centerparent first time, next time reuse the last position
  find_dlg:showxy(iup.CURRENT, iup.CURRENT)
end

function item_font:action()
  local font = multitext.font
  local fontdlg = iup.fontdlg{value = font, parentdialog=iup.GetDialog(self)}

  fontdlg:popup(iup.CENTERPARENT, iup.CENTERPARENT)

  if (tonumber(fontdlg.status) == 1) then
    multitext.font = fontdlg.value
    config:SetVariable("MainWindow", "Font", fontdlg.value)
  end

  fontdlg:destroy()
end

function item_about:action()
  iup.Message("About", "   Simple Notepad\n\nAutors:\n   Gustavo Lyrio\n   Antonio Scuri")
end

--********************************** Main (Part 2/2) *****************************************

recent_menu = iup.menu{}

file_menu = iup.menu{
  item_open,
  item_saveas,
  iup.separator{},
  iup.submenu{title="Recent &Files", recent_menu},
  item_exit
  }
edit_menu = iup.menu{item_find, item_goto}
format_menu = iup.menu{item_font}
help_menu = iup.menu{item_about}
sub_menu_file = iup.submenu{file_menu, title = "&File"}
sub_menu_edit = iup.submenu{edit_menu, title = "&Edit"}
sub_menu_format = iup.submenu{format_menu, title = "F&ormat"}
sub_menu_help = iup.submenu{help_menu, title = "&Help"}

menu = iup.menu{
  sub_menu_file,
  sub_menu_edit,
  sub_menu_format,
  sub_menu_help,
  }

btn_open = iup.button{image = "IUP_FileOpen", flat = "Yes", action = item_open.action, canfocus="No", tip = "Open (Ctrl+O)"}
btn_save = iup.button{image = "IUP_FileSave", flat = "Yes", action = item_save.action, canfocus="No", tip = "Save (Ctrl+S)"}
btn_find = iup.button{image = "IUP_EditFind", flat = "Yes", action = item_find.action, canfocus="No", tip = "Find (Ctrl+F)"}

toolbar_hb = iup.hbox{
  btn_open,
  btn_save,
  iup.label{separator="VERTICAL"},
  btn_find,
  margin = "5x5",
  gap = 2,
  }

vbox = iup.vbox{
  toolbar_hb,
  multitext,
  lbl_statusbar,
}

dlg = iup.dialog{
  vbox,
  title = "Simple Notepad",
  size = "HALFxHALF",
  menu = menu,
  close_cb = item_exit.action,
}

function dlg:k_any(c)
  if (c == iup.K_cO) then
    item_open:action()
  elseif (c == iup.K_cS) then
    item_saveas:action()
  elseif (c == iup.K_cF) then
    item_find:action()
  elseif (c == iup.K_cG) then
    item_goto:action()
  end
end

config:RecentInit(recent_menu, 10)

-- parent for pre-defined dialogs in closed functions (IupMessage)
iup.SetGlobal("PARENTDIALOG", iup.SetHandleName(dlg))

config:DialogShow(dlg, "MainWindow")

-- to be able to run this script inside another context
if (iup.MainLoopLevel()==0) then
  iup.MainLoop()
  iup.Close()
end