text:
/*
 * Created on Sep 8, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package de.mhu.com.morse.cmd;

import de.mhu.com.morse.cmd.ifc.Command;
import de.mhu.com.morse.cmd.ifc.IMessageDelegator;
import de.mhu.com.morse.cmd.ifc.Weak;
import de.mhu.com.morse.net.IMessage;
import de.mhu.com.morse.net.MessageDelegatorImpl;
import de.mhu.lib.plugin.AfPlugin;
import de.mhu.lib.plugin.AfPluginException;

/**
 * @author jesus
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class SysCmd extends AfPlugin {

	private static final String CMD_SYS = "sys";
	private static final String CMD_MEM = "mem";
	// private static final String CMD_DB = "db";
	private static final String CMD_GC = "gc";
	private static final String CMD_TIME = "time";
	// private static final String CMD_LIN = "lin";

	private long started = System.currentTimeMillis();

	protected void apDestroy() throws Exception {

	}

	protected void apDisable() throws AfPluginException {

	}

	protected void apEnable() throws AfPluginException {

	}

	protected void apInit() throws Exception {

		IMessageDelegator sysMd = (IMessageDelegator)getSinglePpi( IMessageDelegator.class );

		MessageDelegatorImpl md = new MyMd( CMD_SYS );
		sysMd.registerCommand( md );

		md.registerCommand( new CmdMemory() );
		//md.registerCommand( new CmdDbInfo() );
		md.registerCommand( new CmdGc() );
		md.registerCommand( new CmdTime() );
		//md.registerCommand( new CmdLin() );

	}

	public void initFromConfig(String prefix) {
	}

	private class MyMd extends MessageDelegatorImpl {

		public MyMd(String command) {
			super(command );
		}

		public void doAction(IMessage msg, Weak weak) {
			/*
			if ( ! msg.getClient().getUserInformation().hasAdminRights() ) {
				replayToUser( msg.getClient(), weak, -100 );
				return;
			}
			*/
			super.doAction( msg, weak );
		}

	}

	private class CmdTime extends Command {

		public CmdTime() {
			super( new String[] { CMD_TIME } );
		}

		public void doAction(IMessage msg, Weak weak) throws Exception {

			IMessage ret = msg.getClient().createMessage( getCommands() );
			ret.append( String.valueOf( System.currentTimeMillis() ) );

			if ( msg.getCount() == 0 ) {
				ret.append( String.valueOf( started ) );
			} else {
				for ( int i = 0; i < msg.getCount(); i++ )
					ret.append( msg.getString( i ) ); // is not fast, canbe done in other way
			}

			replayToUser( weak, ret );

		}

	}
	private class CmdGc extends Command {

		public CmdGc() {
			super( new String[] { CMD_GC } );
		}

		public void doAction(IMessage msg, Weak weak) throws Exception {
			System.gc();
		}

	}

	/*
	private class CmdDbInfo extends Command {

		public CmdDbInfo() {
			super( new String[] { CMD_SYS, CMD_DB } );
		}

		public void doAction(Message msg, Weak weak) throws Exception {
			Message ret = new Message( getCommands() );

			if ( msg.getCount() == 0 ) {
				ret.addParameter( String.valueOf( getServer().getDBPool().getFreeSize() ) );
				ret.addParameter( String.valueOf( getServer().getDBPool().getLockedSize() ) );
				ret.addParameter( String.valueOf( getServer().getWriteConnectionInfo() ) );
			} else
			if ( "locked".equals( msg.getParameter( 0 ) ) ) {
				Object[] list = getServer().getDBPool().getLockedInfo();
				for ( int i = 0; i < list.length; i++ ) {
					ret.addParameter( ((Object[])list[i])[0].toString() );
					ret.addParameter( ((Object[])list[i])[1].toString() );
				}

			} else
			if ( "writeunlock".equals( msg.getParameter( 0 ) ) ) {
				getServer().unlockWriteConnecton();
			}
			replayToUser( msg.getClient(), ret );
		}

	}
	*/

	private class CmdMemory extends Command {

		public CmdMemory() {
			super( new String[] { CMD_MEM } );
		}

		public void doAction(IMessage msg, Weak weak) throws Exception {
			IMessage ret = msg.getClient().createMessage( getCommands() );
			ret.append( String.valueOf( Runtime.getRuntime().totalMemory() ) );
			ret.append( String.valueOf( Runtime.getRuntime().freeMemory() ) );
			replayToUser( weak, ret );
		}

	}

	/*
	private class CmdLin extends Command {

		public CmdLin() {
			super( new String[] { CMD_SYS, CMD_LIN } );
		}

		public void doAction(Message msg, Weak weak) throws Exception {
			Client[] cl = getServer().getTea().getClients();
			Message ret = new Message( getCommands() );
			ret.addParameter( String.valueOf( cl.length ) );
			for ( int i = 0; i < cl.length; i++ )
				ret.addParameter( cl[i].getUserInformation().getUserName() );

			replayToUser( msg.getClient(), ret );
		}

	}
	*/

}

redpajama_set_name: RedPajamaGithub


text:
/*
 * FluentStructure.h
 *
 *  Created on: Apr 27, 2011
 *      Author: Andreas Hertle
 */

#ifndef FLUENTSTRUCTURE_H_
#define FLUENTSTRUCTURE_H_

#include "ElementStructure.h"

namespace opl
{

class FluentStructure: public opl::ElementStructure
{
public:
    FluentStructure();
    virtual ~FluentStructure();

    Element* identify(const ParseUnit* unit) const;
};

}

#endif /* FLUENTSTRUCTURE_H_ */


text:
package s99.p01

import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import P01Option._

@RunWith(classOf[JUnitRunner])
class P01OptionSuite extends FunSuite {

  test("last element on empty returns None") {
    assert(None === last(List()))
  }

  test("last element on single element list returns head") {
    val xs = List(999)
    assert(xs.head === last(xs).get)
  }

  test("last element on multiple element list returns last element") {
    val xs = List(999, 66, 10)
    assert(xs.last === last(xs).get)
  }

  test("last element on multiple string element list returns last element") {
    val xs = List("abc", "def", "geh")
    assert(xs.last === last(xs).get)
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:fitsSystemWindows="true"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:minHeight="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:titleTextColor="@android:color/white"
        android:background="?attr/colorPrimary"
        app:contentInsetLeft="1dp"
        app:contentInsetStart="1dp">
    </android.support.v7.widget.Toolbar>

    <ImageView
        android:id="@+id/ivDetailProfile"
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:layout_margin="5dp"
        android:layout_below="@id/toolbar"/>

    <TextView
        android:id="@+id/tvDetailName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/detail_username"
        style="@style/CodeFont"
        android:layout_below="@id/toolbar"
        android:layout_marginLeft="10dp"
        android:layout_marginStart="5dp"
        android:layout_toRightOf="@+id/ivDetailProfile"
        android:layout_toEndOf="@+id/ivDetailProfile" />

    <TextView
        android:id="@+id/tvDetailScreenName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/detail_screen_name"
        android:layout_below="@id/tvDetailName"
        android:layout_marginLeft="5dp"
        android:layout_marginStart="5dp"
        android:layout_alignBottom="@+id/ivDetailProfile"
        android:layout_toRightOf="@+id/ivDetailProfile"
        android:layout_toEndOf="@+id/ivDetailProfile" />

    <TextView
        android:id="@+id/tvDetailBody"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/CodeFont"
        android:text="@string/detail_body"
        android:layout_below="@+id/ivDetailProfile"
        android:layout_alignLeft="@+id/ivDetailProfile"
        android:layout_alignStart="@+id/ivDetailProfile"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:id="@+id/tvDetailCreatedAt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/detail_created_at"
        android:layout_below="@+id/tvDetailBody"
        android:layout_alignLeft="@+id/tvDetailBody"
        android:layout_alignStart="@+id/tvDetailBody" />

</RelativeLayout>


text:
package walls;

public class BottomWall extends Wall {

	public BottomWall(String id, double x, double y, double length,
			double thickness, double magnitude, double exponent) {
		super(id, x, y, length, thickness, magnitude, exponent);
		myLength = length;
		myThickness = thickness;
	}

	@Override
	public boolean isVertical() {
		return false;
	}

	@Override
	public WallEgg layEgg(double pixels) {
		double newX = myX;
		double newY = myY + pixels;
		return new BottomWallEgg(newX, newY, myLength + 2 * pixels,
				myThickness, myMagnitude, myExponent);
	}
}


text:
package web

import (
	"encoding/json"
	"net/http"

	"github.com/Sirupsen/logrus"
	"github.com/feedhenry/mcp-standalone/pkg/mobile"
	"github.com/feedhenry/mcp-standalone/pkg/mobile/app"
	"github.com/feedhenry/mcp-standalone/pkg/web/headers"
	"github.com/gorilla/mux"
	"github.com/pkg/errors"
)

// MobileAppHandler handle mobile actions
type MobileAppHandler struct {
	logger           *logrus.Logger
	appService       *app.Service
	appCruderBuilder mobile.AppRepoBuilder
}

// NewMobileAppHandler returns a new mobile app handler
func NewMobileAppHandler(logger *logrus.Logger, app mobile.AppRepoBuilder, appService *app.Service) *MobileAppHandler {
	return &MobileAppHandler{
		logger:           logger,
		appCruderBuilder: app,
		appService:       appService,
	}
}

// Read reads a mobileapp based on an id
func (m *MobileAppHandler) Read(rw http.ResponseWriter, req *http.Request) {
	token := headers.DefaultTokenRetriever(req.Header)
	appRepo, err := m.appCruderBuilder.WithToken(token).Build()
	if err != nil {
		handleCommonErrorCases(err, rw, m.logger)
		return
	}
	params := mux.Vars(req)
	id := params["id"]
	encoder := json.NewEncoder(rw)
	if "" == id {
		http.Error(rw, "id cannot be empty", http.StatusBadRequest)
		return
	}
	app, err := appRepo.ReadByName(id)
	if err != nil {
		handleCommonErrorCases(err, rw, m.logger)
		return
	}
	if err := encoder.Encode(app); err != nil {
		handleCommonErrorCases(err, rw, m.logger)
		return
	}
}

// List will list mobile apps
func (m *MobileAppHandler) List(rw http.ResponseWriter, req *http.Request) {
	token := headers.DefaultTokenRetriever(req.Header)
	appRepo, err := m.appCruderBuilder.WithToken(token).Build()
	if err != nil {
		handleCommonErrorCases(err, rw, m.logger)
		return
	}
	apps, err := appRepo.List()
	if err != nil {
		handleCommonErrorCases(err, rw, m.logger)
		return
	}
	encoder := json.NewEncoder(rw)
	if err := encoder.Encode(apps); err != nil {
		handleCommonErrorCases(err, rw, m.logger)
		return
	}

}

// Delete will delete a mobile app
func (m *MobileAppHandler) Delete(rw http.ResponseWriter, req *http.Request) {
	token := headers.DefaultTokenRetriever(req.Header)
	appRepo, err := m.appCruderBuilder.WithToken(token).Build()
	if err != nil {
		handleCommonErrorCases(err, rw, m.logger)
		return
	}
	params := mux.Vars(req)
	id := params["id"]

	if err := m.appService.Delete(appRepo, id); err != nil {
		err = errors.Wrap(err, "mobile app handler, failed to delete app")
		handleCommonErrorCases(err, rw, m.logger)
		return
	}
}

// Create creates a mobileapp
func (m *MobileAppHandler) Create(rw http.ResponseWriter, req *http.Request) {
	token := headers.DefaultTokenRetriever(req.Header)
	appRepo, err := m.appCruderBuilder.WithToken(token).Build()
	if err != nil {
		handleCommonErrorCases(err, rw, m.logger)
		return
	}
	app := &mobile.App{}
	decoder := json.NewDecoder(req.Body)
	if err := decoder.Decode(app); err != nil {
		err = errors.Wrap(err, "mobile app create: Attempted to decode payload in app")
		handleCommonErrorCases(err, rw, m.logger)
		return
	}
	app.MetaData = map[string]string{}
	if err := m.appService.Create(appRepo, app); err != nil {
		err = errors.Wrap(err, "mobile app handler, failed to create app")
		handleCommonErrorCases(err, rw, m.logger)
		return
	}

	rw.WriteHeader(http.StatusCreated)
}

// Update will update a mobile app
func (m *MobileAppHandler) Update(rw http.ResponseWriter, req *http.Request) {

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Enterographa rimata f. rimata

### Remarks
null


text:
"use strict";
var SpecificationBase = require('../specification-base');
var Q = require('q');

class PropertyValueMustBeUniqueInMongoQuery extends SpecificationBase {
  /**
  * @param {string} propertyName - The property that must be validated.
  * @param {Promise} mongoPromise - A promise that will return the mongo entities.
  * @param {string} notSatisfiedReason - The error reason.
  * @param {number} errorCode - The error code.
  */
  constructor(propertyName, mongoPromise, notSatisfiedReason, errorCode) {

    super((target) => {
      let deferred = Q.defer();
      let filter = {};
      filter[propertyName] = target[propertyName];

      Q(mongoPromise(filter)).then((entities) => {
        let isSatisfied = !entities || entities.length === 0;
        if (!isSatisfied) {
          this.notSatisfiedReason = notSatisfiedReason;
          this.errorCode = errorCode;
        }
        deferred.resolve(isSatisfied);
      }, (err) => {
        deferred.reject(err);
      });

      return deferred.promise;
    });
  }
}

module.exports = PropertyValueMustBeUniqueInMongoQuery;


text:
module ConceptSpace
  module ActiveRecordLike
    module Adapter

class Verbose
  attr_reader :target_class
  def initialize(a_target_class)
    @target_class = a_target_class
  end
  def method_missing(method_name, *args)
    if RAILS_ENV=='test' || RAILS_ENV=='development'
      info = "Call: #{method_name} (#{args.inspect})"
      puts info
      Rails.logger.debug info
    end
    target_class.send(method_name, *args)
  end
  def respond_to?
    true
  end
end

    end
  end
end


text:
package com.jvoid.attributes.controller;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jvoid.attributes.attribute.model.Attributes;
import com.jvoid.attributes.attribute.service.AttributesService;

@Controller
@RequestMapping("/")
public class JVoidAttributeController {

	@Autowired
	private AttributesService attributesService;

	public void setAttributesService(AttributesService attributesService){
		this.attributesService = attributesService;
	}

	@RequestMapping
    public @ResponseBody String list() {
		System.out.println("Helloo...jvoid-attributes");
		return "Hello";
    }

	@RequestMapping(value = "listProductAttriburtes", method = RequestMethod.GET)
	public @ResponseBody String listProductAttriburtes() {
		List<Attributes> listAttributes = this.attributesService.listAttributes();
		JSONObject attrs = getAttributesList(listAttributes, "Product");
		return attrs.toString();
	}

	@RequestMapping(value = "listCustomerAttriburtes", method = RequestMethod.GET)
	public @ResponseBody String listCustomerAttriburtes() {
		List<Attributes> listAttributes = this.attributesService.listAttributes();
		JSONObject attrs = getAttributesList(listAttributes, "Customer");
		return attrs.toString();
	}

	public JSONObject getAttributesList(List<Attributes> listAttributes, String type){
		JSONObject obj = new JSONObject();
		JSONArray arr = new JSONArray();
		for(int i=0; i<listAttributes.size(); i++) {
			if ( listAttributes.get(i).getType().equalsIgnoreCase(type) ){
				try {
					JSONObject temp = new JSONObject();
					temp.put("id", listAttributes.get(i).getId());
					temp.put("code", listAttributes.get(i).getCode());
					arr.put(temp);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		try {
			obj.put("Attributes", arr);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return obj;
	}
}


text:
from netlib import encoding

def test_identity():
    assert b"string" == encoding.decode("identity", b"string")
    assert b"string" == encoding.encode("identity", b"string")
    assert b"string" == encoding.encode(b"identity", b"string")
    assert b"string" == encoding.decode(b"identity", b"string")
    assert not encoding.encode("nonexistent", b"string")
    assert not encoding.decode("nonexistent encoding", b"string")

def test_gzip():
    assert b"string" == encoding.decode(
        "gzip",
        encoding.encode(
            "gzip",
            b"string"
        )
    )
    assert encoding.decode("gzip", b"bogus") is None

def test_deflate():
    assert b"string" == encoding.decode(
        "deflate",
        encoding.encode(
            "deflate",
            b"string"
        )
    )
    assert b"string" == encoding.decode(
        "deflate",
        encoding.encode(
            "deflate",
            b"string"
        )[2:-4]
    )
    assert encoding.decode("deflate", b"bogus") is None


text:
import {
  clickFirstActionsButtonPublic,
  clickFirstActionsButtonPrivate,
  goToTab,
  goToUnexpandedSidebarEntry,
  resetDB,
  setTokenUserViewPort,
} from '../../support/commands';

describe('Dockstore hosted workflows', () => {
  resetDB();
  setTokenUserViewPort();

  beforeEach(() => {
    cy.visit('/my-workflows');

    cy.intercept({
      method: 'GET',
      url: /workflows\/.+\/zip\/.+/,
    }).as('downloadZip');
  });

  function getWorkflow() {
    goToUnexpandedSidebarEntry('A2', /hosted/);
  }

  // using an ugly name to flex workflow naming functionality a bit
  const NEW_WORKFLOW_NAME = 'new_Hosted-workflow-8_part-2';

  // Ensure tabs are correct for the hosted workflow, try adding a version
  describe('Should be able to register a hosted workflow and add files to it', () => {
    it('Register the workflow', () => {
      // Select the hosted workflow
      getWorkflow();

      // Should not be able to publish (No valid versions)
      cy.get('#publishButton').should('be.disabled');

      // Check content of the info tab
      cy.contains('Mode: Hosted');

      // Should not be able to download zip
      cy.get('#downloadZipButton').should('not.exist');

      // Should have alert saying there are no versions
      goToTab('Versions');
      cy.contains('To see versions, please add a new version in the Files tab.');

      // Add a new version with one descriptor
      goToTab('Files');
      cy.get('#editFilesButton').click();
      cy.contains('Add File').click();
      cy.wait(100);
      cy.window().then(function (window: any) {
        cy.document().then((doc) => {
          const editors = doc.getElementsByClassName('ace_editor');
          const wdlDescriptorFile = `task md5 { File inputFile command { /bin/my_md5sum \${inputFile} } output { File value = \"md5sum.txt\" } runtime { docker: \"quay.io/agduncan94/my-md5sum\" } } workflow ga4ghMd5 { File inputFile call md5 { input: inputFile=inputFile } }`;
          window.ace.edit(editors[0]).setValue(wdlDescriptorFile, -1);
        });
      });

      cy.get('#saveNewVersionButton').click();
      cy.get('#workflow-path').contains('dockstore.org/A2/hosted-workflow:1');
      // Should have a version 1
      goToTab('Versions');
      cy.get('table').contains('span', /\b1\b/);

      // Should be able to download zip
      goToTab('Info');

      cy.get('#downloadZipButton').should('be.visible');

      // Verify that clicking calls the correct endpoint
      // https://github.com/ga4gh/dockstore/issues/2050
      cy.get('#downloadZipButton').click();

      cy.wait('@downloadZip').its('response.statusCode').should('eq', 200);

      // Add a new version with a second descriptor and a test json
      goToTab('Files');
      cy.get('#editFilesButton').click();
      cy.contains('Add File').click();
      cy.window().then(function (window: any) {
        cy.document().then((doc) => {
          const editors = doc.getElementsByClassName('ace_editor');
          const wdlDescriptorFile = `task test { File inputFile command { /bin/my_md5sum \${inputFile} } output { File value = \"md5sum.txt\" } runtime { docker: \"quay.io/agduncan94/my-md5sum\" } } workflow ga4ghMd5 { File inputFile call test { input: inputFile=inputFile } }`;
          window.ace.edit(editors[1]).setValue(wdlDescriptorFile, -1);
        });
      });

      goToTab('Test Parameter Files');
      cy.wait(500);
      cy.contains('Add File').click();
      cy.window().then(function (window: any) {
        cy.document().then((doc) => {
          const editors = doc.getElementsByClassName('ace_editor');
          const testParameterFile = '{}';
          window.ace.edit(editors[0]).setValue(testParameterFile, -1);
        });
      });

      cy.get('#saveNewVersionButton').click();
      cy.get('#workflow-path').contains('dockstore.org/A2/hosted-workflow:2');
      // Should have a version 2
      goToTab('Versions');
      cy.get('table').contains('span', /\b2\b/);

      // Should be able to publish
      cy.get('#publishButton').should('not.be.disabled');

      // Try deleting a file (.wdl file)
      goToTab('Files');
      cy.get('#editFilesButton').click();
      cy.get('.delete-editor-file').first().click();
      cy.get('#saveNewVersionButton').click();
      cy.get('#workflow-path').contains('dockstore.org/A2/hosted-workflow:3');

      // Testing for one ace editor as mat-tab hides the second element due to it being in a different tab
      cy.get('.ace_editor').should('have.length', 1);

      // New version should be added
      goToTab('Versions');
      cy.get('table').contains('span', /\b3\b/);

      // Delete a version
      clickFirstActionsButtonPrivate();
      cy.contains('Delete').click();
      // Automatically selects the newest version that wasn't the one that was just deleted
      cy.get('#workflow-path').contains('dockstore.org/A2/hosted-workflow:2');
      // Version 3 should no longer exist since it was just deleted
      goToTab('Versions');
      cy.get('table').find('a').should('not.contain', '3');

      // Reload the hosted workflow to test https://github.com/dockstore/dockstore/issues/2854
      cy.reload();

      goToTab('Files');
      cy.contains('/Dockstore.wdl').should('be.visible');
    });
    it('Create a new hosted workflow', () => {
      cy.get('#registerWorkflowButton').should('be.visible').should('be.enabled').click();
      cy.get('#3-register-workflow-option').should('be.visible').click();
      cy.contains('button', 'Next').click();
      cy.get('#hostedWorkflowRepository').type(NEW_WORKFLOW_NAME);
      cy.contains('button', 'Register Workflow').click();
    });
    it('Add files to hosted workflow', () => {
      // navigate to workflow
      cy.get('.mat-expansion-panel');
      cy.contains('.mat-expansion-panel', 'user_A').click();
      cy.contains('a', NEW_WORKFLOW_NAME).click();

      // Check content of the info tab
      cy.contains('Mode: Hosted');

      // Add a new version with 3 descriptors
      goToTab('Files');
      cy.get('#editFilesButton').click();

      // there should be no descriptors files
      cy.get('app-code-editor').should('have.length', 0);

      // add first file. This will be the primary descriptor, so we wont need to give it a custom name
      cy.contains('Add File').click();

      // add a bunch of new files
      for (let i = 0; i < 3; i++) {
        cy.contains('Add File').click();
        cy.wait(100); // focus is pulled to the content box of the editor shortly after adding a file, wait for this to occur
        cy.get('.editor-file-name').last().type(`{selectall}{backspace}/${i}.cwl{enter}`);
      }

      // save as a new version
      cy.get('#saveNewVersionButton').click();
      cy.wait(1000); // have to wait for the response from the webservice, otherwise you may get a false positive

      // should have 4 descriptors.
      cy.get('app-code-editor').should('have.length', 4);
    });
  });
});


text:
"""
seedmerepoter.py: Outputs data about a simulation to seedme

This is a adaptation of the OpenMM molecular simulation tool statedatareporter.py
"""

__author__ = "Sebastian Amara"
__version__ = "1.0"

import simtk.openmm as mm
import simtk.unit as unit
import math
import time
import seedme # import the seedme module

class SeedMeStateDataReporter(object):
    """SeedMeStateDataReporter outputs information about a simulation, such as energy and temperature, to a new SeedMe collection.

    To use it, create a SeedMeStateDataReporter, then add it to the Simulation's list of reporters.  The set of
    data to write is configurable using boolean flags passed to the constructor.  By default the data is
    written in comma-separated-value (CSV) format, but you can specify a different separator to use.
    """

    def __init__(self, collection, reportInterval, step=False, time=False, potentialEnergy=False, kineticEnergy=False, totalEnergy=False, temperature=False, volume=False, density=False,
                 progress=False, remainingTime=False, speed=False, separator=',', systemMass=None, totalSteps=None):
        """Create a SeedMeReporter.

        Parameters:
         - collection (string) The name of the collection to write to.
         - reportInterval (int) The interval (in time steps) at which to write frames
         - step (boolean=False) Whether to write the current step index to the file
         - time (boolean=False) Whether to write the current time to the file
         - potentialEnergy (boolean=False) Whether to write the potential energy to the file
         - kineticEnergy (boolean=False) Whether to write the kinetic energy to the file
         - totalEnergy (boolean=False) Whether to write the total energy to the file
         - temperature (boolean=False) Whether to write the instantaneous temperature to the file
         - volume (boolean=False) Whether to write the periodic box volume to the file
         - density (boolean=False) Whether to write the system density to the file
         - progress (boolean=False) Whether to write current progress (percent completion) to the file.
           If this is True, you must also specify totalSteps.
         - remainingTime (boolean=False) Whether to write an estimate of the remaining clock time until
           completion to the file.  If this is True, you must also specify totalSteps.
         - speed (bool=False) Whether to write an estimate of the simulation speed in ns/day to the file
         - separator (string=',') The separator to use between columns in the file
         - systemMass (mass=None) The total mass to use for the system when reporting density.  If this is
           None (the default), the system mass is computed by summing the masses of all particles.  This
           parameter is useful when the particle masses do not reflect their actual physical mass, such as
           when some particles have had their masses set to 0 to immobilize them.
         - totalSteps (int=None) The total number of steps that will be included in the simulation.  This
           is required if either progress or remainingTime is set to True, and defines how many steps will
           indicate 100% completion.
        """
        self._reportInterval = reportInterval

        self._iserror = False
        try:
            self._obj = seedme.SeedMe()
            self._obj.set_log_level('ERROR')
            result = self._obj.create_collection(title=collection)
            self._my_cid = self._obj.get_id(result)
            url = self._obj.get_url(result)
            print("Collection url is: " + url)
        except:
            self._iserror = True
            #print ('Error in SeedMe API:')

        if (progress or remainingTime) and totalSteps is None:
            raise ValueError('Reporting progress or remaining time requires total steps to be specified')

        self._step = step
        self._time = time
        self._potentialEnergy = potentialEnergy
        self._kineticEnergy = kineticEnergy
        self._totalEnergy = totalEnergy
        self._temperature = temperature
        self._volume = volume
        self._density = density
        self._progress = progress
        self._remainingTime = remainingTime
        self._speed = speed
        self._separator = separator
        self._totalMass = systemMass
        self._totalSteps = totalSteps
        self._hasInitialized = False
        self._needsPositions = False
        self._needsVelocities = False
        self._needsForces = False
        self._needEnergy = potentialEnergy or kineticEnergy or totalEnergy or temperature

    def describeNextReport(self, simulation):
        """Get information about the next report this ect will generate.

        Parameters:
         - simulation (Simulation) The Simulation to generate a report for
        Returns: A five element tuple.  The first element is the number of steps until the
        next report.  The remaining elements specify whether that report will require
        positions, velocities, forces, and energies respectively.
        """
        steps = self._reportInterval - simulation.currentStep%self._reportInterval
        return (steps, self._needsPositions, self._needsVelocities, self._needsForces, self._needEnergy)

    def report(self, simulation, state):
        """Generate a report.

        Parameters:
         - simulation (Simulation) The Simulation to generate a report for
         - state (State) The current state of the simulation
        """
        if not self._iserror:
            if not self._hasInitialized:
                self._initializeConstants(simulation)
                headers = self._constructHeaders()
                self._obj.add_ticker(self._my_cid, '#"%s"' % ('"'+self._separator+'"').join(headers))

                self._initialClockTime = time.time()
                self._initialSimulationTime = state.getTime()
                self._initialSteps = simulation.currentStep
                self._hasInitialized = True

            # Check for errors.
            self._checkForErrors(simulation, state)

            # Query for the values
            values = self._constructReportValues(simulation, state)

            # Write the values.
            try:
                self._obj.add_ticker(self._my_cid, self._separator.join(str(v) for v in values))
            except:
                pass
                #print ('Error in SeedMe API:')

    def _constructReportValues(self, simulation, state):
        """Query the simulation for the current state of our observables of interest.

        Parameters:
         - simulation (Simulation) The Simulation to generate a report for
         - state (State) The current state of the simulation

        Returns: A list of values summarizing the current state of
        the simulation, to be printed or saved. Each element in the list
        corresponds to one of the columns in the resulting CSV file.
        """
        values = []
        box = state.getPeriodicBoxVectors()
        volume = box[0][0]*box[1][1]*box[2][2]
        clockTime = time.time()
        if self._progress:
            values.append('%.1f%%' % (100.0*simulation.currentStep/self._totalSteps))
        if self._step:
            values.append(simulation.currentStep)
        if self._time:
            values.append(state.getTime().value_in_unit(unit.picosecond))
        if self._potentialEnergy:
            values.append(state.getPotentialEnergy().value_in_unit(unit.kilojoules_per_mole))
        if self._kineticEnergy:
            values.append(state.getKineticEnergy().value_in_unit(unit.kilojoules_per_mole))
        if self._totalEnergy:
            values.append((state.getKineticEnergy()+state.getPotentialEnergy()).value_in_unit(unit.kilojoules_per_mole))
        if self._temperature:
            values.append((2*state.getKineticEnergy()/(self._dof*unit.MOLAR_GAS_CONSTANT_R)).value_in_unit(unit.kelvin))
        if self._volume:
            values.append(volume.value_in_unit(unit.nanometer**3))
        if self._density:
            values.append((self._totalMass/volume).value_in_unit(unit.gram/unit.item/unit.milliliter))
        if self._speed:
            elapsedDays = (clockTime-self._initialClockTime)/86400.0
            elapsedNs = (state.getTime()-self._initialSimulationTime).value_in_unit(unit.nanosecond)
            if elapsedDays > 0.0:
                values.append('%.3g' % (elapsedNs/elapsedDays))
            else:
                values.append('--')
        if self._remainingTime:
            elapsedSeconds = clockTime-self._initialClockTime
            elapsedSteps = simulation.currentStep-self._initialSteps
            if elapsedSteps == 0:
                value = '--'
            else:
                estimatedTotalSeconds = (self._totalSteps-self._initialSteps)*elapsedSeconds/elapsedSteps
                remainingSeconds = int(estimatedTotalSeconds-elapsedSeconds)
                remainingDays = remainingSeconds//86400
                remainingSeconds -= remainingDays*86400
                remainingHours = remainingSeconds//3600
                remainingSeconds -= remainingHours*3600
                remainingMinutes = remainingSeconds//60
                remainingSeconds -= remainingMinutes*60
                if remainingDays > 0:
                    value = "%d:%d:%02d:%02d" % (remainingDays, remainingHours, remainingMinutes, remainingSeconds)
                elif remainingHours > 0:
                    value = "%d:%02d:%02d" % (remainingHours, remainingMinutes, remainingSeconds)
                elif remainingMinutes > 0:
                    value = "%d:%02d" % (remainingMinutes, remainingSeconds)
                else:
                    value = "0:%02d" % remainingSeconds
            values.append(value)
        return values

    def _initializeConstants(self, simulation):
        """Initialize a set of constants required for the reports

        Parameters
        - simulation (Simulation) The simulation to generate a report for
        """
        system = simulation.system
        if self._temperature:
            # Compute the number of degrees of freedom.
            dof = 0
            for i in range(system.getNumParticles()):
                if system.getParticleMass(i) > 0*unit.dalton:
                    dof += 3
            dof -= system.getNumConstraints()
            if any(type(system.getForce(i)) == mm.CMMotionRemover for i in range(system.getNumForces())):
                dof -= 3
            self._dof = dof
        if self._density:
            if self._totalMass is None:
                # Compute the total system mass.
                self._totalMass = 0*unit.dalton
                for i in range(system.getNumParticles()):
                    self._totalMass += system.getParticleMass(i)
            elif not unit.is_quantity(self._totalMass):
                self._totalMass = self._totalMass*unit.dalton

    def _constructHeaders(self):
        """Construct the headers for the CSV output

        Returns: a list of strings giving the title of each observable being reported on.
        """
        headers = []
        if self._progress:
            headers.append('Progress (%)')
        if self._step:
            headers.append('Step')
        if self._time:
            headers.append('Time (ps)')
        if self._potentialEnergy:
            headers.append('Potential Energy (kJ/mole)')
        if self._kineticEnergy:
            headers.append('Kinetic Energy (kJ/mole)')
        if self._totalEnergy:
            headers.append('Total Energy (kJ/mole)')
        if self._temperature:
            headers.append('Temperature (K)')
        if self._volume:
            headers.append('Box Volume (nm^3)')
        if self._density:
            headers.append('Density (g/mL)')
        if self._speed:
            headers.append('Speed (ns/day)')
        if self._remainingTime:
            headers.append('Time Remaining')
        return headers

    def _checkForErrors(self, simulation, state):
        """Check for errors in the current state of the simulation

        Parameters
         - simulation (Simulation) The Simulation to generate a report for
         - state (State) The current state of the simulation
        """
        if self._needEnergy:
            energy = (state.getKineticEnergy()+state.getPotentialEnergy()).value_in_unit(unit.kilojoules_per_mole)
            if math.isnan(energy):
                raise ValueError('Energy is NaN')
            if math.isinf(energy):
                raise ValueError('Energy is infinite')

    def _del_(self):
        print('deleting')


text:
{% extends "layout.html" %}

{% block content %}
    {% include "catalogue/catalogue.html" %}
{% endblock %}


text:
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gallio.Framework;
using Gallio.Framework.Pattern;
using MbUnit.Framework;
using Rhino.Mocks;
using Gallio.Common.Reflection;

#pragma warning disable 0414
namespace Gallio.Tests.Framework.Pattern
{
    [TestsOn(typeof(FixtureMemberInvoker<>))]
    public class FixtureMemberInvokerTest
    {
        private IPatternScope ArrangeMockScope()
        {
            var mockScope = MockRepository.GenerateStub<IPatternScope>();
            var mockTestBuilder = MockRepository.GenerateStub<ITestBuilder>();
            mockScope.Stub(x => x.TestBuilder).Return(mockTestBuilder);
            mockTestBuilder.Stub(x => x.CodeElement).Return(Reflector.Wrap(GetType()));
            return mockScope;
        }

        [Test]
        [Row(typeof(int), "PublicInstancePropertyInt32", null, 123)]
        [Row(typeof(int), "PrivateInstancePropertyInt32", null, 123)]
        [Row(typeof(int), "PublicInstanceMethodInt32", null, 123)]
        [Row(typeof(int), "PrivateInstanceMethodInt32", null, 123)]
        [Row(typeof(int), "PublicInstanceFieldInt32", null, 123)]
        [Row(typeof(int), "PrivateInstanceFieldInt32", null, 123)]
        [Row(typeof(int), "PublicStaticPropertyInt32", null, 123)]
        [Row(typeof(int), "PrivateStaticPropertyInt32", null, 123)]
        [Row(typeof(int), "PublicStaticMethodInt32", null, 123)]
        [Row(typeof(int), "PrivateStaticMethodInt32", null, 123)]
        [Row(typeof(int), "PublicStaticFieldInt32", null, 123)]
        [Row(typeof(int), "PrivateStaticFieldInt32", null, 123)]
        [Row(typeof(int), "PublicStaticPropertyInt32", typeof(Sample), 123)]
        [Row(typeof(int), "PrivateStaticPropertyInt32", typeof(Sample), 123)]
        [Row(typeof(int), "PublicStaticMethodInt32", typeof(Sample), 123)]
        [Row(typeof(int), "PrivateStaticMethodInt32", typeof(Sample), 123)]
        [Row(typeof(int), "PublicStaticFieldInt32", typeof(Sample), 123)]
        [Row(typeof(int), "PrivateStaticFieldInt32", typeof(Sample), 123)]
        [Row(typeof(string), "PublicInstancePropertyString", null, "Hello")]
        [Row(typeof(string), "PrivateInstancePropertyString", null, "Hello")]
        [Row(typeof(string), "PublicInstanceMethodString", null, "Hello")]
        [Row(typeof(string), "PrivateInstanceMethodString", null, "Hello")]
        [Row(typeof(string), "PublicInstanceFieldString", null, "Hello")]
        [Row(typeof(string), "PrivateInstanceFieldString", null, "Hello")]
        [Row(typeof(string), "PrivateStaticFieldString", null, "Hello")]
        [Row(typeof(string), "PublicStaticPropertyString", null, "Hello")]
        [Row(typeof(string), "PrivateStaticPropertyString", null, "Hello")]
        [Row(typeof(string), "PublicStaticMethodString", null, "Hello")]
        [Row(typeof(string), "PrivateStaticMethodString", null, "Hello")]
        [Row(typeof(string), "PublicStaticFieldString", null, "Hello")]
        [Row(typeof(string), "PrivateStaticFieldString", typeof(Sample), "Hello")]
        [Row(typeof(string), "PublicStaticPropertyString", typeof(Sample), "Hello")]
        [Row(typeof(string), "PrivateStaticPropertyString", typeof(Sample), "Hello")]
        [Row(typeof(string), "PublicStaticMethodString", typeof(Sample), "Hello")]
        [Row(typeof(string), "PrivateStaticMethodString", typeof(Sample), "Hello")]
        [Row(typeof(string), "PublicStaticFieldString", typeof(Sample), "Hello")]
        public void Invoke_argument_less_member<T>(string memberName, Type source, T expectedValue)
        {
            var mockScope = ArrangeMockScope();
            var invoker = new FixtureMemberInvoker<T>(source, mockScope, memberName);
            T actualValue = invoker.Invoke();
            Assert.AreEqual<T>(expectedValue, actualValue);
        }

        [Test]
        [Row(123, false)]
        [Row(124, true)]
        public void Invoke_member_with_argument(int input, bool expectedResult)
        {
            var mockScope = ArrangeMockScope();
            var invoker = new FixtureMemberInvoker<bool>(null, mockScope, "IsOdd");
            bool actualResult = invoker.Invoke(input);
            Assert.AreEqual(expectedResult, actualResult);
        }

        [Test]
        [Row(123.3d, false)]
        [Row(123.7d, true)]
        [Row(124.1d, true)]
        [Row(124.6d, false)]
        public void Invoke_member_with_converted_argument(double input, bool expectedResult)
        {
            var mockScope = ArrangeMockScope();
            var invoker = new FixtureMemberInvoker<bool>(null, mockScope, "IsOdd");
            bool actualResult = invoker.Invoke(input);
            Assert.AreEqual(expectedResult, actualResult);
        }

        [Test]
        public void Invoke_member_not_found_should_throw_exception()
        {
            var mockScope = ArrangeMockScope();
            var invoker = new FixtureMemberInvoker<bool>(null, mockScope, "DoesNotExist");
            Assert.Throws<PatternUsageErrorException>(() => invoker.Invoke());
        }

        [Test]
        public void Invoke_member_with_invalid_number_of_arguments_should_throw_exception()
        {
            var mockScope = ArrangeMockScope();
            var invoker = new FixtureMemberInvoker<bool>(null, mockScope, "Add");
            Assert.Throws<PatternUsageErrorException>(() => invoker.Invoke(1, 2));
        }

        [Test]
        public void Invoke_member_with_incompatible_argument_should_throw_exception()
        {
            var mockScope = ArrangeMockScope();
            var invoker = new FixtureMemberInvoker<bool>(null, mockScope, "Add");
            Assert.Throws<PatternUsageErrorException>(() => invoker.Invoke(1, new object(), 3));
        }

        #region Invocation samples

        public int PublicInstanceFieldInt32 = 123;
        public string PublicInstanceFieldString = "Hello";
        #pragma warning disable 0414
        private int PrivateInstanceFieldInt32 = 123;
        private string PrivateInstanceFieldString = "Hello";
        public static int PublicStaticFieldInt32 = 123;
        public static string PublicStaticFieldString = "Hello";
        private static int PrivateStaticFieldInt32 = 123;
        private static string PrivateStaticFieldString = "Hello";

        public int PublicInstancePropertyInt32
        {
            get
            {
                return 123;
            }
        }

        public string PublicInstancePropertyString
        {
            get
            {
                return "Hello";
            }
        }

        private int PrivateInstancePropertyInt32
        {
            get
            {
                return 123;
            }
        }

        private string PrivateInstancePropertyString
        {
            get
            {
                return "Hello";
            }
        }

        public static int PublicStaticPropertyInt32
        {
            get
            {
                return 123;
            }
        }

        public static string PublicStaticPropertyString
        {
            get
            {
                return "Hello";
            }
        }

        private static int PrivateStaticPropertyInt32
        {
            get
            {
                return 123;
            }
        }

        private static string PrivateStaticPropertyString
        {
            get
            {
                return "Hello";
            }
        }

        public int PublicInstanceMethodInt32()
        {
            return 123;
        }

        public string PublicInstanceMethodString()
        {
            return "Hello";
        }

        private int PrivateInstanceMethodInt32()
        {
            return 123;
        }

        private string PrivateInstanceMethodString()
        {
            return "Hello";
        }

        public static int PublicStaticMethodInt32()
        {
            return 123;
        }

        public static string PublicStaticMethodString()
        {
            return "Hello";
        }

        private static int PrivateStaticMethodInt32()
        {
            return 123;
        }

        private static string PrivateStaticMethodString()
        {
            return "Hello";
        }

        public bool IsOdd(int value)
        {
            return value % 2 == 0;
        }

        public int Add(int value1, int value2, int value3)
        {
            return value1 + value2 + value3;
        }

        private class Sample
        {
            public static int PublicStaticFieldInt32 = 123;
            public static string PublicStaticFieldString = "Hello";
            private static int PrivateStaticFieldInt32 = 123;
            private static string PrivateStaticFieldString = "Hello";

            public static int PublicStaticPropertyInt32
            {
                get
                {
                    return 123;
                }
            }

            public static string PublicStaticPropertyString
            {
                get
                {
                    return "Hello";
                }
            }

            private static int PrivateStaticPropertyInt32
            {
                get
                {
                    return 123;
                }
            }

            private static string PrivateStaticPropertyString
            {
                get
                {
                    return "Hello";
                }
            }

            public static int PublicStaticMethodInt32()
            {
                return 123;
            }

            public static string PublicStaticMethodString()
            {
                return "Hello";
            }

            private static int PrivateStaticMethodInt32()
            {
                return 123;
            }

            private static string PrivateStaticMethodString()
            {
                return "Hello";
            }
        }

        public class GenericSample<T>
        {
            public T DefaultValue
            {
                get
                {
                    return default(T);
                }
            }
        }

        #endregion
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<mxfile host="Electron" modified="2020-12-05T16:21:02.627Z" agent="5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/13.0.3 Chrome/80.0.3987.163 Electron/8.2.1 Safari/537.36" etag="GBRD-hw5kk_1deXjR4Zt" version="13.0.3" type="device">
  <diagram id="vXif-KvEa_wyBleugNwc" name="Page-1">
    <mxGraphModel dx="1106" dy="1003" grid="0" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="0" pageScale="1" pageWidth="826" pageHeight="1169" math="0" shadow="0">
      <root>
        <mxCell id="0" />
        <mxCell id="1" parent="0" />
        <mxCell id="51" value="&nbsp;loop&nbsp;" style="whiteSpace=wrap;align=left;verticalAlign=top;fontFamily=Share-Tech;fontColor=#FFFFFF;labelBackgroundColor=#666666;labelBorderColor=#666666;spacingTop=-6;spacingLeft=-2;fillColor=#F5F5F5;html=1" parent="1" vertex="1">
          <mxGeometry x="451" y="317" width="340" height="77" as="geometry" />
        </mxCell>
        <mxCell id="2" value="Client" style="shape=umlLifeline;perimeter=lifelinePerimeter;gradientDirection=north;fillColor=#4D4D4D;shadow=0;gradientColor=#B3B3B3;strokeWidth=1;strokeColor=#808080;fontFamily=Share Tech;fontColor=#FFFFFF;rounded=1;spacingRight=0;spacingLeft=15" parent="1" vertex="1">
          <mxGeometry x="10" y="10" width="120" height="455" as="geometry" />
        </mxCell>
        <mxCell id="9" value="" style="shape=umlActor;verticalLabelPosition=bottom;verticalAlign=top;strokeColor=#FFFFFF" parent="1" vertex="1">
          <mxGeometry x="46" y="18" width="10" height="20" as="geometry" />
        </mxCell>
        <mxCell id="10" value="index.php" style="shape=umlLifeline;perimeter=lifelinePerimeter;gradientDirection=north;fillColor=#4D4D4D;shadow=0;gradientColor=#B3B3B3;strokeWidth=1;strokeColor=#808080;fontFamily=Share Tech;fontColor=#FFFFFF;rounded=1" parent="1" vertex="1">
          <mxGeometry x="160" y="10" width="120" height="455" as="geometry" />
        </mxCell>
        <mxCell id="11" value="Core\Bootstrap" style="shape=umlLifeline;perimeter=lifelinePerimeter;gradientDirection=north;fillColor=#4D4D4D;shadow=0;gradientColor=#B3B3B3;strokeWidth=1;strokeColor=#808080;fontFamily=Share Tech;fontColor=#FFFFFF;rounded=1" parent="1" vertex="1">
          <mxGeometry x="295" y="10" width="120" height="455" as="geometry" />
        </mxCell>
        <mxCell id="12" value="Http\RequestHandler" style="shape=umlLifeline;perimeter=lifelinePerimeter;gradientDirection=north;fillColor=#4D4D4D;shadow=0;gradientColor=#B3B3B3;strokeWidth=1;strokeColor=#808080;fontFamily=Share Tech;fontColor=#FFFFFF;rounded=1" parent="1" vertex="1">
          <mxGeometry x="430" y="10" width="120" height="455" as="geometry" />
        </mxCell>
        <mxCell id="13" value="ServerRequest (guzzle)" style="shape=umlLifeline;perimeter=lifelinePerimeter;gradientDirection=north;fillColor=#4D4D4D;shadow=0;gradientColor=#B3B3B3;strokeWidth=1;strokeColor=#808080;fontFamily=Share Tech;fontColor=#FFFFFF;rounded=1" parent="1" vertex="1">
          <mxGeometry x="565" y="10" width="120" height="455" as="geometry" />
        </mxCell>
        <mxCell id="15" value="Http\Middleware" style="shape=umlLifeline;perimeter=lifelinePerimeter;gradientDirection=north;fillColor=#4D4D4D;shadow=0;gradientColor=#B3B3B3;strokeWidth=1;strokeColor=#808080;fontFamily=Share Tech;fontColor=#FFFFFF;rounded=1" parent="1" vertex="1">
          <mxGeometry x="700" y="10" width="120" height="455" as="geometry" />
        </mxCell>
        <mxCell id="17" value="" style="whiteSpace=wrap;fontSize=12;fontFamily=Helvetica;align=center;verticalAlign=middle;fillColor=#E6E6E6;strokeColor=#000000;fontColor=#000000;gradientColor=#FFFFFF;gradientDirection=west" parent="1" vertex="1">
          <mxGeometry x="65" y="60" width="10" height="395" as="geometry" />
        </mxCell>
        <mxCell id="20" value="" style="whiteSpace=wrap;fontSize=12;fontFamily=Helvetica;align=center;verticalAlign=middle;fillColor=#E6E6E6;strokeColor=#000000;fontColor=#000000;gradientColor=#FFFFFF;gradientDirection=west" parent="1" vertex="1">
          <mxGeometry x="215" y="90" width="10" height="22" as="geometry" />
        </mxCell>
        <mxCell id="21" value="raw HTTP request" style="endArrow=block;entryX=0.25;entryY=0;fontFamily=Share Tech;endFill=1;fontStyle=2;fontColor=#808080" parent="1" source="2" target="20" edge="1">
          <mxGeometry relative="1" as="geometry">
            <mxPoint x="80" y="90" as="sourcePoint" />
          </mxGeometry>
        </mxCell>
        <mxCell id="22" value="" style="whiteSpace=wrap;fontSize=12;fontFamily=Helvetica;align=center;verticalAlign=middle;fillColor=#E6E6E6;strokeColor=#000000;fontColor=#000000;gradientColor=#FFFFFF;gradientDirection=west" parent="1" vertex="1">
          <mxGeometry x="350" y="112" width="10" height="68" as="geometry" />
        </mxCell>
        <mxCell id="23" value="run()" style="endArrow=block;entryX=0.25;entryY=0;fontFamily=Share Tech;endFill=1;exitX=0.5;exitY=1" parent="1" source="20" target="22" edge="1">
          <mxGeometry relative="1" as="geometry">
            <mxPoint x="250" y="100" as="sourcePoint" />
          </mxGeometry>
        </mxCell>
        <mxCell id="27" value="" style="whiteSpace=wrap;fontSize=12;fontFamily=Helvetica;align=center;verticalAlign=middle;fillColor=#E6E6E6;strokeColor=#000000;fontColor=#000000;gradientColor=#FFFFFF;gradientDirection=west" parent="1" vertex="1">
          <mxGeometry x="485" y="180" width="10" height="64" as="geometry" />
        </mxCell>
        <mxCell id="29" value="handleRequest()" style="endArrow=block;entryX=0.25;entryY=0;fontFamily=Share Tech;endFill=1;exitX=0.75;exitY=1" parent="1" source="22" target="27" edge="1">
          <mxGeometry relative="1" as="geometry">
            <mxPoint x="355" y="179" as="sourcePoint" />
          </mxGeometry>
        </mxCell>
        <mxCell id="30" value="fromGlobals()" style="endArrow=block;entryX=0.25;entryY=0;fontFamily=Share Tech;endFill=1;fontSize=11;" parent="1" target="31" edge="1">
          <mxGeometry relative="1" as="geometry">
            <mxPoint x="490" y="205" as="sourcePoint" />
          </mxGeometry>
        </mxCell>
        <mxCell id="31" value="" style="whiteSpace=wrap;fontSize=12;fontFamily=Helvetica;align=center;verticalAlign=middle;fillColor=#E6E6E6;strokeColor=#000000;fontColor=#000000;gradientColor=#FFFFFF;gradientDirection=west" parent="1" vertex="1">
          <mxGeometry x="620" y="205" width="10" height="41" as="geometry" />
        </mxCell>
        <mxCell id="34" value="ServerRequest" style="edgeStyle=none;endArrow=block;dashed=1;exitX=0.25;exitY=1;fontFamily=Share Tech;endFill=1;entryX=0.75;entryY=1" parent="1" source="31" target="27" edge="1">
          <mxGeometry width="100" height="100" relative="1" as="geometry">
            <mxPoint x="10" y="95" as="sourcePoint" />
            <mxPoint x="500" y="241" as="targetPoint" />
          </mxGeometry>
        </mxCell>
        <mxCell id="41" value="Http\Response" style="edgeStyle=none;endArrow=block;dashed=1;exitX=0;exitY=1;fontFamily=Share Tech;endFill=1;entryX=1;entryY=1;entryDx=0;entryDy=0;exitDx=0;exitDy=0;" parent="1" source="48" target="46" edge="1">
          <mxGeometry width="100" height="100" relative="1" as="geometry">
            <mxPoint x="10" y="99" as="sourcePoint" />
            <mxPoint x="110" y="-1" as="targetPoint" />
          </mxGeometry>
        </mxCell>
        <mxCell id="43" value="" style="whiteSpace=wrap;fontSize=12;fontFamily=Helvetica;align=center;verticalAlign=middle;fillColor=#E6E6E6;strokeColor=#000000;fontColor=#000000;gradientColor=#FFFFFF;gradientDirection=west" parent="1" vertex="1">
          <mxGeometry x="485" y="270" width="10" height="32" as="geometry" />
        </mxCell>
        <mxCell id="45" value="boot()" style="edgeStyle=elbowEdgeStyle;elbow=horizontal;exitX=1;exitY=0.25;entryX=0.75;entryY=1;fontFamily=Share Tech;" parent="1" edge="1">
          <mxGeometry x="0.007246376811594203" width="100" height="100" relative="1" as="geometry">
            <mxPoint x="496" y="269.5" as="sourcePoint" />
            <mxPoint x="493.5" y="301" as="targetPoint" />
            <Array as="points">
              <mxPoint x="551" y="360" />
            </Array>
            <mxPoint as="offset" />
          </mxGeometry>
        </mxCell>
        <mxCell id="46" value="" style="whiteSpace=wrap;fontSize=12;fontFamily=Helvetica;align=center;verticalAlign=middle;fillColor=#E6E6E6;strokeColor=#000000;fontColor=#000000;gradientColor=#FFFFFF;gradientDirection=west" parent="1" vertex="1">
          <mxGeometry x="485" y="337" width="10" height="40" as="geometry" />
        </mxCell>
        <mxCell id="47" value="handle(request)" style="endArrow=block;entryX=0.25;entryY=0;fontFamily=Share Tech;endFill=1;exitX=0.75;exitY=0" parent="1" source="46" target="48" edge="1">
          <mxGeometry relative="1" as="geometry">
            <mxPoint x="490" y="338" as="sourcePoint" />
          </mxGeometry>
        </mxCell>
        <mxCell id="48" value="" style="whiteSpace=wrap;fontSize=12;fontFamily=Helvetica;align=center;verticalAlign=middle;fillColor=#E6E6E6;strokeColor=#000000;fontColor=#000000;gradientColor=#FFFFFF;gradientDirection=west" parent="1" vertex="1">
          <mxGeometry x="755" y="337" width="10" height="41" as="geometry" />
        </mxCell>
        <mxCell id="52" value="sendResponse()" style="edgeStyle=elbowEdgeStyle;elbow=horizontal;exitX=1;exitY=0.25;entryX=1;entryY=0.25;fontFamily=Share Tech;" parent="1" edge="1">
          <mxGeometry x="0.007246376811594203" width="100" height="100" relative="1" as="geometry">
            <mxPoint x="495" y="408.5" as="sourcePoint" />
            <mxPoint x="495" y="436.5" as="targetPoint" />
            <Array as="points">
              <mxPoint x="550" y="499" />
            </Array>
            <mxPoint as="offset" />
          </mxGeometry>
        </mxCell>
        <mxCell id="53" value="" style="whiteSpace=wrap;fontSize=12;fontFamily=Helvetica;align=center;verticalAlign=middle;fillColor=#E6E6E6;strokeColor=#000000;fontColor=#000000;gradientColor=#FFFFFF;gradientDirection=west" parent="1" vertex="1">
          <mxGeometry x="485" y="408" width="10" height="31" as="geometry" />
        </mxCell>
        <mxCell id="55" value="resolveRequestHandler()" style="edgeStyle=elbowEdgeStyle;elbow=horizontal;exitX=1;exitY=0.25;entryX=1;entryY=0.25;fontFamily=Share Tech;" parent="1" edge="1">
          <mxGeometry x="-0.20289855072463742" y="-15.39042977908712" width="100" height="100" relative="1" as="geometry">
            <mxPoint x="360" y="129.5" as="sourcePoint" />
            <mxPoint x="360" y="157.5" as="targetPoint" />
            <Array as="points">
              <mxPoint x="415" y="220" />
            </Array>
            <mxPoint x="8.13253012048138" y="-2.324164718846034" as="offset" />
          </mxGeometry>
        </mxCell>
        <mxCell id="58" value="echoed output" style="edgeStyle=none;endArrow=block;dashed=1;exitX=0.25;exitY=1;entryX=0.75;entryY=1;endFill=1;fontFamily=Share Tech;fontColor=#808080;fontStyle=2" parent="1" source="53" edge="1">
          <mxGeometry width="100" height="100" relative="1" as="geometry">
            <mxPoint y="43" as="sourcePoint" />
            <mxPoint x="72.5" y="439" as="targetPoint" />
          </mxGeometry>
        </mxCell>
      </root>
    </mxGraphModel>
  </diagram>
</mxfile>


text:
<?php
/*************************************************
 * Titan-2 Mini Framework
 * Routing Library
 *
 * Author 	: Turan Karatuğ
 * Web 		: http://www.titanphp.com
 * Docs 	: http://kilavuz.titanphp.com
 * Github	: http://github.com/tkaratug/titan2
 * License	: MIT
 *
 *************************************************/
namespace System\Libs\Console;

use System\Libs\Router\Router;

class Console
{
    // Params
    private $params;

    // Foreground Colors
    private $foreground_colors = [];

    // Background Colors
    private $background_colors = [];

    public function __construct()
    {
        // Setting up shell colors
		$this->foreground_colors['black']         = '0;30';
		$this->foreground_colors['dark_gray']     = '1;30';
		$this->foreground_colors['blue']          = '0;34';
		$this->foreground_colors['light_blue']    = '1;34';
		$this->foreground_colors['green']         = '0;32';
		$this->foreground_colors['light_green']   = '1;32';
		$this->foreground_colors['cyan']          = '0;36';
		$this->foreground_colors['light_cyan']    = '1;36';
		$this->foreground_colors['red']           = '0;31';
		$this->foreground_colors['light_red']     = '1;31';
		$this->foreground_colors['purple']        = '0;35';
		$this->foreground_colors['light_purple']  = '1;35';
		$this->foreground_colors['brown']         = '0;33';
		$this->foreground_colors['yellow']        = '1;33';
		$this->foreground_colors['light_gray']    = '0;37';
		$this->foreground_colors['white']         = '1;37';

		$this->background_colors['black']         = '40';
		$this->background_colors['red']           = '41';
		$this->background_colors['green']         = '42';
		$this->background_colors['yellow']        = '43';
		$this->background_colors['blue']          = '44';
		$this->background_colors['magenta']       = '45';
		$this->background_colors['cyan']          = '46';
		$this->background_colors['light_gray']    = '47';
    }

    /**
     * Run command
     * @param array $params
     * @return string
     */
    public function run($params)
    {
        $this->params = $params;

        if (!$this->params) {
            return $this->help();
        } else {
            if ($params[0] == '-h') {
                return $this->help();
            } else if ($params[0] == '-v') {
                return $this->version();
            } else if (strpos($params[0], ':') !== false) {
                $slice = explode(':', $params[0]);

                if ($slice[0] == 'make') {
                    if (array_key_exists(1, $params))
                        return $this->make($slice[1], $params[1]);
                    else
                        return $this->make($slice[1]);
                } else if ($slice[0] == 'clear') {
                    return $this->clear($slice[1]);
                } else {
                    return $this->getColoredString('Gecersiz komut. "' . $params[0] . '"', 'white', 'red');
                }
            } else {
                return $this->getColoredString('Gecersiz komut. "' . $params[0] . '"', 'white', 'red');
            }
        }
    }

    /**
     * Returns help document
     *
     * @return string
     */
    private function help()
    {
        return $this->getColoredString('// ========== [+] Titan Web Framework Console Komutlari ========== //', 'red') . "\n\n" .
               $this->getColoredString('- Make', 'yellow') . "\n" .
               $this->getColoredString('[make:controller]', 'light_blue') . "\t" . $this->getColoredString('Controller olusturmak icin kullanilir. (Orn: make:controller MyController).') . "\n" .
               $this->getColoredString('[make:model]', 'light_blue') . "\t\t" . $this->getColoredString('Model olusturmak icin kullanilir. (Orn: make:model MyModel).') . "\n" .
               $this->getColoredString('[make:middleware]', 'light_blue') . "\t" . $this->getColoredString('Middleware olusturmak icin kullanilir. (Orn: make:middleware MyMiddleware).') . "\n" .
               $this->getColoredString('[make:listener]', 'light_blue') . "\t\t" . $this->getColoredString('Listener olusturmak icin kullanilir. (Orn: make:listener MyListener).') . "\n" .
               $this->getColoredString('[make:key]', 'light_blue') . "\t\t" . $this->getColoredString('128 Bit Key olusturmak icin kullanilir.') . "\n\n" .

               $this->getColoredString('- Clear', 'yellow') . "\n" .
               $this->getColoredString('[clear:cache]', 'light_blue') . "\t\t" . $this->getColoredString('/App/Storage/Cache dizinini temizlemek icin kullanilir.') . "\n" .
               $this->getColoredString('[clear:logs]', 'light_blue') . "\t\t" . $this->getColoredString('/App/Storage/Logs dizinini temizlemek icin kullanilir.') . "\n" .

               $this->getColoredString('[-v]', 'light_blue') . "\t\t\t" . $this->getColoredString('Titan Web Framework versiyon bilgisini verir.') . "\n" .
               $this->getColoredString('[-h]', 'light_blue') . "\t\t\t" . $this->getColoredString('Tum console komutlari ile ilgili bilgi verir.') . "\n\n" .
               $this->getColoredString('// ========== [-] Titan Web Framework Console Komutlari ========== //', 'red');
    }

    /**
     * Get version of framework
     *
     * @return string
     */
    private function version()
    {
        return $this->getColoredString('Titan Web Framework: ', 'light_red') . "\t" . $this->getColoredString('v' . VERSION, 'light_blue');
    }

    /**
     * Run make commands
     *
     * @param string $command
     * @param string $params
     * @return string
     */
    private function make($command, $params = null)
    {
        switch ($command) {
            case 'controller'   : return $this->createController($params); break;
            case 'model'        : return $this->createModel($params); break;
            case 'middleware'   : return $this->createMiddleware($params); break;
            case 'listener'     : return $this->createListener($params); break;
            case 'key'          : return $this->generateCode(); break;
            default             : return $this->getColoredString('"make" komutu icin gecersiz parametre. "' . $params . '"', 'white', 'red');
        }
    }

    /**
     * Run clear commands
     *
     * @param string $params
     * @return string
     */
    private function clear($params)
    {
        switch ($params) {
            case 'cache'        : return $this->clearCache(); break;
            case 'logs'         : return $this->clearLogs(); break;
            default             : return $this->getColoredString('"clear" komutu icin gecersiz parametre. "' . $params . '"', 'white', 'red');
        }
    }

    /**
     * Create Controller
     *
     * @param string $controller
     * @return string
     */
    private function createController($controller)
    {
        $isDir          = strpos($controller, '/');

        if ($isDir) {
            $parts      = explode('/', $controller);
            $class      = end($parts);
            array_pop($parts);
            $namespace  = 'App\\Controllers\\' . implode('\\', $parts);
            $location   = 'App/Controllers/' . implode('/', $parts);
        } else {
            $namespace  = 'App\\Controllers';
            $class      = $controller;
            $location   = 'App/Controllers/' . $controller;
        }

        $file = "{$location}/{$class}.php";

        if (file_exists($file)) {
            return $this->getColoredString('Controller zaten mevcut:', 'red') . "\t" . $this->getColoredString($file);
        } else {
            $this->makeDir($location);
            $location   = $location . '/' . $class . '.php';
            $file       = fopen ($location, 'w');
            $content    = "<?php\nnamespace $namespace;\n\nuse System\\Kernel\\Controller;\nuse View;\n\nclass $class extends Controller\n{\n\n\tpublic function index()\n\t{\n\t\t\n\t}\n\n}";
            fwrite ($file, $content);
            fclose($file);

            return $this->getColoredString('Controller basariyla olusturuldu: ', 'light_blue') . "\t" . $this->getColoredString($location);
        }
    }

    /**
     * Create Model
     *
     * @param string $model
     * @return string
     */
    private function createModel($model)
    {
        $isDir          = strpos($model, '/');

        if ($isDir) {
            $parts      = explode('/', $model);
            $class      = end($parts);
            array_pop($parts);
            $namespace  = 'App\\Models\\' . implode('\\', $parts);
            $location   = 'App/Models/' . implode('/', $parts);
        } else {
            $namespace  = 'App\\Models';
            $class      = $model;
            $location   = 'App/Models';
        }

        $file = "{$location}/{$class}.php";

        if (file_exists($file))
            return $this->getColoredString('Model zaten mevcut:', 'red') . "\t" . $this->getColoredString($file);

        $this->makeDir($location);
        $location   = $location . '/' . $class . '.php';
        $file       = fopen ($location, 'w');
        $content    = "<?php\nnamespace $namespace;\n\nuse DB;\n\nclass $class\n{\n\n\t\n\n}";
        fwrite ($file, $content);
        fclose($file);

        return $this->getColoredString('Model basariyla olusturuldu: ', 'light_blue') . "\t" . $this->getColoredString($location);
    }

    /**
     * Create Middleware
     *
     * @param string $middleware
     * @return string
     */
    private function createMiddleware($middleware)
    {
        $namespace  = 'App\\Middlewares';
        $class      = $middleware;

        $location   = 'App/Middlewares/' . $middleware . '.php';

        if (file_exists($location))
            return $this->getColoredString('Middleware zaten mevcut:', 'red') . "\t" . $this->getColoredString($location);

        $file       = fopen ($location, 'w');
        $content    = "<?php\nnamespace $namespace;\n\nclass $class\n{\n\n\tpublic static function handle()\n\t{\n\t\t\n\t}\n\n}";
        fwrite ($file, $content);
        fclose($file);

        return $this->getColoredString('Middleware basariyla olusturuldu: ', 'light_blue') . "\t" . $this->getColoredString($location);
    }

    /**
     * Create Listener
     *
     * @param string $listener
     * @return string
     */
    private function createListener($listener)
    {
        $namespace  = 'App\\Listeners';
        $class      = $listener;

        $location   = 'App/Listeners/' . $listener . '.php';

        if (file_exists($location))
            return $this->getColoredString('Listener zaten mevcut:', 'red') . "\t" . $this->getColoredString($location);

        $file       = fopen ($location, 'w');
        $content    = "<?php\nnamespace $namespace;\n\nclass $class\n{\n\n\tpublic function handle()\n\t{\n\t\t\n\t}\n\n}";
        fwrite ($file, $content);
        fclose($file);

        return $this->getColoredString('Listener basariyla olusturuldu: ', 'light_blue') . "\t" . $this->getColoredString($location);
    }

    /**
     * Generate 128-bit Key
     *
     * @param int $length
     * @param boolean $strong
     */
    private function generateCode($length = 24, $strong = true)
    {
        if (function_exists('openssl_random_pseudo_bytes')) {
            $token = base64_encode(openssl_random_pseudo_bytes($length, $strong));
            if($strong == true)
                return $this->getColoredString('128 Bit Key olusturuldu: ', 'light_cyan') . "\t" . $this->getColoredString(strtr(substr($token, 0, $length), '+/=', '-_,'));
        } else {
            $characters = '0123456789';
            $characters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+';
            $charactersLength = strlen($characters)-1;
            $token = '';

            for ($i = 0; $i < $length; $i++) {
                $token .= $characters[mt_rand(0, $charactersLength)];
            }

            return $this->getColoredString('128-bit key olusturuldu: ', 'light_blue') . "\t" . $this->getColoredString($token);
        }
    }

    /**
     * Clear Cache
     *
     * @return string
     */
    private function clearCache()
    {
        array_map('unlink', glob("App/Storage/Cache/*"));
        return $this->getColoredString('Cache dizini bosaltildi.', 'light_blue');
    }

    /**
     * Clear Logs
     *
     * @return string
     */
    private function clearLogs()
    {
        array_map('unlink', glob("App/Storage/Logs/*"));
        return $this->getColoredString('Logs dizini bosaltildi.', 'light_blue');
    }

    /**
     * Returns colored string
     * @param string $string
     * @param string $foreground_color
     * @param string $background_color
     * @return string
     */
	private function getColoredString($string, $foreground_color = null, $background_color = null) {
		$colored_string = "";

		// Check if given foreground color found
		if (isset($this->foreground_colors[$foreground_color])) {
			$colored_string .= "\e[" . $this->foreground_colors[$foreground_color] . "m";
        }

		// Check if given background color found
		if (isset($this->background_colors[$background_color])) {
			$colored_string .= "\e[" . $this->background_colors[$background_color] . "m";
		}

		// Add string and end coloring
		$colored_string .=  $string . "\e[0m";

		return $colored_string . "\n";
	}

    /**
     * Get foreground colors
     * @return array
     */
	private function getForegroundColors() {
		return array_keys($this->foreground_colors);
	}

	/**
     * Get background colors
     * @return array
     */
	private function getBackgroundColors() {
		return array_keys($this->background_colors);
    }

    /**
     * Create directories recursively
     * @param string $path
     * @param int $permissions
     * @return bool
     */
    private function makeDir($path, $permissions = 0755) {
        return is_dir($path) || mkdir($path, $permissions, true);
    }

}


text:
/*
 * File:   jsLexer.h
 * Author: ghernan
 *
 * Javascript lexical analysis code
 *
 */

#pragma once

#include "ScriptPosition.h"

enum LEX_TYPES
{
    LEX_EOF = 0,
    LEX_INITIAL,
    LEX_COMMENT,

    LEX_ID = 256,
    LEX_INT,
    LEX_FLOAT,
    LEX_STR,

    LEX_EQUAL,
    LEX_TYPEEQUAL,
    LEX_NEQUAL,
    LEX_NTYPEEQUAL,
    LEX_LEQUAL,
    LEX_LSHIFT,
    LEX_GEQUAL,
    LEX_RSHIFT,
    LEX_RSHIFTUNSIGNED,
    LEX_PLUSPLUS,
    LEX_MINUSMINUS,
    LEX_ANDAND,
    LEX_OROR,
    LEX_POWER,
    LEX_CONNECT,
    LEX_SEND,

    LEX_ASSIGN_BASE = 512,

//    LEX_PLUSEQUAL = LEX_ASSIGN_BASE + '+',
//    LEX_MINUSEQUAL = LEX_ASSIGN_BASE + '-',
//    LEX_ANDEQUAL = LEX_ASSIGN_BASE + '&',
//    LEX_OREQUAL = LEX_ASSIGN_BASE + '|',
//    LEX_XOREQUAL = LEX_ASSIGN_BASE + '^',
//    LEX_LSHIFTEQUAL,
//    LEX_RSHIFTEQUAL,
    LEX_ASSIGN_MAX = 1023,

    // reserved words
    LEX_R_WORDS_BASE = 1024,
    LEX_R_IF,
    LEX_R_ELSE,
    LEX_R_DO,
    LEX_R_WHILE,
    LEX_R_FOR,
    LEX_R_BREAK,
    LEX_R_CONTINUE,
    LEX_R_FUNCTION,
    LEX_R_RETURN,
    LEX_R_VAR,
    LEX_R_CONST,
    LEX_R_TRUE,
    LEX_R_FALSE,
    LEX_R_NULL,
    LEX_R_NEW,

    //Actor system keywords
    LEX_R_ACTOR,
    LEX_R_INPUT,
    LEX_R_OUTPUT,
    LEX_R_PROTOCOL,
    LEX_R_SOCKET,

    //Classes and objects keywords.
    LEX_R_CLASS,

    //Modules keywords
    LEX_R_EXPORT,
    LEX_R_IMPORT,

    LEX_R_LIST_END /* always the last entry */
};

/// To get the string representation of a token type
std::string getTokenStr(int token);

/**
 * Javascript token. Tokens are the fragments in which input source is divided
 * and classified before being parsed.
 *
 * The lexical analysis process is implemented taking a functional approach. There
 * is no 'lexer' object. There are functions which return the current state of the
 * lex process as immutable 'CScriptToken' objects.
 * These objects are not strictly 'immutable', as they have assignment operator. But none
 * of their public methods modify its internal state.
 */
class CScriptToken
{
public:

    /**
     * The constructor doesn't make a copy of the input string, so it is important
     * not to delete input string while there are still live 'CSriptTokens' using it.
     *
     * The token created with the constructor is not parsed from input string. It is
     * just the 'initial' token. To parse the first real token, call 'next'.
     */
    CScriptToken(const char* code);

    CScriptToken(LEX_TYPES lexType, const char* code, const ScriptPosition& position, int length);

    /// Reads next token from input, and returns it.
    CScriptToken next(bool skipComments = true)const;

    /// Checks that the current token matches the expected, and returns next
    CScriptToken match(int expected_tk)const;

    ///Return a string representing the position in lines and columns of the token

    const ScriptPosition& getPosition()const
    {
        return m_position;
    }

    LEX_TYPES type()const
    {
        return m_type;
    }

    bool eof()const
    {
        return m_type == LEX_EOF;
    }
    std::string text()const;

    const char* code()const
    {
        return m_code;
    }

    std::string strValue()const;

private:
    const char* m_code;
    LEX_TYPES m_type; ///<Token type.
    ScriptPosition m_position;
    int m_length;

    CScriptToken nextDispatch()const;

    CScriptToken buildNextToken(LEX_TYPES lexType, const char* code, int length)const;
    CScriptToken parseComment(const char * code)const;
    CScriptToken parseId(const char * code)const;
    CScriptToken parseNumber(const char * code)const;
    CScriptToken parseString(const char * code)const;
    CScriptToken parseOperator(const char * code)const;

    ScriptPosition calcPosition(const char* code)const;
    CScriptToken errorAt(const char* charPos, const char* msgFormat, ...)const;
};


text:
import numpy as np
import bayesianoracle as bo
import bayesianoracle.plot as boplotter

# Import function information
from function_data import *
import os
os.system("function_data.py")

def plot_kernels(bmao, X, x0, kernel_ranges, colors):
    """ Auxillary plotting function

    Parameters
    ----------
    bmao : Bayesian model averaging optimization process
    X  : The values that have been previously traversed
    x0 : location at which we want to evaluate the kernel
    kernel_ranges : (list of scalars) the desired kernel_widths to be plotted
    """

    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection
    from matplotlib import colors as cl
    from matplotlib import gridspec

    boplt = boplotter.Plotter1D(x_range=x_range, y_range=y_range, num_points=num_points*10)
    boplt.set_bma(bmao.bma)

    ### Plot the data and the models
    fig = plt.figure(figsize=(8, 6), dpi=dpi)
    ax = plt.gca()

    legend_elements = []
    legend_texts = []

    for i in xrange(len(kernel_ranges)):
        # Plot the kernels
        kernel_line = boplt.plot_kernel(ax, x0, kernel_ranges[i], color=colors[i], ylabel=r'$k_{\gamma}\left(x,x^\prime\right)$')

        # Plot data
        data_scat = boplt.plot_kernel_at_data(ax, x0, kernel_ranges[i], color=colors[i], bool_color_cycled=True, xlabel=r'$x$')

        """
        # Add the information for legends
        legend_elements.append(kernel_line)
        legend_texts.append(r"$K_\gamma(x)$ for $\gamma = "+str(kernel_ranges[i])+"$")

        # Get the data element in the legend
        legend_elements.append(data_scat)
        legend_texts.append(r"$K_\theta(x_i)$ for $\theta = "+str(kernel_ranges[i])+"$")
        """
        legend_elements.append((kernel_line, data_scat))
        legend_texts.append(r"$\gamma = " + str(kernel_ranges[i])+'$')

    #boplt.plot_data_locations(ax, color='black', alpha=0.3, linestyle='--', zorder=1)

    # Create the x0 line
    boplt.draw_vertical_line(ax, x0, r'$x^\prime$', color='#FF9900')

    # Reverse the legend texts and elements
    legend_elements = reversed(legend_elements)
    legend_texts = reversed(legend_texts)

    # Create the legend
    legend = plt.legend(legend_elements,
                        legend_texts,
                        loc='center right', bbox_to_anchor=(1.05, 0.5), ncol=1, fancybox=True, shadow=False, scatterpoints=1)

    # Change the sizes of the scatter dots in legend
    """
    for i in xrange(len(kernel_ranges)):
        legend.legendHandles[2*i+1]._sizes = [30]
    """

    plt.setp(legend.get_texts(), fontsize=12)

    plt.savefig("KernelDisplay_figures/Kernels.png", dpi=dpi)
    plt.close(fig)

bmao = bo.optimizer.QuadraticBMAOptimizer(ndim = 1,
                                          init_kernel_range=0.25,
                                          n_int=50,
                                          precision_beta = 1000.0,
                                          constraints = [constr1, constr2],
                                          bounding_box = bounding_box,
                                          bool_compact = True,
                                          kernel_type='Gaussian')

# Center of the kernel
x0 = np.array([-0.5])

# Initialize x_next
X = None
y_hist = np.array([])

for k in xrange(X_complete.shape[1]):
    # Get next
    x_next = X_complete[:,k]
    x = x_next
    if k == 0:
        X = np.array([x_next])
    else:
        X = np.hstack([X, np.array([x_next])])

    # Get y, grad, hess from precomputed lists
    f = f_complete[k]
    grad = grad_complete[k]
    Hess = Hess_complete[k]

    y_hist = np.append(y_hist, f)

    # Add the observations to the bmao
    bmao.add_observation(x, f, grad, Hess)

kernel_ranges = [2.0, 0.25, 0.1]
colors = ['#FFBBBB', '#FF7777', '#FF0000']
#colors = ['#00FF99', '#66FFCC', '#99FFCC']

#colors = ['#FFD494','#FFB870','#FF9900']
colors = ['#DDDDDD','#AAAAAA','#666666']
#colors = ['#707070','#333333','#000000']
# Plot the Kernels
plot_kernels(bmao, X, x0, kernel_ranges, colors)