<commit_before>// Copyright 2010 Steven Dee. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

if (typeof goog != 'undefined') {
goog.provide('jsprettify.entities');
goog.provide('jsprettify.prettifyHtml');
goog.provide('jsprettify.prettifyStr');
goog.provide('window.prettify');
}

var jsprettify = jsprettify || {};

/**
 * This object contains some common typographical HTML entities.
 * @type {Object.<string,string>}
 */
jsprettify.entities = {
  endash: '\u2013',
  emdash: '\u2014',
  lsquo:  '\u2018',
  rsquo:  '\u2019',
  ldquo:  '\u201c',
  rdquo:  '\u201d',
  hellip: '\u2026'
};

/**
 * Prettifies strings by replacing ASCII shorthand with proper typographical
 * symbols.
 * @param {string} text Text to prettify.
 * @return {string} Prettified text.
 */
jsprettify.prettifyStr = function(text) {
  var e = jsprettify.entities;
  /**
   * This array-of-arrays holds entries consisting of patterns and
   * substitutions in the order that they are to be applied. We need to
   * preserve order, since e.g. if -- were replaced before ---, disaster
   * would ensue.
   * @type {Array.<Array.<string>>}
   */
  var subs = [
    ['\\.\\.\\.', e.hellip],
    ["(^|[\\s\"])'", '$1' + e.lsquo],
    ['(^|[\\s-])"', '$1' + e.ldquo],
    ['---', e.emdash],
    ['--', e.endash],
    ["'($|[\\s\"])?", e.rsquo + '$1'],
    ['"($|[\\s.,;:?!])', e.rdquo + '$1']
  ];
  for (var i = 0; i < subs.length; i++) {
    var arr = subs[i];
    var re = new RegExp(arr[0], 'g');
    var sub = arr[1];
    text = text.replace(re, sub);
  };
  return text;
};

/**
 * Prettifies HTML Nodes by recursively prettifying their child text nodes.
 * This function operates nondestructively -- a prettified HTML fragment is
 * returned, and can replace the existing one to prettify a document.
 * @param {Node|null} e Node to start prettifying.
 * @param {uglyTags: Array.<string>, uglyClass: string} opt_args Optional
 *     arguments to customize the behavior of the function. 'uglyTags' is an
 *     array of tagnames not to prettify. 'uglyClass' is a string consisting
 *     of the class not to prettify.
 * @return {Node|null} Prettified version of the passed node.
 */
jsprettify.prettifyHtml = function(e, opt_args) {
  var args = opt_args || {};
  var uglyTags = args['uglyTags'] || [];
  var uglyClass = args['uglyClass'] || "";
  var contains = function(arr, obj) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == obj) {
        return true;
      }
    }
    return false;
  };
  if (e == null) {
    return null;
  }
  var ret = e.cloneNode(true);
  if (e.nodeType == Node.TEXT_NODE) {
    ret.textContent = jsprettify.prettifyStr(ret.textContent);
  } else if (! contains(uglyTags, e.nodeName.toLowerCase()) &&
      ! (e.className && e.className == uglyClass)) {
    var curChildren = ret.childNodes;
    for (var i = 0; i < curChildren.length; i++) {
      ret.replaceChild(jsprettify.prettifyHtml(curChildren[i], opt_args),
          curChildren[i]);
    }
  }
  return ret;
};

/**
 * Auto-prettify everything with classname 'prettify' in a document.
 */
window.prettify = function() {
  var es = document.getElementsByClassName('prettify');
  var opts = {'uglyTags': ['code', 'pre']};
  for (var i = 0; i < es.length; i++) {
    document.body.replaceChild(jsprettify.prettifyHtml(es[i], opts), es[i]);
  }
};
<commit_msg>Passing all tests.<commit_after>// Copyright 2010 Steven Dee. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

if (typeof goog != 'undefined') {
goog.provide('jsprettify.entities');
goog.provide('jsprettify.prettifyHtml');
goog.provide('jsprettify.prettifyStr');
goog.provide('window.prettify');
}

var jsprettify = jsprettify || {};

/**
 * This object contains some common typographical HTML entities.
 * @type {Object.<string,string>}
 */
jsprettify.entities = {
  endash: '\u2013',
  emdash: '\u2014',
  lsquo:  '\u2018',
  rsquo:  '\u2019',
  ldquo:  '\u201c',
  rdquo:  '\u201d',
  hellip: '\u2026'
};

/**
 * Prettifies strings by replacing ASCII shorthand with proper typographical
 * symbols.
 * @param {string} text Text to prettify.
 * @return {string} Prettified text.
 */
jsprettify.prettifyStr = function(text) {
  var e = jsprettify.entities;
  /**
   * This array-of-arrays holds entries consisting of patterns and
   * substitutions in the order that they are to be applied. We need to
   * preserve order, since e.g. if -- were replaced before ---, disaster
   * would ensue.
   * @type {Array.<Array.<string>>}
   */
  var subs = [
    ['\\.\\.\\.', e.hellip],
    ["(^|[\\s\"])'", '$1' + e.lsquo],
    ['(^|[\\s-])"', '$1' + e.ldquo],
    ['---', e.emdash],
    ['--', e.endash],
    ["'($|[\\s\"])?", e.rsquo + '$1'],
    ['"($|[\\s.,;:?!])', e.rdquo + '$1']
  ];
  for (var i = 0; i < subs.length; i++) {
    var arr = subs[i];
    var re = new RegExp(arr[0], 'g');
    var sub = arr[1];
    text = text.replace(re, sub);
  };
  return text;
};

/**
 * Prettifies HTML Nodes by recursively prettifying their child text nodes.
 * This function operates nondestructively -- a prettified HTML fragment is
 * returned, and can replace the existing one to prettify a document.
 * @param {Node|null} e Node to start prettifying.
 * @param {uglyTags: Array.<string>, uglyClass: string} opt_args Optional
 *     arguments to customize the behavior of the function. 'uglyTags' is an
 *     array of tagnames not to prettify. 'uglyClass' is a string consisting
 *     of the class not to prettify.
 * @return {Node|null} Prettified version of the passed node.
 */
jsprettify.prettifyHtml = function(e, opt_args) {
  var args = opt_args || {};
  var uglyTags = args['uglyTags'] || [];
  var uglyClass = args['uglyClass'] || "";
  var contains = function(arr, obj) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == obj) {
        return true;
      }
    }
    return false;
  };
  if (e == null) {
    return null;
  }
  var ret = e.cloneNode(true);
  if (e.nodeType == Node.TEXT_NODE) {
    ret.textContent = jsprettify.prettifyStr(ret.textContent);
  } else if (! contains(uglyTags, e.nodeName.toLowerCase()) &&
      ! (e.className && e.className == uglyClass)) {
    var curChildren = ret.childNodes;
    for (var i = 0; i < curChildren.length; i++) {
      ret.replaceChild(jsprettify.prettifyHtml(curChildren[i], opt_args),
          curChildren[i]);
    }
  }
  return ret;
};

/**
 * Auto-prettify everything with classname 'prettify' in a document.
 */
window.prettify = function() {
  var es = document.getElementsByClassName('prettify');
  var opts = {'uglyTags': ['code', 'pre'], 'uglyClass': 'keepugly'};
  for (var i = 0; i < es.length; i++) {
    document.body.replaceChild(jsprettify.prettifyHtml(es[i], opts), es[i]);
  }
};
<|endoftext|>


<commit_before>(function(){

    var stream = raw.model();

    var group = stream.dimension()
        .title('Group')
        .required(1)

    var date = stream.dimension()
        .title('Date')
        .types(Number, Date, String)
        .accessor(function (d){ return this.type() == "Date" ? Date.parse(d) : this.type() == "String" ? d : +d; })
        .required(1)

    var size = stream.dimension()
        .title('Size')
        .types(Number)
        .required(1)

    stream.map(function (data){
        if (!group()) return [];

        var dates = d3.set(data.map(function (d){ return date(d); })).values();

        var groups = d3.nest()
            .key(group)
            .rollup(function (g){

                var singles = d3.nest()
                    .key(function(d){ return date(d); })
                    .rollup(function (d){
                        return {
                            group : group(d[0]),
                            x : date(d[0]),
                            y : size() ? d3.sum(d,size) : d.length
                        }
                    })
                    .map(g);

                // let's create the empty ones
                dates.forEach(function(d){
                    if (!singles.hasOwnProperty(d)) {
                        singles[d] = { group : group(g[0]), x : d, y : 0 }
                    }
                })

                return d3.values(singles);
            })
            .map(data)

        return d3.values(groups).map(function(d){ return d.sort(function(a,b){ return a.x - b.x; }) });

    })

    var chart = raw.chart()
        .title('Bump Chart')
        .thumbnail("imgs/bumpChart.png")
        .description(
            "For continuous data such as time series, a bump chart can be used in place of stacked bars. Based on New York Times's interactive visualization.")
        .category('Time series')
        .model(stream)

    var width = chart.number()
        .title("Width")
        .defaultValue(1000)
        .fitToWidth(true)

    var height = chart.number()
        .title("Height")
        .defaultValue(500)

    var padding = chart.number()
        .title("Padding")
        .defaultValue(1)

    var normalize = chart.checkbox()
        .title("Normalize")
        .defaultValue(false)

    var curve = chart.list()
        .title("Interpolation")
        .values(['Basis spline','Sankey','Linear'])
        .defaultValue('Sankey')

    var sort = chart.list()
        .title("Sort by")
        .values(['value (descending)', 'value (ascending)', 'group'])
        .defaultValue('value (descending)')

    var showLabels = chart.checkbox()
        .title("Show labels")
        .defaultValue(true)

    var showGrid = chart.checkbox()
        .title("Show grid")
        .defaultValue(true)

    var colors = chart.color()
        .title("Color scale")

    chart.draw(function (selection, data){

        var g = selection
            .attr("width", +width() )
            .attr("xmlns:xmlns:xlink", "http://www.w3.org/1999/xlink")
            .attr("height", +height() )
            .append("g")

        var layers = data;

        var curves = {
          'Basis spline' : 'basis',
          'Sankey' : interpolate,
          'Linear' : 'linear'
        }

        layers[0].forEach(function(d,i){

            var values = layers.map(function(layer){
                return layer[i];
            })
            .sort(sortBy);

            var sum = d3.sum(values, function(layer){ return layer.y; });
            var y0 = 0;
            values.forEach(function(layer){
              layer.y *= normalize() ? 100 / sum : 1;
              layer.y0 = y0;
              y0 += layer.y + padding();
            })

        })

        var x = date() && date.type() == "Date"
            // Date
            ? d3.time.scale()
                .domain( [ d3.min(layers, function(layer) { return d3.min(layer, function(d) { return d.x; }); }), d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.x; }); }) ])
                .range([0, +width()])
            : date && date.type() == "String"
              // String
              ? d3.scale.ordinal()
                  .domain(layers[0].map(function(d){ return d.x; }) )
                  .rangePoints([0, +width()],0)
              // Number
              : d3.scale.linear()
                  .domain( [ d3.min(layers, function(layer) { return d3.min(layer, function(d) { return d.x; }); }), d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.x; }); }) ])
                  .range([0, +width()]);

        var y = d3.scale.linear()
            .domain([0, d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y0 + d.y; }); })])
            .range([+height()-20, 0]);

        // to be improved
        layers[0].forEach(function(d,i){

            var values = layers.map(function(layer){
                return layer[i];
            })
            .sort(sortBy);

            var sum = d3.sum(values, function(layer){ return layer.y; });
            var y0 = normalize() ? 0 : -sum/2 + y.invert( (+height()-20)/2 ) - padding()*(values.length-1)/2;

            values.forEach(function(layer){
                layer.y *= normalize() ? 100 / sum : 1;
                layer.y0 = y0;
                y0 += layer.y + padding();
            })

        })

        var xAxis = d3.svg.axis().scale(x).tickSize(-height()+20).orient("bottom");

        g.append("g")
            .attr("class", "x axis")
            .style("stroke-width", "1px")
            .style("font-size","10px")
            .style("font-family","Arial, Helvetica")
            .attr("transform", "translate(" + 0 + "," + (height()-20) + ")")
            .style("display",function(){ return showGrid() ? 'block' : 'none'; })
            .call(xAxis);

        d3.selectAll(".x.axis line, .x.axis path")
            .style("shape-rendering","crispEdges")
            .style("fill","none")
            .style("stroke","#ccc")

        colors.domain(layers, function (d){ return d[0].group; })

        var area = d3.svg.area()
            .interpolate(curves[curve()])
            .x(function(d) { return x(d.x); })
            .y0(function(d) { return y(d.y0); })
            .y1(function(d) { return Math.min(y(d.y0)-1, y(d.y0 + d.y)); });

        var line = d3.svg.line()
            .interpolate(curves[curve()])
            .x(function(d) { return x(d.x); })
            .y(function(d) {
                var y0 = y(d.y0), y1 = y(d.y0 + d.y);
                return y0 + (y1 - y0) * 0.5;
            });

        g.selectAll("path.layer")
            .data(layers)
            .enter().append("path")
                .attr("class","layer")
                .attr("d", area)
                .attr("title", function (d){ return d[0].group; })
                .style("fill-opacity",.9)
                .style("fill", function (d) { return colors()(d[0].group); });

        if (!showLabels()) return;

        g.append('defs');

        g.select('defs')
            .selectAll('path')
            .data(layers)
            .enter().append('path')
            .attr('id', function(d,i) { return 'path-' + i; })
            .attr('d', line);

        g.selectAll("text.label")
            .data(layers)
            .enter().append('text')
            .attr('dy', '0.5ex')
            .attr("class","label")
           .append('textPath')
            .attr('xlink:xlink:href', function(d,i) { return '#path-' + i; })
            .attr('startOffset', function(d) {
                var maxYr = 0, maxV = 0;
                d3.range(layers[0].length).forEach(function(i) {
                    if (d[i].y > maxV) {
                        maxV = d[i].y;
                        maxYr = i;
                    }
                });
                d.maxVal = d[maxYr].y;
                d.offset = Math.round(x(d[maxYr].x) / x.range()[1] * 100);
                return Math.min(95, Math.max(5, d.offset))+'%';
            })
            .attr('text-anchor', function(d) {
                return d.offset > 90 ? 'end' : d.offset < 10 ? 'start' : 'middle';
            })
            .text(function(d){ return d[0].group; })
            .style("font-size","11px")
            .style("font-family","Arial, Helvetica")
            .style("font-weight","normal")

        function sortBy(a,b){
            if (sort() == 'value (descending)') return a.y - b.y;
            if (sort() == 'value (ascending)') return b.y - a.y;
            if (sort() == 'group') return a.group - b.group;
        }

        function interpolate(points) {
          var x0 = points[0][0], y0 = points[0][1], x1, y1, x2,
              path = [x0, ",", y0],
              i = 0,
              n = points.length;

          while (++i < n) {
            x1 = points[i][0], y1 = points[i][1], x2 = (x0 + x1) / 2;
            path.push("C", x2, ",", y0, " ", x2, ",", y1, " ", x1, ",", y1);
            x0 = x1, y0 = y1;
          }
          return path.join("");
        }
    })

})();
<commit_msg>small fix<commit_after>(function(){

    var stream = raw.model();

    var group = stream.dimension()
        .title('Group')
        .required(1)

    var date = stream.dimension()
        .title('Date')
        .types(Number, Date, String)
        .accessor(function (d){ return this.type() == "Date" ? Date.parse(d) : this.type() == "String" ? d : +d; })
        .required(1)

    var size = stream.dimension()
        .title('Size')
        .types(Number)
        .required(1)

    stream.map(function (data){
        if (!group()) return [];

        var dates = d3.set(data.map(function (d){ return date(d); })).values();

        var groups = d3.nest()
            .key(group)
            .rollup(function (g){

                var singles = d3.nest()
                    .key(function(d){ return date(d); })
                    .rollup(function (d){
                        return {
                            group : group(d[0]),
                            x : date(d[0]),
                            y : size() ? d3.sum(d,size) : d.length
                        }
                    })
                    .map(g);

                // let's create the empty ones
                dates.forEach(function(d){
                    if (!singles.hasOwnProperty(d)) {
                        singles[d] = { group : group(g[0]), x : d, y : 0 }
                    }
                })

                return d3.values(singles);
            })
            .map(data)

        return d3.values(groups).map(function(d){ return d.sort(function(a,b){ return a.x - b.x; }) });

    })

    var chart = raw.chart()
        .title('Bump Chart')
        .thumbnail("imgs/bumpChart.png")
        .description(
            "For continuous data such as time series, a bump chart can be used in place of stacked bars. Based on New York Times's interactive visualization.")
        .category('Time series')
        .model(stream)

    var width = chart.number()
        .title("Width")
        .defaultValue(1000)
        .fitToWidth(true)

    var height = chart.number()
        .title("Height")
        .defaultValue(500)

    var padding = chart.number()
        .title("Padding")
        .defaultValue(1)

    var normalize = chart.checkbox()
        .title("Normalize")
        .defaultValue(false)

    var curve = chart.list()
        .title("Interpolation")
        .values(['Basis spline','Sankey','Linear'])
        .defaultValue('Sankey')

    var sort = chart.list()
        .title("Sort by")
        .values(['value (descending)', 'value (ascending)', 'group'])
        .defaultValue('value (descending)')

    var showLabels = chart.checkbox()
        .title("Show labels")
        .defaultValue(true)

    var showGrid = chart.checkbox()
        .title("Show grid")
        .defaultValue(true)

    var colors = chart.color()
        .title("Color scale")

    chart.draw(function (selection, data){

        var g = selection
            .attr("width", +width() )
            //.attr("xmlns:xmlns:xlink", "http://www.w3.org/1999/xlink")
            .attr("height", +height() )
            .append("g")

        var layers = data;

        var curves = {
          'Basis spline' : 'basis',
          'Sankey' : interpolate,
          'Linear' : 'linear'
        }

        layers[0].forEach(function(d,i){

            var values = layers.map(function(layer){
                return layer[i];
            })
            .sort(sortBy);

            var sum = d3.sum(values, function(layer){ return layer.y; });
            var y0 = 0;
            values.forEach(function(layer){
              layer.y *= normalize() ? 100 / sum : 1;
              layer.y0 = y0;
              y0 += layer.y + padding();
            })

        })

        var x = date() && date.type() == "Date"
            // Date
            ? d3.time.scale()
                .domain( [ d3.min(layers, function(layer) { return d3.min(layer, function(d) { return d.x; }); }), d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.x; }); }) ])
                .range([0, +width()])
            : date && date.type() == "String"
              // String
              ? d3.scale.ordinal()
                  .domain(layers[0].map(function(d){ return d.x; }) )
                  .rangePoints([0, +width()],0)
              // Number
              : d3.scale.linear()
                  .domain( [ d3.min(layers, function(layer) { return d3.min(layer, function(d) { return d.x; }); }), d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.x; }); }) ])
                  .range([0, +width()]);

        var y = d3.scale.linear()
            .domain([0, d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y0 + d.y; }); })])
            .range([+height()-20, 0]);

        // to be improved
        layers[0].forEach(function(d,i){

            var values = layers.map(function(layer){
                return layer[i];
            })
            .sort(sortBy);

            var sum = d3.sum(values, function(layer){ return layer.y; });
            var y0 = normalize() ? 0 : -sum/2 + y.invert( (+height()-20)/2 ) - padding()*(values.length-1)/2;

            values.forEach(function(layer){
                layer.y *= normalize() ? 100 / sum : 1;
                layer.y0 = y0;
                y0 += layer.y + padding();
            })

        })

        var xAxis = d3.svg.axis().scale(x).tickSize(-height()+20).orient("bottom");

        g.append("g")
            .attr("class", "x axis")
            .style("stroke-width", "1px")
            .style("font-size","10px")
            .style("font-family","Arial, Helvetica")
            .attr("transform", "translate(" + 0 + "," + (height()-20) + ")")
            .style("display",function(){ return showGrid() ? 'block' : 'none'; })
            .call(xAxis);

        d3.selectAll(".x.axis line, .x.axis path")
            .style("shape-rendering","crispEdges")
            .style("fill","none")
            .style("stroke","#ccc")

        colors.domain(layers, function (d){ return d[0].group; })

        var area = d3.svg.area()
            .interpolate(curves[curve()])
            .x(function(d) { return x(d.x); })
            .y0(function(d) { return y(d.y0); })
            .y1(function(d) { return Math.min(y(d.y0)-1, y(d.y0 + d.y)); });

        var line = d3.svg.line()
            .interpolate(curves[curve()])
            .x(function(d) { return x(d.x); })
            .y(function(d) {
                var y0 = y(d.y0), y1 = y(d.y0 + d.y);
                return y0 + (y1 - y0) * 0.5;
            });

        g.selectAll("path.layer")
            .data(layers)
            .enter().append("path")
                .attr("class","layer")
                .attr("d", area)
                .attr("title", function (d){ return d[0].group; })
                .style("fill-opacity",.9)
                .style("fill", function (d) { return colors()(d[0].group); });

        if (!showLabels()) return;

        g.append('defs');

        g.select('defs')
            .selectAll('path')
            .data(layers)
            .enter().append('path')
            .attr('id', function(d,i) { return 'path-' + i; })
            .attr('d', line);

        g.selectAll("text.label")
            .data(layers)
            .enter().append('text')
            .attr('dy', '0.5ex')
            .attr("class","label")
           .append('textPath')
            .attr('xlink:xlink:href', function(d,i) { return '#path-' + i; })
            .attr('startOffset', function(d) {
                var maxYr = 0, maxV = 0;
                d3.range(layers[0].length).forEach(function(i) {
                    if (d[i].y > maxV) {
                        maxV = d[i].y;
                        maxYr = i;
                    }
                });
                d.maxVal = d[maxYr].y;
                d.offset = Math.round(x(d[maxYr].x) / x.range()[1] * 100);
                return Math.min(95, Math.max(5, d.offset))+'%';
            })
            .attr('text-anchor', function(d) {
                return d.offset > 90 ? 'end' : d.offset < 10 ? 'start' : 'middle';
            })
            .text(function(d){ return d[0].group; })
            .style("font-size","11px")
            .style("font-family","Arial, Helvetica")
            .style("font-weight","normal")

        function sortBy(a,b){
            if (sort() == 'value (descending)') return a.y - b.y;
            if (sort() == 'value (ascending)') return b.y - a.y;
            if (sort() == 'group') return a.group - b.group;
        }

        function interpolate(points) {
          var x0 = points[0][0], y0 = points[0][1], x1, y1, x2,
              path = [x0, ",", y0],
              i = 0,
              n = points.length;

          while (++i < n) {
            x1 = points[i][0], y1 = points[i][1], x2 = (x0 + x1) / 2;
            path.push("C", x2, ",", y0, " ", x2, ",", y1, " ", x1, ",", y1);
            x0 = x1, y0 = y1;
          }
          return path.join("");
        }
    })

})();
<|endoftext|>


<commit_before>// Data

var standard_licenses_datasets = [{"label": "Standard license","color":"#27AE60","value": 166}, {"label": "Non-standard license","color":"#CCCCCC","value": 11806}];
var standard_licenses_occurrences = [{"label": "Standard license","color":"#27AE60","value": 9899370}, {"label": "Non-standard license","color":"#CCCCCC","value": 405513274}];
var general_use_parameters_datasets = [{"key": "Open", "color": "#27AE60", "values": [{"value": 905, "label": "Use"}, {"value": 647, "label": "Distribution"}, {"value": 731, "label": "Derivatives"}, {"value": 582, "label": "Commercial use"}, {"value": 213, "label": "Attribution"}, {"value": 178, "label": "Share alike"}, {"value": 738, "label": "Notification"}]}, {"key": "Unclear", "color": "#CCCCCC", "values": [{"value": 10980, "label": "Use"}, {"value": 10975, "label": "Distribution"}, {"value": 10998, "label": "Derivatives"}, {"value": 11098, "label": "Commercial use"}, {"value": 11139, "label": "Attribution"}, {"value": 11761, "label": "Share alike"}, {"value": 11056, "label": "Notification"}]}, {"key": "Restricted/Required", "color": "#C0392B", "values": [{"value": 87, "label": "Use"}, {"value": 350, "label": "Distribution"}, {"value": 243, "label": "Derivatives"}, {"value": 292, "label": "Commercial use"}, {"value": 620, "label": "Attribution"}, {"value": 33, "label": "Share alike"}, {"value": 178, "label": "Notification"}]}];
var general_use_parameters_occurrences = [{"key": "Open", "color": "#27AE60", "values": [{"value": 69775276, "label": "Use"}, {"value": 54581128, "label": "Distribution"}, {"value": 62048951, "label": "Derivatives"}, {"value": 46952477, "label": "Commercial use"}, {"value": 15075888, "label": "Attribution"}, {"value": 19026470, "label": "Share alike"}, {"value": 60420353, "label": "Notification"}]}, {"key": "Unclear", "color": "#CCCCCC", "values": [{"value": 343204732, "label": "Use"}, {"value": 343830898, "label": "Distribution"}, {"value": 339051254, "label": "Derivatives"}, {"value": 339168747, "label": "Commercial use"}, {"value": 333938837, "label": "Attribution"}, {"value": 395366713, "label": "Share alike"}, {"value": 332509768, "label": "Notification"}]}, {"key": "Restriced/Required", "color": "#C0392B", "values": [{"value": 2432636, "label": "Use"}, {"value": 17000618, "label": "Distribution"}, {"value": 14312439, "label": "Derivatives"}, {"value": 29291420, "label": "Commercial use"}, {"value": 66397919, "label": "Attribution"}, {"value": 1019461, "label": "Share alike"}, {"value": 22482523, "label": "Notification"}]}];

// Add charts to HTML

addPieChart("#chart1","Datasets",standard_licenses_datasets);
addPieChart("#chart2","Occurrences",standard_licenses_occurrences);
addMultiHorizontalBarChart("#chart3","Datasets",general_use_parameters_datasets);
addMultiHorizontalBarChart("#chart4","Occurrences",general_use_parameters_occurrences);

// Functions

function addPieChart(element,title,data) {
    // Use this patch for colors to work: https://github.com/novus/nvd3/commit/7dcb8d899bbe6279a71c25e9ea309344924029b9
    nv.addGraph(function() {
        var chart = nv.models.pieChart()
        .x(function(d) {return d.label })
        .y(function(d) {return d.value })
        .valueFormat(d3.format(',.0f'))
        .showLabels(false)
        .donut(true);

        d3.select(element)
        .datum(data)
        .transition()
        .duration(1200)
        .call(chart);

        d3.select(element)
        .append("text")
        .attr("x","50%")
        .attr("y","52%")
        .attr("text-anchor","middle")
        .attr("class","title")
        .text(title);

        nv.utils.windowResize(chart.update);

        return chart;
    });
}

function addMultiHorizontalBarChart(element,title,data) {
    nv.addGraph(function() {
        var chart = nv.models.multiBarHorizontalChart()
        .x(function(d) {return d.label})
        .y(function(d) {return d.value})
        .transitionDuration(100)
        .margin({left: 100})
        .stacked(true);

        d3.select(element)
        .datum(data)
        .transition()
        .duration(500)
        .call(chart);

        nv.utils.windowResize(chart.update);

        return chart;
    });
}
<commit_msg>Edit valueFormat<commit_after>// Data

var standard_licenses_datasets = [{"label": "Standard license","color":"#27AE60","value": 166}, {"label": "Non-standard license","color":"#CCCCCC","value": 11806}];
var standard_licenses_occurrences = [{"label": "Standard license","color":"#27AE60","value": 9899370}, {"label": "Non-standard license","color":"#CCCCCC","value": 405513274}];
var general_use_parameters_datasets = [{"key": "Open", "color": "#27AE60", "values": [{"value": 905, "label": "Use"}, {"value": 647, "label": "Distribution"}, {"value": 731, "label": "Derivatives"}, {"value": 582, "label": "Commercial use"}, {"value": 213, "label": "Attribution"}, {"value": 178, "label": "Share alike"}, {"value": 738, "label": "Notification"}]}, {"key": "Unclear", "color": "#CCCCCC", "values": [{"value": 10980, "label": "Use"}, {"value": 10975, "label": "Distribution"}, {"value": 10998, "label": "Derivatives"}, {"value": 11098, "label": "Commercial use"}, {"value": 11139, "label": "Attribution"}, {"value": 11761, "label": "Share alike"}, {"value": 11056, "label": "Notification"}]}, {"key": "Restricted/Required", "color": "#C0392B", "values": [{"value": 87, "label": "Use"}, {"value": 350, "label": "Distribution"}, {"value": 243, "label": "Derivatives"}, {"value": 292, "label": "Commercial use"}, {"value": 620, "label": "Attribution"}, {"value": 33, "label": "Share alike"}, {"value": 178, "label": "Notification"}]}];
var general_use_parameters_occurrences = [{"key": "Open", "color": "#27AE60", "values": [{"value": 69775276, "label": "Use"}, {"value": 54581128, "label": "Distribution"}, {"value": 62048951, "label": "Derivatives"}, {"value": 46952477, "label": "Commercial use"}, {"value": 15075888, "label": "Attribution"}, {"value": 19026470, "label": "Share alike"}, {"value": 60420353, "label": "Notification"}]}, {"key": "Unclear", "color": "#CCCCCC", "values": [{"value": 343204732, "label": "Use"}, {"value": 343830898, "label": "Distribution"}, {"value": 339051254, "label": "Derivatives"}, {"value": 339168747, "label": "Commercial use"}, {"value": 333938837, "label": "Attribution"}, {"value": 395366713, "label": "Share alike"}, {"value": 332509768, "label": "Notification"}]}, {"key": "Restriced/Required", "color": "#C0392B", "values": [{"value": 2432636, "label": "Use"}, {"value": 17000618, "label": "Distribution"}, {"value": 14312439, "label": "Derivatives"}, {"value": 29291420, "label": "Commercial use"}, {"value": 66397919, "label": "Attribution"}, {"value": 1019461, "label": "Share alike"}, {"value": 22482523, "label": "Notification"}]}];

// Add charts to HTML

addPieChart("#chart1","Datasets",standard_licenses_datasets);
addPieChart("#chart2","Occurrences",standard_licenses_occurrences);
addMultiHorizontalBarChart("#chart3","Datasets",general_use_parameters_datasets);
addMultiHorizontalBarChart("#chart4","Occurrences",general_use_parameters_occurrences);

// Functions

function addPieChart(element,title,data) {
    // Use this patch for colors to work: https://github.com/novus/nvd3/commit/7dcb8d899bbe6279a71c25e9ea309344924029b9
    nv.addGraph(function() {
        var chart = nv.models.pieChart()
        .x(function(d) {return d.label })
        .y(function(d) {return d.value })
        .valueFormat(d3.format("f"))
        .showLabels(false)
        .donut(true);

        d3.select(element)
        .datum(data)
        .transition()
        .duration(1200)
        .call(chart);

        d3.select(element)
        .append("text")
        .attr("x","50%")
        .attr("y","52%")
        .attr("text-anchor","middle")
        .attr("class","title")
        .text(title);

        nv.utils.windowResize(chart.update);

        return chart;
    });
}

function addMultiHorizontalBarChart(element,title,data) {
    nv.addGraph(function() {
        var chart = nv.models.multiBarHorizontalChart()
        .x(function(d) {return d.label})
        .y(function(d) {return d.value})
        .valueFormat(d3.format('f')) // Doesn't seem to have an effect
        .transitionDuration(100)
        .margin({left: 100})
        .stacked(true);

        d3.select(element)
        .datum(data)
        .transition()
        .duration(500)
        .call(chart);

        nv.utils.windowResize(chart.update);

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


<commit_before>var Future = require('fibers/future');
var files = require('./files.js');
var path = require('path');
var fs = require('fs');
var unipackage = require('./unipackage.js');
var Fiber = require('fibers');
var request = require('request');

// a bit of a hack
var _meteor;
var getMeteor = function (context) {
  if (! _meteor) {
    _meteor = unipackage.load({
      library: context.library,
      packages: [ 'livedata', 'mongo-livedata' ],
      release: context.releaseVersion
    }).meteor.Meteor;
  }

  return _meteor;
};

var _galaxy;
var getGalaxy = function (context) {
  if (! _galaxy) {
    var Meteor = getMeteor(context);
    if (!context.galaxy) {
      process.stderr.write("Could not find a deploy endpoint. " +
                           "You can set the GALAXY environment variable, " +
                           "or configure your site's DNS to resolve to " +
                           "your Galaxy's proxy.\n");
      process.exit(1);
    }

    _galaxy = Meteor.connect(context.galaxy.url);
  }

  return _galaxy;
};

var exitWithError = function (error, messages) {
  messages = messages || {};
  var msg = messages[error.error];
  if (msg)
    process.stderr.write(msg + "\n");
  else if (error.message)
    process.stderr.write("Denied: " + error.message + "\n");

  process.exit(1);
};

// XXX copied from galaxy/tool/galaxy.js
var prettyCall = function (galaxy, name, args, messages) {
  try {
    var ret = galaxy.apply(name, args);
  } catch (e) {
    exitWithError(e, messages);
  }
  return ret;
};

var prettySub = function (galaxy, name, args, messages) {
  var onError = function (e) {
    exitWithError(e, messages);
  };

  try {
    var ret = galaxy._subscribeAndWait(name, args, {onLateError: onError});
  } catch (e) {
    onError(e);
  }
  return ret;
};

exports.discoverGalaxy = function (app) {
  app = app + ":" + (process.env.DISCOVERY_PORT || 443);
  var url = "https://" + app + "/_GALAXY_";
  var fut = new Future();

  if (process.env.GALAXY)
    return process.env.GALAXY;

  request(url, function (err, resp, body) {
    if (err || resp.statusCode !== 200) {
      fut.return(null);
    } else {
      try {
        fut.return(body);
      } catch (e) {
        fut.return(null);
      }
    }
  });
  return fut.wait();
};

exports.deleteApp = function (context) {
  throw new Error("Not implemented");
};

// options:
// - context
// - app
// - appDir
// - settings
// - bundleOptions
// - starball
// XXX refactor this to separate the "maybe bundle" part from "actually deploy"
//     so we can be careful to not rely on any of the app dir context when
//     in --star mode.
exports.deploy = function (options) {
  var galaxy = getGalaxy(options.context);
  var Meteor = getMeteor(options.context);

  var tmpdir = files.mkdtemp('deploy');
  var buildDir = path.join(tmpdir, 'build');
  var topLevelDirName = path.basename(options.appDir);
  var bundlePath = path.join(buildDir, topLevelDirName);
  var bundler = require('./bundler.js');
  var starball;
  if (!options.starball) {
    process.stdout.write('Deploying ' + options.app + '. Bundling...\n');
    var bundleResult = bundler.bundle(options.appDir, bundlePath,
                                      options.bundleOptions);
    if (bundleResult.errors) {
      process.stdout.write("\n\nErrors prevented deploying:\n");
      process.stdout.write(bundleResult.errors.formatMessages());
      process.exit(1);
    }

    // S3 (which is what's likely on the other end our upload) requires
    // a content-length header for HTTP PUT uploads. That means that we
    // have to actually tgz up the bundle before we can start the upload
    // rather than streaming it. S3 has an alternate API for doing
    // chunked uploads, but (a) it has a minimum chunk size of 5 MB, so
    // it doesn't help us much (many/most stars will be smaller than
    // that), and (b) it's nonstandard, so we'd have to bake in S3's
    // specific scheme. Doesn't seem worthwhile for now, so just tar to
    // a temporary directory. If stars get radically bigger then it
    // might be worthwhile to tar to memory and spill to S3 every 5MB.
    starball = path.join(tmpdir, topLevelDirName + ".tar.gz");
    files.createTarball(bundlePath, starball);
  } else {
    starball = options.starball;
  }
  process.stdout.write('Uploading...\n');

  var created = true;
  try {
    galaxy.call('createApp', options.app);
  } catch (e) {
    if (e instanceof Meteor.Error && e.error === 'already-exists') {
      // Cool, it already exists. No problem.
      created = false;
    } else {
      exitWithError(e);
    }
  }

  // Get the upload information from Galaxy. It's a surprise if this
  // fails (we already know the app exists.)
  var info = prettyCall(galaxy, 'beginUploadStar', [options.app]);

  // Upload
  // XXX copied from galaxy/tool/galaxy.js
  var fileSize = fs.statSync(starball).size;
  var fileStream = fs.createReadStream(starball);
  var future = new Future;
  var req = request.put({
    url: info.put,
    headers: { 'content-length': fileSize,
               'content-type': 'application/octet-stream' },
    strictSSL: true
  }, function (error, response, body) {
    if (error || ((response.statusCode !== 200)
                  && (response.statusCode !== 201))) {
      if (error && error.message)
        process.stderr.write("Upload failed: " + error.message + "\n");
      else
        process.stderr.write("Upload failed" +
                             (response.statusCode ?
                              " (" + response.statusCode + ")\n" : "\n"));
      process.exit(1);
    }
    future.return();
  });

  fileStream.pipe(req);
  future.wait();

  var result = prettyCall(galaxy, 'completeUploadStar', [info.id], {
    'no-such-upload': 'Upload request expired. Try again.'
  });

  if (created)
    process.stderr.write(options.app + ": created app\n");

  process.stderr.write(options.app + ": " +
                       "pushed revision " + result.serial + "\n");
  // Close the connection to Galaxy (otherwise Node will continue running).
  galaxy.close();
};

// options:
// - context
// - app
// - streaming (BOOL)
exports.logs = function (options) {
  var logReaderURL;
  if (options.context.galaxy.adminBaseUrl) {
    logReaderURL = options.context.galaxy.adminBaseUrl + "log-reader";
  } else {
    var galaxy = getGalaxy(options.context);
    logReaderURL = prettyCall(galaxy, "getLogReaderURL", [], {
      'no-log-reader': "Can't find log reader service"
    });
    galaxy.close();
  }

  var logReader = getMeteor(options.context).connect(logReaderURL);
  var Log = unipackage.load({
    library: options.context.library,
    packages: [ 'logging' ],
    release: options.context.releaseVersion
  }).logging.Log;

  var ok = logReader.registerStore('logs', {
    update: function (msg) {
      // Ignore all messages but 'changed'
      if (msg.msg !== 'changed')
        return;
      var obj = msg.fields.obj;
      obj = Log.parse(obj);
      obj && console.log(Log.format(obj, {color: true}));
    }
  });

  if (!ok)
    throw new Error("Can't listen to messages on the logs collection");

  prettySub(logReader, "logsForApp", [options.app,
                                      {streaming: options.streaming}], {
    "no-such-app": "No such app: " + options.app
  });

  // if streaming is needed there is no point in closing connection
  if (!options.streaming) {
    // Close connections to Galaxy and log-reader
    // (otherwise Node will continue running).
    logReader.close();
  } else {
    Fiber.yield();
  }
};

// options:
// - context
// - app
exports.temporaryMongoUrl = function (options) {
  var galaxy = getGalaxy(options.context);
  return galaxy.call('getTemporaryMongoUrl', options.app);
};
<commit_msg>Continue streaming from the last seen log on reconnect in logs -f.<commit_after>var Future = require('fibers/future');
var files = require('./files.js');
var path = require('path');
var fs = require('fs');
var unipackage = require('./unipackage.js');
var Fiber = require('fibers');
var request = require('request');

// a bit of a hack
var _meteor;
var getMeteor = function (context) {
  if (! _meteor) {
    _meteor = unipackage.load({
      library: context.library,
      packages: [ 'livedata', 'mongo-livedata' ],
      release: context.releaseVersion
    }).meteor.Meteor;
  }

  return _meteor;
};

var _galaxy;
var getGalaxy = function (context) {
  if (! _galaxy) {
    var Meteor = getMeteor(context);
    if (!context.galaxy) {
      process.stderr.write("Could not find a deploy endpoint. " +
                           "You can set the GALAXY environment variable, " +
                           "or configure your site's DNS to resolve to " +
                           "your Galaxy's proxy.\n");
      process.exit(1);
    }

    _galaxy = Meteor.connect(context.galaxy.url);
  }

  return _galaxy;
};

var exitWithError = function (error, messages) {
  messages = messages || {};
  var msg = messages[error.error];
  if (msg)
    process.stderr.write(msg + "\n");
  else if (error.message)
    process.stderr.write("Denied: " + error.message + "\n");

  process.exit(1);
};

// XXX copied from galaxy/tool/galaxy.js
var prettyCall = function (galaxy, name, args, messages) {
  try {
    var ret = galaxy.apply(name, args);
  } catch (e) {
    exitWithError(e, messages);
  }
  return ret;
};

var prettySub = function (galaxy, name, args, messages) {
  var onError = function (e) {
    exitWithError(e, messages);
  };

  try {
    var ret = galaxy._subscribeAndWait(name, args, {onLateError: onError});
  } catch (e) {
    onError(e);
  }
  return ret;
};

exports.discoverGalaxy = function (app) {
  app = app + ":" + (process.env.DISCOVERY_PORT || 443);
  var url = "https://" + app + "/_GALAXY_";
  var fut = new Future();

  if (process.env.GALAXY)
    return process.env.GALAXY;

  request(url, function (err, resp, body) {
    if (err || resp.statusCode !== 200) {
      fut.return(null);
    } else {
      try {
        fut.return(body);
      } catch (e) {
        fut.return(null);
      }
    }
  });
  return fut.wait();
};

exports.deleteApp = function (context) {
  throw new Error("Not implemented");
};

// options:
// - context
// - app
// - appDir
// - settings
// - bundleOptions
// - starball
// XXX refactor this to separate the "maybe bundle" part from "actually deploy"
//     so we can be careful to not rely on any of the app dir context when
//     in --star mode.
exports.deploy = function (options) {
  var galaxy = getGalaxy(options.context);
  var Meteor = getMeteor(options.context);

  var tmpdir = files.mkdtemp('deploy');
  var buildDir = path.join(tmpdir, 'build');
  var topLevelDirName = path.basename(options.appDir);
  var bundlePath = path.join(buildDir, topLevelDirName);
  var bundler = require('./bundler.js');
  var starball;
  if (!options.starball) {
    process.stdout.write('Deploying ' + options.app + '. Bundling...\n');
    var bundleResult = bundler.bundle(options.appDir, bundlePath,
                                      options.bundleOptions);
    if (bundleResult.errors) {
      process.stdout.write("\n\nErrors prevented deploying:\n");
      process.stdout.write(bundleResult.errors.formatMessages());
      process.exit(1);
    }

    // S3 (which is what's likely on the other end our upload) requires
    // a content-length header for HTTP PUT uploads. That means that we
    // have to actually tgz up the bundle before we can start the upload
    // rather than streaming it. S3 has an alternate API for doing
    // chunked uploads, but (a) it has a minimum chunk size of 5 MB, so
    // it doesn't help us much (many/most stars will be smaller than
    // that), and (b) it's nonstandard, so we'd have to bake in S3's
    // specific scheme. Doesn't seem worthwhile for now, so just tar to
    // a temporary directory. If stars get radically bigger then it
    // might be worthwhile to tar to memory and spill to S3 every 5MB.
    starball = path.join(tmpdir, topLevelDirName + ".tar.gz");
    files.createTarball(bundlePath, starball);
  } else {
    starball = options.starball;
  }
  process.stdout.write('Uploading...\n');

  var created = true;
  try {
    galaxy.call('createApp', options.app);
  } catch (e) {
    if (e instanceof Meteor.Error && e.error === 'already-exists') {
      // Cool, it already exists. No problem.
      created = false;
    } else {
      exitWithError(e);
    }
  }

  // Get the upload information from Galaxy. It's a surprise if this
  // fails (we already know the app exists.)
  var info = prettyCall(galaxy, 'beginUploadStar', [options.app]);

  // Upload
  // XXX copied from galaxy/tool/galaxy.js
  var fileSize = fs.statSync(starball).size;
  var fileStream = fs.createReadStream(starball);
  var future = new Future;
  var req = request.put({
    url: info.put,
    headers: { 'content-length': fileSize,
               'content-type': 'application/octet-stream' },
    strictSSL: true
  }, function (error, response, body) {
    if (error || ((response.statusCode !== 200)
                  && (response.statusCode !== 201))) {
      if (error && error.message)
        process.stderr.write("Upload failed: " + error.message + "\n");
      else
        process.stderr.write("Upload failed" +
                             (response.statusCode ?
                              " (" + response.statusCode + ")\n" : "\n"));
      process.exit(1);
    }
    future.return();
  });

  fileStream.pipe(req);
  future.wait();

  var result = prettyCall(galaxy, 'completeUploadStar', [info.id], {
    'no-such-upload': 'Upload request expired. Try again.'
  });

  if (created)
    process.stderr.write(options.app + ": created app\n");

  process.stderr.write(options.app + ": " +
                       "pushed revision " + result.serial + "\n");
  // Close the connection to Galaxy (otherwise Node will continue running).
  galaxy.close();
};

// options:
// - context
// - app
// - streaming (BOOL)
exports.logs = function (options) {
  var logReaderURL;
  if (options.context.galaxy.adminBaseUrl) {
    logReaderURL = options.context.galaxy.adminBaseUrl + "log-reader";
  } else {
    var galaxy = getGalaxy(options.context);
    logReaderURL = prettyCall(galaxy, "getLogReaderURL", [], {
      'no-log-reader': "Can't find log reader service"
    });
    galaxy.close();
  }

  var lastLog = null;
  var logReader = getMeteor(options.context).connect(logReaderURL);
  var Log = unipackage.load({
    library: options.context.library,
    packages: [ 'logging' ],
    release: options.context.releaseVersion
  }).logging.Log;

  var ok = logReader.registerStore('logs', {
    update: function (msg) {
      // Ignore all messages but 'changed'
      if (msg.msg !== 'changed')
        return;
      var obj = msg.fields.obj;
      lastLog = obj;
      obj = Log.parse(obj);
      obj && console.log(Log.format(obj, {color: true}));
    }
  });

  if (!ok)
    throw new Error("Can't listen to messages on the logs collection");

  var logsSubscription = null;
  // In case of reconnect recover the state so user sees only new logs
  logReader.onReconnect = function () {
    if (!lastLog)
      lastLog = "";
    logsSubscription && logsSubscription.stop();
    logsSubscription = logReader.subscribe("logsForApp", options.app,
                        {streaming: options.streaming, startingLog: lastLog});
  };
  logsSubscription = prettySub(logReader, "logsForApp", [options.app,
                                      {streaming: options.streaming}], {
    "no-such-app": "No such app: " + options.app
  });

  // if streaming is needed there is no point in closing connection
  if (!options.streaming) {
    // Close connections to Galaxy and log-reader
    // (otherwise Node will continue running).
    logReader.close();
  } else {
    Fiber.yield();
  }
};

// options:
// - context
// - app
exports.temporaryMongoUrl = function (options) {
  var galaxy = getGalaxy(options.context);
  return galaxy.call('getTemporaryMongoUrl', options.app);
};
<|endoftext|>


<commit_before>"use strict";
define(function(){
	return Backbone.View.extend({
		app:null,
		name:null,
		locale:{},
		subviews:[],
		renderedSubviews:{},
		parent:null,
		_isModal:false,
		_dataId:null,
		initialize:function(){
			this.renderedSubviews={};
			if(typeof this.app == 'string'){
				this.app = openbiz.apps[this.app];
				this.initLocale();
			}
			if(typeof this.model == 'function')this.model = new this.model();
			if(typeof this.template == 'string')this.template = _.template(this.template);
			if(typeof this.metadata == 'string')this.metadata = openbiz.MetadataParser.call(this,this.metadata)
			return this;
		},
		undelegateEvents:function(){
			if(typeof this.renderedSubviews=='object'){
				for(var viewName in this.renderedSubviews){
					var subView = this.renderedSubviews[viewName];
					subView.undelegateEvents();
				}
			}
			Backbone.View.prototype.undelegateEvents.apply(this,arguments);
			return this;
		},
		delegateEvents:function(){
			Backbone.View.prototype.delegateEvents.apply(this,arguments);
			if(typeof this.renderedSubviews=='object'){
				for(var viewName in this.renderedSubviews){
					var subView = this.renderedSubviews[viewName];
					subView.delegateEvents();
					if(typeof subView["_bindEvents"] == "function"){
						subView._bindEvents();
					}
				}
			}
			return this;
		},
		initLocale:function(){
			if(this.name && this.module && this.app ){
				if(this.app.locale.hasOwnProperty(this.module) &&
                    this.app.locale[this.module].hasOwnProperty(this.name) )
					this.locale = this.app.locale[this.module][this.name];
				this.locale.loading = this.app.locale.loading;
				this.locale.app = this.app.locale.app;
                this.locale.breadcrumb = this.app.locale.breadcrumb;
			}
			this.locale.appUrl 	= this.app.appUrl;
			this.locale.baseUrl = this.app.baseUrl;
			return this;
		},
		switchView:function(viewName){
			if(this.app==null)return;
	    	var callback,args=[],self=this;;
	    	switch(arguments.length){
	    		case 2:
	    			if(typeof arguments[1]=='function'){
	    				callback = arguments[1];
	    			}else if(typeof arguments[1]=='object'){
	    				args = arguments[1];
	    			}
	    			break;
	    		case 3:
	    			args = arguments[1];
	    			callback = arguments[2];
	    			break;
	    	}
	    	var viewArr = viewName.split(".");
	    	var viewPath = "./modules/"+viewArr[0]+"/views/"+viewArr[1];
	    	$(self.el).fadeOut(function(){
				self.undelegateEvents();
				if(self.app.views.isRenderred(viewName)){
					self.app.views.get(viewName).undelegateEvents();
				}
	            self.app.views.render(viewName,args,function(view){
	            	var viewHTML = $(view.$el);

	                self.$el.replaceWith(viewHTML);
	                view.delegateEvents();
	                try{
		                self.on('hidden.bs.modal',function(){
		                	view.undelegateEvents();
		                });
	            	}catch(e){};
	                openbiz.ui.update($(self.$el));
	                if(typeof callback =='function'){
	                    callback();
	                }
	            });
			});
		},
		addSubView:function(viewName){
			if(this.app==null)return;
			var callback,args=[],self=this;;
			switch(arguments.length){
				case 2:
					if(typeof arguments[1]=='function'){
						callback = arguments[1];
					}else if(typeof arguments[1]=='object'){
						args = arguments[1];
					}
					break;
				case 3:
					args = arguments[1];
					callback = arguments[2];
					break;
			}
			var viewArr = viewName.split(".");
			if(self.app.views.isRenderred(viewName)){
				self.app.views.get(viewName).undelegateEvents();
			}
			self.app.views.render(viewName,args,function(view){
				view.delegateEvents();
				openbiz.ui.update($(view.el));
				if(typeof callback =='function'){
					callback();
				}
			});
		},
		popupView:function(viewName){
			if(this.app==null)return;
	    	var callback,args=[],self=this;;
	    	switch(arguments.length){
	    		case 2:
	    			if(typeof arguments[1]=='function'){
	    				callback = arguments[1];
	    			}else if(typeof arguments[1]=='object'){
	    				args = arguments[1];
	    			}
	    			break;
	    		case 3:
	    			args = arguments[1];
	    			callback = arguments[2];
	    			break;
	    	}
	    	var viewArr = viewName.split(".");
	    	var viewPath = "./modules/"+viewArr[0]+"/views/"+viewArr[1];
	    	var parentView = openbiz.session.currentView;
	    	parentView.undelegateEvents();
	    	if(self.app.views.isRenderred(viewName)){
				self.app.views.get(viewName).undelegateEvents();
			}
            self.app.views.render(viewName,args,function(view){
            	var $modal = $(view.$el);
            	view.delegateEvents();
	            view.parent = parentView;
                $modal.modal();
                $modal.on('hidden.bs.modal',function(){
                	view.undelegateEvents();
                	openbiz.session.currentView=parentView;
                	parentView.delegateEvents();
                });
                openbiz.ui.update($modal);
                if(typeof callback =='function'){
                    callback();
                }
            });
		},
		render:function(){
			var output={
				locale:this.locale
			}
	        $(this.el).html(this.template(output));
        	openbiz.ui.update($(this.el));
			this.renderSubviews();
 	        return this;
	    },
	    renderSubviews:function(){
	    	var self = this;
	    	if(typeof this.metadata.subviews=='undefined') return;
	    	for(var i =0;i<this.metadata.subviews.length;i++){
	    		var subviewConfig = this.metadata.subviews[i];
	    		var viewConfig = subviewConfig.view.split(".");
	    		var viewFile = "modules/"+viewConfig[0]+"/views/"+viewConfig[1];
	    		this.app.require([viewFile],function(viewClass){
	    			var view = new viewClass();
	    			view.parent =self;
				    if(self._dataId != null)
				    {
					    view.render(self._dataId);
				    }else{
					    view.render();
				    }
	    			self.renderedSubviews[view.metadata.name]=view;
	    		});
	    	}
	    },
		_canDisplayView:function(){
			if(typeof this.metadata.permission == 'undefined' || this.metadata.permission == null){
				return true;
			}
			return openbiz.session.me.hasPermission(this.metadata.permission);
		},
		_renderNoPermissionView:function(){
			//render 403 page
			console.log("no permission");
			this.app = openbiz.apps.cubi;
			this.switchView('common.NoPermissionView');
		}

	});
});<commit_msg>add popupPickerView function<commit_after>"use strict";
define(function(){
	return Backbone.View.extend({
		app:null,
		name:null,
		locale:{},
		subviews:[],
		renderedSubviews:{},
		parent:null,
		_isModal:false,
		_dataId:null,
		initialize:function(){
			this.renderedSubviews={};
			if(typeof this.app == 'string'){
				this.app = openbiz.apps[this.app];
				this.initLocale();
			}
			if(typeof this.model == 'function')this.model = new this.model();
			if(typeof this.template == 'string')this.template = _.template(this.template);
			if(typeof this.metadata == 'string')this.metadata = openbiz.MetadataParser.call(this,this.metadata)
			return this;
		},
		undelegateEvents:function(){
			if(typeof this.renderedSubviews=='object'){
				for(var viewName in this.renderedSubviews){
					var subView = this.renderedSubviews[viewName];
					subView.undelegateEvents();
				}
			}
			Backbone.View.prototype.undelegateEvents.apply(this,arguments);
			return this;
		},
		delegateEvents:function(){
			Backbone.View.prototype.delegateEvents.apply(this,arguments);
			if(typeof this.renderedSubviews=='object'){
				for(var viewName in this.renderedSubviews){
					var subView = this.renderedSubviews[viewName];
					subView.delegateEvents();
					if(typeof subView["_bindEvents"] == "function"){
						subView._bindEvents();
					}
				}
			}
			return this;
		},
		initLocale:function(){
			if(this.name && this.module && this.app ){
				if(this.app.locale.hasOwnProperty(this.module) &&
                    this.app.locale[this.module].hasOwnProperty(this.name) )
					this.locale = this.app.locale[this.module][this.name];
				this.locale.loading = this.app.locale.loading;
				this.locale.app = this.app.locale.app;
                this.locale.breadcrumb = this.app.locale.breadcrumb;
			}
			this.locale.appUrl 	= this.app.appUrl;
			this.locale.baseUrl = this.app.baseUrl;
			return this;
		},
		switchView:function(viewName){
			if(this.app==null)return;
	    	var callback,args=[],self=this;;
	    	switch(arguments.length){
	    		case 2:
	    			if(typeof arguments[1]=='function'){
	    				callback = arguments[1];
	    			}else if(typeof arguments[1]=='object'){
	    				args = arguments[1];
	    			}
	    			break;
	    		case 3:
	    			args = arguments[1];
	    			callback = arguments[2];
	    			break;
	    	}
	    	var viewArr = viewName.split(".");
	    	var viewPath = "./modules/"+viewArr[0]+"/views/"+viewArr[1];
	    	$(self.el).fadeOut(function(){
				self.undelegateEvents();
				if(self.app.views.isRenderred(viewName)){
					self.app.views.get(viewName).undelegateEvents();
				}
	            self.app.views.render(viewName,args,function(view){
	            	var viewHTML = $(view.$el);

	                self.$el.replaceWith(viewHTML);
	                view.delegateEvents();
	                try{
		                self.on('hidden.bs.modal',function(){
		                	view.undelegateEvents();
		                });
	            	}catch(e){};
	                openbiz.ui.update($(self.$el));
	                if(typeof callback =='function'){
	                    callback();
	                }
	            });
			});
		},
		addSubView:function(viewName){
			if(this.app==null)return;
			var callback,args=[],self=this;;
			switch(arguments.length){
				case 2:
					if(typeof arguments[1]=='function'){
						callback = arguments[1];
					}else if(typeof arguments[1]=='object'){
						args = arguments[1];
					}
					break;
				case 3:
					args = arguments[1];
					callback = arguments[2];
					break;
			}
			var viewArr = viewName.split(".");
			if(self.app.views.isRenderred(viewName)){
				self.app.views.get(viewName).undelegateEvents();
			}
			self.app.views.render(viewName,args,function(view){
				view.delegateEvents();
				openbiz.ui.update($(view.el));
				if(typeof callback =='function'){
					callback();
				}
			});
		},
		popupPickerView:function(viewName,callback){
			if(this.app==null)return;
	    	var callback,args=[],self=this;;

	    	var viewArr = viewName.split(".");
	    	var viewPath = "./modules/"+viewArr[0]+"/views/"+viewArr[1];
	    	var parentView = openbiz.session.currentView;
	    	parentView.undelegateEvents();
	    	if(self.app.views.isRenderred(viewName)){
				self.app.views.get(viewName).undelegateEvents();
			}
            self.app.views.render(viewName,args,function(view){
            	var $modal = $(view.$el);
            	view.delegateEvents();
	            view.parent = parentView;
	            view.onPickedRecord = callback;
                $modal.modal();
                $modal.on('hidden.bs.modal',function(){
                	view.undelegateEvents();
                	openbiz.session.currentView=parentView;
                	parentView.delegateEvents();
                });
                openbiz.ui.update($modal);
                if(typeof callback =='function'){
                    callback();
                }
            });
		},
		popupView:function(viewName){
			if(this.app==null)return;
	    	var callback,args=[],self=this;;
	    	switch(arguments.length){
	    		case 2:
	    			if(typeof arguments[1]=='function'){
	    				callback = arguments[1];
	    			}else if(typeof arguments[1]=='object'){
	    				args = arguments[1];
	    			}
	    			break;
	    		case 3:
	    			args = arguments[1];
	    			callback = arguments[2];
	    			break;
	    	}
	    	var viewArr = viewName.split(".");
	    	var viewPath = "./modules/"+viewArr[0]+"/views/"+viewArr[1];
	    	var parentView = openbiz.session.currentView;
	    	parentView.undelegateEvents();
	    	if(self.app.views.isRenderred(viewName)){
				self.app.views.get(viewName).undelegateEvents();
			}
            self.app.views.render(viewName,args,function(view){
            	var $modal = $(view.$el);
            	view.delegateEvents();
	            view.parent = parentView;
                $modal.modal();
                $modal.on('hidden.bs.modal',function(){
                	view.undelegateEvents();
                	openbiz.session.currentView=parentView;
                	parentView.delegateEvents();
                });
                openbiz.ui.update($modal);
                if(typeof callback =='function'){
                    callback();
                }
            });
		},
		render:function(){
			var output={
				locale:this.locale
			}
	        $(this.el).html(this.template(output));
        	openbiz.ui.update($(this.el));
			this.renderSubviews();
 	        return this;
	    },
	    renderSubviews:function(){
	    	var self = this;
	    	if(typeof this.metadata.subviews=='undefined') return;
	    	for(var i =0;i<this.metadata.subviews.length;i++){
	    		var subviewConfig = this.metadata.subviews[i];
	    		var viewConfig = subviewConfig.view.split(".");
	    		var viewFile = "modules/"+viewConfig[0]+"/views/"+viewConfig[1];
	    		this.app.require([viewFile],function(viewClass){
	    			var view = new viewClass();
	    			view.parent =self;
				    if(self._dataId != null)
				    {
					    view.render(self._dataId);
				    }else{
					    view.render();
				    }
	    			self.renderedSubviews[view.metadata.name]=view;
	    		});
	    	}
	    },
		_canDisplayView:function(){
			if(typeof this.metadata.permission == 'undefined' || this.metadata.permission == null){
				return true;
			}
			return openbiz.session.me.hasPermission(this.metadata.permission);
		},
		_renderNoPermissionView:function(){
			//render 403 page
			console.log("no permission");
			this.app = openbiz.apps.cubi;
			this.switchView('common.NoPermissionView');
		}

	});
});<|endoftext|>


<commit_before>var _ = require('underscore');

var buildmessage = require('./buildmessage.js');
var compiler = require('./compiler.js');
var files = require('./files.js');
var Isopack = require('./isopack.js').Isopack;
var utils = require('./utils.js');
var watch = require('./watch.js');
var colonConverter = require("./colon-converter.js");

exports.IsopackCache = function (options) {
  var self = this;
  options = options || {};

  // cacheDir may be null; in this case, we just don't ever save things to disk.
  self.cacheDir = options.cacheDir;

  // This is a bit of a hack, but basically: we really don't want to spend time
  // building web.cordova unibuilds in a project that doesn't have any Cordova
  // platforms. (Note that we need to be careful with 'meteor publish' to still
  // publish a web.cordova unibuild!)
  self._includeCordovaUnibuild = !! options.includeCordovaUnibuild;

  // Defines the versions of packages that we build. Must be set.
  self._packageMap = options.packageMap;

  // tropohouse may be null; in this case, we can't load versioned packages.
  // eg, for building isopackets.
  self._tropohouse = options.tropohouse;

  // If provided, this is another IsopackCache for the same cache dir; when
  // loading Isopacks, if they are definitely unchanged we can load the
  // in-memory objects from this cache instead of recompiling.
  self._previousIsopackCache = options.previousIsopackCache;
  if (self._previousIsopackCache &&
      self._previousIsopackCache.cacheDir !== self.cacheDir) {
    throw Error("previousIsopackCache has different cacheDir!");
  }

  // Map from package name to Isopack.
  self._isopacks = {};

  self._noLineNumbers = !! options.noLineNumbers;

  self.allLoadedLocalPackagesWatchSet = new watch.WatchSet;
};

_.extend(exports.IsopackCache.prototype, {
  buildLocalPackages: function (rootPackageNames) {
    var self = this;
    buildmessage.assertInCapture();

    if (self.cacheDir)
      files.mkdir_p(self.cacheDir);

    var onStack = {};
    if (rootPackageNames) {
      _.each(rootPackageNames, function (name) {
        self._ensurePackageLoaded(name, onStack);
      });
    } else {
      self._packageMap.eachPackage(function (name, packageInfo) {
        self._ensurePackageLoaded(name, onStack);
      });
    }
  },

  wipeCachedPackages: function (packages) {
    var self = this;
    // If we're not saving things to disk, there's nothing to wipe!
    if (! self.cacheDir)
      return;
    if (packages) {
      // Wipe specific packages.
      _.each(packages, function (packageName) {
        files.rm_recursive(self._isopackDir(packageName));
      });
    } else {
      // Wipe all packages.
      files.rm_recursive(self.cacheDir);
    }
  },

  // Returns the isopack (already loaded in memory) for a given name. It is an
  // error to call this if it's not already loaded! So it should only be called
  // after buildLocalPackages has returned, or in the process of building a
  // package whose dependencies have all already been built.
  getIsopack: function (name) {
    var self = this;
    if (! _.has(self._isopacks, name))
      throw Error("isopack " + name + " not yet loaded?");
    return self._isopacks[name];
  },

  eachBuiltIsopack: function (iterator) {
    var self = this;
    _.each(self._isopacks, function (isopack, packageName) {
      iterator(packageName, isopack);
    });
  },

  _ensurePackageLoaded: function (name, onStack) {
    var self = this;
    buildmessage.assertInCapture();
    if (_.has(self._isopacks, name))
      return;

    var ensureLoaded = function (depName) {
      if (_.has(onStack, depName)) {
        buildmessage.error("circular dependency between packages " +
                           name + " and " + depName);
        // recover by not enforcing one of the dependencies
        return;
      }
      onStack[depName] = true;
      self._ensurePackageLoaded(depName, onStack);
      delete onStack[depName];
    };

    var packageInfo = self._packageMap.getInfo(name);
    if (! packageInfo)
      throw Error("Depend on unknown package " + name + "?");
    var previousIsopack = null;
    if (self._previousIsopackCache &&
        _.has(self._previousIsopackCache._isopacks, name)) {
      var previousInfo = self._previousIsopackCache._packageMap.getInfo(name);
      if ((packageInfo.kind === 'versioned' &&
           previousInfo.kind === 'versioned' &&
           packageInfo.version === previousInfo.version) ||
          (packageInfo.kind === 'local' &&
           previousInfo.kind === 'local' &&
           (packageInfo.packageSource.sourceRoot ===
            previousInfo.packageSource.sourceRoot))) {
        previousIsopack = self._previousIsopackCache._isopacks[name];
      }
    }

    if (packageInfo.kind === 'local') {
      var packageNames =
            packageInfo.packageSource.getPackagesToLoadFirst(self._packageMap);
      buildmessage.enterJob("preparing to build package " + name, function () {
        _.each(packageNames, function (depName) {
          ensureLoaded(depName);
        });
        // If we failed to load something that this package depends on, don't
        // load it.
        if (buildmessage.jobHasMessages())
          return;
        self._loadLocalPackage(name, packageInfo, previousIsopack);
      });
    } else if (packageInfo.kind === 'versioned') {
      // We don't have to build this package, and we don't have to build its
      // dependencies either! Just load it from disk.

      if (!self._tropohouse) {
        throw Error("Can't load versioned packages without a tropohouse!");
      }

      var isopack = null, packagesToLoad = [];
      if (previousIsopack) {
        isopack = previousIsopack;
        packagesToLoad = isopack.getStrongOrderedUsedAndImpliedPackages();
      }
      if (! isopack) {
        // Load the isopack from disk.
        buildmessage.enterJob(
          "loading package " + name + "@" + packageInfo.version,
          function () {
            var isopackPath = self._tropohouse.packagePath(
              name, packageInfo.version);
            isopack = new Isopack();
            isopack.initFromPath(name, isopackPath);
            // If loading the isopack fails, then we don't need to look for more
            // packages to load, but we should still recover by putting it in
            // self._isopacks.
            if (buildmessage.jobHasMessages())
              return;
            packagesToLoad = isopack.getStrongOrderedUsedAndImpliedPackages();
          });
      }

      self._isopacks[name] = isopack;
      // Also load its dependencies. This is so that if this package is being
      // built as part of a plugin, all the transitive dependencies of the
      // plugin are loaded.
      _.each(packagesToLoad, function (packageToLoad) {
        ensureLoaded(packageToLoad);
      });
    } else {
      throw Error("unknown packageInfo kind?");
    }
  },

  _loadLocalPackage: function (name, packageInfo, previousIsopack) {
    var self = this;
    buildmessage.assertInCapture();
    buildmessage.enterJob("building package " + name, function () {
      var isopack;
      if (previousIsopack && self._checkUpToDatePreloaded(previousIsopack)) {
        isopack = previousIsopack;
      } else {
        // Do we have an up-to-date package on disk?
        var isopackBuildInfoJson = self.cacheDir && files.readJSONOrNull(
          self._isopackBuildInfoPath(name));
        var upToDate = self._checkUpToDate(isopackBuildInfoJson);

        if (upToDate) {
          isopack = new Isopack();
          isopack.initFromPath(name, self._isopackDir(name), {
            isopackBuildInfoJson: isopackBuildInfoJson
          });
        } else {
          // Nope! Compile it again.
          isopack = compiler.compile(packageInfo.packageSource, {
            packageMap: self._packageMap,
            isopackCache: self,
            noLineNumbers: self._noLineNumbers,
            includeCordovaUnibuild: self._includeCordovaUnibuild,
            includePluginProviderPackageMap: true
          });
          // Accept the compiler's result, even if there were errors (since it
          // at least will have a useful WatchSet and will allow us to keep
          // going and compile other packages that depend on this one).
          if (self.cacheDir && ! buildmessage.jobHasMessages()) {
            // Save to disk, for next time!
            isopack.saveToPath(self._isopackDir(name), {
              includeIsopackBuildInfo: true
            });
          }
        }
      }

      self.allLoadedLocalPackagesWatchSet.merge(isopack.getMergedWatchSet());
      self._isopacks[name] = isopack;
    });
  },

  _checkUpToDate: function (isopackBuildInfoJson) {
    var self = this;
    // If there isn't an isopack-buildinfo.json file, then we definitely aren't
    // up to date!
    if (! isopackBuildInfoJson)
      return false;

    // If we include Cordova but this Isopack doesn't, or via versa, then we're
    // not up to date.
    if (self._includeCordovaUnibuild !==
        isopackBuildInfoJson.includeCordovaUnibuild) {
      return false;
    }

    // If any of the direct dependencies changed their version or location, we
    // aren't up to date.
    if (!self._packageMap.isSupersetOfJSON(
      isopackBuildInfoJson.pluginProviderPackageMap)) {
      return false;
    }
    // Merge in the watchsets for all unibuilds and plugins in the package, then
    // check it once.
    var watchSet = watch.WatchSet.fromJSON(
      isopackBuildInfoJson.pluginDependencies);

    _.each(isopackBuildInfoJson.unibuildDependencies, function (deps) {
      watchSet.merge(watch.WatchSet.fromJSON(deps));
    });
    return watch.isUpToDate(watchSet);
  },

  _checkUpToDatePreloaded: function (previousIsopack) {
    var self = this;

    // If we include Cordova but this Isopack doesn't, or via versa, then we're
    // not up to date.
    if (self._includeCordovaUnibuild !== previousIsopack.hasCordovaUnibuild()) {
      return false;
    }

    // If any of the direct dependencies changed their version or location, we
    // aren't up to date.
    if (!self._packageMap.isSupersetOfJSON(
      previousIsopack.pluginProviderPackageMap)) {
      return false;
    }
    // Merge in the watchsets for all unibuilds and plugins in the package, then
    // check it once.
    var watchSet = previousIsopack.getMergedWatchSet();
    return watch.isUpToDate(watchSet);
  },

  _isopackDir: function (packageName) {
    var self = this;
    return files.pathJoin(self.cacheDir, colonConverter.convert(packageName));
  },

  _isopackBuildInfoPath: function (packageName) {
    var self = this;
    return files.pathJoin(
      self._isopackDir(packageName), 'isopack-buildinfo.json');
  },

  forgetPreviousIsopackCache: function () {
    var self = this;
    self._previousIsopackCache = null;
  }
});
<commit_msg>Don't access Isopack directly because of potential problems of circular dependencies<commit_after>var _ = require('underscore');

var buildmessage = require('./buildmessage.js');
var compiler = require('./compiler.js');
var files = require('./files.js');
var isopackModule = require('./isopack.js');
var utils = require('./utils.js');
var watch = require('./watch.js');
var colonConverter = require("./colon-converter.js");

exports.IsopackCache = function (options) {
  var self = this;
  options = options || {};

  // cacheDir may be null; in this case, we just don't ever save things to disk.
  self.cacheDir = options.cacheDir;

  // This is a bit of a hack, but basically: we really don't want to spend time
  // building web.cordova unibuilds in a project that doesn't have any Cordova
  // platforms. (Note that we need to be careful with 'meteor publish' to still
  // publish a web.cordova unibuild!)
  self._includeCordovaUnibuild = !! options.includeCordovaUnibuild;

  // Defines the versions of packages that we build. Must be set.
  self._packageMap = options.packageMap;

  // tropohouse may be null; in this case, we can't load versioned packages.
  // eg, for building isopackets.
  self._tropohouse = options.tropohouse;

  // If provided, this is another IsopackCache for the same cache dir; when
  // loading Isopacks, if they are definitely unchanged we can load the
  // in-memory objects from this cache instead of recompiling.
  self._previousIsopackCache = options.previousIsopackCache;
  if (self._previousIsopackCache &&
      self._previousIsopackCache.cacheDir !== self.cacheDir) {
    throw Error("previousIsopackCache has different cacheDir!");
  }

  // Map from package name to Isopack.
  self._isopacks = {};

  self._noLineNumbers = !! options.noLineNumbers;

  self.allLoadedLocalPackagesWatchSet = new watch.WatchSet;
};

_.extend(exports.IsopackCache.prototype, {
  buildLocalPackages: function (rootPackageNames) {
    var self = this;
    buildmessage.assertInCapture();

    if (self.cacheDir)
      files.mkdir_p(self.cacheDir);

    var onStack = {};
    if (rootPackageNames) {
      _.each(rootPackageNames, function (name) {
        self._ensurePackageLoaded(name, onStack);
      });
    } else {
      self._packageMap.eachPackage(function (name, packageInfo) {
        self._ensurePackageLoaded(name, onStack);
      });
    }
  },

  wipeCachedPackages: function (packages) {
    var self = this;
    // If we're not saving things to disk, there's nothing to wipe!
    if (! self.cacheDir)
      return;
    if (packages) {
      // Wipe specific packages.
      _.each(packages, function (packageName) {
        files.rm_recursive(self._isopackDir(packageName));
      });
    } else {
      // Wipe all packages.
      files.rm_recursive(self.cacheDir);
    }
  },

  // Returns the isopack (already loaded in memory) for a given name. It is an
  // error to call this if it's not already loaded! So it should only be called
  // after buildLocalPackages has returned, or in the process of building a
  // package whose dependencies have all already been built.
  getIsopack: function (name) {
    var self = this;
    if (! _.has(self._isopacks, name))
      throw Error("isopack " + name + " not yet loaded?");
    return self._isopacks[name];
  },

  eachBuiltIsopack: function (iterator) {
    var self = this;
    _.each(self._isopacks, function (isopack, packageName) {
      iterator(packageName, isopack);
    });
  },

  _ensurePackageLoaded: function (name, onStack) {
    var self = this;
    buildmessage.assertInCapture();
    if (_.has(self._isopacks, name))
      return;

    var ensureLoaded = function (depName) {
      if (_.has(onStack, depName)) {
        buildmessage.error("circular dependency between packages " +
                           name + " and " + depName);
        // recover by not enforcing one of the dependencies
        return;
      }
      onStack[depName] = true;
      self._ensurePackageLoaded(depName, onStack);
      delete onStack[depName];
    };

    var packageInfo = self._packageMap.getInfo(name);
    if (! packageInfo)
      throw Error("Depend on unknown package " + name + "?");
    var previousIsopack = null;
    if (self._previousIsopackCache &&
        _.has(self._previousIsopackCache._isopacks, name)) {
      var previousInfo = self._previousIsopackCache._packageMap.getInfo(name);
      if ((packageInfo.kind === 'versioned' &&
           previousInfo.kind === 'versioned' &&
           packageInfo.version === previousInfo.version) ||
          (packageInfo.kind === 'local' &&
           previousInfo.kind === 'local' &&
           (packageInfo.packageSource.sourceRoot ===
            previousInfo.packageSource.sourceRoot))) {
        previousIsopack = self._previousIsopackCache._isopacks[name];
      }
    }

    if (packageInfo.kind === 'local') {
      var packageNames =
            packageInfo.packageSource.getPackagesToLoadFirst(self._packageMap);
      buildmessage.enterJob("preparing to build package " + name, function () {
        _.each(packageNames, function (depName) {
          ensureLoaded(depName);
        });
        // If we failed to load something that this package depends on, don't
        // load it.
        if (buildmessage.jobHasMessages())
          return;
        self._loadLocalPackage(name, packageInfo, previousIsopack);
      });
    } else if (packageInfo.kind === 'versioned') {
      // We don't have to build this package, and we don't have to build its
      // dependencies either! Just load it from disk.

      if (!self._tropohouse) {
        throw Error("Can't load versioned packages without a tropohouse!");
      }

      var isopack = null, packagesToLoad = [];
      if (previousIsopack) {
        isopack = previousIsopack;
        packagesToLoad = isopack.getStrongOrderedUsedAndImpliedPackages();
      }
      if (! isopack) {
        // Load the isopack from disk.
        buildmessage.enterJob(
          "loading package " + name + "@" + packageInfo.version,
          function () {
            var isopackPath = self._tropohouse.packagePath(
              name, packageInfo.version);
            var Isopack = isopackModule.Isopack;
            isopack = new Isopack();
            isopack.initFromPath(name, isopackPath);
            // If loading the isopack fails, then we don't need to look for more
            // packages to load, but we should still recover by putting it in
            // self._isopacks.
            if (buildmessage.jobHasMessages())
              return;
            packagesToLoad = isopack.getStrongOrderedUsedAndImpliedPackages();
          });
      }

      self._isopacks[name] = isopack;
      // Also load its dependencies. This is so that if this package is being
      // built as part of a plugin, all the transitive dependencies of the
      // plugin are loaded.
      _.each(packagesToLoad, function (packageToLoad) {
        ensureLoaded(packageToLoad);
      });
    } else {
      throw Error("unknown packageInfo kind?");
    }
  },

  _loadLocalPackage: function (name, packageInfo, previousIsopack) {
    var self = this;
    buildmessage.assertInCapture();
    buildmessage.enterJob("building package " + name, function () {
      var isopack;
      if (previousIsopack && self._checkUpToDatePreloaded(previousIsopack)) {
        isopack = previousIsopack;
      } else {
        // Do we have an up-to-date package on disk?
        var isopackBuildInfoJson = self.cacheDir && files.readJSONOrNull(
          self._isopackBuildInfoPath(name));
        var upToDate = self._checkUpToDate(isopackBuildInfoJson);

        if (upToDate) {
          var Isopack = isopackModule.Isopack;
          isopack = new Isopack();
          isopack.initFromPath(name, self._isopackDir(name), {
            isopackBuildInfoJson: isopackBuildInfoJson
          });
        } else {
          // Nope! Compile it again.
          isopack = compiler.compile(packageInfo.packageSource, {
            packageMap: self._packageMap,
            isopackCache: self,
            noLineNumbers: self._noLineNumbers,
            includeCordovaUnibuild: self._includeCordovaUnibuild,
            includePluginProviderPackageMap: true
          });
          // Accept the compiler's result, even if there were errors (since it
          // at least will have a useful WatchSet and will allow us to keep
          // going and compile other packages that depend on this one).
          if (self.cacheDir && ! buildmessage.jobHasMessages()) {
            // Save to disk, for next time!
            isopack.saveToPath(self._isopackDir(name), {
              includeIsopackBuildInfo: true
            });
          }
        }
      }

      self.allLoadedLocalPackagesWatchSet.merge(isopack.getMergedWatchSet());
      self._isopacks[name] = isopack;
    });
  },

  _checkUpToDate: function (isopackBuildInfoJson) {
    var self = this;
    // If there isn't an isopack-buildinfo.json file, then we definitely aren't
    // up to date!
    if (! isopackBuildInfoJson)
      return false;

    // If we include Cordova but this Isopack doesn't, or via versa, then we're
    // not up to date.
    if (self._includeCordovaUnibuild !==
        isopackBuildInfoJson.includeCordovaUnibuild) {
      return false;
    }

    // If any of the direct dependencies changed their version or location, we
    // aren't up to date.
    if (!self._packageMap.isSupersetOfJSON(
      isopackBuildInfoJson.pluginProviderPackageMap)) {
      return false;
    }
    // Merge in the watchsets for all unibuilds and plugins in the package, then
    // check it once.
    var watchSet = watch.WatchSet.fromJSON(
      isopackBuildInfoJson.pluginDependencies);

    _.each(isopackBuildInfoJson.unibuildDependencies, function (deps) {
      watchSet.merge(watch.WatchSet.fromJSON(deps));
    });
    return watch.isUpToDate(watchSet);
  },

  _checkUpToDatePreloaded: function (previousIsopack) {
    var self = this;

    // If we include Cordova but this Isopack doesn't, or via versa, then we're
    // not up to date.
    if (self._includeCordovaUnibuild !== previousIsopack.hasCordovaUnibuild()) {
      return false;
    }

    // If any of the direct dependencies changed their version or location, we
    // aren't up to date.
    if (!self._packageMap.isSupersetOfJSON(
      previousIsopack.pluginProviderPackageMap)) {
      return false;
    }
    // Merge in the watchsets for all unibuilds and plugins in the package, then
    // check it once.
    var watchSet = previousIsopack.getMergedWatchSet();
    return watch.isUpToDate(watchSet);
  },

  _isopackDir: function (packageName) {
    var self = this;
    return files.pathJoin(self.cacheDir, colonConverter.convert(packageName));
  },

  _isopackBuildInfoPath: function (packageName) {
    var self = this;
    return files.pathJoin(
      self._isopackDir(packageName), 'isopack-buildinfo.json');
  },

  forgetPreviousIsopackCache: function () {
    var self = this;
    self._previousIsopackCache = null;
  }
});
<|endoftext|>


<commit_before>var page = new WebPage();
var address = phantom.args[0];

page.onConsoleMessage = function(msg) {
  if (msg === 'Test finished') {
    var result = page.evaluate(function() {
      return result;
    });
    console.log('pass: ' + result.pass.count)
    console.log('warn: ' + result.warn.count)
    console.log('error: ' + result.error.count)
    console.log('fail: ' + result.fail.count)

    if (result.error.count) {
      phantom.exit(1)
    } else if(result.fail.count) {
      phantom.exit(1)
    } else {
      phantom.exit(0)
    }
  }
};

page.open(address, function(status) {
  if (status !== 'success') {
    console.log('can\'t load the address!');
  }
});
<commit_msg>update<commit_after>var page = new WebPage();
var address = phantom.args[0];

page.onConsoleMessage = function(msg) {
  console.log(msg)
  if (msg === 'Test finished') {
    var result = page.evaluate(function() {
      return result;
    });
    console.log('pass: ' + result.pass.count)
    console.log('warn: ' + result.warn.count)
    console.log('error: ' + result.error.count)
    console.log('fail: ' + result.fail.count)

    if (result.error.count) {
      phantom.exit(1)
    } else if(result.fail.count) {
      phantom.exit(1)
    } else {
      phantom.exit(0)
    }
  }
};

page.open(address, function(status) {
  if (status !== 'success') {
    console.log('can\'t load the address!');
  }
});
<|endoftext|>


<commit_before>/*************************************************************
 *
 *  latest.js
 *
 *  Replacement for cdn.mathjax.org/mathjax/latest that loads the
 *  latest (2.x) version of MathJax from cdnjs, rawgit.com, or jsdelivr
 *  depending on where it was loaded from.
 *
 *  ---------------------------------------------------------------------
 *
 *  Copyright (c) 2017 The MathJax Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

(function () {

   var CDN = {
     'cdnjs.cloudflare.com': {
       api: 'https://api.cdnjs.com/libraries/mathjax?fields=version',
       version: 'version',
       mathjax: 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/'
     },

     'cdn.rawgit.com': {
       api: 'https://api.github.com/repos/mathjax/mathjax/releases/latest',
       version: 'tag_name',
       mathjax: 'https://cdn.rawgit.com/mathjax/MathJax/'
     },

     'cdn.jsdelivr.net': {
       api: 'https://api.jsdelivr.com/v1/jsdelivr/libraries?name=mathjax&lastversion=*',
       version: 'lastversion',
       mathjax: 'https://cdn.jsdelivr.net/mathjax/'
     }
   };

   function Error(message) {
     if (console && console.log) console.log(message);
   }

   function getScript() {
     if (document.currentScript) return document.currentScript;
     var scripts = document.getElementsByTagName("script");
     for (var i = 0, m = scripts.length; i < m; i++) {
       var script = scripts[i];
       for (var cdn in CDN) {if (CDN.hasOwnProperty(cdn)) {
         var url = CDN[cdn].mathjax;
         if (script.src && script.src.substr(0,url.length) === url) return script;
       }}
     }
   }

   function getCDN(script) {
     if (!script) return;
     var cdn = script.src.replace(/https:\/\//,'').replace(/[\/\?].*/,'');
     return CDN[cdn];
   }

   var cookiePattern = /(?:^|;\s*)mjx\.latest=([^;]*)(?:;|$)/;
   function getVersion() {
     var match;
     try {match = cookiePattern.exec(document.cookie)} catch (err) {}
     if (match && match[1] !== '') return match[1];
   }
   function setVersion(version) {
     cookie = 'mjx.latest=' + version;
     var time = new Date();
     time.setDate(time.getDate() + 7);
     cookie += '; expires=' + time.toGMTString();
     cookie += '; path=/';
     try {document.cookie = cookie} catch (err) {}
   }

   function getXMLHttpRequest() {
     if (window.XMLHttpRequest) return new XMLHttpRequest();
     if (window.ActiveXObject) {
       try {return new ActiveXObject("Msxml2.XMLHTTP")} catch (err) {}
       try {return new ActiveXObject("Microsoft.XMLHTTP")} catch (err) {}
     }
   }

   function loadMathJax(url) {
     var script = document.createElement('script');
     script.type = 'text/javascript';
     script.async = true;
     script.src = url;
     var head = document.head || document.getElementsByTagName('head')[0] || document.body;
     if (head) {
       head.appendChild(script);
     } else {
       Error("Can't find the document <head> element");
     }
   }

   function loadDefaultMathJax() {
     var script = getScript();
     if (script) {
       loadMathJax(script.src.replace(/\/latest\.js/, "/MathJax.js"));
     } else {
       Error("Can't determine the URL for loading MathJax");
     }
   }

   function getLatestMathJax(cdn,config,unpacked) {
     var request = getXMLHttpRequest();
     if (request) {
       request.onreadystatechange = function() {
         if (request.readyState === 4) {
           if (request.status === 200) {
             var json = JSON.parse(request.responseText);
             if (json instanceof Array) json = json[0];
             var version = json[cdn.version];
             if (version.substr(0,2) === '2.') {
               setVersion(version);
               loadMathJax(cdn.mathjax + json[cdn.version] + unpacked + '/MathJax.js' + config);
               return;
             }
           } else {
             Error("Problem aquiring MathJax version: status = " + request.status);
           }
           laodDefaultMathJax();
         }
       }
       request.open('GET', cdn.api, true);
       request.send(null);
     } else {
       Error("Can't create XMLHttpRequest object");
       loadDefaultMathJax();
     }
   }

   var script = getScript();
   var cdn = getCDN(script);
   if (cdn) {
     var config = script.src.replace(/.*?(\?|$)/, "$1");
     config += (config ? '&' : '?') + 'latest';
     var unpacked = (script.src.match(/\/unpacked\/latest\.js/) ? "/unpacked" : "");
     var version = getVersion();
     if (version) {
       loadMathJax(cdn.mathjax + version + unpacked + '/MathJax.js' + config);
     } else {
       getLatestMathJax(cdn, config, unpacked);
     }
   } else {
     loadDefaultMathJax();
   }

})();
<commit_msg>Fix typo in function name<commit_after>/*************************************************************
 *
 *  latest.js
 *
 *  Replacement for cdn.mathjax.org/mathjax/latest that loads the
 *  latest (2.x) version of MathJax from cdnjs, rawgit.com, or jsdelivr
 *  depending on where it was loaded from.
 *
 *  ---------------------------------------------------------------------
 *
 *  Copyright (c) 2017 The MathJax Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

(function () {

   var CDN = {
     'cdnjs.cloudflare.com': {
       api: 'https://api.cdnjs.com/libraries/mathjax?fields=version',
       version: 'version',
       mathjax: 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/'
     },

     'cdn.rawgit.com': {
       api: 'https://api.github.com/repos/mathjax/mathjax/releases/latest',
       version: 'tag_name',
       mathjax: 'https://cdn.rawgit.com/mathjax/MathJax/'
     },

     'cdn.jsdelivr.net': {
       api: 'https://api.jsdelivr.com/v1/jsdelivr/libraries?name=mathjax&lastversion=*',
       version: 'lastversion',
       mathjax: 'https://cdn.jsdelivr.net/mathjax/'
     }
   };

   function Error(message) {
     if (console && console.log) console.log(message);
   }

   function getScript() {
     if (document.currentScript) return document.currentScript;
     var scripts = document.getElementsByTagName("script");
     for (var i = 0, m = scripts.length; i < m; i++) {
       var script = scripts[i];
       for (var cdn in CDN) {if (CDN.hasOwnProperty(cdn)) {
         var url = CDN[cdn].mathjax;
         if (script.src && script.src.substr(0,url.length) === url) return script;
       }}
     }
   }

   function getCDN(script) {
     if (!script) return;
     var cdn = script.src.replace(/https:\/\//,'').replace(/[\/\?].*/,'');
     return CDN[cdn];
   }

   var cookiePattern = /(?:^|;\s*)mjx\.latest=([^;]*)(?:;|$)/;
   function getVersion() {
     var match;
     try {match = cookiePattern.exec(document.cookie)} catch (err) {}
     if (match && match[1] !== '') return match[1];
   }
   function setVersion(version) {
     cookie = 'mjx.latest=' + version;
     var time = new Date();
     time.setDate(time.getDate() + 7);
     cookie += '; expires=' + time.toGMTString();
     cookie += '; path=/';
     try {document.cookie = cookie} catch (err) {}
   }

   function getXMLHttpRequest() {
     if (window.XMLHttpRequest) return new XMLHttpRequest();
     if (window.ActiveXObject) {
       try {return new ActiveXObject("Msxml2.XMLHTTP")} catch (err) {}
       try {return new ActiveXObject("Microsoft.XMLHTTP")} catch (err) {}
     }
   }

   function loadMathJax(url) {
     var script = document.createElement('script');
     script.type = 'text/javascript';
     script.async = true;
     script.src = url;
     var head = document.head || document.getElementsByTagName('head')[0] || document.body;
     if (head) {
       head.appendChild(script);
     } else {
       Error("Can't find the document <head> element");
     }
   }

   function loadDefaultMathJax() {
     var script = getScript();
     if (script) {
       loadMathJax(script.src.replace(/\/latest\.js/, "/MathJax.js"));
     } else {
       Error("Can't determine the URL for loading MathJax");
     }
   }

   function getLatestMathJax(cdn,config,unpacked) {
     var request = getXMLHttpRequest();
     if (request) {
       request.onreadystatechange = function() {
         if (request.readyState === 4) {
           if (request.status === 200) {
             var json = JSON.parse(request.responseText);
             if (json instanceof Array) json = json[0];
             var version = json[cdn.version];
             if (version.substr(0,2) === '2.') {
               setVersion(version);
               loadMathJax(cdn.mathjax + json[cdn.version] + unpacked + '/MathJax.js' + config);
               return;
             }
           } else {
             Error("Problem aquiring MathJax version: status = " + request.status);
           }
           loadDefaultMathJax();
         }
       }
       request.open('GET', cdn.api, true);
       request.send(null);
     } else {
       Error("Can't create XMLHttpRequest object");
       loadDefaultMathJax();
     }
   }

   var script = getScript();
   var cdn = getCDN(script);
   if (cdn) {
     var config = script.src.replace(/.*?(\?|$)/, "$1");
     config += (config ? '&' : '?') + 'latest';
     var unpacked = (script.src.match(/\/unpacked\/latest\.js/) ? "/unpacked" : "");
     var version = getVersion();
     if (version) {
       loadMathJax(cdn.mathjax + version + unpacked + '/MathJax.js' + config);
     } else {
       getLatestMathJax(cdn, config, unpacked);
     }
   } else {
     loadDefaultMathJax();
   }

})();
<|endoftext|>