<commit_before>import _ from 'lodash';

export default class MQEQuery {

  /** @ngInject */
  constructor(target, templateSrv, scopedVars) {
    this.target = target;
    this.templateSrv = templateSrv;
    // this.templateSrv.formatValue = formatMQEMetric;
    this.scopedVars = scopedVars;
  }

  /////////////////////
  // Query Rendering //
  /////////////////////

  render(metricList, timeFrom, timeTo, interval) {
    let target = this.target;
    let metrics = [];

    for (let m of target.metrics) {
      let metric = m.metric;
      if (metric) {
        if (containsWildcard(metric)) {
          let filteredMetrics = filterMetrics(metric, metricList);

          // Add alias
          if (m.alias) {
            if (containsWildcard(m.alias)) {
              // Set whildcard part as metric alias
              // query: os.cpu.* alias: * -> metric: os.cpu.system -> alias: system
              filteredMetrics = _.map(filteredMetrics,
                _.partial(convertMetricWithWildcard, target.functionList, metric));
            } else if(containsIndex(m.alias)){
                // query: tag1.tag2.* (the  metric can be very lengthy like below)
                // metric: tag1.tag2.tag3.tag4.tag5.tag6
                // alias: $6 ie show only tag6
                var indices = getAliasIndexArray(m.alias);
                filteredMetrics = _.map(filteredMetrics, _.partial(convertMetricWithIndex, target.functionList, indices));
            }
            else {
              filteredMetrics = _.map(filteredMetrics,
                _.compose(_.partial(this.addFunctionsWithAlias, target.functionList, m.alias), wrapMetric));
            }
          } else {
            filteredMetrics = _.map(filteredMetrics, _.partial(this.addFunctionsToMetric, target.functionList));
          }

          metrics = metrics.concat(filteredMetrics);
        } else {
          var defaultAlias = metric;
          metric = wrapMetric(metric);
          // add functions here for single metric without wildcard
          // Render functions if any
          if(target.functionList.length != 0) {
              metric += addFunctions(target.functionList);
          }
          // Add alias
          if (m.alias) {
            metric = addMQEAlias(m.alias, metric);
          }
          else {
              metric = addMQEAlias(defaultAlias, metric);
          }
          metrics = metrics.concat(metric);
        }
      }
    }
    metrics = _.uniq(metrics);

    return _.map(metrics, metric => {
      let query = "";

      // Set custom metric format function
      let formatValueOriginal = this.templateSrv.formatValue;
      this.templateSrv.formatValue = formatMQEMetric;
      metric = this.templateSrv.replace(metric, this.scopedVars);

      // Set original format function
      this.templateSrv.formatValue = formatValueOriginal;

      query += metric;

      // Render apps and hosts
      query += this.renderWhere(target.apps, target.hosts);

      query = MQEQuery.addTimeRange(query, timeFrom, timeTo);
      return query;
    });
  }

   addFunctionsWithAlias(functionList, alias, metric) {
    if(functionList.length != 0) {
        metric += addFunctions(functionList);
    }
    var resultmetric =  addMQEAlias(alias, metric);
    return resultmetric;
  }

  addFunctionsToMetric(functionList, metric) {
    let defaultAlias = metric;
    metric = wrapMetric(metric);
    if(functionList.length != 0) {
        metric += addFunctions(functionList);
        return addMQEAlias(defaultAlias, metric);
    }

    return metric;
}

  renderWhere(apps, hosts) {
    let query = "";
    if (apps.length || hosts.length) {
      query += " where ";
      if (apps.length) {
        query += "app in (" + _.map(apps, wrapTag).join(', ') + ")";
        if (hosts.length)  {
          query += " and ";
        }
      }
      if (hosts.length) {
        query += "host in (" + _.map(hosts, wrapTag).join(', ') + ")";
      }
    }
    return query;
  }

  renderWhereClauses(whereClauses) {
    var renderedClauses = _.map(whereClauses, (clauseObj, index) => {
      var rendered = "";
      if (index !== 0) {
        rendered += clauseObj.condition + " ";
      }

      // Put non-numeric values into quotes.
      var value;
      if (_.isNumber(clauseObj.value) ||
          this.containsVariable(clauseObj.value)) {
        value = clauseObj.value;
      } else {
        value = "'" + clauseObj.value + "'";
      }
      rendered += clauseObj.column + ' ' + clauseObj.operator + ' ' + value;
      return rendered;
    });
    return renderedClauses.join(' ');
  }

  // Check for template variables
  containsVariable(str) {
    var variables = _.map(this.templateSrv.variables, 'name');
    var self = this;
    return _.some(variables, variable => {
      return self.templateSrv.containsVariable(str, variable);
    });
  }

  ////////////////////
  // Static methods //
  ////////////////////

  static getMetrics() {
    var query = "describe all";
    return query;
  }

  static getColumns(metric) {
    return "describe " + metric;
  }

  static addTimeRange(query, timeFrom, timeTo, interval) {
    var timeRangeRegex = /from.*to/;
    if(!timeRangeRegex.test(query)) {
      query = trim(query) + " from " + timeFrom + " to " + timeTo;
    }
    return query;
  }
}

function containsWildcard(str) {
  var wildcardRegex = /[*!]/;
  return wildcardRegex.test(str);
}

function containsIndex(str) {
    var wildcardRegex = /\$(\d)/g;
    return wildcardRegex.test(str);
}

function getAliasIndexArray(str) {
    // replace all the $ with space
    // convert it to list
    str = str.replace(/\$/g, ' ');
    str = str.trim();
    var indices = str.split(' ');
    for(var i=0; i<indices.length; i++) {
        indices[i] = parseInt(indices[i], 10);
    }
    return indices;
}

function getMetricSplits(str) {
    var metricSplits = str.split('.');
    return (metricSplits);

}

function getCustomAliasName(metricSplits, indices) {
    var aliasString = "";
    for( var i = 0; i<indices.length; i++) {
        var index = indices[i]-1;
        if(index >= 0 && index <  metricSplits.length) {

            aliasString += metricSplits[indices[i] - 1] + ".";
        }
    }
    return aliasString.slice(0, -1);
}

function addFunctions(functions){
    var query = "";
    if (functions.length) {
        _.forEach(functions, function (fn) {
            console.log('current function', fn);
            if(fn.func.length != 0) {
                query += "|" + fn.func + " ";
            }
        });
    }
    return query;
}

function convertMetricWithIndex(indices, metric) {
    var suffix = getCustomAliasName(getMetricSplits(metric),indices);
    return addMQEAlias(suffix, wrapMetric(metric));
}
function composeRegex(str){
  var regex="";
  var metricSplits = getMetricSplits(str);
  for(var i = 0; i<metricSplits.length; i++){
    if(metricSplits[i].search(/!/g ) !== -1){
       var str = metricSplits[i].replace(/!/g,"");
          regex += "^(?!.*"+str;
    }
    else if(metricSplits[i].search(/\*/g ) !== -1){
        var str = metricSplits[i].replace(/\*/g,"");
           regex += "(?=.*"+str;
    }
    else {
        regex += "(?=.*"+metricSplits[i];
    }
        regex += (i == metricSplits.length-1) ? ")" : "\.)";
  }
  regex = new RegExp(regex);
  return regex;
}

function filterMetrics(str, metrics) {
  let filterRegex;
  var  containsFilter = str.search(/!/);
  var metricSplits ;
  if(containsFilter !== -1) {
      filterRegex = composeRegex(str);
  }
  else {
      str = str.replace(/\./g, '\\\.');
      filterRegex = new RegExp(str.replace('*', '.*'), 'g');
  }
     return _.filter(metrics, metric => {
       return metric.search(filterRegex) !== -1;
     });
}

function trim(str) {
  var trimRegex = /^[\s]*(.*?)[\s]*$/;
  var match = str.match(trimRegex);
  return match ? match[0] : match;
}

function convertMetricWithWildcard(functions, metricQuery, metric) {
  let suffix = getMetricSuffix(metricQuery, metric);
  metric = wrapMetric(metric);

  // Render functions if any  before add alias
  if(functions.length != 0) {
      metric += addFunctions(functions);
  }
  return addMQEAlias(suffix, metric);
}

function getMetricSuffix(metricQuery, metric) {
  let metricPrefix = metricQuery.replace(/\./g, '\\\.');
  let suffixRegex = new RegExp(metricPrefix.replace('*', '(.*)'));
  let suffix = suffixRegex.exec(metric);
  return suffix[1];
}

function addMQEAlias(alias, metric) {
  return metric + " {" + alias + "}";
}

// Wrap metric with ``: os.cpu.user -> `os.cpu.user`
function wrapMetric(metric) {
  return '`' + metric + '`';
}

function wrapTag(tag) {
  return "'" + tag + "'";
}

// Special value formatter for MQE metric.
// Render multi-value variables for using with metric template:
// $metric => ('os.cpu.user', 'os.cpu.system')
// select `$metric` => select `os.cpu.user`, `os.cpu.system`
function formatMQEMetric(value, format, variable) {
  if (typeof value === 'string') {
    return value;
  }
  return value.join("`, `");
}
<commit_msg>Remove debug console.log<commit_after>import _ from 'lodash';

export default class MQEQuery {

  /** @ngInject */
  constructor(target, templateSrv, scopedVars) {
    this.target = target;
    this.templateSrv = templateSrv;
    // this.templateSrv.formatValue = formatMQEMetric;
    this.scopedVars = scopedVars;
  }

  /////////////////////
  // Query Rendering //
  /////////////////////

  render(metricList, timeFrom, timeTo, interval) {
    let target = this.target;
    let metrics = [];

    for (let m of target.metrics) {
      let metric = m.metric;
      if (metric) {
        if (containsWildcard(metric)) {
          let filteredMetrics = filterMetrics(metric, metricList);

          // Add alias
          if (m.alias) {
            if (containsWildcard(m.alias)) {
              // Set whildcard part as metric alias
              // query: os.cpu.* alias: * -> metric: os.cpu.system -> alias: system
              filteredMetrics = _.map(filteredMetrics,
                _.partial(convertMetricWithWildcard, target.functionList, metric));
            } else if(containsIndex(m.alias)){
                // query: tag1.tag2.* (the  metric can be very lengthy like below)
                // metric: tag1.tag2.tag3.tag4.tag5.tag6
                // alias: $6 ie show only tag6
                var indices = getAliasIndexArray(m.alias);
                filteredMetrics = _.map(filteredMetrics, _.partial(convertMetricWithIndex, target.functionList, indices));
            }
            else {
              filteredMetrics = _.map(filteredMetrics,
                _.compose(_.partial(this.addFunctionsWithAlias, target.functionList, m.alias), wrapMetric));
            }
          } else {
            filteredMetrics = _.map(filteredMetrics, _.partial(this.addFunctionsToMetric, target.functionList));
          }

          metrics = metrics.concat(filteredMetrics);
        } else {
          var defaultAlias = metric;
          metric = wrapMetric(metric);
          // add functions here for single metric without wildcard
          // Render functions if any
          if(target.functionList.length != 0) {
              metric += addFunctions(target.functionList);
          }
          // Add alias
          if (m.alias) {
            metric = addMQEAlias(m.alias, metric);
          }
          else {
              metric = addMQEAlias(defaultAlias, metric);
          }
          metrics = metrics.concat(metric);
        }
      }
    }
    metrics = _.uniq(metrics);

    return _.map(metrics, metric => {
      let query = "";

      // Set custom metric format function
      let formatValueOriginal = this.templateSrv.formatValue;
      this.templateSrv.formatValue = formatMQEMetric;
      metric = this.templateSrv.replace(metric, this.scopedVars);

      // Set original format function
      this.templateSrv.formatValue = formatValueOriginal;

      query += metric;

      // Render apps and hosts
      query += this.renderWhere(target.apps, target.hosts);

      query = MQEQuery.addTimeRange(query, timeFrom, timeTo);
      return query;
    });
  }

   addFunctionsWithAlias(functionList, alias, metric) {
    if(functionList.length != 0) {
        metric += addFunctions(functionList);
    }
    var resultmetric =  addMQEAlias(alias, metric);
    return resultmetric;
  }

  addFunctionsToMetric(functionList, metric) {
    let defaultAlias = metric;
    metric = wrapMetric(metric);
    if(functionList.length != 0) {
        metric += addFunctions(functionList);
        return addMQEAlias(defaultAlias, metric);
    }

    return metric;
}

  renderWhere(apps, hosts) {
    let query = "";
    if (apps.length || hosts.length) {
      query += " where ";
      if (apps.length) {
        query += "app in (" + _.map(apps, wrapTag).join(', ') + ")";
        if (hosts.length)  {
          query += " and ";
        }
      }
      if (hosts.length) {
        query += "host in (" + _.map(hosts, wrapTag).join(', ') + ")";
      }
    }
    return query;
  }

  renderWhereClauses(whereClauses) {
    var renderedClauses = _.map(whereClauses, (clauseObj, index) => {
      var rendered = "";
      if (index !== 0) {
        rendered += clauseObj.condition + " ";
      }

      // Put non-numeric values into quotes.
      var value;
      if (_.isNumber(clauseObj.value) ||
          this.containsVariable(clauseObj.value)) {
        value = clauseObj.value;
      } else {
        value = "'" + clauseObj.value + "'";
      }
      rendered += clauseObj.column + ' ' + clauseObj.operator + ' ' + value;
      return rendered;
    });
    return renderedClauses.join(' ');
  }

  // Check for template variables
  containsVariable(str) {
    var variables = _.map(this.templateSrv.variables, 'name');
    var self = this;
    return _.some(variables, variable => {
      return self.templateSrv.containsVariable(str, variable);
    });
  }

  ////////////////////
  // Static methods //
  ////////////////////

  static getMetrics() {
    var query = "describe all";
    return query;
  }

  static getColumns(metric) {
    return "describe " + metric;
  }

  static addTimeRange(query, timeFrom, timeTo, interval) {
    var timeRangeRegex = /from.*to/;
    if(!timeRangeRegex.test(query)) {
      query = trim(query) + " from " + timeFrom + " to " + timeTo;
    }
    return query;
  }
}

function containsWildcard(str) {
  var wildcardRegex = /[*!]/;
  return wildcardRegex.test(str);
}

function containsIndex(str) {
    var wildcardRegex = /\$(\d)/g;
    return wildcardRegex.test(str);
}

function getAliasIndexArray(str) {
    // replace all the $ with space
    // convert it to list
    str = str.replace(/\$/g, ' ');
    str = str.trim();
    var indices = str.split(' ');
    for(var i=0; i<indices.length; i++) {
        indices[i] = parseInt(indices[i], 10);
    }
    return indices;
}

function getMetricSplits(str) {
    var metricSplits = str.split('.');
    return (metricSplits);

}

function getCustomAliasName(metricSplits, indices) {
    var aliasString = "";
    for( var i = 0; i<indices.length; i++) {
        var index = indices[i]-1;
        if(index >= 0 && index <  metricSplits.length) {

            aliasString += metricSplits[indices[i] - 1] + ".";
        }
    }
    return aliasString.slice(0, -1);
}

function addFunctions(functions){
    var query = "";
    if (functions.length) {
        _.forEach(functions, function (fn) {
            if(fn.func.length != 0) {
                query += "|" + fn.func + " ";
            }
        });
    }
    return query;
}

function convertMetricWithIndex(indices, metric) {
    var suffix = getCustomAliasName(getMetricSplits(metric),indices);
    return addMQEAlias(suffix, wrapMetric(metric));
}
function composeRegex(str){
  var regex="";
  var metricSplits = getMetricSplits(str);
  for(var i = 0; i<metricSplits.length; i++){
    if(metricSplits[i].search(/!/g ) !== -1){
       var str = metricSplits[i].replace(/!/g,"");
          regex += "^(?!.*"+str;
    }
    else if(metricSplits[i].search(/\*/g ) !== -1){
        var str = metricSplits[i].replace(/\*/g,"");
           regex += "(?=.*"+str;
    }
    else {
        regex += "(?=.*"+metricSplits[i];
    }
        regex += (i == metricSplits.length-1) ? ")" : "\.)";
  }
  regex = new RegExp(regex);
  return regex;
}

function filterMetrics(str, metrics) {
  let filterRegex;
  var  containsFilter = str.search(/!/);
  var metricSplits ;
  if(containsFilter !== -1) {
      filterRegex = composeRegex(str);
  }
  else {
      str = str.replace(/\./g, '\\\.');
      filterRegex = new RegExp(str.replace('*', '.*'), 'g');
  }
     return _.filter(metrics, metric => {
       return metric.search(filterRegex) !== -1;
     });
}

function trim(str) {
  var trimRegex = /^[\s]*(.*?)[\s]*$/;
  var match = str.match(trimRegex);
  return match ? match[0] : match;
}

function convertMetricWithWildcard(functions, metricQuery, metric) {
  let suffix = getMetricSuffix(metricQuery, metric);
  metric = wrapMetric(metric);

  // Render functions if any  before add alias
  if(functions.length != 0) {
      metric += addFunctions(functions);
  }
  return addMQEAlias(suffix, metric);
}

function getMetricSuffix(metricQuery, metric) {
  let metricPrefix = metricQuery.replace(/\./g, '\\\.');
  let suffixRegex = new RegExp(metricPrefix.replace('*', '(.*)'));
  let suffix = suffixRegex.exec(metric);
  return suffix[1];
}

function addMQEAlias(alias, metric) {
  return metric + " {" + alias + "}";
}

// Wrap metric with ``: os.cpu.user -> `os.cpu.user`
function wrapMetric(metric) {
  return '`' + metric + '`';
}

function wrapTag(tag) {
  return "'" + tag + "'";
}

// Special value formatter for MQE metric.
// Render multi-value variables for using with metric template:
// $metric => ('os.cpu.user', 'os.cpu.system')
// select `$metric` => select `os.cpu.user`, `os.cpu.system`
function formatMQEMetric(value, format, variable) {
  if (typeof value === 'string') {
    return value;
  }
  return value.join("`, `");
}
<|endoftext|>


<commit_before>var React        = require('react'),
    shallowEqual = require('react/lib/shallowEqual'),
    availableEvents,
    propTypes;

// Events available on iScroll instance
// [`iscroll event name`, `react component event name`]
availableEvents = [
  ['beforeScrollStart', "onBeforeScrollStart"],
  ['scrollCancel', "onScrollCancel"],
  ['scrollStart', "onScrollStart"],
  ['scroll', "onScroll"],
  ['scrollEnd', "onScrollEnd"],
  ['flick', "onFlick"],
  ['zoomStart', "onZoomStart"],
  ['zoomEnd', "onZoomEnd"]
]

// Generate propTypes with event function validating
propTypes = {
  options: React.PropTypes.object,
  iscroll: function(props, propName, componentName) {
    var iscroll = props[propName],
        proto   = iscroll && iscroll.prototype;

    if(!iscroll || !proto || !proto.version || !proto.scrollTo) {
      return new Error(componentName + ": iscroll not passed to component props.")
    } else {
      if(!/^5\..*/.test(proto.version)) {
        console.warn(componentName + ": different version than 5.x.y of iscroll is loaded.")
      }

      if(props.options && props.options.zoom && !proto.zoom) {
        console.warn(componentName + ": options.zoom is true, but iscroll-zoom version is not loaded.")
      }
    }
  },
  onRefresh: React.PropTypes.func
}

for(var i = 0; i < availableEvents.length; i++) {
  propTypes[availableEvents[i][1]] = React.PropTypes.func
}

var ReactIScroll = React.createClass({
  displayName: 'ReactIScroll',

  propTypes: propTypes,

  getDefaultProps: function() {
    return {
      defer: 0,
      options: {},
      style: {
        position: "relative",
        height: "100%",
        width: "100%",
        overflow: "hidden"
      }
    }
  },

  componentWillMount: function() {
    this._queuedCallbacks = []
  },

  componentDidMount: function() {
    this._initializeIScroll()
  },

  componentWillUnmount: function() {
    this._teardownIScroll()
  },

  // There is no state, we can compare only props.
  shouldComponentUpdate: function(nextProps) {
    return !shallowEqual(this.props, nextProps)
  },

  // Check if iscroll options has changed and recreate instance with new one
  componentDidUpdate: function(prevProps) {
    var options = this.props.options,
        x, y, scale;

    if(shallowEqual(prevProps.options, options)) {
      this.refresh()
      this._updateIScrollEvents(prevProps, this.props)
    } else {
      // Save current state
      x     = this._iScrollInstance.x
      y     = this._iScrollInstance.y
      scale = this._iScrollInstance.scale

      // Destroy current and Create new instance of iscroll
      this._teardownIScroll()
      this._initializeIScroll()

      // Restore previous state
      if(scale && this._iScrollInstance.zoom) {
        this._iScrollInstance.zoom(scale, 0, 0, 0)
      }

      this._iScrollInstance.scrollTo(x,y)
    }
  },

  getIScroll: function() {
    return this._iScrollInstance;
  },

  getIScrollInstance: function() {
    console.warn("Function 'getIScrollInstance' is deprecated. Instead use 'getIScroll'")
    return this._iScrollInstance;
  },

  withIScroll: function(waitForInit, callback) {
    if(!callback && typeof waitForInit == "function") {
      callback = waitForInit
    }

    if(this.getIScroll()) {
      callback(this.getIScroll())
    } else if (waitForInit) {
      this._queuedCallbacks.push(callback)
    }
  },

  refresh: function() {
    this._iScrollInstance && this._iScrollInstance.refresh()
  },

  _initializeIScroll: function() {
    var self = this,
        origRefresh;

    setTimeout(function() {
      // Create iScroll instance with given options
      self._iScrollInstance = new self.props.iscroll(self.getDOMNode(), self.props.options)
      self._triggerRefreshEvent()

      // Patch iscroll instance .refresh() function to trigger our onRefresh event
      origRefresh = self._iScrollInstance.refresh
      self._iScrollInstance.refresh = function() {
        origRefresh.apply(self._iScrollInstance)
        self._triggerRefreshEvent()
      }

      // Bind iScroll events
      self._bindIScrollEvents()

      self._callQueuedCallbacks()
    }, this.props.defer)
  },

  _callQueuedCallbacks: function() {
    var callbacks = this._queuedCallbacks,
        len = callbacks.length, i = 0;

    this._queuedCallbacks = []

    for(i; i < len; i++) {
      callbacks[i](this.getIScroll())
    }
  },
  _teardownIScroll: function() {
    this._iScrollInstance.destroy()
    this._iScrollInstance = undefined
  },

  _bindIScrollEvents: function() {
    // Bind events on iScroll instance
    this._iScrollBindedEvents = {}
    this._updateIScrollEvents({}, this.props)
  },

  // Iterate through available events and update one by one
  _updateIScrollEvents: function(props1, props2) {
    var len = availableEvents.length,
        i = 0,
        evenNames;

    for(i; i < len; i++) {
      eventNames = availableEvents[i]

      this._updateIScrollEvent(eventNames[0],
                               props1[eventNames[1]],
                               props2[eventNames[1]])
    }
  },

  // Unbind and/or Bind event if it was changed during update
  _updateIScrollEvent: function(eventName, prevEvent, currentEvent) {
    var iScrollInstance, currentEvents, callback;

    if(prevEvent !== currentEvent) {
      iScrollInstance = this._iScrollInstance
      currentEvents = this._iScrollBindedEvents

      if(prevEvent) {
        iScrollInstance.off(eventName, currentEvents[eventName])
        currentEvents[eventName] = undefined
      }

      if(currentEvent) {
        callback = function() {currentEvent(iScrollInstance)}

        this._iScrollInstance.on(eventName, callback)
        currentEvents[eventName] = callback
      }
    }
  },

  _triggerRefreshEvent: function() {
    if(this.props.onRefresh) {
      this.props.onRefresh(this._iScrollInstance)
    }
  },

  render: function() {
    return React.createElement("div", {className: this.props.className, style: this.props.style},
             React.createElement("div", {style: this.props.scrollerStyle}, this.props.children)
           )
  }
})

module.exports = ReactIScroll
<commit_msg>allow initialization without setTimeout<commit_after>var React        = require('react'),
    shallowEqual = require('react/lib/shallowEqual'),
    availableEvents,
    propTypes;

// Events available on iScroll instance
// [`iscroll event name`, `react component event name`]
availableEvents = [
  ['beforeScrollStart', "onBeforeScrollStart"],
  ['scrollCancel', "onScrollCancel"],
  ['scrollStart', "onScrollStart"],
  ['scroll', "onScroll"],
  ['scrollEnd', "onScrollEnd"],
  ['flick', "onFlick"],
  ['zoomStart', "onZoomStart"],
  ['zoomEnd', "onZoomEnd"]
]

// Generate propTypes with event function validating
propTypes = {
  options: React.PropTypes.object,
  iscroll: function(props, propName, componentName) {
    var iscroll = props[propName],
        proto   = iscroll && iscroll.prototype;

    if(!iscroll || !proto || !proto.version || !proto.scrollTo) {
      return new Error(componentName + ": iscroll not passed to component props.")
    } else {
      if(!/^5\..*/.test(proto.version)) {
        console.warn(componentName + ": different version than 5.x.y of iscroll is loaded.")
      }

      if(props.options && props.options.zoom && !proto.zoom) {
        console.warn(componentName + ": options.zoom is true, but iscroll-zoom version is not loaded.")
      }
    }
  },
  onRefresh: React.PropTypes.func
}

for(var i = 0; i < availableEvents.length; i++) {
  propTypes[availableEvents[i][1]] = React.PropTypes.func
}

var ReactIScroll = React.createClass({
  displayName: 'ReactIScroll',

  propTypes: propTypes,

  getDefaultProps: function() {
    return {
      defer: 0,
      options: {},
      style: {
        position: "relative",
        height: "100%",
        width: "100%",
        overflow: "hidden"
      }
    }
  },

  componentWillMount: function() {
    this._queuedCallbacks = []
  },

  componentDidMount: function() {
    this._initializeIScroll()
  },

  componentWillUnmount: function() {
    this._teardownIScroll()
  },

  // There is no state, we can compare only props.
  shouldComponentUpdate: function(nextProps) {
    return !shallowEqual(this.props, nextProps)
  },

  // Check if iscroll options has changed and recreate instance with new one
  componentDidUpdate: function(prevProps) {
    var options = this.props.options,
        x, y, scale;

    if(shallowEqual(prevProps.options, options)) {
      this.refresh()
      this._updateIScrollEvents(prevProps, this.props)
    } else {
      // Save current state
      x     = this._iScrollInstance.x
      y     = this._iScrollInstance.y
      scale = this._iScrollInstance.scale

      // Destroy current and Create new instance of iscroll
      this._teardownIScroll()
      this._initializeIScroll()

      // Restore previous state
      if(scale && this._iScrollInstance.zoom) {
        this._iScrollInstance.zoom(scale, 0, 0, 0)
      }

      this._iScrollInstance.scrollTo(x,y)
    }
  },

  getIScroll: function() {
    return this._iScrollInstance;
  },

  getIScrollInstance: function() {
    console.warn("Function 'getIScrollInstance' is deprecated. Instead use 'getIScroll'")
    return this._iScrollInstance;
  },

  withIScroll: function(waitForInit, callback) {
    if(!callback && typeof waitForInit == "function") {
      callback = waitForInit
    }

    if(this.getIScroll()) {
      callback(this.getIScroll())
    } else if (waitForInit) {
      this._queuedCallbacks.push(callback)
    }
  },

  refresh: function() {
    this._iScrollInstance && this._iScrollInstance.refresh()
  },

  _initializeIScroll: function() {
    var self = this;
    var init = function() {
      // Create iScroll instance with given options
      self._iScrollInstance = new self.props.iscroll(self.getDOMNode(), self.props.options);
      self._triggerRefreshEvent();

      // Patch iscroll instance .refresh() function to trigger our onRefresh event
      var origRefresh = self._iScrollInstance.refresh;
      self._iScrollInstance.refresh = function() {
        origRefresh.apply(self._iScrollInstance);
        self._triggerRefreshEvent();
      }

      // Bind iScroll events
      self._bindIScrollEvents();

      self._callQueuedCallbacks();
    };

    if (this.props.defer && this.props.defer > 0) {
      setTimeout(init, this.props.defer)
    }
    else {
      init();
    }
  },

  _callQueuedCallbacks: function() {
    var callbacks = this._queuedCallbacks,
        len = callbacks.length, i = 0;

    this._queuedCallbacks = []

    for(i; i < len; i++) {
      callbacks[i](this.getIScroll())
    }
  },
  _teardownIScroll: function() {
    this._iScrollInstance.destroy()
    this._iScrollInstance = undefined
  },

  _bindIScrollEvents: function() {
    // Bind events on iScroll instance
    this._iScrollBindedEvents = {}
    this._updateIScrollEvents({}, this.props)
  },

  // Iterate through available events and update one by one
  _updateIScrollEvents: function(props1, props2) {
    var len = availableEvents.length,
        i = 0,
        evenNames;

    for(i; i < len; i++) {
      eventNames = availableEvents[i]

      this._updateIScrollEvent(eventNames[0],
                               props1[eventNames[1]],
                               props2[eventNames[1]])
    }
  },

  // Unbind and/or Bind event if it was changed during update
  _updateIScrollEvent: function(eventName, prevEvent, currentEvent) {
    var iScrollInstance, currentEvents, callback;

    if(prevEvent !== currentEvent) {
      iScrollInstance = this._iScrollInstance
      currentEvents = this._iScrollBindedEvents

      if(prevEvent) {
        iScrollInstance.off(eventName, currentEvents[eventName])
        currentEvents[eventName] = undefined
      }

      if(currentEvent) {
        callback = function() {currentEvent(iScrollInstance)}

        this._iScrollInstance.on(eventName, callback)
        currentEvents[eventName] = callback
      }
    }
  },

  _triggerRefreshEvent: function() {
    if(this.props.onRefresh) {
      this.props.onRefresh(this._iScrollInstance)
    }
  },

  render: function() {
    return React.createElement("div", {className: this.props.className, style: this.props.style},
             React.createElement("div", {style: this.props.scrollerStyle}, this.props.children)
           )
  }
})

module.exports = ReactIScroll
<|endoftext|>


<commit_before>// @flow
import { dsctypes } from "constants/dsctypes"

const {
  LOGIN_REQUEST,
  LOGIN_SUCCESS,
  LOGIN_FAILURE,
  LOGOUT_REQUEST,
  LOGOUT_SUCCESS,
  FETCH_USER_REQUEST,
  FETCH_USER_SUCCESS,
  FETCH_USER_FAILURE,
  FETCH_ROLE_REQUEST,
  FETCH_ROLE_SUCCESS,
  FETCH_ROLE_FAILURE,
  FETCH_NON_AUTH_ROLE_REQUEST,
  FETCH_NON_AUTH_ROLE_SUCCESS,
  FETCH_NON_AUTH_ROLE_FAILURE,
  FETCH_PERMISSION_REQUEST,
  FETCH_PERMISSION_SUCCESS,
  FETCH_PERMISSION_FAILURE,
} = dsctypes

const authReducer = (state: Object = {}, action: Object) => {
  switch (action.type) {
    case LOGIN_REQUEST:
      return {
        ...state,
        isFetching: true,
        isAuthenticated: false,
        provider: action.payload.provider,
      }
    case LOGIN_SUCCESS:
      return {
        ...state,
        isFetching: false,
        isAuthenticated: action.payload.token ? true : false,
        token: action.payload.token,
        user: action.payload.user,
      }
    case LOGIN_FAILURE:
      return {
        ...state,
        isFetching: false,
        isAuthenticated: false,
        error: action.payload.error,
        provider: null,
      }
    case LOGOUT_REQUEST:
      return {
        ...state,
        isFetching: true,
      }
    case LOGOUT_SUCCESS:
      return {
        ...state,
        isFetching: false,
        isAuthenticated: false,
        provider: null,
        user: null,
        token: null,
      }
    case FETCH_USER_REQUEST:
      return {
        ...state,
        isFetching: true,
      }
    case FETCH_USER_SUCCESS:
      return {
        ...state,
        isFetching: false,
        fetchedUserData: action.payload.json,
      }
    case FETCH_USER_FAILURE:
      return {
        ...state,
        isFetching: false,
        error: action.payload.error,
      }
    case FETCH_ROLE_REQUEST:
      return {
        ...state,
        isFetching: true,
      }
    case FETCH_ROLE_SUCCESS:
      return {
        ...state,
        isFetching: action.payload.isFetching,
        user: {
          ...state.user,
          // merge roles into one array, regardless if they are one or many
          roles: [].concat(action.payload.json.data),
        },
      }
    case FETCH_ROLE_FAILURE:
      return {
        ...state,
        isFetching: false,
        error: action.payload.error,
      }
    case FETCH_NON_AUTH_ROLE_REQUEST:
      return {
        ...state,
        isFetching: true,
      }
    case FETCH_NON_AUTH_ROLE_SUCCESS:
      return {
        ...state,
        isFetching: false,
        fetchedUserData: {
          ...state.fetchedUserData,
          // merge roles into one array, regardless if they are one or many
          roles: [].concat(action.payload.json.data),
        },
      }
    case FETCH_NON_AUTH_ROLE_FAILURE:
      return {
        ...state,
        isFetching: false,
        error: action.payload.error,
      }
    case FETCH_PERMISSION_REQUEST:
      return {
        ...state,
        isFetching: true,
      }
    case FETCH_PERMISSION_SUCCESS:
      return {
        ...state,
        isFetching: false,
        user: {
          ...state.user,
          // merge permissions into one array, regardless if they are one or many
          permissions: [].concat(action.payload.json.data),
        },
      }
    case FETCH_PERMISSION_FAILURE:
      return {
        ...state,
        isFetching: false,
        error: action.payload.error,
      }
    default:
      return state
  }
}
export default authReducer
<commit_msg>fix: remove stale errors on successful login<commit_after>// @flow
import { dsctypes } from "constants/dsctypes"

const {
  LOGIN_REQUEST,
  LOGIN_SUCCESS,
  LOGIN_FAILURE,
  LOGOUT_REQUEST,
  LOGOUT_SUCCESS,
  FETCH_USER_REQUEST,
  FETCH_USER_SUCCESS,
  FETCH_USER_FAILURE,
  FETCH_ROLE_REQUEST,
  FETCH_ROLE_SUCCESS,
  FETCH_ROLE_FAILURE,
  FETCH_NON_AUTH_ROLE_REQUEST,
  FETCH_NON_AUTH_ROLE_SUCCESS,
  FETCH_NON_AUTH_ROLE_FAILURE,
  FETCH_PERMISSION_REQUEST,
  FETCH_PERMISSION_SUCCESS,
  FETCH_PERMISSION_FAILURE,
} = dsctypes

const authReducer = (state: Object = {}, action: Object) => {
  switch (action.type) {
    case LOGIN_REQUEST:
      return {
        ...state,
        isFetching: true,
        isAuthenticated: false,
        provider: action.payload.provider,
      }
    case LOGIN_SUCCESS:
      return {
        ...state,
        isFetching: false,
        isAuthenticated: action.payload.token ? true : false,
        token: action.payload.token,
        user: action.payload.user,
        error: null,
      }
    case LOGIN_FAILURE:
      return {
        ...state,
        isFetching: false,
        isAuthenticated: false,
        error: action.payload.error,
        provider: null,
      }
    case LOGOUT_REQUEST:
      return {
        ...state,
        isFetching: true,
      }
    case LOGOUT_SUCCESS:
      return {
        ...state,
        isFetching: false,
        isAuthenticated: false,
        provider: null,
        user: null,
        token: null,
      }
    case FETCH_USER_REQUEST:
      return {
        ...state,
        isFetching: true,
      }
    case FETCH_USER_SUCCESS:
      return {
        ...state,
        isFetching: false,
        fetchedUserData: action.payload.json,
      }
    case FETCH_USER_FAILURE:
      return {
        ...state,
        isFetching: false,
        error: action.payload.error,
      }
    case FETCH_ROLE_REQUEST:
      return {
        ...state,
        isFetching: true,
      }
    case FETCH_ROLE_SUCCESS:
      return {
        ...state,
        isFetching: action.payload.isFetching,
        user: {
          ...state.user,
          // merge roles into one array, regardless if they are one or many
          roles: [].concat(action.payload.json.data),
        },
      }
    case FETCH_ROLE_FAILURE:
      return {
        ...state,
        isFetching: false,
        error: action.payload.error,
      }
    case FETCH_NON_AUTH_ROLE_REQUEST:
      return {
        ...state,
        isFetching: true,
      }
    case FETCH_NON_AUTH_ROLE_SUCCESS:
      return {
        ...state,
        isFetching: false,
        fetchedUserData: {
          ...state.fetchedUserData,
          // merge roles into one array, regardless if they are one or many
          roles: [].concat(action.payload.json.data),
        },
      }
    case FETCH_NON_AUTH_ROLE_FAILURE:
      return {
        ...state,
        isFetching: false,
        error: action.payload.error,
      }
    case FETCH_PERMISSION_REQUEST:
      return {
        ...state,
        isFetching: true,
      }
    case FETCH_PERMISSION_SUCCESS:
      return {
        ...state,
        isFetching: false,
        user: {
          ...state.user,
          // merge permissions into one array, regardless if they are one or many
          permissions: [].concat(action.payload.json.data),
        },
      }
    case FETCH_PERMISSION_FAILURE:
      return {
        ...state,
        isFetching: false,
        error: action.payload.error,
      }
    default:
      return state
  }
}
export default authReducer
<|endoftext|>


<commit_before>import _curry1 from './internal/_curry1.js';
import curryN from './curryN.js';

/**
 * Returns a curried equivalent of the provided function. The curried function
 * has two unusual capabilities. First, its arguments needn't be provided one
 * at a time. If `f` is a ternary function and `g` is `R.curry(f)`, the
 * following are equivalent:
 *
 *   - `g(1)(2)(3)`
 *   - `g(1)(2, 3)`
 *   - `g(1, 2)(3)`
 *   - `g(1, 2, 3)`
 *
 * Secondly, the special placeholder value [`R.__`](#__) may be used to specify
 * "gaps", allowing partial application of any combination of arguments,
 * regardless of their positions. If `g` is as above and `_` is [`R.__`](#__),
 * the following are equivalent:
 *
 *   - `g(1, 2, 3)`
 *   - `g(_, 2, 3)(1)`
 *   - `g(_, _, 3)(1)(2)`
 *   - `g(_, _, 3)(1, 2)`
 *   - `g(_, 2)(1)(3)`
 *   - `g(_, 2)(1, 3)`
 *   - `g(_, 2)(_, 3)(1)`
 *
 * @func
 * @memberOf R
 * @since v0.1.0
 * @category Function
 * @sig (* -> a) -> (* -> a)
 * @param {Function} fn The function to curry.
 * @return {Function} A new, curried function.
 * @see R.curryN, R.partial
 * @example
 *
 *      const addFourNumbers = (a, b, c, d) => a + b + c + d;
 *
 *      const curriedAddFourNumbers = R.curry(addFourNumbers);
 *      const f = curriedAddFourNumbers(1, 2);
 *      const g = f(3);
 *      g(4); //=> 10
 */
var curry = _curry1(function curry(fn) {
  return curryN(fn.length, fn);
});
export default curry;
<commit_msg>docs: curry: add warning about default parameters. close #3121<commit_after>import _curry1 from './internal/_curry1.js';
import curryN from './curryN.js';

/**
 * Returns a curried equivalent of the provided function. The curried function
 * has two unusual capabilities. First, its arguments needn't be provided one
 * at a time. If `f` is a ternary function and `g` is `R.curry(f)`, the
 * following are equivalent:
 *
 *   - `g(1)(2)(3)`
 *   - `g(1)(2, 3)`
 *   - `g(1, 2)(3)`
 *   - `g(1, 2, 3)`
 *
 * Secondly, the special placeholder value [`R.__`](#__) may be used to specify
 * "gaps", allowing partial application of any combination of arguments,
 * regardless of their positions. If `g` is as above and `_` is [`R.__`](#__),
 * the following are equivalent:
 *
 *   - `g(1, 2, 3)`
 *   - `g(_, 2, 3)(1)`
 *   - `g(_, _, 3)(1)(2)`
 *   - `g(_, _, 3)(1, 2)`
 *   - `g(_, 2)(1)(3)`
 *   - `g(_, 2)(1, 3)`
 *   - `g(_, 2)(_, 3)(1)`
 *
 * Please note that default parameters don't count towards a [function arity](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length)
 * and therefore `curry` won't work well with those:
 *
 * ```
 * const h = R.curry((a, b, c = 2) => a + b + c);
 *
 * h(40);
 * //=> function (waits for `b`)
 *
 * h(39)(1);
 * //=> 42
 *
 * h(1)(2, 3);
 * //=> 6
 *
 * h(1)(2)(7);
 * //=> Error! (`3` is not a function!)
 * ```
 *
 * @func
 * @memberOf R
 * @since v0.1.0
 * @category Function
 * @sig (* -> a) -> (* -> a)
 * @param {Function} fn The function to curry.
 * @return {Function} A new, curried function.
 * @see R.curryN, R.partial
 * @example
 *
 *      const addFourNumbers = (a, b, c, d) => a + b + c + d;
 *
 *      const curriedAddFourNumbers = R.curry(addFourNumbers);
 *      const f = curriedAddFourNumbers(1, 2);
 *      const g = f(3);
 *      g(4); //=> 10
 */
var curry = _curry1(function curry(fn) {
  return curryN(fn.length, fn);
});
export default curry;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var Git = require('../utils/git.js');
var doxygen = require('../utils/doxygen.js');
var ghPages = require('../utils/gh-pages.js');
var sendmail= require('../utils/email.js');
var fs = require("fs-extra");
var async = require('async');

function handlePing(req) {
    winston.info('Ping!');
    winston.info(req.zen);
}

function handleWiki(content) {
    if (!content.pages) {
        return;
    }
    winston.info("Wiki Updated: " + content.repository.full_name);
    var email = {
        to: 'jas138@duke.edu',
        subject: 'Wiki Pages Updated: ' + content.repository.full_name,
        html: '
Wiki Pages Updated
'
    };
    email.html += '
The ' + content.repository.name + ' team has updated their wiki.
';
    email.html += '
The following pages have been changed or created:';
    email.html += '
';

    content.pages.forEach(function(page){
        email.html += '
';
        email.html += '' + page.title +': ' + page.action;
        email.html += '
';
    });

    email.html += '
';
    email.html += '
';
    winston.info('Sending mail.');
    sendmail.sendMail(email);
};

function handlePush(req) {
    if (req.ref != "refs/heads/master") {
        winston.warn("This commit is not for master branch.");
        return;
    }

    winston.profile('Git Push Event');
    winston.info("Head Commit: " + req.head_commit.id);
    winston.info("\tCommit Message: " + req.head_commit.message);
    winston.info("\tAuthor: " + req.head_commit.author.name + "(" + req.head_commit.author.username + ")");

    if (req.head_commit.author.username != 'Tadimsky') {
        //return;
    }

    var git = Git.Git(req.repository);

    git.clone().then(function(repo) {
        async.series([
            function(callback) {
                ghPages.process(repo).then(function() {
                    doxygen.process(git, repo).then(function() {
                        callback(null, 'doxygen');
                    });
                });
            }
        ], function(err, result) {
            winston.info('Completed:')
            winston.info('\t' + result);
            winston.profile('Git Push Event');
        });
    });
}

/* GET users listing. */
router.get('/', function(req, res) {
    res.send('This is a GitHub Hook, what are you doing GETting it? :)');
});

router.post('/webhook', function(req, res) {
    var event_type = req.get('X-GitHub-Event');
    switch (event_type) {
        case 'ping':
            handlePing(req.body);
            break;
        case 'push':
            handlePush(req.body);
            break;
        case 'gollum':
            handleWiki(req.body);
            break;
        default:
            winston.warn("Unknown Event", req.body);
            break;
    }
    res.send('Thanks for the update! <3');
});

router.get('/auth', function(req, res) {

});

module.exports = router;
<commit_msg>email duvall on wiki pages<commit_after>var express = require('express');
var router = express.Router();
var Git = require('../utils/git.js');
var doxygen = require('../utils/doxygen.js');
var ghPages = require('../utils/gh-pages.js');
var sendmail= require('../utils/email.js');
var fs = require("fs-extra");
var async = require('async');

function handlePing(req) {
    winston.info('Ping!');
    winston.info(req.zen);
}

function handleWiki(content) {
    if (!content.pages) {
        return;
    }
    winston.info("Wiki Updated: " + content.repository.full_name);
    var email = {
        to: 'rcd@cs.duke.edu',
        subject: 'Wiki Pages Updated: ' + content.repository.full_name,
        html: '
Wiki Pages Updated
'
    };
    email.html += '
The ' + content.repository.name + ' team has updated their wiki.
';
    email.html += '
The following pages have been changed or created:';
    email.html += '
';

    content.pages.forEach(function(page){
        email.html += '
';
        email.html += '' + page.title +': ' + page.action;
        email.html += '
';
    });

    email.html += '
';
    email.html += '
';
    winston.info('Sending mail.');
    sendmail.sendMail(email);
};

function handlePush(req) {
    if (req.ref != "refs/heads/master") {
        winston.warn("This commit is not for master branch.");
        return;
    }

    winston.profile('Git Push Event');
    winston.info("Head Commit: " + req.head_commit.id);
    winston.info("\tCommit Message: " + req.head_commit.message);
    winston.info("\tAuthor: " + req.head_commit.author.name + "(" + req.head_commit.author.username + ")");

    if (req.head_commit.author.username != 'Tadimsky') {
        //return;
    }

    var git = Git.Git(req.repository);

    git.clone().then(function(repo) {
        async.series([
            function(callback) {
                ghPages.process(repo).then(function() {
                    doxygen.process(git, repo).then(function() {
                        callback(null, 'doxygen');
                    });
                });
            }
        ], function(err, result) {
            winston.info('Completed:')
            winston.info('\t' + result);
            winston.profile('Git Push Event');
        });
    });
}

/* GET users listing. */
router.get('/', function(req, res) {
    res.send('This is a GitHub Hook, what are you doing GETting it? :)');
});

router.post('/webhook', function(req, res) {
    var event_type = req.get('X-GitHub-Event');
    switch (event_type) {
        case 'ping':
            handlePing(req.body);
            break;
        case 'push':
            handlePush(req.body);
            break;
        case 'gollum':
            handleWiki(req.body);
            break;
        default:
            winston.warn("Unknown Event: ", event_type);
            break;
    }
    res.send('Thanks for the update! <3');
});

router.get('/auth', function(req, res) {

});

module.exports = router;
<|endoftext|>


<commit_before>/*
import React from "react";
import {Router, Route} from "react-router";
import MainComponent from "../containers/MainComponent";

var mainroute = (history) => {
	history = history || null;
	return (
			<Router history={history}>
				<Route path="/" component={MainComponent} >
				</Route>
			</Router>
		);
};

export default mainroute;
*/
import React from "react";
import {Route, StaticRouter, BrowserRouter } from 'react-router-dom';
import Main from "../containers/MainComponent";

let serverRoute = (req, context) => {
	return (
		<StaticRouter location={req.url} context={context}>
			<Route path="/*" component={Main} />
		</StaticRouter>
	);
};

let browserRoute = () => {
	return (
		<BrowserRouter>
			<Route path="/*" component={Main} />
		</BrowserRouter>
	);
};
export { serverRoute, browserRoute };
<commit_msg>cleanup<commit_after>import React from "react";
import {Route, StaticRouter, BrowserRouter } from 'react-router-dom';
import Main from "../containers/MainComponent";

let serverRoute = (req, context) => {
	return (
		<StaticRouter location={req.url} context={context}>
			<Route path="/*" component={Main} />
		</StaticRouter>
	);
};

let browserRoute = () => {
	return (
		<BrowserRouter>
			<Route path="/*" component={Main} />
		</BrowserRouter>
	);
};
export { serverRoute, browserRoute };
<|endoftext|>


<commit_before>$( () => {
    let audioContext = new (window.AudioContext || window.webkitAudioContext)();
    let syntho = new Syntho(audioContext);
    let ui = new SynthUI(syntho);
    let kbd = new PhysicalKeyboard;
    let freqMap = new FrequencyMap;

    // connect the physical keyboard to the VCOs
    let keyboardCallback = (message, note) => {
        if (note >= 0) {
            syntho.vco1.frequency.setValueAtTime(freqMap.getFrequency(syntho.vco1.octave, note), audioContext.currentTime)
            syntho.vco2.frequency.setValueAtTime(freqMap.getFrequency(syntho.vco2.octave, note), audioContext.currentTime)
            syntho.vco3.frequency.setValueAtTime(freqMap.getFrequency(syntho.vco3.octave, note), audioContext.currentTime)
        }
    }

    let triggerCallback = (message, value) => {
        syntho.trigger(value)
    }

    PubSub.subscribe('Keyboard', keyboardCallback)
    PubSub.subscribe('Trigger', triggerCallback)

})
<commit_msg>Synth now uses getNoteIndex to get the correct frequencies.<commit_after>$( () => {
    let audioContext = new (window.AudioContext || window.webkitAudioContext)();
    let syntho = new Syntho(audioContext);
    let ui = new SynthUI(syntho);
    let kbd = new PhysicalKeyboard;
    let freqMap = new FrequencyMap;

    // connect the physical keyboard to the VCOs
    let keyboardCallback = (message, note) => {
        if (note >= 0) {
            syntho.vco1.frequency.setValueAtTime(freqMap.getFrequency(freqMap.getNoteIndex(syntho.vco1.octave, note)), audioContext.currentTime)
            syntho.vco2.frequency.setValueAtTime(freqMap.getFrequency(freqMap.getNoteIndex(syntho.vco2.octave, note)), audioContext.currentTime)
            syntho.vco3.frequency.setValueAtTime(freqMap.getFrequency(freqMap.getNoteIndex(syntho.vco3.octave, note)), audioContext.currentTime)
        }
    }

    let triggerCallback = (message, value) => {
        syntho.trigger(value)
    }

    PubSub.subscribe('Keyboard', keyboardCallback)
    PubSub.subscribe('Trigger', triggerCallback)

})
<|endoftext|>


<commit_before>import { renderToString } from "react-dom/server"
import serialize from "serialize-javascript"
import Helmet from "react-helmet"
import { readFileSync } from "fs"

import assets from "./assets"

import { CLIENT_CHUNKHASHES_MANIFESTJSON_FILEPATH } from "./config"

try{
  var ClientChunkManifest = readFileSync(CLIENT_CHUNKHASHES_MANIFESTJSON_FILEPATH, "utf8")
} catch(ex) {
  console.warn("Could not parse chunkhashes from manifest.json: ", ex)
  ClientChunkManifest = "{}"
}

function styleTags(styles) {
  return styles
    .map(style =>
      `<link href="${style}" media="screen, projection" rel="stylesheet" type="text/css" />`
    )
    .join('\n')
}

function scriptTags(scripts) {
  return scripts
    .map(script =>
      `<script type="text/javascript" src="${script}"></script>`
    )
    .join('\n')
}

const styles = styleTags(assets.styles)
const scripts = scriptTags(assets.scripts)

/**
 * Generates a full HTML page containing the render output of the given react
 * element.
 *
 * @param  rootReactElement
 *   [Optional] The root React element to be rendered on the page.
 * @param  initialState
 *   [Optional] The initial state for the redux store which will be used by the
 *   client to mount the redux store into the desired state.
 *
 * @return The full HTML page in the form of a React element.
 */
function render(rootReactElement, initialState) {
  const reactRenderString = rootReactElement
    ? renderToString(rootReactElement)
    : null

  const helmet = rootReactElement
    // We run 'react-helmet' after our renderToString call so that we can fish
    // out all the attributes which need to be attached to our page.
    // React Helmet allows us to control our page header contents via our
    // components.
    // @see https://github.com/nfl/react-helmet
    ? Helmet.rewind()
    // There was no react element, so we just us an empty helmet.
    : null

  return `<!DOCTYPE html>

        <meta charSet='utf-8' />
        <meta httpEquiv='X-UA-Compatible' content='IE=edge' />
        <meta httpEquiv='Content-Language' content='en' />

        ${helmet ? helmet.title.toString() : ''}
        ${helmet ? helmet.meta.toString() : ''}
        ${helmet ? helmet.link.toString() : ''}

        ${styles}
        ${helmet ? helmet.style.toString() : ''}

${reactRenderString || ''}

        ${scripts}
        ${helmet ? helmet.script.toString() : ''}

    `;
}

export default render
<commit_msg>Minor formatting + cleanups<commit_after>import { renderToString } from "react-dom/server"
import serialize from "serialize-javascript"
import Helmet from "react-helmet"
import { readFileSync } from "fs"

import assets from "./assets"

import { CLIENT_CHUNKHASHES_MANIFESTJSON_FILEPATH } from "./config"

try{
  var ClientChunkManifest = readFileSync(CLIENT_CHUNKHASHES_MANIFESTJSON_FILEPATH, "utf8")
} catch(ex) {
  console.warn("Could not parse chunkhashes from manifest.json: ", ex)
  ClientChunkManifest = "{}"
}

function styleTags(styles) {
  return styles
    .map(style =>
      `<link href="${style}" media="screen, projection" rel="stylesheet" />`
    )
    .join('\n')
}

function scriptTags(scripts) {
  return scripts
    .map(script =>
      `<script src="${script}"></script>`
    )
    .join('\n')
}

const styles = styleTags(assets.styles)
const scripts = scriptTags(assets.scripts)

/**
 * Generates a full HTML page containing the render output of the given react
 * element.
 *
 * @param  rootReactElement
 *   [Optional] The root React element to be rendered on the page.
 * @param  initialState
 *   [Optional] The initial state for the redux store which will be used by the
 *   client to mount the redux store into the desired state.
 *
 * @return The full HTML page in the form of a React element.
 */
function render(rootReactElement, initialState) {
  const reactRenderString = rootReactElement
    ? renderToString(rootReactElement)
    : null

  const helmet = rootReactElement
    // We run 'react-helmet' after our renderToString call so that we can fish
    // out all the attributes which need to be attached to our page.
    // React Helmet allows us to control our page header contents via our
    // components.
    // @see https://github.com/nfl/react-helmet
    ? Helmet.rewind()
    // There was no react element, so we just us an empty helmet.
    : null

  return `<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta http-equiv="x-ua-compatible" content="ie=edge" />
        <meta http-equiv="content-language" content="en" />

        ${helmet ? helmet.title.toString() : ''}
        ${helmet ? helmet.meta.toString() : ''}
        ${helmet ? helmet.link.toString() : ''}

        ${styles}
        ${helmet ? helmet.style.toString() : ''}

${reactRenderString || ""}

        ${scripts}
        ${helmet ? helmet.script.toString() : ""}

    `
}

export default render
<|endoftext|>


<commit_before>/* @flow */

import { escape } from 'he'
import { compileToFunctions } from 'web/compiler/index'
import { createComponentInstanceForVnode } from 'core/vdom/create-component'
import { noop } from 'shared/util'

let warned = Object.create(null)
const warnOnce = msg => {
  if (!warned[msg]) {
    warned[msg] = true
    console.warn(`\n\u001b[31m${msg}\u001b[39m\n`)
  }
}

const normalizeAsync = (cache, method) => {
  const fn = cache[method]
  if (!fn) {
    return
  } else if (fn.length > 1) {
    return (key, cb) => fn.call(cache, key, cb)
  } else {
    return (key, cb) => cb(fn.call(cache, key))
  }
}

const compilationCache = Object.create(null)
const normalizeRender = vm => {
  const { render, template } = vm.$options
  if (!render) {
    if (template) {
      const renderFns = (
        compilationCache[template] ||
        (compilationCache[template] = compileToFunctions(template))
      )
      Object.assign(vm.$options, renderFns)
    } else {
      throw new Error(
        `render function or template not defined in component: ${
          vm.$options.name || vm.$options._componentTag || 'anonymous'
        }`
      )
    }
  }
}

function renderNode (node, isRoot, context) {
  const { write, next } = context
  if (node.componentOptions) {
    // check cache hit
    const Ctor = node.componentOptions.Ctor
    const getKey = Ctor.options.serverCacheKey
    const name = Ctor.options.name
    const cache = context.cache
    if (getKey && cache && name) {
      const key = name + '::' + getKey(node.componentOptions.propsData)
      const { has, get } = context
      if (has) {
        has(key, hit => {
          if (hit && get) {
            get(key, res => write(res, next))
          } else {
            renderComponentWithCache(node, isRoot, key, context)
          }
        })
      } else if (get) {
        get(key, res => {
          if (res) {
            write(res, next)
          } else {
            renderComponentWithCache(node, isRoot, key, context)
          }
        })
      }
    } else {
      if (getKey && !cache) {
        warnOnce(
          `[vue-server-renderer] Component ${
            Ctor.options.name || '(anonymous)'
          } implemented serverCacheKey, ` +
          'but no cache was provided to the renderer.'
        )
      }
      if (getKey && !name) {
        warnOnce(
          `[vue-server-renderer] Components that implement "serverCacheKey" ` +
          `must also define a unique "name" option.`
        )
      }
      renderComponent(node, isRoot, context)
    }
  } else {
    if (node.tag) {
      renderElement(node, isRoot, context)
    } else if (node.isComment) {
      write(`<!--${node.text}-->`, next)
    } else {
      write(node.raw ? node.text : escape(String(node.text)), next)
    }
  }
}

function renderComponent (node, isRoot, context) {
  const prevActive = context.activeInstance
  const child = context.activeInstance = createComponentInstanceForVnode(node, context.activeInstance)
  normalizeRender(child)
  const childNode = child._render()
  childNode.parent = node
  context.renderStates.push({
    type: 'Component',
    prevActive
  })
  renderNode(childNode, isRoot, context)
}

function renderComponentWithCache (node, isRoot, key, context) {
  const write = context.write
  write.caching = true
  const buffer = write.cacheBuffer
  const bufferIndex = buffer.push('') - 1
  context.renderStates.push({
    type: 'ComponentWithCache',
    buffer, bufferIndex, key
  })
  renderComponent(node, isRoot, context)
}

function renderElement (el, isRoot, context) {
  if (isRoot) {
    if (!el.data) el.data = {}
    if (!el.data.attrs) el.data.attrs = {}
    el.data.attrs['server-rendered'] = 'true'
  }
  const startTag = renderStartingTag(el, context)
  const endTag = `</${el.tag}>`
  const { write, next } = context
  if (context.isUnaryTag(el.tag)) {
    write(startTag, next)
  } else if (!el.children || !el.children.length) {
    write(startTag + endTag, next)
  } else {
    const children: Array<VNode> = el.children
    context.renderStates.push({
      type: 'Element',
      rendered: 0,
      total: children.length,
      endTag, children
    })
    write(startTag, next)
  }
}

function hasAncestorData (node: VNode) {
  const parentNode = node.parent
  return parentNode && (parentNode.data || hasAncestorData(parentNode))
}

function renderStartingTag (node: VNode, context) {
  let markup = `<${node.tag}`
  const { directives, modules } = context

  // construct synthetic data for module processing
  // because modules like style also produce code by parent VNode data
  if (!node.data && hasAncestorData(node)) {
    node.data = {}
  }
  if (node.data) {
    // check directives
    const dirs = node.data.directives
    if (dirs) {
      for (let i = 0; i < dirs.length; i++) {
        const dirRenderer = directives[dirs[i].name]
        if (dirRenderer) {
          // directives mutate the node's data
          // which then gets rendered by modules
          dirRenderer(node, dirs[i])
        }
      }
    }
    // apply other modules
    for (let i = 0; i < modules.length; i++) {
      const res = modules[i](node)
      if (res) {
        markup += res
      }
    }
  }
  // attach scoped CSS ID
  let scopeId
  const activeInstance = context.activeInstance
  if (activeInstance &&
      activeInstance !== node.context &&
      (scopeId = activeInstance.$options._scopeId)) {
    markup += ` ${scopeId}`
  }
  while (node) {
    if ((scopeId = node.context.$options._scopeId)) {
      markup += ` ${scopeId}`
    }
    node = node.parent
  }
  return markup + '>'
}

const nextFactory = context => function next () {
  const lastState = context.renderStates.pop()
  if (!lastState) {
    context.done()
    // cleanup context, avoid leakage
    context = (null: any)
    return
  }
  switch (lastState.type) {
    case 'Component':
      context.activeInstance = lastState.prevActive
      next()
      break
    case 'Element':
      const { children, total } = lastState
      const rendered = lastState.rendered++
      if (rendered < total) {
        context.renderStates.push(lastState)
        renderNode(children[rendered], false, context)
      } else {
        context.write(lastState.endTag, next)
      }
      break
    case 'ComponentWithCache':
      const { buffer, bufferIndex, key } = lastState
      const result = buffer[bufferIndex]
      context.cache.set(key, result)
      if (bufferIndex === 0) {
        // this is a top-level cached component,
        // exit caching mode.
        context.write.caching = false
      } else {
        // parent component is also being cached,
        // merge self into parent's result
        buffer[bufferIndex - 1] += result
      }
      buffer.length = bufferIndex
      next()
      break
  }
}

export function createRenderFunction (
  modules: Array<Function>,
  directives: Object,
  isUnaryTag: Function,
  cache: any
) {
  if (cache && (!cache.get || !cache.set)) {
    throw new Error('renderer cache must implement at least get & set.')
  }

  const get = cache && normalizeAsync(cache, 'get')
  const has = cache && normalizeAsync(cache, 'has')

  return function render (
    component: Component,
    write: (text: string, next: Function) => void,
    done: Function
  ) {
    checkBuild(component)
    warned = Object.create(null)
    const context = {
      activeInstance: component,
      renderStates: [],
      next: noop, // for flow
      write, done,
      isUnaryTag, modules, directives,
      cache, get, has
    }
    context.next = nextFactory(context)
    normalizeRender(component)
    renderNode(component._render(), true, context)
  }
}

function checkBuild (component) {
  let Vue = component.constructor
  while (Vue.super) {
    Vue = Vue.super
  }
  if (Vue.compile) {
    console.error(
      red(`\n[vue-server-renderer] You are using the standalone build (vue/dist/vue.js) for ` +
      `server-side rendering. It is recommended to use the CommonJS build ` +
      `(vue/dist/vue.common.js) instead so that the code can run in ` +
      `production mode by setting NODE_ENV=production. The server renderer ` +
      `supports the template option regardless of what build you are using.\n`)
    )
  }
}

function red (str) {
  return '\u001B[1m\u001B[31m' + str + '\u001B[39m\u001B[22m'
}
<commit_msg>avoid ssr build warning when using minified build<commit_after>/* @flow */

import { escape } from 'he'
import { compileToFunctions } from 'web/compiler/index'
import { createComponentInstanceForVnode } from 'core/vdom/create-component'
import { noop } from 'shared/util'

let warned = Object.create(null)
const warnOnce = msg => {
  if (!warned[msg]) {
    warned[msg] = true
    console.warn(`\n\u001b[31m${msg}\u001b[39m\n`)
  }
}

const normalizeAsync = (cache, method) => {
  const fn = cache[method]
  if (!fn) {
    return
  } else if (fn.length > 1) {
    return (key, cb) => fn.call(cache, key, cb)
  } else {
    return (key, cb) => cb(fn.call(cache, key))
  }
}

const compilationCache = Object.create(null)
const normalizeRender = vm => {
  const { render, template } = vm.$options
  if (!render) {
    if (template) {
      const renderFns = (
        compilationCache[template] ||
        (compilationCache[template] = compileToFunctions(template))
      )
      Object.assign(vm.$options, renderFns)
    } else {
      throw new Error(
        `render function or template not defined in component: ${
          vm.$options.name || vm.$options._componentTag || 'anonymous'
        }`
      )
    }
  }
}

function renderNode (node, isRoot, context) {
  const { write, next } = context
  if (node.componentOptions) {
    // check cache hit
    const Ctor = node.componentOptions.Ctor
    const getKey = Ctor.options.serverCacheKey
    const name = Ctor.options.name
    const cache = context.cache
    if (getKey && cache && name) {
      const key = name + '::' + getKey(node.componentOptions.propsData)
      const { has, get } = context
      if (has) {
        has(key, hit => {
          if (hit && get) {
            get(key, res => write(res, next))
          } else {
            renderComponentWithCache(node, isRoot, key, context)
          }
        })
      } else if (get) {
        get(key, res => {
          if (res) {
            write(res, next)
          } else {
            renderComponentWithCache(node, isRoot, key, context)
          }
        })
      }
    } else {
      if (getKey && !cache) {
        warnOnce(
          `[vue-server-renderer] Component ${
            Ctor.options.name || '(anonymous)'
          } implemented serverCacheKey, ` +
          'but no cache was provided to the renderer.'
        )
      }
      if (getKey && !name) {
        warnOnce(
          `[vue-server-renderer] Components that implement "serverCacheKey" ` +
          `must also define a unique "name" option.`
        )
      }
      renderComponent(node, isRoot, context)
    }
  } else {
    if (node.tag) {
      renderElement(node, isRoot, context)
    } else if (node.isComment) {
      write(`<!--${node.text}-->`, next)
    } else {
      write(node.raw ? node.text : escape(String(node.text)), next)
    }
  }
}

function renderComponent (node, isRoot, context) {
  const prevActive = context.activeInstance
  const child = context.activeInstance = createComponentInstanceForVnode(node, context.activeInstance)
  normalizeRender(child)
  const childNode = child._render()
  childNode.parent = node
  context.renderStates.push({
    type: 'Component',
    prevActive
  })
  renderNode(childNode, isRoot, context)
}

function renderComponentWithCache (node, isRoot, key, context) {
  const write = context.write
  write.caching = true
  const buffer = write.cacheBuffer
  const bufferIndex = buffer.push('') - 1
  context.renderStates.push({
    type: 'ComponentWithCache',
    buffer, bufferIndex, key
  })
  renderComponent(node, isRoot, context)
}

function renderElement (el, isRoot, context) {
  if (isRoot) {
    if (!el.data) el.data = {}
    if (!el.data.attrs) el.data.attrs = {}
    el.data.attrs['server-rendered'] = 'true'
  }
  const startTag = renderStartingTag(el, context)
  const endTag = `</${el.tag}>`
  const { write, next } = context
  if (context.isUnaryTag(el.tag)) {
    write(startTag, next)
  } else if (!el.children || !el.children.length) {
    write(startTag + endTag, next)
  } else {
    const children: Array<VNode> = el.children
    context.renderStates.push({
      type: 'Element',
      rendered: 0,
      total: children.length,
      endTag, children
    })
    write(startTag, next)
  }
}

function hasAncestorData (node: VNode) {
  const parentNode = node.parent
  return parentNode && (parentNode.data || hasAncestorData(parentNode))
}

function renderStartingTag (node: VNode, context) {
  let markup = `<${node.tag}`
  const { directives, modules } = context

  // construct synthetic data for module processing
  // because modules like style also produce code by parent VNode data
  if (!node.data && hasAncestorData(node)) {
    node.data = {}
  }
  if (node.data) {
    // check directives
    const dirs = node.data.directives
    if (dirs) {
      for (let i = 0; i < dirs.length; i++) {
        const dirRenderer = directives[dirs[i].name]
        if (dirRenderer) {
          // directives mutate the node's data
          // which then gets rendered by modules
          dirRenderer(node, dirs[i])
        }
      }
    }
    // apply other modules
    for (let i = 0; i < modules.length; i++) {
      const res = modules[i](node)
      if (res) {
        markup += res
      }
    }
  }
  // attach scoped CSS ID
  let scopeId
  const activeInstance = context.activeInstance
  if (activeInstance &&
      activeInstance !== node.context &&
      (scopeId = activeInstance.$options._scopeId)) {
    markup += ` ${scopeId}`
  }
  while (node) {
    if ((scopeId = node.context.$options._scopeId)) {
      markup += ` ${scopeId}`
    }
    node = node.parent
  }
  return markup + '>'
}

const nextFactory = context => function next () {
  const lastState = context.renderStates.pop()
  if (!lastState) {
    context.done()
    // cleanup context, avoid leakage
    context = (null: any)
    return
  }
  switch (lastState.type) {
    case 'Component':
      context.activeInstance = lastState.prevActive
      next()
      break
    case 'Element':
      const { children, total } = lastState
      const rendered = lastState.rendered++
      if (rendered < total) {
        context.renderStates.push(lastState)
        renderNode(children[rendered], false, context)
      } else {
        context.write(lastState.endTag, next)
      }
      break
    case 'ComponentWithCache':
      const { buffer, bufferIndex, key } = lastState
      const result = buffer[bufferIndex]
      context.cache.set(key, result)
      if (bufferIndex === 0) {
        // this is a top-level cached component,
        // exit caching mode.
        context.write.caching = false
      } else {
        // parent component is also being cached,
        // merge self into parent's result
        buffer[bufferIndex - 1] += result
      }
      buffer.length = bufferIndex
      next()
      break
  }
}

export function createRenderFunction (
  modules: Array<Function>,
  directives: Object,
  isUnaryTag: Function,
  cache: any
) {
  if (cache && (!cache.get || !cache.set)) {
    throw new Error('renderer cache must implement at least get & set.')
  }

  const get = cache && normalizeAsync(cache, 'get')
  const has = cache && normalizeAsync(cache, 'has')

  return function render (
    component: Component,
    write: (text: string, next: Function) => void,
    done: Function
  ) {
    checkBuild(component)
    warned = Object.create(null)
    const context = {
      activeInstance: component,
      renderStates: [],
      next: noop, // for flow
      write, done,
      isUnaryTag, modules, directives,
      cache, get, has
    }
    context.next = nextFactory(context)
    normalizeRender(component)
    renderNode(component._render(), true, context)
  }
}

function checkBuild (component) {
  let Vue: any = component.constructor
  while (Vue.super) {
    Vue = Vue.super
  }
  if (Vue.compile && Vue.config.devtools !== false) {
    console.error(
      red(`\n[vue-server-renderer] You are using the standalone build (vue/dist/vue.js) for ` +
      `server-side rendering. It is recommended to use the CommonJS build ` +
      `(vue/dist/vue.common.js) instead so that the code can run in ` +
      `production mode by setting NODE_ENV=production. The server renderer ` +
      `supports the template option regardless of what build you are using.\n`)
    )
  }
}

function red (str) {
  return '\u001B[1m\u001B[31m' + str + '\u001B[39m\u001B[22m'
}
<|endoftext|>


<commit_before>"use strict";

var process = require('process')
  , http = require('http')
  , _ = require('underscore')
  , request = require('request')
  , cookie = require('cookie')
  , React = require('react')
  , Immutable = require('immutable')
  , Router = require('../router')
  , jed = require('./jed')
  , router = new Router()

const API_URL = process.env.EDITORSNOTES_API_URL || 'http://localhost:8001'
    , SERVER_PORT = process.env.EDITORSNOTES_CLIENT_PORT || 8450

const FETCH_ERROR = '__error__'
    , USER_DATA = '__AUTHENTICATED_USER__'

function getSessionID(req) {
  return cookie.parse(req.headers.cookie || '').sessionid;
}

// fetchFn should __never__ return anything except 200. Anything else is an error.
const fetchFn = function (req, pathname, headers={}) {
  var sessionID = getSessionID(req)
    , url

  if (pathname[0] !== '/') throw Error('Can only fetch data relative to local API.');

  url = API_URL + pathname;

  if (sessionID) {
    headers.cookie = cookie.serialize('sessionid', sessionID);
  }

  headers.Host = req.headers.host;

  return new Promise((resolve, reject) => {
    request.get({ url, headers }, function (error, response, body) {
      if (error) {
        reject(error);
      } else if (response.statusCode === 200) {
        resolve(body);
      } else {
        let msg

        msg = 'Request resulted in non-200 status code\n. Request content:';
        msg += JSON.stringify(response, true, ' ');

        logError(msg);

        resolve(JSON.stringify({
          [FETCH_ERROR]: {
            statusCode: response.statusCode,
            message: JSON.parse(body).detail
          }
        }));
      }
    });
  });
}

function makeHTML(body, bootstrap) {
  var bootstrapScript = !bootstrap ? '' : `

  `
  return `<!doctype html>

    <title>Editors' Notes</title>
    <meta charset="utf-8"/>
    <link rel="stylesheet" href="/static/style.css" />
    <link rel="stylesheet" href="/static/codemirror.css" />

${body}

    ${bootstrapScript}

`
}

//router.add(require('../admin_views/routes'))
router.add(require('../base_routes'))
router.add(require('../admin_routes'))

function render(props, bootstrap) {
  var Application = require('../components/application')
    , application = React.createElement(Application, props)
    , html = makeHTML(React.renderToString(application), bootstrap)

  return html;
}

function logError(err) {
  process.stderr.write('ERROR\n==========\n');
  process.stderr.write((err.stack || err) + '\n');
  process.stderr.write('=========\n\n');

}

function getUserData(req) {
  var sessionID = getSessionID(req)

  if (!sessionID) return Promise.resolve(null);

  return new Promise((resolve, reject) => {
    var url = API_URL + '/me'
      , headers = {}

    headers.cookie = cookie.serialize('sessionid', sessionID);
    headers.Accept = 'application/json';
    headers.Host = req.headers.host;

    request.get({ url, headers }, function (err, response, body) {
      // TODO: Maybe, if status code is 403, invalidate the sessionid cookie?
      if (err) {
        reject(err);
        return;
      }

      if (response.statusCode === 200) {
        resolve(JSON.parse(body));
      }

      resolve(null);
    });
  })
}

// Render view template, unless there is no template, in which case just
// render a blank page.
//
// FIXME: needs to be able to be cached better- maybe use
// React.renderToStaticMarkup if user is not logged in
router.fallbackHandler = function () {
  return function (config, params, queryParams) {
    var promise = Promise.resolve({})
      , bootstrap

    if (config.getData) {
      promise = promise
        .then(() => config.getData(
          fetchFn.bind(null, this.req),
          this.req.url,
          params,
          queryParams))
    }

    promise = promise
      .then(data => getUserData(this.req).then(userData => {
        if (userData) data[USER_DATA] = userData;

        return data;
      }))
      .then(data => (bootstrap = data))
      .then(data => {
        var immutableData = {};

        Object.keys(data).forEach(key => {
          immutableData[key] = Immutable.fromJS(data[key]);
        });

        return immutableData;
      })
      .then(props => {
        var hadError = props.data && props.data.has(FETCH_ERROR)
          , component = hadError ? require('../components/error.jsx') : config.Component

        return _.extend(props, {
          ActiveComponent: component,
          i18n: jed
        })
      })
      .then(props => render(props, bootstrap))
      .then(html => {
        this.res.writeHead(200, { 'Content-Type': 'text/html' });
        this.res.end(html);
      });

    promise.catch(err => {
      let msg = '
Server error
';

      // FIXME Actually render within the framework of the site
      logError(err);

      this.res.writeHead(500);
      this.res.end(makeHTML(msg));
    });
  }
}

module.exports = {
  serve: function () {
    var server = http.createServer(function (req, res) {
      router.dispatch(req, res, function (err) {
        if (err) {

          getUserData(req)
            .then(userData => {
              var props = {}
                , data = {}

              if (userData) data[USER_DATA] = props[USER_DATA] = Immutable.fromJS(userData);
              props.ActiveComponent = require('../components/not_found.jsx');

              res.writeHead(404, { 'Content-Type': 'text/html' });

              res.end(render(props, data));
            })
            .catch(err => {
              let msg = '
Server error
';

              logError(err);

              res.writeHead(500);
              res.end(makeHTML(msg));
            })
        }
      });
    });

    server.listen(SERVER_PORT);
    return server;
  }
}
<commit_msg>Fix url to fetch information about logged in user<commit_after>"use strict";

var process = require('process')
  , http = require('http')
  , _ = require('underscore')
  , request = require('request')
  , cookie = require('cookie')
  , React = require('react')
  , Immutable = require('immutable')
  , Router = require('../router')
  , jed = require('./jed')
  , router = new Router()

const API_URL = process.env.EDITORSNOTES_API_URL || 'http://localhost:8001'
    , SERVER_PORT = process.env.EDITORSNOTES_CLIENT_PORT || 8450

const FETCH_ERROR = '__error__'
    , USER_DATA = '__AUTHENTICATED_USER__'

function getSessionID(req) {
  return cookie.parse(req.headers.cookie || '').sessionid;
}

// fetchFn should __never__ return anything except 200. Anything else is an error.
const fetchFn = function (req, pathname, headers={}) {
  var sessionID = getSessionID(req)
    , url

  if (pathname[0] !== '/') throw Error('Can only fetch data relative to local API.');

  url = API_URL + pathname;

  if (sessionID) {
    headers.cookie = cookie.serialize('sessionid', sessionID);
  }

  headers.Host = req.headers.host;

  return new Promise((resolve, reject) => {
    request.get({ url, headers }, function (error, response, body) {
      if (error) {
        reject(error);
      } else if (response.statusCode === 200) {
        resolve(body);
      } else {
        let msg

        msg = 'Request resulted in non-200 status code\n. Request content:';
        msg += JSON.stringify(response, true, ' ');

        logError(msg);

        resolve(JSON.stringify({
          [FETCH_ERROR]: {
            statusCode: response.statusCode,
            message: JSON.parse(body).detail
          }
        }));
      }
    });
  });
}

function makeHTML(body, bootstrap) {
  var bootstrapScript = !bootstrap ? '' : `

  `
  return `<!doctype html>

    <title>Editors' Notes</title>
    <meta charset="utf-8"/>
    <link rel="stylesheet" href="/static/style.css" />
    <link rel="stylesheet" href="/static/codemirror.css" />

${body}

    ${bootstrapScript}

`
}

//router.add(require('../admin_views/routes'))
router.add(require('../base_routes'))
router.add(require('../admin_routes'))

function render(props, bootstrap) {
  var Application = require('../components/application')
    , application = React.createElement(Application, props)
    , html = makeHTML(React.renderToString(application), bootstrap)

  return html;
}

function logError(err) {
  process.stderr.write('ERROR\n==========\n');
  process.stderr.write((err.stack || err) + '\n');
  process.stderr.write('=========\n\n');

}

function getUserData(req) {
  var sessionID = getSessionID(req)

  if (!sessionID) return Promise.resolve(null);

  return new Promise((resolve, reject) => {
    var url = API_URL + '/me/'
      , headers = {}

    headers.cookie = cookie.serialize('sessionid', sessionID);
    headers.Accept = 'application/json';
    headers.Host = req.headers.host;

    request.get({ url, headers }, function (err, response, body) {
      // TODO: Maybe, if status code is 403, invalidate the sessionid cookie?
      if (err) {
        reject(err);
        return;
      }

      if (response.statusCode === 200) {
        resolve(JSON.parse(body));
      }

      resolve(null);
    });
  })
}

// Render view template, unless there is no template, in which case just
// render a blank page.
//
// FIXME: needs to be able to be cached better- maybe use
// React.renderToStaticMarkup if user is not logged in
router.fallbackHandler = function () {
  return function (config, params, queryParams) {
    var promise = Promise.resolve({})
      , bootstrap

    if (config.getData) {
      promise = promise
        .then(() => config.getData(
          fetchFn.bind(null, this.req),
          this.req.url,
          params,
          queryParams))
    }

    promise = promise
      .then(data => getUserData(this.req).then(userData => {
        if (userData) data[USER_DATA] = userData;

        return data;
      }))
      .then(data => (bootstrap = data))
      .then(data => {
        var immutableData = {};

        Object.keys(data).forEach(key => {
          immutableData[key] = Immutable.fromJS(data[key]);
        });

        return immutableData;
      })
      .then(props => {
        var hadError = props.data && props.data.has(FETCH_ERROR)
          , component = hadError ? require('../components/error.jsx') : config.Component

        return _.extend(props, {
          ActiveComponent: component,
          i18n: jed
        })
      })
      .then(props => render(props, bootstrap))
      .then(html => {
        this.res.writeHead(200, { 'Content-Type': 'text/html' });
        this.res.end(html);
      });

    promise.catch(err => {
      let msg = '
Server error
';

      // FIXME Actually render within the framework of the site
      logError(err);

      this.res.writeHead(500);
      this.res.end(makeHTML(msg));
    });
  }
}

module.exports = {
  serve: function () {
    var server = http.createServer(function (req, res) {
      router.dispatch(req, res, function (err) {
        if (err) {

          getUserData(req)
            .then(userData => {
              var props = {}
                , data = {}

              if (userData) data[USER_DATA] = props[USER_DATA] = Immutable.fromJS(userData);
              props.ActiveComponent = require('../components/not_found.jsx');

              res.writeHead(404, { 'Content-Type': 'text/html' });

              res.end(render(props, data));
            })
            .catch(err => {
              let msg = '
Server error
';

              logError(err);

              res.writeHead(500);
              res.end(makeHTML(msg));
            })
        }
      });
    });

    server.listen(SERVER_PORT);
    return server;
  }
}
<|endoftext|>


<commit_before>/* eslint global-require:"off", no-console:"off" */
import express from 'express';

import middleware from './middleware';
import handleGlobalException from './global-exception-handler';
import registerHttp from './register-listener-http';
import registerHttps from './register-listener-https';

// main process
export default async function main() {
  try {
    process.on('uncaughtException', handleGlobalException);

    // new express app
    const app = express();

    // configure via middleware
    await middleware(app);

    // add listeners
    await Promise.all([
      registerHttp(app),
      registerHttps(app),
    ]);
  } catch (error) {
    handleGlobalException(error);
  }
}
<commit_msg>ctrl-c handling<commit_after>/* eslint global-require:"off", no-console:"off" */
import express from 'express';

import middleware from './middleware';
import handleGlobalException from './global-exception-handler';
import registerHttp from './register-listener-http';
import registerHttps from './register-listener-https';

// main process
export default async function main() {
  try {
    process.on('uncaughtException', handleGlobalException);
    process.on('SIGINT', () => {
      console.log('Shutting down.');
      setTimeout(() => process.exit(), 10);
    });

    // new express app
    const app = express();

    // configure via middleware
    await middleware(app);

    // add listeners
    await Promise.all([
      registerHttp(app),
      registerHttps(app),
    ]);
  } catch (error) {
    handleGlobalException(error);
  }
}
<|endoftext|>


<commit_before>var ws = new WebSocket('ws://sns-beanstalk-chat.elasticbeanstalk.com/topic/events');

ws.onerror = function(e) {
    console.log(e)
    disable_form();
}

ws.onmessage = function(m) {
    var elem = document.getElementById('messages');
    var msg = document.createElement('li');
    msg.setAttribute('class', 'message');
    msg.appendChild(document.createTextNode(m.data));
    if(elem.childNodes.length == 4) {
        elem.removeChild(elem.lastChild);
    }
    if(elem.firstChild) {
        elem.insertBefore(msg, elem.firstChild);
    } else {
        elem.appendChild(msg);
    }
}

ws.onopen = function(e) {
    setInterval(
        function() {
            console.log('Heartbeat!');
            ws.send(JSON.stringify(["heartbeat"]));
        }, 30 * 1000);
    enable_form();
}

function disable_form() {
    document.getElementById('form').style.opacity = 0.5;
}

function enable_form() {
    document.getElementById('form').style.opacity = 1;
}

function send() {
    var elem = document.getElementById('text');
    var msg = elem.value;
    if(0 < msg.length) {
        ws.send(JSON.stringify(["message", msg]));
    }
    elem.value = '';
    elem.focus();
}
<commit_msg>Update url to wss<commit_after>var ws = new WebSocket('wss://sns-beanstalk-chat.nervous.io/topic/events');

ws.onerror = function(e) {
    console.log(e)
    disable_form();
}

ws.onmessage = function(m) {
    var elem = document.getElementById('messages');
    var msg = document.createElement('li');
    msg.setAttribute('class', 'message');
    msg.appendChild(document.createTextNode(m.data));
    if(elem.childNodes.length == 4) {
        elem.removeChild(elem.lastChild);
    }
    if(elem.firstChild) {
        elem.insertBefore(msg, elem.firstChild);
    } else {
        elem.appendChild(msg);
    }
}

ws.onopen = function(e) {
    setInterval(
        function() {
            ws.send(JSON.stringify(["heartbeat"]));
        }, 30 * 1000);
    enable_form();
}

function disable_form() {
    document.getElementById('form').style.opacity = 0.5;
}

function enable_form() {
    document.getElementById('form').style.opacity = 1;
}

function send() {
    var elem = document.getElementById('text');
    var msg = elem.value;
    if(0 < msg.length) {
        ws.send(JSON.stringify(["message", msg]));
    }
    elem.value = '';
    elem.focus();
}
<|endoftext|>


<commit_before>var registrationPromise = navigator.serviceWorker.register('service-worker.js');

function register() {
  registrationPromise.then(function(registration) {
    return registration.pushManager.getSubscription().then(function(subscription) {
      if (subscription) {
        return subscription;
      }

      return registration.pushManager.subscribe({ userVisibleOnly: true }).then(function(newSubscription) {
        return newSubscription;
      });
    });
  }).then(function(subscription) {
    var key = subscription.getKey ? subscription.getKey('p256dh') : '';

    fetch('./register', {
      method: 'post',
      headers: {
        'Content-type': 'application/json'
      },
      body: JSON.stringify({
        endpoint: subscription.endpoint,
        key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key))) : '',
      }),
    }).then(function(response) {
      response.text().then(function(token) {
        document.getElementById('token').textContent = 'Your token is: ' + token;
      });
    });
  });
}

document.getElementById('register').onclick = register;
<commit_msg>Store token in localStorage<commit_after>var registrationPromise = navigator.serviceWorker.register('service-worker.js');

function register() {
  if (localStorage.getItem('token')) {
    return;
  }

  registrationPromise.then(function(registration) {
    return registration.pushManager.getSubscription().then(function(subscription) {
      if (subscription) {
        return subscription;
      }

      return registration.pushManager.subscribe({ userVisibleOnly: true }).then(function(newSubscription) {
        return newSubscription;
      });
    });
  }).then(function(subscription) {
    var key = subscription.getKey ? subscription.getKey('p256dh') : '';

    fetch('./register', {
      method: 'post',
      headers: {
        'Content-type': 'application/json'
      },
      body: JSON.stringify({
        endpoint: subscription.endpoint,
        key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key))) : '',
      }),
    }).then(function(response) {
      response.text().then(function(token) {
        localStorage.setItem('token', token);
        document.getElementById('token').textContent = 'Your token is: ' + token;
      });
    });
  });
}

document.getElementById('register').onclick = register;
<|endoftext|>


<commit_before>seajs.config({
    alias: {
        '$': 'jquery/1.7.2/jquery'
    }
});

seajs.use(['$', 'popup/0.9.7/popup'], function($, Popup) {

    $.get('http://aralejs.org/-update/package.json?callback=?', function(data) {
        for(var i=0; i<data.length; i++) {
            var item = $('');
            item.html(data[i].name)
                .attr('href', '/' + data[i].name + '/')
                .data('description', data[i].description)
                .data('version', data[i].version);

            $('.modules-' + data[i]['tag']).append(item);
            cardPopup(item);
        }
    }, 'jsonp');

    $('#search').on('keyup', function(e) {
        if (e.keyCode === 13) {
            location.href = $('.module:visible').attr('href');
        }
        var that = this;
        $('.module').each(function(i, item) {
            item = $(item);
            if (item.html().indexOf(that.value) !== -1) {
                item.show();
            } else {
                item.hide();
            }
        });
    });

    function cardPopup(item) {
        // 卡片
        var popup = new Popup({
            element: '#card',
            trigger: item
        });
        popup.on('after:show', function() {
            $('#card .card-name').html(item.html());
            $('#card .card-description').html(item.data('description') || '');
            $('#card .card-version').html(item.data('version') || '');
        });
    }

});
<commit_msg>style<commit_after>seajs.config({
    alias: {
        '$': 'jquery/1.7.2/jquery'
    }
});

seajs.use(['$', 'popup/0.9.7/popup'], function($, Popup) {

    $.get('http://aralejs.org/-update/package.json?callback=?', function(data) {
        for(var i=0; i<data.length; i++) {
            var item = $('');
            item.html(data[i].name)
                .attr('href', '/' + data[i].name + '/')
                .data('description', data[i].description)
                .data('version', data[i].version);

            $('.modules-' + data[i]['tag']).append(item);
            cardPopup(item);
        }
    }, 'jsonp');

    $('#search').on('keyup', function(e) {
        if (e.keyCode === 13 && $('.module:visible').attr('href')) {
            window.open($('.module:visible').attr('href'));
        }
        var that = this;
        $('.module').each(function(i, item) {
            item = $(item);
            if (item.html().indexOf(that.value) !== -1) {
                item.show();
            } else {
                item.hide();
            }
        });
    });

    function cardPopup(item) {
        // 卡片
        var popup = new Popup({
            element: '#card',
            trigger: item
        });
        popup.on('after:show', function() {
            $('#card .card-name').html(item.html());
            $('#card .card-description').html(item.data('description') || '');
            $('#card .card-version').html(item.data('version') || '');
        });
    }

});
<|endoftext|>


<commit_before>'use strict';

if (! ('serviceWorker' in navigator)) {
  let fatal = 'WTF is this browser? no service worker API found';
  alert(fatal);
  throw new Error(fatal); // stop this file's execution
}

let parseFromSwBlob = function(eventData) {
  if (!(eventData && eventData.length && eventData[0] == '{')) {
    return false;
  }

  let mesg = JSON.parse(eventData);
  return Boolean(mesg && mesg.cmd && mesg.cmd.length) ? mesg : false;
}

navigator.serviceWorker.addEventListener('message', event => {
  let msg = parseFromSwBlob(event.data);
  if (!msg) {
    console.warn(
        'got message from service worker with no preparation for. event.data:\n%s\n\n',
        event.data);
    return;
  }
  switch (msg.cmd) {
    case 'INSTALL_URL':
      let urls;
      let urlBlob = localStorage.getItem('URLS');
      if (!urlBlob || !urlBlob.length || !(urls = JSON.parse(urlBlob))) {
        urls = {};
      }
      urls[msg.payload.url] = msg.payload.resp;
      localStorage.setItem('URLS', JSON.stringify(urls));
      break;
    case 'PRIMER_STATUS':
      localStorage.setItem('STATUS', msg.payload);
    default:
      console.error('Unknown service worker command, "%s"', msg.cmd);
      break;
  }
});

navigator.serviceWorker.register('worker.js');

let storageGetBlob = function(key) {
  let val = localStorage.getItem(key);
  return Boolean(val && val.length) ? JSON.parse(val) : null;
};

let lastCardSetCount = -1;
let refreshUi = function() {
  let urls = storageGetBlob('URLS');
  if (!urls) {
    return;
  }
  if (urls['cards.index'].length == lastCardSetCount) {
    return;
  }

  lastCardSetCount = urls['cards.index'].length;
  document.querySelector('#status').textContent =
      lastCardSetCount + ' Flashcard sets loaded. '
      + 'Status: ' + (localStorage.getItem('STATUS') || 'Loading');
};

let uiTick = function(stamp /*DOMHighResTimeStamp*/) {
  refreshUi();
  window.requestAnimationFrame(uiTick);
};
uiTick(performance.now());
<commit_msg>wrap init logic in window.onload, because this is still the web...<commit_after>'use strict';

let parseFromSwBlob = function(eventData) {
  if (!(eventData && eventData.length && eventData[0] == '{')) {
    return false;
  }

  let mesg = JSON.parse(eventData);
  return Boolean(mesg && mesg.cmd && mesg.cmd.length) ? mesg : false;
}

let serviceWorkerMessagHandler = function(event) {
  let msg = parseFromSwBlob(event.data);
  if (!msg) {
    console.warn(
        'got message from service worker with no preparation for. event.data:\n%s\n\n',
        event.data);
    return;
  }
  switch (msg.cmd) {
    case 'INSTALL_URL':
      let urls;
      let urlBlob = localStorage.getItem('URLS');
      if (!urlBlob || !urlBlob.length || !(urls = JSON.parse(urlBlob))) {
        urls = {};
      }
      urls[msg.payload.url] = msg.payload.resp;
      localStorage.setItem('URLS', JSON.stringify(urls));
      break;
    case 'PRIMER_STATUS':
      localStorage.setItem('STATUS', msg.payload);
    default:
      console.error('Unknown service worker command, "%s"', msg.cmd);
      break;
  }
};

let storageGetBlob = function(key) {
  let val = localStorage.getItem(key);
  return Boolean(val && val.length) ? JSON.parse(val) : null;
};

let lastCardSetCount = -1;
let refreshUi = function() {
  let urls = storageGetBlob('URLS');
  if (!urls) {
    return;
  }
  if (urls['cards.index'].length == lastCardSetCount) {
    return;
  }

  lastCardSetCount = urls['cards.index'].length;
  document.querySelector('#status').textContent =
      lastCardSetCount + ' Flashcard sets loaded. '
      + 'Status: ' + (localStorage.getItem('STATUS') || 'Loading');
};

window.onload = function () {
  if (!('serviceWorker' in navigator)) {
    let fatal = 'WTF is this browser? no service worker API found';
    alert(fatal);
    throw new Error(fatal); // stop this file's execution
  }

  navigator.serviceWorker.addEventListener('message', serviceWorkerMessagHandler);

  navigator.serviceWorker.register('worker.js');

  let uiTick = function(stamp /*DOMHighResTimeStamp*/) {
    refreshUi();
    window.requestAnimationFrame(uiTick);
  };
  uiTick(performance.now());
};
<|endoftext|>