<commit_before>/*
 * This file contains common variables, datatypes and functions used by all
 * cellular automata in this folder.
 *
 * Copyright (c) 2015 Johannes Maibaum <jmaibaum@gmail.com>
 */

var Settings = {
    boardDivision: 0,
    boardSideLenght: 0,
    canvas: undefined,
    context: undefined,
    cellsPerLine: 50,        // Devides the canvas into 'n' cellsPerLine.
    cellSize: 0,
    cellColor: ["#ffffff"],  // Needs to be extended by final game with colors.
    cellToDraw: 1,           // Default cell type for drawing operations.
    intervalID: 0,
    speed: 100
};

// Wait for DOM, then initialize.
document.addEventListener("DOMContentLoaded", initialize, false);

// Custom datatypes for generic Cells and a playing Field:
var Cell = function ()
{
    this.state = 0;
    this.neighbours = 0;
}

var Field = function (rows, columns)
{
    this.rows  = rows;
    this.columns = columns;
    this.generation = 0;
    this.generationHTML = undefined;  // Needs to be set by initialize().
    this.population = 0;
    this.oldPopulaton = 0;
    this.populationHTML = undefined;  // Needs to be set by initialize().
    this.data = [];

    for (var i = 0; i < this.rows + 2; i++) {
        this.data[i] = [];

        for (var j = 0; j < this.columns + 2; j++)
            this.data[i].push(new Cell());
    }
}

Field.prototype.updateNeighbours = function (row, column, increment)
{
    this.data[row - 1][column - 1].neighbours += increment;
    this.data[row - 1][column].neighbours     += increment;
    this.data[row - 1][column + 1].neighbours += increment;
    this.data[row][column - 1].neighbours     += increment;
    this.data[row][column + 1].neighbours     += increment;
    this.data[row + 1][column - 1].neighbours += increment;
    this.data[row + 1][column].neighbours     += increment;
    this.data[row + 1][column + 1].neighbours += increment;
}

Field.prototype.resetAllNeighbours = function()
{
    for (var row in this.data)
        for (var column in this.data[row])
            this.data[row][column].neighbours = 0;
}

Field.prototype.increaseGeneration = function()
{
    this.generation++;
    this.generationHTML.innerHTML = this.generation;
}

Field.prototype.updatePopulationHTML = function ()
{
    if (this.population != this.oldPopulation) {
        this.populationHTML.innerHTML = this.population;
        this.oldPopulation = this.population;
    }
}

Field.prototype.clear = function ()
{
    for (var row in this.data)
        for (var column in this.data[row]) {
            this.createCell(row, column, 0);
            drawCell(row, column, 0);
            this.updatePopulationHTML();
        }

    // Reset generation counter.
    this.generation = 0;
    this.generationHTML.innerHTML = this.generation;
}

// Initialize the canvas and add the event listener.
function initialize()
{
    // Prepare canvas:
    Settings.canvas = document.getElementById("board");
    Settings.context = Settings.canvas.getContext("2d");
    field.generationHTML = document.getElementById("Generation");
    field.populationHTML = document.getElementById("Population");

    Settings.boardSideLength = Settings.canvas.width;  // Assume as quadratic.
    Settings.boardDivision = Math.floor(Settings.boardSideLength /
                                        Settings.cellsPerLine);
    Settings.cellSize = Settings.boardDivision - 2;

    // Draw cell grid:
    Settings.context.strokeStyle = "#cccccc";
    Settings.context.lineWidth = 2;

    for (var i = 0; i <= Settings.boardSideLength;
         i = i + Settings.boardDivision) {
        Settings.context.moveTo(0, i);
        Settings.context.lineTo(Settings.boardSideLength, i);
        Settings.context.moveTo(i, 0);
        Settings.context.lineTo(i, Settings.boardSideLength);
        Settings.context.stroke();
    }

    // Add event listeners:
    Settings.canvas.addEventListener("mousedown", drawCellFromMouseClick,
                                     false);

    // Setup for dropping field files on the canvas:
    var dropZone = Settings.canvas;
    dropZone.addEventListener("dragenter", dragenter, false);
    dropZone.addEventListener("dragover", dragover, false);
    dropZone.addEventListener("drop", drop, false);
}

/*
 * Callback function to determine the mouse click coordinates on the canvas.
 * Adapted from:
 * http://miloq.blogspot.de/2011/05/coordinates-mouse-click-canvas.html
 */
function drawCellFromMouseClick(event)
{
    var x = event.x;
    var y = event.y;

    // Firefox workaround:
    if (x == undefined && y == undefined) {
        x = event.clientX + document.body.scrollLeft +
            document.documentElement.scrollLeft;
        y = event.clientY + document.body.scrollTop +
            document.documentElement.scrollTop;
    }

    x -= Settings.canvas.offsetLeft;
    y -= Settings.canvas.offsetTop;

    var coords = convertClickToFieldCoordinates(x, y);
    var row    = coords[0];
    var column = coords[1];

    if (field.createCell(row, column, Settings.cellToDraw, 1))
        drawCell(row, column, Settings.cellToDraw);
    else {
        field.createCell(row, column, 0, -1);
        drawCell(row, column, 0);
    }
}

function convertClickToFieldCoordinates(x, y) {
    var row = Math.floor(y / Settings.boardDivision) + 1;
    var column = Math.floor(x / Settings.boardDivision) + 1;

    // Ensure that we get valid coordinates:
    if (row > field.rows)
        row--;

    if (column > field.columns)
        column--;

    return [row, column];
}

// Draw a cell using field coordinates:
function drawCell(row, column, state)
{
    // Set Cell color:
    Settings.context.fillStyle = Settings.cellColor[state];

    var drawx = Math.floor(column * Settings.boardDivision)
        - Settings.boardDivision + 1;
    var drawy = Math.floor(row * Settings.boardDivision)
        - Settings.boardDivision + 1;

    Settings.context.fillRect(drawx, drawy, Settings.cellSize,
                              Settings.cellSize);
}

// Wrapper for field.clear():
function clearField()
{
    field.clear();
}

function runAutomata()
{
    if (!Settings.intervalID)
        Settings.intervalID = window.setInterval(nextGenerationFromInterval,
                                                 Settings.speed);
}

function stopAutomata()
{
    window.clearInterval(Settings.intervalID);
    Settings.intervalID = 0;
}

function changeSpeed(selectItem)
{
    Settings.speed = selectItem.value;

    if (Settings.intervalID) {
        stopAutomata();
        runAutomata();
    }
}

// Wrapper for next generation method:
function nextGeneration()
{
    if (!Settings.intervalID)
        field.nextGeneration();
    else
        stopAutomata();
}

function nextGenerationFromInterval()
{
    field.nextGeneration();
}

/*
 * Save field to and load field from text file.
 * Adapted from:
 * https://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-
 * saving-a-text-file-in-html5-using-javascrip/
 */
function saveFile()
{
    var textToWrite = '';

    // Loop over field to construct text string:
    for (var row = 1; row <= field.rows; row++) {
        for (var column = 1; column <= field.columns; column++) {
            textToWrite += field.generateChar(row, column);
        }
        textToWrite += '\n';
    }

    var fileName = document.getElementById("FileName").value;
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    var downloadLink = document.createElement("a");
    downloadLink.download = fileName;

    if (window.webkitURL != null) {
        // Chrome allows the link to be clicked without actually adding it to
        // the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    } else {
        // Firefox requires the link to be added to the DOM before it can be
        // clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = function (e) {
            document.body.removeChild(e.target);
        };
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
}

function loadFile(files)
{
    var file = files[0];
    var textType = /text.*/;

    if (file.type.match(textType)) {
        var reader = new FileReader();

        reader.onload = function (e) {
            var row = 1, column = 1;
            field.clear();

            for (var charNr in reader.result) {
                field.parseChar(row, column, reader.result[charNr]);

                column++;
                if (column > field.columns) {
                    column = 0;
                    row++;
                }
            }

            field.countAllNeighbours();
            field.updatePopulationHTML();
        };

        reader.readAsText(file);
    } else {
        console.log("File not supported.")
    }
}

// Functions for drag and dop onto the canvas:
function dragenter(e)
{
    e.stopPropagation();
    e.preventDefault();
}

function dragover(e)
{
    e.stopPropagation();
    e.preventDefault();
}

function drop(e)
{
    e.stopPropagation();
    e.preventDefault();

    loadFile(e.dataTransfer.files);
}

// Function for submitting with enter from a text field:
function handleKeyPress(event, textField)
{
    if (event.keyCode === 13) {  // Enter key was pressed.
        if (textField == "FileName")
            saveFile();
        else if (textField == "RandomCells")
            fillWithRandomCells();
    }
}
<commit_msg>Small logic reordering in loadFile().<commit_after>/*
 * This file contains common variables, datatypes and functions used by all
 * cellular automata in this folder.
 *
 * Copyright (c) 2015 Johannes Maibaum <jmaibaum@gmail.com>
 */

var Settings = {
    boardDivision: 0,
    boardSideLenght: 0,
    canvas: undefined,
    context: undefined,
    cellsPerLine: 50,        // Devides the canvas into 'n' cellsPerLine.
    cellSize: 0,
    cellColor: ["#ffffff"],  // Needs to be extended by final game with colors.
    cellToDraw: 1,           // Default cell type for drawing operations.
    intervalID: 0,
    speed: 100
};

// Wait for DOM, then initialize.
document.addEventListener("DOMContentLoaded", initialize, false);

// Custom datatypes for generic Cells and a playing Field:
var Cell = function ()
{
    this.state = 0;
    this.neighbours = 0;
}

var Field = function (rows, columns)
{
    this.rows  = rows;
    this.columns = columns;
    this.generation = 0;
    this.generationHTML = undefined;  // Needs to be set by initialize().
    this.population = 0;
    this.oldPopulaton = 0;
    this.populationHTML = undefined;  // Needs to be set by initialize().
    this.data = [];

    for (var i = 0; i < this.rows + 2; i++) {
        this.data[i] = [];

        for (var j = 0; j < this.columns + 2; j++)
            this.data[i].push(new Cell());
    }
}

Field.prototype.updateNeighbours = function (row, column, increment)
{
    this.data[row - 1][column - 1].neighbours += increment;
    this.data[row - 1][column].neighbours     += increment;
    this.data[row - 1][column + 1].neighbours += increment;
    this.data[row][column - 1].neighbours     += increment;
    this.data[row][column + 1].neighbours     += increment;
    this.data[row + 1][column - 1].neighbours += increment;
    this.data[row + 1][column].neighbours     += increment;
    this.data[row + 1][column + 1].neighbours += increment;
}

Field.prototype.resetAllNeighbours = function()
{
    for (var row in this.data)
        for (var column in this.data[row])
            this.data[row][column].neighbours = 0;
}

Field.prototype.increaseGeneration = function()
{
    this.generation++;
    this.generationHTML.innerHTML = this.generation;
}

Field.prototype.updatePopulationHTML = function ()
{
    if (this.population != this.oldPopulation) {
        this.populationHTML.innerHTML = this.population;
        this.oldPopulation = this.population;
    }
}

Field.prototype.clear = function ()
{
    for (var row in this.data)
        for (var column in this.data[row]) {
            this.createCell(row, column, 0);
            drawCell(row, column, 0);
            this.updatePopulationHTML();
        }

    // Reset generation counter.
    this.generation = 0;
    this.generationHTML.innerHTML = this.generation;
}

// Initialize the canvas and add the event listener.
function initialize()
{
    // Prepare canvas:
    Settings.canvas = document.getElementById("board");
    Settings.context = Settings.canvas.getContext("2d");
    field.generationHTML = document.getElementById("Generation");
    field.populationHTML = document.getElementById("Population");

    Settings.boardSideLength = Settings.canvas.width;  // Assume as quadratic.
    Settings.boardDivision = Math.floor(Settings.boardSideLength /
                                        Settings.cellsPerLine);
    Settings.cellSize = Settings.boardDivision - 2;

    // Draw cell grid:
    Settings.context.strokeStyle = "#cccccc";
    Settings.context.lineWidth = 2;

    for (var i = 0; i <= Settings.boardSideLength;
         i = i + Settings.boardDivision) {
        Settings.context.moveTo(0, i);
        Settings.context.lineTo(Settings.boardSideLength, i);
        Settings.context.moveTo(i, 0);
        Settings.context.lineTo(i, Settings.boardSideLength);
        Settings.context.stroke();
    }

    // Add event listeners:
    Settings.canvas.addEventListener("mousedown", drawCellFromMouseClick,
                                     false);

    // Setup for dropping field files on the canvas:
    var dropZone = Settings.canvas;
    dropZone.addEventListener("dragenter", dragenter, false);
    dropZone.addEventListener("dragover", dragover, false);
    dropZone.addEventListener("drop", drop, false);
}

/*
 * Callback function to determine the mouse click coordinates on the canvas.
 * Adapted from:
 * http://miloq.blogspot.de/2011/05/coordinates-mouse-click-canvas.html
 */
function drawCellFromMouseClick(event)
{
    var x = event.x;
    var y = event.y;

    // Firefox workaround:
    if (x == undefined && y == undefined) {
        x = event.clientX + document.body.scrollLeft +
            document.documentElement.scrollLeft;
        y = event.clientY + document.body.scrollTop +
            document.documentElement.scrollTop;
    }

    x -= Settings.canvas.offsetLeft;
    y -= Settings.canvas.offsetTop;

    var coords = convertClickToFieldCoordinates(x, y);
    var row    = coords[0];
    var column = coords[1];

    if (field.createCell(row, column, Settings.cellToDraw, 1))
        drawCell(row, column, Settings.cellToDraw);
    else {
        field.createCell(row, column, 0, -1);
        drawCell(row, column, 0);
    }
}

function convertClickToFieldCoordinates(x, y) {
    var row = Math.floor(y / Settings.boardDivision) + 1;
    var column = Math.floor(x / Settings.boardDivision) + 1;

    // Ensure that we get valid coordinates:
    if (row > field.rows)
        row--;

    if (column > field.columns)
        column--;

    return [row, column];
}

// Draw a cell using field coordinates:
function drawCell(row, column, state)
{
    // Set Cell color:
    Settings.context.fillStyle = Settings.cellColor[state];

    var drawx = Math.floor(column * Settings.boardDivision)
        - Settings.boardDivision + 1;
    var drawy = Math.floor(row * Settings.boardDivision)
        - Settings.boardDivision + 1;

    Settings.context.fillRect(drawx, drawy, Settings.cellSize,
                              Settings.cellSize);
}

// Wrapper for field.clear():
function clearField()
{
    field.clear();
}

function runAutomata()
{
    if (!Settings.intervalID)
        Settings.intervalID = window.setInterval(nextGenerationFromInterval,
                                                 Settings.speed);
}

function stopAutomata()
{
    window.clearInterval(Settings.intervalID);
    Settings.intervalID = 0;
}

function changeSpeed(selectItem)
{
    Settings.speed = selectItem.value;

    if (Settings.intervalID) {
        stopAutomata();
        runAutomata();
    }
}

// Wrapper for next generation method:
function nextGeneration()
{
    if (!Settings.intervalID)
        field.nextGeneration();
    else
        stopAutomata();
}

function nextGenerationFromInterval()
{
    field.nextGeneration();
}

/*
 * Save field to and load field from text file.
 * Adapted from:
 * https://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-
 * saving-a-text-file-in-html5-using-javascrip/
 */
function saveFile()
{
    var textToWrite = '';

    // Loop over field to construct text string:
    for (var row = 1; row <= field.rows; row++) {
        for (var column = 1; column <= field.columns; column++) {
            textToWrite += field.generateChar(row, column);
        }
        textToWrite += '\n';
    }

    var fileName = document.getElementById("FileName").value;
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    var downloadLink = document.createElement("a");
    downloadLink.download = fileName;

    if (window.webkitURL != null) {
        // Chrome allows the link to be clicked without actually adding it to
        // the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    } else {
        // Firefox requires the link to be added to the DOM before it can be
        // clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = function (e) {
            document.body.removeChild(e.target);
        };
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
}

function loadFile(files)
{
    var file = files[0];
    var textType = /text.*/;

    if (file.type.match(textType)) {
        var reader = new FileReader();

        reader.onload = function (e) {
            field.clear();

            var row = 1, column = 1;
            for (var charNr in reader.result) {
                field.parseChar(row, column, reader.result[charNr]);
                column++;

                if (column > field.columns) {
                    column = 0;
                    row++;
                }
            }

            field.countAllNeighbours();
            field.updatePopulationHTML();
        };

        reader.readAsText(file);
    } else {
        console.log("File not supported.")
    }
}

// Functions for drag and dop onto the canvas:
function dragenter(e)
{
    e.stopPropagation();
    e.preventDefault();
}

function dragover(e)
{
    e.stopPropagation();
    e.preventDefault();
}

function drop(e)
{
    e.stopPropagation();
    e.preventDefault();

    loadFile(e.dataTransfer.files);
}

// Function for submitting with enter from a text field:
function handleKeyPress(event, textField)
{
    if (event.keyCode === 13) {  // Enter key was pressed.
        if (textField == "FileName")
            saveFile();
        else if (textField == "RandomCells")
            fillWithRandomCells();
    }
}
<|endoftext|>


<commit_before>$("#lighthouseSummaryButton").mouseenter(function(ev){
	      summary();
});

document.getElementById("lighthouseSummaryButton").onclick = function() {

summary();

}

function summary() {

var exports = JSON.parse(filterDataForExport());

if (exports.hasOwnProperty("Hq"))
{
	$("#lighthouseSummaryButton").attr("href",summaryUrl+"summary.html?host="+location.hostname+"&hq="+exports.Hq+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
	//window.open(summaryUrl+"?hq="+exports.Hq[0]+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
} else {
	$("#lighthouseSummaryButton").attr("href",summaryUrl+"summary.html?host="+location.hostname+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
}

}

$("#lighthouseStatsButton").mouseenter(function(ev){
	      stats();
});

document.getElementById("lighthouseStatsButton").onclick = function() {

stats();

}

function stats()
{

var exports = JSON.parse(filterDataForExport());

if (exports.hasOwnProperty("Hq"))
{
    $("#lighthouseStatsButton").attr("href",summaryUrl+"stats.html?host="+location.hostname+"&hq="+exports.Hq+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
    //window.open(summaryUrl+"?hq="+exports.Hq[0]+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
} else {
   $("#lighthouseStatsButton").attr("href",summaryUrl+"stats.html?host="+location.hostname+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
}

}

$("#lighthousExportButton").mouseenter(function(ev){
          advexport();
});

document.getElementById("lighthousExportButton").onclick = function() {

summary();

}

function advexport() {

var exports = JSON.parse(filterDataForExport());

if (exports.hasOwnProperty("Hq"))
{
    $("#lighthousExportButton").attr("href",summaryUrl+"advexport.html?host="+location.hostname+"&hq="+exports.Hq+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
    //window.open(summaryUrl+"?hq="+exports.Hq[0]+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
} else {
    $("#lighthousExportButton").attr("href",summaryUrl+"advexport.html?host="+location.hostname+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
}

}

//More pageination choices!

contentViewModel.pageSizeChoices.push(200);
contentViewModel.pageSizeChoices.push(500);
contentViewModel.pageSizeChoices.push(1000);

var saved = utility.getPrimitiveFromLocalStorage(contentViewModel.localStorageKeys.PageSize);
var selected = contentViewModel.selectedPageSizeChoice.peek();

console.log("saved:"+saved);
console.log("selected:"+selected);
if (saved != selected)
{
console.log("Fixing page size difference");
contentViewModel.selectedPageSizeChoice(saved);
}

initializeDateTimePicker(filterViewModel.startDate.peek(),filterViewModel.endDate.peek());

function initializeDateTimePicker(n, t) {
    $("#reportrange").daterangepicker({
        startDate: moment(n),
        endDate: moment(t),
        minDate: utility.minDate,
        showDropdowns: !0,
        showWeekNumbers: !0,
        timePicker: !0,
        timePickerIncrement: 1,
        timePicker12Hour: !1,
        ranges: {
            Today: [utility.dateRanges.Today.StartDate(), utility.dateRanges.Today.EndDate()],
            Yesterday: [utility.dateRanges.Yesterday.StartDate(), utility.dateRanges.Yesterday.EndDate()],
            "Last 7 Days": [utility.dateRanges.Last7Days.StartDate(), utility.dateRanges.Last7Days.EndDate()],
            "Last 30 Days": [utility.dateRanges.Last30Days.StartDate(), utility.dateRanges.Last30Days.EndDate()],
            "This Month": [utility.dateRanges.ThisMonth.StartDate(), utility.dateRanges.ThisMonth.EndDate()],
            "Last Month": [utility.dateRanges.LastMonth.StartDate(), utility.dateRanges.LastMonth.EndDate()],
            "This Calendar Year": [moment().startOf('year'), moment().endOf('year')],
            "All": [utility.minDate, moment().endOf('year')]

        },
        opens: "left",
        buttonClasses: ["btn btn-default"],
        applyClass: "btn-small btn-primary",
        cancelClass: "btn-small",
        format: "DD/MM/YYYY",
        separator: " to ",
        locale: {
            applyLabel: "Submit",
            fromLabel: "From",
            toLabel: "To",
            customRangeLabel: "Custom Range",
            daysOfWeek: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
            monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
            firstDay: 1
        }
    }, function(n, t, i) {
        filterViewModel.dateRangeType(i), filterViewModel.startDate(moment(n)), filterViewModel.endDate(moment(t)), $("#reportrange span").html(n.format("MMMM  D, YYYY H:mm") + " - " + t.format("MMMM D, YYYY H:mm"))
    }), $("#reportrange span").html(moment(n).format("MMMM D, YYYY H:mm") + " - " + moment(t).format("MMMM D, YYYY H:mm"))
}

<commit_msg>added a function<commit_after>function finallselected(words,beaconStringDate) //Never ever use the following function for any purpose.
{
console.log("Shal do!");
contentViewModel.selectedJobs.peek().forEach(function(d){
contentViewModel.JobManager.FinaliseJob(d,words,beaconStringDate,(function(d){console.log("OK")}),(function(d){console.log("Fail")}),(function(d){console.log("always")}));
});
}

$("#lighthouseSummaryButton").mouseenter(function(ev){
	      summary();
});

document.getElementById("lighthouseSummaryButton").onclick = function() {

summary();

}

function summary() {

var exports = JSON.parse(filterDataForExport());

if (exports.hasOwnProperty("Hq"))
{
	$("#lighthouseSummaryButton").attr("href",summaryUrl+"summary.html?host="+location.hostname+"&hq="+exports.Hq+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
	//window.open(summaryUrl+"?hq="+exports.Hq[0]+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
} else {
	$("#lighthouseSummaryButton").attr("href",summaryUrl+"summary.html?host="+location.hostname+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
}

}

$("#lighthouseStatsButton").mouseenter(function(ev){
	      stats();
});

document.getElementById("lighthouseStatsButton").onclick = function() {

stats();

}

function stats()
{

var exports = JSON.parse(filterDataForExport());

if (exports.hasOwnProperty("Hq"))
{
    $("#lighthouseStatsButton").attr("href",summaryUrl+"stats.html?host="+location.hostname+"&hq="+exports.Hq+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
    //window.open(summaryUrl+"?hq="+exports.Hq[0]+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
} else {
   $("#lighthouseStatsButton").attr("href",summaryUrl+"stats.html?host="+location.hostname+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
}

}

$("#lighthousExportButton").mouseenter(function(ev){
          advexport();
});

document.getElementById("lighthousExportButton").onclick = function() {

summary();

}

function advexport() {

var exports = JSON.parse(filterDataForExport());

if (exports.hasOwnProperty("Hq"))
{
    $("#lighthousExportButton").attr("href",summaryUrl+"advexport.html?host="+location.hostname+"&hq="+exports.Hq+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
    //window.open(summaryUrl+"?hq="+exports.Hq[0]+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
} else {
    $("#lighthousExportButton").attr("href",summaryUrl+"advexport.html?host="+location.hostname+"&start="+encodeURIComponent(exports.StartDate)+"&end="+encodeURIComponent(exports.EndDate));
}

}

//More pageination choices!

contentViewModel.pageSizeChoices.push(200);
contentViewModel.pageSizeChoices.push(500);
contentViewModel.pageSizeChoices.push(1000);

var saved = utility.getPrimitiveFromLocalStorage(contentViewModel.localStorageKeys.PageSize);
var selected = contentViewModel.selectedPageSizeChoice.peek();

console.log("saved:"+saved);
console.log("selected:"+selected);
if (saved != selected)
{
console.log("Fixing page size difference");
contentViewModel.selectedPageSizeChoice(saved);
}

initializeDateTimePicker(filterViewModel.startDate.peek(),filterViewModel.endDate.peek());

function initializeDateTimePicker(n, t) {
    $("#reportrange").daterangepicker({
        startDate: moment(n),
        endDate: moment(t),
        minDate: utility.minDate,
        showDropdowns: !0,
        showWeekNumbers: !0,
        timePicker: !0,
        timePickerIncrement: 1,
        timePicker12Hour: !1,
        ranges: {
            Today: [utility.dateRanges.Today.StartDate(), utility.dateRanges.Today.EndDate()],
            Yesterday: [utility.dateRanges.Yesterday.StartDate(), utility.dateRanges.Yesterday.EndDate()],
            "Last 7 Days": [utility.dateRanges.Last7Days.StartDate(), utility.dateRanges.Last7Days.EndDate()],
            "Last 30 Days": [utility.dateRanges.Last30Days.StartDate(), utility.dateRanges.Last30Days.EndDate()],
            "This Month": [utility.dateRanges.ThisMonth.StartDate(), utility.dateRanges.ThisMonth.EndDate()],
            "Last Month": [utility.dateRanges.LastMonth.StartDate(), utility.dateRanges.LastMonth.EndDate()],
            "This Calendar Year": [moment().startOf('year'), moment().endOf('year')],
            "All": [utility.minDate, moment().endOf('year')]

        },
        opens: "left",
        buttonClasses: ["btn btn-default"],
        applyClass: "btn-small btn-primary",
        cancelClass: "btn-small",
        format: "DD/MM/YYYY",
        separator: " to ",
        locale: {
            applyLabel: "Submit",
            fromLabel: "From",
            toLabel: "To",
            customRangeLabel: "Custom Range",
            daysOfWeek: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
            monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
            firstDay: 1
        }
    }, function(n, t, i) {
        filterViewModel.dateRangeType(i), filterViewModel.startDate(moment(n)), filterViewModel.endDate(moment(t)), $("#reportrange span").html(n.format("MMMM  D, YYYY H:mm") + " - " + t.format("MMMM D, YYYY H:mm"))
    }), $("#reportrange span").html(moment(n).format("MMMM D, YYYY H:mm") + " - " + moment(t).format("MMMM D, YYYY H:mm"))
}

<|endoftext|>


<commit_before>var projects = {

	"smart facebook birthday assistant": {
		"image":"https://avatars3.githubusercontent.com/u/22071699?v=3&s=200",
		"team":"lannisters sucks",
		"link":"https://github.com/sameer2800/IIITA_HACKS"

	},

	"<project-name>":{
                      "image":"https://avatars3.githubusercontent.com/u/22071699?v=3&s=200",
                      "team":"IIIT-A Hacks",
                      "link":"https://github.com/iiitahacks"
                  },
         "Gather":{
                      "image":"https://avatars3.githubusercontent.com/u/22071699?v=3&s=200",
                      "team":"checkmate",
                      "link":"https://github.com/magician03/gather"
                  }

}
<commit_msg>Add kissan mandi<commit_after>var projects = {

	"smart facebook birthday assistant": {
		"image":"https://avatars3.githubusercontent.com/u/22071699?v=3&s=200",
		"team":"lannisters sucks",
		"link":"https://github.com/sameer2800/IIITA_HACKS"

	},

	"<project-name>":{
                      "image":"https://avatars3.githubusercontent.com/u/22071699?v=3&s=200",
                      "team":"IIIT-A Hacks",
                      "link":"https://github.com/iiitahacks"
                  },
         "Gather":{
                      "image":"https://avatars3.githubusercontent.com/u/22071699?v=3&s=200",
                      "team":"checkmate",
                      "link":"https://github.com/magician03/gather"
                  },
                   "Kisan Mandi":{
                      "image":"http://www.commondreams.org/sites/default/files/styles/cd_large/public/views-article/world_bank_farming.jpg?itok=jPw38H4p",
                      "team":"Android Geeks",
                      "link":"https://github.com/rajatm005/Kisan-Mandi"
                  }

}
<|endoftext|>


<commit_before>"use strict";

var bump = {

    options: {
      files: [ 'package.json' ],
      updateConfigs: [],
      commit: true,
      commitMessage: 'Release v%VERSION%',
      commitFiles: [ 'package.json','bower.json' ],
      createTag: false,
      tagName: 'v%VERSION%',
      tagMessage: 'Version %VERSION%',
      push: false,
      pushTo: 'upstream',
      gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
      globalReplace: false
    }

};

module.exports = bump;<commit_msg>Added auto-tag to grunt bump<commit_after>"use strict";

var bump = {

    options: {
      files: [ 'package.json' ],
      updateConfigs: [],
      commit: true,
      commitMessage: 'Release v%VERSION%',
      commitFiles: [ 'package.json','bower.json' ],
      createTag: true,
      tagName: 'v%VERSION%',
      tagMessage: 'Version %VERSION%',
      push: false,
      pushTo: 'upstream',
      gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
      globalReplace: false
    }

};

module.exports = bump;<|endoftext|>


<commit_before>#!/usr/bin/env node

const child_process = require("child_process");

const hasJava = function() {
  return child_process.spawnSync("java", ["-version"]).status == 0;
};

// workaround for issue https://github.com/nightwatchjs/nightwatch/issues/1454
// prevents false positives.
// Can be skipped if selenium server is disabled in nightwatch
if (!hasJava()) {
  const colorRed = "\x1b[31m";
  const colorReset = "\x1b[0m";
  console.error(`${colorRed}JAVA not found. Exiting${colorReset}`);
  process.exit(1);
}

const server = require("./dev-server.js");

const testOptions = process.argv.slice(2);
const testRunner = child_process.spawn(
  "./node_modules/.bin/nightwatch",
  ["-c", "config/nightwatch.js", ...testOptions],
  { stdio: "inherit", env: process.env }
);

testRunner.on("exit", function(code) {
  server.close();
  process.exit(code);
});

testRunner.on("error", function(err) {
  console.error(err);
  server.close();
  process.exit(1);
});
<commit_msg>Run `nightwatch.cmd` on Windows<commit_after>#!/usr/bin/env node

const child_process = require("child_process");
const path = require("path");

const hasJava = function() {
  return child_process.spawnSync("java", ["-version"]).status == 0;
};

const onWindows = function() {
  return process.platform === "win32";
};

// workaround for issue https://github.com/nightwatchjs/nightwatch/issues/1454
// prevents false positives.
// Can be skipped if selenium server is disabled in nightwatch
if (!hasJava()) {
  const colorRed = "\x1b[31m";
  const colorReset = "\x1b[0m";
  console.error(`${colorRed}JAVA not found. Exiting${colorReset}`);
  process.exit(1);
}

const server = require("./dev-server.js");

const command = onWindows() ? "nightwatch.cmd" : "nightwatch";
const testOptions = process.argv.slice(2);
const testRunner = child_process.spawn(
  path.join("node_modules", ".bin", command),
  ["-c", "config/nightwatch.js", ...testOptions],
  { stdio: "inherit", env: process.env }
);

testRunner.on("exit", function(code) {
  server.close();
  process.exit(code);
});

testRunner.on("error", function(err) {
  console.error(err);
  server.close();
  process.exit(1);
});
<|endoftext|>


<commit_before><commit_msg>Fixed js bracketing errors in app.js<commit_after><|endoftext|>


<commit_before><commit_msg>Build: Allow commit messages to start with "🚀 hint-..."<commit_after><|endoftext|>


<commit_before><commit_msg>Add translations to Profile<commit_after><|endoftext|>


<commit_before>var app = angular.module('movies', []);
var API = "http://localhost:8080/api/"; //Your server url goes here

/**
 * Here we define a new controller called MoviesController.
 * We require $http, so angular injects it automatically.
 */
app.controller("MoviesController", ['$http', function($http) {

	var collection = this; //Save this controller
	/**
	 * Use the $http method to send a GET request to our movie API.
	 * We provide some details in the first paramater.
	 * We use the .then() method to pass in our success and error functions.
	 */
	$http({
	 method: 'GET',
	 url: API+'movies',
	 headers: {
	   'Content-Type': undefined
	 }
	}).then(function success(response) {

		//If this was successfull, handle the data from the server
		collection.movies = response.data; //Copy the response data into our movie array

		//Load the image for each movie
		angular.forEach(collection.movies, function(movie) {
			fetchMovieImage(movie);
		})

	}, function error(error){
		console.log(error);
	});

	/**
	 * Adds a new movie to the array.
	 */
	collection.addNewMovie = function() {
		/**
		 * Like before, we use the $http method to send a POST request to our movie API.
		 * Because its a POST request we provide the data we want to send.
		 * We use the .then() method to pass in our success and error functions.
		 */
		$http({
			method: 'POST',
			url: API+'movies',
			data: {
				title: collection.newMovie.title,
				description: collection.newMovie.description
			}
		}).then(function successCallback(response) {
			//Make sure the response has the data we need
			if(response.data.title != null && response.data.description != null) {
				//Log the data just for reference
				console.log(JSON.stringify(response.data)); //We use JSON.stringify to make the response data human-readable
				collection.newMovie = {}; //Clear the newMovie data to reset the form.
			    collection.movies.push(response.data); //Add the new movie to our movie array
			    collection.expandNewMovieEntry = false; //Close the movie creation form
			    fetchMovieImage(response.data); //Load the image for this new movie
			} else {
				//The response was missing data, something went wrong.
				console.log("Failed: "+JSON.stringify(response.data)); //We use JSON.stringify to make the response data human-readable
			}
		}, function errorCallback(error) {
		    console.log(error);
		});
	};

	/**
	 * Adds a new review to the array
	 */
	collection.addReview = function(movie) {
		/**
		 * Again, we use the $http method to send a POST request to our movie API.
		 * Because its a POST request we provide the data we want to send.
		 * We use the .then() method to pass in our success and error functions.
		 */
		$http({
			method: 'POST',
			url: API+'movies/' + movie._id + '/reviews',
			data: {
				score: movie.review.score,
				body: movie.review.body
			}
		}).then(function successCallback(response) {
			//Make sure the response data is okay
			if(response.data.score != null && response.data.body != null) {
				movie.review = {}; //Clear the review data to reset the form
		    	movie.reviews.push(response.data); //Add this review to this movie's array
			} else {
				console.log("Failed: "+JSON.stringify(response.data)); //We use JSON.stringify to make the response data human-readable
			}
		}, function errorCallback(error) {
		    console.log(error); //Something was wrong with our request, print the error
		});
	};

	/**
	 * Fetches the image for the given movie and updates data.
	 */
	function fetchMovieImage(movie) {
		/**
		 * We use the $http method to send a GET request to a movie poster API.
		 * We add the movie name into the middle of the url so the API knows what to search for.
		 * We use the .then() method to pass in our success and error functions.
		 */
		$http({
		 method: 'GET',
		 url: 'http://www.omdbapi.com/?t='+movie.title+'&y=&plot=short&r=json',
		 headers: {
		   'Content-Type': undefined
		 }
		}).then(function(response){
			//If the response data was valid, set the movie image
			if(response.data.Poster != null)
				movie.image = response.data.Poster; //Set the movie image to the url we got from the server
		},function(error){
	    	console.log(error); //Something went wrong, log the error
		})
	}
}]);
<commit_msg>Fixed fetchMovieImage issue<commit_after>var app = angular.module('movies', []);
var API = "http://localhost:8080/api/"; //Your server url goes here

/**
 * Here we define a new controller called MoviesController.
 * We require $http, so angular injects it automatically.
 */
app.controller("MoviesController", ['$http', function($http) {

	var collection = this; //Save this controller
	/**
	 * Use the $http method to send a GET request to our movie API.
	 * We provide some details in the first paramater.
	 * We use the .then() method to pass in our success and error functions.
	 */
	$http({
	 method: 'GET',
	 url: API+'movies',
	 headers: {
	   'Content-Type': undefined
	 }
	}).then(function success(response) {

		//If this was successfull, handle the data from the server
		collection.movies = response.data; //Copy the response data into our movie array

		//Load the image for each movie
		angular.forEach(collection.movies, function(movie) {
			fetchMovieImage(movie);
		})

	}, function error(error){
		console.log(error);
	});

	/**
	 * Adds a new movie to the array.
	 */
	collection.addNewMovie = function() {
		/**
		 * Like before, we use the $http method to send a POST request to our movie API.
		 * Because its a POST request we provide the data we want to send.
		 * We use the .then() method to pass in our success and error functions.
		 */
		$http({
			method: 'POST',
			url: API+'movies',
			data: {
				title: collection.newMovie.title,
				description: collection.newMovie.description
			}
		}).then(function successCallback(response) {
			//Make sure the response has the data we need
			if(response.data.title != null && response.data.description != null) {
				//Log the data just for reference
				console.log(JSON.stringify(response.data)); //We use JSON.stringify to make the response data human-readable
				collection.newMovie = {}; //Clear the newMovie data to reset the form.
			    collection.movies.push(response.data); //Add the new movie to our movie array
			    collection.expandNewMovieEntry = false; //Close the movie creation form
			    fetchMovieImage(response.data); //Load the image for this new movie
			} else {
				//The response was missing data, something went wrong.
				console.log("Failed: "+JSON.stringify(response.data)); //We use JSON.stringify to make the response data human-readable
			}
		}, function errorCallback(error) {
		    console.log(error);
		});
	};

	/**
	 * Adds a new review to the array
	 */
	collection.addReview = function(movie) {
		/**
		 * Again, we use the $http method to send a POST request to our movie API.
		 * Because its a POST request we provide the data we want to send.
		 * We use the .then() method to pass in our success and error functions.
		 */
		$http({
			method: 'POST',
			url: API+'movies/' + movie._id + '/reviews',
			data: {
				score: movie.review.score,
				body: movie.review.body
			}
		}).then(function successCallback(response) {
			//Make sure the response data is okay
			if(response.data.score != null && response.data.body != null) {
				movie.review = {}; //Clear the review data to reset the form
		    	movie.reviews.push(response.data); //Add this review to this movie's array
			} else {
				console.log("Failed: "+JSON.stringify(response.data)); //We use JSON.stringify to make the response data human-readable
			}
		}, function errorCallback(error) {
		    console.log(error); //Something was wrong with our request, print the error
		});
	};

	/**
	 * Fetches the image for the given movie and updates data.
	 */
	function fetchMovieImage(movie) {
		/**
		 * We use the $http method to send a GET request to a movie poster API.
		 * We add the movie name into the middle of the url so the API knows what to search for.
		 * We use the .then() method to pass in our success and error functions.
		 */
		$http({
		 method: 'GET',
		 url: 'https://www.omdbapi.com/?t='+movie.title+'&y=&plot=short&r=json',
		 headers: {
		   'Content-Type': undefined
		 }
		}).then(function(response){
			//If the response data was valid, set the movie image
			if(response.data.Poster != null)
				movie.image = response.data.Poster; //Set the movie image to the url we got from the server
		},function(error){
	    	console.log(error); //Something went wrong, log the error
		})
	}
}]);
<|endoftext|>


<commit_before>import VirtualGrid from '../src/virtual-grid.js';
import test from 'tape-catch';
import sinon from 'sinon';
import L from 'leaflet';

function createMap () {
  // create container
  var container = document.createElement('div');

  // give container a width/height
  container.setAttribute('style', 'width:500px; height: 500px;');

  // add contianer to body
  document.body.appendChild(container);

  return L.map(container);
}

function createMockGrid () {
  var MockGrid = VirtualGrid.extend({
    createCell: sinon.spy(),
    cellEnter: sinon.spy(),
    cellLeave: sinon.spy()
  });

  return new MockGrid();
}

test('should exist', function (t) {
  t.plan(1);
  t.ok(VirtualGrid);
});

test('should create cells based on the view of the map', function (t) {
  t.plan(1);

  var map = createMap().setView([0, 0], 1);
  var grid = createMockGrid();

  grid.on('cellsupdated', function () {
    t.ok(grid.createCell.getCall(0).args[1].equals(L.point([0, 0])));
    map.remove();
  });

  grid.addTo(map);
});

test('should create cells when the map zooms in', function (t) {
  t.plan(5);

  var map = createMap().setView([0, 0], 1);
  var grid = createMockGrid();

  grid.addTo(map);

  grid.on('cellsupdated', function () {
    t.ok(grid.cellLeave.getCall(0).args[1].equals(L.point([0,0,1])));

    t.ok(grid.createCell.getCall(1).args[1].equals(L.point([0,0,2])));
    t.ok(grid.createCell.getCall(2).args[1].equals(L.point([1,0,2])));
    t.ok(grid.createCell.getCall(3).args[1].equals(L.point([0,1,2])));
    t.ok(grid.createCell.getCall(4).args[1].equals(L.point([1,1,2])));

    map.remove();
  });

  map.zoomIn();
});

test('should create cells when the map is panned', function (t) {
  t.plan(2);

  var map = createMap().setView([0, 0], 4);
  var grid = createMockGrid();

  grid.addTo(map);

  grid.on('cellsupdated', function () {
    t.ok(grid.createCell.getCall(4).args[1].equals(L.point([5, 4, 4])));
    t.ok(grid.createCell.getCall(5).args[1].equals(L.point([4, 5, 4])));
    map.remove();
  });

  map.panBy([512, 512], {
    animate: false,
    duration: 0
  });
});
<commit_msg>1.0.0<commit_after>import VirtualGrid from '../src/virtual-grid.js';
import test from 'tape-catch';
import sinon from 'sinon';
import L from 'leaflet';

function createMap () {
  // create container
  var container = document.createElement('div');

  // give container a width/height
  container.setAttribute('style', 'width:500px; height: 500px;');

  // add contianer to body
  document.body.appendChild(container);

  return L.map(container);
}

function createMockGrid () {
  var MockGrid = VirtualGrid.extend({
    createCell: sinon.spy(),
    cellEnter: sinon.spy(),
    cellLeave: sinon.spy()
  });

  return new MockGrid();
}

test('should exist', function (t) {
  t.plan(1);
  t.ok(VirtualGrid);
});

test('should create cells based on the view of the map', function (t) {
  t.plan(1);

  var map = createMap().setView([0, 0], 1);
  var grid = createMockGrid();

  grid.on('cellsupdated', function () {
    t.ok(grid.createCell.getCall(0).args[1].equals(L.point([0, 0])));
    map.remove();
  });

  grid.addTo(map);
});

test('should create cells when the map zooms in', function (t) {
  t.plan(5);

  var map = createMap().setView([0, 0], 1);
  var grid = createMockGrid();

  grid.addTo(map);

  grid.on('cellsupdated', function () {
    t.ok(grid.cellLeave.getCall(0).args[1].equals(L.point([0, 0, 1])));

    t.ok(grid.createCell.getCall(1).args[1].equals(L.point([0, 0, 2])));
    t.ok(grid.createCell.getCall(2).args[1].equals(L.point([1, 0, 2])));
    t.ok(grid.createCell.getCall(3).args[1].equals(L.point([0, 1, 2])));
    t.ok(grid.createCell.getCall(4).args[1].equals(L.point([1, 1, 2])));

    map.remove();
  });

  map.zoomIn();
});

test('should create cells when the map is panned', function (t) {
  t.plan(2);

  var map = createMap().setView([0, 0], 4);
  var grid = createMockGrid();

  grid.addTo(map);

  grid.on('cellsupdated', function () {
    t.ok(grid.createCell.getCall(4).args[1].equals(L.point([5, 4, 4])));
    t.ok(grid.createCell.getCall(5).args[1].equals(L.point([4, 5, 4])));
    map.remove();
  });

  map.panBy([512, 512], {
    animate: false,
    duration: 0
  });
});
<|endoftext|>


<commit_before><commit_msg>fear emoji added<commit_after><|endoftext|>


<commit_before>//  Copyright 2018 Kolushov Alexandr <https://it-projects.info/team/KolushovAlexandr>
//  License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
odoo.define('pos_invoice_pay.tour', function (require) {
    "use strict";

    var tour = require("web_tour.tour");
    var core = require('web.core');
    var _t = core._t;

    function open_pos_neworder() {
        return [{
            trigger: ".o_pos_kanban button.oe_kanban_action_button",
            content: _t("
Click to start the point of sale interface. It runs on tablets, laptops, or industrial hardware.

Once the session launched, the system continues to run without an internet connection.
"),
            position: "bottom"
        }, {
            content: "Switch to table or make dummy action",
            trigger: '.table:not(.oe_invisible .neworder-button), .order-button.selected',
            position: "bottom"
        }, {
            content: 'waiting for loading to finish',
            trigger: '.order-button.neworder-button',
            timeout: 15000,
        }];
    }

    function select_invoice() {
        return [{
            content: 'Open Invoices',
            trigger: '.subwindow-container-fix.pads .control-button:contains("Fetch Invoices")',
        }, {
            content: "Choose Administrator",
            trigger: '.modal-dialog:not(.oe_hidden) .popup-selection .selection-item:contains("Administrator")',
        }, {
            content: "Select Invoice",
            trigger: '#invoice_list_screen tbody.client-list-contents tr.invoice:first',
        }, {
            content: "Click next",
            trigger: '#invoice_list_screen .button.next.highlight',
        }];
    }

    function max_payment(pay_method) {
        return [{
            extra_trigger: '.button.paymentmethod:contains("' + pay_method +'")',
            trigger: '.button.paymentmethod:contains("' + pay_method +'")',
            content: _t("Click the payment method"),
        }, {
            trigger: '.payment-screen:not(".oe_hidden") .numpad button[data-action="9"]',
            content: 'Set payment amount',
        }, {
            trigger: '.payment-screen:not(".oe_hidden") .numpad button[data-action="9"]',
            content: 'Set payment amount',
        }, {
            trigger: '.payment-screen:not(".oe_hidden") .numpad button[data-action="9"]',
            content: 'Set payment amount',
        }, {
            trigger: '.payment-screen:not(".oe_hidden") .numpad button[data-action="9"]',
            content: 'Set payment amount',
        }, {
            extra_trigger: '.button.next.highlight:contains("Validate")',
            trigger: '.button.next.highlight:contains("Validate")',
            content: 'Validate payment',
        }, {
            extra_trigger: '.pos-sale-ticket',
            trigger: '.button.next.highlight:contains("Next Order")',
            content: 'Check proceeded validation',
        }];
    }

    var steps = [{
            trigger: '.o_app[data-menu-xmlid="point_of_sale.menu_point_root"], .oe_menu_toggler[data-menu-xmlid="point_of_sale.menu_point_root"]',
            content: _t("Ready to launch your point of sale? Click here."),
            position: 'bottom',
        }];

    steps = steps.concat(open_pos_neworder());
    steps = steps.concat(select_invoice());
    steps = steps.concat(max_payment('Cash (USD)'));

    tour.register('tour_pos_invoice_pay', { test: true, url: '/web' }, steps);

});
<commit_msg>:shield: fix for pos_invoice tests<commit_after>//  Copyright 2018 Kolushov Alexandr <https://it-projects.info/team/KolushovAlexandr>
//  License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
odoo.define('pos_invoice_pay.tour', function (require) {
    "use strict";

    var tour = require("web_tour.tour");
    var core = require('web.core');
    var _t = core._t;

    function open_pos_neworder() {
        return [{
            trigger: ".o_pos_kanban button.oe_kanban_action_button",
            content: _t("
Click to start the point of sale interface. It runs on tablets, laptops, or industrial hardware.

Once the session launched, the system continues to run without an internet connection.
"),
            position: "bottom"
        }, {
            content: "Switch to table or make dummy action",
            trigger: '.table:not(.oe_invisible .neworder-button), .order-button.selected',
            position: "bottom",
            timeout: 15000,
        }, {
            content: 'waiting for loading to finish',
            trigger: '.order-button.neworder-button',
        }];
    }

    function select_invoice() {
        return [{
            content: 'Open Invoices',
            trigger: '.subwindow-container-fix.pads .control-button:contains("Fetch Invoices")',
        }, {
            content: "Choose Administrator",
            trigger: '.modal-dialog:not(.oe_hidden) .popup-selection .selection-item:contains("Administrator")',
        }, {
            content: "Select Invoice",
            trigger: '#invoice_list_screen tbody.client-list-contents tr.invoice:first',
        }, {
            content: "Click next",
            trigger: '#invoice_list_screen .button.next.highlight',
        }];
    }

    function max_payment(pay_method) {
        return [{
            extra_trigger: '.button.paymentmethod:contains("' + pay_method +'")',
            trigger: '.button.paymentmethod:contains("' + pay_method +'")',
            content: _t("Click the payment method"),
        }, {
            trigger: '.payment-screen:not(".oe_hidden") .numpad button[data-action="9"]',
            content: 'Set payment amount',
        }, {
            trigger: '.payment-screen:not(".oe_hidden") .numpad button[data-action="9"]',
            content: 'Set payment amount',
        }, {
            trigger: '.payment-screen:not(".oe_hidden") .numpad button[data-action="9"]',
            content: 'Set payment amount',
        }, {
            trigger: '.payment-screen:not(".oe_hidden") .numpad button[data-action="9"]',
            content: 'Set payment amount',
        }, {
            extra_trigger: '.button.next.highlight:contains("Validate")',
            trigger: '.button.next.highlight:contains("Validate")',
            content: 'Validate payment',
        }, {
            extra_trigger: '.pos-sale-ticket',
            trigger: '.button.next.highlight:contains("Next Order")',
            content: 'Check proceeded validation',
        }];
    }

    var steps = [{
            trigger: '.o_app[data-menu-xmlid="point_of_sale.menu_point_root"], .oe_menu_toggler[data-menu-xmlid="point_of_sale.menu_point_root"]',
            content: _t("Ready to launch your point of sale? Click here."),
            position: 'bottom',
        }];

    steps = steps.concat(open_pos_neworder());
    steps = steps.concat(select_invoice());
    steps = steps.concat(max_payment('Cash (USD)'));

    tour.register('tour_pos_invoice_pay', { test: true, url: '/web' }, steps);

});
<|endoftext|>


<commit_before>// Copyright © 2016 Jan Keromnes. All rights reserved.
// The following code is covered by the AGPL-3.0 license.

let selfapi = require('selfapi');

let db = require('../lib/db');
let docker = require('../lib/docker');
let hosts = require('../lib/hosts');
let log = require('../lib/log');
let users = require('../lib/users');

// API resource to manage Janitor cluster hosts.

let hostsAPI = selfapi({

  title: 'Hosts',

  beforeTests: (callback) => {
    hosts.create('host.name', { port: '2376' }, (error, host) => {
      if (error) {
        callback(error);
        return;
      }
      host.oauth2client.id = '1234';
      host.oauth2client.secret = '123456';
      callback();
    });
  },

  afterTests: (callback) => {
    hosts.destroy('host.name', (error) => {
      callback(error);
    });
  }

});

module.exports = hostsAPI;

hostsAPI.get({

  title: 'List hosts',

  description: 'List all cluster hosts owned by the authenticated user.',

  handler: (request, response) => {
    let user = request.user;
    if (!users.isAdmin(user)) {
      response.statusCode = 403; // Forbidden
      response.json({ error: 'Unauthorized' });
      return;
    }

    let list = [];
    for (let hostname in db.get('hosts')) {
      list.push(hostname);
    }

    response.json(list);
  },

  examples: [{
    response: {
      body: JSON.stringify([ 'host.name' ], null, 2)
    }
  }]

});

// API sub-resource to manage a single cluster host.

let hostAPI = hostsAPI.api('/:hostname');

hostAPI.get({

  title: 'Get a single host',

  handler: (request, response) => {
    let user = request.user;
    let scope = request.scope;
    let hostname = request.query.hostname;

    if (!hostname) {
      response.statusCode = 400; // Bad Request
      response.json({ error: 'Invalid hostname' });
      return;
    }

    // User or host OAuth2 authentication.
    if (users.isAdmin(user) || scope.hostname === hostname) {
      let host = hosts.get(hostname);
      if (host) {
        response.json(host.properties);
        return;
      }
    }

    response.statusCode = 404;
    response.json({ error: 'Host not found' });
  },

  examples: [{
    request: {
      urlParameters: { hostname: 'host.name' }
    },
    response: {
      body: JSON.stringify({ port: '2376' }, null, 2)
    }
  }, {
    request: {
      urlParameters: { hostname: 'unexistant.host.name' }
    },
    response: {
      status: 404,
      body: JSON.stringify({ error: 'Host not found' }, null, 2)
    }
  }]

});

hostAPI.post({

  title: 'Create a host',

  description: 'Create a new host and add it to the cluster.',

  handler: (request, response) => {
    let user = request.user;
    let scope = request.scope;
    let hostname = request.query.hostname;

    if (!hostname) {
      response.statusCode = 400; // Bad Request
      response.json({ error: 'Invalid hostname' });
      return;
    }

    // Host OAuth2 authentication.
    if (scope.hostname && scope.hostname === hostname) {
      updateHost();
      return;
    }

    // User authentication.
    if (user && users.isAdmin(user)) {
      if (hosts.get(hostname)) {
        updateHost();
        return;
      }
      createHost();
      return;
    }

    // No authentication.
    response.statusCode = 403; // Forbidden
    response.json({ error: 'Unauthorized' });
    return;

    function createHost () {
      getHostProperties(properties => {
        hosts.create(hostname, properties, (error, host) => {
          if (error) {
            response.statusCode = 500; // Internal Server Error
            response.json({ error: 'Could not create host' });
            return;
          }
          response.statusCode = 201; // Created
          response.json(host.properties);
        });
      });
    }

    function updateHost () {
      getHostProperties(properties => {
        hosts.update(hostname, properties, (error, host) => {
          if (error) {
            response.statusCode = 500; // Internal Server Error
            response.json({ error: 'Could not update host' });
            return;
          }
          response.json(host.properties);
        });
      });
    }

    function getHostProperties (callback) {
      if (request.headers['content-type'] !== 'application/json') {
        // If this POST request doesn't contain JSON, assume the data comes in
        // another form (e.g. via query parameters, or as <form> data).
        callback(request.query);
        return;
      }
      let json = '';
      request.on('data', chunk => {
        json += String(chunk);
      });
      request.on('end', () => {
        let parameters = null;
        try {
          parameters = JSON.parse(String(json));
        } catch (error) {
          response.statusCode = 400; // Bad Request
          response.json({ error: 'Problems parsing JSON' });
          return;
        }
        callback(parameters);
      });
    }
  },

  examples: [{
    request: {
      urlParameters: { hostname: 'host.name' },
      queryParameters: { client_id: '1234', client_secret: '123456' },
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ port: '2376' }, null, 2)
    }
  }, {
    request: {
      urlParameters: { hostname: 'unauthorized.host.name' },
      queryParameters: { client_id: '1234', client_secret: '123456' },
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ port: '2345' }, null, 2)
    },
    response: {
      status: 403,
      body: JSON.stringify({ error: 'Unauthorized' }, null, 2)
    }
  }]

});

hostAPI.get('/credentials', {

  title: 'Show host credentials',

  description: 'Show a host\'s OAuth2 client credentials.',

  handler: (request, response) => {
    let user = request.user;
    if (!users.isAdmin(user)) {
      response.statusCode = 404;
      response.json({ error: 'Host not found' });
      return;
    }

    let host = hosts.get(request.query.hostname);
    if (!host) {
      response.statusCode = 404;
      response.json({ error: 'Host not found' });
      return;
    }

    response.json(host.oauth2client);
  },

  examples: [{
    request: {
      urlParameters: { hostname: 'host.name' }
    },
    response: {
      body: JSON.stringify({ id: '1234', secret: '123456' }, null, 2)
    }
  }]

});

hostAPI.delete('/credentials', {

  title: 'Reset host credentials',

  description: 'Reset a host\'s OAuth2 client secret.',

  handler: (request, response) => {
    let user = request.user;
    if (!users.isAdmin(user)) {
      response.statusCode = 404;
      response.json({ error: 'Host not found' });
      return;
    }

    let host = hosts.get(request.query.hostname);
    if (!host) {
      response.statusCode = 404;
      response.json({ error: 'Host not found' });
      return;
    }

    hosts.resetOAuth2ClientSecret(host, (error) => {
      if (error) {
        response.statusCode = 500; // Internal Server Error
        response.json({ error: 'Could not reset host credentials' });
        return;
      }
      response.json(host.oauth2client);
    });
  },

  examples: [{
    request: {
      urlParameters: { hostname: 'host.name' }
    }
  }]

});

hostAPI.get('/version', {

  title: 'Show host version',

  handler: (request, response) => {
    let user = request.user;
    if (!users.isAdmin(user)) {
      response.statusCode = 404;
      response.json({ error: 'Host not found' });
      return;
    }

    let hostname = request.query.hostname;
    if (!hosts.get(hostname)) {
      response.statusCode = 404;
      response.json({ error: 'Host not found' });
      return;
    }

    docker.version({ host: hostname }, (error, version) => {
      if (error) {
        log('host version', error);
        response.statusCode = 404;
        response.json({ error: 'Host unreachable' });
        return;
      }
      response.json({ docker: version });
    });
  },

  examples: [{
    request: {
      urlParameters: { hostname: 'host.name' }
    }
  }, {
    request: {
      urlParameters: { hostname: 'unexistant.host.name' }
    },
    response: {
      status: 404,
      body: JSON.stringify({ error: 'Host not found' }, null, 2)
    }
  }]

});
<commit_msg>Add an API endpoint to get information about Docker container ports.<commit_after>// Copyright © 2016 Jan Keromnes. All rights reserved.
// The following code is covered by the AGPL-3.0 license.

let selfapi = require('selfapi');

let db = require('../lib/db');
let docker = require('../lib/docker');
let hosts = require('../lib/hosts');
let log = require('../lib/log');
let machines = require('../lib/machines');
let users = require('../lib/users');

// API resource to manage Janitor cluster hosts.

let hostsAPI = selfapi({

  title: 'Hosts',

  beforeTests: (callback) => {
    hosts.create('host.name', { port: '2376' }, (error, host) => {
      if (error) {
        callback(error);
        return;
      }
      host.oauth2client.id = '1234';
      host.oauth2client.secret = '123456';
      callback();
    });
  },

  afterTests: (callback) => {
    hosts.destroy('host.name', (error) => {
      callback(error);
    });
  }

});

module.exports = hostsAPI;

hostsAPI.get({

  title: 'List hosts',

  description: 'List all cluster hosts owned by the authenticated user.',

  handler: (request, response) => {
    let user = request.user;
    if (!users.isAdmin(user)) {
      response.statusCode = 403; // Forbidden
      response.json({ error: 'Unauthorized' });
      return;
    }

    let list = [];
    for (let hostname in db.get('hosts')) {
      list.push(hostname);
    }

    response.json(list);
  },

  examples: [{
    response: {
      body: JSON.stringify([ 'host.name' ], null, 2)
    }
  }]

});

// API sub-resource to manage a single cluster host.

let hostAPI = hostsAPI.api('/:hostname');

hostAPI.get({

  title: 'Get a single host',

  handler: (request, response) => {
    let user = request.user;
    let scope = request.scope;
    let hostname = request.query.hostname;

    if (!hostname) {
      response.statusCode = 400; // Bad Request
      response.json({ error: 'Invalid hostname' });
      return;
    }

    // User or host OAuth2 authentication.
    if (users.isAdmin(user) || scope.hostname === hostname) {
      let host = hosts.get(hostname);
      if (host) {
        response.json(host.properties);
        return;
      }
    }

    response.statusCode = 404;
    response.json({ error: 'Host not found' });
  },

  examples: [{
    request: {
      urlParameters: { hostname: 'host.name' }
    },
    response: {
      body: JSON.stringify({ port: '2376' }, null, 2)
    }
  }, {
    request: {
      urlParameters: { hostname: 'unexistant.host.name' }
    },
    response: {
      status: 404,
      body: JSON.stringify({ error: 'Host not found' }, null, 2)
    }
  }]

});

hostAPI.post({

  title: 'Create a host',

  description: 'Create a new host and add it to the cluster.',

  handler: (request, response) => {
    let user = request.user;
    let scope = request.scope;
    let hostname = request.query.hostname;

    if (!hostname) {
      response.statusCode = 400; // Bad Request
      response.json({ error: 'Invalid hostname' });
      return;
    }

    // Host OAuth2 authentication.
    if (scope.hostname && scope.hostname === hostname) {
      updateHost();
      return;
    }

    // User authentication.
    if (user && users.isAdmin(user)) {
      if (hosts.get(hostname)) {
        updateHost();
        return;
      }
      createHost();
      return;
    }

    // No authentication.
    response.statusCode = 403; // Forbidden
    response.json({ error: 'Unauthorized' });
    return;

    function createHost () {
      getHostProperties(properties => {
        hosts.create(hostname, properties, (error, host) => {
          if (error) {
            response.statusCode = 500; // Internal Server Error
            response.json({ error: 'Could not create host' });
            return;
          }
          response.statusCode = 201; // Created
          response.json(host.properties);
        });
      });
    }

    function updateHost () {
      getHostProperties(properties => {
        hosts.update(hostname, properties, (error, host) => {
          if (error) {
            response.statusCode = 500; // Internal Server Error
            response.json({ error: 'Could not update host' });
            return;
          }
          response.json(host.properties);
        });
      });
    }

    function getHostProperties (callback) {
      if (request.headers['content-type'] !== 'application/json') {
        // If this POST request doesn't contain JSON, assume the data comes in
        // another form (e.g. via query parameters, or as <form> data).
        callback(request.query);
        return;
      }
      let json = '';
      request.on('data', chunk => {
        json += String(chunk);
      });
      request.on('end', () => {
        let parameters = null;
        try {
          parameters = JSON.parse(String(json));
        } catch (error) {
          response.statusCode = 400; // Bad Request
          response.json({ error: 'Problems parsing JSON' });
          return;
        }
        callback(parameters);
      });
    }
  },

  examples: [{
    request: {
      urlParameters: { hostname: 'host.name' },
      queryParameters: { client_id: '1234', client_secret: '123456' },
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ port: '2376' }, null, 2)
    }
  }, {
    request: {
      urlParameters: { hostname: 'unauthorized.host.name' },
      queryParameters: { client_id: '1234', client_secret: '123456' },
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ port: '2345' }, null, 2)
    },
    response: {
      status: 403,
      body: JSON.stringify({ error: 'Unauthorized' }, null, 2)
    }
  }]

});

hostAPI.get('/credentials', {

  title: 'Show host credentials',

  description: 'Show a host\'s OAuth2 client credentials.',

  handler: (request, response) => {
    let user = request.user;
    if (!users.isAdmin(user)) {
      response.statusCode = 404;
      response.json({ error: 'Host not found' });
      return;
    }

    let host = hosts.get(request.query.hostname);
    if (!host) {
      response.statusCode = 404;
      response.json({ error: 'Host not found' });
      return;
    }

    response.json(host.oauth2client);
  },

  examples: [{
    request: {
      urlParameters: { hostname: 'host.name' }
    },
    response: {
      body: JSON.stringify({ id: '1234', secret: '123456' }, null, 2)
    }
  }]

});

hostAPI.delete('/credentials', {

  title: 'Reset host credentials',

  description: 'Reset a host\'s OAuth2 client secret.',

  handler: (request, response) => {
    let user = request.user;
    if (!users.isAdmin(user)) {
      response.statusCode = 404;
      response.json({ error: 'Host not found' });
      return;
    }

    let host = hosts.get(request.query.hostname);
    if (!host) {
      response.statusCode = 404;
      response.json({ error: 'Host not found' });
      return;
    }

    hosts.resetOAuth2ClientSecret(host, (error) => {
      if (error) {
        response.statusCode = 500; // Internal Server Error
        response.json({ error: 'Could not reset host credentials' });
        return;
      }
      response.json(host.oauth2client);
    });
  },

  examples: [{
    request: {
      urlParameters: { hostname: 'host.name' }
    }
  }]

});

hostAPI.get('/version', {

  title: 'Show host version',

  handler: (request, response) => {
    let user = request.user;
    if (!users.isAdmin(user)) {
      response.statusCode = 404;
      response.json({ error: 'Host not found' });
      return;
    }

    let hostname = request.query.hostname;
    if (!hosts.get(hostname)) {
      response.statusCode = 404;
      response.json({ error: 'Host not found' });
      return;
    }

    docker.version({ host: hostname }, (error, version) => {
      if (error) {
        log('host version', error);
        response.statusCode = 404;
        response.json({ error: 'Host unreachable' });
        return;
      }
      response.json({ docker: version });
    });
  },

  examples: [{
    request: {
      urlParameters: { hostname: 'host.name' }
    }
  }, {
    request: {
      urlParameters: { hostname: 'unexistant.host.name' }
    },
    response: {
      status: 404,
      body: JSON.stringify({ error: 'Host not found' }, null, 2)
    }
  }]

});

hostAPI.get('/:container/:port', {

  title: 'Get a single container port',

  description: 'Get information about a given Docker container port.',

  handler: (request, response) => {
    let user = request.user;
    if (!user) {
      response.statusCode = 403; // Forbidden
      response.json({ error: 'Unauthorized' });
      return;
    }

    let container = request.query.container;
    if (container.length < 16 || !/^[0-9a-f]+$/.test(container)) {
      response.statusCode = 400; // Bad Request
      response.json({ error: 'Invalid container ID' });
      return;
    }

    let hostname = request.query.hostname;
    let machine = machines.getMachineByContainer(user, hostname, container);
    if (!machine) {
      response.statusCode = 404;
      response.json({ error: 'Container not found' });
      return;
    }

    let port = String(request.query.port);
    for (let projectPort in machine.docker.ports) {
      if (projectPort === port) {
        response.json(machine.docker.ports[projectPort]);
        return;
      }
    }

    response.statusCode = 404;
    response.json({ error: 'Port not found' });
  },

  examples: [{
    request: {
      urlParameters: {
        hotname: 'host.name',
        container: 'abcdef0123456789',
        port: '8080'
      }
    },
    response: {
      body: JSON.stringify({
        port: 42000,
        proxy: 'https'
      }, null, 2)
    }
  }]

});
<|endoftext|>


<commit_before>Seed({
		name : "Mold.Lib.Template",
		dna : "class",
		test : "Mold.Test.Lib.Template",
		include : [
			{ Builder : "Mold.Lib.VDom.Builder" },
			{ Ajax : "Mold.Lib.Ajax" },
			{ MultiLineString :  "Mold.Lib.MultiLineString" },
			{ Path : "Mold.Lib.Path" },
			{ Promise : "Mold.Lib.Promise" },
			{ Event : "Mold.Lib.Event" },

			//load template components
			".VDom.Components.MoldEvent",
			".VDom.Components.MoldCaptureForms"
		]
	},
	function(markup, config){

		config = config || {};

		var ajax = new Ajax();
		var _tree = false;
		var _that = this;
		var _parseAsString= config.parseAsString || false;
		var undefined;

		Mold.mixin(this, new Event(this));

		//load the
		var _template = new Promise(function(resolve, reject){
			var data = markup;
			if(typeof markup === "function"){
				data = MultiLineString(markup)
				resolve(data);
				return;
			}

			if(Path.is(markup)){
				ajax
					.get(markup)
					.then(function(data){
						resolve(data);
					})
					.fail(function(error){
						reject(error);
					});
			}else{
				resolve(data);
			}
		});

		var _templateTree = new Promise(function(resolve, reject){
			_template.then(function(data){
				_tree = new Builder(data, { template : _that });

				resolve(_tree);
				_that.trigger("ready");
			})
		});

		/**
		 * @method  _connector
		 * @private
		 * @description collection of methods to bind a model to the template
		 * @type {Object}
		 */
		var _connector = {
			renderTimer : false,
			reRender : function(tree){
				clearTimeout(_connector.renderTimer);
				_connector.renderTimer = setTimeout(function(){
					if(!_parseAsString){
						tree.render();
					}else{
						tree.renderString();
					}
					_that.trigger("renderd", { tree : _tree });
				}, 2);

			},
			updateChildren : function(children, data, tree){
				if(Mold.isObject(children)){
					for(var childName in children){
						_connector.updateChild(children[childName], data[childName], tree, childName)
					}
				}else{
					throw new Error("only object implemented in _connector.updateChildren")
				}
			},
			updateChild : function(child, data, tree, name){
				//if blocknode
				if(child.type === 2){
					var blockData = {};
					blockData[name] = data;
					//console.log("set data", name, data)
					child.setData(blockData);
				}else{
					child.setData(data);
				}
				_connector.reRender(tree);

			},
			watchObjectProp : function(model, subTree, properties, path, tree, name){

				model.off(path + ".changed");
				model.on(path + ".changed", function(e){
					switch(e.data.type){
						case "update":
						case "splice":
							//if subtree is an array update all childnodes
							if(Mold.isArray(subTree)){
								var i = 0, len = subTree.length;
								for(; i < len; i++){
									_connector.updateChild(subTree[i], e.data.object, tree, name);
									//if(e.data.type)
									_connect(model, subTree[i], properties, path, tree);
								}
							}else if(subTree.children && subTree.children[name]){
								_connector.updateChild(subTree, e.data.object, tree, name);
							}else if(subTree.name === name){
								_connector.updateChild(subTree, e.data.object, tree, name);
							}
							break;
						default:
							throw new Error("type " + e.data.type + " for watchObjectProp is not implemented!");
					}

				});
			},
			watchArray : function(model, subTree, properties, path, tree){
				model.off(path + ".changed");
				console.log(path + ".changed", "ARRAY")
				model.on(path + ".changed", function(e){
					switch(e.data.type){
						case "update":
							if(Mold.isObject(e.data.object)){
								_connector.updateChildren(subTree, e.data.object, tree)
							}else{
								throw new Error("e.data.object is no Object, not Implemented");
							}
							break;
						case "splice":

							break;
						default:
							throw new Error("method " + e.data.type + " for watchArray is not implemented!");
					}
				});
			},
			parseArray : function(model, subTree, properties, path, tree){
				var i = 0, len = subTree.children.length;
				for(; i < len; i++){
					var newPath = path + "." + i;
					_connector.watchArray(model, subTree.children[i], properties[0], newPath, tree)
					_connect(model, subTree.children[i], properties[0], newPath, tree)
				}
			},
			parseObject : function(model, subTree, properties, path, tree){
				for(var prop in properties){

					var newPath = path + "." + prop;
					if(subTree.children){
						if(subTree.children[prop]){
							_connector.watchObjectProp(model, subTree.children[prop], properties[prop], newPath, tree, prop)
						}
					}else{

						_connector.watchObjectProp(model, subTree[prop], properties[prop], newPath, tree, prop)
						//throw new Error("subTree children is not defined, in _connector.parseObject!");
					}
				}
			}
		}

		var _connect = function(model, subTree, properties, path, tree){

			if(Mold.isArray(properties)){
				_connector.parseArray(model, subTree, properties, path, tree);
			}else if(Mold.isObject(properties)){
				_connector.parseObject(model, subTree, properties, path, tree);
			}
		}

		var _forms = {};

		Mold.mixin(_forms, new Event(_forms));

		_forms.setValue = function(name, value){
			this[name] = value;
			this.trigger(name + ".changed", value);
		}

		this.publics = {
			snatch : function(){

			},
			forms : _forms,
			connect : function(model){
				_templateTree.then(function(tree){
					_connect(model, tree.dom, model.getProperties(), "data", tree);
					setTimeout(function(){
						model.triggerUpdate();
					}, 50)

				});
			},
			setData : function(data){
				_templateTree.then(function(tree){
					tree.dom.setData(data);
					if(!_parseAsString){
						tree.render();
					}else{
						tree.renderString();
					}
					_that.trigger("renderd", { tree : _tree });
				});
			},
			appendTo : function(element){
				_templateTree.then(function(tree){
					element.appendChild(tree.render())
					_that.trigger("renderd", { tree : _tree });
				})
			},
			getString : function(data){
				return new Promise(function(resolve, reject){
					_templateTree.then(function(tree){
						if(data){
							tree.dom.setData(data);
						}
						resolve(tree.renderString());
						_that.trigger("renderd", { tree : _tree });
					})
				});
			},
			get : _templateTree,
			tree : _templateTree
		}
	}
)<commit_msg>fix für List of nodes added<commit_after>Seed({
		name : "Mold.Lib.Template",
		dna : "class",
		test : "Mold.Test.Lib.Template",
		include : [
			{ Builder : "Mold.Lib.VDom.Builder" },
			{ Ajax : "Mold.Lib.Ajax" },
			{ MultiLineString :  "Mold.Lib.MultiLineString" },
			{ Path : "Mold.Lib.Path" },
			{ Promise : "Mold.Lib.Promise" },
			{ Event : "Mold.Lib.Event" },

			//load template components
			".VDom.Components.MoldEvent",
			".VDom.Components.MoldCaptureForms"
		]
	},
	function(markup, config){

		config = config || {};

		var ajax = new Ajax();
		var _tree = false;
		var _that = this;
		var _parseAsString= config.parseAsString || false;
		var undefined;

		Mold.mixin(this, new Event(this));

		//load the
		var _template = new Promise(function(resolve, reject){
			var data = markup;
			if(typeof markup === "function"){
				data = MultiLineString(markup)
				resolve(data);
				return;
			}

			if(Path.is(markup)){
				ajax
					.get(markup)
					.then(function(data){
						resolve(data);
					})
					.fail(function(error){
						reject(error);
					});
			}else{
				resolve(data);
			}
		});

		var _templateTree = new Promise(function(resolve, reject){
			_template.then(function(data){
				_tree = new Builder(data, { template : _that });

				resolve(_tree);
				_that.trigger("ready");
			})
		});

		/**
		 * @method  _connector
		 * @private
		 * @description collection of methods to bind a model to the template
		 * @type {Object}
		 */
		var _connector = {
			renderTimer : false,
			reRender : function(tree){
				clearTimeout(_connector.renderTimer);
				_connector.renderTimer = setTimeout(function(){
					if(!_parseAsString){
						tree.reRender();
					}else{
						tree.renderString();
					}
					_that.trigger("renderd", { tree : _tree });
				}, 2);

			},
			updateChildren : function(children, data, tree){
				if(Mold.isObject(children)){
					for(var childName in children){
						_connector.updateChild(children[childName], data[childName], tree, childName)
					}
				}else{
					throw new Error("only object implemented in _connector.updateChildren")
				}
			},
			updateChild : function(child, data, tree, name){

				//if blocknode
				if(child.type === 2){
					var blockData = {};
					blockData[name] = (data[name] === undefined) ? data : data[name];
					child.setData(blockData);
				}else{
					child.setData(data);
				}
				_connector.reRender(tree);

			},
			watchObjectProp : function(model, subTree, properties, path, tree, name){

				model.off(path + ".changed");
				model.on(path + ".changed", function(e){

					switch(e.data.type){
						case "update":
							//if subtree is an array update all childnodes
							if(Mold.isArray(subTree)){
								var i = 0, len = subTree.length;
								for(; i < len; i++){
									_connector.updateChild(subTree[i], e.data.object, tree, name);
									_connect(model, subTree[i], properties, path, tree);
								}
							}else if(subTree.children && subTree.children[name]){
								_connector.updateChild(subTree, e.data.object, tree, name);
							}else if(subTree.name === name){
								_connector.updateChild(subTree, e.data.object, tree, name);
							}
							break;
						case "splice":
							if(!e.data.addedCount && e.data.removed.length){
								if(Mold.isArray(subTree)){
									for(var i = 0; i < subTree.length; i++){
										subTree[i].removeListItems(e.data.index, e.data.removed.length);
									}
								}else{
									subTree.removeListItems(e.data.index, e.data.removed.length);
								}

							}

							if(e.data.addedCount){
								var i = e.data.index, len = e.data.index + e.data.addedCount;
								for(; i < len; i++){
									if(Mold.isArray(subTree)){
										for(var y = 0; y < subTree.length; y++){
											subTree[y].changeListItem(i, e.data.object[i]);
										}
									}else{
										subTree.changeListItem(i, e.data.object[i]);
									}
								}

							}
							_connector.reRender(tree);

							break;
						default:
							throw new Error("type " + e.data.type + " for watchObjectProp is not implemented!");
					}

				});
			},
			watchArray : function(model, subTree, properties, path, tree){
				model.off(path + ".changed");
				model.on(path + ".changed", function(e){
					switch(e.data.type){
						case "update":
							if(Mold.isObject(e.data.object)){
								_connector.updateChildren(subTree, e.data.object, tree)
							}else{
								throw new Error("e.data.object is no Object, not Implemented");
							}
							break;
						case "splice":

							break;
						default:
							throw new Error("method " + e.data.type + " for watchArray is not implemented!");
					}
				});
			},
			parseArray : function(model, subTree, properties, path, tree){
				var i = 0, len = subTree.children.length;
				for(; i < len; i++){
					var newPath = path + "." + i;
					_connector.watchArray(model, subTree.children[i], properties[0], newPath, tree)
					_connect(model, subTree.children[i], properties[0], newPath, tree)
				}
			},
			parseObject : function(model, subTree, properties, path, tree){
				for(var prop in properties){

					var newPath = path + "." + prop;

					if(subTree.children){
						if(subTree.children[prop]){
							_connector.watchObjectProp(model, subTree.children[prop], properties[prop], newPath, tree, prop)
						}
					}else{

						_connector.watchObjectProp(model, subTree[prop], properties[prop], newPath, tree, prop)
						//throw new Error("subTree children is not defined, in _connector.parseObject!");
					}
				}
			}
		}

		var _connect = function(model, subTree, properties, path, tree){

			if(Mold.isArray(properties)){
				_connector.parseArray(model, subTree, properties, path, tree);
			}else if(Mold.isObject(properties)){
				_connector.parseObject(model, subTree, properties, path, tree);
			}
		}

		var _forms = {};

		Mold.mixin(_forms, new Event(_forms));

		_forms.setValue = function(name, value){
			this[name] = value;
			this.trigger(name + ".changed", value);
		}

		this.publics = {
			snatch : function(){

			},
			forms : _forms,
			connect : function(model){
				_templateTree.then(function(tree){
					_connect(model, tree.dom, model.getProperties(), "data", tree);
					setTimeout(function(){
						model.triggerUpdate();
					}, 50)

				});
			},
			setData : function(data){
				_templateTree.then(function(tree){
					tree.dom.setData(data);
					if(!_parseAsString){
						tree.render();
					}else{
						tree.renderString();
					}
					_that.trigger("renderd", { tree : _tree });
				});
			},
			appendTo : function(element){
				_templateTree.then(function(tree){
					element.appendChild(tree.render())
					_that.trigger("renderd", { tree : _tree });
				})
			},
			getString : function(data){
				return new Promise(function(resolve, reject){
					_templateTree.then(function(tree){
						if(data){
							tree.dom.setData(data);
						}
						resolve(tree.renderString());
						_that.trigger("renderd", { tree : _tree });
					})
				});
			},
			get : _templateTree,
			tree : _templateTree
		}
	}
)<|endoftext|>


<commit_before>BR.Sidebar = L.Control.Sidebar.extend({
    storageId: 'sidebar-control',

    options: {
        position: 'right',
        container: 'sidebar',
        tabContainer: 'sidebarTabs',
        autopan: false,
        defaultTabId: '',

        shortcut: {
            toggleTabs: 84 // char code for 't'
        },

        // Tabs to be notified when shown or hidden
        // (tab div id -> object implementing show/hide methods)
        listeningTabs: {}
    },

    initialize: function(id, options) {
        L.Control.Sidebar.prototype.initialize.call(this, id, options);

        this.oldTab = null;

        L.DomEvent.addListener(document, 'keydown', this._keydownListener, this);
    },

    addTo: function(map) {
        L.Control.Sidebar.prototype.addTo.call(this, map);

        this.on('content', this._notifyOnContent, this);
        this.on('closing', this._notifyOnClose, this);
        this.on('toggleExpand', this._notifyOnResize, this);

        this.on(
            'closing',
            function() {
                this._map.getContainer().focus();
            },
            this
        );

        this.recentTab = this.options.defaultTabId;
        this.on(
            'content',
            function(tab) {
                this.recentTab = tab.id;
            },
            this
        );

        this._rememberTabState();

        if (L.Browser.touch && BR.Browser.touchScreenDetectable && !BR.Browser.touchScreen) {
            L.DomUtil.removeClass(this._container, 'leaflet-touch');
            L.DomUtil.removeClass(this._tabContainer, 'leaflet-touch');
        }

        return this;
    },

    showPanel: function(id) {
        var tab = this._getTab(id);
        tab.hidden = false;

        return this;
    },

    _rememberTabState: function() {
        if (BR.Util.localStorageAvailable()) {
            this.on('content closing', this._storeActiveTab, this);

            var tabId = localStorage.getItem(this.storageId);

            // 'true': legacy value for toggling old sidebar
            if (tabId === 'true') {
                tabId = this.options.defaultTabId;
            } else if (tabId === null) {
                // not set: closed by default for new users
                tabId = '';
            }
            if (tabId !== '') {
                this.open(tabId);
            }
        }
    },

    _notifyShow: function(tab) {
        if (tab && tab.show) {
            tab.show();
        }
    },

    _notifyHide: function(tab) {
        if (tab && tab.hide) {
            tab.hide();
        }
    },

    _notifyOnContent: function(e) {
        var tab = this.options.listeningTabs[e.id];
        this._notifyHide(this.oldTab);
        this._notifyShow(tab);
        this.oldTab = tab;
    },

    _notifyOnClose: function(e) {
        this._notifyHide(this.oldTab);
        this.oldTab = null;
    },

    _notifyOnResize: function(e) {
        var tab = this.oldTab;
        if (tab && tab.onResize) {
            tab.onResize();
        }
    },

    _storeActiveTab: function(e) {
        localStorage.setItem(this.storageId, e.id || '');
    },

    _keydownListener: function(e) {
        if (BR.Util.keyboardShortcutsAllowed(e) && e.keyCode === this.options.shortcut.toggleTabs) {
            if ($('#sidebarTabs > ul > li[class=active]').length) {
                // sidebar is currently open
                if (e.shiftKey) {
                    // try to find next tab
                    var nextTab = $('#sidebarTabs > ul > li[class=active] ~ li:not([hidden]) > a');
                    if (!nextTab.length) {
                        // wrap around to first tab
                        nextTab = $('#sidebarTabs > ul > li:not([hidden]) > a');
                    }
                    // switch to next or first tab
                    this.open(nextTab.attr('href').slice(1));
                } else {
                    // close current tab
                    this.close();
                }
            } else {
                // sidebar is currently closed, open recent or default tab
                this.open(this.recentTab);
            }
        }
    }
});

BR.sidebar = function(divId, options) {
    return new BR.Sidebar(divId, options);
};
<commit_msg>Switch to next tab with Shift+T shortcut even if tab is currently closed<commit_after>BR.Sidebar = L.Control.Sidebar.extend({
    storageId: 'sidebar-control',

    options: {
        position: 'right',
        container: 'sidebar',
        tabContainer: 'sidebarTabs',
        autopan: false,
        defaultTabId: '',

        shortcut: {
            toggleTabs: 84 // char code for 't'
        },

        // Tabs to be notified when shown or hidden
        // (tab div id -> object implementing show/hide methods)
        listeningTabs: {}
    },

    initialize: function(id, options) {
        L.Control.Sidebar.prototype.initialize.call(this, id, options);

        this.oldTab = null;

        L.DomEvent.addListener(document, 'keydown', this._keydownListener, this);
    },

    addTo: function(map) {
        L.Control.Sidebar.prototype.addTo.call(this, map);

        this.on('content', this._notifyOnContent, this);
        this.on('closing', this._notifyOnClose, this);
        this.on('toggleExpand', this._notifyOnResize, this);

        this.on(
            'closing',
            function() {
                this._map.getContainer().focus();
            },
            this
        );

        this.recentTab = this.options.defaultTabId;
        this.on(
            'content',
            function(tab) {
                this.recentTab = tab.id;
            },
            this
        );

        this._rememberTabState();

        if (L.Browser.touch && BR.Browser.touchScreenDetectable && !BR.Browser.touchScreen) {
            L.DomUtil.removeClass(this._container, 'leaflet-touch');
            L.DomUtil.removeClass(this._tabContainer, 'leaflet-touch');
        }

        return this;
    },

    showPanel: function(id) {
        var tab = this._getTab(id);
        tab.hidden = false;

        return this;
    },

    _rememberTabState: function() {
        if (BR.Util.localStorageAvailable()) {
            this.on('content closing', this._storeActiveTab, this);

            var tabId = localStorage.getItem(this.storageId);

            // 'true': legacy value for toggling old sidebar
            if (tabId === 'true') {
                tabId = this.options.defaultTabId;
            } else if (tabId === null) {
                // not set: closed by default for new users
                tabId = '';
            }
            if (tabId !== '') {
                this.open(tabId);
            }
        }
    },

    _notifyShow: function(tab) {
        if (tab && tab.show) {
            tab.show();
        }
    },

    _notifyHide: function(tab) {
        if (tab && tab.hide) {
            tab.hide();
        }
    },

    _notifyOnContent: function(e) {
        var tab = this.options.listeningTabs[e.id];
        this._notifyHide(this.oldTab);
        this._notifyShow(tab);
        this.oldTab = tab;
    },

    _notifyOnClose: function(e) {
        this._notifyHide(this.oldTab);
        this.oldTab = null;
    },

    _notifyOnResize: function(e) {
        var tab = this.oldTab;
        if (tab && tab.onResize) {
            tab.onResize();
        }
    },

    _storeActiveTab: function(e) {
        localStorage.setItem(this.storageId, e.id || '');
    },

    _keydownListener: function(e) {
        if (BR.Util.keyboardShortcutsAllowed(e) && e.keyCode === this.options.shortcut.toggleTabs) {
            if ($('#sidebarTabs > ul > li[class=active]').length) {
                // sidebar is currently open, close current tab
                if (!e.shiftKey) {
                    this.close();
                }
            } else {
                // sidebar is currently closed, open recent or default tab
                this.open(this.recentTab);
            }
            if (e.shiftKey) {
                // try to find next tab
                var nextTab = $('#sidebarTabs > ul > li[class=active] ~ li:not([hidden]) > a');
                if (!nextTab.length) {
                    // wrap around to first tab
                    nextTab = $('#sidebarTabs > ul > li:not([hidden]) > a');
                }
                // switch to next or first tab
                this.open(nextTab.attr('href').slice(1));
            }
        }
    }
});

BR.sidebar = function(divId, options) {
    return new BR.Sidebar(divId, options);
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
import config from './config/environment';

Ember.MODEL_FACTORY_INJECTIONS = true;

var App = Ember.Application.extend({
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver: Resolver
});

loadInitializers(App, config.modulePrefix);

export default App;
<commit_msg>Fix polymorphic assocations<commit_after>import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
import config from './config/environment';

Ember.MODEL_FACTORY_INJECTIONS = false;

var App = Ember.Application.extend({
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver: Resolver
});

loadInitializers(App, config.modulePrefix);

export default App;
<|endoftext|>


<commit_before>
function yql_lookup(query, cb_function) {
    var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&diagnostics=true';

    //alert(url);

    $.getJSON(url, cb_function);
}

function look_up_news() {

    // TEMPORARY HACK
    //mediacloud.org is password protected so we can't pull from it directly
    // instead we pull from 'https://blogs.law.harvard.edu/mediacloud2/feed/' and dynamically rewrite the URLs to point to mediacloud.org/blog;
    var feed_url = 'https://blogs.law.harvard.edu/mediacloud2/feed/';

    //alert(google_url);
    yql_lookup("select * from rss where url = '" + feed_url + "'", function (response) {

        var results = response.query.results;

	var news_items = $('#news_items');

        //console.log(results);
        news_items.children().remove();
        news_items.html('');

        $.each(results.item, function (index, element) {
            var title = element.title;
            var link = element.link;

	    link = link.replace('https://blogs.law.harvard.edu/mediacloud2/', 'http://www.mediacloud.org/blog/');
            news_items.append($('', {
                'href': link
            }).text(title)).append('
');
        });

    });
}
<commit_msg>Display load message while news is being looked up.<commit_after>
function yql_lookup(query, cb_function) {
    var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&diagnostics=true';

    //alert(url);

    $.getJSON(url, cb_function);
}

function look_up_news() {

    // TEMPORARY HACK
    //mediacloud.org is password protected so we can't pull from it directly
    // instead we pull from 'https://blogs.law.harvard.edu/mediacloud2/feed/' and dynamically rewrite the URLs to point to mediacloud.org/blog;
    var feed_url = 'https://blogs.law.harvard.edu/mediacloud2/feed/';

    //alert(google_url);
    $('#news_items').html('
Loading...
');
    yql_lookup("select * from rss where url = '" + feed_url + "'", function (response) {

        var results = response.query.results;

	var news_items = $('#news_items');

        //console.log(results);
        news_items.children().remove();
        news_items.html('');

        $.each(results.item, function (index, element) {
            var title = element.title;
            var link = element.link;

	    link = link.replace('https://blogs.law.harvard.edu/mediacloud2/', 'http://www.mediacloud.org/blog/');
            news_items.append($('', {
                'href': link
            }).text(title)).append('
');
        });

    });
}
<|endoftext|>


<commit_before><commit_msg>spatial-grid: Make indices inclusive (<= x + width, instead of <).<commit_after><|endoftext|>