<commit_before>function draw(groups, renderFn, completeFn) {
  $.ajax({
    url: "/api/v1/pipelines/" + concourse.pipelineName + "/jobs",
    dataType: "json",
    complete: completeFn,
    success: function(jobs) {
      $.ajax({
        url: "/api/v1/pipelines/" + concourse.pipelineName + "/resources",
        dataType: "json",
        success: function(resources) {
          renderFn(jobs, resources);
        }
      });
    }
  });
}

var currentHighlight;

function drawContinuously(svg, groups) {
  draw(groups, function(jobs, resources) {
    var graph = createGraph(svg, groups, jobs, resources);

    svg.selectAll("g.edge").remove();
    svg.selectAll("g.node").remove();

    var svgEdges = svg.selectAll("g.edge")
      .data(graph.edges());

    svgEdges.exit().remove();

    var svgNodes = svg.selectAll("g.node")
      .data(graph.nodes());

    svgNodes.exit().remove();

    var svgEdge = svgEdges.enter().append("g")
      .attr("class", function(edge) { return "edge " + edge.source.node.status })

    function highlight(thing) {
      if (!thing.key) {
        return
      }

      currentHighlight = thing.key;

      svgEdges.each(function(edge) {
        if (edge.source.key == thing.key) {
          d3.select(this).classed({
            active: true
          })
        }
      })

      svgNodes.each(function(node) {
        if (node.key == thing.key) {
          d3.select(this).classed({
            active: true
          })
        }
      })
    }

    function lowlight(thing) {
      if (!thing.key) {
        return
      }

      currentHighlight = undefined;

      svgEdges.classed({ active: false })
      svgNodes.classed({ active: false })
    }

    var svgNode = svgNodes.enter().append("g")
      .attr("class", function(node) { return "node " + node.class })
      .on("mouseover", highlight)
      .on("mouseout", lowlight)

    var nodeLink = svgNode.append("svg:a")
      .attr("xlink:href", function(node) { return node.url })

    var jobStatusBackground = nodeLink.append("rect")
      .attr("height", function(node) { return node.height() })

    var animatableBackground = nodeLink.append("foreignObject")
      .attr("height", function(node) { return node.height() })

    var animationTarget = animatableBackground.append("xhtml:div")

    animationTarget.style("height", function(node) { return node.height() + "px" })

    nodeLink.append("text")
      .text(function(node) { return node.name })
      .attr("dominant-baseline", "middle")
      .attr("text-anchor", "middle")
      .attr("x", function(node) { return node.width() / 2 })
      .attr("y", function(node) { return node.height() / 2 })

    jobStatusBackground.attr("width", function(node) { return node.width() })
    animatableBackground.attr("width", function(node) { return node.width() })
    animationTarget.style("width", function(node) { return node.width() + "px" })

    graph.layout()

    svgNode.attr("transform", function(node) {
      var position = node.position();
      return "translate("+position.x+", "+position.y+")"
    })

    svgEdge.append("path")
      .attr("d", function(edge) { return edge.path() })
      .on("mouseover", highlight)
      .on("mouseout", lowlight)

    var bbox = svg.node().getBBox();
    d3.select(svg.node().parentNode)
      .attr("viewBox", "" + (bbox.x - 20) + " " + (bbox.y - 20) + " " + (bbox.width + 40) + " " + (bbox.height + 40))

    if (currentHighlight) {
      svgNodes.each(function(node) {
        if (node.key == currentHighlight) {
          highlight(node)
        }
      });

      svgEdges.each(function(node) {
        if (node.key == currentHighlight) {
          highlight(node)
        }
      });
    }
  }, function() {
    setTimeout(function() {
      drawContinuously(svg, groups)
    }, 4000);
  });
}

function renderPipeline(groups) {
  var svg = d3.select("#pipeline")
    .append("svg")
      .attr("width", "100%")
      .attr("height", "100%");

  svg.append("defs").append("filter")
    .attr("id", "embiggen")
    .append("feMorphology")
    .attr("operator", "dilate")
    .attr("radius", "4")

  var g = svg.append("g");

  svg.on("mousedown", function() {
    var ev = d3.event;
    if (ev.button || ev.ctrlKey)
      ev.stopImmediatePropagation();
  }).call(d3.behavior.zoom().scaleExtent([0.5, 10]).on("zoom", function() {
    var ev = d3.event;
    g.attr("transform", "translate(" + ev.translate + ") scale(" + ev.scale + ")");
  }));

  drawContinuously(g, groups);

  $("ul.groups li:not(.main) a").click(function(e) {
    var group = e.target.text;

    if (e.shiftKey) {
      groups[group] = !groups[group];
    } else {
      for (var name in groups) {
        groups[name] = name == group;
      }
    }

    var groupQueries = [];
    for (var name in groups) {
      if (groups[name]) {
        groupQueries.push("groups="+name);
      }
    }

    window.location.search = "?" + groupQueries.join("&");

    return false;
  });
}

function createGraph(svg, groups, jobs, resources) {
  var graph = new Graph();

  var resourceURLs = {};
  var resourceCheckErrors = {};
  var resourcePaused = {};

  for (var i in resources) {
    var resource = resources[i];
    resourceURLs[resource.name] = resource.url;
    resourceCheckErrors[resource.name] = resource.check_error;
    resourcePaused[resource.name] = resource.paused;
  }

  for (var i in jobs) {
    var job = jobs[i];

    if (!groupsMatch(job.groups, groups)) {
      continue;
    }

    var id = jobNode(job.name);

    var classes = ["job"];

    var url = job.url;
    if (job.next_build) {
      url = job.next_build.url;
    } else if (job.finished_build) {
      url = job.finished_build.url;
    }

    var status;
    if (job.paused) {
      status = "paused";
    } else if (job.finished_build) {
      status = job.finished_build.status
    } else {
      status = "pending";
    }

    classes.push(status);

    if (job.next_build) {
      classes.push("started");
    }

    graph.setNode(id, new Node({
      id: id,
      name: job.name,
      class: classes.join(" "),
      status: status,
      url: url,
      svg: svg
    }));
  }

  // populate job output nodes and edges
  for (var i in jobs) {
    var job = jobs[i];
    var id = jobNode(job.name);

    if (!groupsMatch(job.groups, groups)) {
      continue;
    }

    for (var j in job.outputs) {
      var output = job.outputs[j];

      var outputId = outputNode(job.name, output.resource);

      graph.setNode(outputId, new Node({
        id: outputId,
        name: output.resource,
        key: output.resource,
        class: "output",
        url: resourceURLs[output.resource],
        svg: svg
      }));

      graph.addEdge(id, outputId, output.resource)
    }
  }

  // populate dependant job input edges
  //
  // do this first as this is what primarily determines node ranks
  for (var i in jobs) {
    var job = jobs[i];
    var id = jobNode(job.name);

    if (!groupsMatch(job.groups, groups)) {
      continue;
    }

    for (var j in job.inputs) {
      var input = job.inputs[j];

      if (input.passed && input.passed.length > 0) {
        for (var p in input.passed) {
          var sourceJobNode = jobNode(input.passed[p]);

          var sourceOutputNode = outputNode(input.passed[p], input.resource);
          var sourceInputNode = inputNode(input.passed[p], input.resource);

          var sourceNode;
          if (graph.node(sourceOutputNode)) {
            sourceNode = sourceOutputNode;
          } else {
            if (!graph.node(sourceInputNode)) {
              graph.setNode(sourceInputNode, new Node({
                id: sourceInputNode,
                name: input.resource,
                key: input.resource,
                class: "constrained-input",
                url: resourceURLs[input.resource],
                svg: svg
              }));
            }

            if (graph.node(sourceJobNode)) {
              graph.addEdge(sourceJobNode, sourceInputNode, input.resource);
            }

            sourceNode = sourceInputNode;
          }

          graph.addEdge(sourceNode, id, input.resource);
        }
      }
    }
  }

  // populate unconstrained job inputs
  //
  // now that we know the rank, draw one unconstrained input per rank
  for (var i in jobs) {
    var job = jobs[i];
    var id = jobNode(job.name);

    if (!groupsMatch(job.groups, groups)) {
      continue;
    }

    var node = graph.node(id);

    for (var j in job.inputs) {
      var input = job.inputs[j];
      var status = "";

      if (!input.passed || input.passed.length == 0) {
        var inputId = inputNode(job.name, input.resource+"-unconstrained");

        if (!graph.node(inputId)) {
          var classes = "input";
          if (resourceCheckErrors[input.resource]) {
            classes += " failing";
          }

          if (resourcePaused[input.resource]) {
            classes += " paused";
            status = "paused";
          }

          graph.setNode(inputId, new Node({
            id: inputId,
            name: input.resource,
            key: input.resource,
            class: classes,
            status: status,
            url: resourceURLs[input.resource],
            svg: svg,
            equivalentBy: input.resource+"-unconstrained",
          }));
        }

        graph.addEdge(inputId, id, input.resource)
      }
    }
  }

  graph.computeRanks();
  graph.collapseEquivalentNodes();

  return graph;
}

function objectIsEmpty(o) {
  for (var x in o) {
    return false;
  }

  return true;
}

function groupsMatch(objGroups, groups) {
  if (objectIsEmpty(groups)) {
    return true;
  }

  for(var i in objGroups) {
    if (groups[objGroups[i]]) {
      return true;
    }
  }

  return false;
}

function groupNode(name) {
  return "group-"+name;
}

function resourceNode(name) {
  return "resource-"+name;
}

function jobNode(name) {
  return "job-"+name;
}

function gatewayNode(jobNames) {
  return "gateway-"+jobNames.sort().join("-");
}

function outputNode(jobName, resourceName) {
  return "job-"+jobName+"-output-"+resourceName;
}

function inputNode(jobName, resourceName) {
  return "job-"+jobName+"-input-"+resourceName;
}
<commit_msg>fix janky redrawing in most browsers<commit_after>function draw(groups, renderFn, completeFn) {
  $.ajax({
    url: "/api/v1/pipelines/" + concourse.pipelineName + "/jobs",
    dataType: "json",
    complete: completeFn,
    success: function(jobs) {
      $.ajax({
        url: "/api/v1/pipelines/" + concourse.pipelineName + "/resources",
        dataType: "json",
        success: function(resources) {
          renderFn(jobs, resources);
        }
      });
    }
  });
}

var currentHighlight;

function drawContinuously(svg, groups) {
  draw(groups, function(jobs, resources) {
    // reset viewbox so calculations are done from a blank slate.
    //
    // without this text and boxes jump around on every redraw,
    // in affected browsers (seemingly anything but Chrome + OS X).
    d3.select(svg.node().parentNode).attr("viewBox", "")

    var graph = createGraph(svg, groups, jobs, resources);

    svg.selectAll("g.edge").remove();
    svg.selectAll("g.node").remove();

    var svgEdges = svg.selectAll("g.edge")
      .data(graph.edges());

    svgEdges.exit().remove();

    var svgNodes = svg.selectAll("g.node")
      .data(graph.nodes());

    svgNodes.exit().remove();

    var svgEdge = svgEdges.enter().append("g")
      .attr("class", function(edge) { return "edge " + edge.source.node.status })

    function highlight(thing) {
      if (!thing.key) {
        return
      }

      currentHighlight = thing.key;

      svgEdges.each(function(edge) {
        if (edge.source.key == thing.key) {
          d3.select(this).classed({
            active: true
          })
        }
      })

      svgNodes.each(function(node) {
        if (node.key == thing.key) {
          d3.select(this).classed({
            active: true
          })
        }
      })
    }

    function lowlight(thing) {
      if (!thing.key) {
        return
      }

      currentHighlight = undefined;

      svgEdges.classed({ active: false })
      svgNodes.classed({ active: false })
    }

    var svgNode = svgNodes.enter().append("g")
      .attr("class", function(node) { return "node " + node.class })
      .on("mouseover", highlight)
      .on("mouseout", lowlight)

    var nodeLink = svgNode.append("svg:a")
      .attr("xlink:href", function(node) { return node.url })

    var jobStatusBackground = nodeLink.append("rect")
      .attr("height", function(node) { return node.height() })

    var animatableBackground = nodeLink.append("foreignObject")
      .attr("height", function(node) { return node.height() })

    var animationTarget = animatableBackground.append("xhtml:div")

    animationTarget.style("height", function(node) { return node.height() + "px" })

    nodeLink.append("text")
      .text(function(node) { return node.name })
      .attr("dominant-baseline", "middle")
      .attr("text-anchor", "middle")
      .attr("x", function(node) { return node.width() / 2 })
      .attr("y", function(node) { return node.height() / 2 })

    jobStatusBackground.attr("width", function(node) { return node.width() })
    animatableBackground.attr("width", function(node) { return node.width() })
    animationTarget.style("width", function(node) { return node.width() + "px" })

    graph.layout()

    svgNode.attr("transform", function(node) {
      var position = node.position();
      return "translate("+position.x+", "+position.y+")"
    })

    svgEdge.append("path")
      .attr("d", function(edge) { return edge.path() })
      .on("mouseover", highlight)
      .on("mouseout", lowlight)

    var bbox = svg.node().getBBox();
    d3.select(svg.node().parentNode)
      .attr("viewBox", "" + (bbox.x - 20) + " " + (bbox.y - 20) + " " + (bbox.width + 40) + " " + (bbox.height + 40))

    if (currentHighlight) {
      svgNodes.each(function(node) {
        if (node.key == currentHighlight) {
          highlight(node)
        }
      });

      svgEdges.each(function(node) {
        if (node.key == currentHighlight) {
          highlight(node)
        }
      });
    }
  }, function() {
    setTimeout(function() {
      drawContinuously(svg, groups)
    }, 4000);
  });
}

function renderPipeline(groups) {
  var svg = d3.select("#pipeline")
    .append("svg")
      .attr("width", "100%")
      .attr("height", "100%");

  svg.append("defs").append("filter")
    .attr("id", "embiggen")
    .append("feMorphology")
    .attr("operator", "dilate")
    .attr("radius", "4")

  var g = svg.append("g");

  svg.on("mousedown", function() {
    var ev = d3.event;
    if (ev.button || ev.ctrlKey)
      ev.stopImmediatePropagation();
  }).call(d3.behavior.zoom().scaleExtent([0.5, 10]).on("zoom", function() {
    var ev = d3.event;
    g.attr("transform", "translate(" + ev.translate + ") scale(" + ev.scale + ")");
  }));

  drawContinuously(g, groups);

  $("ul.groups li:not(.main) a").click(function(e) {
    var group = e.target.text;

    if (e.shiftKey) {
      groups[group] = !groups[group];
    } else {
      for (var name in groups) {
        groups[name] = name == group;
      }
    }

    var groupQueries = [];
    for (var name in groups) {
      if (groups[name]) {
        groupQueries.push("groups="+name);
      }
    }

    window.location.search = "?" + groupQueries.join("&");

    return false;
  });
}

function createGraph(svg, groups, jobs, resources) {
  var graph = new Graph();

  var resourceURLs = {};
  var resourceCheckErrors = {};
  var resourcePaused = {};

  for (var i in resources) {
    var resource = resources[i];
    resourceURLs[resource.name] = resource.url;
    resourceCheckErrors[resource.name] = resource.check_error;
    resourcePaused[resource.name] = resource.paused;
  }

  for (var i in jobs) {
    var job = jobs[i];

    if (!groupsMatch(job.groups, groups)) {
      continue;
    }

    var id = jobNode(job.name);

    var classes = ["job"];

    var url = job.url;
    if (job.next_build) {
      url = job.next_build.url;
    } else if (job.finished_build) {
      url = job.finished_build.url;
    }

    var status;
    if (job.paused) {
      status = "paused";
    } else if (job.finished_build) {
      status = job.finished_build.status
    } else {
      status = "pending";
    }

    classes.push(status);

    if (job.next_build) {
      classes.push("started");
    }

    graph.setNode(id, new Node({
      id: id,
      name: job.name,
      class: classes.join(" "),
      status: status,
      url: url,
      svg: svg
    }));
  }

  // populate job output nodes and edges
  for (var i in jobs) {
    var job = jobs[i];
    var id = jobNode(job.name);

    if (!groupsMatch(job.groups, groups)) {
      continue;
    }

    for (var j in job.outputs) {
      var output = job.outputs[j];

      var outputId = outputNode(job.name, output.resource);

      graph.setNode(outputId, new Node({
        id: outputId,
        name: output.resource,
        key: output.resource,
        class: "output",
        url: resourceURLs[output.resource],
        svg: svg
      }));

      graph.addEdge(id, outputId, output.resource)
    }
  }

  // populate dependant job input edges
  //
  // do this first as this is what primarily determines node ranks
  for (var i in jobs) {
    var job = jobs[i];
    var id = jobNode(job.name);

    if (!groupsMatch(job.groups, groups)) {
      continue;
    }

    for (var j in job.inputs) {
      var input = job.inputs[j];

      if (input.passed && input.passed.length > 0) {
        for (var p in input.passed) {
          var sourceJobNode = jobNode(input.passed[p]);

          var sourceOutputNode = outputNode(input.passed[p], input.resource);
          var sourceInputNode = inputNode(input.passed[p], input.resource);

          var sourceNode;
          if (graph.node(sourceOutputNode)) {
            sourceNode = sourceOutputNode;
          } else {
            if (!graph.node(sourceInputNode)) {
              graph.setNode(sourceInputNode, new Node({
                id: sourceInputNode,
                name: input.resource,
                key: input.resource,
                class: "constrained-input",
                url: resourceURLs[input.resource],
                svg: svg
              }));
            }

            if (graph.node(sourceJobNode)) {
              graph.addEdge(sourceJobNode, sourceInputNode, input.resource);
            }

            sourceNode = sourceInputNode;
          }

          graph.addEdge(sourceNode, id, input.resource);
        }
      }
    }
  }

  // populate unconstrained job inputs
  //
  // now that we know the rank, draw one unconstrained input per rank
  for (var i in jobs) {
    var job = jobs[i];
    var id = jobNode(job.name);

    if (!groupsMatch(job.groups, groups)) {
      continue;
    }

    var node = graph.node(id);

    for (var j in job.inputs) {
      var input = job.inputs[j];
      var status = "";

      if (!input.passed || input.passed.length == 0) {
        var inputId = inputNode(job.name, input.resource+"-unconstrained");

        if (!graph.node(inputId)) {
          var classes = "input";
          if (resourceCheckErrors[input.resource]) {
            classes += " failing";
          }

          if (resourcePaused[input.resource]) {
            classes += " paused";
            status = "paused";
          }

          graph.setNode(inputId, new Node({
            id: inputId,
            name: input.resource,
            key: input.resource,
            class: classes,
            status: status,
            url: resourceURLs[input.resource],
            svg: svg,
            equivalentBy: input.resource+"-unconstrained",
          }));
        }

        graph.addEdge(inputId, id, input.resource)
      }
    }
  }

  graph.computeRanks();
  graph.collapseEquivalentNodes();

  return graph;
}

function objectIsEmpty(o) {
  for (var x in o) {
    return false;
  }

  return true;
}

function groupsMatch(objGroups, groups) {
  if (objectIsEmpty(groups)) {
    return true;
  }

  for(var i in objGroups) {
    if (groups[objGroups[i]]) {
      return true;
    }
  }

  return false;
}

function groupNode(name) {
  return "group-"+name;
}

function resourceNode(name) {
  return "resource-"+name;
}

function jobNode(name) {
  return "job-"+name;
}

function gatewayNode(jobNames) {
  return "gateway-"+jobNames.sort().join("-");
}

function outputNode(jobName, resourceName) {
  return "job-"+jobName+"-output-"+resourceName;
}

function inputNode(jobName, resourceName) {
  return "job-"+jobName+"-input-"+resourceName;
}
<|endoftext|>


<commit_before>(function () {
  angular.module('ui.grid').config(['$provide', function($provide) {
    $provide.decorator('i18nService', ['$delegate', function($delegate) {
      $delegate.add('nl', {
        aggregate: {
          label: 'items'
        },
        groupPanel: {
          description: 'Sleep hier een kolomnaam heen om op te groeperen.'
        },
        search: {
          placeholder: 'Zoeken...',
          showingItems: 'Getoonde items:',
          selectedItems: 'Geselecteerde items:',
          totalItems: 'Totaal aantal items:',
          size: 'Items per pagina:',
          first: 'Eerste pagina',
          next: 'Volgende pagina',
          previous: 'Vorige pagina',
          last: 'Laatste pagina'
        },
        menu: {
          text: 'Kies kolommen:'
        },
        sort: {
          ascending: 'Sorteer oplopend',
          descending: 'Sorteer aflopend',
          remove: 'Verwijder sortering'
        },
        column: {
          hide: 'Verberg kolom'
        },
        aggregation: {
          count: 'Aantal rijen: ',
          sum: 'Som: ',
          avg: 'Gemiddelde: ',
          min: 'Min: ',
          max: 'Max: '
        },
        pinning: {
          pinLeft: 'Zet links vast',
          pinRight: 'Zet rechts vast',
          unpin: 'Maak los'
        },
        gridMenu: {
          columns: 'Kolommen:',
          importerTitle: 'Importeer bestand',
          exporterAllAsCsv: 'Exporteer alle data als csv',
          exporterVisibleAsCsv: 'Exporteer zichtbare data als csv',
          exporterSelectedAsCsv: 'Exporteer geselecteerde data als csv',
          exporterAllAsPdf: 'Exporteer alle data als pdf',
          exporterVisibleAsPdf: 'Exporteer zichtbare data als pdf',
          exporterSelectedAsPdf: 'Exporteer geselecteerde data als pdf',
          exporterAllAsExcel: 'Exporteer alle data als excel',
          exporterVisibleAsExcel: 'Exporteer zichtbare data als excel',
          exporterSelectedAsExcel: 'Exporteer alle data als excel',
          clearAllFilters: 'Reinig alle filters'
        },
        importer: {
          noHeaders: 'Kolomnamen kunnen niet worden afgeleid. Heeft het bestand een header?',
          noObjects: 'Objecten kunnen niet worden afgeleid. Bevat het bestand data naast de headers?',
          invalidCsv: 'Het bestand kan niet verwerkt worden. Is het een valide csv bestand?',
          invalidJson: 'Het bestand kan niet verwerkt worden. Is het valide json?',
          jsonNotArray: 'Het json bestand moet een array bevatten. De actie wordt geannuleerd.'
        },
        pagination: {
            sizes: 'items per pagina',
            totalItems: 'items',
            of: 'van de'
        },
        grouping: {
            group: 'Groepeer',
            ungroup: 'Groepering opheffen',
            aggregate_count: 'Agg: Aantal',
            aggregate_sum: 'Agg: Som',
            aggregate_max: 'Agg: Max',
            aggregate_min: 'Agg: Min',
            aggregate_avg: 'Agg: Gem',
            aggregate_remove: 'Agg: Verwijder'
        }
      });
      return $delegate;
    }]);
  }]);
})();
<commit_msg>fix(core): change translation in in i18n nl.js for clearAllFilters<commit_after>(function () {
  angular.module('ui.grid').config(['$provide', function($provide) {
    $provide.decorator('i18nService', ['$delegate', function($delegate) {
      $delegate.add('nl', {
        aggregate: {
          label: 'items'
        },
        groupPanel: {
          description: 'Sleep hier een kolomnaam heen om op te groeperen.'
        },
        search: {
          placeholder: 'Zoeken...',
          showingItems: 'Getoonde items:',
          selectedItems: 'Geselecteerde items:',
          totalItems: 'Totaal aantal items:',
          size: 'Items per pagina:',
          first: 'Eerste pagina',
          next: 'Volgende pagina',
          previous: 'Vorige pagina',
          last: 'Laatste pagina'
        },
        menu: {
          text: 'Kies kolommen:'
        },
        sort: {
          ascending: 'Sorteer oplopend',
          descending: 'Sorteer aflopend',
          remove: 'Verwijder sortering'
        },
        column: {
          hide: 'Verberg kolom'
        },
        aggregation: {
          count: 'Aantal rijen: ',
          sum: 'Som: ',
          avg: 'Gemiddelde: ',
          min: 'Min: ',
          max: 'Max: '
        },
        pinning: {
          pinLeft: 'Zet links vast',
          pinRight: 'Zet rechts vast',
          unpin: 'Maak los'
        },
        gridMenu: {
          columns: 'Kolommen:',
          importerTitle: 'Importeer bestand',
          exporterAllAsCsv: 'Exporteer alle data als csv',
          exporterVisibleAsCsv: 'Exporteer zichtbare data als csv',
          exporterSelectedAsCsv: 'Exporteer geselecteerde data als csv',
          exporterAllAsPdf: 'Exporteer alle data als pdf',
          exporterVisibleAsPdf: 'Exporteer zichtbare data als pdf',
          exporterSelectedAsPdf: 'Exporteer geselecteerde data als pdf',
          exporterAllAsExcel: 'Exporteer alle data als excel',
          exporterVisibleAsExcel: 'Exporteer zichtbare data als excel',
          exporterSelectedAsExcel: 'Exporteer alle data als excel',
          clearAllFilters: 'Alle filters wissen'
        },
        importer: {
          noHeaders: 'Kolomnamen kunnen niet worden afgeleid. Heeft het bestand een header?',
          noObjects: 'Objecten kunnen niet worden afgeleid. Bevat het bestand data naast de headers?',
          invalidCsv: 'Het bestand kan niet verwerkt worden. Is het een valide csv bestand?',
          invalidJson: 'Het bestand kan niet verwerkt worden. Is het valide json?',
          jsonNotArray: 'Het json bestand moet een array bevatten. De actie wordt geannuleerd.'
        },
        pagination: {
            sizes: 'items per pagina',
            totalItems: 'items',
            of: 'van de'
        },
        grouping: {
            group: 'Groepeer',
            ungroup: 'Groepering opheffen',
            aggregate_count: 'Agg: Aantal',
            aggregate_sum: 'Agg: Som',
            aggregate_max: 'Agg: Max',
            aggregate_min: 'Agg: Min',
            aggregate_avg: 'Agg: Gem',
            aggregate_remove: 'Agg: Verwijder'
        }
      });
      return $delegate;
    }]);
  }]);
})();
<|endoftext|>


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

  addAnswersToSessionStorage();
  updateAvatar('introduction', 'sleeping-lion');
  updateAvatar('finish', 'finish__lion');
  const finishPrompt = document.getElementsByClassName("finish__prompt")[0];

  $('.carousel').carousel({
    indicators: true,
    shift: 100
  });

  anime({
    targets: '#strange',
    translateY: '-5px',
    rotate: [-0.5, 0.5],
    easing: 'easeInOutSine',
    duration: 4000,
    direction: 'alternate',
    loop: true,
  });

  anime({
    targets: '#happy',
    rotate: 1,
    translateY: ['-2px', '-9px'],
    easing: 'easeInOutSine',
    duration: 4000,
    direction: 'alternate',
    loop: true,
  });

  anime({
    targets: '#sad',
    translateX: '-20px',
    rotate: [-1, -2],
    easing: 'easeInOutSine',
    duration: 4000,
    direction: 'alternate',
    loop: true,
  });

  anime({
    targets: '#boring',
    translateX: '2px',
    translateY: '-2px',
    rotate: -1,
    easing: 'easeInOutSine',
    duration: 4000,
    direction: 'alternate',
    loop: true
  });

  anime({
    targets: '#angry',
    translateX: '-5px',
    translateY: '15px',
    rotate: [-1, -2],
    easing: 'easeInOutSine',
    duration: 5000,
    direction: 'alternate',
    loop: true
  });

  anime({
    targets: '#kind',
    translateX: '-20px',
    translateY: '5px',
    rotate: -3,
    easing: 'easeInOutSine',
    duration: 4000,
    direction: 'alternate',
    loop: true
  });

  anime({
    targets: '#fun',
    translateX: '-20px',
    translateY: '5px',
    rotate: -1.5,
    easing: 'easeInOutSine',
    duration: 5000,
    direction: 'alternate',
    loop: true
  });

  [
    'lion',
    'bear',
    'monkey'
  ].forEach(function (avatar) {
    var node = document.getElementsByClassName(avatar)[0];
    if (!node ) return;
    node.addEventListener('click', function () {
      var checkmark = node.getElementsByClassName('checkmark')[0];
      if ( !checkmark ) {
        addCheckmark(node);
        location.href = '/introduction';
      } else {
        node.removeChild(checkmark);
      }
    });
  });

  function addCheckmark (node) {
    var checkmark = document.createElement('DIV');
    checkmark.classList.add('checkmark');
    node.appendChild(checkmark);
  }

  function updateAvatar (selector, avatarSelector) {
    var page = document.getElementsByClassName(selector)[0];
    if (!page) return;
    var avatarImg = page.getElementsByClassName(avatarSelector)[0];
    var avatar = sessionStorage.getItem('avatar');
    avatarImg.src = 'assets/' + avatar + '.svg';
  }

  [
    "send-email-button"
  ].forEach(function(button){
    var node = document.getElementsByClassName(button)[0];
    if (node){
      node.addEventListener('click', function(){ sendMail() });
    }
  });

  function addAnswersToSessionStorage(){
    var personality = [];
    var hobbies = [];

    [
      'lion',
      'bear',
      'monkey'
    ].forEach(function (avatar) {
      var node = document.getElementsByClassName(avatar)[0];
      addClickEventSingle('avatar', node, avatar);
    });

    [
      "strange",
      "happy",
      "angry",
      "fun",
      "boring",
      "kind",
      "sad"
    ].forEach(function(emotion){
      var node = document.getElementById(emotion);
      addClassToNode(node, 'pop');
      addClickEventArray('personality', node, emotion, personality);
    });

    [
      "sad-emoji",
      "happy-emoji",
      "indifferent-emoji"
    ].forEach(function(emoji){
      var node = document.getElementsByClassName(emoji)[0];
      addClickEventSingle('feelings', node, emoji.match(/^[a-z]+/));
    });

    [
      "name",
      "age"
    ].forEach(function(inputField){
      var node = document.getElementsByClassName(inputField)[0];
      addKeyupEvent(inputField, node);
    });

    [
      "football",
      "tennis",
      "music",
      "dance",
      "drawing",
      "photography",
      "cooking",
      "gardening",
      "puzzles",
      "camping",
      "fishing",
      "walking"
    ].forEach(function(hobby){
      var node = document.getElementById(hobby);
      addClickEventArray('hobbies', node, hobby, hobbies);
    });

    [
      "school__range",
      "friends__range",
      "sleep__range"
    ].forEach(function(range){
      var node = document.getElementsByClassName(range)[0];
      addOnInputToElement(node, function(key, value){
        if (range === "sleep__range") {
          sleepingLion();
        } else {
          emojiSprite();
        }
        addSingleValueToStorage(key, value);
      });
    });

    [
      "eating__range"
    ].forEach(function(range) {
      var node = document.getElementsByClassName(range)[0];
      addOnInputToElement(node, function(key, value) {
        addSingleValueToStorage(key, value);
      });
    });

    [
      "frineds__like",
      "frineds__dislike",
      "school__like",
      "school__dislike"
    ].forEach(function(textarea){
      var node = document.getElementsByClassName(textarea)[0];
      addKeyupEvent(textarea, node);
    });

    function addKeyupEvent(key, element){
      if(!element){ return; }
      element.addEventListener("keyup", function(){
        addSingleValueToStorage(key, element.value);
      });
    }

    function addClickEventSingle(key, element, value){
      if(!element){ return; }
      element.addEventListener("click", function(){
        addSingleValueToStorage(key, value);
      });
    }

    function addClickEventArray(key, element, value, array){
      if(!element){ return; }
      element.addEventListener("click", function(){
        addValueToArray(key, value, array);
      });
    }

    function addValueToArray(key, value, array){
      array.push(value);
      addArrayToStorage(key, array);
    }

    function addSingleValueToStorage(key, value){
      sessionStorage.setItem(key, value);
    }

    // JSON.stringify() is used here as session storage only supports strings
    function addArrayToStorage(key, array){
      sessionStorage.setItem(key, JSON.stringify(array));
    }
  }

  // Adds a class to node
  function addClassToNode(node, className){
    if (!node){ return; }
    node.addEventListener("click", function(){
      node.classList.add(className);
    });
  }

  function sleepingLion(){
    var value = document.getElementsByClassName("sleep__range")[0].value;
    var element = document.getElementsByClassName("sleep__sleeping-lion")[0];
    changeBackgroundPosition(element, value, -332);
  }

  function changeBackgroundPosition(element, value, illustrationSize){
    element.style.backgroundPosition = parseInt(value) * illustrationSize + "px";
  }

  function addOnInputToElement(element, func){
    if (!element){ return; }
    element.oninput = function(){ func(element.name, this.value) }
  }

  function emojiSprite(){
    var value = document.getElementsByClassName("range")[0].value -1;
    var element = document.getElementsByClassName("friends__emoji-sprite")[0];
    changeBackgroundPosition(element, value, -180);
  }

  function emailValidator(emailAddress){
    var regex = RegExp(
      '^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".' +
      '+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-z' +
      'A-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$'
    );
    return regex.test(emailAddress);
  }

  function sendMail(){
    var emailRecipient = document.getElementsByClassName("finish__email-input")[0];
    if (!emailValidator(emailRecipient.value)){
      emailRecipient.value = 'Please enter a valid email address.';
      return;
    }
    var emailAddress = emailRecipient.value;
    var http = new XMLHttpRequest();
    http.open("POST", '/finished', true);
    http.setRequestHeader("Content-type", "application/json");
    var payload = JSON.stringify({emailAddress:emailAddress,
      sessionStorage:sessionStorage});

    http.onreadystatechange = function() {
      if (http.readyState === 4) {
        var response = JSON.parse(http.responseText);
          if (response.status === 'Email sent'){
            finishPrompt.innerHTML = '

' + response.status;
            sessionStorage.clear();
          } else {
            finishPrompt.innerHTML = '

' + response.status;;
          }
      }
    }

    http.send(payload);
  }
})(jQuery);
<commit_msg>Fix issues with ES6 in frontend and unneeded semicolon;<commit_after>(function ($) {
  "use strict";

  addAnswersToSessionStorage();
  updateAvatar('introduction', 'sleeping-lion');
  updateAvatar('finish', 'finish__lion');
  var finishPrompt = document.getElementsByClassName("finish__prompt")[0];

  $('.carousel').carousel({
    indicators: true,
    shift: 100
  });

  anime({
    targets: '#strange',
    translateY: '-5px',
    rotate: [-0.5, 0.5],
    easing: 'easeInOutSine',
    duration: 4000,
    direction: 'alternate',
    loop: true,
  });

  anime({
    targets: '#happy',
    rotate: 1,
    translateY: ['-2px', '-9px'],
    easing: 'easeInOutSine',
    duration: 4000,
    direction: 'alternate',
    loop: true,
  });

  anime({
    targets: '#sad',
    translateX: '-20px',
    rotate: [-1, -2],
    easing: 'easeInOutSine',
    duration: 4000,
    direction: 'alternate',
    loop: true,
  });

  anime({
    targets: '#boring',
    translateX: '2px',
    translateY: '-2px',
    rotate: -1,
    easing: 'easeInOutSine',
    duration: 4000,
    direction: 'alternate',
    loop: true
  });

  anime({
    targets: '#angry',
    translateX: '-5px',
    translateY: '15px',
    rotate: [-1, -2],
    easing: 'easeInOutSine',
    duration: 5000,
    direction: 'alternate',
    loop: true
  });

  anime({
    targets: '#kind',
    translateX: '-20px',
    translateY: '5px',
    rotate: -3,
    easing: 'easeInOutSine',
    duration: 4000,
    direction: 'alternate',
    loop: true
  });

  anime({
    targets: '#fun',
    translateX: '-20px',
    translateY: '5px',
    rotate: -1.5,
    easing: 'easeInOutSine',
    duration: 5000,
    direction: 'alternate',
    loop: true
  });

  [
    'lion',
    'bear',
    'monkey'
  ].forEach(function (avatar) {
    var node = document.getElementsByClassName(avatar)[0];
    if (!node ) return;
    node.addEventListener('click', function () {
      var checkmark = node.getElementsByClassName('checkmark')[0];
      if ( !checkmark ) {
        addCheckmark(node);
        location.href = '/introduction';
      } else {
        node.removeChild(checkmark);
      }
    });
  });

  function addCheckmark (node) {
    var checkmark = document.createElement('DIV');
    checkmark.classList.add('checkmark');
    node.appendChild(checkmark);
  }

  function updateAvatar (selector, avatarSelector) {
    var page = document.getElementsByClassName(selector)[0];
    if (!page) return;
    var avatarImg = page.getElementsByClassName(avatarSelector)[0];
    var avatar = sessionStorage.getItem('avatar');
    avatarImg.src = 'assets/' + avatar + '.svg';
  }

  [
    "send-email-button"
  ].forEach(function(button){
    var node = document.getElementsByClassName(button)[0];
    if (node){
      node.addEventListener('click', function(){ sendMail() });
    }
  });

  function addAnswersToSessionStorage(){
    var personality = [];
    var hobbies = [];

    [
      'lion',
      'bear',
      'monkey'
    ].forEach(function (avatar) {
      var node = document.getElementsByClassName(avatar)[0];
      addClickEventSingle('avatar', node, avatar);
    });

    [
      "strange",
      "happy",
      "angry",
      "fun",
      "boring",
      "kind",
      "sad"
    ].forEach(function(emotion){
      var node = document.getElementById(emotion);
      addClassToNode(node, 'pop');
      addClickEventArray('personality', node, emotion, personality);
    });

    [
      "sad-emoji",
      "happy-emoji",
      "indifferent-emoji"
    ].forEach(function(emoji){
      var node = document.getElementsByClassName(emoji)[0];
      addClickEventSingle('feelings', node, emoji.match(/^[a-z]+/));
    });

    [
      "name",
      "age"
    ].forEach(function(inputField){
      var node = document.getElementsByClassName(inputField)[0];
      addKeyupEvent(inputField, node);
    });

    [
      "football",
      "tennis",
      "music",
      "dance",
      "drawing",
      "photography",
      "cooking",
      "gardening",
      "puzzles",
      "camping",
      "fishing",
      "walking"
    ].forEach(function(hobby){
      var node = document.getElementById(hobby);
      addClickEventArray('hobbies', node, hobby, hobbies);
    });

    [
      "school__range",
      "friends__range",
      "sleep__range"
    ].forEach(function(range){
      var node = document.getElementsByClassName(range)[0];
      addOnInputToElement(node, function(key, value){
        if (range === "sleep__range") {
          sleepingLion();
        } else {
          emojiSprite();
        }
        addSingleValueToStorage(key, value);
      });
    });

    [
      "eating__range"
    ].forEach(function(range) {
      var node = document.getElementsByClassName(range)[0];
      addOnInputToElement(node, function(key, value) {
        addSingleValueToStorage(key, value);
      });
    });

    [
      "frineds__like",
      "frineds__dislike",
      "school__like",
      "school__dislike"
    ].forEach(function(textarea){
      var node = document.getElementsByClassName(textarea)[0];
      addKeyupEvent(textarea, node);
    });

    function addKeyupEvent(key, element){
      if(!element){ return; }
      element.addEventListener("keyup", function(){
        addSingleValueToStorage(key, element.value);
      });
    }

    function addClickEventSingle(key, element, value){
      if(!element){ return; }
      element.addEventListener("click", function(){
        addSingleValueToStorage(key, value);
      });
    }

    function addClickEventArray(key, element, value, array){
      if(!element){ return; }
      element.addEventListener("click", function(){
        addValueToArray(key, value, array);
      });
    }

    function addValueToArray(key, value, array){
      array.push(value);
      addArrayToStorage(key, array);
    }

    function addSingleValueToStorage(key, value){
      sessionStorage.setItem(key, value);
    }

    // JSON.stringify() is used here as session storage only supports strings
    function addArrayToStorage(key, array){
      sessionStorage.setItem(key, JSON.stringify(array));
    }
  }

  // Adds a class to node
  function addClassToNode(node, className){
    if (!node){ return; }
    node.addEventListener("click", function(){
      node.classList.add(className);
    });
  }

  function sleepingLion(){
    var value = document.getElementsByClassName("sleep__range")[0].value;
    var element = document.getElementsByClassName("sleep__sleeping-lion")[0];
    changeBackgroundPosition(element, value, -332);
  }

  function changeBackgroundPosition(element, value, illustrationSize){
    element.style.backgroundPosition = parseInt(value) * illustrationSize + "px";
  }

  function addOnInputToElement(element, func){
    if (!element){ return; }
    element.oninput = function(){ func(element.name, this.value) }
  }

  function emojiSprite(){
    var value = document.getElementsByClassName("range")[0].value -1;
    var element = document.getElementsByClassName("friends__emoji-sprite")[0];
    changeBackgroundPosition(element, value, -180);
  }

  function emailValidator(emailAddress){
    var regex = RegExp(
      '^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".' +
      '+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-z' +
      'A-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$'
    );
    return regex.test(emailAddress);
  }

  function sendMail(){
    var emailRecipient = document.getElementsByClassName("finish__email-input")[0];
    if (!emailValidator(emailRecipient.value)){
      emailRecipient.value = 'Please enter a valid email address.';
      return;
    }
    var emailAddress = emailRecipient.value;
    var http = new XMLHttpRequest();
    http.open("POST", '/finished', true);
    http.setRequestHeader("Content-type", "application/json");
    var payload = JSON.stringify({emailAddress:emailAddress,
      sessionStorage:sessionStorage});

    http.onreadystatechange = function() {
      if (http.readyState === 4) {
        var response = JSON.parse(http.responseText);
          if (response.status === 'Email sent'){
            finishPrompt.innerHTML = '

' + response.status;
            sessionStorage.clear();
          } else {
            finishPrompt.innerHTML = '

' + response.status;
          }
      }
    }

    http.send(payload);
  }
})(jQuery);
<|endoftext|>


<commit_before>function fetchResultsJS(theForm,event) {
  event.preventDefault();
  var formIntegerArray = ["craftAbility", "craftArtifact", "craftAttribute"];
  var formBooleanArray = ["craftSpeciality"];
  var hash = {}
  $.each(formIntegerArray, function(index, item) {hash.item = theForm.elements.namedItem(item).value});
  $.each(formBooleanArray, function(index, item) {hash.item = (~~theForm.elements.namedItem(item).checked)});
  //console.log(hash.craftAbility);
  $.ajax({
    type: 'GET',
    url: '/exaltedcraftingdieroller',
    data: {
      craftAbility: theForm.elements["craftAbility"].value,
      craftArtifact: theForm.elements["craftArtifact"].value,
      craftSpeciality: (~~theForm.elements["craftSpeciality"].checked),
      craftAttribute: (theForm.elements["craftAttribute"].value)
    },
    dataType: 'json',
    success: function(data) {
      document.getElementById("meanSuc").innerHTML = data["meanSuc"].toFixed(2);
      document.getElementById("medianSuc").innerHTML = data["medianSuc"];
      document.getElementById("stdDevSuc").innerHTML = data["stdDevSuc"].toFixed(2);
    }
  })
}

function isFormInteger(value){
  var formIntegerArray = ["craftAbility", "craftArtifact", "craftAttribute"]
  return $.inArray(value, formIntegerArray) > -1
}
<commit_msg>DRYed pulling data from the form<commit_after>function fetchResultsJS(theForm,event) {
  event.preventDefault();
  var formIntegerArray = ["craftAbility", "craftArtifact", "craftAttribute"];
  var formBooleanArray = ["craftSpeciality"];
  var hash = {}
  $.each(formIntegerArray, function(index, item) { hash[item] = theForm.elements.namedItem(item).value;});
  $.each(formBooleanArray, function(index, item) {hash[item] = (~~theForm.elements.namedItem(item).checked);});
  $.ajax({
    type: 'GET',
    url: '/exaltedcraftingdieroller',
    data: hash,
    dataType: 'json',
    success: function(data) {
      document.getElementById("meanSuc").innerHTML = data["meanSuc"].toFixed(2);
      document.getElementById("medianSuc").innerHTML = data["medianSuc"];
      document.getElementById("stdDevSuc").innerHTML = data["stdDevSuc"].toFixed(2);
      // Need to update the initialPoolSize here
    }
  })
}

function isFormInteger(value){
  var formIntegerArray = ["craftAbility", "craftArtifact", "craftAttribute"]
  return $.inArray(value, formIntegerArray) > -1
}
<|endoftext|>


<commit_before>"use strict";
/*
 * Karma Configuration: "coverage" version.
 *
 * This configuration is the same as basic one-shot version, just with coverage.
 */
var webpackCovCfg = require("../webpack/webpack.config.coverage");

module.exports = function (config) {
  /* eslint-disable global-require */
  require("./karma.conf")(config);
  config.set({
    reporters: ["spec", "coverage"],
    webpack: webpackCovCfg,
    coverageReporter: {
      reporters: [
        { type: "json", file: "coverage.json" },
        { type: "lcov" },
        { type: "text-summary" }
      ],
      dir: "coverage/client"
    }
  });
};
<commit_msg>Fix coverage directory.<commit_after>"use strict";
/*
 * Karma Configuration: "coverage" version.
 *
 * This configuration is the same as basic one-shot version, just with coverage.
 */
var path = require("path");
var webpackCovCfg = require("../webpack/webpack.config.coverage");

// Replace with `__dirname` if using in project root.
var ROOT = process.cwd();

module.exports = function (config) {
  /* eslint-disable global-require */
  require("./karma.conf")(config);
  config.set({
    reporters: ["spec", "coverage"],
    webpack: webpackCovCfg,
    coverageReporter: {
      reporters: [
        { type: "json", file: "coverage.json" },
        { type: "lcov" },
        { type: "text-summary" }
      ],
      dir: path.join(ROOT, "coverage/client")
    }
  });
};
<|endoftext|>


<commit_before>/**
* To run the server on the command line or on your hosting provider.
*/

/**
 * Enable ES6 - this will make it automatically transpile required files. See: http://babeljs.io/docs/usage/require/
 * I've left this as runtime transpilation for now just for simplicity, but a real app should perform this as a build
 * step for performance.
 *
 * NB. Heroku supports some ES6 language features through the --harmony flag, but only a subset. See:
 * https://devcenter.heroku.com/articles/node-best-practices#try-new-things
 */
require('babel/register');

var server = require('./server');

server.start();
<commit_msg>Update comment about server-side ES6<commit_after>/**
* To run the server on the command line or on your hosting provider.
*/

/**
 * Enable ES6 - this will make it automatically transpile required files. See: http://babeljs.io/docs/usage/require/
 * I've left this as runtime transpilation for now just for simplicity, but a real app should perform this as a build
 * step for performance - or ideally use native support. My newer template uses native support in io.js, which is
 * ahead of node.js for ES6:
 * https://github.com/poshaughnessy/es6-react-jspm-starter-template
 */
require('babel/register');

var server = require('./server');

server.start();
<|endoftext|>


<commit_before>/*global alertOK, require, TestSuite, unescape, $, JSON*/

// some helpers
function exit() {
    window.open('', '_self', '');
    window.close();
}

function prepareConfig() {
    // For closing the browser
    Config.askBeforeQuit = false;
    // for network tests
    Config.serverInvokedTest = true;
}

function alertForever(msg) {
    alert(msg, 99999);
}

function getURLParam(name) {
    if (Global.testRun && testRun.hasOwnProperty(name)) {
        return testRun[name];
    }
    var queryRegex = new RegExp(name + '=([^\\&]+)'),
        match = document.URL.split('?').last().match(queryRegex),
        // FIXME OMeta overwrite unescape
        unescape = window._unescape || window.unescape;
    return match && unescape(match[1]);
}

// some preparation
var testRunId = getURLParam("testRunId");

if (!testRunId) {
    var msg = 'no id for test run, cannot execute tests';
    alertForever(msg);
    throw msg;
}

// result processing
function postResult(message) {
    alertOK("Result: \n" + message);
    $.post('/test-result/' + testRunId, {testRunId: testRunId, testResults: message});
}

// running the actual tests
var baseTests = [
    // core
    "lively.tests.BaseTests",
    "lively.tests.ClassTests",
    "lively.tests.ModuleSystemTests",
    "lively.tests.NetworkTests",
    "lively.tests.ObjectTests",
    "lively.tests.PartsTestFrameworkTests",
    "lively.tests.TestFrameworkTests",
    "lively.tests.TracingTests",
    "lively.tests.TraitTests",

    // AST / OMeta
    "ometa.tests.OmetaTests",
    "lively.ast.tests.AstTests",

    // persistence
    "lively.persistence.tests.BuildSpec",
    "lively.persistence.tests.PersistenceTests",
    "lively.persistence.tests.TraitPersistenceTests",

    //bindings
    "lively.bindings.tests.BindingTests"
];

var browserTests = [
    // core
    'lively.tests.BootstrapTests',
    'lively.tests.CoreTests',
    "lively.tests.HelperTests",

    // network
    'lively.net.tests.SessionTracker',

    // lang support
    "lively.lang.tests.ExtensionTests",
    "lively.lang.tests.WorkerTests",

    // persistence
    "lively.persistence.tests.MassMorphCreation",

    //bindings
    "lively.bindings.tests.FRPCoreTests",
    "lively.bindings.tests.FRPSerialization",
    "lively.bindings.tests.GeometryBindingTests",

    // ide / SCB
    "lively.ide.tests.ASTEditingSupport",
    "lively.ide.tests.CodeEditor",
    "lively.ide.tests.FileParserTests",
    "lively.ide.tests.ModuleLookup",
    'lively.ide.tests.SCBTests',
    "lively.ide.tests.SyntaxHighlighting",
    "lively.ide.tests.WindowNavigation",
    'lively.ide.tools.tests.CommandLine',

    // morphic
    "lively.morphic.tests.Connectors",
    "lively.morphic.tests.CoreToolsTests",
    "lively.morphic.tests.DataGridTests",
    "lively.morphic.tests.DiffMerge",
    "lively.morphic.tests.EventTests",
    "lively.morphic.tests.Graphics",
    'lively.morphic.tests.HTML',
    'lively.morphic.tests.HTMLText',
    "lively.morphic.tests.Layout",
    "lively.morphic.tests.Morphic",
    "lively.morphic.tests.Morphic2",
    "lively.morphic.tests.MorphAddons",
    "lively.morphic.tests.PathTests",
    'lively.morphic.tests.Serialization',
    "lively.morphic.tests.ShapeTests",
    "lively.morphic.tests.StyleSheets",
    "lively.morphic.tests.StyleSheetsHTML",
    "lively.morphic.tests.TabTests",
    "lively.morphic.tests.Text",
    "lively.morphic.tests.TextUndoTests",

    // cop
    "cop.tests.LayerTests",

    // apps
    "apps.tests.Handlebars"
];

var testList = baseTests;
if (!Global.testRun || !testRun.isNodeJS) {
    testList.pushAll(browserTests);
}

var additionalModules = getURLParam('additionalModules');
if (additionalModules) {
    var moduleNames = additionalModules.split(',');
    testList.pushAll(moduleNames);
}

// filter is something like "lively.morphic.*|.*Origin.*|test03"
var filter = getURLParam('testFilter'), suiteFilter;
if (filter) {
    var parts = filter.split('|'),
        modulePart = parts[0],
        moduleFilterRegexp = new RegExp(modulePart, "i");
    testList = testList.select(function(name) {
        return moduleFilterRegexp.test(name) });
    suiteFilter = parts.slice(1).join('|'); // last 2
}

prepareConfig();

require(['lively.TestFramework'].concat(testList)).toRun(function() {
    var suite = TestSuite.forAllAvailableTests(suiteFilter);
    suite.runFinished = function() {
        if (Global.testRun) {
            testRun.onTestResult(suite.result.asJSON());
        } else {
            var result = suite.result.asJSONString();
            postResult(result);
            if (!getURLParam('stayOpen')) { exit.delay(0.5); }
        }
    };
    suite.runAll();
});
<commit_msg>morphic: adding list tests<commit_after>/*global alertOK, require, TestSuite, unescape, $, JSON*/

// some helpers
function exit() {
    window.open('', '_self', '');
    window.close();
}

function prepareConfig() {
    // For closing the browser
    Config.askBeforeQuit = false;
    // for network tests
    Config.serverInvokedTest = true;
}

function alertForever(msg) {
    alert(msg, 99999);
}

function getURLParam(name) {
    if (Global.testRun && testRun.hasOwnProperty(name)) {
        return testRun[name];
    }
    var queryRegex = new RegExp(name + '=([^\\&]+)'),
        match = document.URL.split('?').last().match(queryRegex),
        // FIXME OMeta overwrite unescape
        unescape = window._unescape || window.unescape;
    return match && unescape(match[1]);
}

// some preparation
var testRunId = getURLParam("testRunId");

if (!testRunId) {
    var msg = 'no id for test run, cannot execute tests';
    alertForever(msg);
    throw msg;
}

// result processing
function postResult(message) {
    alertOK("Result: \n" + message);
    $.post('/test-result/' + testRunId, {testRunId: testRunId, testResults: message});
}

// running the actual tests
var baseTests = [
    // core
    "lively.tests.BaseTests",
    "lively.tests.ClassTests",
    "lively.tests.ModuleSystemTests",
    "lively.tests.NetworkTests",
    "lively.tests.ObjectTests",
    "lively.tests.PartsTestFrameworkTests",
    "lively.tests.TestFrameworkTests",
    "lively.tests.TracingTests",
    "lively.tests.TraitTests",

    // AST / OMeta
    "ometa.tests.OmetaTests",
    "lively.ast.tests.AstTests",

    // persistence
    "lively.persistence.tests.BuildSpec",
    "lively.persistence.tests.PersistenceTests",
    "lively.persistence.tests.TraitPersistenceTests",

    //bindings
    "lively.bindings.tests.BindingTests"
];

var browserTests = [
    // core
    'lively.tests.BootstrapTests',
    'lively.tests.CoreTests',
    "lively.tests.HelperTests",

    // network
    'lively.net.tests.SessionTracker',

    // lang support
    "lively.lang.tests.ExtensionTests",
    "lively.lang.tests.WorkerTests",

    // persistence
    "lively.persistence.tests.MassMorphCreation",

    //bindings
    "lively.bindings.tests.FRPCoreTests",
    "lively.bindings.tests.FRPSerialization",
    "lively.bindings.tests.GeometryBindingTests",

    // ide / SCB
    "lively.ide.tests.ASTEditingSupport",
    "lively.ide.tests.CodeEditor",
    "lively.ide.tests.FileParserTests",
    "lively.ide.tests.ModuleLookup",
    'lively.ide.tests.SCBTests',
    "lively.ide.tests.SyntaxHighlighting",
    "lively.ide.tests.WindowNavigation",
    'lively.ide.tools.tests.CommandLine',

    // morphic
    "lively.morphic.tests.Connectors",
    "lively.morphic.tests.CoreToolsTests",
    "lively.morphic.tests.DataGridTests",
    "lively.morphic.tests.DiffMerge",
    "lively.morphic.tests.EventTests",
    "lively.morphic.tests.Graphics",
    'lively.morphic.tests.HTML',
    'lively.morphic.tests.HTMLText',
    "lively.morphic.tests.Layout",
    "lively.morphic.tests.Lists",
    "lively.morphic.tests.Morphic",
    "lively.morphic.tests.Morphic2",
    "lively.morphic.tests.MorphAddons",
    "lively.morphic.tests.PathTests",
    'lively.morphic.tests.Serialization',
    "lively.morphic.tests.ShapeTests",
    "lively.morphic.tests.StyleSheets",
    "lively.morphic.tests.StyleSheetsHTML",
    "lively.morphic.tests.TabTests",
    "lively.morphic.tests.Text",
    "lively.morphic.tests.TextUndoTests",

    // cop
    "cop.tests.LayerTests",

    // apps
    "apps.tests.Handlebars"
];

var testList = baseTests;
if (!Global.testRun || !testRun.isNodeJS) {
    testList.pushAll(browserTests);
}

var additionalModules = getURLParam('additionalModules');
if (additionalModules) {
    var moduleNames = additionalModules.split(',');
    testList.pushAll(moduleNames);
}

// filter is something like "lively.morphic.*|.*Origin.*|test03"
var filter = getURLParam('testFilter'), suiteFilter;
if (filter) {
    var parts = filter.split('|'),
        modulePart = parts[0],
        moduleFilterRegexp = new RegExp(modulePart, "i");
    testList = testList.select(function(name) {
        return moduleFilterRegexp.test(name) });
    suiteFilter = parts.slice(1).join('|'); // last 2
}

prepareConfig();

require(['lively.TestFramework'].concat(testList)).toRun(function() {
    var suite = TestSuite.forAllAvailableTests(suiteFilter);
    suite.runFinished = function() {
        if (Global.testRun) {
            testRun.onTestResult(suite.result.asJSON());
        } else {
            var result = suite.result.asJSONString();
            postResult(result);
            if (!getURLParam('stayOpen')) { exit.delay(0.5); }
        }
    };
    suite.runAll();
});
<|endoftext|>


<commit_before>function draw(groups, renderFn) {
  $.get("/api/v1/jobs", function(jobsPayload) {
    var jobs = JSON.parse(jobsPayload);

    $.get("/api/v1/resources", function(resourcesPayload) {
      var resources = JSON.parse(resourcesPayload);

      var graph = generateGraph(groups, jobs, resources);

      graph.nodes().forEach(function(v) {
        var node = graph.node(v);

        if (node.gateway) {
          node.height = 30;
          node.width = 2;
        }

        node.paddingLeft = 0;
        node.paddingRight = 0;
        node.paddingTop = 0;
        node.paddingBottom = 0;
      });

      graph.edges().forEach(function(e) {
        var edge = graph.edge(e);

        // curvy
        edge.lineInterpolate = "bundle";
        edge.lineTension = 1.0;
      });

      renderFn(graph);

      graph.edges().forEach(function(e) {
        var edge = graph.edge(e);

        if (edge.status) {
          $("#"+edge.id).attr("class", "path " + edge.status);
        }
      });
    });
  });
}

function drawContinuously(render, svg, groups) {
  draw(groups, function(graph) {
    render(svg, graph);

    svg.attr("viewBox", "-20 -20 " + (graph.graph().width + 40) + " " + (graph.graph().height + 40));

    setTimeout(function() {
      drawContinuously(render, svg, groups)
    }, 5000)
  });
}

function renderPipeline(groups) {
  var svg = d3.select("svg");

  svg.call(d3.behavior.zoom().on("zoom", function() {
    var ev = d3.event;
    svg.select("g.output")
       .attr("transform", "translate(" + ev.translate + ") scale(" + ev.scale + ")");
  }));

  var render = new dagreD3.render();

  render.arrows().status = function(parent, id, edge, type) {
    parent.append("svg:marker")
      .attr("id", id)
      .attr("class", "arrowhead-"+edge.status)
      .attr("viewBox", "0 0 10 10")
      .attr("refX", 8)
      .attr("refY", 5)
      .attr("markerWidth", 8)
      .attr("markerHeight", 5)
      .attr("orient", "auto")
      .append("svg:path")
      .attr("d", "M 0 0 L 10 5 L 0 10 z");
  };

  drawContinuously(render, svg, groups);
}
<commit_msg>shift+click on a group to toggle it<commit_after>function draw(groups, renderFn) {
  $.get("/api/v1/jobs", function(jobsPayload) {
    var jobs = JSON.parse(jobsPayload);

    $.get("/api/v1/resources", function(resourcesPayload) {
      var resources = JSON.parse(resourcesPayload);

      var graph = generateGraph(groups, jobs, resources);

      graph.nodes().forEach(function(v) {
        var node = graph.node(v);

        if (node.gateway) {
          node.height = 30;
          node.width = 2;
        }

        node.paddingLeft = 0;
        node.paddingRight = 0;
        node.paddingTop = 0;
        node.paddingBottom = 0;
      });

      graph.edges().forEach(function(e) {
        var edge = graph.edge(e);

        // curvy
        edge.lineInterpolate = "bundle";
        edge.lineTension = 1.0;
      });

      renderFn(graph);

      graph.edges().forEach(function(e) {
        var edge = graph.edge(e);

        if (edge.status) {
          $("#"+edge.id).attr("class", "path " + edge.status);
        }
      });
    });
  });
}

function drawContinuously(render, svg, groups) {
  draw(groups, function(graph) {
    render(svg, graph);

    svg.attr("viewBox", "-20 -20 " + (graph.graph().width + 40) + " " + (graph.graph().height + 40));

    setTimeout(function() {
      drawContinuously(render, svg, groups)
    }, 5000)
  });
}

function renderPipeline(groups) {
  var svg = d3.select("svg");

  svg.call(d3.behavior.zoom().on("zoom", function() {
    var ev = d3.event;
    svg.select("g.output")
       .attr("transform", "translate(" + ev.translate + ") scale(" + ev.scale + ")");
  }));

  var render = new dagreD3.render();

  render.arrows().status = function(parent, id, edge, type) {
    parent.append("svg:marker")
      .attr("id", id)
      .attr("class", "arrowhead-"+edge.status)
      .attr("viewBox", "0 0 10 10")
      .attr("refX", 8)
      .attr("refY", 5)
      .attr("markerWidth", 8)
      .attr("markerHeight", 5)
      .attr("orient", "auto")
      .append("svg:path")
      .attr("d", "M 0 0 L 10 5 L 0 10 z");
  };

  drawContinuously(render, svg, groups);

  $("ul.groups li a").click(function(e) {
    var group = e.target.text;

    if (e.shiftKey) {
      groups[group] = !groups[group];
    } else {
      for (var name in groups) {
        groups[name] = name == group;
      }
    }

    var groupQueries = [];
    for (var name in groups) {
      if (groups[name]) {
        groupQueries.push("groups="+name);
      }
    }

    window.location.search = "?" + groupQueries.join("&");

    return false;
  });
}
<|endoftext|>


<commit_before>var linda = new Linda();
var ts = new linda.TupleSpace(space_name);

linda.io.on("connect", function(){
  ts.watch(tuple, function(tuple){
    log(tuple);
  });
});

$(function(){
  $("#space").editable("click", function(e){
    space_name = e.value;
  });

  $("#tuple").editable("click", function(e){
    try{
      tuple = JSON.parse(e.value);
    }
    catch(ex){
      alert(e.value + " is not valid Tuple");
      e.target.html(e.old_value);
    }
  });

  $("#btn_write").click(function(e){
    ts.write(tuple);
  });
});

var log = function(msg){
  console.log(msg);
  if(typeof msg !== "string") msg = JSON.stringify(msg);
  var watch_msg = $("<p>").text(msg).append(" - "+ new Date().toString());
  watch_msg.fadeIn(600);
  $("#watch").prepend(watch_msg);
};
<commit_msg>edit tuple and jump #4<commit_after>var linda = new Linda();
var ts = new linda.TupleSpace(space_name);

linda.io.on("connect", function(){
  ts.watch(tuple, function(tuple){
    log(tuple);
  });
});

$(function(){
  $("#space").editable("click", function(e){
    space_name = e.value;
    if(url() !== location.href) location.href = url();
  });

  $("#tuple").editable("click", function(e){
    try{
      tuple = JSON.parse(e.value);
      if(url() !== location.href) location.href = url();
    }
    catch(ex){
      alert(e.value + " is not valid Tuple");
      e.target.html(e.old_value);
    }
  });

  $("#btn_write").click(function(e){
    ts.write(tuple);
  });
});

var log = function(msg){
  console.log(msg);
  if(typeof msg !== "string") msg = JSON.stringify(msg);
  var watch_msg = $("<p>").text(msg).append(" - "+ new Date().toString());
  watch_msg.fadeIn(600);
  $("#watch").prepend(watch_msg);
};

var url = function(){
  var _url = location.protocol+"//"+location.host+"/"+space_name;
  for(var i = 0; i < tuple.length; i++){
    if(tuple[i] && tuple[i].length > 0) _url += "/"+tuple[i];
  };
  return _url;
};
<|endoftext|>


<commit_before>'use strict';

//https://github.com/angular/protractor/blob/master/docs/api.md
//GetAttribute() returns "boolean" values and will return either "true" or null

describe('Authentication', function(){

    var AuthPage = require('../../../app/auth/auth-page');
    var auth = new AuthPage();
    var login = auth.login;
    var logout = auth.logout;
    var config = require('../config/config').config;

    it('should have been redirected to the auth page', function() {
        logout.visitPage();
        logout.getCurrentUrl().then(function(url){
            expect(url.substring(url.length - '/auth'.length)).toBe('/auth');
        });
    });

    it('shouldn\'t login', function(){
        login.login(config.testUser, 'hello');
        expect(login.wrongCombinationMessage().isDisplayed()).toBe(true);
    });

    it('should login', function(){
        login.login(config.testUser, config.testPassword);
        login.getCurrentUrl().then(function(url) {
            expect(url.substring(url.length - 1)).toBe('/');
        });
    });
});
<commit_msg>:bug: fix not existing function.<commit_after>'use strict';

//https://github.com/angular/protractor/blob/master/docs/api.md
//GetAttribute() returns "boolean" values and will return either "true" or null

describe('Authentication', function(){

    var AuthPage = require('../../../app/auth/auth-page');
    var auth = new AuthPage();
    var login = auth.login;
    var logout = auth.logout;
    var config = require('../config/config').config;

    it('should have been redirected to the auth page', function() {
        logout.visitPage();
        auth.getCurrentUrl().then(function(url){
            expect(url.substring(url.length - '/auth'.length)).toBe('/auth');
        });
    });

    it('shouldn\'t login', function(){
        login.login(config.testUser, 'hello');
        expect(login.wrongCombinationMessage().isDisplayed()).toBe(true);
    });

    it('should login', function(){
        login.login(config.testUser, config.testPassword);
        login.getCurrentUrl().then(function(url) {
            expect(url.substring(url.length - 1)).toBe('/');
        });
    });
});
<|endoftext|>


<commit_before>export const getBasename = (path) => {
  const parts = path.split('/');
  return parts[parts.length - 1];
};

export const getExtension = (path) => {
  const parts = path.split(/[./]/);
  return parts[parts.length - 1];
};

export const IMAGE_EXTENSIONS = new Set(['jpg', 'bmp', 'jpeg', 'png', 'gif', 'svg']);
export const TEXT_EXTENSIONS = new Set(
  ['txt', 'log', 'py', 'js', 'yaml', 'yml', 'json', 'csv', 'tsv',
    'md', 'rst', 'MLmodel', 'MLproject', 'jsonnet']);
<commit_msg>fix bug that causes MLmodel files to not be previewed in artifact preview (#1819)<commit_after>export const getBasename = (path) => {
  const parts = path.split('/');
  return parts[parts.length - 1];
};

export const getExtension = (path) => {
  const parts = path.split(/[./]/);
  return parts[parts.length - 1];
};

export const IMAGE_EXTENSIONS = new Set(['jpg', 'bmp', 'jpeg', 'png', 'gif', 'svg']);
export const TEXT_EXTENSIONS = new Set(
  ['txt', 'log', 'py', 'js', 'yaml', 'yml', 'json', 'csv', 'tsv',
    'md', 'rst', 'mlmodel', 'mlproject', 'jsonnet']);
<|endoftext|>


<commit_before>var defineSupportCode = require("cucumber").defineSupportCode;

var webdriver = require("selenium-webdriver");
var browserstack = require("browserstack-local");

var createBrowserStackSession = function(config, caps){
  return new webdriver.Builder().
    usingServer("http://"+config.server+"/wd/hub").
    withCapabilities(caps).
    build();
};

var config = {
    server: "hub-cloud.browserstack.com",
    capabilities: [
        {
            browserName: "chrome",
            build: process.env.CIRCLE_BUILD_NUM,
            project: process.env.CIRCLE_PROJECT_REPONAME + "-" + process.env.CIRCLE_BRANCH,
            "browserstack.local": true
        }
    ]
};

var username = process.env.BS_USERNAME || config.user;
var accessKey = process.env.BS_AUTHKEY || config.key;

defineSupportCode(function(context) {
  var before = context.Before;
  var after = context.After;
  var bsLocal = null;

  before(function (scenario, callback) {
    var world = this;
    var taskId = parseInt(process.env.TASK_ID || 0, 10);
    var caps = config.capabilities[taskId];
    caps["browserstack.user"] = username;
    caps["browserstack.key"] = accessKey;

    if(caps["browserstack.local"]){
      // Code to start browserstack local before start of test and stop browserstack local after end of test
      bsLocal = new browserstack.Local();
      bsLocal.start({key: accessKey}, function(error) {
        if (error) {
          throw new Error("Error at starting browserstack local.");
        }
        world.driver = createBrowserStackSession(config, caps);
        callback();
      });
    }
    else {
      world.driver = createBrowserStackSession(config, caps);
      callback();
    }
  });

  after(function(scenario, callback){
    this.driver.quit().then(function(){
      if(bsLocal){
        bsLocal.stop(callback);
      }
      else {
        callback();
      }
    });
  });
});
<commit_msg>Separate capabilities for browserstack.<commit_after>var defineSupportCode = require("cucumber").defineSupportCode;

var webdriver = require("selenium-webdriver");
var browserstack = require("browserstack-local");

var createBrowserStackSession = function(config, caps){
  return new webdriver.Builder().
    usingServer("http://"+config.server+"/wd/hub").
    withCapabilities(caps).
    build();
};

var config = {
    server: "hub-cloud.browserstack.com",
    capabilities: require("../../browserstack-capabilities")
};

var username = process.env.BS_USERNAME || config.user;
var accessKey = process.env.BS_AUTHKEY || config.key;

defineSupportCode(function(context) {
  var before = context.Before;
  var after = context.After;
  var bsLocal = null;

  before(function (scenario, callback) {
    var world = this;
    var taskId = parseInt(process.env.TASK_ID || 0, 10);
    var caps = config.capabilities[taskId];
    caps["browserstack.user"] = username;
    caps["browserstack.key"] = accessKey;
    caps.build = process.env.CIRCLE_BUILD_NUM;
    caps.project = process.env.CIRCLE_PROJECT_REPONAME + "-" + process.env.CIRCLE_BRANCH;
    caps["browserstack.local"] = true;

    if(caps["browserstack.local"]){
      // Code to start browserstack local before start of test and stop browserstack local after end of test
      bsLocal = new browserstack.Local();
      bsLocal.start({key: accessKey}, function(error) {
        if (error) {
          throw new Error("Error at starting browserstack local.");
        }
        world.driver = createBrowserStackSession(config, caps);
        callback();
      });
    }
    else {
      world.driver = createBrowserStackSession(config, caps);
      callback();
    }
  });

  after(function(scenario, callback){
    this.driver.quit().then(function(){
      if(bsLocal){
        bsLocal.stop(callback);
      }
      else {
        callback();
      }
    });
  });
});
<|endoftext|>


<commit_before>define(["Ti/_/declare", "Ti/_/dom", "Ti/_/lang", "Ti/UI", "Ti/UI/View"], function(declare, dom, lang, UI, View) {

	var sessionId = Math.random(),historyStack = [],
		pageNum = 1,
		hist = window.history,
		POP_STATE_WAITING_FOR_OPERATION = -1,
		POP_STATE_UNDOING_OPERATION = -2,
		POP_STATE_PUSHING = -3,
		POP_STATE_REWINDING_HISTORY = -4,
		POP_STATE_RESETTING = -5,
		historyPopState = POP_STATE_WAITING_FOR_OPERATION,
		prefix = location.href;

	function pushToHistory(widget) {
		historyPopState = POP_STATE_PUSHING;
		historyStack.push(widget);
		location.href = prefix + "#" + (widget.title || widget.widgetId);
	}

	function removeFromHistory(widget) {
		if (historyStack.length > 0 && historyPopState === POP_STATE_WAITING_FOR_OPERATION) {
			var historyStackIndex = historyStack.indexOf(widget);
			if (historyStackIndex !== -1) {
				historyStack.splice(historyStackIndex,historyStack.length - historyStackIndex);
				historyPopState = POP_STATE_REWINDING_HISTORY;
				hist.go(-historyStack.length - 1);
			}
		}
	}

	window.addEventListener("popstate", function(e) {
		switch(historyPopState) {
			case POP_STATE_WAITING_FOR_OPERATION:
				// We need to undo the previous operation and redo it
				var listItem = window.location.href.split("#")[1];
				if (listItem) {
					historyPopState = POP_STATE_UNDOING_OPERATION;
					hist.forward();
				}
				break;
			case POP_STATE_UNDOING_OPERATION:
				var widget = historyStack[historyStack.length - 1];
				historyPopState = POP_STATE_WAITING_FOR_OPERATION;
				widget.close();
				break;
			case POP_STATE_PUSHING:
				historyPopState = POP_STATE_WAITING_FOR_OPERATION;
				break;
			case POP_STATE_REWINDING_HISTORY:
				historyPopState = POP_STATE_RESETTING;
				location.href = prefix + "#_history_reset";
				break;
			case POP_STATE_RESETTING:
				historyPopState = 0;
				hist.back();
				break;
			default:
				if (historyPopState < historyStack.length) {
					var widget = historyStack[historyPopState++];
					location.href = prefix + "#" + (widget.title || widget.widgetId);
				} else {
					historyPopState = POP_STATE_WAITING_FOR_OPERATION;
				}
				break;
		}
	});

	return declare("Ti._.UI.SuperView", View, {

		constructor: function() {
			this.addEventListener("focus", lang.hitch(this, function() {
				this.setWindowTitle(this.title);
			}));
		},

		destroy: function() {
			this.close();
			View.prototype.destroy.apply(this, arguments);
		},

		open: function(args) {
			if (!this._opened) {
				this._opened = 1;
				UI._addWindow(this, 1).show();

				pushToHistory(this);

				this.fireEvent("open");
				this.fireEvent("focus", this._state);
			}
		},

		close: function(args) {
			if (this._opened) {
				this._opened = 0;
				UI._removeWindow(this);

				removeFromHistory(this);

				this.fireEvent("close");
			}
		},

		setWindowTitle: function(title) {
			historyStack[historyStack.length-1] === this && (document.title = title || require.config.project.name);
			return title;
		}

	});

});<commit_msg>[TIMOB-7566] Fleshed out the details of navigation.<commit_after>define(["Ti/_/declare", "Ti/_/dom", "Ti/_/lang", "Ti/UI", "Ti/UI/View"], function(declare, dom, lang, UI, View) {

	var sessionId = Math.random(),historyStack = [],
		pageNum = 1,
		hist = window.history,
		POP_STATE_WAITING_FOR_OPERATION = -1,
		POP_STATE_UNDOING_OPERATION = -2,
		POP_STATE_PUSHING = -3,
		POP_STATE_REWINDING_HISTORY = -4,
		POP_STATE_RESETTING = -5,
		historyPopState = POP_STATE_WAITING_FOR_OPERATION,
		prefix = location.href,
		widgetToClose;

	function pushToHistory(widget) {
		historyPopState = POP_STATE_PUSHING;
		historyStack.push(widget);
		location.href = prefix + "#" + widget.widgetId;
	}

	function removeFromHistory(widget, recursive) {
		if (historyPopState === POP_STATE_WAITING_FOR_OPERATION) {
			var historyStackIndex = historyStack.indexOf(widget);
			if (historyStackIndex !== -1) {
				historyStack.splice(historyStackIndex,recursive ? historyStack.length - historyStackIndex : 1);
				historyPopState = POP_STATE_REWINDING_HISTORY;
				hist.go(-historyStack.length - 1);
			}
		}
	}

	window.addEventListener("hashchange", function(e) {
		switch(historyPopState) {
			case POP_STATE_WAITING_FOR_OPERATION:
				// We need to undo the previous operation and redo it
				var listItem = window.location.href.split("#")[1];
				if (prefix === window.location.href) {
					listItem = historyStack[0].widgetId;
				}
				if (listItem) {
					var historyStackIndex = -1,
						historyStackLength = historyStack.length,
						widget;
					historyPopState = POP_STATE_UNDOING_OPERATION;
					for (var i = 0; i < historyStackLength; i++) {
						widget = historyStack[i];
						if (listItem === widget.widgetId) {
							historyStackIndex = i + 1;
							break;
						}
					}
					for (i = historyStackIndex; i < historyStackLength; i++) {
						historyStack[i].close();
					}
					widgetToClose = historyStack[historyStackIndex];
					hist.go(historyStackLength - historyStackIndex);
				}
				break;
			case POP_STATE_UNDOING_OPERATION:
				historyPopState = POP_STATE_WAITING_FOR_OPERATION;
				removeFromHistory(widgetToClose, true);
				break;
			case POP_STATE_PUSHING:
				historyPopState = POP_STATE_WAITING_FOR_OPERATION;
				break;
			case POP_STATE_REWINDING_HISTORY:
				historyPopState = POP_STATE_RESETTING;
				location.href = prefix + "#history_reset";
				break;
			case POP_STATE_RESETTING:
				historyPopState = 0;
				hist.back();
				break;
			default:
				if (historyPopState < historyStack.length) {
					var widget = historyStack[historyPopState++];
					location.href = prefix + "#" + widget.widgetId;
				} else {
					historyPopState = POP_STATE_WAITING_FOR_OPERATION;
				}
				break;
		}
	});

	return declare("Ti._.UI.SuperView", View, {

		constructor: function() {
			this.addEventListener("focus", lang.hitch(this, function() {
				this.setWindowTitle(this.title);
			}));
		},

		destroy: function() {
			this.close();
			View.prototype.destroy.apply(this, arguments);
		},

		open: function(args) {
			if (!this._opened) {
				this._opened = 1;
				UI._addWindow(this, 1).show();

				pushToHistory(this);

				this.fireEvent("open");
				this.fireEvent("focus", this._state);
			}
		},

		close: function(args) {
			if (this._opened) {
				this._opened = 0;
				UI._removeWindow(this);

				if (historyPopState === POP_STATE_WAITING_FOR_OPERATION) {
					removeFromHistory(this);
				}

				this.fireEvent("close");
			}
		},

		setWindowTitle: function(title) {
			historyStack[historyStack.length-1] === this && (document.title = title || require.config.project.name);
			return title;
		}

	});

});<|endoftext|>


<commit_before>import * as _ from 'lodash'

function onlyQuarterCreditCoursesCanBePassFail(course) {
	// NOTE: Because we can't check this (don't know p/f data), we return true
	// for everything.
	return true
}

let hasGenEd = _.curry(function(gened, course) {
	return _.contains(course.gereqs, gened)
})

let hasFOL = function(course) {
	return _.any(course.gereqs,
		req => req.substr(0,3) === 'FOL')
}

function countGeneds(courses, gened) {
	let uniqed = _.uniq(courses, 'crsid');
	if (gened === 'FOL')
		return _.size(_.filter(uniqed, hasFOL))
	return _.size(_.filter(uniqed, hasGenEd(gened)))
}

function getDepartments(courses) {
	return _.chain(courses).pluck('depts').flatten().uniq().value()
}

function acrossAtLeastTwoDepartments(courses) {
	let depts = getDepartments(courses)

	return _.size(depts) >= 2
}

function checkThatNCoursesSpanTwoDepartments(courses, geneds, genedToCheck, n=2) {
	// Input: courses-array of courses. geneds-['ALS-A', 'ALS-L']. genedToCheck-'ALS-A'
	// XXX,YYY - N courses, from different departments
	let coursesOne = _.filter(courses, hasGenEd(geneds[0]))
	let coursesTwo = _.filter(courses, hasGenEd(geneds[1]))

	let allCourses = _.uniq(coursesOne.concat(coursesTwo), 'crsid')
	let coversTwoDepartments = acrossAtLeastTwoDepartments(allCourses)

	return _.all([
		countGeneds(courses, genedToCheck) >= 1,
		_.size(allCourses) >= n,
		coversTwoDepartments,
	])
}

function isIntercollegiateSport(course) {
	// Only one SPM course credit may be earned by students as a result of
	// participation in an approved intercollegiate sport. This credit must be
	// entered as Exercise Science 171-194 at the registration preceding the
	// sport/participation term.
	let result = hasDeptNumBetween({dept: 'ESTH', start: 171, end: 194}, course)
	return result
}

export {
	onlyQuarterCreditCoursesCanBePassFail,
	hasGenEd,
	hasFOL,
	countGeneds,
	getDepartments,
	acrossAtLeastTwoDepartments,
	checkThatNCoursesSpanTwoDepartments,
	isIntercollegiateSport
}
<commit_msg>Remove a semicolon from areas/lib/commonEducUtilities<commit_after>import * as _ from 'lodash'

function onlyQuarterCreditCoursesCanBePassFail(course) {
	// NOTE: Because we can't check this (don't know p/f data), we return true
	// for everything.
	return true
}

let hasGenEd = _.curry(function(gened, course) {
	return _.contains(course.gereqs, gened)
})

let hasFOL = function(course) {
	return _.any(course.gereqs,
		req => req.substr(0,3) === 'FOL')
}

function countGeneds(courses, gened) {
	let uniqed = _.uniq(courses, 'crsid')
	if (gened === 'FOL')
		return _.size(_.filter(uniqed, hasFOL))
	return _.size(_.filter(uniqed, hasGenEd(gened)))
}

function getDepartments(courses) {
	return _.chain(courses).pluck('depts').flatten().uniq().value()
}

function acrossAtLeastTwoDepartments(courses) {
	let depts = getDepartments(courses)

	return _.size(depts) >= 2
}

function checkThatNCoursesSpanTwoDepartments(courses, geneds, genedToCheck, n=2) {
	// Input: courses-array of courses. geneds-['ALS-A', 'ALS-L']. genedToCheck-'ALS-A'
	// XXX,YYY - N courses, from different departments
	let coursesOne = _.filter(courses, hasGenEd(geneds[0]))
	let coursesTwo = _.filter(courses, hasGenEd(geneds[1]))

	let allCourses = _.uniq(coursesOne.concat(coursesTwo), 'crsid')
	let coversTwoDepartments = acrossAtLeastTwoDepartments(allCourses)

	return _.all([
		countGeneds(courses, genedToCheck) >= 1,
		_.size(allCourses) >= n,
		coversTwoDepartments,
	])
}

function isIntercollegiateSport(course) {
	// Only one SPM course credit may be earned by students as a result of
	// participation in an approved intercollegiate sport. This credit must be
	// entered as Exercise Science 171-194 at the registration preceding the
	// sport/participation term.
	let result = hasDeptNumBetween({dept: 'ESTH', start: 171, end: 194}, course)
	return result
}

export {
	onlyQuarterCreditCoursesCanBePassFail,
	hasGenEd,
	hasFOL,
	countGeneds,
	getDepartments,
	acrossAtLeastTwoDepartments,
	checkThatNCoursesSpanTwoDepartments,
	isIntercollegiateSport
}
<|endoftext|>


<commit_before>var wompt     = require("./lib/includes");

/*

	Objects:
		App
		 - has many channels
		 - has many clients

		Channel
		 - has many clients

*/

var app = new wompt.App({
	config: wompt.env,
	root: __dirname
});

app.start_server();
<commit_msg>Removed some comments from server.js<commit_after>var wompt     = require("./lib/includes");

var app = new wompt.App({
	config: wompt.env,
	root: __dirname
});

app.start_server();
<|endoftext|>


<commit_before>'use strict';

var memoize            = require('memoizee/plain')
  , validDbType        = require('dbjs/valid-dbjs-type')
  , definePercentage   = require('dbjs-ext/number/percentage')
  , defineStringLine   = require('dbjs-ext/string/string-line')
  , defineRegistration = require('../registration')
  , defineSubmission   = require('../submission')
  , endsWith           = require('es5-ext/string/#/ends-with');

module.exports = memoize(function (Target/* options */) {
	var db, StringLine, Percentage, Submission, options;
	validDbType(Target);
	db = Target.database;
	options = Object(arguments[1]);
	defineRegistration(db);
	Percentage = definePercentage(db);
	StringLine = defineStringLine(db);
	Submission = options.submissionClass || defineSubmission(db);

	Target.prototype.defineProperties({
		registrations: {
			type: db.Object,
			nested: true
		},
		applicableRegistrations: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var regs = [];
				this.registrations.forEach(function (reg) {
					var isApplicable = reg._get ? _observe(reg._isApplicable) : reg.isApplicable;
					if (isApplicable) regs.push(reg.key);
				}, this);
				return regs;
			}
		},
		mandatoryRegistrations: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var regs = [];
				this.applicableRegistrations.forEach(function (regName) {
					var registration = this.registrations[regName];
					var isMandatory = registration._get
						? _observe(registration._isMandatory) : registration.isMandatory;
					if (isMandatory) regs.push(regName);
				}, this);
				return regs;
			}
		},

		optionalRegistrations: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var regs = [];
				this.applicableRegistrations.forEach(function (regName) {
					var registration = this.registrations[regName];
					var isMandatory = registration._get
						? _observe(registration._isMandatory) : registration.isMandatory;
					if (!isMandatory) regs.push(regName);
				}, this);
				return regs;
			}
		},
		requestedRegistrations: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var regs = [];
				this.applicableRegistrations.forEach(function (regName) {
					var registration = this.registrations[regName];
					var isRequested = registration._get
						? _observe(registration._isRequested) : registration.isRequested;
					if (isRequested) regs.push(regName);
				}, this);
				return regs;
			}
		},
		requestedCertificates: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var certs = [];
				this.requestedRegistrations.forEach(function (regName) {
					_observe(this.registrations[regName].certificates).forEach(function (cert) {
						certs.push(cert);
					});
				}, this);
				return certs;
			}
		},
		resolvedRequirements: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var certs = this.requestedCertificates, result = [];
				this.requestedRegistrations.forEach(function (regName) {
					_observe(this.registrations[regName].requirements).forEach(function (req) {
						if (certs.has(req)) return;
						result.push(req);
					}, this);
				}, this);
				return result;
			}
		},
		applicableRequirements: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var result = [];
				this.resolvedRequirements.forEach(function (requirement) {
					if (_observe(this.requirements[requirement].isApplicable)) result.push(requirement);
				}, this);
				return result;
			}
		},
		applicableSubmissions: {
			type: Submission,
			multiple: true,
			value: function (_observe) {
				var result = [];
				this.applicableRequirements.forEach(function (req) {
					_observe(this.requirements[req].submissions).forEach(function (sub) {
						result.push(sub);
					});
				}, this);
				return result;
			}
		},
		questionsStatus: {
			type: Percentage,
			value: 1
		},
		submissionsStatus: {
			type: Percentage,
			value: function (_observe) {
				var total, valid;
				total = valid = 0;
				if (this.questionsStatus !== 1) return 0;
				if (!this.applicableSubmissions.size) return 1;
				this.applicableSubmissions.forEach(function (submission) {
					++total;
					if (!_observe(submission.orderedFiles._size)) return;
					if (submission.orderedFiles.some(function (file) { return _observe(file._path); })) {
						++valid;
					}
				}, this);
				return valid / total;
			}
		}
	});

	if (options.classes) {
		options.classes.forEach(function (registration) {
			if (!endsWith.call(registration.__id__, "Registration")) {
				throw new Error("Class: " + registration.__id__ + " doesn't end with 'Registration'." +
					" All registration class names must end with 'Registration'.");
			}
			Target.prototype.registrations.define(registration.__id__[0].toLowerCase() +
				registration.__id__.slice(1, -("Registration".length)), {
					type: registration,
					nested: true
				});
		});
	}

	return Target;
}, { normalizer: require('memoizee/normalizers/get-1')() });
<commit_msg>Assure sorted result in resolvedRequirements<commit_after>'use strict';

var memoize            = require('memoizee/plain')
  , validDbType        = require('dbjs/valid-dbjs-type')
  , definePercentage   = require('dbjs-ext/number/percentage')
  , defineStringLine   = require('dbjs-ext/string/string-line')
  , defineRegistration = require('../registration')
  , defineSubmission   = require('../submission')
  , endsWith           = require('es5-ext/string/#/ends-with');

module.exports = memoize(function (Target/* options */) {
	var db, StringLine, Percentage, Submission, options;
	validDbType(Target);
	db = Target.database;
	options = Object(arguments[1]);
	defineRegistration(db);
	Percentage = definePercentage(db);
	StringLine = defineStringLine(db);
	Submission = options.submissionClass || defineSubmission(db);

	Target.prototype.defineProperties({
		registrations: {
			type: db.Object,
			nested: true
		},
		applicableRegistrations: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var regs = [];
				this.registrations.forEach(function (reg) {
					var isApplicable = reg._get ? _observe(reg._isApplicable) : reg.isApplicable;
					if (isApplicable) regs.push(reg.key);
				}, this);
				return regs;
			}
		},
		mandatoryRegistrations: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var regs = [];
				this.applicableRegistrations.forEach(function (regName) {
					var registration = this.registrations[regName];
					var isMandatory = registration._get
						? _observe(registration._isMandatory) : registration.isMandatory;
					if (isMandatory) regs.push(regName);
				}, this);
				return regs;
			}
		},

		optionalRegistrations: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var regs = [];
				this.applicableRegistrations.forEach(function (regName) {
					var registration = this.registrations[regName];
					var isMandatory = registration._get
						? _observe(registration._isMandatory) : registration.isMandatory;
					if (!isMandatory) regs.push(regName);
				}, this);
				return regs;
			}
		},
		requestedRegistrations: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var regs = [];
				this.applicableRegistrations.forEach(function (regName) {
					var registration = this.registrations[regName];
					var isRequested = registration._get
						? _observe(registration._isRequested) : registration.isRequested;
					if (isRequested) regs.push(regName);
				}, this);
				return regs;
			}
		},
		requestedCertificates: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var certs = [];
				this.requestedRegistrations.forEach(function (regName) {
					_observe(this.registrations[regName].certificates).forEach(function (cert) {
						certs.push(cert);
					});
				}, this);
				return certs;
			}
		},
		resolvedRequirements: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var certs = this.requestedCertificates, resolved = {}, result = [], i, count = 0;
				this.requestedRegistrations.forEach(function (regName) {
					_observe(this.registrations[regName].requirements).forEach(function (req) {
						if (certs.has(req)) return;
						if (result[req]) return;
						result[req] = true;
						++count;
					}, this);
				}, this);
				for (i in this.requirements) {
					if (resolved.hasOwnProperty(i)) {
						result.push(i);
						--count;
					}
				}
				if (count) throw new Error("Undefined requirements resolved from registrations");
				return result;
			}
		},
		applicableRequirements: {
			type: StringLine,
			multiple: true,
			value: function (_observe) {
				var result = [];
				this.resolvedRequirements.forEach(function (requirement) {
					if (_observe(this.requirements[requirement].isApplicable)) result.push(requirement);
				}, this);
				return result;
			}
		},
		applicableSubmissions: {
			type: Submission,
			multiple: true,
			value: function (_observe) {
				var result = [];
				this.applicableRequirements.forEach(function (req) {
					_observe(this.requirements[req].submissions).forEach(function (sub) {
						result.push(sub);
					});
				}, this);
				return result;
			}
		},
		questionsStatus: {
			type: Percentage,
			value: 1
		},
		submissionsStatus: {
			type: Percentage,
			value: function (_observe) {
				var total, valid;
				total = valid = 0;
				if (this.questionsStatus !== 1) return 0;
				if (!this.applicableSubmissions.size) return 1;
				this.applicableSubmissions.forEach(function (submission) {
					++total;
					if (!_observe(submission.orderedFiles._size)) return;
					if (submission.orderedFiles.some(function (file) { return _observe(file._path); })) {
						++valid;
					}
				}, this);
				return valid / total;
			}
		}
	});

	if (options.classes) {
		options.classes.forEach(function (registration) {
			if (!endsWith.call(registration.__id__, "Registration")) {
				throw new Error("Class: " + registration.__id__ + " doesn't end with 'Registration'." +
					" All registration class names must end with 'Registration'.");
			}
			Target.prototype.registrations.define(registration.__id__[0].toLowerCase() +
				registration.__id__.slice(1, -("Registration".length)), {
					type: registration,
					nested: true
				});
		});
	}

	return Target;
}, { normalizer: require('memoizee/normalizers/get-1')() });
<|endoftext|>


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

    angular
        .module('app.avengers')
        .controller('Avengers', Avengers);

    Avengers.$inject = ['common', 'dataservice'];

    function Avengers(common, dataservice) {
        var log = common.logger.info;

        /*jshint validthis: true */
        var vm = this;
        vm.avengers = [];
        vm.title = 'Avengers';

        activate();

        function activate() {
            var promises = [getAvengers()];
            return dataservice.ready(promises).then(function(){
                log('Activated Avengers View');
            });
        }

        function getAvengers() {
            dataservice.getAvengers().then(function (data) {
                vm.avengers = data;
                return vm.avengers;
            });
        }
    }
})();<commit_msg>modular: need to return the promise from data retrieval functions<commit_after>(function () {
    'use strict';

    angular
        .module('app.avengers')
        .controller('Avengers', Avengers);

    Avengers.$inject = ['common', 'dataservice'];

    function Avengers(common, dataservice) {
        var log = common.logger.info;

        /*jshint validthis: true */
        var vm = this;
        vm.avengers = [];
        vm.title = 'Avengers';

        activate();

        function activate() {
            var promises = [getAvengers()];
            return dataservice.ready(promises).then(function(){
                log('Activated Avengers View');
            });
        }

        function getAvengers() {
            return dataservice.getAvengers().then(function (data) {
                vm.avengers = data;
                return vm.avengers;
            });
        }
    }
})();<|endoftext|>