text:
function strict() { 'use strict'; return this; }
function lenient() { return this; }
var obj = {};

assertEquals(true, strict.bind(true)());
assertEquals(42, strict.bind(42)());
assertEquals("", strict.bind("")());
assertEquals(null, strict.bind(null)());
assertEquals(undefined, strict.bind(undefined)());
assertEquals(obj, strict.bind(obj)());

assertEquals(true, lenient.bind(true)() instanceof Boolean);
assertEquals(true, lenient.bind(42)() instanceof Number);
assertEquals(true, lenient.bind("")() instanceof String);
assertEquals(this, lenient.bind(null)());
assertEquals(this, lenient.bind(undefined)());
assertEquals(obj, lenient.bind(obj)());


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace _7.ReplaceWords
{
    class Program
    {
        const string READ_FROM = @"..\..\..\BigTextFile.txt";
        const string WRITE_TO = @"..\..\..\ReplacedWords.txt";
        const string WORD_TO_REPLACE = "start";
        const string REPLACE_WITH = "finish";

        static void Main(string[] args)
        {
            StreamReader read = new StreamReader(READ_FROM);
            StreamWriter write = new StreamWriter(WRITE_TO);

            using (read)
            {
                using (write)
                {
                    string pattern = WORD_TO_REPLACE;
                    string line;
                    while ((line=read.ReadLine()) != null)
                    {
                        string replacedLine = Regex.Replace(line, pattern, REPLACE_WITH);
                        write.WriteLine(replacedLine);
                    }
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
![Logo](admin/starline_git.jpg)
# ioBroker.starline
![Number of Installations](http://iobroker.live/badges/starline-installed.svg) ![Number of Installations](http://iobroker.live/badges/starline-stable.svg)
[![NPM version](https://img.shields.io/npm/v/iobroker.starline.svg)](https://www.npmjs.com/package/iobroker.starline)
[![Downloads](https://img.shields.io/npm/dm/iobroker.starline.svg)](https://www.npmjs.com/package/iobroker.starline)
[![Tests](https://github.com/instalator/iobroker.starline/workflows/Test%20and%20Release/badge.svg)](https://github.com/instalator/ioBroker.starline/actions/)

[![NPM](https://nodei.co/npm/iobroker.starline.png?downloads=true)](https://nodei.co/npm/iobroker.starline/)

[![Donate](https://img.shields.io/badge/donate-YooMoney-green)](https://sobe.ru/na/instalator)
[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=PFUALWTR2CTPY)

Для работы драйвера необходимо установленное и настроенное противоугонное устройство поддерживающее сервис StarLine телематика 2.0.

Драйвер позволяет получать данные состояния автомобиля через сервис StarLine Телематика. https://starline-online.ru.
##### Управление основными режимами работы автосигнализации:
  - Постановка/снятие с охраны
  - Активация функции AntiHiJack
  - Автозапуск
  - Активация сервисного режима (Valet)
  - Активация доп. каналов
  - Включение/отключение подогревателя Webasto (При его наличии)
  - Запрос координат автомобиля
  - Отключение датчиков удара и наклона

## Changelog

#### 1.1.3
* (instalator) fixed error parse mayak

#### 1.1.2
* (instalator) fixed objects
* (instalator) fixed interval

#### 1.1.1
* (instalator) fixed send command

#### 1.1.0
* (instalator) fixed auth
* (instalator) added support admin3

#### 1.0.0
* (instalator) up to stable

#### 0.2.0
* (instalator) fix error sendCommand

#### 0.1.9
* (instalator) change send command,
* (instalator) fix parse balance"

#### 0.1.8
* (instalator) change link getdata

#### 0.1.7
* (instalator) change position x and y to longitude and latitude

#### 0.1.5
* (instalator) release

#### 0.1.2
* (instalator) fix widget for new structure

#### 0.1.1
* (Bluefox) changed the structure of the widget

#### 0.1.0
* (instalator) add widget

#### 0.0.3
* (instalator) added monitoring function
* (instalator) added control function

#### 0.0.2
* (instalator) initial release

## License
The MIT License (MIT)

Copyright (c) 2021 instalator <vvvalt@mail.ru>

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

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

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


text:
package kroki.app.analyzer;

import java.util.ArrayList;

import java.util.List;

import kroki.app.generators.utils.*;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;

import kroki.app.bodyElements.*;
import kroki.app.bodyElements.Operation;
import kroki.app.processors.*;
import tudresden.ocl20.pivot.essentialocl.expressions.impl.BooleanLiteralExpImpl;
import tudresden.ocl20.pivot.essentialocl.expressions.impl.CollectionLiteralExpImpl;
import tudresden.ocl20.pivot.essentialocl.expressions.impl.EnumLiteralExpImpl;
import tudresden.ocl20.pivot.essentialocl.expressions.impl.IfExpImpl;
import tudresden.ocl20.pivot.essentialocl.expressions.impl.IntegerLiteralExpImpl;
import tudresden.ocl20.pivot.essentialocl.expressions.impl.IteratorExpImpl;
import tudresden.ocl20.pivot.essentialocl.expressions.impl.LetExpImpl;
import tudresden.ocl20.pivot.essentialocl.expressions.impl.OperationCallExpImpl;
import tudresden.ocl20.pivot.essentialocl.expressions.impl.PropertyCallExpImpl;
import tudresden.ocl20.pivot.essentialocl.expressions.impl.RealLiteralExpImpl;
import tudresden.ocl20.pivot.essentialocl.expressions.impl.StringLiteralExpImpl;
import tudresden.ocl20.pivot.essentialocl.expressions.impl.TypeLiteralExpImpl;
import tudresden.ocl20.pivot.essentialocl.expressions.impl.VariableExpImpl;
import tudresden.ocl20.pivot.essentialocl.expressions.impl.VariableImpl;
import tudresden.ocl20.pivot.pivotmodel.Constraint;

public class ConstraintBodyAnalyzer {
	private kroki.app.generators.utils.Constraint fmCon;
	private List<BodyElement> elementList=new ArrayList<BodyElement>();

	public ConstraintBodyAnalyzer(Constraint e,kroki.app.generators.utils.Constraint con){
		fmCon=con;
	}

	public BodyElement getElementData(EObject o){
		if(o instanceof PropertyCallExpImpl)
			return getPropertyCallData((PropertyCallExpImpl) o);
		else if(o instanceof IntegerLiteralExpImpl)
			return getIntData((IntegerLiteralExpImpl)o);
		else if(o instanceof IteratorExpImpl){
			if(getIteratorData((IteratorExpImpl)o)!=null)
				return getIteratorData((IteratorExpImpl)o);
		}else if(o instanceof IfExpImpl)
			return getIfExpData((IfExpImpl)o);
		else if(o instanceof OperationCallExpImpl)
			return getOperationData((OperationCallExpImpl)o);
		else if(o instanceof StringLiteralExpImpl)
			return getStringData((StringLiteralExpImpl)o);
		else if(o instanceof VariableImpl){
			if(getVariableData((VariableImpl)o)!=null)
				return getVariableData((VariableImpl)o);
		}else if(o instanceof EnumLiteralExpImpl)
			return getEnumData((EnumLiteralExpImpl)o);
		else if(o instanceof VariableExpImpl){
			if(getVariableExpData((VariableExpImpl)o)!=null)
				return getVariableExpData((VariableExpImpl)o);
		}else if(o instanceof LetExpImpl)
			return getLetData((LetExpImpl)o);
		else if(o instanceof BooleanLiteralExpImpl)
			return getBooleanData((BooleanLiteralExpImpl)o);
		else if(o instanceof RealLiteralExpImpl)
			return getRealData((RealLiteralExpImpl)o);
		else if(o instanceof TypeLiteralExpImpl)
			return getTypeLiteralData((TypeLiteralExpImpl)o);
		else if(o instanceof CollectionLiteralExpImpl)
			return getCollectionLiteralData((CollectionLiteralExpImpl)o);
		//System.out.println(o);
		return null;
	}

	public List<BodyElement> getContentsData(TreeIterator<EObject> tree) {
		List<BodyElement> result=new ArrayList<BodyElement>();
		while(tree.hasNext()){
			EObject o=tree.next();
			if(getElementData(o)!=null)
				result.add(getElementData(o));
			//System.out.println(o);
		}

		return result;
	}

	public List<BodyElement> getContentsData(EList<EObject> tree) {
		List<BodyElement> result=new ArrayList<BodyElement>();
		for(int i=0;i<tree.size();i++){
			EObject o=tree.get(i);
			if(getElementData(o)!=null)
				result.add(getElementData(o));
		}
		return result;
	}

	public void processBody() {
		for(int n=0;n<elementList.size();n++)
			System.out.println(elementList.get(n).getValue()+"\t"+elementList.get(n).getType()+"\t"+elementList.get(n).getValueType());

		if(supported()){
			prepareLet();
			checkSizeOperation();
		//	processCollectionLiteral();
			checkCollectionLiterals();
			elementList=linkProperties(elementList);
			if(fmCon.getKind().equals("postcondition")){
				preparePost();		// bitan je redosled poziva metoda
			}else if(fmCon.getKind().equals("initial")){
				processInit();
			}
			processLet();
			processElementList();

			if(fmCon.getKind().equals("derived")){
				processDerived();
			}else if(fmCon.getKind().equals("precondition"))
				processPre();
		}

		List<BodyElement> lista=getElementList();
		for(int l=0;l<lista.size();l++){
			System.out.println(lista.get(l).getValue());
		}
		System.out.println("");
		System.out.println("");
	}

	private BodyElement getCollectionLiteralData(CollectionLiteralExpImpl o){
		String value=o.getType().getName();
		value=correctPropertyType(value);
		CollectionLiteral b=new CollectionLiteral(value, "CollectionLiteralExpImpl");
		b.setValueType(value);
		b.setNumberOfLiterals(o.getPart().size());
		TreeIterator<EObject> tree=o.eAllContents();
		b.setContents(getContentsData(tree));
		return b;
	}

	private BodyElement getTypeLiteralData(TypeLiteralExpImpl o) {
		String value=o.getReferredType().getName();
		if(value.startsWith("Sequence"))
			value="List"+value.substring(8);
		else if(value.startsWith("Bag"))
			value="List"+value.substring(3);
		else if(value.startsWith("OrderedSet"))
			value="List"+value.substring(10);
		else if(value.startsWith("Set"))
			value="Set"+value.substring(3);
		else if(value.equals("Real"))
			value="float";
		else if(value.equals("Boolean"))
			value="boolean";
		else if(value.equals("OclType"))
			value="Class";
		else if(value.equals("OclAny"))
			value="Object";
		BodyElement b=new BodyElement(value, "TypeLiteralExpImpl");
		return b;
	}

	private BodyElement getRealData(RealLiteralExpImpl o) {
		float f=o.getRealSymbol();
		String value=String.valueOf(f);
		BodyElement b=new BodyElement(value, "RealLiteralExpImpl");
		b.setValueType("float");
		return b;
	}

	private BodyElement getBooleanData(BooleanLiteralExpImpl o) {
		String value=o.toString();
		int i=value.indexOf("true");
		if(i==-1)
			value="false";
		else
			value="true";
		BodyElement b=new BodyElement(value, "BooleanLiteralExpImpl");
		b.setValueType("boolean");
		return b;
	}

	private BodyElement getLetData(LetExpImpl o) {
		TreeIterator<EObject> tree=o.getVariable().eAllContents();
		List<BodyElement> variableContents=new ArrayList<BodyElement>();
		variableContents=getContentsData(tree);
		String value=o.getVariable().getName();
		LetContents let=new LetContents(value, "LetExpImpl");
		let.setLetVariableContents(variableContents);
		String type=o.getVariable().getType().getName();
		type=correctPropertyType(type);
		let.setValueType(type);
		return let;
	}

	private BodyElement getVariableExpData(VariableExpImpl o) {
		BodyElement b=null;
		String value=o.getReferredVariable().getName();
		if(!(value.equals("self")) && !(value.startsWith("$implicitVariable")) && !(value.startsWith("$implicitCollect"))){
			b=new BodyElement(value, "VariableExpImpl");
			String type=correctPropertyType(o.getReferredVariable().getType().getName());
			b.setValueType(type);
		}
		return b;
	}

	private BodyElement getEnumData(EnumLiteralExpImpl o) {
		String value=o.getType().getName()+"."+o.getReferredEnumLiteral().getName();
		BodyElement b=new BodyElement(value, "EnumLiteralExpImpl");
		return b;
	}

	private BodyElement getVariableData(VariableImpl o) {
		BodyElement b=null;
		String value=o.getName();
		if(!(value.equals("self")) && !(value.startsWith("$implicitVariable")) && !(value.startsWith("$implicitCollect")) && !(value.equals(""))){
			b=new BodyElement(value, "VariableImpl");
			elementList.add(b);
		}
		return b;
	}

	private BodyElement getStringData(StringLiteralExpImpl o) {
		String value='\"'+o.getStringSymbol()+'\"';
		BodyElement b=new BodyElement(value, "StringLiteralExpImpl");
		b.setValueType("String");
		return b;
	}

	private BodyElement getOperationData(OperationCallExpImpl o) {
		String value;
		if(o.getReferredOperation()!=null){
			value=o.getReferredOperation().getName();
		}else{
			value=o.getName();
		}
		Operation b=new Operation(value, "OperationCallExpImpl");;
		b.correctValue(value);

		if(o.getReferredOperation()!=null)
			b.setValueType(o.getReferredOperation().getType().getName());

		b.setTip(b.determineTip(b.getValue()));	// odredjivanje tipa operatora

		if(!(b.getTip().equals("binarni")) && !(b.getTip().equals("set")) && !(b.getTip().equals("loop")) &&
				!(b.getTip().equals("math")) && !(b.getTip().equals("string"))&& !(b.getTip().equals("unarni")) && !(b.getTip().equals("unsupported")))
			b.setValue(b.getValue()+"()");

		if(b.getTip().equals("set")){
			EList<EObject> tree =o.eContents();
			List<BodyElement> absList=getContentsData(tree);
			b.setElementList(absList);
		}
		if(b.getValue().equals("sum")){
			TreeIterator<EObject> tree=o.eAllContents();
			List<BodyElement> absList=getContentsData(tree);
			b.setElementList(absList);
		}
		return b;
	}

	private BodyElement getIfExpData(IfExpImpl o) {
		String value="if";
		BodyElement b=new BodyElement(value, "IfExpImpl");
		b.setValueType("Boolean");
		return b;
	}

	private BodyElement getIteratorData(IteratorExpImpl o) {
		Operation b=null;
		String value=o.getName();
		if(!(value.equals("collect")) || fmCon.getBody().indexOf("collect")!=-1){
			TreeIterator<EObject> tree =o.eAllContents();
			List<BodyElement> iterList=getContentsData(tree);
			b=new Operation(value, "OperationCallExpImpl");
			b.setTip("loop");
			b.setElementList(iterList);
			elementList.add(b);
		}
		return b;
	}

	private BodyElement getIntData(IntegerLiteralExpImpl o) {
		int value=o.getIntegerSymbol();
		BodyElement b=new BodyElement(Integer.toString(value), "IntegerLiteralExpImpl");
		b.setValueType("Integer");
		return b;
	}

	private BodyElement getPropertyCallData(PropertyCallExpImpl o) {
		String value=o.getReferredProperty().getName();
		BodyElement b=new BodyElement("ka_" + value, "PropertyCallExpImpl");
		String type=o.getType().getName();
		type=correctPropertyType(type);
		b.setValueType(type);
		return b;
	}

	private void processInit() {
	/*	InitialValue init=new InitialValue(fmCon.getOperation().getName(),elementList.get(0).getValue());
		List<FMClass> classes=FMModel.getInstance().getClasses();
		FMModel.getInstance().findConstraintClassByName(fmCon.getContext()).getInitialValues().add(init);
		for(int i=0;i<classes.size();i++)
			if(classes.get(i).getName().equals(fmCon.getContext())){
				FMModel.getInstance().getClasses().get(i).getInitialValues().add(init);
				for(int j=0;j<FMModel.getInstance().getClasses().get(i).getConstructorParams().size();j++)
					if(FMModel.getInstance().getClasses().get(i).getConstructorParams().get(j).getName().equals(fmCon.getOperation().getName()))
						FMModel.getInstance().getClasses().get(i).getConstructorParams().remove(j);
			}
		for(int j=0;j<FMModel.getInstance().findConstraintClassByName(fmCon.getContext()).getConstructorParams().size();j++)
			if(FMModel.getInstance().findConstraintClassByName(fmCon.getContext()).getConstructorParams().get(j).getName().equals(fmCon.getOperation().getName()))
				FMModel.getInstance().findConstraintClassByName(fmCon.getContext()).getConstructorParams().remove(j);

		*/
	}

	private void processPre() {
		int index=fmCon.getOperation().getHeader().indexOf("(");  // ubacivanje Pre u ime metode
		String operHeader=fmCon.getOperation().getHeader().substring(0, index)+"Pre"+fmCon.getOperation().getHeader().substring(index);
		fmCon.getOperation().setHeader(operHeader);
		String operName=fmCon.getOperation().getName().substring(0, index)+"Pre"+fmCon.getOperation().getName().substring(index);
		fmCon.getOperation().setName(operName);
		for(int i=0;i<elementList.size();i++)
			if(getElementList().get(i).getType().equals("OperationCallExpImpl") && !(getElementList().get(i).getValue().equals("not()"))){
				fmCon.setCondition(makeStatement(i));
				break;
			}
	}

	public void preparePost(){
		int index=fmCon.getOperation().getHeader().indexOf("(");  // ubacivanje Post u ime metode
		String operHeader=fmCon.getOperation().getHeader().substring(0, index)+"Post"+fmCon.getOperation().getHeader().substring(index);
		fmCon.getOperation().setHeader(operHeader);
		for(int i=0;i<elementList.size();i++) // zamena result sa pozivom operacije
			if(elementList.get(i).getValue().equals("result")){
				elementList.get(i).setValue(fmCon.getOperation().getHeaderWithoutTypes());
			}

		String javaResult="";
		String preType = "";
		String preValue = "";
		Boolean atPre=false; // oznacava da li postoji element sa operatorom @pre
		for(int i=0;i<elementList.size();i++)
			if(elementList.get(i).getValue().equals("atPre()")){  // pronadje se element na koji se odnosi operator @pre
				atPre=true;  // element na koji se odnosi operator @pre i sam operator se spajaju u jednu vrednost
				preType=elementList.get(i+1).getValueType();
				preValue=elementList.get(i+1).getValue();
				if(preValue.endsWith("()"))
					preValue=preValue.substring(0, preValue.length()-2);
				if(elementList.get(i+1).getType().equals("PropertyCallExpImpl"))
					javaResult="\t"+preType+" "+preValue+"Pre = "+preValue+";"; // deklaracija promenljive koja ce cuvati prethodnu vrednost atributa
				else if(elementList.get(i+1).getType().equals("OperationCallExpImpl"))
					javaResult="\t"+preType+" "+preValue+"Pre = "+preValue+"();"; // deklaracija promenljive koja ce cuvati prethodnu vrednost atributa

				elementList.get(i).setValue(preValue+"Pre");
				elementList.get(i).setValueType(preType);
				elementList.get(i).setType("PropertyCallExpImpl");
				fmCon.getDeclarations().add(javaResult);
				elementList.remove(i+1);	//element se brise iz liste, jer vise nije potreban
			}
		if(atPre){
			javaResult="\t"+fmCon.getOperation().getHeaderWithoutTypes()+";"; // poziv metode
			fmCon.getDeclarations().add(javaResult);
		}
		String operName=fmCon.getOperation().getName().substring(0, index)+"Post"+fmCon.getOperation().getName().substring(index);
		fmCon.getOperation().setName(operName);
	}

	public void processElementList(){
		if(elementList.size()==1)
			fmCon.setCondition(elementList.get(0).getValue());
		for(int i=0;i<elementList.size();i++){
			if(elementList.get(i).getType().equals("OperationCallExpImpl")){
				if(fmCon.getCondition().length()==0)
					fmCon.setCondition(makeStatement(i));
			}
			else if(elementList.get(i).getType().equals("IfExpImpl") && elementList.get(i).getValue().equals("if")){
				fmCon.setCondition(makeStatement(i+1));
				fmCon.setThenPart(makeStatement(pom+1));
				fmCon.setElsePart(makeStatement(pom+1));
			}
			else if(elementList.get(i).getType().equals("BooleanLiteralExpImpl")){
				fmCon.setCondition(makeStatement(i));
			}
		}
	}

	private void processLet(){
		for(int i=0;i<elementList.size();i++){
			if(elementList.get(i).getType().equals("LetExpImpl")){
				String letJava=elementList.get(i).getValueType()+" "+elementList.get(i).getValue()+" = ";
				letJava+=makeStatement(i+1)+";";
				for (int bound = i + 1; bound <= lastOperand; bound++)
					elementList.remove(i + 1);
				fmCon.getDeclarations().add(letJava);
			}
		}
	}

	/**
	 * Sadrzaj koji se odnosi na let promenljivu se brise iz liste i prebacuje ispred naziva let promenljive
	 */
	private void prepareLet(){
		for(int i=0;i<elementList.size();i++){
			if(elementList.get(i).getType().equals("LetExpImpl")){
				LetContents let=(LetContents) elementList.get(i);
				let.determineBounds(elementList);
				for(int bound=let.getLowerBound();bound<let.getUpperBound();bound++)
					elementList.remove(let.getLowerBound());
				for(int j=let.getLetVariableContents().size();j>0;j--)
					elementList.add(i+1, let.getLetVariableContents().get(j-1));
				i+=let.getLetVariableContents().size();
			}
		}
	}

	public void checkCollectionLiterals(){
		for(int i=0;i<elementList.size();i++)
			if(elementList.get(i).getType().equals("CollectionLiteralExpImpl") && elementList.get(i).getValue().contains("<")){
				processCollectionLiteral(i);
			}
	}
	int index=0;
	public String processCollectionLiteral(int i){
				index++;
				elementList.get(i).setValue("list"+index);
				CollectionLiteral lit=(CollectionLiteral) elementList.get(i);
				if(lit.getValueType().startsWith("List"))
					fmCon.getDeclarations().add(lit.getValueType()+" "+lit.getValue()+"=new Array"+lit.getValueType()+"();");
				else if(lit.getValueType().startsWith("Set"))
					fmCon.getDeclarations().add(lit.getValueType()+" "+lit.getValue()+"=new Hash"+lit.getValueType()+"();");
				String literal;
				System.out.println(lit.getValue());
				for(int j=0;j<lit.getNumberOfLiterals();j++){
					if(elementList.get(i+1).getType().equals("OperationCallExpImpl")){
						literal=makeStatement(i+1);
						for(int b=i+1;b<=lastOperand;b++)
							elementList.remove(i+1);
					}
					else if(elementList.get(i+1).getType().equals("CollectionLiteralExpImpl")){
						literal=processCollectionLiteral(i+1);
						elementList.remove(i+1);
					}

					else{
						literal=elementList.get(i+1).getValue();
						elementList.remove(i+1);
					}
					fmCon.getDeclarations().add(lit.getValue()+".add("+literal+");");
				}
				return lit.getValue();
	}

	int pom=0; // cuva poziciju drugog operanda u situaciji kada nijedan od operanada nije operator
	private int lastOperand=0;	// pozicija poslennjeg clana u izrazu
	public int getLastOperand() {
		return lastOperand;
	}

	public void setLastOperand(int lastOperand) {
		this.lastOperand = lastOperand;
	}

	public String makeStatement(int i){
		String ifPart = "";
			if(elementList.get(i).getType().equals("OperationCallExpImpl")){
				Operation operation=(Operation) elementList.get(i);
				if(operation.getTip().equals("binarni")){
					int not=0; // da li ispred uslova stoji negacija
					int poz=i;
					if(poz>0)
						if(elementList.get(i-1).getValue().equals("not()"))
							not=1;
					String secondOperandType=elementList.get(i+2).getType();
					String firstOperandValue=elementList.get(i+1).getValue();
					String secondOperandValue=elementList.get(i+2).getValue();

					Controller controller=new Controller();
					controller.chooseProcessor(elementList.get(i+1));
					if(controller.getProcessor()!=null){
						controller.setCaller(this);
						firstOperandValue=controller.process(i+1);
						secondOperandValue=elementList.get(lastOperand+1).getValue();
					}
					controller.chooseProcessor(elementList.get(i+2));
					if(controller.getProcessor()!=null){
						controller.setCaller(this);
						secondOperandValue=controller.process(i+2);
					}
					 secondOperandType=elementList.get(i+2).getType();
					 firstOperandValue=elementList.get(i+1).getValue();
					 secondOperandValue=elementList.get(i+2).getValue();

					if(!(Operation.getBinarniOperatori().contains(firstOperandValue))){
						ifPart="( "+firstOperandValue;
						if(needEqual(elementList.get(i), elementList.get(i+1), elementList.get(i+2))){
							if(secondOperandType.equals("OperationCallExpImpl") && Operation.getBinarniOperatori().contains(secondOperandValue)) // drugi operand je operator
								ifPart+=".equals("+makeStatement(i+2)+"))";
							else{
								ifPart+=".equals("+secondOperandValue+"))";
								pom=i+2;
								lastOperand=pom;
							}
						}else{
							ifPart+=" "+elementList.get(i).getValue()+" ";
							if(secondOperandType.equals("OperationCallExpImpl") && Operation.getBinarniOperatori().contains(secondOperandValue)){
								ifPart+=makeStatement(i+2)+" )";
							}else{
								ifPart+=secondOperandValue+" )";
								pom=i+2;
								lastOperand=pom;
							}
						}
					}else if(Operation.getBinarniOperatori().contains(firstOperandValue)){  // prvi operand je operator
						ifPart+=makeStatement(i+1);
						BodyElement firstOper=new BodyElement(ifPart, "PropertyCallExpImpl");
						ifPart="( "+makeStatement(elementList.get(i),firstOper,elementList.get(pom+1),pom+1)+" )";
					}
					if(operation.getValue().equals("implies")){
						((Operation)(elementList.get(i))).setFirstOperand(makeStatement(i+1));
						((Operation)(elementList.get(i))).setSecondOperand(makeStatement(pom+1));
						ifPart="implies("+((Operation)(elementList.get(i))).getFirstOperand()+", "+((Operation)(elementList.get(i))).getSecondOperand()+ ")";
						kroki.app.generators.utils.Operation oper=new kroki.app.generators.utils.Operation();
						oper.setName("implies");
						oper.setType(""); // da u sablonu ne bi pukao null pointer exception
						//****FMModel.getInstance().findConstraintClassByName(fmCon.getContext()).addOperation(oper);
					}

					if(not==1 || operation.getValue().equals("!=")){
						ifPart="!("+ifPart+")";
					}
				}
				else{
					Controller controller=new Controller();
					controller.chooseProcessor(elementList.get(i));
					if(controller.getProcessor()!=null){
						controller.setCaller(this);
						ifPart=controller.process(i);
					}
				}

			}else if(elementList.get(i).getType().equals("PropertyCallExpImpl") && elementList.get(i).getValueType().equals("Boolean")){
				ifPart=elementList.get(i).getValue();
				pom=i;
				lastOperand=i;
			}else if(elementList.get(i).getType().equals("BooleanLiteralExpImpl")){
				ifPart=elementList.get(i).getValue();
				pom=i;
				lastOperand=i;
			}
		return ifPart;
	}

	public String makeStatement(BodyElement znak, BodyElement op1, BodyElement op2, int op2Poz){
		String ifPart = "";
		//Operation o=new Operation();
				if(Operation.getBinarniOperatori().contains(znak.getValue())){
					String secondOperandType=op2.getType();
					String firstOperandValue=op1.getValue();
					String secondOperandValue=op2.getValue();

					Controller controller=new Controller();
					controller.chooseProcessor(op2);
					if(controller.getProcessor()!=null){
						controller.setCaller(this);
						secondOperandValue=controller.process(op2Poz);
					}

					if(!(Operation.getBinarniOperatori().contains(firstOperandValue))){
						ifPart=firstOperandValue;
						if(needEqual(znak, op1, op2)){
							if(secondOperandType.equals("OperationCallExpImpl")&& Operation.getBinarniOperatori().contains(firstOperandValue))
								ifPart+=".equals("+makeStatement(op2Poz)+")";
							else{
								ifPart+=".equals("+secondOperandValue+")";
								pom=op2Poz;
								lastOperand=pom;
							}
						}else{
							ifPart+=" "+znak.getValue()+" ";
							if(secondOperandType.equals("OperationCallExpImpl") && Operation.getBinarniOperatori().contains(secondOperandValue)){
								ifPart+=makeStatement(op2Poz);
							}else{
								ifPart+=secondOperandValue;
								pom=op2Poz;
								lastOperand=pom;
							}
						}
					}else if(Operation.getBinarniOperatori().contains(firstOperandValue)){
						ifPart+=makeStatement(op2Poz-1);
						BodyElement fo=new BodyElement(ifPart, "PropertyCallExpImpl");
						ifPart+=makeStatement(elementList.get(op2Poz-2),fo,elementList.get(pom+1),pom+1);
					}
				}
		return ifPart;
	}

	public List<BodyElement> linkProperties(List<BodyElement> list){
		/*String linkedValue="";
		int count=0;	// broji atribute u lancu
		int end;  // oznacava kraj lanca
		String resultType = null;
		for(int i=0;i<list.size();i++){
			end=1;
			if(list.get(i).getType().equals("PropertyCallExpImpl") || list.get(i).getType().equals("VariableExpImpl")){
				int poz=i;
				if(list.size()>poz+1){  // provera da li postoji naredni element da bi se izbegao null pointer exeption
					if(list.get(i+1).getType().equals("PropertyCallExpImpl") || list.get(i+1).getType().equals("VariableExpImpl")){
						String tip=list.get(i+1).getValueType();    // ime klase kojoj atribut pripada
						List<FMClass> classes = FMModel.getInstance().getClasses();
						for(int c=0;c<classes.size();c++){
							if(classes.get(c).getName().equals(tip)){  //poredi se naziv klase sa tipom atributa
								EJBClass cl=classes.get(c);
								for(int a=0;a<cl.getProperties().size();a++){
									if(cl.getProperties().get(a).getName().equals(list.get(i).getValue())){
										resultType=list.get(i+1).getType();
										end=0;
										String newPart;
										// ako je u pitanju poziv operacije koja vraca neki objekat, ne dodaje se get
										if(list.get(i+1).getValue().endsWith("()"))
											newPart=list.get(i+1).getValue();
										else
											newPart="get"+upperFirst(list.get(i+1).getValue())+"()";
										if(count==0){ // u pitanju je prvi krug
											linkedValue=newPart+".get"+upperFirst(list.get(i).getValue())+"()";
										}else{
											linkedValue=newPart+"."+linkedValue;
										}
										count++;
									}
								}
							}
						}
					}
				}
			}
			if(end==1 && !(linkedValue.equals(""))){ // ubacuje se u listu dobijeni lanac i brisu se sastavni delovi
				if(resultType.equals("VariableExpImpl")){
					linkedValue=lowerFirst(linkedValue.substring(3, linkedValue.length())); // skinda se get sa pocetka
					int index=linkedValue.indexOf(".");
					linkedValue=linkedValue.substring(0, index-2)+linkedValue.substring(index); // skidanje zagrada sa prvog clana
				}

				BodyElement b=new BodyElement(linkedValue, resultType);
				b.setValueType(list.get(i-count).getValueType());
				list.add(i+1, b);
				linkedValue="";
				for(int r=0;r<=count;r++){
					list.remove(i-r);
				}
				count=0;
				i--;	// prilikom brisanja, i se pomeri za jedno mesto u napred pa mora da se vrati
			}
		}*/
		return list;
	}

	private void processDerived() {
	/*	DerivedValue der=new DerivedValue(fmCon.getOperation().getName(),fmCon.getOperation().getType(),fmCon.getCondition());
		List<FMClass> classes=FMModel.getInstance().getClasses();
		for(int i=0;i<classes.size();i++)
			if(classes.get(i).getName().equals(fmCon.getContext())){
				FMModel.getInstance().getClasses().get(i).removeGetter(fmCon.getOperation().getName());
				FMModel.getInstance().getClasses().get(i).getDerivedValues().add(der);
			}*/
	}

	private Boolean needEqual(BodyElement znak, BodyElement op1, BodyElement op2){
		if(!(znak.getValue().equals("==")) && !(znak.getValue().equals("!=")))
			return false;
		int o1=1; // 0 - int, 1 - string
		int o2=1;
		if(op1.getValueType()!=null)
			if(op1.getValueType().equals("Integer"))
				o1=0;
		if(op1.getType().equals("OperationCallExpImpl") && op1.getValueType()!=null)
			if(op1.getValueType().equals("Integer"))
				o1=0;
		if(op2.getValueType()!=null)
			if(op2.getValueType().equals("Integer"))
				o2=0;
		if(op2.getType().equals("OperationCallExpImpl") && op2.getValueType()!=null)
			if(op2.getValueType().equals("Integer"))
				o2=0;
		if(o1==1 && o2==1)
			return true;
		else
			return false;
	}

	public String upperFirst(String linkedValue) {
		String s="";
		if(linkedValue.length()>0)
			s=linkedValue.substring(0, 1).toUpperCase()+linkedValue.substring(1);
		return s;
	}
	private String lowerFirst(String linkedValue) {
		String s=linkedValue.substring(0, 1).toLowerCase()+linkedValue.substring(1);
		return s;
	}
	private void checkSizeOperation(){
		for(int i=0;i<elementList.size();i++)
			if(elementList.get(i).getValue().equals("size")){
				if(elementList.get(i+1).getValueType()!=null)
					if(elementList.get(i+1).getValueType().length()>4)	// zbog substring da ne dodje do IndexOutOfBoundsException
						if(!(elementList.get(i+1).getValueType().substring(0, 3).equals("Set")) && !(elementList.get(i+1).getValueType().substring(0, 4).equals("List")))
							if(!(Operation.getSetOperatori().contains(elementList.get(i+1).getValue()))){
								elementList.get(i).setValue("length");
								((Operation)(elementList.get(i))).setTip("string");
							}
			}
	}

	private String correctPropertyType(String type) {
		String res=type;
		String typePart="";
		if(type.startsWith("Bag")){
			typePart=type.substring(4, type.length()-1);
			typePart=correctPropertyType(typePart);
			res="List<"+typePart+">";
		}
		else if(type.startsWith("Sequence")){
			typePart=type.substring(9, type.length()-1);
			typePart=correctPropertyType(typePart);
			res="List<"+typePart+">";
		}
		else if(type.startsWith("OrderedSet")){
			typePart=type.substring(11, type.length()-1);
			typePart=correctPropertyType(typePart);
			res="List<"+typePart+">";
		}
		else if(type.substring(0, 3).equals("Set")){
			typePart=type.substring(4, type.length()-1);
			typePart=correctPropertyType(typePart);
			res="Set<"+typePart+">";
		}

		if(res.startsWith("List")){
			//FMModel.getInstance().findConstraintClassByName(fmCon.getContext()).addImportedPackage("import java.util.List;");
			//FMModel.getInstance().findConstraintClassByName(fmCon.getContext()).addImportedPackage("import java.util.ArrayList;");
		}
		else if(res.startsWith("Set")){
			//FMModel.getInstance().findConstraintClassByName(fmCon.getContext()).addImportedPackage("import java.util.Set;");
			//FMModel.getInstance().findConstraintClassByName(fmCon.getContext()).addImportedPackage("import java.util.HashSet;");
		}
		return res;
	}

	private boolean supported() {
		for(int i=0;i<elementList.size();i++)
			if(elementList.get(i).getType().equals("OperationCallExpImpl")){
				Operation op=(Operation) elementList.get(i);
				if(op.getTip().equals("unsupported")){
					fmCon.setBody("Operacija "+op.getValue()+" nije podrzana. Ogranicenje se mora implementirati rucno.");
					fmCon.setKind("unsupported");
					return false;
				}
			}else if(!(elementList.get(i).getType().equals("VariableImpl")) && !(elementList.get(i).getType().equals("EnumLiteralExpImpl")))
				if(elementList.get(i).getValueType().startsWith("Tuple")){
					fmCon.setKind("unsupported");
					fmCon.setBody("Tip podataka Tuple nije podrzan. Ogranicenje se mora implementirati rucno.");
					return false;
				}

		return true;
	}

	public List<BodyElement> getElementList() {
		return elementList;
	}
	public void setElementList(List<BodyElement> objectList) {
		this.elementList = objectList;
	}
	public kroki.app.generators.utils.Constraint getFmCon() {
		return fmCon;
	}
}


text:
<!doctype html>

		<meta charset="utf-8">
		<title>Dots and Boxes</title>
		<link rel="stylesheet" href="index.css">

    <form id="settings" class="hidden">

Settings

        Number of players
        <input type="number" id="playerNum" name="playerNum" maxlength="1" max="4" min="2" value="2"/>

        Number of lines
        <input type="number" id="size" name="size" maxlength="2" max="20" min="2" value="2"/>

        <button type="submit">Ok</button>
        <button id="settings-cancel" type="button">Cancel</button>

    </form>


text:
layout: post
title:  "Roasties"
excerpt: "A quick and easy guide to prepare your potatoes in a different way"
date:   2015-03-11
categories: recipes
author: david
comments: true
share: true
---

Ingredients:

Oven

Potatoes (skinned)

Olive oil

Pan for boiling

Steps:

Skin your potatoes

Halve them

Par-boil them. In the mean time pre-heat your oven at 160 degrees

Drain them, make sure that they are as dry as possible

Put them in a baking tray and sprinkle olive oil over them. Make sure that at least the bottom of the tray is covered with oil

Roast them in the oven until golden brown

Enjoy!


text:
package registry

import (
	"os"
	"path/filepath"
	"strings"

	"github.com/spf13/pflag"
)

// CertsDir is the directory where certificates are stored
var CertsDir = os.Getenv("programdata") + `\docker\certs.d`

// cleanPath is used to ensure that a directory name is valid on the target
// platform. It will be passed in something *similar* to a URL such as
// https:\index.docker.io\v1. Not all platforms support directory names
// which contain those characters (such as : on Windows)
func cleanPath(s string) string {
	return filepath.FromSlash(strings.Replace(s, ":", "", -1))
}

// installCliPlatformFlags handles any platform specific flags for the service.
func (options *ServiceOptions) installCliPlatformFlags(flags *pflag.FlagSet) {
	// No Windows specific flags.
}


text:
import os, os.path
from time import time
import numpy
import random

# in order to always generate the same random sequence
random.seed(19)

def fill_arrays(start, stop):
    col_i = numpy.arange(start, stop, dtype=numpy.int32)
    if userandom:
        col_j = numpy.random.uniform(0, nrows, stop-start)
    else:
        col_j = numpy.array(col_i, dtype=numpy.float64)
    return col_i, col_j

# Generator for ensure pytables benchmark compatibility
def int_generator(nrows):
    step = 1000*100
    j = 0
    for i in xrange(nrows):
        if i >= step*j:
            stop = (j+1)*step
            if stop > nrows:  # Seems unnecessary
                stop = nrows
            col_i, col_j = fill_arrays(i, stop)
            j += 1
            k = 0
        yield (col_i[k], col_j[k])
        k += 1

def int_generator_slow(nrows):
    for i in xrange(nrows):
        if userandom:
            yield (i, float(random.randint(0, nrows)))
        else:
            yield (i, float(i))

def open_db(filename, remove=0):
    if remove and os.path.exists(filename):
        os.remove(filename)
    con = sqlite.connect(filename)
    cur = con.cursor()
    return con, cur

def create_db(filename, nrows):
    con, cur = open_db(filename, remove=1)
    cur.execute("create table ints(i integer, j real)")
    t1=time()
    # This is twice as fast as a plain loop
    cur.executemany("insert into ints(i,j) values (?,?)", int_generator(nrows))
    con.commit()
    ctime = time()-t1
    if verbose:
        print "insert time:", round(ctime, 5)
        print "Krows/s:", round((nrows/1000.)/ctime, 5)
    close_db(con, cur)

def index_db(filename):
    con, cur = open_db(filename)
    t1=time()
    cur.execute("create index ij on ints(j)")
    con.commit()
    itime = time()-t1
    if verbose:
        print "index time:", round(itime, 5)
        print "Krows/s:", round(nrows/itime, 5)
    # Close the DB
    close_db(con, cur)

def query_db(filename, rng):
    con, cur = open_db(filename)
    t1=time()
    ntimes = 10
    for i in range(ntimes):
        # between clause does not seem to take advantage of indexes
        #cur.execute("select j from ints where j between %s and %s" % \
        cur.execute("select i from ints where j >= %s and j <= %s" % \
        #cur.execute("select i from ints where i >= %s and i <= %s" % \
                    (rng[0]+i, rng[1]+i))
        results = cur.fetchall()
    con.commit()
    qtime = (time()-t1)/ntimes
    if verbose:
        print "query time:", round(qtime, 5)
        print "Mrows/s:", round((nrows/1000.)/qtime, 5)
        print results
    close_db(con, cur)

def close_db(con, cur):
    cur.close()
    con.close()

if __name__=="__main__":
    import sys
    import getopt
    try:
        import psyco
        psyco_imported = 1
    except:
        psyco_imported = 0

    usage = """usage: %s [-v] [-p] [-m] [-i] [-q] [-c] [-R range] [-n nrows] file
            -v verbose
            -p use "psyco" if available
            -m use random values to fill the table
            -q do query
            -c create the database
            -i index the table
            -2 use sqlite2 (default is use sqlite3)
            -R select a range in a field in the form "start,stop" (def "0,10")
            -n sets the number of rows (in krows) in each table
            \n""" % sys.argv[0]

    try:
        opts, pargs = getopt.getopt(sys.argv[1:], 'vpmiqc2R:n:')
    except:
        sys.stderr.write(usage)
        sys.exit(0)

    # default options
    verbose = 0
    usepsyco = 0
    userandom = 0
    docreate = 0
    createindex = 0
    doquery = 0
    sqlite_version = "3"
    rng = [0, 10]
    nrows = 1

    # Get the options
    for option in opts:
        if option[0] == '-v':
            verbose = 1
        elif option[0] == '-p':
            usepsyco = 1
        elif option[0] == '-m':
            userandom = 1
        elif option[0] == '-i':
            createindex = 1
        elif option[0] == '-q':
            doquery = 1
        elif option[0] == '-c':
            docreate = 1
        elif option[0] == "-2":
            sqlite_version = "2"
        elif option[0] == '-R':
            rng = [int(i) for i in option[1].split(",")]
        elif option[0] == '-n':
            nrows = int(option[1])

    # Catch the hdf5 file passed as the last argument
    filename = pargs[0]

    if sqlite_version == "2":
        import sqlite
    else:
        from pysqlite2 import dbapi2 as sqlite

    if verbose:
        print "pysqlite version:", sqlite.version
        if userandom:
            print "using random values"

    if docreate:
        if verbose:
            print "writing %s krows" % nrows
        if psyco_imported and usepsyco:
            psyco.bind(create_db)
        nrows *= 1000
        create_db(filename, nrows)

    if createindex:
        index_db(filename)

    if doquery:
        query_db(filename, rng)


text:
<?php

namespace Glory\Bundle\WechatBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class GloryWechatBundle extends Bundle
{
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
  ~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you 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.
  -->

<!--
        This configuration file represents the configuration that are needed
        when publishing APIs to API Manager
-->
<WebappPublisherConfigs>

    <!-- This host is used to define the host address which is used to publish APIs -->
    <Host>https://localhost:9445</Host>

    <!-- If it is true, the APIs of this instance will be published to the defined host -->
    <PublishAPI>true</PublishAPI>

    <!-- If it is true, the APIs of this instance will be updated when the webapps are redeployed -->
    <EnabledUpdateApi>true</EnabledUpdateApi>

    <!--Webapp will be published only when running below profiles-->
    <Profiles>
        <Profile>default</Profile>
    </Profiles>
</WebappPublisherConfigs>


text:
<?php

/**
 * MQseries MQBEGIN
 *
 * @phpstub
 *
 * @param resource $hconn
 * @param array $beginOptions
 * @param resource $compCode
 * @param resource $reason
 *
 * @return void
 */
function mqseries_begin($hconn, $beginOptions, &$compCode, &$reason)
{
}


text:
<?php
/**
 * PHP fault tolerance library
 *
 * @author    Михаил Красильников <m.krasilnikov@yandex.ru>
 * @license   http://opensource.org/licenses/MIT MIT
 */
namespace Mekras\Obereg\Storage;

/**
 * Storage interface.
 *
 * @api
 * @since 1.0
 */
interface Storage
{
    /**
     * Fetch next data item.
     *
     * @param string $gatewayId The gateway ID.
     *
     * @return DataContainer|null The data container or null if queue is empty.
     *
     * @since 1.0
     */
    public function dequeue($gatewayId);

    /**
     * Push data to queue.
     *
     * @param string $gatewayId The gateway ID.
     * @param string $data      The data to be stored.
     *
     * @return void
     *
     * @since 1.0
     */
    public function enqueue($gatewayId, $data);

    /**
     * Fetch cached data from storage.
     *
     * @param string $gatewayId The gateway ID.
     * @param string $hash      The data hash.
     *
     * @return DataContainer|null The data container or null if no data available
     *
     * @since 1.0
     */
    public function get($gatewayId, $hash);

    /**
     * Store data.
     *
     * @param string $gatewayId The gateway ID.
     * @param string $hash      The data hash.
     * @param string $data      The data to be stored.
     *
     * @return void
     *
     * @since 1.0
     */
    public function put($gatewayId, $hash, $data);
}


text:
import styled from 'styled-components';
import MobileContentWrapper from 'mcs-lite-ui/lib/MobileContentWrapper';

export const Container = styled(MobileContentWrapper)`
  padding: 16px 16px 56px 16px;
`;

export const InputWrapper = styled.div`
  margin-bottom: 8px;

  > *:first-child {
    margin-bottom: 4px;
  }
`;

export const FakeInput = styled.div`
  display: flex;
  align-items: center;
  box-sizing: border-box;
  border-width: 1px;
  border-style: solid;
  border-radius: 3px;
  padding: 0 10px;
  cursor: pointer;
  min-height: ${props => props.theme.height.normal};
  color: ${props => props.theme.color.black};
  background-color: ${props => props.theme.color.white};
  border-color: ${props => props.theme.color.grayBase};
  font-size: ${props => props.theme.fontSize.p};
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: auto;
`;

export const ButtonWrapper = styled.div`
  display: flex;
  padding: 8px 16px;

  > * {
    flex: 1;
  }

  > *:first-child {
    margin-right: 8px;
  }
`;


text:
package net.jselby.escapists.game.events.functions;

import com.badlogic.gdx.Gdx;
import net.jselby.escapists.game.Layer;
import net.jselby.escapists.game.ObjectInstance;
import net.jselby.escapists.game.events.Action;
import net.jselby.escapists.game.events.Condition;
import net.jselby.escapists.game.events.FunctionCollection;

/**
 * Frame functions handle scenes and layers.
 */
public class Frames extends FunctionCollection {
    @Action(subId = -3, id = 0)
    public void NextFrame() {
        JumpToFrame(scope.getGame().getSceneIndex() + 1);
    }

    @Action(subId = -3, id = 2)
    public void JumpToFrame(final int scene) {
        Gdx.app.postRunnable(new Runnable() {
            @Override
            public void run() {
                scope.getGame().loadScene(scene);
            }
        });
    }

    @Action(subId = 48, id = 111)
    public void ShowLayer(int id) {
        scope.getScene().getLayers()[id - 1].setVisible(true);
    }

    @Action(subId = 48, id = 112)
    public void HideLayer(int id) {
        scope.getScene().getLayers()[id - 1].setVisible(false);
    }

    @Condition(subId = 48, id = -91)
    public boolean IsLayerVisible(int layer) {
        return scope.getScene().getLayers()[layer - 1].isVisible();
    }

    @Action(subId = 2, id = 57)
    public void BringToFront() {
        for (ObjectInstance object : scope.getObjects()) {
            Layer[] layers = scope.getScene().getLayers();
            for (Layer layer : layers) {
                layer.objects.remove(object);
            }
            layers[layers.length - 1].objects.add(object);
        }
    }

    @Action(subId = 2, id = 61)
    public void SetLayer(int id) {
        for (ObjectInstance object : scope.getObjects()) {
            for (Layer layer : scope.getScene().getLayers()) {
                layer.objects.remove(object);
            }
            scope.getScene().getLayers()[id].objects.add(object);
        }
    }
}


text:
@interface PodsDummy_Pods_SwiftSample_Facebook_iOS_SDK : NSObject
@end
@implementation PodsDummy_Pods_SwiftSample_Facebook_iOS_SDK
@end


text:
[![Build Status](https://img.shields.io/travis/CocoaPods/cocoapods-plugins/master.svg?style=flat)](https://travis-ci.org/CocoaPods/cocoapods-plugins)
[![Coverage](https://img.shields.io/codeclimate/coverage/github/CocoaPods/cocoapods-plugins.svg?style=flat)](https://codeclimate.com/github/CocoaPods/cocoapods-plugins)
[![Code Climate](https://img.shields.io/codeclimate/github/CocoaPods/cocoapods-plugins.svg?style=flat)](https://codeclimate.com/github/CocoaPods/cocoapods-plugins)

CocoaPods plugin which shows info about available CocoaPods plugins or helps you get started developing a new plugin. Yeah, it's very meta.

## Installation

    $ gem install cocoapods-plugins

## Usage

##### List installed plugins

    $ pod plugins installed

List all installed CocoaPods plugins with their respective version (and pre_install/post_insall hooks if any)

##### List known plugins

    $ pod plugins list

List all known CocoaPods plugins (according to the list hosted on `http://github.com/CocoaPods/cocoapods-plugins`)

##### Search plugins

    $ pod plugins search QUERY

Search plugins whose name contains the given text (ignoring case). With --full, it searches by name but also by author and description.

##### Create a new plugin

    $ pod plugins create NAME [TEMPLATE_URL]

Create a scaffold for the development of a new plugin according to the CocoaPods best practices.
If a `TEMPLATE_URL`, pointing to a git repo containing a compatible template, is specified, it will be used in place of the default one.

## Get your plugin listed

    $ pod plugins publish

Create an issue in the `cocoapods-plugins` GitHub repository to ask for your plugin to be added to the official list (with the proper JSON fragment to be added to `plugins.json` so we just have to copy/paste it).


text:
/**
 * Complex Number Algebra v1.0.0
 * Created by Julian D. Quitian on 12/25/2015.
 */

//Test File
public class ComplexNumberAlgebra {
    public static void main(String[] args){
        Complex a = new Complex(1, 2);
        Complex b = new Complex(2, 3);
        System.out.println(a.getNegation());
    }
}


text:
"""
Change modification date of newly added languoids
"""
from datetime import datetime

from sqlalchemy import create_engine
from clldutils.apilib import assert_release

from glottolog3.cli_util import get_releases

def register(parser):  # pragma: no cover
    parser.add_argument('--previous', help='previous version to compare against', default=None)

def run(args):  # pragma: no cover
    version = assert_release(args.repos.repos)
    if args.previous:
        last = args.previous
    else:
        rels = get_releases(args)
        last = sorted(set(rel.tag for rel in rels) - {version}, key=lambda s: float(s[1:]))[-1][1:]
    print('previous version: {0}'.format(last))

    cdb = create_engine('postgresql://postgres@/glottolog3')
    ldb = create_engine('postgresql://postgres@/glottolog-{0}'.format(last))
    sql = "select id from language as l, languoid as ll where l.pk = ll.pk and ll.level = 'language'"

    current = set(r[0] for r in cdb.execute(sql))
    last = set(r[0] for r in ldb.execute(sql))
    for gc in sorted(current - last):
        cdb.execute(
            "update language set updated = %s where id = %s", (datetime.utcnow(), gc))


text:
typedef void
( AOC_INTERFACE *isaDisassemble)(
    oclCompiler* cl,
    oclElf* bin,
    const char* kernel,
    oclLogFunction disasm_callback
    ) AOC_API_0_7;

typedef const void*
( AOC_INTERFACE *isaGetBinaryBlob)(
    oclCompiler* cl,
    const oclElf* bin,
    const char* kernel,
    size_t* size
    ) AOC_API_0_7;
#endif // _INTERFACE_GPUISA_H_


text:
package http

import (
	"compress/gzip"
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/influxdata/influxdb/v2"
	"github.com/influxdata/influxdb/v2/http/metric"
	httpmock "github.com/influxdata/influxdb/v2/http/mock"
	"github.com/influxdata/influxdb/v2/kit/platform"
	"github.com/influxdata/influxdb/v2/kit/platform/errors"
	kithttp "github.com/influxdata/influxdb/v2/kit/transport/http"
	"github.com/influxdata/influxdb/v2/mock"
	influxtesting "github.com/influxdata/influxdb/v2/testing"
	"github.com/influxdata/influxdb/v2/tsdb"
	"github.com/stretchr/testify/require"
	"go.uber.org/zap/zaptest"
)

func TestWriteService_WriteTo(t *testing.T) {
	type args struct {
		org      string
		orgId    platform.ID
		bucket   string
		bucketId platform.ID
		r        io.Reader
	}

	orgId := platform.ID(1)
	org := "org"
	bucketId := platform.ID(2)
	bucket := "bucket"

	tests := []struct {
		name        string
		args        args
		status      int
		want        string
		wantFilters influxdb.BucketFilter
		wantErr     bool
	}{
		{
			name: "write with org and bucket IDs",
			args: args{
				orgId:    orgId,
				bucketId: bucketId,
				r:        strings.NewReader("m,t1=v1 f1=2"),
			},
			status: http.StatusNoContent,
			want:   "m,t1=v1 f1=2",
			wantFilters: influxdb.BucketFilter{
				ID:             &bucketId,
				OrganizationID: &orgId,
			},
		},
		{
			name: "write with org ID and bucket name",
			args: args{
				orgId:  orgId,
				bucket: bucket,
				r:      strings.NewReader("m,t1=v1 f1=2"),
			},
			status: http.StatusNoContent,
			want:   "m,t1=v1 f1=2",
			wantFilters: influxdb.BucketFilter{
				Name:           &bucket,
				OrganizationID: &orgId,
			},
		},
		{
			name: "write with org name and bucket ID",
			args: args{
				org:      org,
				bucketId: bucketId,
				r:        strings.NewReader("m,t1=v1 f1=2"),
			},
			status: http.StatusNoContent,
			want:   "m,t1=v1 f1=2",
			wantFilters: influxdb.BucketFilter{
				ID:  &bucketId,
				Org: &org,
			},
		},
		{
			name: "write with org and bucket names",
			args: args{
				org:    org,
				bucket: bucket,
				r:      strings.NewReader("m,t1=v1 f1=2"),
			},
			status: http.StatusNoContent,
			want:   "m,t1=v1 f1=2",
			wantFilters: influxdb.BucketFilter{
				Name: &bucket,
				Org:  &org,
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var org, bucket *string
			var orgId, bucketId *platform.ID
			var lp []byte
			ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				orgStr := r.URL.Query().Get("org")
				bucketStr := r.URL.Query().Get("bucket")
				var err error
				if orgId, err = platform.IDFromString(orgStr); err != nil {
					org = &orgStr
				}
				if bucketId, err = platform.IDFromString(bucketStr); err != nil {
					bucket = &bucketStr
				}
				defer r.Body.Close()
				in, _ := gzip.NewReader(r.Body)
				defer in.Close()
				lp, _ = ioutil.ReadAll(in)
				w.WriteHeader(tt.status)
			}))
			s := &WriteService{
				Addr: ts.URL,
			}
			err := s.WriteTo(
				context.Background(),
				influxdb.BucketFilter{ID: &tt.args.bucketId, Name: &tt.args.bucket, OrganizationID: &tt.args.orgId, Org: &tt.args.org},
				tt.args.r,
			)
			require.Equalf(t, err != nil, tt.wantErr, "error didn't match expectations: %v", err)
			require.Equal(t, tt.wantFilters.OrganizationID, orgId)
			require.Equal(t, tt.wantFilters.Org, org)
			require.Equal(t, tt.wantFilters.ID, bucketId)
			require.Equal(t, tt.wantFilters.Name, bucket)
			require.Equal(t, tt.want, string(lp))
		})
	}
}

func TestWriteHandler_handleWrite(t *testing.T) {
	// state is the internal state of org and bucket services
	type state struct {
		org       *influxdb.Organization // org to return in org service
		orgErr    error                  // err to return in org service
		bucket    *influxdb.Bucket       // bucket to return in bucket service
		bucketErr error                  // err to return in bucket service
		writeErr  error                  // err to return from the points writer
		opts      []WriteHandlerOption   // write handle configured options
	}

	// want is the expected output of the HTTP endpoint
	type wants struct {
		body string
		code int
	}

	// request is sent to the HTTP endpoint
	type request struct {
		auth   influxdb.Authorizer
		org    string
		bucket string
		body   string
	}

	tests := []struct {
		name    string
		request request
		state   state
		wants   wants
	}{
		{
			name: "simple body is accepted",
			request: request{
				org:    "043e0780ee2b1000",
				bucket: "04504b356e23b000",
				body:   "m1,t1=v1 f1=1",
				auth:   bucketWritePermission("043e0780ee2b1000", "04504b356e23b000"),
			},
			state: state{
				org:    testOrg("043e0780ee2b1000"),
				bucket: testBucket("043e0780ee2b1000", "04504b356e23b000"),
			},
			wants: wants{
				code: 204,
			},
		},
		{
			name: "partial write error is unprocessable",
			request: request{
				org:    "043e0780ee2b1000",
				bucket: "04504b356e23b000",
				body:   "m1,t1=v1 f1=1",
				auth:   bucketWritePermission("043e0780ee2b1000", "04504b356e23b000"),
			},
			state: state{
				org:      testOrg("043e0780ee2b1000"),
				bucket:   testBucket("043e0780ee2b1000", "04504b356e23b000"),
				writeErr: tsdb.PartialWriteError{Reason: "bad points", Dropped: 1},
			},
			wants: wants{
				code: 422,
				body: `{"code":"unprocessable entity","message":"failure writing points to database: partial write: bad points dropped=1"}`,
			},
		},
		{
			name: "points writer error is an internal error",
			request: request{
				org:    "043e0780ee2b1000",
				bucket: "04504b356e23b000",
				body:   "m1,t1=v1 f1=1",
				auth:   bucketWritePermission("043e0780ee2b1000", "04504b356e23b000"),
			},
			state: state{
				org:      testOrg("043e0780ee2b1000"),
				bucket:   testBucket("043e0780ee2b1000", "04504b356e23b000"),
				writeErr: fmt.Errorf("error"),
			},
			wants: wants{
				code: 500,
				body: `{"code":"internal error","message":"unexpected error writing points to database: error"}`,
			},
		},
		{
			name: "empty request body is ok",
			request: request{
				org:    "043e0780ee2b1000",
				bucket: "04504b356e23b000",
				auth:   bucketWritePermission("043e0780ee2b1000", "04504b356e23b000"),
			},
			state: state{
				org:    testOrg("043e0780ee2b1000"),
				bucket: testBucket("043e0780ee2b1000", "04504b356e23b000"),
			},
			wants: wants{
				code: 204,
			},
		},
		{
			name: "org error returns 404 error",
			request: request{
				org:    "043e0780ee2b1000",
				bucket: "04504b356e23b000",
				body:   "m1,t1=v1 f1=1",
				auth:   bucketWritePermission("043e0780ee2b1000", "04504b356e23b000"),
			},
			state: state{
				orgErr: &errors.Error{Code: errors.ENotFound, Msg: "not found"},
			},
			wants: wants{
				code: 404,
				body: `{"code":"not found","message":"not found"}`,
			},
		},
		{
			name: "missing bucket returns 404",
			request: request{
				org:    "043e0780ee2b1000",
				bucket: "",
				body:   "m1,t1=v1 f1=1",
				auth:   bucketWritePermission("043e0780ee2b1000", "04504b356e23b000"),
			},
			state: state{
				org:    testOrg("043e0780ee2b1000"),
				bucket: testBucket("043e0780ee2b1000", "04504b356e23b000"),
			},
			wants: wants{
				code: 404,
				body: `{"code":"not found","message":"bucket not found"}`,
			},
		},
		{
			name: "bucket error returns 404 error",
			request: request{
				org:    "043e0780ee2b1000",
				bucket: "04504b356e23b000",
				body:   "m1,t1=v1 f1=1",
				auth:   bucketWritePermission("043e0780ee2b1000", "04504b356e23b000"),
			},
			state: state{
				org:       testOrg("043e0780ee2b1000"),
				bucketErr: &errors.Error{Code: errors.ENotFound, Msg: "not found"},
			},
			wants: wants{
				code: 404,
				body: `{"code":"not found","message":"not found"}`,
			},
		},
		{
			name: "500 when bucket service returns internal error",
			request: request{
				org:    "043e0780ee2b1000",
				bucket: "04504b356e23b000",
				auth:   bucketWritePermission("043e0780ee2b1000", "04504b356e23b000"),
			},
			state: state{
				org:       testOrg("043e0780ee2b1000"),
				bucketErr: &errors.Error{Code: errors.EInternal, Msg: "internal error"},
			},
			wants: wants{
				code: 500,
				body: `{"code":"internal error","message":"internal error"}`,
			},
		},
		{
			name: "invalid line protocol returns 400",
			request: request{
				org:    "043e0780ee2b1000",
				bucket: "04504b356e23b000",
				auth:   bucketWritePermission("043e0780ee2b1000", "04504b356e23b000"),
				body:   "invalid",
			},
			state: state{
				org:    testOrg("043e0780ee2b1000"),
				bucket: testBucket("043e0780ee2b1000", "04504b356e23b000"),
			},
			wants: wants{
				code: 400,
				body: `{"code":"invalid","message":"unable to parse 'invalid': missing fields"}`,
			},
		},
		{
			name: "forbidden to write with insufficient permission",
			request: request{
				org:    "043e0780ee2b1000",
				bucket: "04504b356e23b000",
				body:   "m1,t1=v1 f1=1",
				auth:   bucketWritePermission("043e0780ee2b1000", "000000000000000a"),
			},
			state: state{
				org:    testOrg("043e0780ee2b1000"),
				bucket: testBucket("043e0780ee2b1000", "04504b356e23b000"),
			},
			wants: wants{
				code: 403,
				body: `{"code":"forbidden","message":"insufficient permissions for write"}`,
			},
		},
		{
			// authorization extraction happens in a different middleware.
			name: "no authorizer is an internal error",
			request: request{
				org:    "043e0780ee2b1000",
				bucket: "04504b356e23b000",
			},
			state: state{
				org:    testOrg("043e0780ee2b1000"),
				bucket: testBucket("043e0780ee2b1000", "04504b356e23b000"),
			},
			wants: wants{
				code: 500,
				body: `{"code":"internal error","message":"authorizer not found on context"}`,
			},
		},
		{
			name: "large requests rejected",
			request: request{
				org:    "043e0780ee2b1000",
				bucket: "04504b356e23b000",
				body:   "m1,t1=v1 f1=1",
				auth:   bucketWritePermission("043e0780ee2b1000", "04504b356e23b000"),
			},
			state: state{
				org:    testOrg("043e0780ee2b1000"),
				bucket: testBucket("043e0780ee2b1000", "04504b356e23b000"),
				opts:   []WriteHandlerOption{WithMaxBatchSizeBytes(5)},
			},
			wants: wants{
				code: 413,
				body: `{"code":"request too large","message":"unable to read data: points batch is too large"}`,
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			orgs := mock.NewOrganizationService()
			orgs.FindOrganizationF = func(ctx context.Context, filter influxdb.OrganizationFilter) (*influxdb.Organization, error) {
				return tt.state.org, tt.state.orgErr
			}
			buckets := mock.NewBucketService()
			buckets.FindBucketFn = func(context.Context, influxdb.BucketFilter) (*influxdb.Bucket, error) {
				return tt.state.bucket, tt.state.bucketErr
			}

			b := &APIBackend{
				HTTPErrorHandler:    kithttp.NewErrorHandler(zaptest.NewLogger(t)),
				Logger:              zaptest.NewLogger(t),
				OrganizationService: orgs,
				BucketService:       buckets,
				PointsWriter:        &mock.PointsWriter{Err: tt.state.writeErr},
				WriteEventRecorder:  &metric.NopEventRecorder{},
			}
			writeHandler := NewWriteHandler(zaptest.NewLogger(t), NewWriteBackend(zaptest.NewLogger(t), b), tt.state.opts...)
			handler := httpmock.NewAuthMiddlewareHandler(writeHandler, tt.request.auth)

			r := httptest.NewRequest(
				"POST",
				"http://localhost:8086/api/v2/write",
				strings.NewReader(tt.request.body),
			)

			params := r.URL.Query()
			params.Set("org", tt.request.org)
			params.Set("bucket", tt.request.bucket)
			r.URL.RawQuery = params.Encode()

			w := httptest.NewRecorder()
			handler.ServeHTTP(w, r)
			if got, want := w.Code, tt.wants.code; got != want {
				t.Errorf("unexpected status code: got %d want %d", got, want)
			}

			if got, want := w.Body.String(), tt.wants.body; got != want {
				t.Errorf("unexpected body: got %s want %s", got, want)
			}
		})
	}
}

func bucketWritePermission(org, bucket string) *influxdb.Authorization {
	oid := influxtesting.MustIDBase16(org)
	bid := influxtesting.MustIDBase16(bucket)
	return &influxdb.Authorization{
		OrgID:  oid,
		Status: influxdb.Active,
		Permissions: []influxdb.Permission{
			{
				Action: influxdb.WriteAction,
				Resource: influxdb.Resource{
					Type:  influxdb.BucketsResourceType,
					OrgID: &oid,
					ID:    &bid,
				},
			},
		},
	}
}

func testOrg(org string) *influxdb.Organization {
	oid := influxtesting.MustIDBase16(org)
	return &influxdb.Organization{
		ID: oid,
	}
}

func testBucket(org, bucket string) *influxdb.Bucket {
	oid := influxtesting.MustIDBase16(org)
	bid := influxtesting.MustIDBase16(bucket)

	return &influxdb.Bucket{
		ID:    bid,
		OrgID: oid,
	}
}


text:
DEBUG = True

# We are not really using a relational database, but tests fail without
# defining it because flush command is being run, which expects it
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:',
    }
}

# Make this unique, and don't share it with anybody
SECRET_KEY = 'sq=uf!nqw=aibl+y1&5pp=)b7pc=c$4hnh$om*_c48r)^t!ob)'

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'test_project.urls'

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.admin',
    'guardian',
    'tastypie',
    'pieguard',
    'test_app',
)

# Gardian Config
ANONYMOUS_USER_ID = -1
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'guardian.backends.ObjectPermissionBackend',
)


text:
import qualified AtomicExpr as AE
import qualified Data.List  as L
import qualified Data.Map   as M
import qualified System.IO  as IO

allTheSame :: (Eq a) => [a] -> Bool
allTheSame xs = and $ map (== head xs) (tail xs)

unique = reverse . L.nub . reverse
allTheSameF xs func = and $ map (func (head xs)) (tail xs)

hasVar :: AE.Term -> AE.Term -> Bool
hasVar (AE.TermVar id) (AE.TermVar id') = id == id'
hasVar var (AE.TermFunc _ args) = hasVar2 var args
hasVar _ _ = False

hasVar2 var [] = False
hasVar2 var (h:t) =
    if hasVar var h
        then True
        else hasVar2 var t

findVar [] = Nothing
findVar (h:t) =
    case h of
        AE.TermVar _ -> Just h
        _ -> findVar t

findTerm var (h:t) =
    if var == h
        then findTerm var t
        else h

getNewSubstituion :: [AE.Term] -> Maybe (AE.Term, AE.Term)
getNewSubstituion terms =
    let var  = findVar terms in
        case var of
            Nothing -> Nothing
            Just v  ->
                let term = findTerm v terms in
                    if hasVar v $ findTerm v terms
                        then Nothing
                        else Just (v, term)

getDisagreementSetOfArgs :: [[AE.Term]] -> Either String (Maybe [AE.Term])
getDisagreementSetOfArgs argsList =
    if (length $ head argsList) == 0
        then Right Nothing
        else
            case getDisagreementSet $ map (\x -> head x) argsList of
                Right Nothing -> getDisagreementSetOfArgs $ map (\x -> tail x) argsList
                result -> result

getDisagreementSetOfFuncs :: [AE.Term] -> Either String (Maybe [AE.Term])
getDisagreementSetOfFuncs funcs =
    let argsList = map (\(AE.TermFunc _ x) -> x) funcs in
        if allTheSame (map length argsList) == True
            then getDisagreementSetOfArgs argsList
            else
                let AE.TermFunc id _ = head funcs in
                    Left $ "error: the number of arguments is different (function \"" ++ id ++ "\")"

getDisagreementSet :: [AE.Term] -> Either String (Maybe [AE.Term])
getDisagreementSet [] = Left "error: no terms"
getDisagreementSet terms =
    if allTheSameF terms AE.sameTerms == True
        then
            case head terms of
                AE.TermFunc _ _ -> getDisagreementSetOfFuncs terms
                _ -> Right Nothing
        else Right $ Just (unique terms)

compose1 :: [(AE.Term, AE.Term)] -> (AE.Term, AE.Term) -> (AE.Term, AE.Term)
compose1 y (id, term) = (id, head $ substitute [term] y)

compose3 [] _ = True
compose3 ((a, _):t) (b, c) =
    if a == b
        then False
        else compose3 t (b, c)

compose :: [(AE.Term, AE.Term)] -> [(AE.Term, AE.Term)] -> [(AE.Term, AE.Term)]
compose x y = s2 ++ s3 where
    s1 = map (compose1 y) x
    s2 = [(a, b) | (a, b) <-s1, a /= b]
    s3 = [z | z <- y, compose3 x z]

printTerms [] = do
    return ()
printTerms (h:t) = do
    putStr "  "
    putStrLn $ AE.term2str h
    printTerms t

substitute = substitute1 []

substitute1 :: [AE.Term] -> [AE.Term] -> [(AE.Term, AE.Term)] -> [AE.Term]
substitute1 result [] sub = reverse result
substitute1 result (h:t) sub =
    substitute1 (term:result) t sub where
        term = substitute2 h sub

substitute2 :: AE.Term -> [(AE.Term, AE.Term)] -> AE.Term
substitute2 term [] = term
substitute2 (AE.TermVar id) sub =
        getTerm (AE.TermVar id) sub
    where
        getTerm term [] = term
        getTerm (AE.TermVar id) ((AE.TermVar id', term):t)
            | id == id' = term
            | otherwise = getTerm (AE.TermVar id) t
substitute2 (AE.TermFunc id terms) sub =
    let terms' = substitute1 [] terms sub in
        AE.TermFunc id terms'
substitute2 term _ = term

unify2 :: [AE.Term] -> [(AE.Term, AE.Term)] -> Either String (AE.Term, [(AE.Term, AE.Term)])
unify2 terms sub =
    let t1 = unique $ substitute terms sub in
        if length t1 == 1
            then Right (head t1, sub)
            else unify3 terms sub t1

unify3 :: [AE.Term] -> [(AE.Term, AE.Term)] -> [AE.Term] -> Either String (AE.Term, [(AE.Term, AE.Term)])
unify3 terms sub t1 =
    case getDisagreementSet t1 of
        Left str       -> Left str
        Right Nothing  -> Left "error: could not find a disagreement set"
        Right (Just d) ->
            case getNewSubstituion d of
                Nothing -> Left "error: could not find a new substitution"
                Just s  -> unify2 terms (compose sub [s])

unify terms = unify2 terms []

printResult (Left str) = do
    putStrLn str
printResult (Right (term, c)) = do
    putStrLn "unified term:"
    printTerms [term]
    putStrLn "unifier:"
    printSubstitution c

printSubstitution [] = return ()
printSubstitution ((AE.TermVar id, term):t) = do
    putStrLn $ "  " ++ id ++ " -> " ++ (AE.term2str term)
    printSubstitution t

parseLine line exprs =
    printErr $ AE.parse line
    where
        printErr result =
            case result of
            Left err -> do
                print err
                return exprs
            Right expr -> do
                return $ expr:exprs

getUserLines terms = do
    putStr "> "
    IO.hFlush IO.stdout
    line <- getLine
    if line == "" && length terms /= 0
        then do
            putStrLn "terms:"
            t <- return $ reverse $ unique terms
            printTerms t
            printResult $ unify t
            getUserLines []
        else do
            e <- parseLine line terms
            getUserLines e

main :: IO ()
main = do
    putStrLn "(an empty line unifies the expressions and Ctrl+c terminates this process)"
    getUserLines []


text:
package org.camunda.bpm.model.cmmn.impl.instance;

import static org.camunda.bpm.model.cmmn.impl.CmmnModelConstants.CMMN11_NS;
import static org.camunda.bpm.model.cmmn.impl.CmmnModelConstants.CMMN_ELEMENT_PLAN_ITEM_CONTROL;

import org.camunda.bpm.model.cmmn.instance.CmmnElement;
import org.camunda.bpm.model.cmmn.instance.ManualActivationRule;
import org.camunda.bpm.model.cmmn.instance.PlanItemControl;
import org.camunda.bpm.model.cmmn.instance.RepetitionRule;
import org.camunda.bpm.model.cmmn.instance.RequiredRule;
import org.camunda.bpm.model.xml.ModelBuilder;
import org.camunda.bpm.model.xml.impl.instance.ModelTypeInstanceContext;
import org.camunda.bpm.model.xml.type.ModelElementTypeBuilder;
import org.camunda.bpm.model.xml.type.ModelElementTypeBuilder.ModelTypeInstanceProvider;
import org.camunda.bpm.model.xml.type.child.ChildElement;
import org.camunda.bpm.model.xml.type.child.SequenceBuilder;

/**
 * @author Roman Smirnov
 *
 */
public class PlanItemControlImpl extends CmmnElementImpl implements PlanItemControl {

  protected static ChildElement<RepetitionRule> repetitionRuleChild;
  protected static ChildElement<RequiredRule> requiredRuleChild;
  protected static ChildElement<ManualActivationRule> manualActivationRuleChild;

  public PlanItemControlImpl(ModelTypeInstanceContext instanceContext) {
    super(instanceContext);
  }

  public RepetitionRule getRepetitionRule() {
    return repetitionRuleChild.getChild(this);
  }

  public void setRepetitionRule(RepetitionRule repetitionRule) {
    repetitionRuleChild.setChild(this, repetitionRule);
  }

  public RequiredRule getRequiredRule() {
    return requiredRuleChild.getChild(this);
  }

  public void setRequiredRule(RequiredRule requiredRule) {
    requiredRuleChild.setChild(this, requiredRule);
  }

  public ManualActivationRule getManualActivationRule() {
    return manualActivationRuleChild.getChild(this);
  }

  public void setManualActivationRule(ManualActivationRule manualActivationRule) {
    manualActivationRuleChild.setChild(this, manualActivationRule);
  }

  public static void registerType(ModelBuilder modelBuilder) {
    ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PlanItemControl.class, CMMN_ELEMENT_PLAN_ITEM_CONTROL)
        .namespaceUri(CMMN11_NS)
        .extendsType(CmmnElement.class)
        .instanceProvider(new ModelTypeInstanceProvider<PlanItemControl>() {
          public PlanItemControl newInstance(ModelTypeInstanceContext instanceContext) {
            return new PlanItemControlImpl(instanceContext);
          }
        });

    SequenceBuilder sequenceBuilder = typeBuilder.sequence();

    repetitionRuleChild = sequenceBuilder.element(RepetitionRule.class)
        .build();

    requiredRuleChild = sequenceBuilder.element(RequiredRule.class)
        .build();

    manualActivationRuleChild = sequenceBuilder.element(ManualActivationRule.class)
        .build();

    typeBuilder.build();
  }

}


text:
from xml.dom import minidom

class Configuration:
    mCurNode = None

    def __init__(self, node):
        self.mCurNode = node

    """
    get first child
    """
    def GetChild(self, name):
        for node in self.mCurNode.childNodes:
            if node.nodeName == name:
                return Configuration(node)
        return None

    def GetChilds(self, name):
        nodes = []
        for node in self.mCurNode.childNodes:
            if node.nodeName == name:
                nodes.append(Configuration(node))
        return nodes

    def GetName(self):
        return self.mCurNode.nodeName

    def GetValue(self):
        return self.mCurNode.firstChild.data

    @staticmethod
    def FromFile(path):
        return Configuration(minidom.parse(path).childNodes[0])

"""
if __name__ == "__main__":
    cfg = Configuration.FromFile("sandbox/test.xml")
    print cfg.GetName()
    print cfg.GetValue()
    cfg1 = cfg.GetChild("hello")
    print cfg1.GetName()
    print cfg1.GetValue()
    cfgs = cfg.GetChilds("world")
    for c in cfgs:
        print c.GetName()
        print c.GetValue()
"""


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<title>BuilderEngine Dashboard | Login Page</title>
	<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
	<meta content="BuilderEngine Dashboard" name="description" />
	<meta content="BuilderEngine" name="author" />

    <link href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet">
    <link href="<?php echo get_theme_path()?>assets/plugins/jquery-ui-1.10.4/themes/base/minified/jquery-ui.min.css" rel="stylesheet" />
    <link href="<?php echo get_theme_path()?>assets/plugins/bootstrap-3.2.0/css/bootstrap.min.css" rel="stylesheet" />
    <link href="<?php echo get_theme_path()?>assets/plugins/font-awesome-4.2.0/css/font-awesome.min.css" rel="stylesheet" />
    <link href="<?php echo get_theme_path()?>assets/css/animate.min.css" rel="stylesheet" />
    <link href="<?php echo get_theme_path()?>assets/css/style.css?v2" rel="stylesheet" />
    <link href="<?php echo get_theme_path()?>assets/css/style-responsive.min.css" rel="stylesheet" />
    <link href="<?php echo get_theme_path()?>assets/css/theme/blue.css" rel="stylesheet" id="theme" />

<img src="<?php echo $url?>" data-id="login-cover-image" alt="" />

                    <img src="<?php echo get_theme_path()?>assets/img/BuilderEngine_Logo_Admin.png" alt="BuilderEngine Dashboard">
                    Administration Control Panel - Dashboard Login

                <form action="index.html" method="POST" class="margin-bottom-0">

                        <input type="text" class="form-control input-lg" placeholder="Username" id="user" />

                        <input type="password" class="form-control input-lg" placeholder="Password" id="password" />

                            <input type="checkbox" /> Remember Me

                        <button type="submit" class="btn btn-success btn-block btn-lg">Sign In</button>

                        Forgot your password? Click here to recover.

                </form>

                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Forgotten Password

                            <form method="post">

                                        Your Email
                                        <input style="color:#000;width:75%;background: #fff;border: 1px solid rgba(0,0,0,0.4);" type="email" class="form-control input-lg" name="email" placeholder="Email Address"/>

                                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                    <button type="submit" name="forgot" class="btn btn-primary">Reset Password</button>

                            </form>

    <?=$BuilderEngine->handle_head()?>


text:
require 'spec_helper'

klass = OneviewSDK::API300::Synergy::DriveEnclosure
RSpec.describe klass, integration: true, type: DELETE, sequence: rseq(klass) do
  let(:current_client) { $client_300_synergy }
  include_examples 'DriveEnclosureDeleteExample', 'integration api300 context'
end


text:
'use strict';

/**
 * @ngdoc service
 * @name mobileControlPanelApp.McpService
 * @description
 * # McpService
 * Service in the mobileControlPanelApp.
 */
angular.module('mobileControlPanelApp').service('McpService', [
  '$http',
  'AuthService',
  function($http, AuthService) {
    function getMobileAppsURL() {
      return window.MCP_URL + '/mobileapp';
    }
    function getMobileServicesURL() {
      return window.MCP_URL + '/mobileservice';
    }
    // AngularJS will instantiate a singleton by calling "new" on this function
    let requestConfig = { headers: {} };
    AuthService.addAuthToRequest(requestConfig);

    return {
      mobileApps: function() {
        if (!window.MCP_URL) {
          return new Promise(function(resolve, reject) {
            return reject('No MCP URL');
          });
        }

        return $http.get(getMobileAppsURL(), requestConfig).then(res => {
          return res.data;
        });
      },
      mobileApp: function(id) {
        if (!window.MCP_URL) {
          return new Promise(function(resolve, reject) {
            return reject('No MCP URL');
          });
        }
        return $http
          .get(getMobileAppsURL() + '/' + id, requestConfig)
          .then(res => {
            return res.data;
          });
      },
      mobileAppDownloadUrl: function(id) {
        if (!window.MCP_URL) {
          return Promise.reject('No MCP URL');
        }

        return $http
          .post(`${window.MCP_URL}/build/${id}/download`, {}, requestConfig)
          .then(res => {
            res.data.url = `${window.MCP_URL}${res.data.url}`;
            res.data.expires = res.data.expires * 1000;
            return res.data;
          });
      },
      createMobileApp: function(mobileApp) {
        if (!window.MCP_URL) {
          return new Promise(function(resolve, reject) {
            return reject('No MCP URL');
          });
        }
        return $http
          .post(getMobileAppsURL(), mobileApp, requestConfig)
          .then(res => {
            return res.data;
          });
      },
      createBuildConfig: function(buildConfig) {
        if (!window.MCP_URL) {
          return Promise.reject('No MCP URL');
        }
        return $http
          .post(`${window.MCP_URL}/build`, buildConfig, requestConfig)
          .then(res => {
            return res.data;
          });
      },
      mobileServices: function() {
        if (!window.MCP_URL) {
          return new Promise(function(resolve, reject) {
            return reject('No MCP URL');
          });
        }
        return $http.get(getMobileServicesURL(), requestConfig).then(res => {
          return res.data;
        });
      },
      mobileService: function(name, withIntegrations) {
        if (!window.MCP_URL) {
          return new Promise(function(resolve, reject) {
            return reject('No MCP URL');
          });
        }
        let url = getMobileServicesURL() + '/' + name;
        if (withIntegrations) {
          console.log('withIntegrations');
          url += '?withIntegrations=true';
        }
        console.log('calling ', url);
        return $http.get(url, requestConfig).then(res => {
          return res.data;
        });
      },
      createMobileService: function(mobileService) {
        return $http
          .post(getMobileServicesURL(), mobileService, requestConfig)
          .then(res => {
            return res.data;
          });
      },
      deleteService: function(service) {
        if (!window.MCP_URL) {
          return Promise.reject('No MCP URL');
        }

        return $http
          .delete(`${getMobileServicesURL()}/${service.id}`, requestConfig)
          .then(res => {
            return res.data;
          });
      },
      deleteApp: function(app) {
        if (!window.MCP_URL) {
          return Promise.reject('No MCP URL');
        }

        return $http
          .delete(`${getMobileAppsURL()}/${app.id}`, requestConfig)
          .then(res => {
            return res.data;
          });
      },
      mobileServiceMetrics: function(name) {
        // TODO: Avoid duplicate code for checking existance of MCP Url
        if (!window.MCP_URL) {
          return new Promise(function(resolve, reject) {
            return reject('No MCP URL');
          });
        }
        let url = getMobileServicesURL() + '/' + name + '/metrics';
        console.log('calling ', url);
        return $http.get(url, requestConfig).then(res => {
          // return new Promise(function(resolve, reject) {
          // var res = {
          //   data: [
          //     {
          //       x: [
          //         '2013-01-01 11:22:45',
          //         '2013-01-02 11:22:45',
          //         '2013-01-03 11:22:45',
          //         '2013-01-04 11:22:45',
          //         '2013-01-05 11:22:45',
          //         '2013-01-06 11:22:45'
          //       ],
          //       y: {
          //         data5: [90, 150, 160, 165, 180, 5]
          //       }
          //     },
          //     {
          //       x: [
          //         '2013-01-01 11:22:45',
          //         '2013-01-02 11:22:45',
          //         '2013-01-03 11:22:45',
          //         '2013-01-04 11:22:45',
          //         '2013-01-05 11:22:45',
          //         '2013-01-06 11:22:45'
          //       ],
          //       y: {
          //         data3: [70, 100, 390, 295, 170, 220]
          //       }
          //     }
          //   ]
          // };
          // console.log('res.data', res.data);

          var data = [];
          res.data.forEach(raw => {
            // x axis
            //   from -> ['val1', 'val2', val3'],
            //     to -> ['x', 'val1', 'val2', val3'],
            raw.x.unshift('x');

            _.forIn(raw.y, (val, key) => {
              var columns = [raw.x];

              // y axis
              //   from -> [30, 200, 100, 400, 150, 250]
              //     to -> ['data1', 30, 200, 100, 400, 150, 250],
              val.unshift(key);
              columns.push(val);
              data.push(columns);
            });
          });

          return data;
        });
      },
      integrateService: function(integration) {
        if (!window.MCP_URL) {
          return new Promise(function(resolve, reject) {
            return reject('No MCP URL');
          });
        }

        let url =
          getMobileServicesURL() +
          '/configure' +
          '/' +
          integration.target.name +
          '/' +
          integration.service;
        return $http.post(url, {}, requestConfig).then(res => {
          return res.data;
        });
      },
      deintegrateService: function(integration) {
        if (!window.MCP_URL) {
          return new Promise(function(resolve, reject) {
            return reject('No MCP URL');
          });
        }

        let url =
          getMobileServicesURL() +
          '/configure' +
          '/' +
          integration.target.name +
          '/' +
          integration.service;
        return $http.delete(url, requestConfig).then(res => {
          return res.data;
        });
      }
    };
  }
]);