text:
var simplerScene = (function(){

    // Expression window height
    var expWindowX,expWindowY;
    var expWindowWidth,expWindowHeight;
    var ioPanel;
    var colorPanelWidth, colorPanelHeight;
    var colorPanelX, colorPanelY;
    var selectionPanelWidth, selectionPanelHeight;
    var selectionPanelX, selectionPanelY;
    var colors;
    var margin = .1;
    var elementArray = [];
    var arrowArray = [];
    var runResults = [0,0,0,0,0,0,0,0,0,0];
    var numTestCase = 0;
    var arrowHit = 0;

    var colorElements = [];
    var currentColor;
    var plusElement;
    var checkElement;
    var hoverElement;

    var dragging = false;
    var currentElementId ;
    var currentElementIndex ;
    var currentElement;

    var renderSuccess = false;
    var renderNextFrame;
    var active = false;

    var animation = false;
    function initialize(){
        var windowSize = renderer.getScreenSize();
        colors = renderer.colors;
        elementArray = [];
        dragging = false;
        expWindowY = 0;
        expWindowX = 0;
        expWindowWidth = windowSize.width - 50;
        expWindowHeight = windowSize.height * 5/8;
        colorPanelWidth = windowSize.width;
        colorPanelHeight = windowSize.height * 3/8 * 1/4;
        colorPanelX = 0;
        colorPanelY = expWindowHeight;
        selectionPanelWidth = windowSize.width;
        selectionPanelX = 0;
        selectionPanelY = expWindowHeight + colorPanelHeight;
        selectionPanelHeight = windowSize.height - selectionPanelY;
        ioPanel = {
            width: windowSize.width/2,
            height: expWindowHeight,
            x: windowSize.width/2,
            y:0,
            closedX: windowSize.width,
            openX: windowSize.width/2,
            open:true
        };
        plusElement = {
            x:windowSize.width - 40,
            y:windowSize.height/2 - 100,
            width:30,
            height:30
        };
        checkElement = {
            x: windowSize.width - 50,
            y: expWindowHeight - 50,
            width:40,
            height:40
        };
        currentColor = 0;
        setInterval(function(){
            if (active){
                animateIOPanel();
                if (renderNextFrame){
                    render();
                    animateController.nextframe();
                    animatedScene.render();
                    renderNextFrame = false;
                }
            }
        },1000/30);
        }

    function loadUIElements(foodChain){
        colorElements = [];
        var highestColor = controller.getHighestColor(foodChain);
        var boxWidth = colorPanelWidth / highestColor;
        var boxHeight = colorPanelHeight;
        for (var i = 0;i<highestColor;i++){
            var colorElement = {
                color: i,
                position:{
                    x: boxWidth * i,
                    y: colorPanelY,
                },
                width: boxWidth,
                height:boxHeight
            };
            colorElements.push(colorElement);
        }
    }

    function loadFoodChain(foodChain, testFoodChains){
        numTestCase = testFoodChains.length;
        elementArray = [];
        for (var i =0;i<foodChain.length;i++){
            addElement(foodChain[i], expWindowX + i * (expWindowWidth/foodChain.length),expWindowY,(expWindowWidth/foodChain.length), expWindowHeight);
        }
        for (var u = 0;u < testFoodChains.length;u++){
            var input = testFoodChains[u].input;
            var output = testFoodChains[u].output;
            for (var i =0;i<input.length;i++){
                addElement(input[i],
                    ioPanel.openX + i * (ioPanel.width/input.length/3),ioPanel.y + (ioPanel.height / testFoodChains.length) * u,
                    (ioPanel.width/input.length/3), ioPanel.height / testFoodChains.length, false);
            }
            for (var i =0;i<output.length;i++){
                addElement(output[i],
                    ioPanel.openX + ioPanel.width/3*2 + i * (ioPanel.width/output.length/2),ioPanel.y+ (ioPanel.height / testFoodChains.length) * u,
                    (ioPanel.width/output.length/3), ioPanel.height / testFoodChains.length, false);
            }
            addElement({
                "type": "rightArrow",
                "id": Math.floor(Math.random() * 9999999),
                "valid" : false
            }, ioPanel.openX + ioPanel.width/3, ioPanel.y + (ioPanel.height / testFoodChains.length) * u,
               ioPanel.width/3, ioPanel.height/testFoodChains.length, false);
        }
        loadUIElements(foodChain);
        addDraggys();
        render(foodChain);
    }

    function render(){
        renderer.clear("#fff");
        renderer.getContext().globalAlpha = .3;
        renderer.drawBgImg();
        renderer.getContext().globalAlpha = 1;
        renderer.drawColorPanel(colorPanelX,colorPanelY,colorPanelWidth,colorPanelHeight);
        renderer.drawSelectionPanel(selectionPanelX,selectionPanelY,selectionPanelWidth,selectionPanelHeight);
        renderer.drawPlus(plusElement.x,plusElement.y,plusElement.width,plusElement.height);
        drawElementArray();
        colorElements.forEach(function(colorElement){
            renderer.drawColorBox(
                colorElement.position.x, colorElement.position.y,
                colorElement.width, colorElement.height,
                colors[colorElement.color]
            );
        });
        renderer.drawCheck(checkElement.x, checkElement.y, checkElement.width, checkElement.height);
        renderer.drawIOPanel(ioPanel.x,ioPanel.y,ioPanel.width,ioPanel.height);
        drawIOPanelElements();

        if (dragging){
            hoverElementIndex = getObjectIndexAtId(hoverElement);
            var e = elementArray[hoverElementIndex];
            drawSingleElement(currentElement);
            if (e){
                renderer.drawHighlight(e.topLeft.x,e.topLeft.y,e.size.x,e.size.y,e.color);
            }

        }

        if (renderSuccess){
            renderer.drawSuccess(0,0,renderer.getScreenSize().width,renderer.getScreenSize().height);
        }
    }

    function drawIOPanelElements(){
        arrowHit = 0;
        for (var i = 0 ; i < elementArray.length ; i++){
            if (!elementArray[i].draggable){
                //TODO remove, this is really bad
                drawSingleElement(elementArray[i],ioPanel.x - ioPanel.openX, ioPanel.y - ioPanel.openY);
            }
        }
    }

    function addElement(element, x, y, szx, szy, draggable){
        draggable = !(draggable===false);
        if (element.type == "family" || element.type == "dummyFamily"){
            var totalElements = 0;
            if (element.gators && element.gators.length > 0){
                totalElements = element.gators.length + 1;
            }
            else{
                totalElements = 2;
            }

            // Box size for gators
            var bxx = szx;
            var bxy = szy / totalElements;

            if (bxy > bxx * .75){
                bxy = bxx * .75;
            }

            for (var i = 0;i < element.gators.length;i++){
                addElement(element.gators[i], x, y + bxy * i, bxx, bxy, draggable);
            }

            // Box size for foodChain
            bxx = szx / element.foodChain.length;

            for (var i = 0;i < element.foodChain.length;i++){
                addElement(element.foodChain[i], x + bxx * i, y + bxy * (totalElements - 1), bxx, bxy, draggable);
            }

        } else if ( element.type == "gator" ){
            addAlligator(x,y,szx,szy,colors[element.colorId],element.id, draggable);
        } else if ( element.type == "egg" ){
            addEgg(x,y,szx,szy,colors[element.colorId],element.id, draggable);
        }else if ( element.type == "dummy" ){
            addDummy(x,y,szx,szy,colors[element.colorId],element.id, draggable);
        }

        // UI Elements (TODO remove these)
        if (element.type == "trash"){
            elementArray.push({
                topLeft:{
                    x: x,
                    y: y
                },
                bottomRight:{
                    x: x + szx,
                    y: y + szy
                },
                size:{
                    x:szx,
                    y:szy
                },
                id: element.id,
                type: element.type,
                draggable: true
            });
        }
        else if (element.type == "rightArrow"){
            var arrayAddition = {
                topLeft:{
                    x: x,
                    y: y
                },
                bottomRight:{
                    x: x + szx,
                    y: y + szy
                },
                size:{
                    x:szx,
                    y:szy
                },
                id: element.id,
                type: element.type,
                valid: element.valid,
                draggable: draggable
            };
            elementArray.push(arrayAddition);
            arrowArray.push(arrayAddition);
        }

    }

    function addAlligator(x,y,w,h,color, id, draggable){
        var aw = w - w * margin * 2;
        var ah = h - h * margin * 2;

        var algSize = renderer.getAlligatorSize();
        var ih = aw * algSize.height / algSize.width;

        if (ih <= ah){
            ah = ih;
        }else{
            aw = ah * algSize.width / algSize.height;
        }

        x = x + w/2 - aw/2 ;
        y = y + h/2 - ah/2 ;

        elementArray.push({
            'topLeft': {'x' : x , 'y' : y },
            'bottomRight': {'x' : x+aw , 'y' : y+ah },
            'size': {'x': aw , 'y':ah},
            'id': id,
            'color' : color,
            'type':'gator',
            draggable: draggable
            });
    }

    function addDummy(x,y,w,h,color, id, draggable){

        var aw = w - w * margin * 2;
        var ah = h - h * margin * 2;

        x = x + w/2 - aw/2 ;
        y = y + h/2 - ah/2 ;

        elementArray.push({
            'topLeft': {'x' : x , 'y' : y },
            'bottomRight': {'x' : x+aw , 'y' : y+ah },
            'size': {'x': aw , 'y':ah},
            'id': id,
            'type':'dummy',
            draggable: draggable
            });
    }

    function addEgg(x,y,w,h,color,id, draggable){

        var aw = w - w * margin * 2;
        var ah = h - h * margin * 2;

        var eggSize = renderer.getEggSize();
        var ih = aw * eggSize.height / eggSize.width;

        if (ih <= ah){
            ah = ih;
        }else{
            aw = ah * eggSize.width / eggSize.height;
        }

        x = x + w/2 - aw/2
        y = y + h/2 - ah/2

        elementArray.push({
            'topLeft': {'x' : x , 'y' : y },
            'bottomRight': {'x' : x+aw , 'y' : y+ah },
            'size': {'x': aw , 'y':ah},
            'id': id,
            'color' : color,
            'type':'egg',
            draggable: draggable
            });

    }

    function drawElementArray(){
        for (var i = 0 ; i < elementArray.length ; i++){
            if (!(dragging && elementArray[i].draggable && elementArray[i].id == currentElementId) && elementArray[i].draggable){
                drawSingleElement(elementArray[i]);
            }
        }
    }

    //TODO remove the offset, that's just a hacky solution to the ioPanel offset problem
    function drawSingleElement(e,offx,offy){
        offx = offx || 0;
        offy = offy || 0;
        if (!e){
            return;
        }
        if ( e.type == "gator" ){
            renderer.drawAlligator(e.topLeft.x+offx,e.topLeft.y+offy,e.size.x,e.size.y,e.color);
        } else if ( e.type == "egg" ){
            renderer.drawEgg(e.topLeft.x+offx,e.topLeft.y+offy,e.size.x,e.size.y,e.color);
        } else if ( e.type == "dummy" ){
            renderer.drawDummy(e.topLeft.x+offx,e.topLeft.y+offy,e.size.x,e.size.y,e.color);
        } else if ( e.type == "trash"){
            renderer.drawTrash(e.topLeft.x+offx,e.topLeft.y+offy,e.size.x,e.size.y);
        } else if ( e.type == "rightArrow" ){
            renderer.drawRightArrow(e.topLeft.x+offx,e.topLeft.y+offy,e.size.x,e.size.y, runResults[arrowHit]);
            arrowHit ++;
        }
    }

    function animateIOPanel(){
        if (ioPanel.open){
            ioPanel.x -= (ioPanel.x - ioPanel.openX)/4;
        }else{
            ioPanel.x -= (ioPanel.x - ioPanel.closedX)/4;
        }
        // TODO this is called every frame which is bad
        renderNextFrame = true;
    }

    function closeIOPanel(){
        if (!ioPanel.open) return;
        ioPanel.open = false;
    }

    function openIOPanel(){
        if (ioPanel.open) return;
        ioPanel.open = true;

        var results = controller.runTests();
        runResults = results;
        var anyFalse = false;
        for (var i = 0; i < results.length ; i++){
            if (!results[i]){
                anyFalse = true;
            }
            arrowArray[i].valid = results[i] == 1;
        }
        if (!anyFalse){
            renderSuccess = true;
            setTimeout(function(){
                deactivate();
                menu.activate();
                menu.openChallengeMenu();
            },1000);
        }
        //     if (i < arrowArray.length){
        //         for (var a = 0 ; a < elementArray.length ; a++){
        //
        //             if (elementArray[a].id == arrowArray[i]){
        //                 elementArray[a].valid = results[i];
        //             }
        //         }
        //     }
        // }

    }

    var currentElementOffset;
    function uiMouseDown(x,y){

        if (animation){
            animation = false;
            controller.stopAnimation();
            return;
        }
        if (ioPanel.open && x > ioPanel.x){
            console.log(x,y,ioPanel.x,ioPanel.y,ioPanel.width, ioPanel.height);
            var split = 1 / numTestCase ;
            for (var i = 0 ; i < numTestCase ; i++){
                if (y > ioPanel.y + ioPanel.height*split*i){
                    controller.startAnimation(i, expWindowHeight, expWindowWidth+50, expWindowX,expWindowY );
                    animation = true;
                    return;
                }
            }

            return;
        }else if (!ioPanel.open && x > ioPanel.x - 40&&
                  y < ioPanel.y + 40){
            openIOPanel();
        }else{
            closeIOPanel();
        }

        if (x > checkElement.x && x < checkElement.x + checkElement.width &&
            y > checkElement.y && y < checkElement.y + checkElement.height){
            openIOPanel();
        }

        if (x > plusElement.x && x < plusElement.x + plusElement.width &&
            y > plusElement.y && y < plusElement.y + plusElement.height){
                controller.newFamily({
                    "type":"family",
                    "id": Math.floor(Math.random() * 9999999),
                    "gators":[{
                        "id": Math.floor(Math.random() * 9999999),
                        "type":"dummy"
                    }],
                    "foodChain":[{
                        "id": Math.floor(Math.random() * 9999999),
                        "type":"dummy"
                    }]
                });
                return;
        }

        var selectedElementId = getIdAt(x,y);
        if (selectedElementId && elementArray[getObjectIndexAtId(selectedElementId)].draggable){
            dragging = true;
            currentElementId = selectedElementId;
            currentElementIndex = getObjectIndexAtId(currentElementId);
            currentElement = JSON.parse(JSON.stringify(elementArray[currentElementIndex]));
            currentElementOffset = {
                x: x - currentElement.topLeft.x,
                y: y - currentElement.topLeft.y
            };

        }

        colorElements.forEach(function(element){
            if (x > element.position.x && x < element.position.x + element.width &&
                y > element.position.y && y < element.position.y + element.height){
                    changeDraggyColor(element.color);
            }
        });

    }

    function changeDraggyColor(newColor){
        currentColor = newColor;
        elementArray.forEach(function(element){
            if (element.id == "DRAGGY_GATOR" || element.id == "DRAGGY_EGG"){
                element.colorId = currentColor;
                element.color = colors[currentColor];
            }
        });
        renderNextFrame = true;
    }

    function addDraggys(){
        // One alligator, one egg and one family
        addElement({
            "type": "trash",
            "id":"DRAGGY_TRASH"
        },  selectionPanelX, selectionPanelY + selectionPanelHeight/4,
            selectionPanelWidth/3, selectionPanelHeight/2,
            true);
        addElement({
            type: "gator",
            id:"DRAGGY_GATOR",
            colorId: currentColor,
            color:colors[currentColor],
        },  selectionPanelX + selectionPanelWidth/4, selectionPanelY + selectionPanelHeight/4,
            selectionPanelWidth/3, selectionPanelHeight/2,
            true);
        addElement({
            type: "egg",
            id:"DRAGGY_EGG",
            colorId: currentColor,
            color:colors[currentColor],
        },  selectionPanelX + selectionPanelWidth/4*2, selectionPanelY + selectionPanelHeight/4,
            selectionPanelWidth/3, selectionPanelHeight/2,
            true);
        addElement({
            type: "dummy",
            id:"DRAGGY_DUMMY",
            colorId: currentColor,
            color:colors[currentColor],
        },  selectionPanelX + selectionPanelWidth/4*3, selectionPanelY + selectionPanelHeight/4,
            selectionPanelWidth/3, selectionPanelHeight/2,
            true);
    }

    function uiMouseUp(x,y){
        if (animation){
            return;
        }
        var selectedElementId = getIdAt(x,y);
        if (currentElementId == "DRAGGY_GATOR"){
            dragging = false;
            controller.insertElement({
                "type": "gator",
                "colorId": currentColor
            },selectedElementId);
        }else if (currentElementId == "DRAGGY_EGG"){
            dragging = false;
            controller.insertElement({
                "type": "egg",
                "colorId": currentColor
            },selectedElementId);
        }else if (currentElementId == "DRAGGY_DUMMY"){
            dragging = false;
            controller.makeFamily(selectedElementId);
        }else if (selectedElementId == "DRAGGY_TRASH"){
            dragging = false;
            controller.deleteElement(currentElementId);
        }else if (selectedElementId && elementArray[getObjectIndexAtId(selectedElementId)].draggable){
            dragging = false;
            controller.swapElements(selectedElementId,currentElementId);
        }
        else{
            dragging = false;
        }
        renderNextFrame = true;
    }

    function uiMouseMove(x,y){
        if (animation){
            return;
        }
        if (dragging){
            hoverElement = getIdAt(x,y);

            hoverElementIndex = getObjectIndexAtId(hoverElement);
            var e = elementArray[hoverElementIndex];

            currentElement.topLeft.x = x - currentElementOffset.x;
            currentElement.topLeft.y = y - currentElementOffset.y;
            currentElement.bottomRight.x = x+currentElement.size.x - currentElementOffset.x;
            currentElement.bottomRight.y = y+currentElement.size.y - currentElementOffset.y;

            renderNextFrame = true;
        }

    }

    function getIdAt(x,y){
        for (var i = 0 ; i < elementArray.length ; i++){
            var element = elementArray[i];
            if (element.draggable && x >= element.topLeft.x && x <= element.bottomRight.x){
                if (y >= element.topLeft.y && y <= element.bottomRight.y){
                    return element.id;
                }
            }
        }
        return null;
    }

    function getObjectIndexAtId(id){
        for (var i = 0 ; i < elementArray.length ; i++){
            if (elementArray[i].draggable &&  elementArray[i].id == id){
                return i;
            }
        }
        return null;
    }

    function activate(){
        active = true;
    }

    function deactivate(){
        active = false;
    }

    return {
        "initialize": initialize,
        "loadScene": loadFoodChain,
        "getIdAt": getIdAt,
        "redraw": render,
        "render": render,
        "uiMouseDown": uiMouseDown,
        "uiMouseUp": uiMouseUp,
        "uiMouseMove": uiMouseMove,
        "activate": activate,
        "deactivate": deactivate,
        "isActive": function(){return active},
        "debugGetElementArray": function(){return elementArray;}
    };
})();


text:
require('ts-node').register()

/* eslint-disable-next-line node/no-unsupported-features/node-builtins */
const worker = require('worker_threads')
const assert = require('chai').assert
const couchbase = require('../lib/couchbase')

const workerData = worker.workerData

async function doWork() {
  try {
    const cluster = await couchbase.connect(
      workerData.connStr,
      workerData.connOpts
    )
    const bucket = cluster.bucket(workerData.bucketName)
    const coll = bucket.defaultCollection()

    // increased timeout for the first operation.  sometimes the connection
    // isn't available immediately and leads to this failing.
    await coll.insert(workerData.testKey, 'bar', { timeout: 25000 })

    const getRes = await coll.get(workerData.testKey)
    assert.isObject(getRes)
    assert.isNotEmpty(getRes.cas)
    assert.deepStrictEqual(getRes.value, 'bar')

    // We intentionally omit the call to close here to test that the
    // connection is correctly cleaned up automatically when the context
    // is destroyed.  Without proper handling, this causes libuv to panic
    // due to handles that are left open.
    //await cluster.close()

    worker.parentPort.postMessage({
      success: true,
    })
  } catch (e) {
    worker.parentPort.postMessage({
      error: e,
    })
  }
}
doWork()

redpajama_set_name: RedPajamaGithub


text:
package com.appbootup.gwt.client.chart.column;

import com.amcharts.api.IsGraphDataItem;
import com.amcharts.impl.AmCharts;
import com.amcharts.impl.AmGraph;
import com.amcharts.impl.AmSerialChart;
import com.amcharts.impl.AxisAuto;
import com.amcharts.impl.CategoryAxis;
import com.amcharts.impl.ExportConfig;
import com.amcharts.impl.MenuItem;
import com.amcharts.impl.ValueAxis;
import com.amcharts.impl.event.AmChartEventJSO;
import com.amcharts.impl.event.AmChartListener;
import com.amcharts.impl.wrapper.AbstractChartWrapper;
import com.appbootup.gwt.client.ChartServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class ColumnChartWithEvents  extends AbstractChartWrapper
{
	public ColumnChartWithEvents()
	{
		ChartServiceAsync.Util.getInstance()
				.getData( "/data/columnChartWithEvents.json", new AsyncCallback<String>()
				{
					@Override
					public void onSuccess( String chartData )
					{
						JsArray<JavaScriptObject> dataProvider = JsonUtils
								.unsafeEval( chartData );
						drawChart( dataProvider );
					}

					@Override
					public void onFailure( Throwable caught )
					{
						GWT.log( "This Sucks", caught );
					}
				} );
	}

	protected void drawChart( JsArray<JavaScriptObject> chartData )
	{
		final AmSerialChart amSerialChart = AmCharts.AmSerialChart();
		amSerialChart.setTheme( "none" );
		amSerialChart.setPathToImages( AmCharts.JS_AMCHARTS_IMAGES );
		amSerialChart.setDataProvider( chartData );

		amSerialChart.setAutoMargins( false );
		amSerialChart.setMarginLeft( 30 );
		amSerialChart.setMarginRight( 8 );
		amSerialChart.setMarginTop( 10 );
		amSerialChart.setMarginBottom( 26 );

		final ValueAxis valueAxis = AmCharts.ValueAxis();
		valueAxis.setPosition( "left" );
		valueAxis.setAxisAlpha( 0.2 );
		amSerialChart.addValueAxis( valueAxis );

		amSerialChart.setStartDuration( 1 );

		final AmGraph amGraph1 = AmCharts.AmGraph();
		amGraph1.setBalloonText( "[[title]] in [[category]]:[[value]] [[additional]]" );
		amGraph1.setAlphaField( "alpha" );
		amGraph1.setDashLengthField( "dashLengthColumn" );
		amGraph1.setFillAlphas( 1 );
		amGraph1.setType( "column" );
		amGraph1.setTitle( "Income" );
		amGraph1.setValueField( "income" );
		amSerialChart.addGraph( amGraph1 );

		AmGraph amGraph2 = AmCharts.AmGraph();
		amGraph2.setBalloonText( "[[title]] in [[category]]:[[value]] [[additional]]" );
		amGraph2.setBullet( "round" );
		amGraph2.setDashLengthField( "dashLengthLine" );
		amGraph2.setLineThickness( 3 );
		amGraph2.setBulletSize( 7 );
		amGraph2.setBulletBorderAlpha( 1 );
		amGraph2.setBulletColor( "#FFFFFF" );
		amGraph2.setBulletBorderThickness( 3 );
		//TODO: Cannot see setUseLineColorForBulletBorder api in AMChart documentation.
		amGraph2.setUseLineColorForBulletBorder( true );
		amGraph2.setFillAlphas( 0 );
		amGraph2.setLineAlpha( 1 );
		amGraph2.setType( "column" );
		amGraph2.setTitle( "Expenses" );
		amGraph2.setValueField( "expenses" );
		amSerialChart.addGraph( amGraph2 );

		amSerialChart.setCategoryField( "year" );

		CategoryAxis categoryAxis = amSerialChart.getCategoryAxis();
		categoryAxis.setGridPosition( "start" );
		categoryAxis.setAxisAlpha( 0 );
		categoryAxis.setTickLength( 0 );

		ExportConfig exportConfig = new ExportConfig();
		MenuItem menuItem = new MenuItem();
		menuItem.setIcon( AmCharts.JS_AMCHARTS_IMAGES + "export.png" );
		menuItem.setFormat( "png" );
		exportConfig.addMenuItem( menuItem );
		exportConfig.setMenuTop( 0 );
		amSerialChart.setExportConfig( exportConfig );

		final AmChartListener handleClick = new AmChartListener()
		{
			@Override
			public void function( AmChartEventJSO event )
			{
				GWT.log( "handleClick - > " + event.getValue() );
			}
		};
		final AmChartListener handleOver = new AmChartListener()
		{
			@Override
			public void function( AmChartEventJSO event )
			{
				//TODO: target needs allow jsni to invoke setAttr. Target is currently a JSO.
				//event.getTarget().setAttr( "cursor", "default" );
				//event.getTarget().setAttr( "fill", "#000000" );
				GWT.log( "handleOver - > " + event.getValue() );
			}
		};
		final AmChartListener handleOut = new AmChartListener()
		{
			@Override
			public void function( AmChartEventJSO event )
			{
				//TODO: target needs allow jsni to invoke setAttr. Target is currently a JSO.
				//event.getTarget().setAttr( "cursor", "pointer" );
				//event.getTarget().setAttr( "fill", "#CC0000" );
				GWT.log( "handleOut - > " );
			}
		};

		amSerialChart.addListener( "rendered", new AmChartListener()
		{
			public void function( AmChartEventJSO event )
			{
				GWT.log( "rendered" );
				CategoryAxis categoryAxis = amSerialChart.getCategoryAxis();
				categoryAxis.addListener( "clickItem", handleClick );
				categoryAxis.addListener( "rollOverItem", handleOver );
				categoryAxis.addListener( "rollOutItem", handleOut );
			}
		} );

		amSerialChart.addListener( "clickGraphItem", new AmChartListener()
		{
			@Override
			public void function( AmChartEventJSO event )
			{
				String axisId = valueAxis.getId();
				AxisAuto axis = ( AxisAuto ) event.getClickItem()
						.getSerialDataItem().getAxis( axisId );
				String graphId = amGraph1.getId();
				IsGraphDataItem graph = axis.getGraph( graphId );
				GWT.log( graph.getSerialDataItem().getCategory() );
			}
		} );

		setAmChart( amSerialChart );
		getReadyCallback().onReady();
	}
}


text:
:warning: The `/test` directory only holds fixture data (and some simple tests).

:point_right: The specs are located in `/src/spec` and supporting code in `/src/test` (as an experiment to manage the relative paths and partial compilation mess).


text:
<?php echo Form::open(array("class"=>"form-horizontal")); ?>

	<fieldset>

			<?php echo Form::label('Setting key', 'setting_key', array('class'=>'control-label')); ?>

				<?php echo Form::input('setting_key', Input::post('setting_key', isset($setting) ? $setting->setting_key : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Setting key')); ?>

			<?php echo Form::label('Setting title', 'setting_title', array('class'=>'control-label')); ?>

				<?php echo Form::input('setting_title', Input::post('setting_title', isset($setting) ? $setting->setting_title : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Setting title')); ?>

                    <?php echo Form::label('Setting value', 'setting_value', array('class'=>'control-label')); ?>

                    <?php echo Form::textarea('setting_value', Input::post('setting_value', isset($setting) ? $setting->setting_value : ''), array('class' => 'col-md-8 form-control', 'rows' => 2, 'placeholder'=>'Setting value')); ?>

                <?php echo Form::label('Setting data type', 'setting_data_type_id', array('class'=>'control-label')); ?>
                <select class="form-control" name="setting_data_type_id" required="">
                    <option value="" selected>- - SELECT - -</option>
                    <?php foreach ($data_types as $type): ?>
                    <option value="<?php echo $type->id; ?>" <?php echo strcasecmp(Input::post('setting_data_type_id', isset($setting) ? $setting->setting_data_type_id : 0), $type->id) == 0 ? ' selected ' : ''; ?>><?php echo $type->name; ?></option>
                    <?php endforeach; ?>
                </select>

                        <?php echo Fuel\Core\Html::anchor('admin/settings', '« Settings', array('class' => 'btn btn-default')); ?>
                        <?php echo isset($setting) ? Fuel\Core\Html::anchor('admin/settings/view/'.$setting->id, 'View', array('class' => 'btn btn-warning')) : ''; ?>
			<?php echo Form::submit('submit', 'Save', array('class' => 'btn btn-primary')); ?>

	</fieldset>
<?php echo Form::close(); ?>


text:
/*
 * 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 specic language governing permissions and
 * limitations under the License.
 */

package app.metatron.discovery.domain.datasource.ingestion.job;

import com.google.common.collect.Maps;

import net.jodah.failsafe.Failsafe;
import net.jodah.failsafe.RetryPolicy;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.client.ResourceAccessException;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import app.metatron.discovery.common.GlobalObjectMapper;
import app.metatron.discovery.common.ProgressResponse;
import app.metatron.discovery.common.fileloader.FileLoaderFactory;
import app.metatron.discovery.domain.datasource.DataSource;
import app.metatron.discovery.domain.datasource.DataSourceErrorCodes;
import app.metatron.discovery.domain.datasource.DataSourceIngestionException;
import app.metatron.discovery.domain.datasource.DataSourceService;
import app.metatron.discovery.domain.datasource.DataSourceSummary;
import app.metatron.discovery.domain.datasource.Field;
import app.metatron.discovery.domain.datasource.connection.jdbc.JdbcConnectionService;
import app.metatron.discovery.domain.datasource.ingestion.HdfsIngestionInfo;
import app.metatron.discovery.domain.datasource.ingestion.HiveIngestionInfo;
import app.metatron.discovery.domain.datasource.ingestion.IngestionHistory;
import app.metatron.discovery.domain.datasource.ingestion.IngestionHistoryRepository;
import app.metatron.discovery.domain.datasource.ingestion.IngestionInfo;
import app.metatron.discovery.domain.datasource.ingestion.IngestionOptionService;
import app.metatron.discovery.domain.datasource.ingestion.LocalFileIngestionInfo;
import app.metatron.discovery.domain.datasource.ingestion.jdbc.JdbcIngestionInfo;
import app.metatron.discovery.domain.engine.DruidEngineMetaRepository;
import app.metatron.discovery.domain.engine.DruidEngineRepository;
import app.metatron.discovery.domain.engine.EngineIngestionService;
import app.metatron.discovery.domain.engine.EngineProperties;
import app.metatron.discovery.domain.engine.EngineQueryService;
import app.metatron.discovery.domain.engine.model.IngestionStatusResponse;
import app.metatron.discovery.domain.engine.model.SegmentMetaDataResponse;
import app.metatron.discovery.domain.mdm.MetadataService;
import app.metatron.discovery.domain.storage.StorageProperties;
import app.metatron.discovery.util.PolarisUtils;

import static app.metatron.discovery.domain.datasource.DataSourceErrorCodes.INGESTION_COMMON_ERROR;
import static app.metatron.discovery.domain.datasource.DataSourceErrorCodes.INGESTION_ENGINE_REGISTRATION_ERROR;
import static app.metatron.discovery.domain.datasource.DataSourceErrorCodes.INGESTION_ENGINE_TASK_ERROR;
import static app.metatron.discovery.domain.datasource.ingestion.IngestionHistory.IngestionStatus.FAILED;
import static app.metatron.discovery.domain.datasource.ingestion.IngestionHistory.IngestionStatus.SUCCESS;
import static app.metatron.discovery.domain.datasource.ingestion.job.IngestionProgress.END_INGESTION_JOB;
import static app.metatron.discovery.domain.datasource.ingestion.job.IngestionProgress.ENGINE_INIT_TASK;
import static app.metatron.discovery.domain.datasource.ingestion.job.IngestionProgress.ENGINE_REGISTER_DATASOURCE;
import static app.metatron.discovery.domain.datasource.ingestion.job.IngestionProgress.ENGINE_RUNNING_TASK;
import static app.metatron.discovery.domain.datasource.ingestion.job.IngestionProgress.FAIL_INGESTION_JOB;
import static app.metatron.discovery.domain.datasource.ingestion.job.IngestionProgress.PREPARATION_HANDLE_LOCAL_FILE;
import static app.metatron.discovery.domain.datasource.ingestion.job.IngestionProgress.PREPARATION_LOAD_FILE_TO_ENGINE;
import static app.metatron.discovery.domain.datasource.ingestion.job.IngestionProgress.START_INGESTION_JOB;

@Component
public class IngestionJobRunner {

  private static final Logger LOGGER = LoggerFactory.getLogger(IngestionJobRunner.class);

  public static final String TOPIC_INGESTION_PROGRESS = "/topic/datasources/%s/progress";

  @Autowired
  private PlatformTransactionManager platformTransactionManager;

  @Autowired
  private EngineProperties engineProperties;

  @Autowired(required = false)
  private StorageProperties storageProperties;

  @Autowired
  private FileLoaderFactory fileLoaderFactory;

  @Autowired
  private DataSourceService dataSourceService;

  @Autowired
  private JdbcConnectionService jdbcConnectionService;

  @Autowired
  private IngestionHistoryRepository historyRepository;

  @Autowired
  private DruidEngineMetaRepository engineMetaRepository;

  @Autowired
  private DruidEngineRepository engineRepository;

  @Autowired
  private EngineIngestionService ingestionService;

  @Autowired
  private EngineQueryService queryService;

  @Autowired
  private IngestionOptionService ingestionOptionService;

  @Autowired
  private MetadataService metadataService;

  private SimpMessageSendingOperations messagingTemplate;

  private TransactionTemplate transactionTemplate;

  @Value("${polaris.datasource.ingestion.retries.delay:3}")
  private Long delay;

  @Value("${polaris.datasource.ingestion.retries.maxDelay:60}")
  private Long maxDelay;

  @Value("${polaris.datasource.ingestion.retries.maxDuration:3600}")
  private Long maxDuration;

  public IngestionJobRunner() {
    // Empty Constructor
  }

  @Autowired
  public void setMessagingTemplate(SimpMessageSendingOperations messagingTemplate) {
    this.messagingTemplate = messagingTemplate;
  }

  @PostConstruct
  public void init() {
    transactionTemplate = new TransactionTemplate(platformTransactionManager);
  }

  public void ingestion(DataSource dataSource) {

    String sendTopicUri = String.format(TOPIC_INGESTION_PROGRESS, dataSource.getId());

    IngestionHistory history = null;
    Map<String, Object> results = Maps.newLinkedHashMap();
    Boolean isResultEmpty = false;

    try {

      // Temporary Process
      Thread.sleep(3000L);
      history = createNewHistory(dataSource.getId(), dataSource.getIngestionInfo());

      sendTopic(sendTopicUri, new ProgressResponse(0, START_INGESTION_JOB));
      history = updateHistoryProgress(history.getId(), START_INGESTION_JOB);

      IngestionJob ingestionJob = getJob(dataSource, history);

      sendTopic(sendTopicUri, new ProgressResponse(20, PREPARATION_HANDLE_LOCAL_FILE));
      history = updateHistoryProgress(history.getId(), PREPARATION_HANDLE_LOCAL_FILE);

      try{
        ingestionJob.preparation();
      } catch(DataSourceIngestionException e){
        //if Result is Empty, complete ingestion.
        if(e.getCode() == DataSourceErrorCodes.INGESTION_JDBC_EMPTY_RESULT_ERROR){
          LOGGER.debug("Jdbc result is empty. : {}", dataSource.getId());
          isResultEmpty = true;
        } else { throw e; }
      }

      if(!isResultEmpty){
        sendTopic(sendTopicUri, new ProgressResponse(40, PREPARATION_LOAD_FILE_TO_ENGINE));
        history = updateHistoryProgress(history.getId(), PREPARATION_LOAD_FILE_TO_ENGINE);

        ingestionJob.loadToEngine();

        sendTopic(sendTopicUri, new ProgressResponse(50, ENGINE_INIT_TASK));
        history = updateHistoryProgress(history.getId(), ENGINE_INIT_TASK);

        ingestionJob.buildSpec();

        // Call engine api.
        String taskId = ingestionJob.process();

        history = updateHistoryProgress(history.getId(), ENGINE_RUNNING_TASK, taskId);

        results.put("history", history);
        sendTopic(sendTopicUri, new ProgressResponse(70, ENGINE_RUNNING_TASK, results));

        // Check ingestion Task.
        IngestionStatusResponse statusResponse = checkIngestion(taskId);
        if (statusResponse.getStatus() == FAILED) {
          throw new DataSourceIngestionException(INGESTION_ENGINE_TASK_ERROR, "An error occurred while loading the data source : " + statusResponse.getCause());
        }

        // Check registering datasource
        sendTopic(sendTopicUri, new ProgressResponse(90, ENGINE_REGISTER_DATASOURCE));
        history = updateHistoryProgress(history.getId(), ENGINE_REGISTER_DATASOURCE, taskId);
      }

      SegmentMetaDataResponse segmentMetaData = checkDataSource(dataSource.getEngineName());
      if (segmentMetaData == null) {
        throw new DataSourceIngestionException(INGESTION_ENGINE_REGISTRATION_ERROR, "An error occurred while registering the data source");
      }

      // FIXME: fix deprecated code with DataSourceCheckJob
      DataSourceSummary summary = new DataSourceSummary(segmentMetaData);
      summary.updateSummary(segmentMetaData);

      if (BooleanUtils.isTrue(dataSource.getIncludeGeo())) {
        List<Field> geoFields = dataSource.getGeoFields();

        Map<String, Object> result = queryService.geoBoundary(dataSource.getEngineName(), geoFields);
        summary.updateGeoCorner(result);
      }

      results.put("summary", summary);
      results.put("history", history);

      // create metadata
      createMetadata(dataSource);

      ProgressResponse successResponse = new ProgressResponse(100, END_INGESTION_JOB);
      successResponse.setResults(results);

      sendTopic(sendTopicUri, successResponse);
      setSuccessProgress(history.getId(), summary);

    } catch (Exception e) {

      DataSourceIngestionException ie;
      if (!(e instanceof DataSourceIngestionException)) {
        ie = new DataSourceIngestionException(INGESTION_COMMON_ERROR, e);
      } else {
        ie = (DataSourceIngestionException) e;
      }

      try {
        history = setFailProgress(history.getId(), ie);
      } catch (TransactionException ex) {
        LOGGER.warn("Fail to save fail process : {}", ex.getMessage());
      }

      results.put("history", history);
      sendTopic(sendTopicUri, new ProgressResponse(-1, FAIL_INGESTION_JOB, results));

      LOGGER.error("Fail to ingestion : {}", history, ie);
    }

  }

  public IngestionHistory createNewHistory(final String datasourceId, final IngestionInfo ingestionInfo) {
    return transactionTemplate.execute(transactionStatus -> {
      IngestionHistory history = new IngestionHistory();
      history.setIngestionInfo(ingestionInfo);
      history.setDataSourceId(datasourceId);
      history.setStatus(IngestionHistory.IngestionStatus.RUNNING);
      history.setHostname(PolarisUtils.getLocalHostname());
      return historyRepository.saveAndFlush(history);
    });
  }

  public IngestionHistory updateHistoryProgress(final Long id, final IngestionProgress progress) {
    return updateHistoryProgress(id, progress, null);
  }

  public IngestionHistory updateHistoryProgress(final Long id, final IngestionProgress progress, final String taskId) {
    return transactionTemplate.execute(transactionStatus -> {
      IngestionHistory history = historyRepository.findOne(id);
      history.setProgress(progress);

      if (StringUtils.isNotEmpty(taskId)) {
        history.setIngestionId(taskId);
      }

      return historyRepository.save(history);
    });
  }

  public IngestionHistory setSuccessProgress(final Long historyId, final DataSourceSummary summary) {
    return transactionTemplate.execute(transactionStatus -> {
      IngestionHistory history = historyRepository.findOne(historyId);
      history.setStatus(SUCCESS);
      history.setProgress(END_INGESTION_JOB);

      dataSourceService.setDataSourceStatus(history.getDataSourceId(), DataSource.Status.ENABLED, summary, null);

      return historyRepository.save(history);
    });
  }

  public IngestionHistory setFailProgress(final Long historyId, final DataSourceIngestionException ie) {
    return transactionTemplate.execute(transactionStatus -> {
      IngestionHistory history = historyRepository.findOne(historyId);
      history.setStatus(FAILED, ie);

      dataSourceService.setDataSourceStatus(history.getDataSourceId(), DataSource.Status.FAILED,
                                            null,
                                            history.getProgress() == ENGINE_REGISTER_DATASOURCE);

      return historyRepository.save(history);
    });
  }

  public IngestionJob getJob(DataSource dataSource, IngestionHistory ingestionHistory) {
    IngestionInfo ingestionInfo = dataSource.getIngestionInfo();

    if (ingestionInfo instanceof LocalFileIngestionInfo) {
      FileIngestionJob ingestionJob = new FileIngestionJob(dataSource, ingestionHistory);
      ingestionJob.setEngineProperties(engineProperties);
      ingestionJob.setStorageProperties(storageProperties);
      ingestionJob.setEngineMetaRepository(engineMetaRepository);
      ingestionJob.setEngineRepository(engineRepository);
      ingestionJob.setFileLoaderFactory(fileLoaderFactory);
      ingestionJob.setHistoryRepository(historyRepository);
      ingestionJob.setIngestionOptionService(ingestionOptionService);
      return ingestionJob;

    } else if (ingestionInfo instanceof JdbcIngestionInfo) {
      JdbcIngestionJob ingestionJob = new JdbcIngestionJob(dataSource, ingestionHistory);
      ingestionJob.setEngineProperties(engineProperties);
      ingestionJob.setStorageProperties(storageProperties);
      ingestionJob.setEngineMetaRepository(engineMetaRepository);
      ingestionJob.setEngineRepository(engineRepository);
      ingestionJob.setFileLoaderFactory(fileLoaderFactory);
      ingestionJob.setHistoryRepository(historyRepository);
      ingestionJob.setIngestionOptionService(ingestionOptionService);
      ingestionJob.setJdbcConnectionService(jdbcConnectionService);
      return ingestionJob;

    } else if (ingestionInfo instanceof HdfsIngestionInfo) {
      HdfsIngestionJob ingestionJob = new HdfsIngestionJob(dataSource, ingestionHistory);
      ingestionJob.setEngineProperties(engineProperties);
      ingestionJob.setStorageProperties(storageProperties);
      ingestionJob.setEngineMetaRepository(engineMetaRepository);
      ingestionJob.setEngineRepository(engineRepository);
      ingestionJob.setFileLoaderFactory(fileLoaderFactory);
      ingestionJob.setHistoryRepository(historyRepository);
      ingestionJob.setIngestionOptionService(ingestionOptionService);
      return ingestionJob;

    } else if (ingestionInfo instanceof HiveIngestionInfo) {
      HiveIngestionJob ingestionJob = new HiveIngestionJob(dataSource, ingestionHistory);
      ingestionJob.setEngineProperties(engineProperties);
      ingestionJob.setStorageProperties(storageProperties);
      ingestionJob.setEngineMetaRepository(engineMetaRepository);
      ingestionJob.setEngineRepository(engineRepository);
      ingestionJob.setFileLoaderFactory(fileLoaderFactory);
      ingestionJob.setHistoryRepository(historyRepository);
      ingestionJob.setIngestionOptionService(ingestionOptionService);
      ingestionJob.setJdbcConnectionService(jdbcConnectionService);
      return ingestionJob;
    } else {
      throw new IllegalArgumentException("Not supported ingestion information.");
    }

  }

  public void sendTopic(String topicUri, ProgressResponse progressResponse) {
    LOGGER.debug("Send Progress Topic : {}, {}", topicUri, progressResponse);
    try {
      messagingTemplate.convertAndSend(topicUri,
                                       GlobalObjectMapper.writeValueAsString(progressResponse));
    } catch (Exception e) {
      LOGGER.error("Fail to send message : {}, {}", topicUri, progressResponse, e);
    }

  }

  public SegmentMetaDataResponse checkDataSource(String engineName) {

    // @formatter:off
    RetryPolicy retryPolicy = new RetryPolicy()
        .retryOn(ResourceAccessException.class)
        .retryOn(Exception.class)
        .retryIf(result -> result == null)
        .withBackoff(delay, maxDelay, TimeUnit.SECONDS)
        .withMaxDuration(maxDuration, TimeUnit.SECONDS);
		// @formatter:on

    Callable<SegmentMetaDataResponse> callable = () -> queryService.segmentMetadata(engineName);

    // @formatter:off
    SegmentMetaDataResponse response = Failsafe.with(retryPolicy)
            .onRetriesExceeded((o, throwable) -> {
              throw new DataSourceIngestionException("Retries exceed for checking datasource : " + engineName);
            })
            .onComplete((o, throwable, ctx) -> {
              if(ctx != null) {
                LOGGER.debug("Completed checking datasource({}). {} tries. Take time {} seconds.", engineName, ctx.getExecutions(), ctx.getElapsedTime().toSeconds());
              }
            })
            .get(callable);
    // @formatter:on

    return response;
  }

  public IngestionStatusResponse checkIngestion(String taskId) {

    // @formatter:off
    RetryPolicy retryPolicy = new RetryPolicy()
        .retryOn(ResourceAccessException.class)
        .retryOn(Exception.class)
        .retryIf(result -> {
          if(result instanceof IngestionStatusResponse) {
            IngestionStatusResponse response = (IngestionStatusResponse) result;
            if(response.getStatus() == SUCCESS || response.getStatus() == FAILED) {
              return false;
            }
          }
          return true;
        })
        .withBackoff(delay, maxDelay, TimeUnit.SECONDS)
        .withMaxDuration(maxDuration, TimeUnit.SECONDS);
		// @formatter:on

    Callable<IngestionStatusResponse> callable = () -> ingestionService.doCheckResult(taskId);

    // @formatter:off
    IngestionStatusResponse statusResponse = Failsafe.with(retryPolicy)
            .onRetriesExceeded((o, throwable) -> {
              throw new DataSourceIngestionException("Retries exceed for ingestion task : " + taskId);
            })
            .onComplete((o, throwable, ctx) -> {
              if(ctx != null) {
                LOGGER.debug("Completed checking task ({}). {} tries. Take time {} seconds.", taskId, ctx.getExecutions(), ctx.getElapsedTime().toSeconds());
              }
            })
            .get(callable);
    // @formatter:on

    return statusResponse;
  }

  public void createMetadata(DataSource dataSource){
    try{
      // create metadata
      metadataService.saveFromDataSource(dataSource);
    }catch (Exception e){
      LOGGER.error("Fail to create Metadata : {}", e);
    }
  }
}


text:
<?php

/**#@+ @ignore */
require_once("ID3/Frame/AbstractLink.php");
/**#@-*/

/**
 * The <i>Publishers official webpage</i> frame is a URL pointing at the
 * official webpage for the publisher.
 *
 * @package    php-reader
 * @subpackage ID3
 * @author     Sven Vollbehr <svollbehr@gmail.com>
 * @copyright  Copyright (c) 2008 The PHP Reader Project Workgroup
 * @license    http://code.google.com/p/php-reader/wiki/License New BSD License
 * @version    $Rev: 65 $
 */
final class ID3_Frame_WPUB extends ID3_Frame_AbstractLink {}


text:
/* eslint-disable prefer-arrow-callback */
(function scrollSpy() {
  const OFFSET = 10;
  let timer;
  let headingsCache;
  const findHeadings = function findHeadings() {
    return headingsCache || document.querySelectorAll('.toc-headings > li > a');
  };
  const onScroll = function onScroll() {
    if (timer) {
      // throttle
      return;
    }
    timer = setTimeout(function() {
      timer = null;
      let activeNavFound = false;
      const headings = findHeadings(); // toc nav anchors
      /**
       * On every call, try to find header right after  <-- next header
       * the one whose content is on the current screen <-- highlight this
       */
      for (let i = 0; i < headings.length; i++) {
        // headings[i] is current element
        // if an element is already active, then current element is not active
        // if no element is already active, then current element is active
        let currNavActive = !activeNavFound;
        /**
         * Enter the following check up only when an active nav header is not yet found
         * Then, check the bounding rectangle of the next header
         * The headers that are scrolled passed will have negative bounding rect top
         * So the first one with positive bounding rect top will be the nearest next header
         */
        if (currNavActive && i < headings.length - 1) {
          const heading = headings[i + 1];
          const next = decodeURIComponent(heading.href.split('#')[1]);
          const nextHeader = document.getElementById(next);

          if (nextHeader) {
            const top = nextHeader.getBoundingClientRect().top;
            currNavActive = top > OFFSET;
          } else {
            console.error('Can not find header element', {
              id: next,
              heading,
            });
          }
        }
        /**
         * Stop searching once a first such header is found,
         * this makes sure the highlighted header is the most current one
         */
        if (currNavActive) {
          activeNavFound = true;
          headings[i].classList.add('active');
        } else {
          headings[i].classList.remove('active');
        }
      }
    }, 100);
  };

  document.addEventListener('scroll', onScroll);
  document.addEventListener('resize', onScroll);
  document.addEventListener('DOMContentLoaded', function() {
    // Cache the headings once the page has fully loaded.
    headingsCache = findHeadings();
    onScroll();
  });
})();


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd">
<ldml>
	<identity>
		<version number="$Revision: 4123 $"/>
		<generation date="$Date: 2009-05-05 19:06:42 -0400 (Tue, 05 May 2009) $"/>
		<language type="en"/>
		<territory type="TT"/>
	</identity>
	<numbers>
		<currencyFormats>
			<currencyFormatLength>
				<currencyFormat>
					<pattern>¤#,##0.00</pattern>
				</currencyFormat>
			</currencyFormatLength>
		</currencyFormats>
		<currencies>
			<currency type="TTD">
				<symbol>$</symbol>
			</currency>
			<currency type="USD">
				<symbol>US$</symbol>
			</currency>
		</currencies>
	</numbers>
</ldml>


text:
<?php
header("content-type: application/x-javascript");
$absolute_path = __FILE__;
$path_to_file = explode( 'wp-content', $absolute_path );
$path_to_wp = $path_to_file[0];
require_once( $path_to_wp.'/wp-load.php' );
?>
<?php
if(isset($_GET['id']) && !empty($_GET['id']))
{
?>
jQuery(document).ready(function(){
	var player = new MediaElementPlayer('#<?php echo esc_js($_GET['id']); ?>', {
		alwaysShowControls: false,
	    features: ['playpause']
	});
	player.play();
});
<?php
}
?>


text:
package org.motechproject.tasks.dto;

import org.motechproject.tasks.domain.enums.ParameterType;

import java.util.Objects;
import java.util.SortedSet;

public class ActionParameterDto extends ParameterDto implements Comparable<ActionParameterDto> {

    private Integer order;
    private String key;
    private String value;
    private Boolean required;
    private Boolean hidden;
    private SortedSet<String> options;

    public ActionParameterDto(String displayName, ParameterType type, Integer order, String key, String value, Boolean required, Boolean hidden, SortedSet<String> options) {
        super(displayName, type);
        this.order = order;
        this.key = key;
        this.value = value;
        this.required = required;
        this.hidden = hidden;
        this.options = options;
    }

    @Override
    public int compareTo(ActionParameterDto o) {
        return Integer.compare(this.order, o.order);
    }

    public Integer getOrder() {
        return order;
    }

    public void setOrder(Integer order) {
        this.order = order;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Boolean getRequired() {
        return required;
    }

    public void setRequired(Boolean required) {
        this.required = required;
    }

    public Boolean getHidden() {
        return hidden;
    }

    public void setHidden(Boolean hidden) {
        this.hidden = hidden;
    }

    public SortedSet<String> getOptions() {
        return options;
    }

    public void setOptions(SortedSet<String> options) {
        this.options = options;
    }

    @Override
    public int hashCode() {
        return Objects.hash(order, key, value, required, hidden, options);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }

        if (!super.equals(obj)) {
            return false;
        }

        final ActionParameterDto other = (ActionParameterDto) obj;
        return Objects.equals(this.order, other.order)
                && Objects.equals(this.key, other.key)
                && Objects.equals(this.value, other.value)
                && Objects.equals(this.required, other.required)
                && Objects.equals(this.hidden, other.hidden)
                && Objects.equals(this.options, other.options);
    }
}


text:
<?php

class JavascriptConfig {

    public $extensions = array('js');

    public $commentRules = array(
        'singleline' => array(),
        'multiline' => array()
    );
}
?>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#eeeeee"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/bottomlinear"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        android:background="#DCDCDC">
        <TextView
            android:id="@+id/btn_first"
            android:layout_width="0dp"
            android:gravity="center"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:padding="-5dp"
            android:textSize="14sp"
            android:text="全部"
            />
        <TextView
            android:id="@+id/btn_second"
            android:layout_width="0dp"
            android:gravity="center"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:textSize="14sp"
            android:text="未付款"/>
        <TextView
            android:id="@+id/btn_third"
            android:layout_width="0dp"
            android:gravity="center"
            android:layout_height="fill_parent"
            android:layout_weight="1.5"
            android:textSize="14sp"
            android:text="已完成"/>
        <TextView
            android:id="@+id/btn_four"
            android:layout_width="0dp"
            android:gravity="center"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:textSize="14sp"
            android:text="已延期"/>
        <TextView
            android:id="@+id/btn_five"
            android:layout_width="0dp"
            android:gravity="center"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:textSize="14sp"
            android:text="使用中"/>

    </LinearLayout>
    <LinearLayout
        android:id="@+id/cursorarea"
        android:layout_width="fill_parent"
        android:background="#CDCDCD"
        android:orientation="horizontal"
        android:layout_height="2dp">
        <ImageView
            android:id="@+id/cursor_btn"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
        </ImageView>
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/myviewpager"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="12">
    </android.support.v4.view.ViewPager>
</LinearLayout>


text:
Run and RunOnce keys cause programs to run each time a user logs on. There are
system and per-user Run and RunOnce keys.

## Run and RunOnce keys

System Run and RunOnce keys:

```
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnceEx
```

Per-user Run and RunOnce keys:

```
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
```

Values:

Name | Data type | Description
--- | --- | ---
%NAME% | REG_SZ | Command to run or run once

### RunOnce\\Setup sub key

Contains first-boot activities after setup or when the Add/Remove Programs
Wizard was used.

```
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce\Setup
```

## RunServices and RunServicesOnce

Only on Windows 9x/Me.

Run in the background when the logon dialog box first appears, or at the boot
process stage if there is no logon.

```
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce
```

Values:

Name | Data type | Description
--- | --- | ---
%NAME% | REG_SZ | Command to run or run once

## Notes

```
description-string=commandline
```

According to [Microsoft](https://docs.microsoft.com/en-us/windows/win32/setupapi/run-and-runonce-registry-keys):

```
By default, the value of a RunOnce key is deleted before the command line is
run. You can prefix a RunOnce value name with an exclamation point (!) to defer
deletion of the value until after the command runs. Without the exclamation
point prefix, if the RunOnce operation fails the associated program will not be
asked to run the next time you start the computer.

By default, these keys are ignored when the computer is started in Safe Mode.
The value name of RunOnce keys can be prefixed with an asterisk (*) to force
the program to run even in Safe mode.
```

```
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\policies\Explorer\Run
HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows\Run
```

Installed "Programs and Features"

```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer
```

## External Links

* [Run and RunOnce Registry Keys](https://docs.microsoft.com/en-us/windows/win32/setupapi/run-and-runonce-registry-keys)


text:
.. PureScript documentation master file, created by
   sphinx-quickstart on Wed Jan 22 22:04:23 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to PureScript's documentation!
======================================

Contents:

.. toctree::
   :maxdepth: 2

   intro
   start
   types
   kinds
   syntax
   typeclasses
   patterns
   modules
   ffi
   prelude

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"os/exec"
	"os/user"
	"path/filepath"
	"runtime"
	"strings"
)

// goToolsVersion is the git revision of the x/tools subrepo we need
// to build cmd/api.  This only needs to be updated whenever a go/types
// bug fix is needed by the cmd/api tool.
const goToolsVersion = "875ff2496f865e" // aka hg 6698ca2900e2

var goroot string

func main() {
	log.SetFlags(0)
	goroot = os.Getenv("GOROOT") // should be set by run.{bash,bat}
	if goroot == "" {
		log.Fatal("No $GOROOT set.")
	}
	_, err := exec.LookPath("git")
	if err != nil {
		fmt.Println("Skipping cmd/api checks; git not available")
		return
	}

	gopath := prepGoPath()

	cmd := exec.Command("go", "install", "--tags=api_tool", "cmd/api")
	cmd.Env = append(filterOut(os.Environ(), "GOARCH", "GOPATH"), "GOPATH="+gopath)
	out, err := cmd.CombinedOutput()
	if err != nil {
		log.Fatalf("Error installing cmd/api: %v\n%s", err, out)
	}

	out, err = exec.Command("go", "tool", "api",
		"-c", file("go1", "go1.1", "go1.2", "go1.3", "go1.4"),
		"-next", file("next"),
		"-except", file("except")).CombinedOutput()
	if err != nil {
		log.Fatalf("Error running API checker: %v\n%s", err, out)
	}
	fmt.Print(string(out))
}

// filterOut returns a copy of the src environment without environment
// variables from remove.
// TODO: delete when issue 6201 is fixed.
func filterOut(src []string, remove ...string) (out []string) {
S:
	for _, s := range src {
		for _, r := range remove {
			if strings.HasPrefix(s, r) && strings.HasPrefix(s, r+"=") {
				continue S
			}
		}
		out = append(out, s)
	}
	return
}

// file expands s to $GOROOT/api/s.txt.
// If there are more than 1, they're comma-separated.
func file(s ...string) string {
	if len(s) > 1 {
		return file(s[0]) + "," + file(s[1:]...)
	}
	return filepath.Join(goroot, "api", s[0]+".txt")
}

// prepGoPath returns a GOPATH for the "go" tool to compile the API tool with.
// It tries to re-use a go.tools checkout from a previous run if possible,
// else it hg clones it.
func prepGoPath() string {
	// Use a builder-specific temp directory name, so builders running
	// two copies don't trample on each other: https://golang.org/issue/9407
	// We don't use io.TempDir or a PID or timestamp here because we do
	// want this to be stable between runs, to minimize "git clone" calls
	// in the common case.
	var tempBase = fmt.Sprintf("go.tools.TMP.%s.%s", runtime.GOOS, runtime.GOARCH)

	username := ""
	u, err := user.Current()
	if err == nil {
		username = u.Username
	} else {
		username = os.Getenv("USER")
		if username == "" {
			username = "nobody"
		}
	}

	// The GOPATH we'll return
	gopath := filepath.Join(os.TempDir(), "gopath-api-"+cleanUsername(username)+"-"+cleanUsername(strings.Fields(runtime.Version())[0]), goToolsVersion)

	// cloneDir is where we run "git clone".
	cloneDir := filepath.Join(gopath, "src", "code.google.com", "p")

	// The dir we clone into. We only atomically rename it to finalDir on
	// clone success.
	tmpDir := filepath.Join(cloneDir, tempBase)

	// finalDir is where the checkout will live once it's complete.
	finalDir := filepath.Join(cloneDir, "go.tools")

	if goToolsCheckoutGood(finalDir) {
		return gopath
	}
	os.RemoveAll(finalDir) // in case it's there but corrupt
	os.RemoveAll(tmpDir)   // in case of aborted hg clone before

	if err := os.MkdirAll(cloneDir, 0700); err != nil {
		log.Fatal(err)
	}
	cmd := exec.Command("git", "clone", "https://go.googlesource.com/tools", tempBase)
	cmd.Dir = cloneDir
	out, err := cmd.CombinedOutput()
	if err != nil {
		if _, err := http.Head("http://ip.appspot.com/"); err != nil {
			log.Printf("# Skipping API check; network appears to be unavailable")
			os.Exit(0)
		}
		log.Fatalf("Error running git clone on x/tools: %v\n%s", err, out)
	}
	cmd = exec.Command("git", "reset", "--hard", goToolsVersion)
	cmd.Dir = tmpDir
	out, err = cmd.CombinedOutput()
	if err != nil {
		log.Fatalf("Error updating x/tools in %v to %v: %v, %s", tmpDir, goToolsVersion, err, out)
	}

	if err := os.Rename(tmpDir, finalDir); err != nil {
		if os.IsExist(err) {
			// A different builder beat us into putting this repo into
			// its final place. But that's fine; if it's there, it's
			// the right version and we can use it.
			//
			// This happens on the Go project's Windows builders
			// especially, where we have two builders (386 and amd64)
			// running at the same time, trying to compete for moving
			// it into place.
			os.RemoveAll(tmpDir)
		} else {
			log.Fatal(err)
		}
	}
	return gopath
}

func cleanUsername(n string) string {
	b := make([]rune, len(n))
	for i, r := range n {
		if r == '\\' || r == '/' || r == ':' {
			b[i] = '_'
		} else {
			b[i] = r
		}
	}
	return string(b)
}

func goToolsCheckoutGood(dir string) bool {
	if _, err := os.Stat(dir); err != nil {
		return false
	}

	cmd := exec.Command("git", "rev-parse", "HEAD")
	cmd.Dir = dir
	out, err := cmd.Output()
	if err != nil {
		return false
	}
	id := strings.TrimSpace(string(out))
	if !strings.HasPrefix(id, goToolsVersion) {
		return false
	}

	cmd = exec.Command("git", "status", "--porcelain")
	cmd.Dir = dir
	out, err = cmd.Output()
	if err != nil || strings.TrimSpace(string(out)) != "" {
		return false
	}
	return true
}


text:
<title> item onhand quantity </title>

<form action="includes/onhand_insert.php" method="POST">

item_id
org_id
material onhand quantity

<select name="item_id">
<?php
// connect to mongodb
   $m = new MongoClient();
   // select a database\
   $db = $m->db_ess;
   $collection = $db->ess_item_info;
   $cursor=$collection->find();
   foreach($cursor as $document)
{
echo'<option value="'.$document["_id"].'">'. $document["_id"].'</option>';
}
?>

	<select name="org_id">
<?php
// connect to mongodb
   $m = new MongoClient();
   // select a database\
   $db = $m->db_ess;
   $collection = $db->ess_organization;
   $cursor=$collection->find();
   foreach($cursor as $document)
{
echo'<option value="'.$document["_id"].'">'. $document["_id"].'</option>';
echo '<input type='text' name="moq" value="'.$document['onhand'].'">	';
}
?>

<input  type="button" align='center' value="save">

<input  type="reset" align='center' value="clear">
</form>


text:
namespace blink {

void InspectorWebSocketCreateEvent::Data(perfetto::TracedValue context,
                                         ExecutionContext* execution_context,
                                         uint64_t identifier,
                                         const KURL& url,
                                         const String& protocol) {
  auto dict = std::move(context).WriteDictionary();
  DCHECK(execution_context->IsContextThread());
  dict.Add("identifier", identifier);
  dict.Add("url", url.GetString());
  if (auto* window = DynamicTo<LocalDOMWindow>(execution_context)) {
    dict.Add("frame", IdentifiersFactory::FrameId(window->GetFrame()));
  } else if (auto* scope = DynamicTo<WorkerGlobalScope>(execution_context)) {
    dict.Add("workerId", IdentifiersFactory::IdFromToken(
                             scope->GetThread()->GetDevToolsWorkerToken()));
  } else {
    NOTREACHED()
        << "WebSocket is available only in Window and WorkerGlobalScope";
  }
  if (!protocol.IsNull())
    dict.Add("webSocketProtocol", protocol);
  SetCallStack(dict);
}

void InspectorWebSocketEvent::Data(perfetto::TracedValue context,
                                   ExecutionContext* execution_context,
                                   uint64_t identifier) {
  DCHECK(execution_context->IsContextThread());
  auto dict = std::move(context).WriteDictionary();
  dict.Add("identifier", identifier);
  if (auto* window = DynamicTo<LocalDOMWindow>(execution_context)) {
    dict.Add("frame", IdentifiersFactory::FrameId(window->GetFrame()));
  } else if (auto* scope = DynamicTo<WorkerGlobalScope>(execution_context)) {
    dict.Add("workerId", IdentifiersFactory::IdFromToken(
                             scope->GetThread()->GetDevToolsWorkerToken()));
  } else {
    NOTREACHED()
        << "WebSocket is available only in Window and WorkerGlobalScope";
  }
  SetCallStack(dict);
}

}  // namespace blink


text: Inverted pendulum open-loop control demo


text:
package com.svbio.cloudkeeper.model.beans.execution;

import cloudkeeper.serialization.IntegerMarshaler;
import com.svbio.cloudkeeper.model.bare.element.module.BareInputModule;
import com.svbio.cloudkeeper.model.beans.MutableLocatableContract;
import com.svbio.cloudkeeper.model.beans.XmlRootElementContract;
import com.svbio.cloudkeeper.model.beans.element.module.MutableCompositeModule;
import com.svbio.cloudkeeper.model.beans.element.module.MutableConnection;
import com.svbio.cloudkeeper.model.beans.element.module.MutableInputModule;
import com.svbio.cloudkeeper.model.beans.element.module.MutableModule;
import com.svbio.cloudkeeper.model.beans.element.module.MutableProxyModule;
import com.svbio.cloudkeeper.model.beans.element.module.MutableSiblingConnection;
import com.svbio.cloudkeeper.model.beans.element.serialization.MutableSerializationNode;
import com.svbio.cloudkeeper.model.beans.element.serialization.MutableSerializationRoot;
import com.svbio.cloudkeeper.model.beans.element.serialization.MutableSerializedString;
import com.svbio.cloudkeeper.model.beans.type.MutableDeclaredType;
import org.testng.annotations.Factory;

import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class MutableExecutableTest {
    @Factory
    public Object[] contracts() {
        List<Object> contractsList = new ArrayList<>();
        contractsList.addAll(Arrays.asList(MutableLocatableContract.contractsFor(MutableExecutable.class)));
        contractsList.add(new XmlRootElementContract(
            new MutableExecutable()
                .setModule(
                    new MutableCompositeModule()
                        .setModules(Arrays.<MutableModule<?>>asList(
                            new MutableInputModule()
                                .setSimpleName("zero")
                                .setOutPortType(new MutableDeclaredType().setDeclaration(Integer.class.getName()))
                                .setRaw(
                                    new MutableSerializationRoot()
                                        .setDeclaration(IntegerMarshaler.class.getName())
                                        .setEntries(Collections.<MutableSerializationNode<?>>singletonList(
                                            new MutableSerializedString().setString("0")
                                        ))
                                ),
                            new MutableProxyModule()
                                .setSimpleName("sum")
                                .setDeclaration("test.Sum")
                        ))
                        .setConnections(Collections.<MutableConnection<?>>singletonList(
                            new MutableSiblingConnection()
                                .setFromModule("zero").setFromPort(BareInputModule.OUT_PORT_NAME)
                                .setToModule("sum").setToPort("num1")
                        ))
                )
                .setBundleIdentifiers(Collections.singletonList(
                    URI.create("x-maven:com.svbio.cloudkeeper.examples.bundles:simple:ckbundle.zip:1.0.0-SNAPSHOT")
                ))
        ));
        return contractsList.toArray();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:title="@string/issue_list_filter"
        app:showAsAction="never"
        android:id="@+id/issue_list_filter">

        <menu>
            <item
                android:title="@string/issue_list_filter_closed"
                android:id="@+id/issue_list_filter_closed" />
            <item
                android:title="@string/issue_list_filter_open"
                android:id="@+id/issue_list_filter_open" />
            <item
                android:title="@string/issue_list_filter_search"
                android:id="@+id/issue_list_filter_search" />
        </menu>

    </item>

</menu>


text:
require 'spec_helper'

RSpec.describe OneviewSDK::API3000::C7000::UplinkSet do
  include_context 'shared context'

  it 'inherits from OneviewSDK::API2800::C7000::UplinkSet' do
    expect(described_class).to be < OneviewSDK::API2800::C7000::UplinkSet
  end
end


text:
class CreateComments < ActiveRecord::Migration[5.0]
  def change
    create_table :comments do |t|
      t.text       :content
      t.belongs_to :post, index: true
      t.belongs_to :user, index: true

      t.timestamps
    end
  end
end


text:
package org.panteleyev.money.app.settings;

import javafx.application.Platform;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.Control;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.text.Font;
import org.controlsfx.dialog.FontSelectorDialog;
import org.controlsfx.validation.ValidationResult;
import org.controlsfx.validation.ValidationSupport;
import org.panteleyev.fx.BaseDialog;
import org.panteleyev.fx.Controller;

import java.util.List;

import static javafx.collections.FXCollections.observableArrayList;
import static org.panteleyev.fx.BoxFactory.vBox;
import static org.panteleyev.fx.ButtonFactory.button;
import static org.panteleyev.fx.FxFactory.newTab;
import static org.panteleyev.fx.FxUtils.COLON;
import static org.panteleyev.fx.FxUtils.ELLIPSIS;
import static org.panteleyev.fx.FxUtils.fxString;
import static org.panteleyev.fx.LabelFactory.label;
import static org.panteleyev.fx.TitledPaneBuilder.titledPane;
import static org.panteleyev.fx.grid.GridBuilder.gridPane;
import static org.panteleyev.fx.grid.GridRowBuilder.gridRow;
import static org.panteleyev.money.app.MainWindowController.UI;
import static org.panteleyev.money.app.Styles.DOUBLE_SPACING;
import static org.panteleyev.money.app.Styles.GRID_PANE;
import static org.panteleyev.money.app.settings.ColorName.CREDIT;
import static org.panteleyev.money.app.settings.ColorName.DEBIT;
import static org.panteleyev.money.app.settings.ColorName.STATEMENT_CHECKED;
import static org.panteleyev.money.app.settings.ColorName.STATEMENT_MISSING;
import static org.panteleyev.money.app.settings.ColorName.STATEMENT_UNCHECKED;
import static org.panteleyev.money.app.settings.ColorName.TRANSFER;
import static org.panteleyev.money.app.settings.FontName.CONTROLS_FONT;
import static org.panteleyev.money.app.settings.FontName.DIALOG_LABEL_FONT;
import static org.panteleyev.money.app.settings.FontName.MENU_FONT;
import static org.panteleyev.money.app.settings.FontName.TABLE_CELL_FONT;
import static org.panteleyev.money.bundles.Internationalization.I18N_MISC_AUTOCOMPLETE_PREFIX_LENGTH;
import static org.panteleyev.money.bundles.Internationalization.I18N_MISC_DAYS_BEFORE_CLOSING;
import static org.panteleyev.money.bundles.Internationalization.I18N_MISC_NOT_FOUND;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_COLORS;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_CONFIRMED;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_CONTROLS;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_CREDIT;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_DEBIT;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_DIALOGS;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_FONTS;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_GENERAL;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_MENU;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_OPTIONS;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_STATEMENTS;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_TABLES;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_TEXT;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_TRANSACTIONS;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_TRANSFER;
import static org.panteleyev.money.bundles.Internationalization.I18N_WORD_UNCONFIRMED;

public class SettingsDialog extends BaseDialog<ButtonType> {
    private final ValidationSupport validation = new ValidationSupport();

    private final ChoiceBox<Integer> autoCompleteLength = new ChoiceBox<>(observableArrayList(2, 3, 4, 5));
    private final TextField accountClosingDayDeltaEdit = new TextField();

    private final TextField controlsFontField = new TextField();
    private final TextField menuFontField = new TextField();
    private final TextField cellFontField = new TextField();
    private final ColorPicker debitColorPicker = new ColorPicker();
    private final ColorPicker creditColorPicker = new ColorPicker();
    private final ColorPicker transferColorPicker = new ColorPicker();
    private final ColorPicker statementCheckedColorPicker = new ColorPicker();
    private final ColorPicker statementUncheckedColorPicker = new ColorPicker();
    private final ColorPicker statementMissingColorPicker = new ColorPicker();

    private final TextField dialogLabelFontField = new TextField();

    public SettingsDialog(Controller owner, Settings settings) {
        super(owner, settings.getDialogCssFileUrl());

        setTitle(fxString(UI, I18N_WORD_OPTIONS));
        createDefaultButtons(UI, validation.invalidProperty());

        controlsFontField.setEditable(false);
        controlsFontField.setPrefColumnCount(20);
        menuFontField.setEditable(false);
        menuFontField.setPrefColumnCount(20);
        cellFontField.setEditable(false);
        cellFontField.setPrefColumnCount(20);
        dialogLabelFontField.setEditable(false);
        dialogLabelFontField.setPrefColumnCount(20);

        debitColorPicker.setValue(settings.getColor(DEBIT));
        creditColorPicker.setValue(settings.getColor(CREDIT));
        transferColorPicker.setValue(settings.getColor(TRANSFER));
        statementCheckedColorPicker.setValue(settings.getColor(STATEMENT_CHECKED));
        statementUncheckedColorPicker.setValue(settings.getColor(STATEMENT_UNCHECKED));
        statementMissingColorPicker.setValue(settings.getColor(STATEMENT_MISSING));

        setupFontField(controlsFontField, settings.getFont(CONTROLS_FONT));
        setupFontField(menuFontField, settings.getFont(MENU_FONT));
        setupFontField(cellFontField, settings.getFont(TABLE_CELL_FONT));
        setupFontField(dialogLabelFontField, settings.getFont(DIALOG_LABEL_FONT));

        var tabPane = new TabPane(
                newTab(UI, I18N_WORD_GENERAL, false, gridPane(
                        List.of(
                                gridRow(label(fxString(UI, I18N_MISC_AUTOCOMPLETE_PREFIX_LENGTH, COLON)),
                                        autoCompleteLength),
                                gridRow(label(fxString(UI, I18N_MISC_DAYS_BEFORE_CLOSING)), accountClosingDayDeltaEdit)
                        ), b -> b.withStyle(GRID_PANE))
                ),
                newTab(UI, I18N_WORD_FONTS, false,
                        vBox(DOUBLE_SPACING,
                                titledPane(fxString(UI, I18N_WORD_CONTROLS),
                                        gridPane(List.of(
                                                gridRow(label(fxString(UI, I18N_WORD_TEXT, COLON)), controlsFontField,
                                                        button(ELLIPSIS,
                                                                actionEvent -> onFontSelected(controlsFontField))),
                                                gridRow(label(fxString(UI, I18N_WORD_MENU, COLON)), menuFontField,
                                                        button(ELLIPSIS, actionEvent -> onFontSelected(menuFontField)))
                                        ), b -> b.withStyle(GRID_PANE))
                                ),
                                titledPane(fxString(UI, I18N_WORD_TABLES),
                                        gridPane(List.of(
                                                        gridRow(cellFontField,
                                                                button(ELLIPSIS,
                                                                        actionEvent -> onFontSelected(cellFontField)))
                                                ), b -> b.withStyle(GRID_PANE)
                                        )
                                ),
                                titledPane(fxString(UI, I18N_WORD_DIALOGS),
                                        gridPane(List.of(
                                                        gridRow(dialogLabelFontField,
                                                                button(ELLIPSIS,
                                                                        actionEvent -> onFontSelected(dialogLabelFontField)))
                                                ), b -> b.withStyle(GRID_PANE)
                                        )
                                )
                        )
                ),
                newTab(UI, I18N_WORD_COLORS, false,
                        vBox(DOUBLE_SPACING,
                                titledPane(fxString(UI, I18N_WORD_TRANSACTIONS),
                                        gridPane(List.of(
                                                        gridRow(label(fxString(UI, I18N_WORD_DEBIT, COLON)),
                                                                debitColorPicker),
                                                        gridRow(label(fxString(UI, I18N_WORD_CREDIT, COLON)),
                                                                creditColorPicker),
                                                        gridRow(label(fxString(UI, I18N_WORD_TRANSFER, COLON)),
                                                                transferColorPicker)
                                                ), b -> b.withStyle(GRID_PANE)
                                        )
                                ),
                                titledPane(fxString(UI, I18N_WORD_STATEMENTS),
                                        gridPane(List.of(
                                                        gridRow(label(fxString(UI, I18N_WORD_CONFIRMED, COLON)),
                                                                statementCheckedColorPicker),
                                                        gridRow(label(fxString(UI, I18N_WORD_UNCONFIRMED, COLON)),
                                                                statementUncheckedColorPicker),
                                                        gridRow(label(fxString(UI, I18N_MISC_NOT_FOUND, COLON)),
                                                                statementMissingColorPicker)
                                                ), b -> b.withStyle(GRID_PANE)
                                        )
                                )
                        )
                )
        );
        getDialogPane().setContent(tabPane);

        autoCompleteLength.getSelectionModel().select(Integer.valueOf(settings.getAutoCompleteLength()));
        accountClosingDayDeltaEdit.setText(Integer.toString(settings.getAccountClosingDayDelta()));

        setResultConverter((ButtonType param) -> {
            if (param == ButtonType.OK) {
                settings.update(opt -> {
                    opt.setAutoCompleteLength(autoCompleteLength.getValue());
                    opt.setAccountClosingDayDelta(Integer.parseInt(accountClosingDayDeltaEdit.getText()));
                    // Fonts
                    opt.setFont(CONTROLS_FONT, (Font) controlsFontField.getUserData());
                    opt.setFont(MENU_FONT, (Font) menuFontField.getUserData());
                    opt.setFont(TABLE_CELL_FONT, (Font) cellFontField.getUserData());
                    opt.setFont(DIALOG_LABEL_FONT, (Font) dialogLabelFontField.getUserData());
                    // Colors
                    opt.setColor(DEBIT, debitColorPicker.getValue());
                    opt.setColor(CREDIT, creditColorPicker.getValue());
                    opt.setColor(TRANSFER, transferColorPicker.getValue());
                    opt.setColor(STATEMENT_CHECKED, statementCheckedColorPicker.getValue());
                    opt.setColor(STATEMENT_UNCHECKED, statementUncheckedColorPicker.getValue());
                    opt.setColor(STATEMENT_MISSING, statementMissingColorPicker.getValue());
                });
            }
            return param;
        });

        Platform.runLater(this::createValidationSupport);
    }

    private void createValidationSupport() {
        validation.registerValidator(accountClosingDayDeltaEdit, (Control control, String value) -> {
            var invalid = false;
            try {
                Integer.parseInt(value);
                invalid = Integer.parseInt(value) <= 0;
            } catch (NumberFormatException ex) {
                invalid = true;
            }

            return ValidationResult.fromErrorIf(control, null, invalid);
        });

        validation.initInitialDecoration();
    }

    private void onFontSelected(TextField field) {
        var font = (Font) field.getUserData();
        new FontSelectorDialog(font)
                .showAndWait()
                .ifPresent(newFont -> setupFontField(field, newFont));
    }

    private static void setupFontField(TextField field, Font font) {
        field.setUserData(font);
        field.setText(String.format("%s %s, %d",
                font.getFamily(), font.getStyle(), (int) font.getSize()));
    }
}


text:
<?php

namespace PaxWs\Wsdl\Binding\DocumentStyle;

use PaxWs\Wsdl\Binding\WSDLBinding;

/**
 * Description of WSDLBindingDocument
 *
 * @author Victor Ribeiro <victormech@gmail.com>
 */
class WSDLBindingDocument extends WSDLBinding
{
    //put your code here
}


text:
package tbx2rdfservice.store;

import com.hp.hpl.jena.rdf.model.Model;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RDFFormat;

/**
 * Class with the method that adds the only required prefixes
 * @author Victor
 */
public class RDFPrefixes {

    private static Map<String, String> map = new HashMap();

    private static void init() {
        map.put("http://purl.org/dc/terms/", "dct");
        map.put("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf");
        map.put("http://www.w3.org/2000/01/rdf-schema#", "rdfs");
        map.put("http://semanticweb.cs.vu.nl/2009/11/sem/", "sem");
        map.put("http://purl.org/dc/terms/", "dct");
        map.put("http://www.w3.org/2004/02/skos/core#", "skos");
        map.put("http://www.geonames.org/ontology#", "gn");
        map.put("http://xmlns.com/foaf/0.1/", "foaf");
        map.put("http://tbx2rdf.lider-project.eu/tbx#", "tbx");
        map.put("http://www.w3.org/ns/lemon/ontolex#", "ontolex");
        map.put("http://tbx2rdf.lider-project.eu/converter/resource/iate/", "iate");
        map.put("http://lemon-model.net/lemon#", "lemon");
        map.put("http://creativecommons.org/ns#", "cc");

    }
    public static String reverse(String prefix)
    {
        if (map.isEmpty()) {
            init();
        }
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry e = (Map.Entry)it.next();
            String prefijo = (String)e.getValue();
            if (!prefijo.equals(prefix))
                continue;
            String nombre = (String)e.getKey();
            return nombre;
        }
        return "";
    }

    /**
     * Adds only the prefix that are required in a model
     */
    public static Model addPrefixesIfNeeded(Model modelo) {
        if (map.isEmpty()) {
            init();
        }
        StringWriter sw = new StringWriter();
        RDFDataMgr.write(sw, modelo, RDFFormat.TURTLE_PRETTY);
        String ttl = sw.toString();
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry e = (Map.Entry) it.next();
            String key = (String) e.getKey();
            if (ttl.contains(key))
            {
                modelo.setNsPrefix((String)e.getValue(), key);
            }
        }
        return modelo;
    }

    public static String getSampleTTL()
    {
        String ttl ="<http://purl.org/NET/vroddon> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://xmlns.com/foaf/0.1/Person> .";
        return ttl;
    }

    public static String extend(String param) {
        if (!param.contains(":"))
            return param;
        String left=param.substring(0,param.indexOf(":"));
        String right=param.substring(param.indexOf(":")+1, param.length());
        String prefex = RDFPrefixes.reverse(left);
        if (prefex.isEmpty())
            return param;
        return prefex+right;
    }

    public static String encode(String base, String name) {
        if (name.contains("%"))
            return base+name;
        try {
            String codificado = URLEncoder.encode(name, "UTF-8");
            codificado=codificado.replace("+", "%20");
            codificado=codificado.replace("(", "%28");
            codificado=codificado.replace(")", "%29");
            String sres = base + codificado;
            return sres;
        } catch (Exception e) {
            return "";
        }
    }

    public static String getLastPart(String uri) {
        String s="";
        int index=uri.lastIndexOf("/");
        if (index==-1)
            return uri;
        s=uri.substring(index+1, uri.length());
        s=s.replace("%20", " ");
        s=s.replace("+", " ");
        return s;
    }
        public static void main(String[] args) {
            System.out.println(getLastPart("http://tbx2rdf.lider-project.eu/data/iate/IATE-74645"));
        }

}


text:
package com.andymark.crosslink;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class UpdateJaguarPacket implements Message {

	private short[] uiMode = new short[20];
	private short[] uiSetVoltage = new short[20];

	@Override
	public ByteBuffer getMessage() {

		for (int i = 16; i < 20; i++) {
			uiMode[i] = (short) 0xffff;
		}

		uiSetVoltage[1] = (short) 0x1999;

		ByteBuffer buffer = ByteBuffer.allocate(86);
		buffer.order(ByteOrder.LITTLE_ENDIAN);
		buffer.putShort((short) 0xaaa0);  // sig
		buffer.putShort((short) 86); // byte len

		for (short val : uiMode) {
			buffer.putShort(val);
		}

		for (short val : uiSetVoltage) {
			buffer.putShort(val);
		}

		short checksum = (short) Utilities.checksum(buffer, 0, 84);
		buffer.putShort(checksum);
		return buffer;
	}

}