<commit_before> function isStudyQuestionMode() {
    return studyQuestionManager != undefined;
}

function clearStudyQuestionMode() {
    $('#q-and-a-div').empty();
    $("#left-block-div").remove();
    $("#right-block-div").remove();
    studyQuestionManager = undefined;
}
function getStudyQuestionManager(questions, userId, treatmentId) {
    var sqm = {};
    sqm.renderer = getStudyQuestionRenderer();
    sqm.userId = userId;
    sqm.userIdHasBeenSet = false;
    sqm.treatmentId = treatmentId;

    sqm.questionMap = {};
    sqm.questionIds = [];

    sqm.windowRangeForStep = {};
    sqm.questionWasAnswered = false;
    sqm.activeRange = undefined;

    for (var i in questions){
        var question = questions[i];
        var step = question.getStep();
        var questionIndexForStep = question.getQuestionIdForStep();;
        var questionId = getQuestionId(step, questionIndexForStep);
        var answers = question.getAnswersList();
        var qu = {};
        qu.step = step;
        qu.questionIndexForStep = questionIndexForStep;
        qu.questionId = questionId;
        qu.questionText= question.getQuestion();;
        var allTypeInfo = question.getQuestionType();
        var typeParts = allTypeInfo.split(":");
        qu.questionType = typeParts[0];
        if (qu.questionType == "waitForClick"){
            qu.regionsToAllow = typeParts[1].split("_");
            qu.clickQuestionText = typeParts[2];
        }
        qu.answers = answers;
        sqm.questionIds.push(questionId);
        sqm.questionMap[questionId] = qu;
    }
    sqm.squim = getStudyQuestionIndexManager(sqm.questionIds);
    studyQuestionIndexManager = sqm.squim;
    sqm.windowRangeForStep = getRanges(sqm.squim.getDecisionPointSteps());

    sqm.isAtEndOfRange = function(step) {
        if (this.activeRange != undefined){
            var endOfRange = this.activeRange[1];
            // stop one prior to the true end to avoid showing the blank gameboard
            //if (step >= endOfRange) {
            if (step >= endOfRange - 1) {
                // if we are at end of game, don't stop two shy
                if (step == sessionIndexManager.getMaxIndex()- 1){
                    return false;
                }
                // otherwise, stop two shy to avoid blank gameboard
                return true;
            }
        }
        return false;
    }

    sqm.hasShownUserId = function() {
        return this.userIdHasBeenSet;
    }

    sqm.configureForCurrentStep = function() {
        var currentStep = sessionIndexManager.getCurrentIndex();
        if (!this.hasShownUserId()) {
            this.renderer.poseUserIdQuestion();
        }
        else if (this.squim.hasQuestionForStep(currentStep)) {
            this.poseCurrentQuestion();
        }
    }

    sqm.poseFirstQuestion = function() {
        var step = this.squim.getCurrentStep();
        var args = ["" + step];
        var userCommand = new proto.scaii.common.UserCommand;
        userCommand.setCommandType(proto.scaii.common.UserCommand.UserCommandType.JUMP_TO_STEP);
        userCommand.setArgsList(args);
        stageUserCommand(userCommand);
        controlsManager.userJumped();
        this.poseCurrentQuestion();
    }

    sqm.poseNextQuestion = function() {
        var priorStep = this.squim.getCurrentStep();
        this.squim.next();
        var newStep = this.squim.getCurrentStep();
        if (priorStep != newStep && !this.squim.isCurrentQuestionSummary()) {
            // move to next step
            var args = ["" + newStep];
            var userCommand = new proto.scaii.common.UserCommand;
            userCommand.setCommandType(proto.scaii.common.UserCommand.UserCommandType.JUMP_TO_STEP);
            userCommand.setArgsList(args);
            stageUserCommand(userCommand);
            controlsManager.userJumped();
        }
        this.poseCurrentQuestion();
    }

    // sqm.jumpBackToCurrentDecisionPoint = function() {
    //     var targetStep = this.steps[this.currentStepIndex];
    //     var args = ["" + nextStep];
    //     var userCommand = new proto.scaii.common.UserCommand;
    //     userCommand.setCommandType(proto.scaii.common.UserCommand.UserCommandType.JUMP_TO_STEP);
    //     userCommand.setArgsList(args);
    //     stageUserCommand(userCommand);
    //     controlsManager.userJumped();
    // }

    sqm.poseCurrentQuestion = function() {
        var qid = this.squim.getCurrentQuestionId();
        stateMonitor.setUserAction("showQuestion:"+ qid);
        stateMonitor.setQuestionId(qid);
        var qu = this.questionMap[qid];
        this.renderer.poseQuestion(qu, this.squim.getCurrentDecisionPointNumber(), this.squim.getCurrentStep());
    }

    sqm.clearTimelineBlocks = function() {
        $("#left-block-div").remove();
        $("#right-block-div").remove();
    }

    sqm.blockClicksOutsideRange = function() {
        var step = this.squim.getCurrentStep();
        if (step == undefined){
            return;
        }
        var rangePair = this.windowRangeForStep[step];
        this.activeRange = rangePair;
        var maxIndex = sessionIndexManager.getMaxIndex();
        var widthOfTimeline = expl_ctrl_canvas.width - 2*timelineMargin;

        // get offset of explanation-control-panel relative to document
        var ecpOffset = $("#explanation-control-panel").offset();
        var x1 = ecpOffset.left;
        // calculate left window edge position
        var leftValueOnTimeline = Math.floor((rangePair[0] / maxIndex ) * 100);
        var x2 = ecpOffset.left + timelineMargin + (leftValueOnTimeline / 100) * widthOfTimeline;
        // shift x2 to the left to fully expose the current DecisionPoint;
        var currentIndex = sessionIndexManager.getCurrentIndex();
        if (currentIndex == rangePair[0]) {
            x2 = x2 - explanationPointBigDiamondHalfWidth;
        }
        else {
            x2 = x2 - explanationPointSmallDiamondHalfWidth;
        }

        // calculate right window edge position
        var rightValueOnTimeline = Math.floor((rangePair[1] / maxIndex ) * 100);
        var x3 = ecpOffset.left + timelineMargin + (rightValueOnTimeline / 100) * widthOfTimeline;
        // shift x3 to the left to fully cover the next DecisionPoint
        if (!this.squim.isAtLastDecisionPoint()) {
            x3 = x3 - explanationPointSmallDiamondHalfWidth;
        }
        var x4 = expl_ctrl_canvas.width;

        var y = ecpOffset.top;
        var width1 = x2 - x1;
        var width2 = x4 - x3;
        var height = $("#explanation-control-panel").height();
        // make blocking div from 0 -> rightXofLeftBlock
        var gradientBars = "repeating-linear-gradient(135deg,rgba(100, 100, 100, 0.1),rgba(100, 100, 100, 0.3) 20px,rgba(100, 100, 100, 0.6) 20px,rgba(100, 100, 100, 0.7) 20px)";
        var leftBlockDiv = document.createElement("DIV");
        leftBlockDiv.setAttribute("id", "left-block-div");
        leftBlockDiv.setAttribute("style", "position:absolute;left:" + x1 + "px;top:" + y + "px;z-index:" + zIndexMap["clickBlockerRectangle"] + ";background:" + gradientBars + ";width:" + width1 + "px;height:" + height + "px;");
        //$("body").append(leftBlockDiv);

        // make blocking div from leftXofRightBlock -> expl_ctrl_canvas.width
        var rightBlockDiv = document.createElement("DIV");
        rightBlockDiv.setAttribute("id", "right-block-div");
        rightBlockDiv.setAttribute("style", "position:absolute;left:" + x3 + "px;top:" + y + "px;z-index:" + zIndexMap["clickBlockerRectangle"] + ";background:" + gradientBars + ";width:" + width2 + "px;height:" + height + "px;");
        rightBlockDiv.onclick = function(e) {
            if (isStudyQuestionMode()){
                targetClickHandler(e,"clickTimelineBlocker:NA");
                regionClickHandlerGameArea(e);
                userActionMonitor.globalClick(e.clientX, e.clientY);
            }
        }

        $("body").append(rightBlockDiv);
    }
    return sqm;
}

function getRanges(steps) {
    var stepRangePairs = {};
    for (var i = 0; i < steps.length; i++) {
        if (i == steps.length - 1) {
            // looking at the final entry - pair this one with the max index
            var range_pair = [ Number(steps[i]), Number(sessionIndexManager.getMaxIndex()) ];
            stepRangePairs[steps[i]] = range_pair;
        }
        else {
            // prior to last one, we make a pair with the step prior to the next question's step
            var range_pair = [ Number(steps[i]), Number(steps[i+1]) - 1 ];
            stepRangePairs[steps[i]] = range_pair;
        }
    }
    console.log(stepRangePairs)
    return stepRangePairs;
}

function acceptUserId() {
    var userId = studyQuestionManager.userId;
    if (userId == undefined || userId == "") {
        alert('No userId specified.  Please specify a userId and then click "Next".');
    }
    else {
        $("#user-id-div").remove();
        studyQuestionManager.userIdHasBeenSet = true;
        studyQuestionManager.poseFirstQuestion();
    }

}
function acceptAnswer(e) {
    var renderer = studyQuestionManager.renderer;
    renderer.removeMissingClickInfoMessage();
    // block if no answer specified
    if (renderer.controlsWaitingForClick.length != 0) {
        if (renderer.clickInfoFromUserActionMonitor == undefined) {
            renderer.expressMissingClickInfoMessage();
            return;
        }
    }
    var answer = renderer.getCurrentAnswer();

    if (answer == undefined || answer == '') {
        alert('No answer chosen for the current question.  Please specify an answer and then click "Next Question".');
        return;
    }
    // gather answer, send to backend
    var currentStep = studyQuestionIndexManager.getCurrentStep();
    var questionId = studyQuestionIndexManager.getCurrentQuestionId();
    var currentQuestionIndexAtStep = getQuestionIndexFromQuestionId(questionId);
    var clickInfo = renderer.collectClickInfo();
    userActionMonitor.clickListener = undefined;

    if (clickInfo == undefined){
        clickInfo = "NA";
    }
    var followupAnswer;
    if (!(currentStep == 'summary')){
        followupAnswer = renderer.getCurrentFollowupAnswer();
    }
    targetClickHandler(e,"answerQuestion:"+ currentStep + "." + currentQuestionIndexAtStep + "_" + answer + "_" + followupAnswer + "_(" + clickInfo + ")");

    renderer.forgetQuestion();
    if (studyQuestionIndexManager.hasMoreQuestionsAtThisStep()) {
        studyQuestionManager.poseNextQuestion();
    }
    else {
        if (studyQuestionIndexManager.hasMoreQuestions()){
            renderer.renderCueAndArrowToPlayButton();
        }
        studyQuestionManager.questionWasAnswered = true;
        if (studyQuestionIndexManager.hasMoreQuestions()){
            // wait for play button to take us to next Decision Point
            controlsManager.enablePauseResume();
        }
        else {
            renderer.poseThankYouScreen();
        }
    }
}

// function chooseNextQuestionAfterStep(step) {
//     // clear current question
//     $('#q-and-a-div').empty();

//     if (step == 'summary'){
//         renderer.poseThankYouScreen();
//     }
//     else {
//         // pose next question
//         studyQuestionManager.poseNextQuestion();
//     }
// }
<commit_msg>don't render blocks if jump back from summary question<commit_after> function isStudyQuestionMode() {
    return studyQuestionManager != undefined;
}

function clearStudyQuestionMode() {
    $('#q-and-a-div').empty();
    $("#left-block-div").remove();
    $("#right-block-div").remove();
    studyQuestionManager = undefined;
}
function getStudyQuestionManager(questions, userId, treatmentId) {
    var sqm = {};
    sqm.renderer = getStudyQuestionRenderer();
    sqm.userId = userId;
    sqm.userIdHasBeenSet = false;
    sqm.treatmentId = treatmentId;

    sqm.questionMap = {};
    sqm.questionIds = [];

    sqm.windowRangeForStep = {};
    sqm.questionWasAnswered = false;
    sqm.activeRange = undefined;

    for (var i in questions){
        var question = questions[i];
        var step = question.getStep();
        var questionIndexForStep = question.getQuestionIdForStep();;
        var questionId = getQuestionId(step, questionIndexForStep);
        var answers = question.getAnswersList();
        var qu = {};
        qu.step = step;
        qu.questionIndexForStep = questionIndexForStep;
        qu.questionId = questionId;
        qu.questionText= question.getQuestion();;
        var allTypeInfo = question.getQuestionType();
        var typeParts = allTypeInfo.split(":");
        qu.questionType = typeParts[0];
        if (qu.questionType == "waitForClick"){
            qu.regionsToAllow = typeParts[1].split("_");
            qu.clickQuestionText = typeParts[2];
        }
        qu.answers = answers;
        sqm.questionIds.push(questionId);
        sqm.questionMap[questionId] = qu;
    }
    sqm.squim = getStudyQuestionIndexManager(sqm.questionIds);
    studyQuestionIndexManager = sqm.squim;
    sqm.windowRangeForStep = getRanges(sqm.squim.getDecisionPointSteps());

    sqm.isAtEndOfRange = function(step) {
        if (this.activeRange != undefined){
            var endOfRange = this.activeRange[1];
            // stop one prior to the true end to avoid showing the blank gameboard
            //if (step >= endOfRange) {
            if (step >= endOfRange - 1) {
                // if we are at end of game, don't stop two shy
                if (step == sessionIndexManager.getMaxIndex()- 1){
                    return false;
                }
                // otherwise, stop two shy to avoid blank gameboard
                return true;
            }
        }
        return false;
    }

    sqm.hasShownUserId = function() {
        return this.userIdHasBeenSet;
    }

    sqm.configureForCurrentStep = function() {
        var currentStep = sessionIndexManager.getCurrentIndex();
        if (!this.hasShownUserId()) {
            this.renderer.poseUserIdQuestion();
        }
        else if (this.squim.hasQuestionForStep(currentStep)) {
            this.poseCurrentQuestion();
        }
    }

    sqm.poseFirstQuestion = function() {
        var step = this.squim.getCurrentStep();
        var args = ["" + step];
        var userCommand = new proto.scaii.common.UserCommand;
        userCommand.setCommandType(proto.scaii.common.UserCommand.UserCommandType.JUMP_TO_STEP);
        userCommand.setArgsList(args);
        stageUserCommand(userCommand);
        controlsManager.userJumped();
        this.poseCurrentQuestion();
    }

    sqm.poseNextQuestion = function() {
        var priorStep = this.squim.getCurrentStep();
        this.squim.next();
        var newStep = this.squim.getCurrentStep();
        if (priorStep != newStep && !this.squim.isCurrentQuestionSummary()) {
            // move to next step
            var args = ["" + newStep];
            var userCommand = new proto.scaii.common.UserCommand;
            userCommand.setCommandType(proto.scaii.common.UserCommand.UserCommandType.JUMP_TO_STEP);
            userCommand.setArgsList(args);
            stageUserCommand(userCommand);
            controlsManager.userJumped();
        }
        this.poseCurrentQuestion();
    }

    // sqm.jumpBackToCurrentDecisionPoint = function() {
    //     var targetStep = this.steps[this.currentStepIndex];
    //     var args = ["" + nextStep];
    //     var userCommand = new proto.scaii.common.UserCommand;
    //     userCommand.setCommandType(proto.scaii.common.UserCommand.UserCommandType.JUMP_TO_STEP);
    //     userCommand.setArgsList(args);
    //     stageUserCommand(userCommand);
    //     controlsManager.userJumped();
    // }

    sqm.poseCurrentQuestion = function() {
        var qid = this.squim.getCurrentQuestionId();
        stateMonitor.setUserAction("showQuestion:"+ qid);
        stateMonitor.setQuestionId(qid);
        var qu = this.questionMap[qid];
        this.renderer.poseQuestion(qu, this.squim.getCurrentDecisionPointNumber(), this.squim.getCurrentStep());
    }

    sqm.clearTimelineBlocks = function() {
        $("#left-block-div").remove();
        $("#right-block-div").remove();
    }

    sqm.blockClicksOutsideRange = function() {
        var step = this.squim.getCurrentStep();
        if (step == undefined || step == 'summary'){
            return;
        }
        var rangePair = this.windowRangeForStep[step];
        this.activeRange = rangePair;
        var maxIndex = sessionIndexManager.getMaxIndex();
        var widthOfTimeline = expl_ctrl_canvas.width - 2*timelineMargin;

        // get offset of explanation-control-panel relative to document
        var ecpOffset = $("#explanation-control-panel").offset();
        var x1 = ecpOffset.left;
        // calculate left window edge position
        var leftValueOnTimeline = Math.floor((rangePair[0] / maxIndex ) * 100);
        var x2 = ecpOffset.left + timelineMargin + (leftValueOnTimeline / 100) * widthOfTimeline;
        // shift x2 to the left to fully expose the current DecisionPoint;
        var currentIndex = sessionIndexManager.getCurrentIndex();
        if (currentIndex == rangePair[0]) {
            x2 = x2 - explanationPointBigDiamondHalfWidth;
        }
        else {
            x2 = x2 - explanationPointSmallDiamondHalfWidth;
        }

        // calculate right window edge position
        var rightValueOnTimeline = Math.floor((rangePair[1] / maxIndex ) * 100);
        var x3 = ecpOffset.left + timelineMargin + (rightValueOnTimeline / 100) * widthOfTimeline;
        // shift x3 to the left to fully cover the next DecisionPoint
        if (!this.squim.isAtLastDecisionPoint()) {
            x3 = x3 - explanationPointSmallDiamondHalfWidth;
        }
        var x4 = expl_ctrl_canvas.width;

        var y = ecpOffset.top;
        var width1 = x2 - x1;
        var width2 = x4 - x3;
        var height = $("#explanation-control-panel").height();
        // make blocking div from 0 -> rightXofLeftBlock
        var gradientBars = "repeating-linear-gradient(135deg,rgba(100, 100, 100, 0.1),rgba(100, 100, 100, 0.3) 20px,rgba(100, 100, 100, 0.6) 20px,rgba(100, 100, 100, 0.7) 20px)";
        var leftBlockDiv = document.createElement("DIV");
        leftBlockDiv.setAttribute("id", "left-block-div");
        leftBlockDiv.setAttribute("style", "position:absolute;left:" + x1 + "px;top:" + y + "px;z-index:" + zIndexMap["clickBlockerRectangle"] + ";background:" + gradientBars + ";width:" + width1 + "px;height:" + height + "px;");
        //$("body").append(leftBlockDiv);

        // make blocking div from leftXofRightBlock -> expl_ctrl_canvas.width
        var rightBlockDiv = document.createElement("DIV");
        rightBlockDiv.setAttribute("id", "right-block-div");
        rightBlockDiv.setAttribute("style", "position:absolute;left:" + x3 + "px;top:" + y + "px;z-index:" + zIndexMap["clickBlockerRectangle"] + ";background:" + gradientBars + ";width:" + width2 + "px;height:" + height + "px;");
        rightBlockDiv.onclick = function(e) {
            if (isStudyQuestionMode()){
                targetClickHandler(e,"clickTimelineBlocker:NA");
                regionClickHandlerGameArea(e);
                userActionMonitor.globalClick(e.clientX, e.clientY);
            }
        }

        $("body").append(rightBlockDiv);
    }
    return sqm;
}

function getRanges(steps) {
    var stepRangePairs = {};
    for (var i = 0; i < steps.length; i++) {
        if (i == steps.length - 1) {
            // looking at the final entry - pair this one with the max index
            var range_pair = [ Number(steps[i]), Number(sessionIndexManager.getMaxIndex()) ];
            stepRangePairs[steps[i]] = range_pair;
        }
        else {
            // prior to last one, we make a pair with the step prior to the next question's step
            var range_pair = [ Number(steps[i]), Number(steps[i+1]) - 1 ];
            stepRangePairs[steps[i]] = range_pair;
        }
    }
    console.log(stepRangePairs)
    return stepRangePairs;
}

function acceptUserId() {
    var userId = studyQuestionManager.userId;
    if (userId == undefined || userId == "") {
        alert('No userId specified.  Please specify a userId and then click "Next".');
    }
    else {
        $("#user-id-div").remove();
        studyQuestionManager.userIdHasBeenSet = true;
        studyQuestionManager.poseFirstQuestion();
    }

}
function acceptAnswer(e) {
    var renderer = studyQuestionManager.renderer;
    renderer.removeMissingClickInfoMessage();
    // block if no answer specified
    if (renderer.controlsWaitingForClick.length != 0) {
        if (renderer.clickInfoFromUserActionMonitor == undefined) {
            renderer.expressMissingClickInfoMessage();
            return;
        }
    }
    var answer = renderer.getCurrentAnswer();

    if (answer == undefined || answer == '') {
        alert('No answer chosen for the current question.  Please specify an answer and then click "Next Question".');
        return;
    }
    // gather answer, send to backend
    var currentStep = studyQuestionIndexManager.getCurrentStep();
    var questionId = studyQuestionIndexManager.getCurrentQuestionId();
    var currentQuestionIndexAtStep = getQuestionIndexFromQuestionId(questionId);
    var clickInfo = renderer.collectClickInfo();
    userActionMonitor.clickListener = undefined;

    if (clickInfo == undefined){
        clickInfo = "NA";
    }
    var followupAnswer;
    if (!(currentStep == 'summary')){
        followupAnswer = renderer.getCurrentFollowupAnswer();
    }
    targetClickHandler(e,"answerQuestion:"+ currentStep + "." + currentQuestionIndexAtStep + "_" + answer + "_" + followupAnswer + "_(" + clickInfo + ")");

    renderer.forgetQuestion();
    if (studyQuestionIndexManager.hasMoreQuestionsAtThisStep()) {
        studyQuestionManager.poseNextQuestion();
    }
    else {
        if (studyQuestionIndexManager.hasMoreQuestions()){
            renderer.renderCueAndArrowToPlayButton();
        }
        studyQuestionManager.questionWasAnswered = true;
        if (studyQuestionIndexManager.hasMoreQuestions()){
            // wait for play button to take us to next Decision Point
            controlsManager.enablePauseResume();
        }
        else {
            renderer.poseThankYouScreen();
        }
    }
}

// function chooseNextQuestionAfterStep(step) {
//     // clear current question
//     $('#q-and-a-div').empty();

//     if (step == 'summary'){
//         renderer.poseThankYouScreen();
//     }
//     else {
//         // pose next question
//         studyQuestionManager.poseNextQuestion();
//     }
// }
<|endoftext|>


<commit_before>goog.provide('ol.format.WMTSCapabilities');

goog.require('goog.asserts');
goog.require('goog.dom.NodeType');
goog.require('goog.object');
goog.require('goog.string');
goog.require('ol.extent');
goog.require('ol.format.OWS');
goog.require('ol.format.XLink');
goog.require('ol.format.XML');
goog.require('ol.format.XSD');
goog.require('ol.xml');

/**
 * @classdesc
 * Format for reading WMTS capabilities data.
 *
 * @constructor
 * @extends {ol.format.XML}
 * @api
 */
ol.format.WMTSCapabilities = function() {
  goog.base(this);

  /**
   * @type {ol.format.OWS}
   * @private
   */
  this.owsParser_ = new ol.format.OWS();
};
goog.inherits(ol.format.WMTSCapabilities, ol.format.XML);

/**
 * Read a WMTS capabilities document.
 *
 * @function
 * @param {Document|Node|string} source The XML source.
 * @return {Object} An object representing the WMTS capabilities.
 * @api
 */
ol.format.WMTSCapabilities.prototype.read;

/**
 * @param {Document} doc Document.
 * @return {Object} WMTS Capability object.
 */
ol.format.WMTSCapabilities.prototype.readFromDocument = function(doc) {
  goog.asserts.assert(doc.nodeType == goog.dom.NodeType.DOCUMENT,
      'doc.nodeType should be DOCUMENT');
  for (var n = doc.firstChild; !goog.isNull(n); n = n.nextSibling) {
    if (n.nodeType == goog.dom.NodeType.ELEMENT) {
      return this.readFromNode(n);
    }
  }
  return null;
};

/**
 * @param {Node} node Node.
 * @return {Object} WMTS Capability object.
 */
ol.format.WMTSCapabilities.prototype.readFromNode = function(node) {
  goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
      'node.nodeType should be ELEMENT');
  goog.asserts.assert(node.localName == 'Capabilities',
      'localName should be Capabilities');
  this.version = goog.string.trim(node.getAttribute('version'));
  goog.asserts.assertString(this.version, 'this.version should be a string');
  var WMTSCapabilityObject = this.owsParser_.readFromNode(node);
  if (!goog.isDef(WMTSCapabilityObject)) {
    return null;
  }
  goog.object.set(WMTSCapabilityObject, 'version', this.version);
  WMTSCapabilityObject = ol.xml.pushParseAndPop(WMTSCapabilityObject,
      ol.format.WMTSCapabilities.PARSERS_, node, []);
  return goog.isDef(WMTSCapabilityObject) ? WMTSCapabilityObject : null;
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Attribution object.
 */
ol.format.WMTSCapabilities.readContents_ = function(node, objectStack) {
  goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
      'node.nodeType should be ELEMENT');
  goog.asserts.assert(node.localName == 'Contents',
      'localName should be Contents');

  return ol.xml.pushParseAndPop({},
      ol.format.WMTSCapabilities.CONTENTS_PARSERS_, node, objectStack);
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Layers object.
 */
ol.format.WMTSCapabilities.readLayer_ = function(node, objectStack) {
  goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
      'node.nodeType should be ELEMENT');
  goog.asserts.assert(node.localName == 'Layer', 'localName should be Layer');
  return ol.xml.pushParseAndPop({},
      ol.format.WMTSCapabilities.LAYER_PARSERS_, node, objectStack);
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Tile Matrix Set object.
 */
ol.format.WMTSCapabilities.readTileMatrixSet_ = function(node, objectStack) {
  return ol.xml.pushParseAndPop({},
      ol.format.WMTSCapabilities.TMS_PARSERS_, node, objectStack);
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Style object.
 */
ol.format.WMTSCapabilities.readStyle_ = function(node, objectStack) {
  var style = ol.xml.pushParseAndPop({},
      ol.format.WMTSCapabilities.STYLE_PARSERS_, node, objectStack);
  if (!goog.isDef(style)) {
    return undefined;
  }
  var isDefault = node.getAttribute('isDefault') === 'true';
  style['isDefault'] = isDefault;
  return style;

};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Tile Matrix Set Link object.
 */
ol.format.WMTSCapabilities.readTileMatrixSetLink_ = function(node,
    objectStack) {
  return ol.xml.pushParseAndPop({},
      ol.format.WMTSCapabilities.TMS_LINKS_PARSERS_, node, objectStack);
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Resource URL object.
 */
ol.format.WMTSCapabilities.readResourceUrl_ = function(node, objectStack) {
  var format = node.getAttribute('format');
  var template = node.getAttribute('template');
  var resourceType = node.getAttribute('resourceType');
  var resource = {};
  if (goog.isDef(format)) {
    resource['format'] = format;
  }
  if (goog.isDef(template)) {
    resource['template'] = template;
  }
  if (goog.isDef(resourceType)) {
    resource['resourceType'] = resourceType;
  }
  return resource;
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} WGS84 BBox object.
 */
ol.format.WMTSCapabilities.readWgs84BoundingBox_ = function(node, objectStack) {
  var coordinates = ol.xml.pushParseAndPop([],
      ol.format.WMTSCapabilities.WGS84_BBOX_READERS_, node, objectStack);
  if (coordinates.length != 2) {
    return undefined;
  }
  return ol.extent.boundingExtent(coordinates);
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Legend object.
 */
ol.format.WMTSCapabilities.readLegendUrl_ = function(node, objectStack) {
  var legend = {};
  legend['format'] = node.getAttribute('format');
  legend['href'] = ol.format.XLink.readHref(node);
  return legend;
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Coordinates object.
 */
ol.format.WMTSCapabilities.readCoordinates_ = function(node, objectStack) {
  var coordinates = ol.format.XSD.readString(node).split(' ');
  if (!goog.isDef(coordinates) || coordinates.length != 2) {
    return undefined;
  }
  var x = +coordinates[0];
  var y = +coordinates[1];
  if (isNaN(x) || isNaN(y)) {
    return undefined;
  }
  return [x, y];
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} TileMatrix object.
 */
ol.format.WMTSCapabilities.readTileMatrix_ = function(node, objectStack) {
  return ol.xml.pushParseAndPop({},
      ol.format.WMTSCapabilities.TM_PARSERS_, node, objectStack);
};

/**
 * @const
 * @private
 * @type {Array.<string>}
 */
ol.format.WMTSCapabilities.NAMESPACE_URIS_ = [
  null,
  'http://www.opengis.net/wmts/1.0'
];

/**
 * @const
 * @private
 * @type {Array.<string>}
 */
ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_ = [
  null,
  'http://www.opengis.net/ows/1.1'
];

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.PARSERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
      'Contents': ol.xml.makeObjectPropertySetter(
          ol.format.WMTSCapabilities.readContents_)
    });

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.CONTENTS_PARSERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
      'Layer': ol.xml.makeObjectPropertyPusher(
          ol.format.WMTSCapabilities.readLayer_),
      'TileMatrixSet': ol.xml.makeObjectPropertyPusher(
          ol.format.WMTSCapabilities.readTileMatrixSet_)
    });

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.LAYER_PARSERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
      'Style': ol.xml.makeObjectPropertyPusher(
          ol.format.WMTSCapabilities.readStyle_),
      'Format': ol.xml.makeObjectPropertyPusher(
          ol.format.XSD.readString),
      'TileMatrixSetLink': ol.xml.makeObjectPropertyPusher(
          ol.format.WMTSCapabilities.readTileMatrixSetLink_),
      'ResourceURL': ol.xml.makeObjectPropertyPusher(
          ol.format.WMTSCapabilities.readResourceUrl_)
    }, ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
      'Title': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString),
      'Abstract': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString),
      'WGS84BoundingBox': ol.xml.makeObjectPropertySetter(
          ol.format.WMTSCapabilities.readWgs84BoundingBox_),
      'Identifier': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString)
    }));

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.STYLE_PARSERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
      'LegendURL': ol.xml.makeObjectPropertyPusher(
          ol.format.WMTSCapabilities.readLegendUrl_)
    }, ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
      'Title': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString),
      'Identifier': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString)
    }));

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.TMS_LINKS_PARSERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
      'TileMatrixSet': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString)
    });

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.WGS84_BBOX_READERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
      'LowerCorner': ol.xml.makeArrayPusher(
          ol.format.WMTSCapabilities.readCoordinates_),
      'UpperCorner': ol.xml.makeArrayPusher(
          ol.format.WMTSCapabilities.readCoordinates_)
    });

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.TMS_PARSERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
      'WellKnownScaleSet': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString),
      'TileMatrix': ol.xml.makeObjectPropertyPusher(
          ol.format.WMTSCapabilities.readTileMatrix_)
    }, ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
      'SupportedCRS': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString),
      'Identifier': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString)
    }));

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.TM_PARSERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
      'TopLeftCorner': ol.xml.makeObjectPropertySetter(
          ol.format.WMTSCapabilities.readCoordinates_),
      'ScaleDenominator': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readDecimal),
      'TileWidth': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readNonNegativeInteger),
      'TileHeight': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readNonNegativeInteger),
      'MatrixWidth': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readNonNegativeInteger),
      'MatrixHeight': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readNonNegativeInteger)
    }, ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
      'Identifier': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString)
    }));
<commit_msg>Use bracket notation instead of goog.object.set<commit_after>goog.provide('ol.format.WMTSCapabilities');

goog.require('goog.asserts');
goog.require('goog.dom.NodeType');
goog.require('goog.string');
goog.require('ol.extent');
goog.require('ol.format.OWS');
goog.require('ol.format.XLink');
goog.require('ol.format.XML');
goog.require('ol.format.XSD');
goog.require('ol.xml');

/**
 * @classdesc
 * Format for reading WMTS capabilities data.
 *
 * @constructor
 * @extends {ol.format.XML}
 * @api
 */
ol.format.WMTSCapabilities = function() {
  goog.base(this);

  /**
   * @type {ol.format.OWS}
   * @private
   */
  this.owsParser_ = new ol.format.OWS();
};
goog.inherits(ol.format.WMTSCapabilities, ol.format.XML);

/**
 * Read a WMTS capabilities document.
 *
 * @function
 * @param {Document|Node|string} source The XML source.
 * @return {Object} An object representing the WMTS capabilities.
 * @api
 */
ol.format.WMTSCapabilities.prototype.read;

/**
 * @param {Document} doc Document.
 * @return {Object} WMTS Capability object.
 */
ol.format.WMTSCapabilities.prototype.readFromDocument = function(doc) {
  goog.asserts.assert(doc.nodeType == goog.dom.NodeType.DOCUMENT,
      'doc.nodeType should be DOCUMENT');
  for (var n = doc.firstChild; !goog.isNull(n); n = n.nextSibling) {
    if (n.nodeType == goog.dom.NodeType.ELEMENT) {
      return this.readFromNode(n);
    }
  }
  return null;
};

/**
 * @param {Node} node Node.
 * @return {Object} WMTS Capability object.
 */
ol.format.WMTSCapabilities.prototype.readFromNode = function(node) {
  goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
      'node.nodeType should be ELEMENT');
  goog.asserts.assert(node.localName == 'Capabilities',
      'localName should be Capabilities');
  this.version = goog.string.trim(node.getAttribute('version'));
  goog.asserts.assertString(this.version, 'this.version should be a string');
  var WMTSCapabilityObject = this.owsParser_.readFromNode(node);
  if (!goog.isDef(WMTSCapabilityObject)) {
    return null;
  }
  WMTSCapabilityObject['version'] = this.version;
  WMTSCapabilityObject = ol.xml.pushParseAndPop(WMTSCapabilityObject,
      ol.format.WMTSCapabilities.PARSERS_, node, []);
  return goog.isDef(WMTSCapabilityObject) ? WMTSCapabilityObject : null;
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Attribution object.
 */
ol.format.WMTSCapabilities.readContents_ = function(node, objectStack) {
  goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
      'node.nodeType should be ELEMENT');
  goog.asserts.assert(node.localName == 'Contents',
      'localName should be Contents');

  return ol.xml.pushParseAndPop({},
      ol.format.WMTSCapabilities.CONTENTS_PARSERS_, node, objectStack);
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Layers object.
 */
ol.format.WMTSCapabilities.readLayer_ = function(node, objectStack) {
  goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
      'node.nodeType should be ELEMENT');
  goog.asserts.assert(node.localName == 'Layer', 'localName should be Layer');
  return ol.xml.pushParseAndPop({},
      ol.format.WMTSCapabilities.LAYER_PARSERS_, node, objectStack);
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Tile Matrix Set object.
 */
ol.format.WMTSCapabilities.readTileMatrixSet_ = function(node, objectStack) {
  return ol.xml.pushParseAndPop({},
      ol.format.WMTSCapabilities.TMS_PARSERS_, node, objectStack);
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Style object.
 */
ol.format.WMTSCapabilities.readStyle_ = function(node, objectStack) {
  var style = ol.xml.pushParseAndPop({},
      ol.format.WMTSCapabilities.STYLE_PARSERS_, node, objectStack);
  if (!goog.isDef(style)) {
    return undefined;
  }
  var isDefault = node.getAttribute('isDefault') === 'true';
  style['isDefault'] = isDefault;
  return style;

};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Tile Matrix Set Link object.
 */
ol.format.WMTSCapabilities.readTileMatrixSetLink_ = function(node,
    objectStack) {
  return ol.xml.pushParseAndPop({},
      ol.format.WMTSCapabilities.TMS_LINKS_PARSERS_, node, objectStack);
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Resource URL object.
 */
ol.format.WMTSCapabilities.readResourceUrl_ = function(node, objectStack) {
  var format = node.getAttribute('format');
  var template = node.getAttribute('template');
  var resourceType = node.getAttribute('resourceType');
  var resource = {};
  if (goog.isDef(format)) {
    resource['format'] = format;
  }
  if (goog.isDef(template)) {
    resource['template'] = template;
  }
  if (goog.isDef(resourceType)) {
    resource['resourceType'] = resourceType;
  }
  return resource;
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} WGS84 BBox object.
 */
ol.format.WMTSCapabilities.readWgs84BoundingBox_ = function(node, objectStack) {
  var coordinates = ol.xml.pushParseAndPop([],
      ol.format.WMTSCapabilities.WGS84_BBOX_READERS_, node, objectStack);
  if (coordinates.length != 2) {
    return undefined;
  }
  return ol.extent.boundingExtent(coordinates);
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Legend object.
 */
ol.format.WMTSCapabilities.readLegendUrl_ = function(node, objectStack) {
  var legend = {};
  legend['format'] = node.getAttribute('format');
  legend['href'] = ol.format.XLink.readHref(node);
  return legend;
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} Coordinates object.
 */
ol.format.WMTSCapabilities.readCoordinates_ = function(node, objectStack) {
  var coordinates = ol.format.XSD.readString(node).split(' ');
  if (!goog.isDef(coordinates) || coordinates.length != 2) {
    return undefined;
  }
  var x = +coordinates[0];
  var y = +coordinates[1];
  if (isNaN(x) || isNaN(y)) {
    return undefined;
  }
  return [x, y];
};

/**
 * @private
 * @param {Node} node Node.
 * @param {Array.<*>} objectStack Object stack.
 * @return {Object|undefined} TileMatrix object.
 */
ol.format.WMTSCapabilities.readTileMatrix_ = function(node, objectStack) {
  return ol.xml.pushParseAndPop({},
      ol.format.WMTSCapabilities.TM_PARSERS_, node, objectStack);
};

/**
 * @const
 * @private
 * @type {Array.<string>}
 */
ol.format.WMTSCapabilities.NAMESPACE_URIS_ = [
  null,
  'http://www.opengis.net/wmts/1.0'
];

/**
 * @const
 * @private
 * @type {Array.<string>}
 */
ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_ = [
  null,
  'http://www.opengis.net/ows/1.1'
];

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.PARSERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
      'Contents': ol.xml.makeObjectPropertySetter(
          ol.format.WMTSCapabilities.readContents_)
    });

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.CONTENTS_PARSERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
      'Layer': ol.xml.makeObjectPropertyPusher(
          ol.format.WMTSCapabilities.readLayer_),
      'TileMatrixSet': ol.xml.makeObjectPropertyPusher(
          ol.format.WMTSCapabilities.readTileMatrixSet_)
    });

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.LAYER_PARSERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
      'Style': ol.xml.makeObjectPropertyPusher(
          ol.format.WMTSCapabilities.readStyle_),
      'Format': ol.xml.makeObjectPropertyPusher(
          ol.format.XSD.readString),
      'TileMatrixSetLink': ol.xml.makeObjectPropertyPusher(
          ol.format.WMTSCapabilities.readTileMatrixSetLink_),
      'ResourceURL': ol.xml.makeObjectPropertyPusher(
          ol.format.WMTSCapabilities.readResourceUrl_)
    }, ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
      'Title': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString),
      'Abstract': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString),
      'WGS84BoundingBox': ol.xml.makeObjectPropertySetter(
          ol.format.WMTSCapabilities.readWgs84BoundingBox_),
      'Identifier': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString)
    }));

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.STYLE_PARSERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
      'LegendURL': ol.xml.makeObjectPropertyPusher(
          ol.format.WMTSCapabilities.readLegendUrl_)
    }, ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
      'Title': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString),
      'Identifier': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString)
    }));

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.TMS_LINKS_PARSERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
      'TileMatrixSet': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString)
    });

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.WGS84_BBOX_READERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
      'LowerCorner': ol.xml.makeArrayPusher(
          ol.format.WMTSCapabilities.readCoordinates_),
      'UpperCorner': ol.xml.makeArrayPusher(
          ol.format.WMTSCapabilities.readCoordinates_)
    });

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.TMS_PARSERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
      'WellKnownScaleSet': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString),
      'TileMatrix': ol.xml.makeObjectPropertyPusher(
          ol.format.WMTSCapabilities.readTileMatrix_)
    }, ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
      'SupportedCRS': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString),
      'Identifier': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString)
    }));

/**
 * @const
 * @type {Object.<string, Object.<string, ol.xml.Parser>>}
 * @private
 */
ol.format.WMTSCapabilities.TM_PARSERS_ = ol.xml.makeStructureNS(
    ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
      'TopLeftCorner': ol.xml.makeObjectPropertySetter(
          ol.format.WMTSCapabilities.readCoordinates_),
      'ScaleDenominator': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readDecimal),
      'TileWidth': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readNonNegativeInteger),
      'TileHeight': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readNonNegativeInteger),
      'MatrixWidth': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readNonNegativeInteger),
      'MatrixHeight': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readNonNegativeInteger)
    }, ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
      'Identifier': ol.xml.makeObjectPropertySetter(
          ol.format.XSD.readString)
    }));
<|endoftext|>


<commit_before>/* global $ */
/* global requirejs */

'use strict';

var exec = require('exec');
var spawn = require('child_process').spawn;
var ipc = require("electron-safe-ipc/guest");

var app;
var grid;
var userData;
exports.child = null;

var bootstrapProcess = function(name, args) {

	grid.clear();
	exports.terminateProcess();

	var command = userData.dataservClient + " ";
	for(var i = 0; i < args.length; ++i) {
		command += args[i];
		if(i < args.length - 1) {
			command += ' ';
		}
	}
	grid.insertRecord(command);

	exports.child = spawn(userData.dataservClient, args);
	exports.child.stdout.on('data', function (data) {
		grid.insertRecord(data.toString());
	});
	exports.child.stderr.on('data', function (data) {
		grid.insertRecord(data.toString());
	});

	grid.refreshToolbar();
};

exports.initProcess = function() {
	app = requirejs('./app');
	userData = app.userData;
	grid = requirejs('./modules/grid');
	ipc.on('farm', exports.farm);
	ipc.on('terminateProcess', exports.terminateProcess);
};

exports.farm = function() {
	if(app.hasValidSettings()) {
		bootstrapProcess('farm', ['--store_path=' + userData.dataservDirectory, '--max_size=' + userData.dataservSize, 'farm']);
	}
}

exports.build = function() {
	if(app.hasValidSettings()) {
		bootstrapProcess('build', ['--store_path=' + userData.dataservDirectory, '--max_size=' + userData.dataservSize, 'build']);
	}
}

exports.register = function() {
	if(app.hasValidSettings()) {
		bootstrapProcess('register', ['register']);
	}
};

exports.poll = function() {
	if(app.hasValidSettings()) {
		bootstrapProcess('poll', ['poll']);
	}
};

exports.saveConfig = function() {
	if(app.hasValidDataservClient() && app.hasValidPayoutAddress()) {
		bootstrapProcess('config', ['config', '--set_payout_address=' + userData.payoutAddress]);
	}
}

exports.validateDataservClient = function(callback) {
	if(app.hasValidDataservClient()) {
		exec([userData.dataservClient, 'version'], function(err, out, code) {
			var output;
			if(err) {
				output = err.toString();
			}
			if(code !== 0) {
				output = 'invalid dataserv-client';
			}
			if(callback) {
				callback(output);
			}
		});
	} else if(callback) {
		callback('invalid dataserv-client');
	}
}

exports.terminateProcess = function() {
	if(exports.child) {
		grid.insertRecord('exports.child ' + exports.child.pid + ' terminated');
		exports.child.kill();
		exports.child = null;
		grid.refreshToolbar();
	}
}
<commit_msg>Fixing issue that caused start button to turn to stop button when preferences dialog was closed.<commit_after>/* global $ */
/* global requirejs */

'use strict';

var exec = require('exec');
var spawn = require('child_process').spawn;
var ipc = require("electron-safe-ipc/guest");

var app;
var grid;
var userData;
exports.child = null;

var bootstrapProcess = function(name, args) {

	grid.clear();
	exports.terminateProcess();

	var command = userData.dataservClient + " ";
	for(var i = 0; i < args.length; ++i) {
		command += args[i];
		if(i < args.length - 1) {
			command += ' ';
		}
	}
	grid.insertRecord(command);

	exports.child = spawn(userData.dataservClient, args);
	exports.child.stdout.on('data', function (data) {
		grid.insertRecord(data.toString());
	});
	exports.child.stderr.on('data', function (data) {
		grid.insertRecord(data.toString());
	});

	grid.refreshToolbar();
};

exports.initProcess = function() {
	app = requirejs('./app');
	userData = app.userData;
	grid = requirejs('./modules/grid');
	ipc.on('farm', exports.farm);
	ipc.on('terminateProcess', exports.terminateProcess);
};

exports.farm = function() {
	if(app.hasValidSettings()) {
		bootstrapProcess('farm', ['--store_path=' + userData.dataservDirectory, '--max_size=' + userData.dataservSize, 'farm']);
	}
}

exports.build = function() {
	if(app.hasValidSettings()) {
		bootstrapProcess('build', ['--store_path=' + userData.dataservDirectory, '--max_size=' + userData.dataservSize, 'build']);
	}
}

exports.register = function() {
	if(app.hasValidSettings()) {
		bootstrapProcess('register', ['register']);
	}
};

exports.poll = function() {
	if(app.hasValidSettings()) {
		bootstrapProcess('poll', ['poll']);
	}
};

exports.saveConfig = function() {
	if(app.hasValidDataservClient() && app.hasValidPayoutAddress()) {
		exec([userData.dataservClient, ['config', '--set_payout_address=' + userData.payoutAddress]]);
	}
}

exports.validateDataservClient = function(callback) {
	if(app.hasValidDataservClient()) {
		exec([userData.dataservClient, 'version'], function(err, out, code) {
			var output;
			if(err) {
				output = err.toString();
			}
			if(code !== 0) {
				output = 'invalid dataserv-client';
			}
			if(callback) {
				callback(output);
			}
		});
	} else if(callback) {
		callback('invalid dataserv-client');
	}
}

exports.terminateProcess = function() {
	if(exports.child) {
		grid.insertRecord('exports.child ' + exports.child.pid + ' terminated');
		exports.child.kill();
		exports.child = null;
		grid.refreshToolbar();
	}
}
<|endoftext|>


<commit_before>const GOING_IN = 'in'
const GOING_OUT = 'out'

const going = visibilityRatio => visibilityRatio > 0 ? GOING_IN : GOING_OUT

const DIRECTION_TOP = 'top'
const DIRECTION_RIGHT = 'right'
const DIRECTION_BOTTOM = 'bottom'
const DIRECTION_LEFT = 'left'

const direction = (boundingClientRect, oldBoundingClientRect) => {
  if (boundingClientRect.y < oldBoundingClientRect.y) return DIRECTION_TOP
  if (boundingClientRect.x > oldBoundingClientRect.x) return DIRECTION_RIGHT
  if (boundingClientRect.y > oldBoundingClientRect.y) return DIRECTION_BOTTOM
  if (boundingClientRect.x < oldBoundingClientRect.x) return DIRECTION_LEFT
}

const extractWaypointData = node => node._waypointData

const extractOldBoundingClientRect = (node, defaultBoundingClientRect) => {
  const nodeData = extractWaypointData(node)
  return typeof nodeData !== 'undefined' ? nodeData : defaultBoundingClientRect
}

const mapEntry = entry => {
  const { boundingClientRect, intersectionRatio, target } = entry
  const oldBoundingClientRect = extractOldBoundingClientRect(target, boundingClientRect)

  // save current rect
  target._waypointData = boundingClientRect

  return {
    el: target,
    going: going(intersectionRatio),
    direction: direction(boundingClientRect, oldBoundingClientRect),
    _entry: entry
  }
}

export {
  going,
  GOING_IN,
  GOING_OUT,
  direction,
  DIRECTION_TOP,
  DIRECTION_RIGHT,
  DIRECTION_BOTTOM,
  DIRECTION_LEFT,
  mapEntry
}
<commit_msg>Update waypointInterface.js (#14)<commit_after>const GOING_IN = 'in'
const GOING_OUT = 'out'

const going = visibilityRatio => visibilityRatio > 0 ? GOING_IN : GOING_OUT

const DIRECTION_TOP = 'top'
const DIRECTION_RIGHT = 'right'
const DIRECTION_BOTTOM = 'bottom'
const DIRECTION_LEFT = 'left'

const direction = (boundingClientRect, oldBoundingClientRect) => {
  const y = boundingClientRect.y || boundingClientRect.top
  const x = boundingClientRect.x || boundingClientRect.left
  const oldY = oldBoundingClientRect.y || oldBoundingClientRect.top
  const oldX = oldBoundingClientRect.x || oldBoundingClientRect.left
  if (y < oldY) return DIRECTION_TOP
  if (x > oldX) return DIRECTION_RIGHT
  if (y > oldY) return DIRECTION_BOTTOM
  if (x < oldX) return DIRECTION_LEFT
}

const extractWaypointData = node => node._waypointData

const extractOldBoundingClientRect = (node, defaultBoundingClientRect) => {
  const nodeData = extractWaypointData(node)
  return typeof nodeData !== 'undefined' ? nodeData : defaultBoundingClientRect
}

const mapEntry = entry => {
  const { boundingClientRect, intersectionRatio, target } = entry
  const oldBoundingClientRect = extractOldBoundingClientRect(target, boundingClientRect)

  // save current rect
  target._waypointData = boundingClientRect

  return {
    el: target,
    going: going(intersectionRatio),
    direction: direction(boundingClientRect, oldBoundingClientRect),
    _entry: entry
  }
}

export {
  going,
  GOING_IN,
  GOING_OUT,
  direction,
  DIRECTION_TOP,
  DIRECTION_RIGHT,
  DIRECTION_BOTTOM,
  DIRECTION_LEFT,
  mapEntry
}
<|endoftext|>


<commit_before>import {Platform, Page, NavController} from 'ionic/ionic';
import {AddItemPage} from '../add-item/add-item'
import {ItemDetailPage} from '../item-detail/item-detail';
import {DataService} from '../../data/data';

@Page({
  templateUrl: 'build/pages/list/list.html'
})
export class ListPage {
  constructor(platform: Platform, nav:NavController, dataService: DataService) {

    this.nav = nav;
    this.dataService = dataService;

    this.items=[];

    platform.ready().then(()=>{
      this.dataService.getData().then((data)=>{
        this.items = [];
        if(data.res.rows.length>0){
          for(var i=0; i<data.res.rows.length;i++){
            this.items.push({title: data.res.rows.item(i).title,
               description: data.res.rows.item(i).description});
          }
        }
      }, (error)=>{
        console.log("ERROR -> " + JSON.stringify(error.err));
      })
    });
  }

  addItem(){
    this.nav.push(AddItemPage,{ListPage:this});
  }

  saveItem(item){
    this.items.push(item);
    this.dataService.save(item);
  }

  viewItem(item){
    this.nav.push(ItemDetailPage, {item:item});
  }
}
<commit_msg>sql version<commit_after>import {Platform, Page, NavController} from 'ionic/ionic';
import {AddItemPage} from '../add-item/add-item'
import {ItemDetailPage} from '../item-detail/item-detail';
import {DataService} from '../../data/data';

@Page({
  templateUrl: 'build/pages/list/list.html'
})
export class ListPage {
  constructor(platform: Platform, nav:NavController, dataService: DataService) {

    this.nav = nav;
    this.dataService = dataService;

    this.items=[];

    platform.ready().then(()=>{
      this.dataService.getData().then((data)=>{
        this.items = [];
        if(data.res.rows.length>0){
          for(var i=0; i<data.res.rows.length;i++){
            this.items.push({title: data.res.rows.item(i).title,
               description: data.res.rows.item(i).description});
          }
        }
      }, (error)=>{
        console.log("ERROR -> " + JSON.stringify(error.err));
      })
    });
  }

  addItem(){
    this.nav.push(AddItemPage,{listPage:this});
  }

  saveItem(item){
    this.items.push(item);
    this.dataService.save(item);
  }

  viewItem(item){
    this.nav.push(ItemDetailPage, {item:item});
  }
}
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2018  The Software Heritage developers
 * See the AUTHORS file at the top-level directory of this distribution
 * License: GNU Affero General Public License version 3, or any later version
 * See top-level LICENSE file for more information
 */

import {heapsPermute} from 'utils/heaps-permute';
import {handleFetchError} from 'utils/functions';

let originPatterns;
let perPage = 20;
let limit = perPage * 10;
let offset = 0;
let currentData = null;
let inSearch = false;

function fixTableRowsStyle() {
  setTimeout(() => {
    $('#origin-search-results tbody tr').removeAttr('style');
  });
}

function clearOriginSearchResultsTable() {
  $('#origin-search-results tbody tr').remove();
}

function populateOriginSearchResultsTable(data, offset) {
  let localOffset = offset % limit;
  if (data.length > 0) {
    $('#swh-origin-search-results').show();
    $('#swh-no-result').hide();
    clearOriginSearchResultsTable();
    let table = $('#origin-search-results tbody');
    for (let i = localOffset; i < localOffset + perPage && i < data.length; ++i) {
      let elem = data[i];
      let tableRow = '
';
      tableRow += '' + elem.type + '	';
      let browseUrl = Urls.browse_origin(elem.url);
      tableRow += '' + browseUrl + '	';
      tableRow += '	';
      tableRow += '
';
      table.append(tableRow);
      // get async latest visit snapshot and update visit status icon
      let latestSnapshotUrl = Urls.browse_origin_latest_snapshot(elem.id);
      fetch(latestSnapshotUrl)
        .then(response => response.json())
        .then(data => {
          let originId = elem.id;
          $('#visit-status-origin-' + originId).children().remove();
          if (data) {
            $('#visit-status-origin-' + originId).append('');
          } else {
            $('#visit-status-origin-' + originId).append('');
          }
        });
    }
    fixTableRowsStyle();
  } else {
    $('#swh-origin-search-results').hide();
    $('#swh-no-result').text('No origins matching the search criteria were found.');
    $('#swh-no-result').show();
  }
  if (data.length - localOffset < perPage ||
      (data.length < limit && (localOffset + perPage) === data.length)) {
    $('#origins-next-results-button').addClass('disabled');
  } else {
    $('#origins-next-results-button').removeClass('disabled');
  }
  if (offset > 0) {
    $('#origins-prev-results-button').removeClass('disabled');
  } else {
    $('#origins-prev-results-button').addClass('disabled');
  }
  inSearch = false;
  setTimeout(() => {
    window.scrollTo(0, 0);
  });
}

function searchOrigins(patterns, limit, searchOffset, offset) {
  originPatterns = patterns;
  let patternsArray = patterns.trim().replace(/\s+/g, ' ').split(' ');
  let patternsPermut = [];
  heapsPermute(patternsArray, p => patternsPermut.push(p.join('.*')));
  let regex = patternsPermut.join('|');
  let searchUrl = Urls.browse_origin_search(regex) + `?limit=${limit}&offset=${searchOffset}&regexp=true`;

  clearOriginSearchResultsTable();
  $('.swh-loading').addClass('show');
  fetch(searchUrl)
    .then(handleFetchError)
    .then(response => response.json())
    .then(data => {
      currentData = data;
      if (typeof Storage !== 'undefined') {
        sessionStorage.setItem('last-swh-origin-url-patterns', patterns);
        sessionStorage.setItem('last-swh-origin-search-results', JSON.stringify(data));
        sessionStorage.setItem('last-swh-origin-search-offset', offset);
      }
      $('.swh-loading').removeClass('show');
      populateOriginSearchResultsTable(data, offset);
    })
    .catch(() => {
      $('.swh-loading').removeClass('show');
      inSearch = false;
    });
}

export function initOriginSearch() {
  $(document).ready(() => {
    if (typeof Storage !== 'undefined') {
      originPatterns = sessionStorage.getItem('last-swh-origin-url-patterns');
      let data = sessionStorage.getItem('last-swh-origin-search-results');
      offset = sessionStorage.getItem('last-swh-origin-search-offset');
      if (data) {
        $('#origins-url-patterns').val(originPatterns);
        offset = parseInt(offset);
        populateOriginSearchResultsTable(JSON.parse(data), offset);
      }
    }

    $('#search_origins').submit(event => {
      event.preventDefault();
      $('#swh-no-result').hide();
      let patterns = $('#origins-url-patterns').val();
      offset = 0;
      inSearch = true;
      // first try to resolve a swh persistent identifier
      let resolvePidUrl = Urls.resolve_swh_pid(patterns);
      fetch(resolvePidUrl)
        .then(handleFetchError)
        .then(response => response.json())
        .then(data => {
          // pid has been successfully resolved,
          // so redirect to browse page
          window.location = data.browse_url;
        })
        .catch(response => {
          // pid resolving failed
          if (patterns.startsWith('swh:')) {
            // display a useful error message if the input
            // looks like a swh pid
            response.json().then(data => {
              $('#swh-origin-search-results').hide();
              $('.swh-search-pagination').hide();
              $('#swh-no-result').text(data.reason);
              $('#swh-no-result').show();
            });
          } else {
            // otherwise, proceed with origins search
            $('#swh-origin-search-results').show();
            $('.swh-search-pagination').show();
            searchOrigins(patterns, limit, offset, offset);
          }
        });
    });

    $('#origins-next-results-button').click(event => {
      if ($('#origins-next-results-button').hasClass('disabled') || inSearch) {
        return;
      }
      inSearch = true;
      offset += perPage;
      if (!currentData || offset % limit === 0) {
        searchOrigins(originPatterns, limit, offset, offset);
      } else {
        populateOriginSearchResultsTable(currentData, offset);
      }
      event.preventDefault();
    });

    $('#origins-prev-results-button').click(event => {
      if ($('#origins-prev-results-button').hasClass('disabled') || inSearch) {
        return;
      }
      inSearch = true;
      offset -= perPage;
      if (!currentData || (offset > 0 && (offset + perPage) % limit === 0)) {
        searchOrigins(originPatterns, limit, (offset + perPage) - limit, offset);
      } else {
        populateOriginSearchResultsTable(currentData, offset);
      }
      event.preventDefault();
    });

    $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', e => {
      if (e.currentTarget.text.trim() === 'Search') {
        fixTableRowsStyle();
      }
    });
  });
}
<commit_msg>assets: Fix origin search results backup and retrieval issues<commit_after>/**
 * Copyright (C) 2018  The Software Heritage developers
 * See the AUTHORS file at the top-level directory of this distribution
 * License: GNU Affero General Public License version 3, or any later version
 * See top-level LICENSE file for more information
 */

import {heapsPermute} from 'utils/heaps-permute';
import {handleFetchError} from 'utils/functions';

let originPatterns;
let perPage = 20;
let limit = perPage * 10;
let offset = 0;
let currentData = null;
let inSearch = false;

function fixTableRowsStyle() {
  setTimeout(() => {
    $('#origin-search-results tbody tr').removeAttr('style');
  });
}

function clearOriginSearchResultsTable() {
  $('#origin-search-results tbody tr').remove();
}

function populateOriginSearchResultsTable(data, offset) {
  let localOffset = offset % limit;
  if (data.length > 0) {
    $('#swh-origin-search-results').show();
    $('#swh-no-result').hide();
    clearOriginSearchResultsTable();
    let table = $('#origin-search-results tbody');
    for (let i = localOffset; i < localOffset + perPage && i < data.length; ++i) {
      let elem = data[i];
      let tableRow = '
';
      tableRow += '' + elem.type + '	';
      let browseUrl = Urls.browse_origin(elem.url);
      tableRow += '' + browseUrl + '	';
      tableRow += '	';
      tableRow += '
';
      table.append(tableRow);
      // get async latest visit snapshot and update visit status icon
      let latestSnapshotUrl = Urls.browse_origin_latest_snapshot(elem.id);
      fetch(latestSnapshotUrl)
        .then(response => response.json())
        .then(data => {
          let originId = elem.id;
          $('#visit-status-origin-' + originId).children().remove();
          if (data) {
            $('#visit-status-origin-' + originId).append('');
          } else {
            $('#visit-status-origin-' + originId).append('');
          }
        });
    }
    fixTableRowsStyle();
  } else {
    $('#swh-origin-search-results').hide();
    $('#swh-no-result').text('No origins matching the search criteria were found.');
    $('#swh-no-result').show();
  }
  if (data.length - localOffset < perPage ||
      (data.length < limit && (localOffset + perPage) === data.length)) {
    $('#origins-next-results-button').addClass('disabled');
  } else {
    $('#origins-next-results-button').removeClass('disabled');
  }
  if (offset > 0) {
    $('#origins-prev-results-button').removeClass('disabled');
  } else {
    $('#origins-prev-results-button').addClass('disabled');
  }
  inSearch = false;
  if (typeof Storage !== 'undefined') {
    sessionStorage.setItem('last-swh-origin-search-offset', offset);
  }
  setTimeout(() => {
    window.scrollTo(0, 0);
  });
}

function searchOrigins(patterns, limit, searchOffset, offset) {
  originPatterns = patterns;
  let patternsArray = patterns.trim().replace(/\s+/g, ' ').split(' ');
  let patternsPermut = [];
  heapsPermute(patternsArray, p => patternsPermut.push(p.join('.*')));
  let regex = patternsPermut.join('|');
  let searchUrl = Urls.browse_origin_search(regex) + `?limit=${limit}&offset=${searchOffset}&regexp=true`;

  clearOriginSearchResultsTable();
  $('.swh-loading').addClass('show');
  fetch(searchUrl)
    .then(handleFetchError)
    .then(response => response.json())
    .then(data => {
      currentData = data;
      if (typeof Storage !== 'undefined') {
        sessionStorage.setItem('last-swh-origin-url-patterns', patterns);
        sessionStorage.setItem('last-swh-origin-search-results', JSON.stringify(data));
        sessionStorage.setItem('last-swh-origin-search-offset', offset);
      }
      $('.swh-loading').removeClass('show');
      populateOriginSearchResultsTable(data, offset);
    })
    .catch(() => {
      $('.swh-loading').removeClass('show');
      inSearch = false;
    });
}

export function initOriginSearch() {
  $(document).ready(() => {
    if (typeof Storage !== 'undefined') {
      originPatterns = sessionStorage.getItem('last-swh-origin-url-patterns');
      let data = sessionStorage.getItem('last-swh-origin-search-results');
      offset = sessionStorage.getItem('last-swh-origin-search-offset');
      if (data) {
        $('#origins-url-patterns').val(originPatterns);
        offset = parseInt(offset);
        currentData = JSON.parse(data);
        populateOriginSearchResultsTable(currentData, offset);
      }
    }

    $('#search_origins').submit(event => {
      event.preventDefault();
      $('#swh-no-result').hide();
      let patterns = $('#origins-url-patterns').val();
      offset = 0;
      inSearch = true;
      // first try to resolve a swh persistent identifier
      let resolvePidUrl = Urls.resolve_swh_pid(patterns);
      fetch(resolvePidUrl)
        .then(handleFetchError)
        .then(response => response.json())
        .then(data => {
          // pid has been successfully resolved,
          // so redirect to browse page
          window.location = data.browse_url;
        })
        .catch(response => {
          // pid resolving failed
          if (patterns.startsWith('swh:')) {
            // display a useful error message if the input
            // looks like a swh pid
            response.json().then(data => {
              $('#swh-origin-search-results').hide();
              $('.swh-search-pagination').hide();
              $('#swh-no-result').text(data.reason);
              $('#swh-no-result').show();
            });
          } else {
            // otherwise, proceed with origins search
            $('#swh-origin-search-results').show();
            $('.swh-search-pagination').show();
            searchOrigins(patterns, limit, offset, offset);
          }
        });
    });

    $('#origins-next-results-button').click(event => {
      if ($('#origins-next-results-button').hasClass('disabled') || inSearch) {
        return;
      }
      inSearch = true;
      offset += perPage;
      if (!currentData || (offset >= limit && offset % limit === 0)) {
        searchOrigins(originPatterns, limit, offset, offset);
      } else {
        populateOriginSearchResultsTable(currentData, offset);
      }
      event.preventDefault();
    });

    $('#origins-prev-results-button').click(event => {
      if ($('#origins-prev-results-button').hasClass('disabled') || inSearch) {
        return;
      }
      inSearch = true;
      offset -= perPage;
      if (!currentData || (offset > 0 && (offset + perPage) % limit === 0)) {
        searchOrigins(originPatterns, limit, (offset + perPage) - limit, offset);
      } else {
        populateOriginSearchResultsTable(currentData, offset);
      }
      event.preventDefault();
    });

    $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', e => {
      if (e.currentTarget.text.trim() === 'Search') {
        fixTableRowsStyle();
      }
    });
  });
}
<|endoftext|>


<commit_before>import {BubbleMixin} from '../base/bubble-mixin';
import {CoordinateGridMixin} from '../base/coordinate-grid-mixin';
import {transition} from '../core/core';

/**
 * A concrete implementation of a general purpose bubble chart that allows data visualization using the
 * following dimensions:
 * - x axis position
 * - y axis position
 * - bubble radius
 * - color
 *
 * Examples:
 * - {@link http://dc-js.github.com/dc.js/ Nasdaq 100 Index}
 * - {@link http://dc-js.github.com/dc.js/vc/index.html US Venture Capital Landscape 2011}
 * @class bubbleChart
 * @memberof dc
 * @mixes dc.bubbleMixin
 * @mixes dc.coordinateGridMixin
 * @example
 * // create a bubble chart under #chart-container1 element using the default global chart group
 * var bubbleChart1 = dc.bubbleChart('#chart-container1');
 * // create a bubble chart under #chart-container2 element using chart group A
 * var bubbleChart2 = dc.bubbleChart('#chart-container2', 'chartGroupA');
 * @param {String|node|d3.selection} parent - Any valid
 * {@link https://github.com/d3/d3-selection/blob/master/README.md#select d3 single selector} specifying
 * a dom block element such as a div; or a dom element or d3 selection.
 * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in.
 * Interaction with a chart will only trigger events and redraws within the chart's group.
 * @returns {dc.bubbleChart}
 */
export const bubbleChart = (parent, chartGroup) => new BubbleChart(parent, chartGroup);

class BubbleChart extends BubbleMixin(CoordinateGridMixin) {
    constructor (parent, chartGroup) {
        super();

        const _chart = this;

        _chart.transitionDuration(750);

        _chart.transitionDelay(0);

        var bubbleLocator = function (d) {
            return 'translate(' + (bubbleX(d)) + ',' + (bubbleY(d)) + ')';
        };

        _chart.plotData = function () {
            _chart.calculateRadiusDomain();
            _chart.r().range([_chart.MIN_RADIUS, _chart.xAxisLength() * _chart.maxBubbleRelativeSize()]);

            var data = _chart.data();
            var bubbleG = _chart.chartBodyG().selectAll('g.' + _chart.BUBBLE_NODE_CLASS)
                .data(data, function (d) {
                    return d.key;
                });
            if (_chart.sortBubbleSize()) {
                // update dom order based on sort
                bubbleG.order();
            }

            removeNodes(bubbleG);

            bubbleG = renderNodes(bubbleG);

            updateNodes(bubbleG);

            _chart.fadeDeselectedArea(_chart.filter());
        };

        function renderNodes (bubbleG) {
            var bubbleGEnter = bubbleG.enter().append('g');

            bubbleGEnter
                .attr('class', _chart.BUBBLE_NODE_CLASS)
                .attr('transform', bubbleLocator)
                .append('circle').attr('class', function (d, i) {
                return _chart.BUBBLE_CLASS + ' _' + i;
            })
                .on('click', _chart.onClick)
                .attr('fill', _chart.getColor)
                .attr('r', 0);

            bubbleG = bubbleGEnter.merge(bubbleG);

            transition(bubbleG, _chart.transitionDuration(), _chart.transitionDelay())
                .select('circle.' + _chart.BUBBLE_CLASS)
                .attr('r', function (d) {
                    return _chart.bubbleR(d);
                })
                .attr('opacity', function (d) {
                    return (_chart.bubbleR(d) > 0) ? 1 : 0;
                });

            _chart._doRenderLabel(bubbleGEnter);

            _chart._doRenderTitles(bubbleGEnter);

            return bubbleG;
        }

        function updateNodes (bubbleG) {
            transition(bubbleG, _chart.transitionDuration(), _chart.transitionDelay())
                .attr('transform', bubbleLocator)
                .select('circle.' + _chart.BUBBLE_CLASS)
                .attr('fill', _chart.getColor)
                .attr('r', function (d) {
                    return _chart.bubbleR(d);
                })
                .attr('opacity', function (d) {
                    return (_chart.bubbleR(d) > 0) ? 1 : 0;
                });

            _chart.doUpdateLabels(bubbleG);
            _chart.doUpdateTitles(bubbleG);
        }

        function removeNodes (bubbleG) {
            bubbleG.exit().remove();
        }

        function bubbleX (d) {
            var x = _chart.x()(_chart.keyAccessor()(d));
            if (isNaN(x) || !isFinite(x)) {
                x = 0;
            }
            return x;
        }

        function bubbleY (d) {
            var y = _chart.y()(_chart.valueAccessor()(d));
            if (isNaN(y) || !isFinite(y)) {
                y = 0;
            }
            return y;
        }

        _chart.renderBrush = function () {
            // override default x axis brush from parent chart
        };

        _chart.redrawBrush = function (brushSelection, doTransition) {
            // override default x axis brush from parent chart
            _chart.fadeDeselectedArea(brushSelection);
        };

        return _chart.anchor(parent, chartGroup);
    }
}
<commit_msg>Convert bubble-chart to ES6 class<commit_after>import {BubbleMixin} from '../base/bubble-mixin';
import {CoordinateGridMixin} from '../base/coordinate-grid-mixin';
import {transition} from '../core/core';

/**
 * A concrete implementation of a general purpose bubble chart that allows data visualization using the
 * following dimensions:
 * - x axis position
 * - y axis position
 * - bubble radius
 * - color
 *
 * Examples:
 * - {@link http://dc-js.github.com/dc.js/ Nasdaq 100 Index}
 * - {@link http://dc-js.github.com/dc.js/vc/index.html US Venture Capital Landscape 2011}
 * @class bubbleChart
 * @memberof dc
 * @mixes dc.bubbleMixin
 * @mixes dc.coordinateGridMixin
 * @example
 * // create a bubble chart under #chart-container1 element using the default global chart group
 * var bubbleChart1 = dc.bubbleChart('#chart-container1');
 * // create a bubble chart under #chart-container2 element using chart group A
 * var bubbleChart2 = dc.bubbleChart('#chart-container2', 'chartGroupA');
 * @param {String|node|d3.selection} parent - Any valid
 * {@link https://github.com/d3/d3-selection/blob/master/README.md#select d3 single selector} specifying
 * a dom block element such as a div; or a dom element or d3 selection.
 * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in.
 * Interaction with a chart will only trigger events and redraws within the chart's group.
 * @returns {dc.bubbleChart}
 */
class BubbleChart extends BubbleMixin(CoordinateGridMixin) {
    constructor (parent, chartGroup) {
        super();

        this.transitionDuration(750);

        this.transitionDelay(0);

        // ES6: come back here after mixins have been converted
        this.renderBrush = () => {
            // override default x axis brush from parent chart
        };

        // ES6: come back here after mixins have been converted
        this.redrawBrush = (brushSelection, doTransition) => {
            // override default x axis brush from parent chart
            this.fadeDeselectedArea(brushSelection);
        };

        this.anchor(parent, chartGroup);
    }

    _bubbleLocator (d) {
        return 'translate(' + (this._bubbleX(d)) + ',' + (this._bubbleY(d)) + ')';
    }

    plotData () {
        this.calculateRadiusDomain();
        this.r().range([this.MIN_RADIUS, this.xAxisLength() * this.maxBubbleRelativeSize()]);

        const data = this.data();
        let bubbleG = this.chartBodyG().selectAll('g.' + this.BUBBLE_NODE_CLASS)
            .data(data, d => d.key);
        if (this.sortBubbleSize()) {
            // update dom order based on sort
            bubbleG.order();
        }

        this._removeNodes(bubbleG);

        bubbleG = this._renderNodes(bubbleG);

        this._updateNodes(bubbleG);

        this.fadeDeselectedArea(this.filter());
    }

    _renderNodes (bubbleG) {
        const bubbleGEnter = bubbleG.enter().append('g');

        bubbleGEnter
            .attr('class', this.BUBBLE_NODE_CLASS)
            .attr('transform', (d) => this._bubbleLocator(d))
            .append('circle').attr('class', (d, i) => this.BUBBLE_CLASS + ' _' + i)
            .on('click', this.onClick)
            .attr('fill', this.getColor)
            .attr('r', 0);

        bubbleG = bubbleGEnter.merge(bubbleG);

        transition(bubbleG, this.transitionDuration(), this.transitionDelay())
            .select('circle.' + this.BUBBLE_CLASS)
            .attr('r', d => this.bubbleR(d))
            .attr('opacity', d => (this.bubbleR(d) > 0) ? 1 : 0);

        this._doRenderLabel(bubbleGEnter);

        this._doRenderTitles(bubbleGEnter);

        return bubbleG;
    }

    _updateNodes (bubbleG) {
        transition(bubbleG, this.transitionDuration(), this.transitionDelay())
            .attr('transform', (d) => this._bubbleLocator(d))
            .select('circle.' + this.BUBBLE_CLASS)
            .attr('fill', this.getColor)
            .attr('r', d => this.bubbleR(d))
            .attr('opacity', d => (this.bubbleR(d) > 0) ? 1 : 0);

        this.doUpdateLabels(bubbleG);
        this.doUpdateTitles(bubbleG);
    }

    _removeNodes (bubbleG) {
        bubbleG.exit().remove();
    }

    _bubbleX (d) {
        let x = this.x()(this.keyAccessor()(d));
        if (isNaN(x) || !isFinite(x)) {
            x = 0;
        }
        return x;
    }

    _bubbleY (d) {
        let y = this.y()(this.valueAccessor()(d));
        if (isNaN(y) || !isFinite(y)) {
            y = 0;
        }
        return y;
    }

}

export const bubbleChart = (parent, chartGroup) => new BubbleChart(parent, chartGroup);
<|endoftext|>


<commit_before>'use strict';

const Koch = require('./_koch').default;
const Dragon = require('./_dragon').default;
const Hilbert = require('./_hilbert').default;

/**
 * When a message is received, calculate the points requested and post the results
 * back to the requesting script.
 * @param e
 */
onmessage = e => {
	try {
		let points;
		switch (e.data.algorithm) {
			case 'Hilbert':
				points = Hilbert.calculatePoints(e.data);
				break;
			case 'Koch':
				e.data.opts = {...e.data.opts, full: true};
				points = Koch.calculatePoints(e.data);
				break;
			case 'Cesàro':
				e.data.opts = {...e.data.opts, full: false};
				points = Koch.calculatePoints(e.data);
				break;
			case 'Dragon':
				points = Dragon.calculatePoints(e.data);
				break;
			default:
				points = [];
				break;
		}
		send({
			input: e.data,
			output: points
		});
	} catch (error) {
		send({
			input: e.data,
			error: error.message
		});
	}
};

/**
 * Send a message back to the calling script.
 * @param data
 */
function send (data) {
	postMessage(JSON.stringify(data));
}
<commit_msg>minor code cleanup<commit_after>'use strict';

const Koch = require('./_koch').default;
const Dragon = require('./_dragon').default;
const Hilbert = require('./_hilbert').default;

/**
 * When a message is received, calculate the points requested and post the results
 * back to the requesting script.
 * @param e
 */
onmessage = e => {
	try {
		let points;
		switch (e.data.algorithm) {
			case 'Hilbert':
				points = Hilbert.calculatePoints(e.data);
				break;
			case 'Koch':
			case 'Cesàro':
				e.data.opts = {...e.data.opts, full: e.data.algorithm === 'Koch'};
				points = Koch.calculatePoints(e.data);
				break;
			case 'Dragon':
				points = Dragon.calculatePoints(e.data);
				break;
			default:
				points = [];
				break;
		}
		send({
			input: e.data,
			output: points
		});
	} catch (error) {
		send({
			input: e.data,
			error: error.message
		});
	}
};

/**
 * Send a message back to the calling script.
 * @param data
 */
function send (data) {
	postMessage(JSON.stringify(data));
}
<|endoftext|>


<commit_before>;(function(undefined) {

  function injectScript() {
    var script = document.createElement('script'),
        body = document.getElementsByTagName('body')[0],
        workerscript = document.createElement('script');

    workerscript.src = chrome.runtime.getURL('RankTermsWebWorker.js');
    workerscript.type = 'text/javascript';
    workerscript.setAttribute('chrome', 'true');
    workerscript.setAttribute('id', 'worker-script')
    // Appending to body
    body.appendChild(workerscript);

    script.src = chrome.runtime.getURL('dime.logger.js');
    script.type = 'text/javascript';
    script.setAttribute('chrome', 'true');
    // Appending to body
    body.appendChild(script);

    window.addEventListener('message', function(event) {
      if(event.data && event.data.type && event.data.type === 'fromInjectedJStoHook') {
        console.log('hooking is done')
        chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
          if (request.data.url) {
              console.log('url changed, parsing page')
              window.postMessage({
                type: 'fromContentScriptNotifyURLChanged',
                message: request.data.url
              }, '*');
          }
        });

        window.addEventListener('message', function(event) {
          if(event.data && event.data.type && event.data.type === 'compiledResult') {
            let {pageURL, frequentTerms, pageTexts, imageURLs, hyperlinks, title, openGraphProtocol, metaTags} = event.data.pageData
            let tags = frequentTerms.slice(0,5).map((term)=> {
              return {
                '@type': 'Tag',
                text: term,
                //auto: true,
                //date: Date.now()
              }
            })
            let dataWithDimeStructure = {
              '@type': 'DesktopEvent',
              type: 'http://www.semanticdesktop.org/ontologies/2010/01/25/nuao/#UsageEvent',
              actor: 'DiMe browser extension',
              start: Date.now(),
              targettedResource: {
                title: title,
                '@type': 'Document',
                type: 'http://www.semanticdesktop.org/ontologies/2007/03/22/nfo/#PlainTextDocument',
                tags: tags,
                isStoredAs: 'http://www.semanticdesktop.org/ontologies/2007/03/22/nfo/#RemoteDataObject',
                mimeType: 'application/json',
                plainTextContent: JSON.stringify({pageTexts, frequentTerms, imageURLs, hyperlinks, openGraphProtocol, metaTags}),
                uri: pageURL,
              }
            }
            //var data = JSON.stringify(dataWithDimeStructure, undefined, 4)
            //var blob = new Blob([data], {type: 'text/json'}),
            //    e    = document.createEvent('MouseEvents'),
            //    a    = document.createElement('a')
            //a.download = 'hiit.json'
            //a.href = window.URL.createObjectURL(blob)
            //a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
            //e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
            //a.dispatchEvent(e)
            chrome.runtime.sendMessage({dataWithDimeStructure: dataWithDimeStructure}, (response) => {
                //console.log(response)
            });

          }
        });

      }

    });
  }
  const notLocalhost = /^http:\/\/\w+(\.\w+)*(:[0-9]+)?\/?(\/[.\w]*)*$/
  //Requesting variables from background page
  chrome.runtime.sendMessage({variable: 'enabled'}, function(response) {
    if (response.enabled)
      chrome.storage.local.get(['skipSites', 'disconnected'], (items)=> {
        let {skipSites, disconnected} = items
        if (disconnected)
          console.log('disconnected with dime, do nothing.')
        else
          if (skipSites.indexOf(window.location.href.replace(/.*?:\/\//g, "")) === -1 && !notLocalhost.test(window.location.href)) {
            console.log(`site is not in the filter list: ${skipSites}, continue`)
            injectScript();
          }
      })
    else
      console.log('dime extension is disable by user, wont do anything.')
  });
}).call(this);
<commit_msg>minor changes: deleted empty lines<commit_after>

  function injectScript() {
    var script = document.createElement('script'),
        body = document.getElementsByTagName('body')[0],
        workerscript = document.createElement('script');

    workerscript.src = chrome.runtime.getURL('RankTermsWebWorker.js');
    workerscript.type = 'text/javascript';
    workerscript.setAttribute('chrome', 'true');
    workerscript.setAttribute('id', 'worker-script')
    // Appending to body
    body.appendChild(workerscript);

    script.src = chrome.runtime.getURL('dime.logger.js');
    script.type = 'text/javascript';
    script.setAttribute('chrome', 'true');
    // Appending to body
    body.appendChild(script);

    window.addEventListener('message', function(event) {
      if(event.data && event.data.type && event.data.type === 'fromInjectedJStoHook') {
        console.log('hooking is done')
        chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
          if (request.data.url) {
              console.log('url changed, parsing page')
              window.postMessage({
                type: 'fromContentScriptNotifyURLChanged',
                message: request.data.url
              }, '*');
          }
        });

        window.addEventListener('message', function(event) {
          if(event.data && event.data.type && event.data.type === 'compiledResult') {
            let {pageURL, frequentTerms, pageTexts, imageURLs, hyperlinks, title, openGraphProtocol, metaTags} = event.data.pageData
            let tags = frequentTerms.slice(0,5).map((term)=> {
              return {
                '@type': 'Tag',
                text: term,
                //auto: true,
                //date: Date.now()
              }
            })
            let dataWithDimeStructure = {
              '@type': 'DesktopEvent',
              type: 'http://www.semanticdesktop.org/ontologies/2010/01/25/nuao/#UsageEvent',
              actor: 'DiMe browser extension',
              start: Date.now(),
              targettedResource: {
                title: title,
                '@type': 'Document',
                type: 'http://www.semanticdesktop.org/ontologies/2007/03/22/nfo/#PlainTextDocument',
                tags: tags,
                isStoredAs: 'http://www.semanticdesktop.org/ontologies/2007/03/22/nfo/#RemoteDataObject',
                mimeType: 'application/json',
                plainTextContent: JSON.stringify({pageTexts, frequentTerms, imageURLs, hyperlinks, openGraphProtocol, metaTags}),
                uri: pageURL,
              }
            }
            //var data = JSON.stringify(dataWithDimeStructure, undefined, 4)
            //var blob = new Blob([data], {type: 'text/json'}),
            //    e    = document.createEvent('MouseEvents'),
            //    a    = document.createElement('a')
            //a.download = 'hiit.json'
            //a.href = window.URL.createObjectURL(blob)
            //a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
            //e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
            //a.dispatchEvent(e)
            chrome.runtime.sendMessage({dataWithDimeStructure: dataWithDimeStructure}, (response) => {
                //console.log(response)
            });

          }
        });

      }

    });
  }
  const notLocalhost = /^http:\/\/\w+(\.\w+)*(:[0-9]+)?\/?(\/[.\w]*)*$/
  //Requesting variables from background page
  chrome.runtime.sendMessage({variable: 'enabled'}, function(response) {
    if (response.enabled)
      chrome.storage.local.get(['skipSites', 'disconnected'], (items)=> {
        let {skipSites, disconnected} = items
        if (disconnected)
          console.log('disconnected with dime, do nothing.')
        else
          if (skipSites.indexOf(window.location.href.replace(/.*?:\/\//g, "")) === -1 && !notLocalhost.test(window.location.href)) {
            console.log(`site is not in the filter list: ${skipSites}, continue`)
            injectScript();
          }
      })
    else
      console.log('dime extension is disable by user, wont do anything.')
  })
<|endoftext|>


<commit_before>'use strict';

var locationsInfo = [
['1st and Pike' , 23 , 65 ,6.3],
['SeaTac Airport', 3 ,24 , 1.2],
['Seattle Center', 11, 38 , 3.7],
['Capitol Hill', 20,38 , 2.3],
['Alki', 2 ,16 , 4.6],
];

function Store (name, minCustomer, maxCustomer, avgCookieSale) {
  this.name = name;
  this.minCustomer = minCustomer;
  this.maxCustomer = maxCustomer;
  this.avgCookieSale = avgCookieSale;
}

Store.prototype.customersPerHour = function() {
  return Math.random() * (this.maxCustomer - this.minCustomer) + this.minCustomer;
};

var stores = [];

for(var ea in locationsInfo){
  stores.push(
    new Store(
            locationsInfo[ea][0],
            locationsInfo[ea][1],
            locationsInfo[ea][2],
            locationsInfo[ea][3]
            )
  );
}

var hours = [ '6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm'];

for (var i = 0; i < stores.length; i += 1){
  var locationsStats = [];
  var store = stores[i];
  var totalCookiesSold = 0;
  for (var j = 0; j < hours.length; j += 1){
    var flooredNumber = Math.floor(store.avgCookieSale * store.customersPerHour());
    // | Int Value of average sold | String description
    locationsStats.push(flooredNumber);
    totalCookiesSold += flooredNumber;
  }
  console.log(locationsStats);
  store.locationsStats = locationsStats;
  store.totalCookiesSold = totalCookiesSold;
}

function creatingElementNameWithContent(node, content){
  var li = document.createElement(node);
  li.textContent = content;
  return li;
}

Store.prototype.renderStats = function(parentElement){
  // appends Name
  parentElement.appendChild(creatingElementNameWithContent('li', this.name));
  // appends All Hours
  for(var statKey in this.locationsStats){
    parentElement.appendChild(creatingElementNameWithContent(
        'li', this.locationsStats[statKey]
      ));
  }
  // appends the total sold per store
  parentElement.appendChild(creatingElementNameWithContent('li', this.totalCookiesSold));
};

var parentMyElement = document.getElementById('mylistsOfStats');

for (var each = 0; each < stores.length; each += 1){
  var eachStore = stores[each];
  var article = document.createElement('article');
  parentMyElement.appendChild(article);
  //TODO: HEADER
  var ul = document.createElement('ul');
  article.appendChild(ul);
  eachStore.renderStats(ul);
  //TODO: FOOTER
}
<commit_msg>added header code<commit_after>'use strict';

var locationsInfo = [
['1st and Pike' , 23 , 65 ,6.3],
['SeaTac Airport', 3 ,24 , 1.2],
['Seattle Center', 11, 38 , 3.7],
['Capitol Hill', 20,38 , 2.3],
['Alki', 2 ,16 , 4.6],
];

function Store (name, minCustomer, maxCustomer, avgCookieSale) {
  this.name = name;
  this.minCustomer = minCustomer;
  this.maxCustomer = maxCustomer;
  this.avgCookieSale = avgCookieSale;
}

Store.prototype.customersPerHour = function() {
  return Math.random() * (this.maxCustomer - this.minCustomer) + this.minCustomer;
};

var stores = [];
var hours = [ '6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm'];
for(var ea in locationsInfo){
  stores.push(
    new Store(
            locationsInfo[ea][0],
            locationsInfo[ea][1],
            locationsInfo[ea][2],
            locationsInfo[ea][3]
            )
  );
}
function renderTableHeader(parent){
  var tr = document.createElement('tr');

  tr.appendChild(creatingElementNameWithContent('th', 'Store Name'));
  for (var each in hours) {
    tr.appendChild(creatingElementNameWithContent('th', hours[each]));
  }
  tr.appendChild(creatingElementNameWithContent('th', 'Daily Location Total'));

  parent.appendChild(tr);
}

for (var i = 0; i < stores.length; i += 1){
  var locationsStats = [];
  var store = stores[i];
  var totalCookiesSold = 0;
  for (var j = 0; j < hours.length; j += 1){
    var flooredNumber = Math.floor(store.avgCookieSale * store.customersPerHour());
    // | Int Value of average sold | String description
    locationsStats.push(flooredNumber);
    totalCookiesSold += flooredNumber;
  }
  console.log(locationsStats);
  store.locationsStats = locationsStats;
  store.totalCookiesSold = totalCookiesSold;
}

function creatingElementNameWithContent(node, content){
  var li = document.createElement(node);
  li.textContent = content;
  return li;
}

Store.prototype.renderStats = function(parentElement){
  // appends Name
  parentElement.appendChild(creatingElementNameWithContent('li', this.name));
  // appends All Hours
  for(var statKey in this.locationsStats){
    parentElement.appendChild(creatingElementNameWithContent(
        'li', this.locationsStats[statKey]
      ));
  }
  // appends the total sold per store
  parentElement.appendChild(creatingElementNameWithContent('li', this.totalCookiesSold));
};

var parentMyElement = document.getElementById('mylistsOfStats');
var table = document.createElement('table');
renderTableHeader(table);
parentMyElement.appendChild(table);

for (var each = 0; each < stores.length; each += 1){
  var eachStore = stores[each];
  var article = document.createElement('article');
  parentMyElement.appendChild(article);
  //TODO: HEADER
  var ul = document.createElement('ul');
  article.appendChild(ul);
  eachStore.renderStats(ul);
  //TODO: FOOTER
}
<|endoftext|>