<commit_before>function startWithRandomPuzzle() {
    jsonXhr("/Puzzle/Train/GetOneRandomly" + (window.trainingSessionId ? "?trainingSessionId=" + window.trainingSessionId : ""), "GET", null, function (req, jsonResponse) {
        setup(jsonResponse["id"]);
    }, function (req, err) {
        alert(err);
    });
}

function setup(puzzleId) {
    window.puzzleId = puzzleId;
    jsonXhr("/Puzzle/Train/Setup", "POST", "id=" + window.puzzleId + (window.trainingSessionId ? "&trainingSessionId=" + window.trainingSessionId : ""), function (req, jsonResponse) {
        window.ground.set({
            fen: jsonResponse["fen"],
            orientation: jsonResponse["whoseTurn"],
            turnColor: jsonResponse["whoseTurn"],
            lastMove: null,
            selected: null,
            movable: {
                free: false,
                dests: jsonResponse["dests"]
            }
        });
        clearExplanation();
        clearComments();
        loadComments();
        document.getElementById("nextPuzzleLink").classList.add("nodisplay");
        document.getElementById("result").setAttribute("class", "blue");
        document.getElementById("result").innerHTML = "Find the best move!";
        document.getElementById("author").textContent = jsonResponse["author"];
        window.trainingSessionId = jsonResponse["trainingSessionId"];
    }, function (req, err) {
        alert(err);
    });
}

function showExplanation(expl) {
    document.getElementById("explanation").innerHTML = expl;
}

function clearExplanation() {
    document.getElementById("explanation").innerHTML = "";
}

function processPuzzleMove(origin, destination, metadata) {
    if (ChessgroundExtensions.needsPromotion(window.ground, destination)) {
        ChessgroundExtensions.drawPromotionDialog(origin, destination, document.getElementById("chessground"), submitPuzzleMove, window.ground);
    } else {
        submitPuzzleMove(origin, destination, null);
    }
}

function submitPuzzleMove(origin, destination, promotion) {
    jsonXhr("/Puzzle/Train/SubmitMove", "POST", "id=" + window.puzzleId + "&trainingSessionId=" + window.trainingSessionId + "&origin=" + origin + "&destination=" + destination + (promotion ? "&promotion=" + promotion : ""), function (req, jsonResponse) {
        window.ground.set({
            fen: jsonResponse["fen"]
        });
        if (jsonResponse["check"]) {
            window.ground.setCheck(jsonResponse["check"]);
        } else {
            window.ground.set({ check: null });
        }
        if (jsonResponse["play"]) {
            window.ground.set({
                fen: jsonResponse["fenAfterPlay"]
            });
            if (jsonResponse["checkAfterAutoMove"]) {
                window.ground.setCheck(jsonResponse["checkAfterAutoMove"]);
            }
        }
        switch (jsonResponse["correct"]) {
            case 0:
                break;
            case 1:
                document.getElementById("nextPuzzleLink").classList.remove("blue");
                with (document.getElementById("result")) {
                    textContent = "Success!";
                    setAttribute("class", "green");
                };
                break;
            case -1:
                document.getElementById("nextPuzzleLink").classList.remove("blue");
                with (document.getElementById("result")) {
                    textContent = "Sorry, that's not correct. This was correct: " + jsonResponse["solution"];
                    setAttribute("class", "red");
                }
        }
        if (jsonResponse["dests"]) {
            window.ground.set({
                movable: {
                    dests: jsonResponse["dests"]
                }
            });
        }
        if (jsonResponse["explanation"]) {
            showExplanation(jsonResponse["explanation"] + "

Puzzle rating: " + jsonResponse["rating"]);
        }
    }, function (req, err) {
        alert(err);
    });
}

function submitComment(e) {
    e = e || window.event;
    e.preventDefault();
    jsonXhr("/Comment/PostComment", "POST", "commentBody=" + encodeURIComponent(document.getElementById("commentBody").value) + "&puzzleId=" + window.puzzleId, function (req, jsonResponse) {
        document.getElementById("commentBody").value = "";
        clearComments();
        loadComments();
    },
    function (req, err) {
        alert(err);
    });
}

function clearComments() {
    var commentContainer = document.getElementById("commentContainer");
    while (commentContainer.firstChild) {
        commentContainer.removeChild(commentContainer.firstChild);
    }
}

function loadComments() {
    xhr("/Comment/ViewComments?puzzleId=" + window.puzzleId, "GET", null, function (req) {
        document.getElementById("commentContainer").innerHTML = req.responseText;
        var comments = document.getElementById("commentContainer").querySelectorAll(".comment");
        for (var i = 0; i < comments.length; i++) {
            comments[i].style.marginLeft = comments[i].dataset.indentlevel + "vw";
        }
        var voteLinks = document.getElementById("commentContainer").querySelectorAll("a[data-vote]");
        for (var i = 0; i < voteLinks.length; i++) {
            voteLinks[i].addEventListener("click", voteClicked);
        }
        var replyLinks = document.getElementById("commentContainer").querySelectorAll("a[data-to]");
        for (var i = 0; i < replyLinks.length; i++) {
            replyLinks[i].addEventListener("click", replyLinkClicked);
        }
        var sendLinks = document.getElementById("commentContainer").getElementsByClassName("send-reply");
        for (var i = 0; i < sendLinks.length; i++) {
            sendLinks[i].addEventListener("click", sendLinkClicked);
        }
        var cancelLinks = document.getElementById("commentContainer").getElementsByClassName("cancel-reply");
        for (var i = 0; i < cancelLinks.length; i++) {
            cancelLinks[i].addEventListener("click", cancelLinkClicked);
        }
        var reportLinks = document.getElementById("commentContainer").getElementsByClassName("report-link");
        for (var i = 0; i < reportLinks.length; i++) {
            reportLinks[i].addEventListener("click", reportLinkClicked);
        }
        var modLinks = document.getElementById("commentContainer").getElementsByClassName("mod-link");
        for (var i = 0; i < modLinks.length; i++) {
            modLinks[i].addEventListener("click", modLinkClicked);
        }
        if (window.location.search !== "") {
            var matches = /[?&]c=[0-9a-zA-Z_-]+/.exec(window.location.search);
            if (matches) {
                var id = matches[0].slice(3);
                var highlighted = document.getElementById(id);
                if (highlighted) {
                    highlighted.scrollIntoView(true);
                    highlighted.style.backgroundColor = "#feb15a";
                }
            }
        }
    }, function (req, err) {
        alert(err);
    });
}

function upvoteComment(commentId) {
    jsonXhr("/Comment/Upvote", "POST", "commentId=" + commentId, function (req, jsonResponse) {
        clearComments();
        loadComments();
    }, function (req, err) {
        alert(err);
    });
}

function downvoteComment(commentId) {
    jsonXhr("/Comment/Downvote", "POST", "commentId=" + commentId, function (req, jsonResponse) {
        clearComments();
        loadComments();
    }, function (req, err) {
        alert(err);
    });
}

function undoVote(commentId) {
    jsonXhr("/Comment/UndoVote", "POST", "commentId=" + commentId, function (req, jsonResponse) {
        clearComments();
        loadComments();
    }, function (req, err) {
        alert(err);
    });
}

function sendReply(to, body) {
    jsonXhr("/Comment/Reply", "POST", "to=" + to + "&body=" + encodeURIComponent(body) + "&puzzleId=" + window.puzzleId, function (req, jsonResponse) {
        clearComments();
        loadComments();
    },
    function (req, err) {
        alert(err);
    });
}

function voteClicked(e) {
    e = e || window.event;
    e.preventDefault();
    var target = e.target;
    if (target.dataset.vote === "up") {
        if (target.classList.contains("upvote-highlighted")) {
            undoVote(target.dataset.commentid);
        } else {
            upvoteComment(target.dataset.commentid);
        }
    } else {
        if (target.classList.contains("downvote-highlighted")) {
            undoVote(target.dataset.commentid);
        } else {
            downvoteComment(target.dataset.commentid);
        }
    }
}

function replyLinkClicked(e) {
    e = e || window.event;
    e.preventDefault();
    (document.getElementById("to-" + e.target.dataset.to) || { style: {} }).style.display = "block";
}

function sendLinkClicked(e) {
    e = e || window.event;
    e.preventDefault();
    var to = e.target.parentElement.id.slice(3);
    var body = e.target.parentElement.firstElementChild.value;
    sendReply(to, body);
}

function cancelLinkClicked(e) {
    e = e || window.event;
    e.preventDefault();
}

function reportLinkClicked(e) {
    e = e || window.event;
    e.preventDefault();
    var itemToReport = e.target.dataset.item;
    if (!window.reportDialogHtml) {
        xhr("/Report/Dialog/Comment", "GET", null, function (req) {
            window.reportDialogHtml = req.responseText;
            showReportDialog(itemToReport);
        }, function (req, err) {
            alert(err);
        });
    }
    else {
        showReportDialog(itemToReport);
    }
}

function showReportDialog(itemToReport) {
    var itemToReportElement = document.getElementById(itemToReport);
    itemToReportElement.getElementsByClassName("comment-content")[0].style.display = "none";
    itemToReportElement.insertAdjacentHTML("beforeend", window.reportDialogHtml);
    itemToReportElement.getElementsByClassName("report-dialog")[0].lastElementChild.addEventListener("click", reportLinkInDialogClicked);
}

function removeReportDialog(itemReported) {
    var itemReportedElement = document.getElementById(itemReported);
    itemReportedElement.getElementsByClassName("comment-content")[0].style.display = "flex";
    itemReportedElement.removeChild(itemReportedElement.getElementsByClassName("report-dialog")[0]);
}

function reportLinkInDialogClicked(e) {
    e = e || window.event;
    e.preventDefault();
    var parent = e.target.parentElement;
    jsonXhr("/Report/Submit/Comment", "POST", "item=" + parent.parentElement.id + "&reason=" + parent.getElementsByTagName("select")[0].value + "&reasonExplanation=" + encodeURIComponent(parent.getElementsByTagName("textarea")[0].value),
        function (req, jsonResponse) {
            removeReportDialog(parent.parentElement.id);
        },
        function (req, err) {
            alert(err);
        });
}

function modLinkClicked(e) {
    e = e || window.event;
    e.preventDefault();
    var action = e.target.dataset.action;
    var commentId = e.target.dataset.commentid;
    jsonXhr("/Comment/Mod/" + action, "POST", "commentId=" + commentId, function (req, jsonResponse) {
        clearComments();
        loadComments();
    }, function (req, err) {
        alert(err);
    });
}

function nextPuzzle(e) {
    e = e || window.event;
    if (e.target.getAttribute("href") !== "#") return true;
    e.preventDefault();
    startWithRandomPuzzle();
}

window.addEventListener("load", function () {
    window.ground = Chessground(document.getElementById("chessground"), {
        coordinates: false,
        movable: {
            free: false,
            dropOff: "revert",
            showDests: false,
            events: {
                after: processPuzzleMove
            }
        }
    });
    var submitCommentLink = document.getElementById("submitCommentLink");
    if (submitCommentLink) {
        submitCommentLink.addEventListener("click", submitComment);
    }
    document.getElementById("nextPuzzleLink").addEventListener("click", nextPuzzle);
    if (!window.selectedPuzzle) {
        startWithRandomPuzzle();
    } else {
        setup(window.selectedPuzzle);
    }
});<commit_msg>I was too fast when replacing 'nodisplay' a few commits ago...<commit_after>function startWithRandomPuzzle() {
    jsonXhr("/Puzzle/Train/GetOneRandomly" + (window.trainingSessionId ? "?trainingSessionId=" + window.trainingSessionId : ""), "GET", null, function (req, jsonResponse) {
        setup(jsonResponse["id"]);
    }, function (req, err) {
        alert(err);
    });
}

function setup(puzzleId) {
    window.puzzleId = puzzleId;
    jsonXhr("/Puzzle/Train/Setup", "POST", "id=" + window.puzzleId + (window.trainingSessionId ? "&trainingSessionId=" + window.trainingSessionId : ""), function (req, jsonResponse) {
        window.ground.set({
            fen: jsonResponse["fen"],
            orientation: jsonResponse["whoseTurn"],
            turnColor: jsonResponse["whoseTurn"],
            lastMove: null,
            selected: null,
            movable: {
                free: false,
                dests: jsonResponse["dests"]
            }
        });
        clearExplanation();
        clearComments();
        loadComments();
        document.getElementById("nextPuzzleLink").classList.add("nodisplay");
        document.getElementById("result").setAttribute("class", "blue");
        document.getElementById("result").innerHTML = "Find the best move!";
        document.getElementById("author").textContent = jsonResponse["author"];
        window.trainingSessionId = jsonResponse["trainingSessionId"];
    }, function (req, err) {
        alert(err);
    });
}

function showExplanation(expl) {
    document.getElementById("explanation").innerHTML = expl;
}

function clearExplanation() {
    document.getElementById("explanation").innerHTML = "";
}

function processPuzzleMove(origin, destination, metadata) {
    if (ChessgroundExtensions.needsPromotion(window.ground, destination)) {
        ChessgroundExtensions.drawPromotionDialog(origin, destination, document.getElementById("chessground"), submitPuzzleMove, window.ground);
    } else {
        submitPuzzleMove(origin, destination, null);
    }
}

function submitPuzzleMove(origin, destination, promotion) {
    jsonXhr("/Puzzle/Train/SubmitMove", "POST", "id=" + window.puzzleId + "&trainingSessionId=" + window.trainingSessionId + "&origin=" + origin + "&destination=" + destination + (promotion ? "&promotion=" + promotion : ""), function (req, jsonResponse) {
        window.ground.set({
            fen: jsonResponse["fen"]
        });
        if (jsonResponse["check"]) {
            window.ground.setCheck(jsonResponse["check"]);
        } else {
            window.ground.set({ check: null });
        }
        if (jsonResponse["play"]) {
            window.ground.set({
                fen: jsonResponse["fenAfterPlay"]
            });
            if (jsonResponse["checkAfterAutoMove"]) {
                window.ground.setCheck(jsonResponse["checkAfterAutoMove"]);
            }
        }
        switch (jsonResponse["correct"]) {
            case 0:
                break;
            case 1:
                document.getElementById("nextPuzzleLink").classList.remove("nodisplay");
                with (document.getElementById("result")) {
                    textContent = "Success!";
                    setAttribute("class", "green");
                };
                break;
            case -1:
                document.getElementById("nextPuzzleLink").classList.remove("nodisplay");
                with (document.getElementById("result")) {
                    textContent = "Sorry, that's not correct. This was correct: " + jsonResponse["solution"];
                    setAttribute("class", "red");
                }
        }
        if (jsonResponse["dests"]) {
            window.ground.set({
                movable: {
                    dests: jsonResponse["dests"]
                }
            });
        }
        if (jsonResponse["explanation"]) {
            showExplanation(jsonResponse["explanation"] + "

Puzzle rating: " + jsonResponse["rating"]);
        }
    }, function (req, err) {
        alert(err);
    });
}

function submitComment(e) {
    e = e || window.event;
    e.preventDefault();
    jsonXhr("/Comment/PostComment", "POST", "commentBody=" + encodeURIComponent(document.getElementById("commentBody").value) + "&puzzleId=" + window.puzzleId, function (req, jsonResponse) {
        document.getElementById("commentBody").value = "";
        clearComments();
        loadComments();
    },
    function (req, err) {
        alert(err);
    });
}

function clearComments() {
    var commentContainer = document.getElementById("commentContainer");
    while (commentContainer.firstChild) {
        commentContainer.removeChild(commentContainer.firstChild);
    }
}

function loadComments() {
    xhr("/Comment/ViewComments?puzzleId=" + window.puzzleId, "GET", null, function (req) {
        document.getElementById("commentContainer").innerHTML = req.responseText;
        var comments = document.getElementById("commentContainer").querySelectorAll(".comment");
        for (var i = 0; i < comments.length; i++) {
            comments[i].style.marginLeft = comments[i].dataset.indentlevel + "vw";
        }
        var voteLinks = document.getElementById("commentContainer").querySelectorAll("a[data-vote]");
        for (var i = 0; i < voteLinks.length; i++) {
            voteLinks[i].addEventListener("click", voteClicked);
        }
        var replyLinks = document.getElementById("commentContainer").querySelectorAll("a[data-to]");
        for (var i = 0; i < replyLinks.length; i++) {
            replyLinks[i].addEventListener("click", replyLinkClicked);
        }
        var sendLinks = document.getElementById("commentContainer").getElementsByClassName("send-reply");
        for (var i = 0; i < sendLinks.length; i++) {
            sendLinks[i].addEventListener("click", sendLinkClicked);
        }
        var cancelLinks = document.getElementById("commentContainer").getElementsByClassName("cancel-reply");
        for (var i = 0; i < cancelLinks.length; i++) {
            cancelLinks[i].addEventListener("click", cancelLinkClicked);
        }
        var reportLinks = document.getElementById("commentContainer").getElementsByClassName("report-link");
        for (var i = 0; i < reportLinks.length; i++) {
            reportLinks[i].addEventListener("click", reportLinkClicked);
        }
        var modLinks = document.getElementById("commentContainer").getElementsByClassName("mod-link");
        for (var i = 0; i < modLinks.length; i++) {
            modLinks[i].addEventListener("click", modLinkClicked);
        }
        if (window.location.search !== "") {
            var matches = /[?&]c=[0-9a-zA-Z_-]+/.exec(window.location.search);
            if (matches) {
                var id = matches[0].slice(3);
                var highlighted = document.getElementById(id);
                if (highlighted) {
                    highlighted.scrollIntoView(true);
                    highlighted.style.backgroundColor = "#feb15a";
                }
            }
        }
    }, function (req, err) {
        alert(err);
    });
}

function upvoteComment(commentId) {
    jsonXhr("/Comment/Upvote", "POST", "commentId=" + commentId, function (req, jsonResponse) {
        clearComments();
        loadComments();
    }, function (req, err) {
        alert(err);
    });
}

function downvoteComment(commentId) {
    jsonXhr("/Comment/Downvote", "POST", "commentId=" + commentId, function (req, jsonResponse) {
        clearComments();
        loadComments();
    }, function (req, err) {
        alert(err);
    });
}

function undoVote(commentId) {
    jsonXhr("/Comment/UndoVote", "POST", "commentId=" + commentId, function (req, jsonResponse) {
        clearComments();
        loadComments();
    }, function (req, err) {
        alert(err);
    });
}

function sendReply(to, body) {
    jsonXhr("/Comment/Reply", "POST", "to=" + to + "&body=" + encodeURIComponent(body) + "&puzzleId=" + window.puzzleId, function (req, jsonResponse) {
        clearComments();
        loadComments();
    },
    function (req, err) {
        alert(err);
    });
}

function voteClicked(e) {
    e = e || window.event;
    e.preventDefault();
    var target = e.target;
    if (target.dataset.vote === "up") {
        if (target.classList.contains("upvote-highlighted")) {
            undoVote(target.dataset.commentid);
        } else {
            upvoteComment(target.dataset.commentid);
        }
    } else {
        if (target.classList.contains("downvote-highlighted")) {
            undoVote(target.dataset.commentid);
        } else {
            downvoteComment(target.dataset.commentid);
        }
    }
}

function replyLinkClicked(e) {
    e = e || window.event;
    e.preventDefault();
    (document.getElementById("to-" + e.target.dataset.to) || { style: {} }).style.display = "block";
}

function sendLinkClicked(e) {
    e = e || window.event;
    e.preventDefault();
    var to = e.target.parentElement.id.slice(3);
    var body = e.target.parentElement.firstElementChild.value;
    sendReply(to, body);
}

function cancelLinkClicked(e) {
    e = e || window.event;
    e.preventDefault();
}

function reportLinkClicked(e) {
    e = e || window.event;
    e.preventDefault();
    var itemToReport = e.target.dataset.item;
    if (!window.reportDialogHtml) {
        xhr("/Report/Dialog/Comment", "GET", null, function (req) {
            window.reportDialogHtml = req.responseText;
            showReportDialog(itemToReport);
        }, function (req, err) {
            alert(err);
        });
    }
    else {
        showReportDialog(itemToReport);
    }
}

function showReportDialog(itemToReport) {
    var itemToReportElement = document.getElementById(itemToReport);
    itemToReportElement.getElementsByClassName("comment-content")[0].style.display = "none";
    itemToReportElement.insertAdjacentHTML("beforeend", window.reportDialogHtml);
    itemToReportElement.getElementsByClassName("report-dialog")[0].lastElementChild.addEventListener("click", reportLinkInDialogClicked);
}

function removeReportDialog(itemReported) {
    var itemReportedElement = document.getElementById(itemReported);
    itemReportedElement.getElementsByClassName("comment-content")[0].style.display = "flex";
    itemReportedElement.removeChild(itemReportedElement.getElementsByClassName("report-dialog")[0]);
}

function reportLinkInDialogClicked(e) {
    e = e || window.event;
    e.preventDefault();
    var parent = e.target.parentElement;
    jsonXhr("/Report/Submit/Comment", "POST", "item=" + parent.parentElement.id + "&reason=" + parent.getElementsByTagName("select")[0].value + "&reasonExplanation=" + encodeURIComponent(parent.getElementsByTagName("textarea")[0].value),
        function (req, jsonResponse) {
            removeReportDialog(parent.parentElement.id);
        },
        function (req, err) {
            alert(err);
        });
}

function modLinkClicked(e) {
    e = e || window.event;
    e.preventDefault();
    var action = e.target.dataset.action;
    var commentId = e.target.dataset.commentid;
    jsonXhr("/Comment/Mod/" + action, "POST", "commentId=" + commentId, function (req, jsonResponse) {
        clearComments();
        loadComments();
    }, function (req, err) {
        alert(err);
    });
}

function nextPuzzle(e) {
    e = e || window.event;
    if (e.target.getAttribute("href") !== "#") return true;
    e.preventDefault();
    startWithRandomPuzzle();
}

window.addEventListener("load", function () {
    window.ground = Chessground(document.getElementById("chessground"), {
        coordinates: false,
        movable: {
            free: false,
            dropOff: "revert",
            showDests: false,
            events: {
                after: processPuzzleMove
            }
        }
    });
    var submitCommentLink = document.getElementById("submitCommentLink");
    if (submitCommentLink) {
        submitCommentLink.addEventListener("click", submitComment);
    }
    document.getElementById("nextPuzzleLink").addEventListener("click", nextPuzzle);
    if (!window.selectedPuzzle) {
        startWithRandomPuzzle();
    } else {
        setup(window.selectedPuzzle);
    }
});<|endoftext|>


<commit_before>/*jslint node: true */

/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

const child_process = require("child_process");
const exitHook = require("exit-hook");
const PerformanceUtilities = require("./performanceutilities");

const options = PerformanceUtilities.getCommandLineOptionsOrDefaults();
const measureMemory = options.measureMemory == "true";

const ProcessManager = {};

function ChildProcessStuff(type) {
    this.file = type === "provider" ? "providerChildProcess.js" : "proxyChildProcess.js";
}
ChildProcessStuff.prototype.initialize = function() {
    const config = PerformanceUtilities.createChildProcessConfig();
    config.env = Object.create(process.env);

    this.process = child_process.fork(`src/main/js/${this.file}`, [], config);
    this.ready = PerformanceUtilities.createPromise();
    const that = this;

    this.process.on("message", msg => {
        switch (msg.msg) {
            case "initialized":
                that.ready.resolve();
                break;
            case "gotMeasurement":
                that.measurementPromise.resolve(msg.data);
                break;
            case "prepareBenchmarkFinished":
                that.prepareBenchmarkPromise.resolve();
                break;
            case "executeBenchmarkFinished":
                that.executeBenchmarkPromise.resolve();
                break;
            case "subscriptionFinished":
                that.subsciptionFinishedPromise.resolve();
                break;
            case "receivedBroadcasts":
                that.broadcastsReceivedPromise.resolve();
                break;
            default:
                throw new Error(`unknown MessageType${JSON.stringify(msg)}`);
        }
    });

    return this.ready.promise;
};

ChildProcessStuff.prototype.shutdown = function() {
    this.process.send({ msg: "terminate" });
};

ChildProcessStuff.prototype.startMeasurement = function() {
    this.process.send({ msg: "startMeasurement" });
};

ChildProcessStuff.prototype.stopMeasurement = function() {
    this.process.send({ msg: "stopMeasurement" });
    this.measurementPromise = PerformanceUtilities.createPromise();
    return this.measurementPromise.promise;
};

ChildProcessStuff.prototype.prepareForBroadcast = function(benchmarkConfig) {
    this.process.send({ msg: "subscribeBroadcast", amount: benchmarkConfig.numRuns });
    this.subsciptionFinishedPromise = PerformanceUtilities.createPromise();
    this.broadcastsReceivedPromise = PerformanceUtilities.createPromise();
    return this.subsciptionFinishedPromise.promise;
};

ProcessManager.provider = new ChildProcessStuff("provider");
ProcessManager.proxy = new ChildProcessStuff("proxy");

ProcessManager.proxy.prepareBenchmark = function(benchmarkConfig) {
    this.process.send({ msg: "prepareBenchmark", config: benchmarkConfig });
    this.prepareBenchmarkPromise = PerformanceUtilities.createPromise();
    return this.prepareBenchmarkPromise.promise;
};

ProcessManager.proxy.executeBenchmark = function(benchmarkConfig) {
    this.process.send({ msg: "executeBenchmark", config: benchmarkConfig });
    this.executeBenchmarkPromise = PerformanceUtilities.createPromise();
    return this.executeBenchmarkPromise.promise;
};

ProcessManager.initializeChildProcesses = function() {
    const providerPromise = ProcessManager.provider.initialize();
    const proxyPromise = ProcessManager.proxy.initialize();

    exitHook(() => {
        ProcessManager.provider.shutdown();
        ProcessManager.proxy.shutdown();
    });
    return Promise.all([providerPromise, proxyPromise]);
};

ProcessManager.takeHeapSnapShot = function(name) {
    this.proxy.process.send({ msg: "takeHeapSnapShot", name: `./proxy${name}.heapsnapshot` });
    this.provider.process.send({ msg: "takeHeapSnapShot", name: `./provider${name}.heapsnapshot` });
};

let initializedBroadcasts = false;

ProcessManager.initializeBroadcast = function(benchmarkConfig) {
    if (initializedBroadcasts) {
        return Promise.resolve();
    }
    initializedBroadcasts = true;
    let count = benchmarkConfig.numProxies;
    this.broadcastProxies = [];
    const broadcastProxiesInitializedPromises = [];
    while (count--) {
        const broadcastProxy = new ChildProcessStuff("proxy");
        const broadCastProxyInitialized = broadcastProxy.initialize();
        this.broadcastProxies.push(broadcastProxy);
        broadcastProxiesInitializedPromises.push(broadCastProxyInitialized);
    }
    return Promise.all(broadcastProxiesInitializedPromises);
};

ProcessManager.prepareBroadcasts = function(benchmarkConfig) {
    return ProcessManager.initializeBroadcast(benchmarkConfig).then(() => {
        return Promise.all(this.broadcastProxies.map(proxy => proxy.prepareForBroadcast(benchmarkConfig)));
    });
};

ProcessManager._prepareBroadcastResults = function() {
    const timeMs = Date.now() - this.broadcastStarted;
    console.log(`broadcast took: ${timeMs}ms`);
    const providerFinished = this.provider.stopMeasurement();

    const broadcastProxiesFinished = this.broadcastProxies.map(proxy => proxy.stopMeasurement());
    const broadcastProxiesReduced = Promise.all(broadcastProxiesFinished).then(results => {
        let total;
        const numberOfProxies = broadcastProxiesFinished.length;
        if (measureMemory) {
            total = results.reduce(
                (acc, curr) => {
                    acc.user += curr.user;
                    acc.system += curr.system;
                    acc.averageMemory += curr.averageMemory;
                },
                { user: 0, system: 0, averageMemory: 0 }
            );
            total.averageMemory /= numberOfProxies;
        } else {
            total = results.reduce(
                (acc, curr) => {
                    acc.user += curr.user;
                    acc.system += curr.system;
                    return acc;
                },
                { user: 0, system: 0 }
            );
        }
        total.user /= numberOfProxies;
        total.system /= numberOfProxies;
        return total;
    });
    return Promise.all([providerFinished, broadcastProxiesReduced]).then(values => {
        return { proxy: values[1], provider: values[0], time: timeMs };
    });
};

ProcessManager.executeBroadcasts = function(benchmarkConfig) {
    this.provider.startMeasurement();
    let l = this.broadcastProxies.length;
    const promises = [];
    while (l--) {
        const broadcastProxy = this.broadcastProxies[l];
        broadcastProxy.startMeasurement();
        promises.push(broadcastProxy.broadcastsReceivedPromise.promise);
    }
    this.broadcastStarted = Date.now();
    this.provider.process.send({ msg: "fireBroadCast", amount: benchmarkConfig.numRuns });
    return Promise.all(promises).then(() => ProcessManager._prepareBroadcastResults());
};

module.exports = ProcessManager;
<commit_msg>[JS] make perf-tests independant of basepath<commit_after>/*jslint node: true */

/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

const child_process = require("child_process");
const exitHook = require("exit-hook");
const PerformanceUtilities = require("./performanceutilities");

const options = PerformanceUtilities.getCommandLineOptionsOrDefaults();
const measureMemory = options.measureMemory == "true";
const path = require("path");

const ProcessManager = {};

function ChildProcessStuff(type) {
    this.file = type === "provider" ? "providerChildProcess.js" : "proxyChildProcess.js";
}
ChildProcessStuff.prototype.initialize = function() {
    const config = PerformanceUtilities.createChildProcessConfig();
    config.env = Object.create(process.env);
    const fileLocation = path.join(__dirname, this.file);
    this.process = child_process.fork(fileLocation, [], config);
    this.ready = PerformanceUtilities.createPromise();
    const that = this;

    this.process.on("message", msg => {
        switch (msg.msg) {
            case "initialized":
                that.ready.resolve();
                break;
            case "gotMeasurement":
                that.measurementPromise.resolve(msg.data);
                break;
            case "prepareBenchmarkFinished":
                that.prepareBenchmarkPromise.resolve();
                break;
            case "executeBenchmarkFinished":
                that.executeBenchmarkPromise.resolve();
                break;
            case "subscriptionFinished":
                that.subsciptionFinishedPromise.resolve();
                break;
            case "receivedBroadcasts":
                that.broadcastsReceivedPromise.resolve();
                break;
            default:
                throw new Error(`unknown MessageType${JSON.stringify(msg)}`);
        }
    });

    return this.ready.promise;
};

ChildProcessStuff.prototype.shutdown = function() {
    this.process.send({ msg: "terminate" });
};

ChildProcessStuff.prototype.startMeasurement = function() {
    this.process.send({ msg: "startMeasurement" });
};

ChildProcessStuff.prototype.stopMeasurement = function() {
    this.process.send({ msg: "stopMeasurement" });
    this.measurementPromise = PerformanceUtilities.createPromise();
    return this.measurementPromise.promise;
};

ChildProcessStuff.prototype.prepareForBroadcast = function(benchmarkConfig) {
    this.process.send({ msg: "subscribeBroadcast", amount: benchmarkConfig.numRuns });
    this.subsciptionFinishedPromise = PerformanceUtilities.createPromise();
    this.broadcastsReceivedPromise = PerformanceUtilities.createPromise();
    return this.subsciptionFinishedPromise.promise;
};

ProcessManager.provider = new ChildProcessStuff("provider");
ProcessManager.proxy = new ChildProcessStuff("proxy");

ProcessManager.proxy.prepareBenchmark = function(benchmarkConfig) {
    this.process.send({ msg: "prepareBenchmark", config: benchmarkConfig });
    this.prepareBenchmarkPromise = PerformanceUtilities.createPromise();
    return this.prepareBenchmarkPromise.promise;
};

ProcessManager.proxy.executeBenchmark = function(benchmarkConfig) {
    this.process.send({ msg: "executeBenchmark", config: benchmarkConfig });
    this.executeBenchmarkPromise = PerformanceUtilities.createPromise();
    return this.executeBenchmarkPromise.promise;
};

ProcessManager.initializeChildProcesses = function() {
    const providerPromise = ProcessManager.provider.initialize();
    const proxyPromise = ProcessManager.proxy.initialize();

    exitHook(() => {
        ProcessManager.provider.shutdown();
        ProcessManager.proxy.shutdown();
    });
    return Promise.all([providerPromise, proxyPromise]);
};

ProcessManager.takeHeapSnapShot = function(name) {
    this.proxy.process.send({ msg: "takeHeapSnapShot", name: `./proxy${name}.heapsnapshot` });
    this.provider.process.send({ msg: "takeHeapSnapShot", name: `./provider${name}.heapsnapshot` });
};

let initializedBroadcasts = false;

ProcessManager.initializeBroadcast = function(benchmarkConfig) {
    if (initializedBroadcasts) {
        return Promise.resolve();
    }
    initializedBroadcasts = true;
    let count = benchmarkConfig.numProxies;
    this.broadcastProxies = [];
    const broadcastProxiesInitializedPromises = [];
    while (count--) {
        const broadcastProxy = new ChildProcessStuff("proxy");
        const broadCastProxyInitialized = broadcastProxy.initialize();
        this.broadcastProxies.push(broadcastProxy);
        broadcastProxiesInitializedPromises.push(broadCastProxyInitialized);
    }
    return Promise.all(broadcastProxiesInitializedPromises);
};

ProcessManager.prepareBroadcasts = function(benchmarkConfig) {
    return ProcessManager.initializeBroadcast(benchmarkConfig).then(() => {
        return Promise.all(this.broadcastProxies.map(proxy => proxy.prepareForBroadcast(benchmarkConfig)));
    });
};

ProcessManager._prepareBroadcastResults = function() {
    const timeMs = Date.now() - this.broadcastStarted;
    console.log(`broadcast took: ${timeMs}ms`);
    const providerFinished = this.provider.stopMeasurement();

    const broadcastProxiesFinished = this.broadcastProxies.map(proxy => proxy.stopMeasurement());
    const broadcastProxiesReduced = Promise.all(broadcastProxiesFinished).then(results => {
        let total;
        const numberOfProxies = broadcastProxiesFinished.length;
        if (measureMemory) {
            total = results.reduce(
                (acc, curr) => {
                    acc.user += curr.user;
                    acc.system += curr.system;
                    acc.averageMemory += curr.averageMemory;
                },
                { user: 0, system: 0, averageMemory: 0 }
            );
            total.averageMemory /= numberOfProxies;
        } else {
            total = results.reduce(
                (acc, curr) => {
                    acc.user += curr.user;
                    acc.system += curr.system;
                    return acc;
                },
                { user: 0, system: 0 }
            );
        }
        total.user /= numberOfProxies;
        total.system /= numberOfProxies;
        return total;
    });
    return Promise.all([providerFinished, broadcastProxiesReduced]).then(values => {
        return { proxy: values[1], provider: values[0], time: timeMs };
    });
};

ProcessManager.executeBroadcasts = function(benchmarkConfig) {
    this.provider.startMeasurement();
    let l = this.broadcastProxies.length;
    const promises = [];
    while (l--) {
        const broadcastProxy = this.broadcastProxies[l];
        broadcastProxy.startMeasurement();
        promises.push(broadcastProxy.broadcastsReceivedPromise.promise);
    }
    this.broadcastStarted = Date.now();
    this.provider.process.send({ msg: "fireBroadCast", amount: benchmarkConfig.numRuns });
    return Promise.all(promises).then(() => ProcessManager._prepareBroadcastResults());
};

module.exports = ProcessManager;
<|endoftext|>


<commit_before>const base = require('./karma.base.conf');

module.exports = Object.assign(base, {
	browserDisconnectTimeout: 10000,
	browserDisconnectTolerance: 1,
	browserNoActivityTimeout: 30000,
	captureTimeout: 30000,
	concurrency: 1,
	browserStack: {
		username: process.env.BROWSERSTACK_USERNAME,
		accessKey: process.env.BROWSERSTACK_ACCESS_KEY
	},
	autoWatch: false,
	singleRun: true,
	reporters: ['dots', 'BrowserStack']
});<commit_msg>Update karma browserstack reporter to mocha<commit_after>const base = require('./karma.base.conf');

module.exports = Object.assign(base, {
	browserDisconnectTimeout: 10000,
	browserDisconnectTolerance: 1,
	browserNoActivityTimeout: 30000,
	captureTimeout: 30000,
	concurrency: 1,
	browserStack: {
		username: process.env.BROWSERSTACK_USERNAME,
		accessKey: process.env.BROWSERSTACK_ACCESS_KEY
	},
	autoWatch: false,
	singleRun: true,
	reporters: ['mocha', 'BrowserStack']
});<|endoftext|>


<commit_before>/* global assert, process, setup, suite, test */

var helpers = require('../helpers'),
    entityFactory = helpers.entityFactory;

suite('super-hands lifecycle', function () {
  setup(function (done) {
    var el = this.el = entityFactory();
    el.setAttribute('super-hands', '');
    el.addEventListener('loaded', function () {
      done();
    });
  });
  test('component attaches without errors', function () {
    assert.isOk(this.el.components['super-hands'].data);
    assert.equal(this.el.components['super-hands'].data.colliderState,
                 'collided');
  });
  test('component removes without errors', function (done) {
    var el = this.el;
    el.removeComponent('super-hands');
    process.nextTick(function () {
      assert.notOk(el.components['super-hands']);
      done();
    });
  });
});

suite('super-hands hit processing & event emission', function () {
  setup(function (done) {
    this.target1 = entityFactory();
    this.target2 = document.createElement('a-entity');
    this.target1.parentNode.appendChild(this.target2);
    this.hand1 = helpers.controllerFactory({
      'super-hands': ''
    });
    this.hand2 = helpers.controllerFactory({
      'vive-controls': 'hand: left',
      'super-hands': ''
    }, true);
    this.hand1.parentNode.addEventListener('loaded', () => {
      this.sh1 = this.hand1.components['super-hands'];
      this.sh2 = this.hand2.components['super-hands'];
      done();
    });
  });
  test('hover event', function (done) {
    this.target1.addEventListener('hover-start', evt => {
      assert.strictEqual(evt.detail.hand, this.hand1);
      assert.includeMembers(this.sh1.hoverEls, [this.target1]);
      done();
    });
    this.sh1.onHit({ detail: { el: this.target1 } });
  });
  test('unhover event', function (done) {
    this.sh1.onHit({ detail: { el: this.target1 } });
    this.target1.addEventListener('hover-end', evt => {
      assert.strictEqual(evt.detail.hand, this.hand1);
      assert.strictEqual(this.sh1.hoverEls.indexOf(this.target1), -1);
      done();
    });
    this.sh1.useHoveredEl();
  });
  test('stacking hovered entities', function () {
    this.sh1.onHit({ detail: { el: this.target1 } });
    this.sh1.onHit({ detail: { el: this.target2 } });
    assert.equal(this.sh1.hoverEls.length, 2);
    assert.strictEqual(this.sh1.useHoveredEl(), this.target1);
    assert.equal(this.sh1.hoverEls.length, 1);
    assert.strictEqual(this.sh1.useHoveredEl(), this.target2);
    assert.equal(this.sh1.hoverEls.length, 0);
  });
  test('grab event', function (done) {
    this.sh1.onGrabStartButton();
    this.target1.addEventListener('grab-start', evt => {
      assert.strictEqual(evt.detail.hand, this.hand1);
      assert.strictEqual(this.sh1.carried, this.target1);
      done();
    });
    this.sh1.onHit({ detail: { el: this.target1 } });
  });
  test('ungrab event', function (done) {
    this.sh1.onGrabStartButton();
    this.target1.addEventListener('grab-end', evt => {
      assert.strictEqual(evt.detail.hand, this.hand1);
      process.nextTick(() => {
        assert.isNotOk(this.sh1.carried);
        assert.isFalse(this.sh1.grabbing);
        done();
      });
    });
    this.sh1.onHit({ detail: { el: this.target1 } });
    this.sh1.onGrabEndButton({});
  });
  test('finds other controller', function() {
    assert.isOk(this.sh1.otherController);
    assert.isOk(this.sh2.otherController);
    assert.strictEqual(this.sh1.otherController, this.hand2);
    assert.strictEqual(this.sh2.otherController, this.hand1);
  });
  test('stretch event', function () {
    var emitSpy = sinon.spy(this.target1, 'emit'),
        stretchSpy = emitSpy.withArgs('stretch-start'),
        unStretchSpy = emitSpy.withArgs('stretch-end');
    this.sh1.onStretchStartButton();
    this.sh1.onHit({ detail: { el: this.target1 } });
    assert.isTrue(this.sh1.stretching);
    assert.strictEqual(this.sh1.stretched, this.target1);
    assert.isFalse(stretchSpy.called);
    this.sh2.onStretchStartButton();
    this.sh2.onHit({ detail: { el: this.target1 } });
    assert.isTrue(this.sh2.stretching);
    assert.strictEqual(this.sh2.stretched, this.target1);
    assert.isTrue(stretchSpy.called);
    assert.isFalse(unStretchSpy.called);
    this.sh1.onStretchEndButton();
    assert.isTrue(unStretchSpy.called);
    assert.isNotOk(this.sh1.stretching);
    assert.strictEqual(this.sh2.stretched, this.target1);
    this.sh2.onStretchEndButton();
    assert.isTrue(unStretchSpy.calledOnce);
    assert.isNotOk(this.sh2.stretching);
  });
  test('drag events', function () {
    var emitSpy1 = sinon.spy(this.target1, 'emit'),
        dragOverSpy1 = emitSpy1.withArgs('dragover-start'),
        unDragOverSpy1 = emitSpy1.withArgs('dragover-end'),
        dragDropSpy1 = emitSpy1.withArgs('drag-drop'),
        emitSpy2 = sinon.spy(this.target2, 'emit'),
        dragOverSpy2 = emitSpy2.withArgs('dragover-start'),
        unDragOverSpy2 = emitSpy2.withArgs('dragover-end'),
        dragDropSpy2 = emitSpy2.withArgs('drag-drop');
    this.sh1.onDragDropStartButton();
    assert.isTrue(this.sh1.dragging, 'dragging');
    this.sh1.onHit({ detail: { el: this.target1 } });
    assert.strictEqual(this.sh1.dragged, this.target1);
    assert.isFalse(dragOverSpy1.called, 'dragover-start not emitted with no droptarget');
    assert.isFalse(dragOverSpy2.called, 'dragover-start not emitted with no droptarget');
    this.sh1.onHit({ detail: { el: this.target2 } });
    assert.notEqual(this.sh1.hoverEls.indexOf(this.target2), -1, 'droptaret added to hoverEls');
    assert.isTrue(dragOverSpy1.called, 'dragover-start emitted from held');
    assert.isTrue(dragOverSpy2.called, 'dragover-start emitted from hovered');
    this.sh1.unHover({ detail: { state: 'unrelated' }, target: this.target2 });
    assert.isFalse(unDragOverSpy1.called, 'unhover ignores unrelated state changes: held');
    assert.isFalse(unDragOverSpy2.called, 'unhover ignores unrelated state changes: hovered');
    this.sh1.unHover({ detail: { state: 'collided' }, target: this.target2 });
    assert.isTrue(unDragOverSpy1.called, 'drag-over ends with drag-drop: held');
    assert.isTrue(unDragOverSpy2.called, 'drag-over ends with drag-drop: hovered');
    this.sh1.onHit({ detail: { el: this.target2 } });
    assert.isFalse(dragDropSpy1.called, 'drag-drop not yet emitted from held');
    assert.isFalse(dragDropSpy2.called, 'drag-drop not yet emitted form hovered');
    this.sh1.onDragDropEndButton();
    assert.isTrue(unDragOverSpy1.calledTwice, 'drag-over ends with drag-drop: held');
    assert.isTrue(unDragOverSpy2.calledTwice, 'drag-over ends with drag-drop: hovered');
    assert.isTrue(dragDropSpy1.called, 'drag-drop emitted from held');
    assert.isTrue(dragDropSpy2.called, 'drag-drop emitted form hovered');
  });
});<commit_msg>test gesture interactions<commit_after>/* global assert, process, setup, suite, test */

var helpers = require('../helpers'),
    entityFactory = helpers.entityFactory;

suite('super-hands lifecycle', function () {
  setup(function (done) {
    var el = this.el = entityFactory();
    el.setAttribute('super-hands', '');
    el.addEventListener('loaded', function () {
      done();
    });
  });
  test('component attaches without errors', function () {
    assert.isOk(this.el.components['super-hands'].data);
    assert.equal(this.el.components['super-hands'].data.colliderState,
                 'collided');
  });
  test('component removes without errors', function (done) {
    var el = this.el;
    el.removeComponent('super-hands');
    process.nextTick(function () {
      assert.notOk(el.components['super-hands']);
      done();
    });
  });
});

suite('super-hands hit processing & event emission', function () {
  setup(function (done) {
    this.target1 = entityFactory();
    this.target2 = document.createElement('a-entity');
    this.target1.parentNode.appendChild(this.target2);
    this.hand1 = helpers.controllerFactory({
      'super-hands': ''
    });
    this.hand2 = helpers.controllerFactory({
      'vive-controls': 'hand: left',
      'super-hands': ''
    }, true);
    this.hand1.parentNode.addEventListener('loaded', () => {
      this.sh1 = this.hand1.components['super-hands'];
      this.sh2 = this.hand2.components['super-hands'];
      done();
    });
  });
  test('hover event', function (done) {
    this.target1.addEventListener('hover-start', evt => {
      assert.strictEqual(evt.detail.hand, this.hand1);
      assert.includeMembers(this.sh1.hoverEls, [this.target1]);
      done();
    });
    this.sh1.onHit({ detail: { el: this.target1 } });
  });
  test('unhover event', function (done) {
    this.sh1.onHit({ detail: { el: this.target1 } });
    this.target1.addEventListener('hover-end', evt => {
      assert.strictEqual(evt.detail.hand, this.hand1);
      assert.strictEqual(this.sh1.hoverEls.indexOf(this.target1), -1);
      done();
    });
    this.sh1.useHoveredEl();
  });
  test('stacking hovered entities', function () {
    this.sh1.onHit({ detail: { el: this.target1 } });
    this.sh1.onHit({ detail: { el: this.target2 } });
    assert.equal(this.sh1.hoverEls.length, 2);
    assert.strictEqual(this.sh1.useHoveredEl(), this.target1);
    assert.equal(this.sh1.hoverEls.length, 1);
    assert.strictEqual(this.sh1.useHoveredEl(), this.target2);
    assert.equal(this.sh1.hoverEls.length, 0);
  });
  test('grab event', function (done) {
    this.sh1.onGrabStartButton();
    this.target1.addEventListener('grab-start', evt => {
      assert.strictEqual(evt.detail.hand, this.hand1);
      assert.strictEqual(this.sh1.carried, this.target1);
      done();
    });
    this.sh1.onHit({ detail: { el: this.target1 } });
  });
  test('ungrab event', function (done) {
    this.sh1.onGrabStartButton();
    this.target1.addEventListener('grab-end', evt => {
      assert.strictEqual(evt.detail.hand, this.hand1);
      process.nextTick(() => {
        assert.isNotOk(this.sh1.carried);
        assert.isFalse(this.sh1.grabbing);
        done();
      });
    });
    this.sh1.onHit({ detail: { el: this.target1 } });
    this.sh1.onGrabEndButton({});
  });
  test('finds other controller', function() {
    assert.isOk(this.sh1.otherController);
    assert.isOk(this.sh2.otherController);
    assert.strictEqual(this.sh1.otherController, this.hand2);
    assert.strictEqual(this.sh2.otherController, this.hand1);
  });
  test('stretch event', function () {
    var emitSpy = sinon.spy(this.target1, 'emit'),
        stretchSpy = emitSpy.withArgs('stretch-start'),
        unStretchSpy = emitSpy.withArgs('stretch-end');
    this.sh1.onStretchStartButton();
    this.sh1.onHit({ detail: { el: this.target1 } });
    assert.isTrue(this.sh1.stretching);
    assert.strictEqual(this.sh1.stretched, this.target1);
    assert.isFalse(stretchSpy.called);
    this.sh2.onStretchStartButton();
    this.sh2.onHit({ detail: { el: this.target1 } });
    assert.isTrue(this.sh2.stretching);
    assert.strictEqual(this.sh2.stretched, this.target1);
    assert.isTrue(stretchSpy.called);
    assert.isFalse(unStretchSpy.called);
    this.sh1.onStretchEndButton();
    assert.isTrue(unStretchSpy.called);
    assert.isNotOk(this.sh1.stretching);
    assert.strictEqual(this.sh2.stretched, this.target1);
    this.sh2.onStretchEndButton();
    assert.isTrue(unStretchSpy.calledOnce);
    assert.isNotOk(this.sh2.stretching);
  });
  test('drag events', function () {
    var emitSpy1 = sinon.spy(this.target1, 'emit'),
        dragOverSpy1 = emitSpy1.withArgs('dragover-start'),
        unDragOverSpy1 = emitSpy1.withArgs('dragover-end'),
        dragDropSpy1 = emitSpy1.withArgs('drag-drop'),
        emitSpy2 = sinon.spy(this.target2, 'emit'),
        dragOverSpy2 = emitSpy2.withArgs('dragover-start'),
        unDragOverSpy2 = emitSpy2.withArgs('dragover-end'),
        dragDropSpy2 = emitSpy2.withArgs('drag-drop');
    this.sh1.onDragDropStartButton();
    assert.isTrue(this.sh1.dragging, 'dragging');
    this.sh1.onHit({ detail: { el: this.target1 } });
    assert.strictEqual(this.sh1.dragged, this.target1);
    assert.isFalse(dragOverSpy1.called, 'dragover-start not emitted with no droptarget');
    assert.isFalse(dragOverSpy2.called, 'dragover-start not emitted with no droptarget');
    this.sh1.onHit({ detail: { el: this.target2 } });
    assert.notEqual(this.sh1.hoverEls.indexOf(this.target2), -1, 'droptaret added to hoverEls');
    assert.isTrue(dragOverSpy1.called, 'dragover-start emitted from held');
    assert.isTrue(dragOverSpy2.called, 'dragover-start emitted from hovered');
    this.sh1.unHover({ detail: { state: 'unrelated' }, target: this.target2 });
    assert.isFalse(unDragOverSpy1.called, 'unhover ignores unrelated state changes: held');
    assert.isFalse(unDragOverSpy2.called, 'unhover ignores unrelated state changes: hovered');
    this.sh1.unHover({ detail: { state: 'collided' }, target: this.target2 });
    assert.isTrue(unDragOverSpy1.called, 'drag-over ends with drag-drop: held');
    assert.isTrue(unDragOverSpy2.called, 'drag-over ends with drag-drop: hovered');
    this.sh1.onHit({ detail: { el: this.target2 } });
    assert.isFalse(dragDropSpy1.called, 'drag-drop not yet emitted from held');
    assert.isFalse(dragDropSpy2.called, 'drag-drop not yet emitted form hovered');
    this.sh1.onDragDropEndButton();
    assert.isTrue(unDragOverSpy1.calledTwice, 'drag-over ends with drag-drop: held');
    assert.isTrue(unDragOverSpy2.calledTwice, 'drag-over ends with drag-drop: hovered');
    assert.isTrue(dragDropSpy1.called, 'drag-drop emitted from held');
    assert.isTrue(dragDropSpy2.called, 'drag-drop emitted form hovered');
  });
  test('all gestures at once capture same entity', function () {
    this.sh1.onGrabStartButton();
    this.sh1.onDragDropStartButton();
    this.sh1.onStretchStartButton();
    this.sh1.onHit({ detail: { el: this.target1 } });
    assert.equal(this.sh1.hoverEls.length, 0);
    assert.strictEqual(this.sh1.carried, this.sh1.dragged);
    assert.strictEqual(this.sh1.dragged, this.sh1.stretched);
  });
  test('drag after grab uses carried entity', function () {
    this.sh1.onGrabStartButton();
    this.sh1.onHit({ detail: { el: this.target1 } });
    this.sh1.onDragDropStartButton();
    this.sh1.onHit({ detail: { el: this.target2 } });
    assert.strictEqual(this.sh1.carried, this.sh1.dragged);
    assert.sameMembers(this.sh1.hoverEls, [this.target2]);
  });
});<|endoftext|>


<commit_before>'use strict';

if (typeof Symbol == 'undefined') {
  require("babel-core/polyfill");
}

import DeepFramework from 'deep-framework';
import Handler from './Handler';

exports.handler = function (event, context) {
  DeepFramework.KernelFromLambdaContext(context).loadFromFile("_config.json", function (deepKernel) {
    new Handler(deepKernel).run(event, context);
  });
};
<commit_msg>Update bootstrap.es6<commit_after>'use strict';

if (typeof Symbol == 'undefined') {
  require("babel-polyfill");
}

import DeepFramework from 'deep-framework';
import Handler from './Handler';

exports.handler = function (event, context) {
  DeepFramework.KernelFromLambdaContext(context).loadFromFile("_config.json", function (deepKernel) {
    new Handler(deepKernel).run(event, context);
  });
};
<|endoftext|>


<commit_before>/**
 * Shopware 5
 * Copyright (c) shopware AG
 *
 * According to our dual licensing model, this program can be used either
 * under the terms of the GNU Affero General Public License, version 3,
 * or under a proprietary license.
 *
 * The texts of the GNU Affero General Public License with an additional
 * permission and of our proprietary license can be found at and
 * in the LICENSE file you have received along with this program.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * "Shopware" is a registered trademark of shopware AG.
 * The licensing of the program under the AGPLv3 does not imply a
 * trademark license. Therefore any rights, title and interest in
 * our trademarks remain entirely with us.
 *
 * @category   Shopware
 * @package    Order
 * @subpackage View
 * @version    $Id$
 * @author shopware AG
 */

//{namespace name=backend/order/main}

/**
 * Shopware UI - Order batch window
 */
//{block name="backend/order/view/mail/form"}
Ext.define('Shopware.apps.Order.view.mail.Form', {

    /**
     * Define that the additional information is an Ext.panel.Panel extension
     *
     * @type { String }
     */
    extend:'Ext.form.Panel',

    /**
     * List of short aliases for class names. Most useful for defining xtypes for widgets.
     *
     * @type { String }
     */
    alias:'widget.order-mail-form',

    /**
     * An optional extra CSS class that will be added to this component's Element.
     */
    cls: Ext.baseCSSPrefix + 'batch-mail-panel',

    /**
     * Component layout definition
     *
     * @type { Object }
     */
    layout: {
        type: 'vbox',
        align: 'stretch'
    },

    /**
     * A shortcut for setting a padding style on the body element. The value can either be a number to be applied to all sides, or a normal css string describing padding.
     *
     * @type { Number }
     */
    bodyPadding: 10,

    border: false,

    /**
     * Contains all snippets for the view component
     *
     * @type { Object }
     */
    snippets: {
        subject: '{s name=subject}Subject{/s}',
        to: '{s name=to}To{/s}',
        button: '{s name=button}Send mail{/s}'
    },

    /**
     * The initComponent template method is an important initialization step for a Component.
     * It is intended to be implemented by each subclass of Ext.Component to provide any needed constructor logic.
     * The initComponent method of the class being created is called first,
     * with each initComponent method up the hierarchy to Ext.Component being called thereafter.
     * This makes it easy to implement and, if needed, override the constructor logic of the Component at any step in the hierarchy.
     * The initComponent method must contain a call to callParent in order to ensure that the parent class' initComponent method is also called.
     */
    initComponent:function () {
        var me = this;

        me.registerEvents();

        me.items = me.getFormItems();

        me.dockedItems = me.getToolbar();

        me.callParent(arguments);
    },

    registerEvents: function() {
        this.addEvents(
            /**
             * Event will be fired when the user clicks the "generate documents" button which is
             * displayed within the form field set.
             *
             * @event sendMail
             * @param { Ext.form.Panel } - This component
             */
            'sendMail'
        );
    },

    getToolbar: function () {
        var me = this;

        return Ext.create('Ext.toolbar.Toolbar', {
            dock: 'bottom',
            items: [
                '->',
                {
                    xtype: 'button',
                    cls: 'primary',
                    text: me.snippets.button,
                    handler: function () {
                        me.fireEvent('sendMail', me);
                    }
                }
            ]
        });
    },

    getFormItems: function() {
        var me = this;

        return [
            {
                xtype: 'textfield',
                name: 'to',
                fieldLabel: me.snippets.to
            },
            {
                xtype: 'textfield',
                name: 'subject',
                fieldLabel: me.snippets.subject
            },
            {
                xtype: 'textarea',
                name: 'content',
                minHeight: 90,
                flex: 1
            }
        ];
    }

});
//{/block}
<commit_msg>SW-10015 - Added docs<commit_after>/**
 * Shopware 5
 * Copyright (c) shopware AG
 *
 * According to our dual licensing model, this program can be used either
 * under the terms of the GNU Affero General Public License, version 3,
 * or under a proprietary license.
 *
 * The texts of the GNU Affero General Public License with an additional
 * permission and of our proprietary license can be found at and
 * in the LICENSE file you have received along with this program.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * "Shopware" is a registered trademark of shopware AG.
 * The licensing of the program under the AGPLv3 does not imply a
 * trademark license. Therefore any rights, title and interest in
 * our trademarks remain entirely with us.
 *
 * @category   Shopware
 * @package    Order
 * @subpackage View
 * @version    $Id$
 * @author shopware AG
 */

//{namespace name=backend/order/main}

/**
 * Shopware UI - Order batch window
 */
//{block name="backend/order/view/mail/form"}
Ext.define('Shopware.apps.Order.view.mail.Form', {

    /**
     * Define that the additional information is an Ext.panel.Panel extension
     *
     * @type { String }
     */
    extend:'Ext.form.Panel',

    /**
     * List of short aliases for class names. Most useful for defining xtypes for widgets.
     *
     * @type { String }
     */
    alias:'widget.order-mail-form',

    /**
     * An optional extra CSS class that will be added to this component's Element.
     */
    cls: Ext.baseCSSPrefix + 'batch-mail-panel',

    /**
     * Component layout definition
     *
     * @type { Object }
     */
    layout: {
        type: 'vbox',
        align: 'stretch'
    },

    /**
     * A shortcut for setting a padding style on the body element. The value can either be a number to be applied to all sides, or a normal css string describing padding.
     *
     * @type { Number }
     */
    bodyPadding: 10,

    /**
     * Whether or not the form panel should have a border.
     *
     * @type { Boolean }
     */
    border: false,

    /**
     * Contains all snippets for the view component
     *
     * @type { Object }
     */
    snippets: {
        subject: '{s name=subject}Subject{/s}',
        to: '{s name=to}To{/s}',
        button: '{s name=button}Send mail{/s}'
    },

    /**
     * The initComponent template method is an important initialization step for a Component.
     * It is intended to be implemented by each subclass of Ext.Component to provide any needed constructor logic.
     * The initComponent method of the class being created is called first,
     * with each initComponent method up the hierarchy to Ext.Component being called thereafter.
     * This makes it easy to implement and, if needed, override the constructor logic of the Component at any step in the hierarchy.
     * The initComponent method must contain a call to callParent in order to ensure that the parent class' initComponent method is also called.
     */
    initComponent:function () {
        var me = this;

        me.registerEvents();

        me.items = me.getFormItems();

        me.dockedItems = me.getToolbar();

        me.callParent(arguments);
    },

    /**
     * Registers the custom component events.
     */
    registerEvents: function() {
        this.addEvents(
            /**
             * Event will be fired when the user clicks the "generate documents" button which is
             * displayed within the form field set.
             *
             * @event sendMail
             * @param { Ext.form.Panel } - This component
             */
            'sendMail'
        );
    },

    /**
     * Creates and returns the toolbar which contains the send mail button.
     *
     * @returns { Ext.toolbar.Toolbar }
     */
    getToolbar: function () {
        var me = this;

        return Ext.create('Ext.toolbar.Toolbar', {
            dock: 'bottom',
            items: [
                '->',
                {
                    xtype: 'button',
                    cls: 'primary',
                    text: me.snippets.button,
                    handler: function () {
                        me.fireEvent('sendMail', me);
                    }
                }
            ]
        });
    },

    /**
     * Creates and returns an array of the form elements to send a mail.
     *
     * @returns { Array }
     */
    getFormItems: function() {
        var me = this;

        return [
            {
                xtype: 'textfield',
                name: 'to',
                fieldLabel: me.snippets.to
            },
            {
                xtype: 'textfield',
                name: 'subject',
                fieldLabel: me.snippets.subject
            },
            {
                xtype: 'textarea',
                name: 'content',
                minHeight: 90,
                flex: 1
            }
        ];
    }

});
//{/block}
<|endoftext|>


<commit_before>/**
@ngdoc directive
@name umbraco.directives.directive:umbTable
@restrict E
@scope

@description
Added in Umbraco v. 7.4: Use this directive to render a data table.

Markup example

        <umb-table
            ng-if="items"
            items="vm.items"
            item-properties="vm.options.includeProperties"
            allow-select-all="vm.allowSelectAll"
            on-select="vm.selectItem"
            on-click="vm.clickItem"
            on-select-all="vm.selectAll"
            on-selected-all="vm.isSelectedAll"
            on-sorting-direction="vm.isSortDirection"
            on-sort="vm.sort">
        </umb-table>

Controller example

    (function () {
        "use strict";

        function Controller() {

            var vm = this;

            vm.items = [
                {
                    "icon": "icon-document",
                    "name": "My node 1",
                    "published": true,
                    "description": "A short description of my node",
                    "author": "Author 1"
                },
                {
                    "icon": "icon-document",
                    "name": "My node 2",
                    "published": true,
                    "description": "A short description of my node",
                    "author": "Author 2"
                }
            ];

            vm.options = {
                includeProperties: [
                    { alias: "description", header: "Description" },
                    { alias: "author", header: "Author" }
                ]
            };

            vm.selectItem = selectItem;
            vm.clickItem = clickItem;
            vm.selectAll = selectAll;
            vm.isSelectedAll = isSelectedAll;
            vm.isSortDirection = isSortDirection;
            vm.sort = sort;

            function selectAll($event) {
                alert("select all");
            }

            function isSelectedAll() {

            }

            function clickItem(item) {
                alert("click node");
            }

            function selectItem(selectedItem, $index, $event) {
                alert("select node");
            }

            function isSortDirection(col, direction) {

            }

            function sort(field, allow, isSystem) {

            }

        }

        angular.module("umbraco").controller("My.TableController", Controller);

    })();

@param {array} items (binding): The items for the table.
@param {array} itemProperties (binding): The properties for the items to use in table.
@param {boolean} allowSelectAll (binding): Specify whether to allow select all.
@param {function} onSelect (expression): Callback function when the row is selected.
@param {function} onClick (expression): Callback function when the "Name" column link is clicked.
@param {function} onSelectAll (expression): Callback function when selecting all items.
@param {function} onSelectedAll (expression): Callback function when all items are selected.
@param {function} onSortingDirection (expression): Callback function when sorting direction is changed.
@param {function} onSort (expression): Callback function when sorting items.
**/

(function () {
    'use strict';

    function TableController(iconHelper) {

        var vm = this;

        vm.clickItem = function (item, $event) {
            if (vm.onClick && !($event.metaKey || $event.ctrlKey)) {
                vm.onClick({ item: item});
                $event.preventDefault();
            }
            $event.stopPropagation();
        };

        vm.selectItem = function (item, $index, $event) {
            if (vm.onSelect) {
                vm.onSelect({ item: item, $index: $index, $event: $event });
                $event.stopPropagation();
            }
        };

        vm.selectAll = function ($event) {
            if (vm.onSelectAll) {
                vm.onSelectAll({ $event: $event});
            }
        };

        vm.isSelectedAll = function () {
            if (vm.onSelectedAll && vm.items && vm.items.length > 0) {
                return vm.onSelectedAll();
            }
        };

        vm.isSortDirection = function (col, direction) {
            if (vm.onSortingDirection) {
                return vm.onSortingDirection({ col: col, direction: direction });
            }
        };

        vm.sort = function (field, allow, isSystem) {
            if (vm.onSort) {
                vm.onSort({ field: field, allow: allow, isSystem: isSystem  });
            }
        };

        vm.getIcon = function (entry) {
            return iconHelper.convertFromLegacyIcon(entry.icon);
        };
    }

    angular
        .module('umbraco.directives')
        .component('umbTable', {
            templateUrl: 'views/components/umb-table.html',
            controller: TableController,
            controllerAs: 'vm',
            bindings: {
                items: '<',
                itemProperties: '<',
                allowSelectAll: '<',
                onSelect: '&',
                onClick: '&',
                onSelectAll: '&',
                onSelectedAll: '&',
                onSortingDirection: '&',
                onSort: '&'
            }
        });

})();
<commit_msg>Updated umbtable.directive.js for a working example<commit_after>/**
@ngdoc directive
@name umbraco.directives.directive:umbTable
@restrict E
@scope

@description
Added in Umbraco v. 7.4: Use this directive to render a data table.

Markup example

        <umb-table
            ng-if="vm.items"
            items="vm.items"
            item-properties="vm.options.includeProperties"
            allow-select-all="vm.allowSelectAll"
            on-select="vm.selectItem"
            on-click="vm.clickItem"
            on-select-all="vm.selectAll"
            on-selected-all="vm.isSelectedAll"
            on-sorting-direction="vm.isSortDirection"
            on-sort="vm.sort">
        </umb-table>

Controller example

    (function () {
        "use strict";

        function Controller() {

            var vm = this;

            vm.items = [
                {
                    "icon": "icon-document",
                    "name": "My node 1",
                    "published": true,
                    "description": "A short description of my node",
                    "author": "Author 1"
                },
                {
                    "icon": "icon-document",
                    "name": "My node 2",
                    "published": true,
                    "description": "A short description of my node",
                    "author": "Author 2"
                }
            ];

            vm.options = {
                includeProperties: [
                    { alias: "description", header: "Description" },
                    { alias: "author", header: "Author" }
                ]
            };

            vm.selectItem = selectItem;
            vm.clickItem = clickItem;
            vm.selectAll = selectAll;
            vm.isSelectedAll = isSelectedAll;
            vm.isSortDirection = isSortDirection;
            vm.sort = sort;

            function selectAll($event) {
                alert("select all");
            }

            function isSelectedAll() {

            }

            function clickItem(item) {
                alert("click node");
            }

            function selectItem(selectedItem, $index, $event) {
                alert("select node");
            }

            function isSortDirection(col, direction) {

            }

            function sort(field, allow, isSystem) {

            }

        }

        angular.module("umbraco").controller("My.TableController", Controller);

    })();

@param {array} items (binding): The items for the table.
@param {array} itemProperties (binding): The properties for the items to use in table.
@param {boolean} allowSelectAll (binding): Specify whether to allow select all.
@param {function} onSelect (expression): Callback function when the row is selected.
@param {function} onClick (expression): Callback function when the "Name" column link is clicked.
@param {function} onSelectAll (expression): Callback function when selecting all items.
@param {function} onSelectedAll (expression): Callback function when all items are selected.
@param {function} onSortingDirection (expression): Callback function when sorting direction is changed.
@param {function} onSort (expression): Callback function when sorting items.
**/

(function () {
    'use strict';

    function TableController(iconHelper) {

        var vm = this;

        vm.clickItem = function (item, $event) {
            if (vm.onClick && !($event.metaKey || $event.ctrlKey)) {
                vm.onClick({ item: item});
                $event.preventDefault();
            }
            $event.stopPropagation();
        };

        vm.selectItem = function (item, $index, $event) {
            if (vm.onSelect) {
                vm.onSelect({ item: item, $index: $index, $event: $event });
                $event.stopPropagation();
            }
        };

        vm.selectAll = function ($event) {
            if (vm.onSelectAll) {
                vm.onSelectAll({ $event: $event});
            }
        };

        vm.isSelectedAll = function () {
            if (vm.onSelectedAll && vm.items && vm.items.length > 0) {
                return vm.onSelectedAll();
            }
        };

        vm.isSortDirection = function (col, direction) {
            if (vm.onSortingDirection) {
                return vm.onSortingDirection({ col: col, direction: direction });
            }
        };

        vm.sort = function (field, allow, isSystem) {
            if (vm.onSort) {
                vm.onSort({ field: field, allow: allow, isSystem: isSystem  });
            }
        };

        vm.getIcon = function (entry) {
            return iconHelper.convertFromLegacyIcon(entry.icon);
        };
    }

    angular
        .module('umbraco.directives')
        .component('umbTable', {
            templateUrl: 'views/components/umb-table.html',
            controller: TableController,
            controllerAs: 'vm',
            bindings: {
                items: '<',
                itemProperties: '<',
                allowSelectAll: '<',
                onSelect: '&',
                onClick: '&',
                onSelectAll: '&',
                onSelectedAll: '&',
                onSortingDirection: '&',
                onSort: '&'
            }
        });

})();
<|endoftext|>


<commit_before>(function () {
  "use strict";

  function ContentAppListViewController($scope) {

    var vm = this;

    vm.propertyEditorReadonly = propertyEditorReadonly;

    function propertyEditorReadonly () {
      // check for permission to update
      return !(typeof $scope.variantContent !== 'undefined' && $scope.variantContent.allowedActions.includes('A'));
    }

  }

  angular.module("umbraco").controller("Umbraco.Editors.Content.Apps.ListViewController", ContentAppListViewController);
})();
<commit_msg>Fix broken selectable state for list view items (#13148)<commit_after>(function () {
  "use strict";

  function ContentAppListViewController($scope) {

    var vm = this;

    vm.propertyEditorReadonly = propertyEditorReadonly;

    function propertyEditorReadonly () {
      // check for permission to update
      return $scope.variantContent && !$scope.variantContent.allowedActions.includes('A');
    }

  }

  angular.module("umbraco").controller("Umbraco.Editors.Content.Apps.ListViewController", ContentAppListViewController);
})();
<|endoftext|>


<commit_before><commit_msg>Fixed problems with hour = 0<commit_after><|endoftext|>


<commit_before>var GetTransformedPoint = require('./GetTransformedPoint');
var PointWithinGameObject = require('./PointWithinGameObject');

var PointScreenToWorldHitTest = function (tempMatrix, x, y, gameObjectArray, camera, output)
{
    var length = gameObjectArray.length;
    var scrollX = camera.scrollX;
    var scrollY = camera.scrollY;
    var cameraW = camera.width;
    var cameraH = camera.height;

    if (!(x >= camera.x && y >= camera.y &&
        x <= camera.x + cameraW && y <= camera.y + cameraH))
    {
        return null;
    }

    var screenPoint = camera.cameraToScreen({x: x, y: y});

    output.length = 0;

    if (gameObjectArray instanceof Array)
    {
        var culled = camera.cull(gameObjectArray);
        var culledLength = culled.length;

        for (var index = 0; index < culledLength; ++index)
        {
            var object = culled[index];
            var tpoint = GetTransformedPoint(tempMatrix, object, screenPoint.x + scrollX * object.scrollFactorX, screenPoint.y + scrollY * object.scrollFactorY);

            if (PointWithinGameObject(object, tpoint.x, tpoint.y))
            {
                output.push(object);
            }
        }

        return output;
    }
    else
    {
        var tpoint = GetTransformedPoint(tempMatrix, object, screenPoint.x + scrollX * object.scrollFactorX, screenPoint.y + scrollY * object.scrollFactorY);

        if (PointWithinGameObject(object, tpoint.x, tpoint.y))
        {
            return object;
        }
    }

    return null;
};

module.exports = PointScreenToWorldHitTest;
<commit_msg>PointScreenToWorldHitTest now always returns an array no matter what<commit_after>var GetTransformedPoint = require('./GetTransformedPoint');
var PointWithinGameObject = require('./PointWithinGameObject');

//  Will always return an array.
//  Array contains matching Game Objects.
//  Array will be empty if no objects were matched.

var PointScreenToWorldHitTest = function (tempMatrix, x, y, gameObjectArray, camera, output)
{
    var length = gameObjectArray.length;
    var scrollX = camera.scrollX;
    var scrollY = camera.scrollY;
    var cameraW = camera.width;
    var cameraH = camera.height;

    output.length = 0;

    if (!(x >= camera.x && y >= camera.y &&
        x <= camera.x + cameraW && y <= camera.y + cameraH))
    {
        return output;
    }

    var screenPoint = camera.cameraToScreen({x: x, y: y});

    if (Array.isArray(gameObjectArray))
    {
        var culled = camera.cull(gameObjectArray);
        var culledLength = culled.length;

        for (var index = 0; index < culledLength; ++index)
        {
            var object = culled[index];
            var tpoint = GetTransformedPoint(tempMatrix, object, screenPoint.x + scrollX * object.scrollFactorX, screenPoint.y + scrollY * object.scrollFactorY);

            if (PointWithinGameObject(object, tpoint.x, tpoint.y))
            {
                output.push(object);
            }
        }
    }
    else
    {
        var tpoint = GetTransformedPoint(tempMatrix, object, screenPoint.x + scrollX * object.scrollFactorX, screenPoint.y + scrollY * object.scrollFactorY);

        if (PointWithinGameObject(object, tpoint.x, tpoint.y))
        {
            output.push(object);
        }
    }

    return output;
};

module.exports = PointScreenToWorldHitTest;
<|endoftext|>


<commit_before>import { JATS_BIBR_TYPES_TO_INTERNAL, INTERNAL_BIBR_TYPES_TO_JATS } from '../../ArticleConstants'
import { getText, getSeparatedText, getHTML, getAttr } from '../util/domHelpers'

export default class ElementCitationConverter {
  // Note: this will create different types according to the attributes in the JATS element
  get type () { return 'bibr' }

  matchElement (el) {
    return el.is('ref')
  }

  import (el, node, importer) {
    const doc = importer.state.doc
    let elementCitation = el.find('element-citation')
    if (!elementCitation) {
      throw new Error('<element-citation> is required')
    }
    _importElementCitation(elementCitation, node, doc)
  }

  export (node, el, exporter) {
    el.tagName = 'ref'
    el.append(
      _exportElementCitation(node, exporter)
    )
    return el
  }
}

function _importElementCitation (el, node, doc) {
  const type = el.attr('publication-type')
  node.type = JATS_BIBR_TYPES_TO_INTERNAL[type]

  Object.assign(node, {
    assignee: getText(el, 'collab[collab-type=assignee] > named-content'),
    confName: getText(el, 'conf-name'),
    confLoc: getText(el, 'conf-loc'),
    day: getText(el, 'day'),
    edition: getText(el, 'edition'),
    elocationId: getText(el, 'elocation-id'),
    fpage: getText(el, 'fpage'),
    issue: getText(el, 'issue'),
    lpage: getText(el, 'lpage'),
    month: getText(el, 'month'),
    pageCount: getText(el, 'page-count'),
    pageRange: getText(el, 'page-range'),
    partTitle: getText(el, 'part-title'),
    patentCountry: getAttr(el, 'patent', 'country'),
    patentNumber: getText(el, 'patent'),
    publisherLoc: getSeparatedText(el, 'publisher-loc'),
    publisherName: getSeparatedText(el, 'publisher-name'),
    series: getText(el, 'series'),
    uri: getText(el, 'uri'),
    version: getText(el, 'version'),
    volume: getText(el, 'volume'),
    year: getText(el, 'year'),
    // identifiers
    accessionId: getText(el, 'pub-id[pub-id-type=accession]'),
    archiveId: getText(el, 'pub-id[pub-id-type=archive]'),
    arkId: getText(el, 'pub-id[pub-id-type=ark]'),
    isbn: getText(el, 'pub-id[pub-id-type=isbn]'),
    doi: getText(el, 'pub-id[pub-id-type=doi]'),
    pmid: getText(el, 'pub-id[pub-id-type=pmid]')
  })

  if (type === 'book' || type === 'report' || type === 'software') {
    node.title = getText(el, 'source')
  } else {
    node.containerTitle = getText(el, 'source')
    if (type === 'chapter') {
      node.title = getHTML(el, 'chapter-title')
    } else if (type === 'data') {
      node.title = getHTML(el, 'data-title')
    } else {
      node.title = getHTML(el, 'article-title')
    }
  }

  node.authors = _importPersonGroup(el, doc, 'author')
  node.editors = _importPersonGroup(el, doc, 'editor')
  node.inventors = _importPersonGroup(el, doc, 'inventor')
  node.sponsors = _importPersonGroup(el, doc, 'sponsor')
  node.translators = _importPersonGroup(el, doc, 'translator')
}

function _importPersonGroup (el, doc, type) {
  let groupEl = el.find(`person-group[person-group-type=${type}]`)
  if (groupEl) {
    return groupEl.children.reduce((ids, childEl) => {
      let refContrib = _importRefContrib(doc, childEl)
      if (refContrib) ids.push(refContrib.id)
      return ids
    }, [])
  } else {
    return []
  }
}

function _importRefContrib (doc, el) {
  let refContrib = {
    type: 'ref-contrib'
  }
  if (el.tagName === 'name') {
    refContrib.givenNames = getText(el, 'given-names')
    refContrib.name = getText(el, 'surname')
    // TODO: We may want to consider prefix postfix, and mix it into givenNames, or name properties
    // We don't want separate fields because this gets complex/annoying during editing
    // prefix: getText(el, 'prefix'),
    // suffix: getText(el, 'suffix'),
  } else if (el.tagName === 'collab') {
    refContrib.name = getText(el, 'named-content[content-type=name]')
  } else {
    console.warn(`${el.tagName} not supported inside <person-group>`)
    return null
  }
  return doc.create(refContrib)
}

function _exportElementCitation (node, exporter) {
  const $$ = exporter.$$
  const doc = node.getDocument()
  const type = node.type
  let el = $$('element-citation').attr('publication-type', INTERNAL_BIBR_TYPES_TO_JATS[type])
  if (node.assignee) {
    el.append(
      $$('collab').attr('collab-type', 'assignee').append(
        $$('named-content').attr({ 'content-type': 'name' }).text(node.assignee)
      )
    )
  }
  el.append(_createTextElement($$, node.confName, 'conf-name'))
  el.append(_createTextElement($$, node.confLoc, 'conf-loc'))
  el.append(_createTextElement($$, node.day, 'day'))
  el.append(_createTextElement($$, node.edition, 'edition'))
  el.append(_createTextElement($$, node.elocationId, 'elocation-id'))
  el.append(_createTextElement($$, node.fpage, 'fpage'))
  el.append(_createTextElement($$, node.issue, 'issue'))
  el.append(_createTextElement($$, node.lpage, 'lpage'))
  el.append(_createTextElement($$, node.month, 'month'))
  el.append(_createTextElement($$, node.pageCount, 'page-count'))
  el.append(_createTextElement($$, node.pageRange, 'page-range'))
  el.append(_createTextElement($$, node.partTitle, 'part-title'))
  el.append(_createTextElement($$, node.patentNumber, 'patent', { 'country': node.patentCountry }))
  el.append(_createMultipleTextElements($$, node.publisherLoc, 'publisher-loc'))
  el.append(_createMultipleTextElements($$, node.publisherName, 'publisher-name'))
  el.append(_createTextElement($$, node.uri, 'uri'))
  el.append(_createTextElement($$, node.version, 'version'))
  el.append(_createTextElement($$, node.volume, 'volume'))
  el.append(_createTextElement($$, node.year, 'year'))
  // identifiers
  el.append(_createTextElement($$, node.accessionId, 'pub-id', {'pub-id-type': 'accession'}))
  el.append(_createTextElement($$, node.arkId, 'pub-id', {'pub-id-type': 'ark'}))
  el.append(_createTextElement($$, node.archiveId, 'pub-id', {'pub-id-type': 'archive'}))
  el.append(_createTextElement($$, node.isbn, 'pub-id', {'pub-id-type': 'isbn'}))
  el.append(_createTextElement($$, node.doi, 'pub-id', {'pub-id-type': 'doi'}))
  el.append(_createTextElement($$, node.pmid, 'pub-id', {'pub-id-type': 'pmid'}))
  // creators
  el.append(_exportPersonGroup($$, doc, node.authors, 'author'))
  el.append(_exportPersonGroup($$, doc, node.editors, 'editor'))
  el.append(_exportPersonGroup($$, doc, node.inventors, 'inventor'))
  el.append(_exportPersonGroup($$, doc, node.sponsors, 'sponsor'))

  if (type === 'book' || type === 'report' || type === 'software') {
    el.append(_createTextElement($$, node.title, 'source'))
  } else {
    el.append(_createTextElement($$, node.containerTitle, 'source'))
    if (type === 'chapter') {
      el.append(_createHTMLElement($$, node.title, 'chapter-title'))
    } else if (type === 'data') {
      el.append(_createHTMLElement($$, node.title, 'data-title'))
    } else {
      el.append(_createHTMLElement($$, node.title, 'article-title'))
    }
  }
  return el
}

function _exportPersonGroup ($$, doc, contribIds, personGroupType) {
  if (contribIds && contribIds.length > 0) {
    let el = $$('person-group').attr('person-group-type', personGroupType)
    contribIds.forEach(id => {
      let refContribNode = doc.get(id)
      el.append(
        _exportRefContrib($$, refContribNode)
      )
    })
    return el
  }
}

function _exportRefContrib ($$, refContrib) {
  let el
  if (refContrib.givenNames) {
    el = $$('name')
    el.append(_createTextElement($$, refContrib.name, 'surname'))
    el.append(_createTextElement($$, refContrib.givenNames, 'given-names'))
    // el.append(_createTextElement($$, record.prefix, 'prefix'))
    // el.append(_createTextElement($$, record.suffix, 'suffix'))
  } else if (refContrib.name) {
    el = $$('collab')
    el.append(_createTextElement($$, refContrib.name, 'named-content', { 'content-type': 'name' }))
  } else {
    console.warn('No content found for refContrib node')
  }
  return el
}

function _createTextElement ($$, text, tagName, attrs) {
  if (text) {
    return $$(tagName).append(text).attr(attrs)
  }
}

function _createMultipleTextElements ($$, text, tagName, attrs) {
  if (text) {
    const textItems = text.split(';')
    return textItems.map(ti => {
      return $$(tagName).append(ti.trim()).attr(attrs)
    })
  }
}

function _createHTMLElement ($$, html, tagName, attrs) {
  if (html) {
    return $$(tagName).html(html).attr(attrs)
  }
}
<commit_msg>Adapt ElementCitationConverter to import/export rich text for title properties.<commit_after>import { JATS_BIBR_TYPES_TO_INTERNAL, INTERNAL_BIBR_TYPES_TO_JATS } from '../../ArticleConstants'
import { getText, getSeparatedText, getHTML, getAttr } from '../util/domHelpers'

export default class ElementCitationConverter {
  // Note: this will create different types according to the attributes in the JATS element
  get type () { return 'bibr' }

  matchElement (el) {
    return el.is('ref')
  }

  import (el, node, importer) {
    const doc = importer.state.doc
    let elementCitation = el.find('element-citation')
    if (!elementCitation) {
      throw new Error('<element-citation> is required')
    }
    _importElementCitation(elementCitation, node, doc, importer)
  }

  export (node, el, exporter) {
    el.tagName = 'ref'
    el.append(
      _exportElementCitation(node, exporter)
    )
    return el
  }
}

function _importElementCitation (el, node, doc, importer) {
  const type = el.attr('publication-type')
  node.type = JATS_BIBR_TYPES_TO_INTERNAL[type]

  Object.assign(node, {
    assignee: getText(el, 'collab[collab-type=assignee] > named-content'),
    confName: getText(el, 'conf-name'),
    confLoc: getText(el, 'conf-loc'),
    day: getText(el, 'day'),
    edition: getText(el, 'edition'),
    elocationId: getText(el, 'elocation-id'),
    fpage: getText(el, 'fpage'),
    issue: getText(el, 'issue'),
    lpage: getText(el, 'lpage'),
    month: getText(el, 'month'),
    pageCount: getText(el, 'page-count'),
    pageRange: getText(el, 'page-range'),
    partTitle: getText(el, 'part-title'),
    patentCountry: getAttr(el, 'patent', 'country'),
    patentNumber: getText(el, 'patent'),
    publisherLoc: getSeparatedText(el, 'publisher-loc'),
    publisherName: getSeparatedText(el, 'publisher-name'),
    series: getText(el, 'series'),
    uri: getText(el, 'uri'),
    version: getText(el, 'version'),
    volume: getText(el, 'volume'),
    year: getText(el, 'year'),
    // identifiers
    accessionId: getText(el, 'pub-id[pub-id-type=accession]'),
    archiveId: getText(el, 'pub-id[pub-id-type=archive]'),
    arkId: getText(el, 'pub-id[pub-id-type=ark]'),
    isbn: getText(el, 'pub-id[pub-id-type=isbn]'),
    doi: getText(el, 'pub-id[pub-id-type=doi]'),
    pmid: getText(el, 'pub-id[pub-id-type=pmid]')
  })

  if (type === 'book' || type === 'report' || type === 'software') {
    node.title = getAnnotatedText(importer, el, 'source', [node.id, 'title'])
  } else {
    node.containerTitle = getText(el, 'source')
    if (type === 'chapter') {
      node.title = getAnnotatedText(importer, el, 'chapter-title', [node.id, 'title'])
    } else if (type === 'data') {
      node.title = getAnnotatedText(importer, el, 'data-title', [node.id, 'title'])
    } else {
      node.title = getAnnotatedText(importer, el, 'article-title', [node.id, 'title'])
    }
  }

  node.authors = _importPersonGroup(el, doc, 'author')
  node.editors = _importPersonGroup(el, doc, 'editor')
  node.inventors = _importPersonGroup(el, doc, 'inventor')
  node.sponsors = _importPersonGroup(el, doc, 'sponsor')
  node.translators = _importPersonGroup(el, doc, 'translator')
}

function getAnnotatedText (importer, rootEl, selector, path) {
  let el = rootEl.find(selector)
  if (el) {
    return importer.annotatedText(el, path)
  } else {
    return ''
  }
}

function _importPersonGroup (el, doc, type) {
  let groupEl = el.find(`person-group[person-group-type=${type}]`)
  if (groupEl) {
    return groupEl.children.reduce((ids, childEl) => {
      let refContrib = _importRefContrib(doc, childEl)
      if (refContrib) ids.push(refContrib.id)
      return ids
    }, [])
  } else {
    return []
  }
}

function _importRefContrib (doc, el) {
  let refContrib = {
    type: 'ref-contrib'
  }
  if (el.tagName === 'name') {
    refContrib.givenNames = getText(el, 'given-names')
    refContrib.name = getText(el, 'surname')
    // TODO: We may want to consider prefix postfix, and mix it into givenNames, or name properties
    // We don't want separate fields because this gets complex/annoying during editing
    // prefix: getText(el, 'prefix'),
    // suffix: getText(el, 'suffix'),
  } else if (el.tagName === 'collab') {
    refContrib.name = getText(el, 'named-content[content-type=name]')
  } else {
    console.warn(`${el.tagName} not supported inside <person-group>`)
    return null
  }
  return doc.create(refContrib)
}

function _exportElementCitation (node, exporter) {
  const $$ = exporter.$$
  const doc = node.getDocument()
  const type = node.type
  let el = $$('element-citation').attr('publication-type', INTERNAL_BIBR_TYPES_TO_JATS[type])
  if (node.assignee) {
    el.append(
      $$('collab').attr('collab-type', 'assignee').append(
        $$('named-content').attr({ 'content-type': 'name' }).text(node.assignee)
      )
    )
  }
  el.append(_createTextElement($$, node.confName, 'conf-name'))
  el.append(_createTextElement($$, node.confLoc, 'conf-loc'))
  el.append(_createTextElement($$, node.day, 'day'))
  el.append(_createTextElement($$, node.edition, 'edition'))
  el.append(_createTextElement($$, node.elocationId, 'elocation-id'))
  el.append(_createTextElement($$, node.fpage, 'fpage'))
  el.append(_createTextElement($$, node.issue, 'issue'))
  el.append(_createTextElement($$, node.lpage, 'lpage'))
  el.append(_createTextElement($$, node.month, 'month'))
  el.append(_createTextElement($$, node.pageCount, 'page-count'))
  el.append(_createTextElement($$, node.pageRange, 'page-range'))
  el.append(_createTextElement($$, node.partTitle, 'part-title'))
  el.append(_createTextElement($$, node.patentNumber, 'patent', { 'country': node.patentCountry }))
  el.append(_createMultipleTextElements($$, node.publisherLoc, 'publisher-loc'))
  el.append(_createMultipleTextElements($$, node.publisherName, 'publisher-name'))
  el.append(_createTextElement($$, node.uri, 'uri'))
  el.append(_createTextElement($$, node.version, 'version'))
  el.append(_createTextElement($$, node.volume, 'volume'))
  el.append(_createTextElement($$, node.year, 'year'))
  // identifiers
  el.append(_createTextElement($$, node.accessionId, 'pub-id', {'pub-id-type': 'accession'}))
  el.append(_createTextElement($$, node.arkId, 'pub-id', {'pub-id-type': 'ark'}))
  el.append(_createTextElement($$, node.archiveId, 'pub-id', {'pub-id-type': 'archive'}))
  el.append(_createTextElement($$, node.isbn, 'pub-id', {'pub-id-type': 'isbn'}))
  el.append(_createTextElement($$, node.doi, 'pub-id', {'pub-id-type': 'doi'}))
  el.append(_createTextElement($$, node.pmid, 'pub-id', {'pub-id-type': 'pmid'}))
  // creators
  el.append(_exportPersonGroup($$, doc, node.authors, 'author'))
  el.append(_exportPersonGroup($$, doc, node.editors, 'editor'))
  el.append(_exportPersonGroup($$, doc, node.inventors, 'inventor'))
  el.append(_exportPersonGroup($$, doc, node.sponsors, 'sponsor'))

  if (type === 'book' || type === 'report' || type === 'software') {
    el.append(_exportAnnotatedText(exporter, [node.id, 'title'], 'source'))
  } else {
    el.append(_createTextElement($$, node.containerTitle, 'source'))
    if (type === 'chapter') {
      el.append(
        _exportAnnotatedText(exporter, [node.id, 'title'], 'chapter-title')
      )
    } else if (type === 'data') {
      el.append(
        _exportAnnotatedText(exporter, [node.id, 'title'], 'data-title')
      )
    } else {
      el.append(
        _exportAnnotatedText(exporter, [node.id, 'title'], 'article-title')
      )
    }
  }
  return el
}

function _exportPersonGroup ($$, doc, contribIds, personGroupType) {
  if (contribIds && contribIds.length > 0) {
    let el = $$('person-group').attr('person-group-type', personGroupType)
    contribIds.forEach(id => {
      let refContribNode = doc.get(id)
      el.append(
        _exportRefContrib($$, refContribNode)
      )
    })
    return el
  }
}

function _exportRefContrib ($$, refContrib) {
  let el
  if (refContrib.givenNames) {
    el = $$('name')
    el.append(_createTextElement($$, refContrib.name, 'surname'))
    el.append(_createTextElement($$, refContrib.givenNames, 'given-names'))
    // el.append(_createTextElement($$, record.prefix, 'prefix'))
    // el.append(_createTextElement($$, record.suffix, 'suffix'))
  } else if (refContrib.name) {
    el = $$('collab')
    el.append(_createTextElement($$, refContrib.name, 'named-content', { 'content-type': 'name' }))
  } else {
    console.warn('No content found for refContrib node')
  }
  return el
}

function _createTextElement ($$, text, tagName, attrs) {
  if (text) {
    return $$(tagName).append(text).attr(attrs)
  }
}

function _exportAnnotatedText (exporter, path, tagName, attrs) {
  const $$ = exporter.$$
  return $$(tagName).attr(attrs).append(
    exporter.annotatedText(path)
  )
}

function _createMultipleTextElements ($$, text, tagName, attrs) {
  if (text) {
    const textItems = text.split(';')
    return textItems.map(ti => {
      return $$(tagName).append(ti.trim()).attr(attrs)
    })
  }
}
<|endoftext|>


<commit_before>'use strict';

const AffiliationsList = require('../components/affiliation/affiliations.json');

/**
 * Method to return a list of designated classification approvers
 * with an affiliation given the affiliation ID
 * @param {string} id - Affiliation ID

 */
export function getAffiliationApprover(id) {
    let approvers = [];
    if (id.length) {
        AffiliationsList.forEach(affiliation => {
            if (affiliation.affiliation_id === id && affiliation.hasOwnProperty['approver']) {
                approvers = affiliation.approver;
            }
        });
    }
    return approvers;
}<commit_msg>:bug: Fixed bug in returning the approvers within an affiliation<commit_after>'use strict';

const AffiliationsList = require('../components/affiliation/affiliations.json');

/**
 * Method to return a list of designated classification approvers
 * with an affiliation given the affiliation ID
 * @param {string} id - Affiliation ID

 */
export function getAffiliationApprover(id) {
    let approvers = [];
    if (id.length) {
        AffiliationsList.forEach(affiliation => {
            if (affiliation.affiliation_id === id && affiliation.approver && affiliation.approver.length) {
                approvers = affiliation.approver;
            }
        });
    }
    return approvers;
}<|endoftext|>