<commit_before>var _ = require("lodash"),
    Digraph = require("../digraph"),
    List = require("../data/list");

/*
 * A greedy heuristic for finding a feedback arc set for a graph. A feedback
 * arc set is a set of edges that can be removed to make a graph acyclic.
 * The algorithm comes from: P. Eades, X. Lin, and W. F. Smyth, "A fast and
 * effective heuristic for the feedback arc set problem." This implementation
 * adjusts that from the paper to allow for weighted edges.
 */
module.exports = greedyFAS;

var DEFAULT_WEIGHT_FN = _.constant(1);

function greedyFAS(g, weightFn) {
  if (g.nodeCount() <= 1) {
    return [];
  }
  return doGreedyFAS(buildGraph(g, weightFn || DEFAULT_WEIGHT_FN));
}

function doGreedyFAS(g) {
  var results = [],
      graphObj = g.getGraph(),
      buckets = graphObj.buckets,
      sources = buckets[buckets.length - 1],
      sinks = buckets[0];

  var node;
  while (g.nodeCount()) {
    while ((node = sinks.dequeue()))   { removeNode(g, node); }
    while ((node = sources.dequeue())) { removeNode(g, node); }
    if (g.nodeCount()) {
      for (var i = buckets.length - 2; i > 0; --i) {
        node = buckets[i].dequeue();
        if (node) {
          results = results.concat(removeNode(g, node, true));
          break;
        }
      }
    }
  }

  return results;
}

function removeNode(g, node, collectPredecessors) {
  var results = collectPredecessors ? [] : undefined,
      v = node.v;

  _.each(g.inEdges(v), function(edge) {
    var weight = edge.label,
        uCtx = g.getNode(edge.v);

    if (collectPredecessors) {
      results.push({ v: edge.v, w: edge.w });
    }

    uCtx.out -= weight;
    assignBucket(g.getGraph(), uCtx);
  });

  _.each(g.outEdges(v), function(edge) {
    var weight = edge.label,
        wCtx = g.getNode(edge.w);
    wCtx.in -= weight;
    assignBucket(g.getGraph(), wCtx);
  });

  g.removeNode(v);

  return results;
}

function buildGraph(g, weightFn) {
  var fasGraph = new Digraph(),
      graphObj = {},
      maxIn = 0,
      maxOut = 0;

  fasGraph.setGraph(graphObj);

  _.each(g.nodeIds(), function(v) {
    fasGraph.setNode(v, { v: v, in: 0, out: 0 });
  });

  _.each(g.edges(), function(edge) {
    var weight = weightFn(edge);
    fasGraph.setEdge(edge.v, edge.w, weight);
    fasGraph.updateNode(edge.v, function(label) {
      label.out += weight;
      maxOut = Math.max(maxOut, label.out);
      return label;
    });
    fasGraph.updateNode(edge.w, function(label) {
      label.in += weight;
      maxIn = Math.max(maxIn, label.in);
      return label;
    });
  });

  graphObj.buckets = _.range(maxOut + maxIn + 3).map(function() { return new List(); });
  graphObj.zeroIdx = maxIn + 1;

  _.each(fasGraph.nodes(), function(node) { assignBucket(graphObj, node.label); });

  return fasGraph;
}

function assignBucket(graphState, node) {
  var buckets = graphState.buckets;
  if (!node.out) {
    buckets[0].enqueue(node);
  } else if (!node.in) {
    buckets[buckets.length - 1].enqueue(node);
  } else {
    buckets[node.out - node.in + graphState.zeroIdx].enqueue(node);
  }
}
<commit_msg>Don't use updateNode in greedy-fas<commit_after>var _ = require("lodash"),
    Digraph = require("../digraph"),
    List = require("../data/list");

/*
 * A greedy heuristic for finding a feedback arc set for a graph. A feedback
 * arc set is a set of edges that can be removed to make a graph acyclic.
 * The algorithm comes from: P. Eades, X. Lin, and W. F. Smyth, "A fast and
 * effective heuristic for the feedback arc set problem." This implementation
 * adjusts that from the paper to allow for weighted edges.
 */
module.exports = greedyFAS;

var DEFAULT_WEIGHT_FN = _.constant(1);

function greedyFAS(g, weightFn) {
  if (g.nodeCount() <= 1) {
    return [];
  }
  return doGreedyFAS(buildGraph(g, weightFn || DEFAULT_WEIGHT_FN));
}

function doGreedyFAS(g) {
  var results = [],
      graphObj = g.getGraph(),
      buckets = graphObj.buckets,
      sources = buckets[buckets.length - 1],
      sinks = buckets[0];

  var node;
  while (g.nodeCount()) {
    while ((node = sinks.dequeue()))   { removeNode(g, node); }
    while ((node = sources.dequeue())) { removeNode(g, node); }
    if (g.nodeCount()) {
      for (var i = buckets.length - 2; i > 0; --i) {
        node = buckets[i].dequeue();
        if (node) {
          results = results.concat(removeNode(g, node, true));
          break;
        }
      }
    }
  }

  return results;
}

function removeNode(g, node, collectPredecessors) {
  var results = collectPredecessors ? [] : undefined,
      v = node.v;

  _.each(g.inEdges(v), function(edge) {
    var weight = edge.label,
        uCtx = g.getNode(edge.v);

    if (collectPredecessors) {
      results.push({ v: edge.v, w: edge.w });
    }

    uCtx.out -= weight;
    assignBucket(g.getGraph(), uCtx);
  });

  _.each(g.outEdges(v), function(edge) {
    var weight = edge.label,
        wCtx = g.getNode(edge.w);
    wCtx.in -= weight;
    assignBucket(g.getGraph(), wCtx);
  });

  g.removeNode(v);

  return results;
}

function buildGraph(g, weightFn) {
  var fasGraph = new Digraph(),
      graphObj = {},
      maxIn = 0,
      maxOut = 0;

  fasGraph.setGraph(graphObj);

  _.each(g.nodeIds(), function(v) {
    fasGraph.setNode(v, { v: v, in: 0, out: 0 });
  });

  _.each(g.edges(), function(edge) {
    var weight = weightFn(edge);
    fasGraph.setEdge(edge.v, edge.w, weight);
    maxOut = Math.max(maxOut, fasGraph.getNode(edge.v).out += weight);
    maxIn  = Math.max(maxIn,  fasGraph.getNode(edge.w).in  += weight);
  });

  graphObj.buckets = _.range(maxOut + maxIn + 3).map(function() { return new List(); });
  graphObj.zeroIdx = maxIn + 1;

  _.each(fasGraph.nodes(), function(node) { assignBucket(graphObj, node.label); });

  return fasGraph;
}

function assignBucket(graphState, node) {
  var buckets = graphState.buckets;
  if (!node.out) {
    buckets[0].enqueue(node);
  } else if (!node.in) {
    buckets[buckets.length - 1].enqueue(node);
  } else {
    buckets[node.out - node.in + graphState.zeroIdx].enqueue(node);
  }
}
<|endoftext|>


<commit_before>// VISUALIZATION
// ------------------------------------------

var stageWidth = 1600;
var stageHeight = 12000;
var stageSvg = null;

function visualizationInit() {
    var margin = {top: 20, right: 500, bottom: 0, left: 20};

    stageSvg = d3.select("body").append("svg")
        .attr("width", stageWidth + margin.left + margin.right)
        .attr("height", stageHeight + margin.top + margin.bottom)
        .style("margin-left", margin.left + "px")
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
}

var visualize = function visualize(interval, data) {

    var intervalSeconds = interval * 60 * 1000;

    function truncate(str, maxLength, suffix) {
        if (str.length > maxLength) {
            str = str.substring(0, maxLength + 1);
            str = str.substring(0, Math.min(str.length, str.lastIndexOf(" ")));
            str = str + suffix;
        }
        return str;
    }

    data = data['aggregations']['timeframes']['buckets'];
    var timeframesCount = data.length;
    var clusterList = [];
    data.forEach(function (timeframeData) {
        timeframeData['timeframe_start'] = new Date(timeframeData['key']);
        timeframeData['timeframe_end'] = new Date((timeframeData['key'] + intervalSeconds));
        timeframeData['behaviors']['value']['clusters'].forEach(function (cluster) {
            var timeframe = [
                timeframeData['timeframe_start'],
                timeframeData['timeframe_end'],
                cluster['size'],
                timeframeData['behaviors']['value']['clusters_users_count']
            ];
            var percentValue = Math.round((timeframe[2]/timeframe[3])*10000)/100;
            if(percentValue > 1) {
                var representant = cluster['representants'][0];
                if (clusterList.hasOwnProperty(representant.pathHash)) {
                    clusterList[representant.pathHash].timeframes.push(timeframe)
                } else {
                    clusterList[representant.pathHash] = {
                        "timeframes": [
                            timeframe
                        ],
                        "path": representant['path'],
                        "name": representant['path'].join(', ')
                    }
                }
            }
        });
    });
    // fill clusters between timeframes
    data.forEach(function (timeframeData) {
        timeframeData['timeframe_start'] = new Date(timeframeData['key']);
        timeframeData['timeframe_end'] = new Date((timeframeData['key'] + intervalSeconds));
        timeframeData['behaviors']['value']['clusters'].forEach(function (timeFrameCluster) {
            var timeframe = [
                timeframeData['timeframe_start'],
                timeframeData['timeframe_end'],
                timeFrameCluster['size'],
                timeframeData['behaviors']['value']['clusters_users_count']
            ];
            var percentValue = Math.round((timeframe[2]/timeframe[3])*10000)/100;
            if(percentValue > 1) {
                var representant = timeFrameCluster['representants'][0];
                var path = representant['path'];
                var name = path.join(', ');
                for (var key in clusterList) {
                    cluster = clusterList[key];
                    if(path.length > cluster.path.length && name.indexOf(cluster.name) !== -1) {
                        console.log("boosting '" + cluster.name + "' with '" + name + "' -> +"+timeframe[2]);
                        var found = false;
                        for (var timeframeKey in cluster.timeframes) {
                            if(cluster.timeframes[timeframeKey][0] == timeframe[0] && cluster.timeframes[timeframeKey][1] == timeframe[1]) {
                                cluster.timeframes[timeframeKey][2] = cluster.timeframes[timeframeKey][2] + timeframe[2];
                                console.log('add to timeframe');
                                found = true;
                            }
                        }
//                        if(!found) {
//                            clusterList[key].timeframes.push(timeframe);
//                        }
                    }
                }
            }
        });
    });
    clusterList = clusterList.sort(function(a, b) {
        console.log("sorting");
        var aSum = a.timeframes.reduce( function(prev, next){
           return prev + next[2];
        }, 0);
        var bSum = b.timeframes.reduce( function(prev, next){
           return prev + next[2];
        }, 0);
        console.log(a.name + ": " + aSum);
        console.log(b.name + ": " + bSum);
        return parseFloat(aSum) - parseFloat(bSum);
    });
    data = [];
    for (var key in clusterList) {
        if (!clusterList.hasOwnProperty(key)) continue;
        data.push(clusterList[key]);
    }
    clusterList = null;

    var xMin = d3.min(data, function (cluster) {
        return d3.min(cluster['timeframes'], function (timeframe) {
            return timeframe[0];
        });
    });
    var xMax = d3.max(data, function (cluster) {
        return d3.max(cluster['timeframes'], function (timeframe) {
            return timeframe[0];
        });
    });
    console.log(xMin);
    console.log(xMax);

    var xScale = d3.time.scale()
        .domain([xMin, xMax])
        .range([0, stageWidth]);

    var timeFormat = d3.time.format("%m/%d %H:%M");
    xAxis = d3.svg.axis()
        .scale(xScale)
        .orient("top")
        .ticks(timeframesCount)
        .tickPadding(5)
        .tickFormat(timeFormat);

    stageSvg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + 0 + ")")
        .call(xAxis);

    var c = d3.scale.category20c();

    for (var j = 0; j < data.length; j++) {
        var g = stageSvg.append("g").attr("class", "journal");

        var circles = g.selectAll("circle")
            .data(data[j]['timeframes'])
            .enter()
            .append("circle");

        var text = g.selectAll("text")
            .data(data[j]['timeframes'])
            .enter()
            .append("text");

        var rScale = d3.scale.linear()
            .domain([0, d3.max(data[j]['timeframes'], function (d) {
                return d[3];
            })])
            .range([6, 14]);

        circles
            .attr("cx", function (d, i) {
                return xScale(d[0]);
            })
            .attr("cy", j * 30 + 20)
            .attr("r", function (d) {
                return rScale(d[2]);
            })
            .style("fill", function (d) {
                return c(j);
            });

        text
            .attr("y", j * 30 + 25)
            .attr("x", function (d, i) {
                return xScale(d[0]) - 5;
            })
            .attr("class", "value")
            .text(function (d) {
                return (Math.round((d[2]/d[3])*10000)/100)+"%";
            })
            .style("fill", function (d) {
                return c(j);
            })
            .style("display", "none");

        g.append("text")
            .attr("y", j * 30 + 25)
            .attr("x", stageWidth + 50)
            .attr("class", "label")
            .text(truncate(data[j]['name'], 60, "..."))
            .style("fill", function (d) {
                return c(j);
            })
            .on("mouseover", mouseover)
            .on("mouseout", mouseout);
    }
    ;

    function mouseover(p) {
        var g = d3.select(this).node().parentNode;
        d3.select(g).selectAll("circle").style("display", "none");
        d3.select(g).selectAll("text.value").style("display", "block");
    }

    function mouseout(p) {
        var g = d3.select(this).node().parentNode;
        d3.select(g).selectAll("circle").style("display", "block");
        d3.select(g).selectAll("text.value").style("display", "none");
    }
};<commit_msg>adjustemnts<commit_after>// VISUALIZATION
// ------------------------------------------

var stageWidth = 1600;
var stageHeight = 12000;
var stageSvg = null;

function visualizationInit() {
    var margin = {top: 20, right: 500, bottom: 0, left: 20};

    stageSvg = d3.select("body").append("svg")
        .attr("width", stageWidth + margin.left + margin.right)
        .attr("height", stageHeight + margin.top + margin.bottom)
        .style("margin-left", margin.left + "px")
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
}

var visualize = function visualize(interval, data) {

    var intervalSeconds = interval * 60 * 1000;

    function truncate(str, maxLength, suffix) {
        if (str.length > maxLength) {
            str = str.substring(0, maxLength + 1);
            str = str.substring(0, Math.min(str.length, str.lastIndexOf(" ")));
            str = str + suffix;
        }
        return str;
    }

    data = data['aggregations']['timeframes']['buckets'];
    var timeframesCount = data.length;
    var clusterList = [];
    data.forEach(function (timeframeData) {
        timeframeData['timeframe_start'] = new Date(timeframeData['key']);
        timeframeData['timeframe_end'] = new Date((timeframeData['key'] + intervalSeconds));
        timeframeData['behaviors']['value']['clusters'].forEach(function (cluster) {
            var timeframe = [
                timeframeData['timeframe_start'],
                timeframeData['timeframe_end'],
                cluster['size'],
                timeframeData['behaviors']['value']['clusters_users_count']
            ];
            var percentValue = Math.round((timeframe[2]/timeframe[3])*10000)/100;
            if(percentValue > 1) {
                var representant = cluster['representants'][0];
                if (clusterList.hasOwnProperty(representant.pathHash)) {
                    clusterList[representant.pathHash].timeframes.push(timeframe)
                } else {
                    clusterList[representant.pathHash] = {
                        "timeframes": [
                            timeframe
                        ],
                        "path": representant['path'],
                        "name": representant['path'].join(', ')
                    }
                }
            }
        });
    });
    // fill clusters between timeframes
    data.forEach(function (timeframeData) {
        timeframeData['timeframe_start'] = new Date(timeframeData['key']);
        timeframeData['timeframe_end'] = new Date((timeframeData['key'] + intervalSeconds));
        timeframeData['behaviors']['value']['clusters'].forEach(function (timeFrameCluster) {
            var timeframe = [
                timeframeData['timeframe_start'],
                timeframeData['timeframe_end'],
                timeFrameCluster['size'],
                timeframeData['behaviors']['value']['clusters_users_count']
            ];
            var percentValue = Math.round((timeframe[2]/timeframe[3])*10000)/100;
            if(percentValue > 1) {
                var representant = timeFrameCluster['representants'][0];
                var path = representant['path'];
                var name = path.join(', ');
                for (var key in clusterList) {
                    cluster = clusterList[key];
                    if(path.length > cluster.path.length && name.indexOf(cluster.name) !== -1) {
                        console.log("boosting '" + cluster.name + "' with '" + name + "' -> +"+timeframe[2]);
                        var found = false;
                        for (var timeframeKey in cluster.timeframes) {
                            console.log('checking' + cluster.timeframes[timeframeKey][0] + '-' + cluster.timeframes[timeframeKey][1]);
                            if(cluster.timeframes[timeframeKey][0] == timeframe[0] && cluster.timeframes[timeframeKey][1] == timeframe[1]) {
                                cluster.timeframes[timeframeKey][2] = cluster.timeframes[timeframeKey][2] + timeframe[2];
                                console.log('add to timeframe');
                                found = true;
                            }
                        }
//                        if(!found) {
//                            clusterList[key].timeframes.push(timeframe);
//                        }
                    }
                }
            }
        });
    });
    clusterList = clusterList.sort(function(a, b) {
        console.log("sorting");
        var aSum = a.timeframes.reduce( function(prev, next){
           return prev + next[2];
        }, 0);
        var bSum = b.timeframes.reduce( function(prev, next){
           return prev + next[2];
        }, 0);
        console.log(a.name + ": " + aSum);
        console.log(b.name + ": " + bSum);
        return parseFloat(aSum) - parseFloat(bSum);
    });
    data = [];
    for (var key in clusterList) {
        if (!clusterList.hasOwnProperty(key)) continue;
        data.push(clusterList[key]);
    }
    clusterList = null;

    var xMin = d3.min(data, function (cluster) {
        return d3.min(cluster['timeframes'], function (timeframe) {
            return timeframe[0];
        });
    });
    var xMax = d3.max(data, function (cluster) {
        return d3.max(cluster['timeframes'], function (timeframe) {
            return timeframe[0];
        });
    });
    console.log(xMin);
    console.log(xMax);

    var xScale = d3.time.scale()
        .domain([xMin, xMax])
        .range([0, stageWidth]);

    var timeFormat = d3.time.format("%m/%d %H:%M");
    xAxis = d3.svg.axis()
        .scale(xScale)
        .orient("top")
        .ticks(timeframesCount)
        .tickPadding(5)
        .tickFormat(timeFormat);

    stageSvg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + 0 + ")")
        .call(xAxis);

    var c = d3.scale.category20c();

    for (var j = 0; j < data.length; j++) {
        var g = stageSvg.append("g").attr("class", "journal");

        var circles = g.selectAll("circle")
            .data(data[j]['timeframes'])
            .enter()
            .append("circle");

        var text = g.selectAll("text")
            .data(data[j]['timeframes'])
            .enter()
            .append("text");

        var rScale = d3.scale.linear()
            .domain([0, d3.max(data[j]['timeframes'], function (d) {
                return d[3];
            })])
            .range([6, 14]);

        circles
            .attr("cx", function (d, i) {
                return xScale(d[0]);
            })
            .attr("cy", j * 30 + 20)
            .attr("r", function (d) {
                return rScale(d[2]);
            })
            .style("fill", function (d) {
                return c(j);
            });

        text
            .attr("y", j * 30 + 25)
            .attr("x", function (d, i) {
                return xScale(d[0]) - 5;
            })
            .attr("class", "value")
            .text(function (d) {
                return (Math.round((d[2]/d[3])*10000)/100)+"%";
            })
            .style("fill", function (d) {
                return c(j);
            })
            .style("display", "none");

        g.append("text")
            .attr("y", j * 30 + 25)
            .attr("x", stageWidth + 50)
            .attr("class", "label")
            .text(truncate(data[j]['name'], 60, "..."))
            .style("fill", function (d) {
                return c(j);
            })
            .on("mouseover", mouseover)
            .on("mouseout", mouseout);
    }
    ;

    function mouseover(p) {
        var g = d3.select(this).node().parentNode;
        d3.select(g).selectAll("circle").style("display", "none");
        d3.select(g).selectAll("text.value").style("display", "block");
    }

    function mouseout(p) {
        var g = d3.select(this).node().parentNode;
        d3.select(g).selectAll("circle").style("display", "block");
        d3.select(g).selectAll("text.value").style("display", "none");
    }
};<|endoftext|>


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

  // Setup for different environments, incase this goes public. First is Node.js or CommonJS.
  if(typeof exports !== 'undefined') { // jshint ignore:line
    factory(exports); // jshint ignore:line
  } else {
    self.lilBox = factory({}); // jshint ignore:line

    if(typeof define === 'function' && define.amd) { // jshint ignore:line
      define('lilBox', [], function() { // jshint ignore:line
        return self.lilBox; // jshint ignore:line
      });
    }
  }

}(function(lilBox) {'use strict';

  function inherit(parent, obj) {
    var result = {}, key;
    for (key in parent) {
      result[key] = parent[key];
    }
    if (obj) {
      for (key in obj) {
        result[key] = obj[key];
      }
    }
    return result;
  }

  var options = {
    classPrefix: 'lilbox-', // not doing anything yet
    shadow: 'rgba(0,0,0,0.7)',
    boxBackgroundColor: 'white',
    maxWidth: '100%',
    color: 'black',
    okText: 'Ok',
    yesText: 'Yes',
    noText: 'No',
    opacity: 1.0,
    transitionSpeed: '500ms',
  };

  function config(userOptions) {
    options = inherit(options, userOptions);
  }

  function init () {
    // create a super simple stylesheet, just for the basic functionality
    var sheet = (function() {
      var style = document.createElement('style');
      style.appendChild(document.createTextNode('')); // WebKit hack :(
      style.id = 'lilBox-styles';
      document.head.appendChild(style);
      return style.sheet;
    })();

    sheet.insertRule('#lilBox-background {z-index: 998; position: fixed; top: 0; bottom: 0; left: 0; right: 0; background: ' +
                     options.shadow + '; transition: opacity ' + options.transitionSpeed + ';}', 0);
    sheet.insertRule('#lilBox {z-index: 999; padding: 20px; position: fixed; max-width: ' + options.maxWidth + '; opacity: ' +
                     options.opacity + '}', 1);
    sheet.insertRule('#lilBox-content {clear: both;}', 2);
    sheet.insertRule('#lilBox-close {float: right; cursor: pointer;}', 3);
    sheet.insertRule('#lilBox-yes-button {float: left; cursor: pointer;}', 4);
    sheet.insertRule('#lilBox-no-button {float: right; cursor: pointer;}', 5);
    sheet.insertRule('#lilBox-ok-button {margin-left: auto; margin-right: auto; cursor: pointer;}', 6);

    var background = document.createElement('div');
    background.id = 'lilBox-background';

    document.body.appendChild(background);
  }

function cleanupBox () {
  document.getElementById('lilBox-styles').remove();
  document.getElementById('lilBox').remove();
  document.getElementById('lilBox-background').remove();
}

  function baseTemplate (html, close) {
    var template = document.createElement('div');
    var contentBox = document.createElement('div');

    // determine if we're getting a template or a string
    if (typeof html === 'object') {
      content = html[0].innerHTML;
    } else {
      content = html;
    }

    if (close) {
      var closeBox = document.createElement('div');
      var closeButton = document.createTextNode('X');
      closeBox.id = 'lilBox-close';
      closeBox.appendChild(closeButton);
      template.appendChild(closeBox);
    }

    template.id = 'lilBox';
    contentBox.id = 'lilBox-content';
    contentBox.innerHTML = content;
    template.appendChild(contentBox);

    return template;
  }

  function basicTemplate (html) {
    var template = baseTemplate(html, true);
    template.style.top = '20px';
    template.style.left = '50%';
    template.style.backgroundColor = options.backgroundColor;

    return template;
  }

  function confirmTemplate (html) {
    var template = baseTemplate(html, false);
    template.style.backgroundColor = options.backgroundColor;

    var yesButton = document.createElement('div');
    var yesText = document.createTextNode(options.yesText);
    yesButton.id = 'lilBox-yes-button';
    yesButton.appendChild(yesText);
    template.appendChild(yesButton);

    var noButton = document.createElement('div');
    var noText = document.createTextNode(options.noText);
    noButton.id = 'lilBox-no-button';
    noButton.appendChild(noText);
    template.appendChild(noButton);

    return template;
  }

  function okTemplate (html) {
    var template = baseTemplate(html, false);
    template.style.backgroundColor = options.backgroundColor;

    var okButton = document.createElement('div');
    var okText = document.createTextNode(options.okText);
    okButton.id = 'lilBox-ok-button';
    okButton.appendChild(okText);
    template.appendChild(okButton);

    return template;
  }

  function centerLilBox (template) {
    template.style.left = (document.body.offsetWidth / 2) - (template.offsetWidth / 2) + 'px';
    template.style.top = (document.body.offsetHeight / 2) - (template.offsetHeight / 2) + 'px';
  }

  lilBox.basic = function (html, userOptions) {
    if (userOptions !== null) {
      config(userOptions);
    }

    init();

    document.body.appendChild(basicTemplate(html));

    var closeBox = document.getElementById('lilBox-close');
    closeBox.addEventListener('click', function () {
      cleanupBox();
    });

  };

  lilBox.setDefaults = function (userOptions) {
    config(userOptions);
  };

  lilBox.confirm = function (html, confirmed, userOptions) {
    if (userOptions !== null) {
      config(userOptions);
    }
    init();

    var template = confirmTemplate(html);
    document.body.appendChild(template);

    centerLilBox (template);

    var yesButton = document.getElementById('lilBox-yes-button');
    yesButton.addEventListener('click', function () {
      cleanupBox();

      if (typeof confirmed === 'function') {
        confirmed();
      }
    });

    var noButton = document.getElementById('lilBox-no-button');
    noButton.addEventListener('click', function () {
      cleanupBox();
    });

    window.addEventListener('resize', function () {centerLilBox(template);});
  };

  lilBox.ok = function (html, okayed, userOptions) {
    if (userOptions !== null) {
      config(userOptions);
    }
    init();

    var template = okTemplate(html);
    document.body.appendChild(template);

    centerLilBox (template);

    var okButton = document.getElementById('lilBox-ok-button');
    okButton.addEventListener('click', function () {
      cleanupBox();

      if (typeof okayed === 'function') {
        okayed();
      }
    });

    window.addEventListener('resize', function () {centerLilBox(template);});
  };

  return lilBox;
}));
<commit_msg>fix variable declaration<commit_after>(function(factory) {
  'use strict';

  // Setup for different environments, incase this goes public. First is Node.js or CommonJS.
  if(typeof exports !== 'undefined') { // jshint ignore:line
    factory(exports); // jshint ignore:line
  } else {
    self.lilBox = factory({}); // jshint ignore:line

    if(typeof define === 'function' && define.amd) { // jshint ignore:line
      define('lilBox', [], function() { // jshint ignore:line
        return self.lilBox; // jshint ignore:line
      });
    }
  }

}(function(lilBox) {'use strict';

  function inherit(parent, obj) {
    var result = {}, key;
    for (key in parent) {
      result[key] = parent[key];
    }
    if (obj) {
      for (key in obj) {
        result[key] = obj[key];
      }
    }
    return result;
  }

  var options = {
    classPrefix: 'lilbox-', // not doing anything yet
    shadow: 'rgba(0,0,0,0.7)',
    boxBackgroundColor: 'white',
    maxWidth: '100%',
    color: 'black',
    okText: 'Ok',
    yesText: 'Yes',
    noText: 'No',
    opacity: 1.0,
    transitionSpeed: '500ms',
  };

  function config(userOptions) {
    options = inherit(options, userOptions);
  }

  function init () {
    // create a super simple stylesheet, just for the basic functionality
    var sheet = (function() {
      var style = document.createElement('style');
      style.appendChild(document.createTextNode('')); // WebKit hack :(
      style.id = 'lilBox-styles';
      document.head.appendChild(style);
      return style.sheet;
    })();

    sheet.insertRule('#lilBox-background {z-index: 998; position: fixed; top: 0; bottom: 0; left: 0; right: 0; background: ' +
                     options.shadow + '; transition: opacity ' + options.transitionSpeed + ';}', 0);
    sheet.insertRule('#lilBox {z-index: 999; padding: 20px; position: fixed; max-width: ' + options.maxWidth + '; opacity: ' +
                     options.opacity + '}', 1);
    sheet.insertRule('#lilBox-content {clear: both;}', 2);
    sheet.insertRule('#lilBox-close {float: right; cursor: pointer;}', 3);
    sheet.insertRule('#lilBox-yes-button {float: left; cursor: pointer;}', 4);
    sheet.insertRule('#lilBox-no-button {float: right; cursor: pointer;}', 5);
    sheet.insertRule('#lilBox-ok-button {margin-left: auto; margin-right: auto; cursor: pointer;}', 6);

    var background = document.createElement('div');
    background.id = 'lilBox-background';

    document.body.appendChild(background);
  }

function cleanupBox () {
  document.getElementById('lilBox-styles').remove();
  document.getElementById('lilBox').remove();
  document.getElementById('lilBox-background').remove();
}

  function baseTemplate (html, close) {
    var content,
    template = document.createElement('div'),
    contentBox = document.createElement('div');

    // determine if we're getting a template or a string
    if (typeof html === 'object') {
      content = html[0].innerHTML;
    } else {
      content = html;
    }

    if (close) {
      var closeBox = document.createElement('div');
      var closeButton = document.createTextNode('X');
      closeBox.id = 'lilBox-close';
      closeBox.appendChild(closeButton);
      template.appendChild(closeBox);
    }

    template.id = 'lilBox';
    contentBox.id = 'lilBox-content';
    contentBox.innerHTML = content;
    template.appendChild(contentBox);

    return template;
  }

  function basicTemplate (html) {
    var template = baseTemplate(html, true);
    template.style.top = '20px';
    template.style.left = '50%';
    template.style.backgroundColor = options.backgroundColor;

    return template;
  }

  function confirmTemplate (html) {
    var template = baseTemplate(html, false);
    template.style.backgroundColor = options.backgroundColor;

    var yesButton = document.createElement('div');
    var yesText = document.createTextNode(options.yesText);
    yesButton.id = 'lilBox-yes-button';
    yesButton.appendChild(yesText);
    template.appendChild(yesButton);

    var noButton = document.createElement('div');
    var noText = document.createTextNode(options.noText);
    noButton.id = 'lilBox-no-button';
    noButton.appendChild(noText);
    template.appendChild(noButton);

    return template;
  }

  function okTemplate (html) {
    var template = baseTemplate(html, false);
    template.style.backgroundColor = options.backgroundColor;

    var okButton = document.createElement('div');
    var okText = document.createTextNode(options.okText);
    okButton.id = 'lilBox-ok-button';
    okButton.appendChild(okText);
    template.appendChild(okButton);

    return template;
  }

  function centerLilBox (template) {
    template.style.left = (document.body.offsetWidth / 2) - (template.offsetWidth / 2) + 'px';
    template.style.top = (document.body.offsetHeight / 2) - (template.offsetHeight / 2) + 'px';
  }

  lilBox.basic = function (html, userOptions) {
    if (userOptions !== null) {
      config(userOptions);
    }

    init();

    document.body.appendChild(basicTemplate(html));

    var closeBox = document.getElementById('lilBox-close');
    closeBox.addEventListener('click', function () {
      cleanupBox();
    });

  };

  lilBox.setDefaults = function (userOptions) {
    config(userOptions);
  };

  lilBox.confirm = function (html, confirmed, userOptions) {
    if (userOptions !== null) {
      config(userOptions);
    }
    init();

    var template = confirmTemplate(html);
    document.body.appendChild(template);

    centerLilBox (template);

    var yesButton = document.getElementById('lilBox-yes-button');
    yesButton.addEventListener('click', function () {
      cleanupBox();

      if (typeof confirmed === 'function') {
        confirmed();
      }
    });

    var noButton = document.getElementById('lilBox-no-button');
    noButton.addEventListener('click', function () {
      cleanupBox();
    });

    window.addEventListener('resize', function () {centerLilBox(template);});
  };

  lilBox.ok = function (html, okayed, userOptions) {
    if (userOptions !== null) {
      config(userOptions);
    }
    init();

    var template = okTemplate(html);
    document.body.appendChild(template);

    centerLilBox (template);

    var okButton = document.getElementById('lilBox-ok-button');
    okButton.addEventListener('click', function () {
      cleanupBox();

      if (typeof okayed === 'function') {
        okayed();
      }
    });

    window.addEventListener('resize', function () {centerLilBox(template);});
  };

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


<commit_before>var response_kakao = function (json) {
  var video_list = json.content;
    video_list.forEach(function(v, i) {
        var item = v;
        var shareLink = "http://vikicast.com/index.html?utm_source=kakaoLink&utm_medium=social#" + item.id;
        console.log(shareLink);
        // 카카오톡 링크 버튼을 생성합니다. 처음 한번만 호출하면 됩니다.
        Kakao.Link.sendTalkLink({
          label: item.description,
          image: {
            src: item.picture,
            width: item.width,
            height: item.height
          },
          webButton: {
            text: "vikicast x " + item.name,
            url: shareLink // 앱 설정의 웹 플랫폼에 등록한 도메인의 URL이어야 합니다.
          },
          fail: Materialize.toast('카카오톡 링크는 모바일 기기에서만 전송 가능합니다.', 4000, 'rounded')
          // webLink : {
          //   text: item.name,
          //   url: 'http://facebook.com/' + item.id
          // }
        });
        // Kakao.Link.cleanup();
        // 카카오 공유를 GA로 추적
        ga('send', 'event', "shareLink", "sendkakao", item.id );
      });
    }

    // 페이스북
    var windowHeight = 360;
    var windowWidth = 640;

    var response_facebook = function (json){
      var video_list = json.content;
        video_list.forEach(function(v, i) {
            var item = v;
            var REDIRECT_URL = "http://vikicast.com/index.html#" + item.id;
            console.log(REDIRECT_URL);

            // 페이스북 메타 데이터 변경
            $("meta[property=og\\:url]").attr("content", REDIRECT_URL);
            // $("meta[property=og\\:type]").attr("content", item.category);
            $("meta[property=og\\:title]").attr("content", "[VIKICAST x" + item.name + "]");
            $("meta[property=og\\:description]").attr("content", item.description);
            $("meta[property=og\\:image]").attr("content", item.picture);

            //  페이스북 로그인 시도
              FB.ui(
                 {
                   method: 'feed',
                   display: 'touch',
                   name: 'VIKICAST x ' + item.name,
                   picture: "http://vikicast.com/res/facebook/Untitled05.png",
                   caption: 'category: ' + item.category,
                   description: item.description,
                   message: '당신만 못 봤던 그 영상, 여기 다 있다!',
                  //  redirect_uri: "http://vikicast.com/responseSuccess.html",
                   link: REDIRECT_URL
                 },
                 function(response) {
                   if (response && response.post_id) {
                     console.log('Post was published.');
                     ga('send', 'event', "sendFBshareSuccess", item.id );

                   } else {
                     console.log('Post was not published.');
                     ga('send', 'event', "sendFBshareFail", item.id );

                   }
                 }
               );

            // var facebookUrl = "https://www.facebook.com/dialog/share?"+
            // "app_id=1463571523951964" +
            // "&display=touch" +
            // "&utm_source=facebookLink&utm_medium=social" +
            // // "&action_type=og.like"+
            // "$description=" + item.description +
            // "&pictire=" + item.pictire +
            // "&redirect_uri=http://vikicast.com/responseSuccess.html" +
            // // "&action_properties={'object':'"+ REDIRECT_URL +"'}"
            //
            // "&href=" + REDIRECT_URL;
            // // var $fbiFrame = "";
            //
            // // $('.modal-content').append($fbiFrame);
            // // $('#modal1').openModal();
            //
            // ga('send', 'event', "sendFBshareRequest", item.id );
            // window.open(facebookUrl, "_blank", "height=" + windowHeight + ",width=" + windowWidth);
          });
        }

var shareTwitter = function() {
  var twitterUrl = "https://twitter.com/intent/tweet?url=" + location.href;
  window.open(twitterUrl, "_blank", "height=" + windowHeight + ",width=" + windowWidth);
};
<commit_msg>redirect uri 수정<commit_after>var response_kakao = function (json) {
  var video_list = json.content;
    video_list.forEach(function(v, i) {
        var item = v;
        var shareLink = "http://vikicast.com/index.html?utm_source=kakaoLink&utm_medium=social#" + item.id;
        console.log(shareLink);
        // 카카오톡 링크 버튼을 생성합니다. 처음 한번만 호출하면 됩니다.
        Kakao.Link.sendTalkLink({
          label: item.description,
          image: {
            src: item.picture,
            width: item.width,
            height: item.height
          },
          webButton: {
            text: "vikicast x " + item.name,
            url: shareLink // 앱 설정의 웹 플랫폼에 등록한 도메인의 URL이어야 합니다.
          },
          fail: Materialize.toast('카카오톡 링크는 모바일 기기에서만 전송 가능합니다.', 4000, 'rounded')
          // webLink : {
          //   text: item.name,
          //   url: 'http://facebook.com/' + item.id
          // }
        });
        // Kakao.Link.cleanup();
        // 카카오 공유를 GA로 추적
        ga('send', 'event', "shareLink", "sendkakao", item.id );
      });
    }

    // 페이스북
    var windowHeight = 360;
    var windowWidth = 640;

    var response_facebook = function (json){
      var video_list = json.content;
        video_list.forEach(function(v, i) {
            var item = v;
            var REDIRECT_URL = "http://vikicast.com/index.html#" + item.id;
            console.log(REDIRECT_URL);

            // 페이스북 메타 데이터 변경
            $("meta[property=og\\:url]").attr("content", REDIRECT_URL);
            // $("meta[property=og\\:type]").attr("content", item.category);
            $("meta[property=og\\:title]").attr("content", "[VIKICAST x" + item.name + "]");
            $("meta[property=og\\:description]").attr("content", item.description);
            $("meta[property=og\\:image]").attr("content", item.picture);

            //  페이스북 로그인 시도
              FB.ui(
                 {
                   method: 'feed',
                   display: 'touch',
                   name: 'VIKICAST x ' + item.name,
                   picture: "http://vikicast.com/res/facebook/Untitled05.png",
                   caption: 'category: ' + item.category,
                   description: item.description,
                   message: '당신만 못 봤던 그 영상, 여기 다 있다!',
                   redirect_uri: "http://vikicast.com/responseSuccess.html",
                   link: REDIRECT_URL
                 },
                 function(response) {
                   if (response && response.post_id) {
                     console.log('Post was published.');
                     ga('send', 'event', "sendFBshareSuccess", item.id );

                   } else {
                     console.log('Post was not published.');
                     ga('send', 'event', "sendFBshareFail", item.id );

                   }
                 }
               );

            // var facebookUrl = "https://www.facebook.com/dialog/share?"+
            // "app_id=1463571523951964" +
            // "&display=touch" +
            // "&utm_source=facebookLink&utm_medium=social" +
            // // "&action_type=og.like"+
            // "$description=" + item.description +
            // "&pictire=" + item.pictire +
            // "&redirect_uri=http://vikicast.com/responseSuccess.html" +
            // // "&action_properties={'object':'"+ REDIRECT_URL +"'}"
            //
            // "&href=" + REDIRECT_URL;
            // // var $fbiFrame = "";
            //
            // // $('.modal-content').append($fbiFrame);
            // // $('#modal1').openModal();
            //
            // ga('send', 'event', "sendFBshareRequest", item.id );
            // window.open(facebookUrl, "_blank", "height=" + windowHeight + ",width=" + windowWidth);
          });
        }

var shareTwitter = function() {
  var twitterUrl = "https://twitter.com/intent/tweet?url=" + location.href;
  window.open(twitterUrl, "_blank", "height=" + windowHeight + ",width=" + windowWidth);
};
<|endoftext|>


<commit_before>"use strict";
//handy routines for line-oriented communications protocols
var events=require("events");
var util=require("util");

function LineIO(myconn) //inherits-from...
{
  this.conn=myconn;
  var buffer='';
  var that=this;
  events.EventEmitter.call(this);
  var linecount=0;
  var line_end;
  var line_emitter=function () {
    if(!activated) {
      console.warn("Deactivated stream - ")
      return;
    }
    if(buffer.indexOf("\r\n") !== -1) {
      linecount++;
      line_end=buffer.indexOf("\r\n");
      console.warn("FOUND line end at: "+line_end);
      if(line_end>998) {
        that.emit('error',{name: "LengthError",message: "line is too long: "+line_end+2+" characters"});
      } else {
        var chunk_to_emit=buffer.substring(0,line_end);
        console.warn("Chunk to emit '"+chunk_to_emit+"'");
        if(!that.emit('line',chunk_to_emit)) {
          console.warn("We tried to emit, but no one was listening!!!");
          throw new Error("What the heck?");
          process.nextTick(line_emitter);
          return;
        }
      }
      buffer=buffer.slice(line_end+2); //skip past the \r\n
      console.warn("Remaining buffer: '"+buffer+"'");
      if(linecount>10) {
        throw new Error("TOO MANY LINES IN ONE PACKET!")
      }
      process.nextTick(line_emitter);
    } else {
      console.warn("No CRNL found!");
    }
  };
  var listener=function () {
    linecount=0; //reset linecount!
    buffer+=that.conn.read();
    console.warn("listener invoked? Buffer is now: "+buffer);
    /*if(buffer.length>16384) {
      throw new Error("Huge buffer.");
    }*/
    line_emitter();
  };
  var activated=false;

  this.remoteAddress=this.conn.remoteAddress;

  this.on('newListener',function (name) {
    if(name=="line") {
      console.warn("New line listener found! PRevious activation status: "+activated);
      if(!activated) {
        that.conn.on('readable',listener);
        activated=true;
        //if we still had data in the buffer waiting to go,
        //and now we have a new listener - start emitting lines
        //again.
        if(buffer.length>0) {
          process.nextTick(line_emitter); //MUST do this async or you may emit
                                          //lines before everyone's ready!
                                          //can we end up double-emitting somehow?
                                          //e.g. we're eating up buffer *here*
                                          //and also the readable event's callback
                                          //fires and now we have two people
                                          //trying to eat the buffer?
        }
      }
    }
  });
  this.on('removeListener',function (name) {
    console.warn("Removing listener for "+name);
    if(name==="line" && events.EventEmitter.listenerCount(that.conn,"line")===0) {
      console.warn("DEACTIVATE CALLED! Previous status: "+activated);
      if(activated) {
        that.conn.removeListener('readable',listener);
        activated=false;
      }
    }
  });
  this.conn.on('end',function () {
    that.emit("end");
  });
  this.conn.on('error',function (err) {
    that.emit("error",err);
  });
  this.conn.on('connect',function () {
    that.emit("connect");
  });
}

util.inherits(LineIO, events.EventEmitter);

LineIO.prototype.write= function (line,optcallback) {
  if(!optcallback) {
    optcallback=function () {};
  }
  this.conn.write(line+"\r\n",optcallback);
};

//LineIO.prototype.command=function (line)

LineIO.prototype.end=function (optional) {
  if(optional) {
    this.write(optional);
  }
  this.conn.end();
};

module.exports=LineIO;
<commit_msg>Maximum line-count increased for reasonable-sized files?<commit_after>"use strict";
//handy routines for line-oriented communications protocols
var events=require("events");
var util=require("util");

function LineIO(myconn) //inherits-from...
{
  this.conn=myconn;
  var buffer='';
  var that=this;
  events.EventEmitter.call(this);
  var linecount=0;
  var line_end;
  var line_emitter=function () {
    if(!activated) {
      console.warn("Deactivated stream - ")
      return;
    }
    if(buffer.indexOf("\r\n") !== -1) {
      linecount++;
      line_end=buffer.indexOf("\r\n");
      console.warn("FOUND line end at: "+line_end);
      if(line_end>998) {
        that.emit('error',{name: "LengthError",message: "line is too long: "+line_end+2+" characters"});
      } else {
        var chunk_to_emit=buffer.substring(0,line_end);
        console.warn("Chunk to emit '"+chunk_to_emit+"'");
        if(!that.emit('line',chunk_to_emit)) {
          console.warn("We tried to emit, but no one was listening!!!");
          throw new Error("What the heck?");
          process.nextTick(line_emitter);
          return;
        }
      }
      buffer=buffer.slice(line_end+2); //skip past the \r\n
      console.warn("Remaining buffer: '"+buffer+"'");
      if(linecount>100000) {
        throw new Error("TOO MANY LINES IN ONE PACKET! ("+linecount+")");
      }
      process.nextTick(line_emitter);
    } else {
      console.warn("No CRNL found!");
    }
  };
  var listener=function () {
    linecount=0; //reset linecount!
    buffer+=that.conn.read();
    console.warn("listener invoked? Buffer is now: "+buffer);
    /*if(buffer.length>16384) {
      throw new Error("Huge buffer.");
    }*/
    line_emitter();
  };
  var activated=false;

  this.remoteAddress=this.conn.remoteAddress;

  this.on('newListener',function (name) {
    if(name=="line") {
      console.warn("New line listener found! PRevious activation status: "+activated);
      if(!activated) {
        that.conn.on('readable',listener);
        activated=true;
        //if we still had data in the buffer waiting to go,
        //and now we have a new listener - start emitting lines
        //again.
        if(buffer.length>0) {
          process.nextTick(line_emitter); //MUST do this async or you may emit
                                          //lines before everyone's ready!
                                          //can we end up double-emitting somehow?
                                          //e.g. we're eating up buffer *here*
                                          //and also the readable event's callback
                                          //fires and now we have two people
                                          //trying to eat the buffer?
        }
      }
    }
  });
  this.on('removeListener',function (name) {
    console.warn("Removing listener for "+name);
    if(name==="line" && events.EventEmitter.listenerCount(that.conn,"line")===0) {
      console.warn("DEACTIVATE CALLED! Previous status: "+activated);
      if(activated) {
        that.conn.removeListener('readable',listener);
        activated=false;
      }
    }
  });
  this.conn.on('end',function () {
    that.emit("end");
  });
  this.conn.on('error',function (err) {
    that.emit("error",err);
  });
  this.conn.on('connect',function () {
    that.emit("connect");
  });
}

util.inherits(LineIO, events.EventEmitter);

LineIO.prototype.write= function (line,optcallback) {
  if(!optcallback) {
    optcallback=function () {};
  }
  this.conn.write(line+"\r\n",optcallback);
};

//LineIO.prototype.command=function (line)

LineIO.prototype.end=function (optional) {
  if(optional) {
    this.write(optional);
  }
  this.conn.end();
};

module.exports=LineIO;
<|endoftext|>


<commit_before>'use strict';

(function(scope) {
//  const nodeProto = document.registerElement('jsbind-node');

  function bindAttribute(value) {
    this.value = value;
  }
  function bindTextContent(value) {
    this.textContent = value;
  }
  function getOuter(code) {
    if (code instanceof HTMLTemplateElement) {
      return document.importNode(code.content, true);
    } else if (code instanceof HTMLElement) {
      return document.cloneNode(true);
    }

    code = code.valueOf();
    if (typeof code !== 'string') {
      throw new TypeError('expected HTMLTemplateElement, HTMLElement or string');
    }

    const fragment = document.createDocumentFragment();
    const holder = document.createElement('div');
    holder.innerHTML = code;
    while (holder.children.length) {
      fragment.appendChild(holder.children[0]);
    }
    return fragment;
  }

  window['JSBind'] = function(code, opt_data) {
    const binding = {};
    function addBinding(value, helper) {
      let arr = binding[value];
      if (arr === undefined) {
        binding[value] = arr = [];
      }
      arr.push(helper);
    }

    const re = new RegExp(/{{(.*?)}}/g);
    function convert(text) {
      const fragment = document.createDocumentFragment();
      function appendTextNode(text) {
        const node = document.createTextNode(text);
        fragment.appendChild(node);
        return node;
      }

      let atIndex = 0;
      let match;
      while ((match = re.exec(text)) !== null) {
        if (match.index > atIndex) {
          appendTextNode(text.substring(atIndex, match.index));
          atIndex = re.lastIndex;  // step over match
        }

        // TODO: using a fake text node doesn't work in Safari, it coalesces them.
        // const node = appendTextNode('');
        const node = document.createElement('jsbind-node');
        fragment.appendChild(node);
        addBinding(match[1], bindTextContent.bind(node));
      }
      re.lastIndex = null;
      if (!atIndex) {
        return null;  // don't do anything, no matches
      }

      const tail = text.substring(atIndex);
      if (tail.length) {
        appendTextNode(tail);
      }
      return fragment;
    }

    // Traverse the entire DOM, finding insertion points.
    const outer = getOuter(code);
    const pending = [outer];
    let n;
    while ((n = pending.shift())) {
      pending.push(...n.childNodes);

      if (n instanceof Text) {
        // TODO: matches e.g. any HTMLElement, although doesn't do anything
        const out = convert(n.wholeText);
        if (out) {
          n.parentNode.replaceChild(out, n);
        }
      }

      // TODO: looks for attr$="bound", but Polymer uses attr$="{{bound}}" syntax
      if ('attributes' in n) {
        const found = {};
        for (let i = 0, curr; curr = n.attributes[i]; ++i) {
          if (curr.name.substring(curr.name.length - 1) == '$') {
            const attr = curr.name.substr(0, curr.name.length - 1);
            found[attr] = curr.value;
          }
        }
        for (const attr in found) {
          n.removeAttribute(attr + '$');
          n.setAttribute(attr, '');
          addBinding(found[attr], bindAttribute.bind(n.attributes[attr]));
        }
      }
    }

    for (let k in binding) {
      // parses opt_data and converts to 'foo.bar' property syntax
      const parts = k.split('.');
      let curr = opt_data;
      while (parts.length) {
        if (typeof curr !== 'object') {
          break;
        }
        curr = curr[parts.shift()] || '';
      }
      binding[k].forEach(helper => helper(curr));
    }

    function update(k, value) {
      (binding[k] || []).forEach(helper => helper(value));
    }
    return {root: outer, update};
  };
}(window));
<commit_msg>clarify Safari stuff<commit_after>'use strict';

(function(scope) {
//  const nodeProto = document.registerElement('jsbind-node');

  function bindAttribute(value) {
    this.value = value;
  }
  function bindTextContent(value) {
    this.textContent = value;
  }
  function getOuter(code) {
    if (code instanceof HTMLTemplateElement) {
      return document.importNode(code.content, true);
    } else if (code instanceof HTMLElement) {
      return document.cloneNode(true);
    }

    code = code.valueOf();
    if (typeof code !== 'string') {
      throw new TypeError('expected HTMLTemplateElement, HTMLElement or string');
    }

    const fragment = document.createDocumentFragment();
    const holder = document.createElement('div');
    holder.innerHTML = code;
    while (holder.children.length) {
      fragment.appendChild(holder.children[0]);
    }
    return fragment;
  }

  window['JSBind'] = function(code, opt_data) {
    const binding = {};
    function addBinding(value, helper) {
      let arr = binding[value];
      if (arr === undefined) {
        binding[value] = arr = [];
      }
      arr.push(helper);
    }

    const re = new RegExp(/{{(.*?)}}/g);
    function convert(text) {
      const fragment = document.createDocumentFragment();
      function appendTextNode(text) {
        const node = document.createTextNode(text);
        fragment.appendChild(node);
        return node;
      }

      let atIndex = 0;
      let match;
      while ((match = re.exec(text)) !== null) {
        if (match.index > atIndex) {
          appendTextNode(text.substring(atIndex, match.index));
          atIndex = re.lastIndex;  // step over match
        }

        const node = appendTextNode('');
        fragment.appendChild(node);
        addBinding(match[1], bindTextContent.bind(node));
      }
      re.lastIndex = NaN;  // nb. Safari doesn't like -1
      if (!atIndex) {
        return null;  // don't do anything, no matches
      }

      const tail = text.substring(atIndex);
      if (tail.length) {
        appendTextNode(tail);
      }
      return fragment;
    }

    // Traverse the entire DOM, finding insertion points.
    const outer = getOuter(code);
    const pending = [outer];
    let n;
    while ((n = pending.shift())) {
      pending.push(...n.childNodes);

      if (n instanceof Text) {
        // TODO: matches e.g. any HTMLElement, although doesn't do anything
        const out = convert(n.wholeText);
        if (out) {
          n.parentNode.replaceChild(out, n);
        }
      }

      // TODO: looks for attr$="bound", but Polymer uses attr$="{{bound}}" syntax
      if ('attributes' in n) {
        const found = {};
        for (let i = 0, curr; curr = n.attributes[i]; ++i) {
          if (curr.name.substring(curr.name.length - 1) == '$') {
            const attr = curr.name.substr(0, curr.name.length - 1);
            found[attr] = curr.value;
          }
        }
        for (const attr in found) {
          n.removeAttribute(attr + '$');
          n.setAttribute(attr, '');
          addBinding(found[attr], bindAttribute.bind(n.attributes[attr]));
        }
      }
    }

    for (let k in binding) {
      // parses opt_data and converts to 'foo.bar' property syntax
      const parts = k.split('.');
      let curr = opt_data;
      while (parts.length) {
        if (typeof curr !== 'object') {
          break;
        }
        curr = curr[parts.shift()] || '';
      }
      binding[k].forEach(helper => helper(curr));
    }

    function update(k, value) {
      (binding[k] || []).forEach(helper => helper(value));
    }
    return {root: outer, update};
  };
}(window));
<|endoftext|>


<commit_before>var AWS = require('../core');

function Shape(rules, options) {
  if (!rules) {
    this.rules = { type: 'structure', members: {} };
    return;
  }

  this.options = options;
  this.rules = {};
  this.set_type(rules.type);
  AWS.util.each.call(this, rules, function (key, value) {
    if (key !== 'type') this['set_' + key](value);
  });

  if (this.rules.type === 'blob') {
    if (this.rules.payload || this.rules.streaming) {
      this.rules.type = 'binary';
    } else {
      this.rules.type = 'base64';
    }
  }
}

function InputShape(rules, options) {
  Shape.call(this, rules, options);
}

function OutputShape(rules, options) {
  Shape.call(this, rules, options);
}

Shape.prototype = {
  shapeClass: function() {
    if (this instanceof InputShape) return InputShape;
    if (this instanceof OutputShape) return OutputShape;
  },

  xmlname: function() {
    if (this.rules.flattened) {
      return this._xmlname || (this.rules.members || {}).name;
    } else {
      return this._xmlname;
    }
  },

  set_type: function(name) {
    types = {
      structure: 'structure',
      list: 'list',
      map: 'map',
      boolean: 'boolean',
      timestamp: 'timestamp',
      character: 'string',
      double: 'float',
      float: 'float',
      integer: 'integer',
      long: 'integer',
      short: 'integer',
      string: 'string',
      blob: 'blob',
      biginteger: 'integer',
      bigdecimal: 'float'
    };
    if (name === 'string') { // omit string to reduce size
    } else if (types[name]) {
      this.rules.type = types[name];
    } else {
      throw new Error('unhandled shape type ' + name);
    }
  },

  set_members: function(members) {
    var type = this.rules.type;
    var ShapeClass = this.shapeClass();
    if (type === 'structure') {
      this.rules.members = {}
      AWS.util.each.call(this, members, function(memberName, memberRules) {
        var shape = new ShapeClass(memberRules, this.options);
        if (this.swapNames(shape)) {
          shape.rules.name = memberName;
          memberName = shape.xmlname();
        }
        this.rules.members[memberName] = shape.rules;
      });
    } else if (type === 'list') {
      this.rules.members = new ShapeClass(members, this.options).rules;
    } else if (type === 'map') {
      this.rules.members = new ShapeClass(members, this.options).rules;
    } else if (type === 'blob') {
      this.rules.members = {};
    } else {
      throw new Error('unhandled complex shape `' + type + '\'');
    }
  },

  set_keys: function(rules) {
    var ShapeClass = this.shapeClass();
    this.rules.keys = new ShapeClass(rules, this.options).rules;
  },

  set_timestamp_format: function(format) {
    this.rules.format = format;
  },

  set_xmlname: function(name) {
    this._xmlname = name;
    this.rules.name = name;
  },

  set_location: function (location) {
    this.rules.location = (location === 'http_status' ? 'status' : location);
  },

  set_location_name: function(header_name) {
    this.rules.name = header_name;
  },

  set_payload: function(state) {
    if (state) this.rules.payload = true;
  },

  set_flattened: function(state) {
    if (state) this.rules.flattened = true;
  },

  set_streaming: function(state) {
    if (state) this.rules.streaming = true;
  },

  set_wrapper: function(state) {
    if (state) this.rules.wrapper = true;
  },

  set_xmlattribute: function(state) {
    if (state) this.rules.attribute = true;
  },

  set_xmlnamespace: function(ns) {
    this.rules.xmlns = ns;
  },

  set_documentation: function(docs) {
    if (this.options.documentation) this.rules.documentation = docs;
  },

  set_enum: function(values) {
    if (this.options.documentation) this.rules.enum = values;
  },

  set_shape_name: function() {},
  set_box: function() {},
  set_sensitive: function() {}
};

InputShape.prototype = AWS.util.merge(Shape.prototype, {
  swapNames: function() { return false; },

  set_required: function() { this.rules.required = true; },
  set_member_order: function(order) { this.rules.order = order; },

  set_min_length: function(min) {
    if (this.options.documentation) this.rules.min_length = min;
  },

  set_max_length: function(max) {
    if (this.options.documentation) this.rules.max_length = max;
  },

  set_pattern: function(pattern) {
    if (this.options.documentation) this.rules.pattern = pattern;
  }
});

OutputShape.prototype = AWS.util.merge(Shape.prototype, {
  swapNames: function(shape) {
    if (this.options.documentation) return false;
    return shape.xmlname() && ['query', 'rest-xml'].indexOf(this.options.type) >= 0;
  },

  set_required: function() {},
  set_member_order: function() {},
  set_min_length: function() {},
  set_max_length: function() {},
  set_pattern: function() {}
});

function Operation(rules, options) {
  var origRules = rules;

  function normalizeInputs() {
    if (options.type.indexOf('rest') < 0) return;

    var xml = options.type.indexOf('xml') >= 0;
    var payload = false;
    var wrapper = false;

    var hasPayload = false;
    AWS.util.each(rules.input.members, function (name, rule) {
      if (rule.payload) {
        hasPayload = true;
        payload = name;
        delete rule.payload;
        return AWS.util.abort;
      }
    });

    if (!hasPayload) {
      var list = [];
      AWS.util.each(rules.input.members, function (name, rule) {
        if (!rule.location) { list.push(name); }
      });

      if (list.length > 0) {
        payload = list;
        if (xml) wrapper = origRules.input.shape_name;
      }
    }

    if (wrapper) rules.input = AWS.util.merge({wrapper: wrapper}, rules.input);
    if (payload) rules.input = AWS.util.merge({payload: payload}, rules.input);
  }

  function normalizeOutputs() {
    var moveUp = null;

    AWS.util.each(rules.output.members, function(memberName, rule) {
      if (rule.payload && rule.type === 'structure') {
        delete rule.payload;
        moveUp = memberName;
      }
      else if (rule.payload || rule.streaming) {
        delete rule.payload;
        rules.output.payload = memberName;
      }
    });

    if (moveUp) {
      var rule = rules.output.members[moveUp];
      delete rules.output.members[moveUp];
      AWS.util.update(rules.output.members, rule.members);
    }
  }

  rules = AWS.util.copy(rules);

  rules.input = new InputShape(rules.input, options).rules;
  rules.output = new OutputShape(rules.output, options).rules;
  rules.input.members = rules.input.members || {};
  rules.output.members = rules.output.members || {};

  normalizeInputs();
  normalizeOutputs();

  if (rules.http) delete rules.http.response_code;
  if (options.documentation) {
    rules.errors = rules.errors.map(function(e) { return e.shape_name });
  } else {
    delete rules.errors;
    delete rules.documentation;
    delete rules.documentation_url;
    delete rules.response_code;
  }

  return rules;
}

function Translator(api, options) {
  function inflect(key) {
    return key.replace(/_(\w)/g, function (_, m) { return m.toUpperCase(); });
  }

  var options = options || {};
  options.type = api.type;

  var translate = {};
  translate.format = api.type;

  var list = Object.keys(api);
  list.push('timestamp_format');
  list.sort().forEach(function (key) { translate[inflect(key)] = api[key]; });
  translate.timestampFormat = translate.timestampFormat || 'iso8601';
  if (translate.jsonVersion) translate.jsonVersion = translate.jsonVersion.toString();
  if (translate.jsonVersion === '1') translate.jsonVersion = '1.0';
  if (!options.documentation) delete translate.documentation;
  if (!translate.resultWrapped) delete translate.resultWrapped;
  if (!api.type.match(/xml/)) delete translate.xmlnamespace;
  delete translate.operations;
  delete translate.pagination;
  delete translate.waiters;
  delete translate.type;

  translate.operations = {};
  Object.keys(api.operations).forEach(function (key) {
    var methodName = key[0].toLowerCase() + key.substr(1);
    methodName = methodName.replace(/\d{4}_\d{2}_\d{2}$/, '');
    var operation = new Operation(api.operations[key], options);
    translate.operations[methodName] = operation;
  });

  if (api.pagination) {
    translate.pagination = {};
    AWS.util.each(api.pagination, function (key, value) {
      var object = {};
      AWS.util.each(value, function (k2, v2) { object[inflect(k2)] = v2; });
      translate.pagination[key[0].toLowerCase() + key.substr(1)] = object;
    });
  }

  return translate;
}

var fs = require('fs');
var util = require('util');
var path = process.argv[2];
var file = fs.readFileSync(path);
var string = JSON.stringify(new Translator(JSON.parse(file), {documentation: false}), null, "  ");
string = string.replace(/"(\w+)": /g, function (_, m) { return m === 'default' ? _ : m + ": "; }).replace(/"/g, '\'');
console.log(string);

module.exports = Translator;
<commit_msg>Add buffer check and export AWS.API.Translator<commit_after>var AWS = require('../core');

/* jshint -W079 */
var Buffer = require('buffer').Buffer;
/* jshint +W079 */

function Shape(rules, options) {
  if (!rules) {
    this.rules = { type: 'structure', members: {} };
    return;
  }

  this.options = options;
  this.rules = {};
  this.set_type(rules.type);
  AWS.util.each.call(this, rules, function (key, value) {
    if (key !== 'type') this['set_' + key](value);
  });

  if (this.rules.type === 'blob') {
    if (this.rules.payload || this.rules.streaming) {
      this.rules.type = 'binary';
    } else {
      this.rules.type = 'base64';
    }
  }
}

function InputShape(rules, options) {
  Shape.call(this, rules, options);
}

function OutputShape(rules, options) {
  Shape.call(this, rules, options);
}

Shape.prototype = {
  shapeClass: function() {
    if (this instanceof InputShape) return InputShape;
    if (this instanceof OutputShape) return OutputShape;
  },

  xmlname: function() {
    if (this.rules.flattened) {
      return this._xmlname || (this.rules.members || {}).name;
    } else {
      return this._xmlname;
    }
  },

  set_type: function(name) {
    types = {
      structure: 'structure',
      list: 'list',
      map: 'map',
      boolean: 'boolean',
      timestamp: 'timestamp',
      character: 'string',
      double: 'float',
      float: 'float',
      integer: 'integer',
      long: 'integer',
      short: 'integer',
      string: 'string',
      blob: 'blob',
      biginteger: 'integer',
      bigdecimal: 'float'
    };
    if (name === 'string') { // omit string to reduce size
    } else if (types[name]) {
      this.rules.type = types[name];
    } else {
      throw new Error('unhandled shape type ' + name);
    }
  },

  set_members: function(members) {
    var type = this.rules.type;
    var ShapeClass = this.shapeClass();
    if (type === 'structure') {
      this.rules.members = {}
      AWS.util.each.call(this, members, function(memberName, memberRules) {
        var shape = new ShapeClass(memberRules, this.options);
        if (this.swapNames(shape)) {
          shape.rules.name = memberName;
          memberName = shape.xmlname();
        }
        this.rules.members[memberName] = shape.rules;
      });
    } else if (type === 'list') {
      this.rules.members = new ShapeClass(members, this.options).rules;
    } else if (type === 'map') {
      this.rules.members = new ShapeClass(members, this.options).rules;
    } else if (type === 'blob') {
      this.rules.members = {};
    } else {
      throw new Error('unhandled complex shape `' + type + '\'');
    }
  },

  set_keys: function(rules) {
    var ShapeClass = this.shapeClass();
    this.rules.keys = new ShapeClass(rules, this.options).rules;
  },

  set_timestamp_format: function(format) {
    this.rules.format = format;
  },

  set_xmlname: function(name) {
    this._xmlname = name;
    this.rules.name = name;
  },

  set_location: function (location) {
    this.rules.location = (location === 'http_status' ? 'status' : location);
  },

  set_location_name: function(header_name) {
    this.rules.name = header_name;
  },

  set_payload: function(state) {
    if (state) this.rules.payload = true;
  },

  set_flattened: function(state) {
    if (state) this.rules.flattened = true;
  },

  set_streaming: function(state) {
    if (state) this.rules.streaming = true;
  },

  set_wrapper: function(state) {
    if (state) this.rules.wrapper = true;
  },

  set_xmlattribute: function(state) {
    if (state) this.rules.attribute = true;
  },

  set_xmlnamespace: function(ns) {
    this.rules.xmlns = ns;
  },

  set_documentation: function(docs) {
    if (this.options.documentation) this.rules.documentation = docs;
  },

  set_enum: function(values) {
    if (this.options.documentation) this.rules.enum = values;
  },

  set_shape_name: function() {},
  set_box: function() {},
  set_sensitive: function() {}
};

InputShape.prototype = AWS.util.merge(Shape.prototype, {
  swapNames: function() { return false; },

  set_required: function() { this.rules.required = true; },
  set_member_order: function(order) { this.rules.order = order; },

  set_min_length: function(min) {
    if (this.options.documentation) this.rules.min_length = min;
  },

  set_max_length: function(max) {
    if (this.options.documentation) this.rules.max_length = max;
  },

  set_pattern: function(pattern) {
    if (this.options.documentation) this.rules.pattern = pattern;
  }
});

OutputShape.prototype = AWS.util.merge(Shape.prototype, {
  swapNames: function(shape) {
    if (this.options.documentation) return false;
    return shape.xmlname() && ['query', 'rest-xml'].indexOf(this.options.type) >= 0;
  },

  set_required: function() {},
  set_member_order: function() {},
  set_min_length: function() {},
  set_max_length: function() {},
  set_pattern: function() {}
});

function Operation(rules, options) {
  var origRules = rules;

  function normalizeInputs() {
    if (options.type.indexOf('rest') < 0) return;

    var xml = options.type.indexOf('xml') >= 0;
    var payload = false;
    var wrapper = false;

    var hasPayload = false;
    AWS.util.each(rules.input.members, function (name, rule) {
      if (rule.payload) {
        hasPayload = true;
        payload = name;
        delete rule.payload;
        return AWS.util.abort;
      }
    });

    if (!hasPayload) {
      var list = [];
      AWS.util.each(rules.input.members, function (name, rule) {
        if (!rule.location) { list.push(name); }
      });

      if (list.length > 0) {
        payload = list;
        if (xml) wrapper = origRules.input.shape_name;
      }
    }

    if (wrapper) rules.input = AWS.util.merge({wrapper: wrapper}, rules.input);
    if (payload) rules.input = AWS.util.merge({payload: payload}, rules.input);
  }

  function normalizeOutputs() {
    var moveUp = null;

    AWS.util.each(rules.output.members, function(memberName, rule) {
      if (rule.payload && rule.type === 'structure') {
        delete rule.payload;
        moveUp = memberName;
      }
      else if (rule.payload || rule.streaming) {
        delete rule.payload;
        rules.output.payload = memberName;
      }
    });

    if (moveUp) {
      var rule = rules.output.members[moveUp];
      delete rules.output.members[moveUp];
      AWS.util.update(rules.output.members, rule.members);
    }
  }

  rules = AWS.util.copy(rules);

  rules.input = new InputShape(rules.input, options).rules;
  rules.output = new OutputShape(rules.output, options).rules;
  rules.input.members = rules.input.members || {};
  rules.output.members = rules.output.members || {};

  normalizeInputs();
  normalizeOutputs();

  if (rules.http) delete rules.http.response_code;
  if (options.documentation) {
    rules.errors = rules.errors.map(function(e) { return e.shape_name });
  } else {
    delete rules.errors;
    delete rules.documentation;
    delete rules.documentation_url;
    delete rules.response_code;
  }

  return rules;
}

function Translator(api, options) {
  function inflect(key) {
    return key.replace(/_(\w)/g, function (_, m) { return m.toUpperCase(); });
  }

  if (typeof api === 'string' || Buffer.isBuffer(api)) {
    api = JSON.parse(api);
  }

  var options = options || {};
  options.type = api.type;

  var translate = {};
  translate.format = api.type;

  var list = Object.keys(api);
  list.push('timestamp_format');
  list.sort().forEach(function (key) { translate[inflect(key)] = api[key]; });
  translate.timestampFormat = translate.timestampFormat || 'iso8601';
  if (translate.jsonVersion) translate.jsonVersion = translate.jsonVersion.toString();
  if (translate.jsonVersion === '1') translate.jsonVersion = '1.0';
  if (!options.documentation) delete translate.documentation;
  if (!translate.resultWrapped) delete translate.resultWrapped;
  if (!api.type.match(/xml/)) delete translate.xmlnamespace;
  delete translate.operations;
  delete translate.pagination;
  delete translate.waiters;
  delete translate.type;

  translate.operations = {};
  Object.keys(api.operations).forEach(function (key) {
    var methodName = key[0].toLowerCase() + key.substr(1);
    methodName = methodName.replace(/\d{4}_\d{2}_\d{2}$/, '');
    var operation = new Operation(api.operations[key], options);
    translate.operations[methodName] = operation;
  });

  if (api.pagination) {
    translate.pagination = {};
    AWS.util.each(api.pagination, function (key, value) {
      var object = {};
      AWS.util.each(value, function (k2, v2) { object[inflect(k2)] = v2; });
      translate.pagination[key[0].toLowerCase() + key.substr(1)] = object;
    });
  }

  return translate;
}

AWS.API = { Translator: Translator };

module.exports = Translator;
<|endoftext|>


<commit_before>"use strict";

var express = require('../../express-inherit'),
    apiRequireUserOrGuest = require('../../apps/auth').apiRequireUserOrGuest,
    base_url = require('../../middleware/route').base_url,
    about = require('../about'),
    config = require('config'),
    popitApi = require('popit-api');

var app = module.exports = express();

var api_01_app = express();
// Ensure that these methods all require a user.
api_01_app.post( '*', apiRequireUserOrGuest );
api_01_app.put(  '*', apiRequireUserOrGuest );
api_01_app.del(  '*', apiRequireUserOrGuest );

app.use(function(req, res, next) {
  req.base_url = base_url(req);
  req.api_base_url = req.base_url + '/api/v0.1';
  next();
});

api_01_app.get('/', function (req, res, next) {
  res.jsonp({
    note: "This is the API entry point - use a '*_api_url' link in 'meta' to search a collection.",
    meta: {
      persons_api_url: req.api_base_url + '/persons',
      organizations_api_url: req.api_base_url + '/organizations',
      memberships_api_url: req.api_base_url + '/memberships',
      image_proxy_url: base_url(req) + config.image_proxy.path,
    },
  });
});

api_01_app.get('/about', function (req, res, next) {
  var about_object = about();
  var about_info = about_object.load_about_data(req, function(result){
    res.jsonp({
      'result' : result,
    });
  });
});

api_01_app.use( function(req, res, next) {
    var db_name = config.MongoDB.popit_prefix + req.popit.instance_name();
    popitApi({
      databaseName: db_name,
      baseUrl: req.base_url,
      apiBaseUrl: req.api_base_url
    })(req, res, next);
});

// Load the various different API versions
app.use( '/v0.1', api_01_app );

app.get('/', function (req, res) {
  res.render('api/index.html');
});

app.all('*', function(req, res, next) {
  // 404
  res.json({ error: "page not found"}, 404);
});
<commit_msg>Set default language when calling the API<commit_after>"use strict";

var express = require('../../express-inherit'),
    apiRequireUserOrGuest = require('../../apps/auth').apiRequireUserOrGuest,
    base_url = require('../../middleware/route').base_url,
    about = require('../about'),
    config = require('config'),
    popitApi = require('popit-api');

var app = module.exports = express();

var api_01_app = express();
// Ensure that these methods all require a user.
api_01_app.post( '*', apiRequireUserOrGuest );
api_01_app.put(  '*', apiRequireUserOrGuest );
api_01_app.del(  '*', apiRequireUserOrGuest );

app.use(function(req, res, next) {
  req.base_url = base_url(req);
  req.api_base_url = req.base_url + '/api/v0.1';
  next();
});

api_01_app.get('/', function (req, res, next) {
  res.jsonp({
    note: "This is the API entry point - use a '*_api_url' link in 'meta' to search a collection.",
    meta: {
      persons_api_url: req.api_base_url + '/persons',
      organizations_api_url: req.api_base_url + '/organizations',
      memberships_api_url: req.api_base_url + '/memberships',
      image_proxy_url: base_url(req) + config.image_proxy.path,
    },
  });
});

api_01_app.get('/about', function (req, res, next) {
  var about_object = about();
  var about_info = about_object.load_about_data(req, function(result){
    res.jsonp({
      'result' : result,
    });
  });
});

api_01_app.use( function(req, res, next) {
    var db_name = config.MongoDB.popit_prefix + req.popit.instance_name();
    popitApi({
      databaseName: db_name,
      baseUrl: req.base_url,
      apiBaseUrl: req.api_base_url,

      // TODO: Make this configurable through the UI
      defaultLanguage: 'en',

    })(req, res, next);
});

// Load the various different API versions
app.use( '/v0.1', api_01_app );

app.get('/', function (req, res) {
  res.render('api/index.html');
});

app.all('*', function(req, res, next) {
  // 404
  res.json({ error: "page not found"}, 404);
});
<|endoftext|>


<commit_before>window.addEventListener('DOMContentLoaded', function() {
  chrome.tabs.query({
    url: "https://www.youtube.com/watch*"
  }, function(tabs) {

    var videoList = document.getElementById('video-list'),
      notice = document.getElementById('notice'),
      youtubeTitleEnding = "- YouTube",
      youtubeTitleEndingLength = youtubeTitleEnding.length;

    if (tabs.length > 0) {
      notice.classList.add("hidden");
      videoList.classList.remove("hidden");
    }

    tabs.forEach(function(tab) {
      var videoListItem = document.createElement("li"),
        videoListItemText = document.createElement("span"),
        videoControl = document.createElement("button"),
        videoControlText = "",
        tabId = tab.id,
        tabTitle = tab.title;

      if (tabTitle.substring(tabTitle.length - youtubeTitleEndingLength, tabTitle.length) === youtubeTitleEnding) {
        tabTitle = tabTitle.substring(0, tabTitle.length - youtubeTitleEndingLength).trim();
      }

      chrome.tabs.executeScript(tabId, {
        code: 'var video = document.querySelector("video");' +
          'video.paused;'
      }, function(result) {

        videoControlText = (result[0] === true) ? "Play" : "Pause";

        videoControl.classList.add("videoControlButton");
        videoControl.appendChild(document.createTextNode(videoControlText));
        videoControl.addEventListener("click", videoControlClicked);
        videoListItemText.appendChild(document.createTextNode(tabTitle));
        videoListItemText.addEventListener("click", videoNameClicked);
        videoListItem.appendChild(videoListItemText);
        videoListItem.appendChild(videoControl);
        videoListItem.dataset.tabId = tabId;
        videoList.appendChild(videoListItem);
      });

    });

  });

});

function videoControlClicked() {
  var tabId = parseInt(this.parentNode.dataset.tabId);
  chrome.tabs.executeScript(tabId, {
    code: 'var video = document.querySelector("video");' +
      'if (video.paused){video.play();} else {video.pause();}'
  }, function(result) {

  });
}

function videoNameClicked() {
  var tabId = parseInt(this.parentNode.dataset.tabId);
  chrome.tabs.update(tabId, {
    selected: true
  });
}
<commit_msg>Updated the control text after click<commit_after>window.addEventListener('DOMContentLoaded', function() {
  chrome.tabs.query({
    url: "https://www.youtube.com/watch*"
  }, function(tabs) {

    var videoList = document.getElementById('video-list'),
      notice = document.getElementById('notice'),
      youtubeTitleEnding = "- YouTube",
      youtubeTitleEndingLength = youtubeTitleEnding.length;

    if (tabs.length > 0) {
      notice.classList.add("hidden");
      videoList.classList.remove("hidden");
    }

    tabs.forEach(function(tab) {
      var videoListItem = document.createElement("li"),
        videoListItemText = document.createElement("span"),
        videoControl = document.createElement("button"),
        videoControlText = "",
        tabId = tab.id,
        tabTitle = tab.title;

      if (tabTitle.substring(tabTitle.length - youtubeTitleEndingLength, tabTitle.length) === youtubeTitleEnding) {
        tabTitle = tabTitle.substring(0, tabTitle.length - youtubeTitleEndingLength).trim();
      }

      chrome.tabs.executeScript(tabId, {
        code: 'var video = document.querySelector("video");' +
          'video.paused;'
      }, function(result) {

        videoControlText = (result[0] === true) ? "Play" : "Pause";

        videoControl.classList.add("videoControlButton");
        videoControl.textContent = videoControlText;
        videoControl.addEventListener("click", videoControlClicked);
        videoListItemText.appendChild(document.createTextNode(tabTitle));
        videoListItemText.addEventListener("click", videoNameClicked);
        videoListItem.appendChild(videoListItemText);
        videoListItem.appendChild(videoControl);
        videoListItem.dataset.tabId = tabId;
        videoList.appendChild(videoListItem);
      });

    });

  });

});

function videoControlClicked() {
  var tabId = parseInt(this.parentNode.dataset.tabId);
  chrome.tabs.executeScript(tabId, {
    code: 'var video = document.querySelector("video");' +
      'if (video.paused){video.play();} else {video.pause();}'+
      'video.paused;'
  }, function(result) {
      var paused = (result[0] === true),
          videoListItem = document.querySelector("li[data-tab-id=\""+tabId+"\"]"),
          videoControl  = videoListItem.querySelector("button");

      videoControl.textContent = paused?"Play":"Pause";
  });
}

function videoNameClicked() {
  var tabId = parseInt(this.parentNode.dataset.tabId);
  chrome.tabs.update(tabId, {
    selected: true
  });
}
<|endoftext|>


<commit_before>'use strict';

var debug = require('debug')('secc:archivemanager');
var path = require('path');
var mkdirp = require('mkdirp');

var ArchiveManager = function(express, io, SECC, SCHEDULER) {
  if (!(this instanceof ArchiveManager)) {
     return new ArchiveManager(express, io, SECC, SCHEDULER);
  }
  this.SECC = SECC;

  if (!SECC.uploadPath)
    throw new TypeError('SECC uploadPath is not set');
  if (!SECC.archivePath)
    throw new TypeError('SECC archivePath is not set');

  this.archiveDatabase = path.join(this.SECC.archivePath, 'archive.json');
  this.archives = {};

  //mkdir if not exists.
  mkdirp.sync(this.SECC.uploadPath);
  mkdirp.sync(this.SECC.archivePath);

  this.loadArchivesFromJson();
};

ArchiveManager.prototype.loadArchivesFromJson = function() {
  var self = this;
  var fs = require('fs');

  try {
    var data = fs.readFileSync(self.archiveDatabase);
    self.archives = JSON.parse(data.toString());
  } catch(e) {
    debug("archive.json read error")
  }

}

ArchiveManager.prototype.saveArchivesToJSON = function() {
  var self = this;
  var fs = require('fs');

  try {
    fs.writeFileSync(self.archiveDatabase, JSON.stringify(self.archives,null,2));
  } catch(e) {
    debug("archive.json write error")
  }

}

ArchiveManager.prototype.archiveExists = function(archiveId) {
  return this.archives.hasOwnProperty(archiveId);
}

ArchiveManager.prototype.getArchiveId = function(information) {
  var self = this;

  for (var archiveId in self.archives) {
    var a = self.archives[archiveId];

    if (information.compiler === 'gcc') {
      if ( a.platform === information.platform
        && a.arch === information.arch
        && a.compiler === information.compiler
        && a.version === information.version.replace('g++','gcc')
        && a.dumpmachine === information.dumpmachine) {
        return a.archiveId;
      }
    } else if (information.compiler === 'clang') {
      if ( a.platform === information.platform
        && a.arch === information.arch
        && a.compiler === information.compiler
        && a.version === information.version
        && a.dumpmachine === information.dumpmachine) {
        return a.archiveId;
      }
    } else {
      return null;
    }
  }

  return null;
}

ArchiveManager.prototype.getArchiveInfo = function(archiveId) {
  var self = this;

  if (self.archiveExists(archiveId)) {
    var a = self.archives[archiveId];
    return {archiveId: a.archiveId
          , platform: a.platform
          , arch: a.arch
          , compiler: a.compiler
          , compilerVersion: a.compilerVersion
          , version: a.version
          , dumpmachine: a.dumpmachine
          , targets: a.targets
          , archiveLog: a.archiveLog
          , archiveFile: a.archiveFile
          , creationDatetime : a.creationDatetime};
  } else
    return null;
}

ArchiveManager.prototype.getArchiveList = function() {
  var self = this;
  var archiveList = [];

  for(var archiveId in self.archives) {
    archiveList.push(self.getArchiveInfo(archiveId));
  }
  return archiveList;
}

ArchiveManager.prototype.getArchiveIdsByTarget = function(target) {
  var self = this;
  var archiveIds = [];

  for(var archiveId in self.archives) {
    if (self.archives[archiveId].targets.indexOf(target) !== -1)
      archiveIds.push(archiveId);
  }

  return archiveIds;
}

ArchiveManager.prototype.addTarget = function(archiveId, target, cb) {
  var self = this;

  if (!self.archiveExists(archiveId))
    return cb(new Error('Archive not exists'));

  var archive = self.archives[archiveId];
  if (archive.targets.indexOf(target) !== -1)
    return cb(null, archive); //Target already exists

  archive.targets.push(target);
  self.saveArchivesToJSON();
  return cb(null, archive);
}

ArchiveManager.prototype.removeTarget = function(archiveId, target, cb) {
  var self = this;

  if (!self.archiveExists(archiveId))
    return cb(new Error('Archive not exists'));

  var archive = self.archives[archiveId];
  var index = archive.targets.indexOf(target);
  if (index === -1)
    return cb(null, archive); //Target not exists

  archive.targets.splice(index, 1);
  self.saveArchivesToJSON();
  return cb(null, archive);
}

ArchiveManager.prototype.addArchive = function(archive, file, cb) {
  var self = this;

  if (self.archiveExists(archive.archiveId))
    return cb(new Error('This archive already exists'));

  archive.creationDatetime = new Date();

  //file..
  var fs = require('fs');
  var path = require('path');
  var fromFile = path.join(self.SECC.uploadPath, file.filename);
  var toFile = path.join(self.SECC.archivePath, archive.archiveFile);

  //FIXME : looks ugly.. need to refactoring.
  return fs.createReadStream(fromFile)
    .on('error',function(err){
      debug('error raised in createReadStream');
      debug(err);
      fs.unlink(fromFile, function(err){
        if(err && err.code !== 'ENOENT')
          return debug(err);
        return ;
      });
      return cb(err);
    })
    .pipe(fs.createWriteStream(toFile))
    .on('error', function(err){
      debug('error raised in createWriteStream');
      debug(err);
      fs.unlink(toFile, function(err){
        if(err && err.code !== 'ENOENT')
          return debug(err);
        return ;
      });
      return cb(err);
    })
    .on('finish', function(){
      debug('copy done.');
      fs.unlink(fromFile, function(err){
        if(err && err.code !== 'ENOENT')
          return debug(err);
        return ;
      });

      self.archives[archive.archiveId] = archive;
      self.saveArchivesToJSON();
      return cb(null, archive);
    });
}

ArchiveManager.prototype.removeArchive = function(archiveId, cb) {
  var self = this;

  if (!self.archiveExists(archiveId))
    return cb(new Error('Archive not exists'));

  var fs = require('fs');
  return fs.unlink(path.join(self.SECC.archivePath, self.archives[archiveId].archiveFile) , function(err){
    if (err) return cb(err);

    delete self.archives[archiveId];
    self.saveArchivesToJSON();
    return cb(null);
  });

  cb(new Error('Assert not reached in removeArchive'));
}

module.exports = ArchiveManager;
<commit_msg>[scheduler] refactoring. do not check the dumpversion in getArchiveId()<commit_after>'use strict';

var debug = require('debug')('secc:archivemanager');
var path = require('path');
var mkdirp = require('mkdirp');

var ArchiveManager = function(express, io, SECC, SCHEDULER) {
  if (!(this instanceof ArchiveManager)) {
     return new ArchiveManager(express, io, SECC, SCHEDULER);
  }
  this.SECC = SECC;

  if (!SECC.uploadPath)
    throw new TypeError('SECC uploadPath is not set');
  if (!SECC.archivePath)
    throw new TypeError('SECC archivePath is not set');

  this.archiveDatabase = path.join(this.SECC.archivePath, 'archive.json');
  this.archives = {};

  //mkdir if not exists.
  mkdirp.sync(this.SECC.uploadPath);
  mkdirp.sync(this.SECC.archivePath);

  this.loadArchivesFromJson();
};

ArchiveManager.prototype.loadArchivesFromJson = function() {
  var self = this;
  var fs = require('fs');

  try {
    var data = fs.readFileSync(self.archiveDatabase);
    self.archives = JSON.parse(data.toString());
  } catch(e) {
    debug("archive.json read error")
  }

}

ArchiveManager.prototype.saveArchivesToJSON = function() {
  var self = this;
  var fs = require('fs');

  try {
    fs.writeFileSync(self.archiveDatabase, JSON.stringify(self.archives,null,2));
  } catch(e) {
    debug("archive.json write error")
  }

}

ArchiveManager.prototype.archiveExists = function(archiveId) {
  return this.archives.hasOwnProperty(archiveId);
}

ArchiveManager.prototype.getArchiveId = function(information) {
  var self = this;

  for (var archiveId in self.archives) {
    var a = self.archives[archiveId];

    if ( a.platform === information.platform
      && a.arch === information.arch
      && a.compiler === information.compiler
      && a.compilerVersion === information.compilerVersion
      && a.dumpmachine === information.dumpmachine) {
      return a.archiveId;
    }
  }

  return null;
}

ArchiveManager.prototype.getArchiveInfo = function(archiveId) {
  var self = this;

  if (self.archiveExists(archiveId)) {
    var a = self.archives[archiveId];
    return {archiveId: a.archiveId
          , platform: a.platform
          , arch: a.arch
          , compiler: a.compiler
          , compilerVersion: a.compilerVersion
          , version: a.version
          , dumpmachine: a.dumpmachine
          , targets: a.targets
          , archiveLog: a.archiveLog
          , archiveFile: a.archiveFile
          , creationDatetime : a.creationDatetime};
  } else
    return null;
}

ArchiveManager.prototype.getArchiveList = function() {
  var self = this;
  var archiveList = [];

  for(var archiveId in self.archives) {
    archiveList.push(self.getArchiveInfo(archiveId));
  }
  return archiveList;
}

ArchiveManager.prototype.getArchiveIdsByTarget = function(target) {
  var self = this;
  var archiveIds = [];

  for(var archiveId in self.archives) {
    if (self.archives[archiveId].targets.indexOf(target) !== -1)
      archiveIds.push(archiveId);
  }

  return archiveIds;
}

ArchiveManager.prototype.addTarget = function(archiveId, target, cb) {
  var self = this;

  if (!self.archiveExists(archiveId))
    return cb(new Error('Archive not exists'));

  var archive = self.archives[archiveId];
  if (archive.targets.indexOf(target) !== -1)
    return cb(null, archive); //Target already exists

  archive.targets.push(target);
  self.saveArchivesToJSON();
  return cb(null, archive);
}

ArchiveManager.prototype.removeTarget = function(archiveId, target, cb) {
  var self = this;

  if (!self.archiveExists(archiveId))
    return cb(new Error('Archive not exists'));

  var archive = self.archives[archiveId];
  var index = archive.targets.indexOf(target);
  if (index === -1)
    return cb(null, archive); //Target not exists

  archive.targets.splice(index, 1);
  self.saveArchivesToJSON();
  return cb(null, archive);
}

ArchiveManager.prototype.addArchive = function(archive, file, cb) {
  var self = this;

  if (self.archiveExists(archive.archiveId))
    return cb(new Error('This archive already exists'));

  archive.creationDatetime = new Date();

  //file..
  var fs = require('fs');
  var path = require('path');
  var fromFile = path.join(self.SECC.uploadPath, file.filename);
  var toFile = path.join(self.SECC.archivePath, archive.archiveFile);

  //FIXME : looks ugly.. need to refactoring.
  return fs.createReadStream(fromFile)
    .on('error',function(err){
      debug('error raised in createReadStream');
      debug(err);
      fs.unlink(fromFile, function(err){
        if(err && err.code !== 'ENOENT')
          return debug(err);
        return ;
      });
      return cb(err);
    })
    .pipe(fs.createWriteStream(toFile))
    .on('error', function(err){
      debug('error raised in createWriteStream');
      debug(err);
      fs.unlink(toFile, function(err){
        if(err && err.code !== 'ENOENT')
          return debug(err);
        return ;
      });
      return cb(err);
    })
    .on('finish', function(){
      debug('copy done.');
      fs.unlink(fromFile, function(err){
        if(err && err.code !== 'ENOENT')
          return debug(err);
        return ;
      });

      self.archives[archive.archiveId] = archive;
      self.saveArchivesToJSON();
      return cb(null, archive);
    });
}

ArchiveManager.prototype.removeArchive = function(archiveId, cb) {
  var self = this;

  if (!self.archiveExists(archiveId))
    return cb(new Error('Archive not exists'));

  var fs = require('fs');
  return fs.unlink(path.join(self.SECC.archivePath, self.archives[archiveId].archiveFile) , function(err){
    if (err) return cb(err);

    delete self.archives[archiveId];
    self.saveArchivesToJSON();
    return cb(null);
  });

  cb(new Error('Assert not reached in removeArchive'));
}

module.exports = ArchiveManager;
<|endoftext|>