<commit_before>/*
  Table v0.1
  Adam Schwartz

  Based on:
  SortTable version 2
  Stuart Langridge, http://www.kryogenix.org/code/browser/Table/, 7th April 2007
*/

Table = {
  numberRegExp: /^-?[$]?[\d,.]+%?$/,

  makeSortable: function(table) {
    var c, r, tHeadRow;

    if (table.tHead.rows.length !== 1) return;

    tHeadRow = table.tHead.rows[0].cells;

    for (c = 0; c < tHeadRow.length; c++) {
      if (tHeadRow[c].getAttribute('data-sort') === 'false') continue;

      tHeadRow[c].sortFunction = Table.guessSortFunctionFromColumn(table, c);

      tHeadRow[c].columnIndex = c;
      tHeadRow[c].tBody = table.tBodies[0];

      tHeadRow[c].addEventListener('click', function(e) {

        if (this.getAttribute('data-sorted') === 'true') {
          Table.reverse(this.tBody);

          if (this.getAttribute('data-sorted-reverse') !== 'true') {
            this.setAttribute('data-sorted-reverse', 'true');
          } else {
            this.setAttribute('data-sorted-reverse', 'false');
          }

          return;
        }

        tHeadRow = this.parentNode;

        Array.prototype.slice.call(tHeadRow.childNodes).forEach(function(cell) {
          if (cell.nodeType == 1) {
            cell.setAttribute('data-sorted', 'false');
            cell.setAttribute('data-sorted-reverse', 'false');
          }
        });

        this.setAttribute('data-sorted', 'true');

        rowArray = [];

        col = this.columnIndex;
        rows = this.tBody.rows;

        for (r = 0; r < rows.length; r++) {
          rowArray[rowArray.length] = [Table.getCellValue(rows[r].cells[col]), rows[r]];
        }

        rowArray.sort(this.sortFunction);

        var fragment = document.createDocumentFragment();

        for (r = 0; r < rowArray.length; r++) {
          fragment.appendChild(rowArray[r][1].cloneNode(true));
        }

        this.tBody.innerHTML = '';
        this.tBody.appendChild(fragment);
      });
    }
  },

  guessSortFunctionFromColumn: function(table, column) {
    var i, text, sortFn;

    sortFn = Table.sortAlpha;

    for (i = 0; i < table.tBodies[0].rows.length; i++) {
      text = Table.getCellValue(table.tBodies[0].rows[i].cells[column]);

      if (text !== '' && text.match(Table.numberRegExp)) {
        return Table.sortNumeric;
      }
    }

    return sortFn;
  },

  getCellValue: function(node) {
    if (!node) return '';

    if (node.getAttribute('data-value') !== null) {
      return node.getAttribute('data-value');
    }

    return node.innerText.replace(/^\s+|\s+$/g, '');
  },

  reverse: function(tbody) {
    var r, fragment;

    fragment = document.createDocumentFragment();

    for (r = tbody.rows.length - 1; r >= 0; r--) {
      fragment.appendChild(tbody.rows[r].cloneNode(true));
    }

    tbody.innerHTML = '';
    tbody.appendChild(fragment);
  },

  sortNumeric: function(a,b) {
    var aa = parseFloat(a[0].replace(/[^0-9.-]/g, '')),
        bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''))
    ;
    if (isNaN(aa)) aa = 0;
    if (isNaN(bb)) bb = 0;
    return aa - bb;
  },

  sortAlpha: function(a, b) {
    var aa = a[0].toLowerCase(),
        bb = b[0].toLowerCase()
    ;
    if (aa === bb) return 0;
    if (aa < bb) return -1;
    return 1;
  }
};<commit_msg>Cleanup<commit_after>/*
  Table v0.1
  Adam Schwartz

  Based on:
  SortTable version 2
  Stuart Langridge, http://www.kryogenix.org/code/browser/Table/, 7th April 2007
*/

Table = {
  numberRegExp: /^-?[$]?[\d,.]+%?$/,

  makeSortable: function(table) {
    var c, r, tHeadRow;

    if (table.tHead.rows.length !== 1) return;

    tHeadRow = table.tHead.rows[0].cells;

    for (c = 0; c < tHeadRow.length; c++) {
      if (tHeadRow[c].getAttribute('data-sort') === 'false') continue;

      tHeadRow[c].sortFunction = Table.guessSortFunctionFromColumn(table, c);

      tHeadRow[c].columnIndex = c;
      tHeadRow[c].tBody = table.tBodies[0];

      tHeadRow[c].addEventListener('click', function(e) {

        if (this.getAttribute('data-sorted') === 'true') {
          Table.reverse(this.tBody);

          if (this.getAttribute('data-sorted-reverse') !== 'true') {
            this.setAttribute('data-sorted-reverse', 'true');
          } else {
            this.setAttribute('data-sorted-reverse', 'false');
          }

          return;
        }

        tHeadRow = this.parentNode;

        Array.prototype.slice.call(tHeadRow.childNodes).forEach(function(cell) {
          if (cell.nodeType == 1) {
            cell.setAttribute('data-sorted', 'false');
            cell.setAttribute('data-sorted-reverse', 'false');
          }
        });

        this.setAttribute('data-sorted', 'true');

        rowArray = [];

        col = this.columnIndex;
        rows = this.tBody.rows;

        for (r = 0; r < rows.length; r++) {
          rowArray[rowArray.length] = [Table.getCellValue(rows[r].cells[col]), rows[r]];
        }

        rowArray.sort(this.sortFunction);

        var fragment = document.createDocumentFragment();

        for (r = 0; r < rowArray.length; r++) {
          fragment.appendChild(rowArray[r][1].cloneNode(true));
        }

        this.tBody.innerHTML = '';
        this.tBody.appendChild(fragment);
      });
    }
  },

  guessSortFunctionFromColumn: function(table, column) {
    var i, text, sortFn;

    sortFn = Table.sortAlpha;

    for (i = 0; i < table.tBodies[0].rows.length; i++) {
      text = Table.getCellValue(table.tBodies[0].rows[i].cells[column]);

      if (text !== '' && text.match(Table.numberRegExp)) {
        return Table.sortNumeric;
      }
    }

    return sortFn;
  },

  getCellValue: function(node) {
    if (!node) return '';

    if (node.getAttribute('data-value') !== null) {
      return node.getAttribute('data-value');
    }

    return node.innerText.replace(/^\s+|\s+$/g, '');
  },

  reverse: function(tbody) {
    var r, fragment;

    fragment = document.createDocumentFragment();

    for (r = tbody.rows.length - 1; r >= 0; r--) {
      fragment.appendChild(tbody.rows[r].cloneNode(true));
    }

    tbody.innerHTML = '';
    tbody.appendChild(fragment);
  },

  sortNumeric: function(a, b) {
    var aa = parseFloat(a[0].replace(/[^0-9.-]/g, '')),
        bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''))
    ;
    if (isNaN(aa)) aa = 0;
    if (isNaN(bb)) bb = 0;
    return aa - bb;
  },

  sortAlpha: function(a, b) {
    var aa = a[0].toLowerCase(),
        bb = b[0].toLowerCase()
    ;
    if (aa === bb) return 0;
    if (aa < bb) return -1;
    return 1;
  }
};<|endoftext|>


<commit_before>const sounds = {
    redSound: new Howl({
        urls: ['soundSamples/A/bubbles.mp3']
    }),
    yellowSound: new Howl({
        urls: ['soundSamples/A/clay.mp3']
    }),
    cyanSound: new Howl({
        urls: ['soundSamples/A/confetti.mp3']
    }),
    magentaSound: new Howl({
        urls: ['soundSamples/A/corona.mp3']
    }),
    purpleSound: new Howl({
        urls: ['soundSamples/A/dotted-spiral.mp3']
    }),
    blueSound: new Howl({
        urls: ['soundSamples/A/flash-1.mp3']
    }),
    greenSound: new Howl({
        urls: ['soundSamples/A/flash-2.mp3']
    }),
    pinkSound: new Howl({
        urls: ['soundSamples/A/flash-3.mp3']
    }),
    blackSound: null
};

document.getElementById('sampleInputInfoMessage').style.visibility = 'hidden';

document.addEventListener('click', function(event){
    if(event.target.id  === 'red' || event.target.id  === 'red-h1'){
        sounds.redSound.play();
    } else if (event.target.id === 'yellow' || event.target.id  === 'yellow-h1') {
        sounds.yellowSound.play();
    } else if (event.target.id === 'cyan' || event.target.id  === 'cyan-h1') {
        sounds.cyanSound.play();
    } else if (event.target.id === 'magenta' || event.target.id  === 'magenta-h1') {
        sounds.magentaSound.play();
    } else if (event.target.id === 'purple' || event.target.id  === 'purple-h1') {
        sounds.purpleSound.play();
    } else if (event.target.id === 'blue' || event.target.id  === 'blue-h1') {
        sounds.blueSound.play();
    } else if (event.target.id === 'green' || event.target.id  === 'green-h1') {
        sounds.greenSound.play();
    } else if (event.target.id === 'pink' || event.target.id  === 'pink-h1') {
        sounds.pinkSound.play();
    } else if (event.target.id === 'square') {
        if (sounds.blackSound === null){
            document.getElementById('sampleInputInfoMessage').style.visibility = 'visible';
        }
        sounds.blackSound.play();
    }
});

document.addEventListener('keypress', function(event){
    pressedKey = event.which;

    console.log(event.which);
    if(pressedKey == 113){
        sounds.redSound.play();
    } else if (pressedKey == 119) {
        sounds.yellowSound.play();
    } else if (pressedKey == 101) {
        sounds.cyanSound.play();
    } else if (pressedKey == 114) {
        sounds.magentaSound.play();
    } else if (pressedKey == 116) {
        sounds.purpleSound.play();
    } else if (pressedKey == 121) {
        sounds.blueSound.play();
    } else if (pressedKey == 117) {
        sounds.greenSound.play();
    } else if (pressedKey == 105) {
        sounds.pinkSound.play();
    }
});
<commit_msg>Some information message added to "black square", when it is clicked without any sample uploaded, it displays a message to notify the user to upload a sample first.<commit_after>const sounds = {
    redSound: new Howl({
        urls: ['soundSamples/A/bubbles.mp3']
    }),
    yellowSound: new Howl({
        urls: ['soundSamples/A/clay.mp3']
    }),
    cyanSound: new Howl({
        urls: ['soundSamples/A/confetti.mp3']
    }),
    magentaSound: new Howl({
        urls: ['soundSamples/A/corona.mp3']
    }),
    purpleSound: new Howl({
        urls: ['soundSamples/A/dotted-spiral.mp3']
    }),
    blueSound: new Howl({
        urls: ['soundSamples/A/flash-1.mp3']
    }),
    greenSound: new Howl({
        urls: ['soundSamples/A/flash-2.mp3']
    }),
    pinkSound: new Howl({
        urls: ['soundSamples/A/flash-3.mp3']
    }),
    blackSound: null
};

document.getElementById('sampleInputInfoMessage').style.visibility = 'hidden';

document.addEventListener('click', function(event){
    if(event.target.id  === 'red' || event.target.id  === 'red-h1'){
        sounds.redSound.play();
    } else if (event.target.id === 'yellow' || event.target.id  === 'yellow-h1') {
        sounds.yellowSound.play();
    } else if (event.target.id === 'cyan' || event.target.id  === 'cyan-h1') {
        sounds.cyanSound.play();
    } else if (event.target.id === 'magenta' || event.target.id  === 'magenta-h1') {
        sounds.magentaSound.play();
    } else if (event.target.id === 'purple' || event.target.id  === 'purple-h1') {
        sounds.purpleSound.play();
    } else if (event.target.id === 'blue' || event.target.id  === 'blue-h1') {
        sounds.blueSound.play();
    } else if (event.target.id === 'green' || event.target.id  === 'green-h1') {
        sounds.greenSound.play();
    } else if (event.target.id === 'pink' || event.target.id  === 'pink-h1') {
        sounds.pinkSound.play();
    } else if (event.target.id === 'square') {
        if (sounds.blackSound === null){
            document.getElementById('sampleInputInfoMessage').style.visibility = 'visible';
        } else {
            sounds.blackSound.play();
        }
    }
});

document.addEventListener('keypress', function(event){
    pressedKey = event.which;

    console.log(event.which);
    if(pressedKey == 113){
        sounds.redSound.play();
    } else if (pressedKey == 119) {
        sounds.yellowSound.play();
    } else if (pressedKey == 101) {
        sounds.cyanSound.play();
    } else if (pressedKey == 114) {
        sounds.magentaSound.play();
    } else if (pressedKey == 116) {
        sounds.purpleSound.play();
    } else if (pressedKey == 121) {
        sounds.blueSound.play();
    } else if (pressedKey == 117) {
        sounds.greenSound.play();
    } else if (pressedKey == 105) {
        sounds.pinkSound.play();
    }
});
<|endoftext|>


<commit_before>var util         = require("util")
  , EventEmitter = require("events").EventEmitter

module.exports = (function() {
  var CustomEventEmitter = function(fct) {
    this.fct = fct
  }
  util.inherits(CustomEventEmitter, EventEmitter)

  CustomEventEmitter.prototype.run = function() {
    process.nextTick(function() {
      if (this.fct) {
        this.fct.call(this, this)
      }
    }.bind(this))

    return this
  }

  CustomEventEmitter.prototype.success =
  CustomEventEmitter.prototype.ok =
  function(fct) {
    this.on('success', fct)
    return this
  }

  CustomEventEmitter.prototype.failure =
  CustomEventEmitter.prototype.fail =
  CustomEventEmitter.prototype.error =
  function(fct) {
    this.on('error', fct)
    return this;
  }

  CustomEventEmitter.prototype.done =
  CustomEventEmitter.prototype.complete =
  function(fct) {
    this.on('error', function(err) { fct(err, null) })
        .on('success', function(result) { fct(null, result) })
    return this
  }

  CustomEventEmitter.prototype.proxy = function(emitter) {
    ['success', 'error', 'sql'].each(function (eventKey) {
      this.on(eventKey, function (result) {
        emitter.emit(eventKey, result)
      })
    }.bind(this))
  }

  return CustomEventEmitter;
})()
<commit_msg>each -> foreaceh<commit_after>var util         = require("util")
  , EventEmitter = require("events").EventEmitter
  , proxyEventKeys = ['success', 'error', 'sql']

module.exports = (function() {
  var CustomEventEmitter = function(fct) {
    this.fct = fct
  }
  util.inherits(CustomEventEmitter, EventEmitter)

  CustomEventEmitter.prototype.run = function() {
    process.nextTick(function() {
      if (this.fct) {
        this.fct.call(this, this)
      }
    }.bind(this))

    return this
  }

  CustomEventEmitter.prototype.success =
  CustomEventEmitter.prototype.ok =
  function(fct) {
    this.on('success', fct)
    return this
  }

  CustomEventEmitter.prototype.failure =
  CustomEventEmitter.prototype.fail =
  CustomEventEmitter.prototype.error =
  function(fct) {
    this.on('error', fct)
    return this;
  }

  CustomEventEmitter.prototype.done =
  CustomEventEmitter.prototype.complete =
  function(fct) {
    this.on('error', function(err) { fct(err, null) })
        .on('success', function(result) { fct(null, result) })
    return this
  }

  CustomEventEmitter.prototype.proxy = function(emitter) {
    proxyEventKeys.forEach(function (eventKey) {
      this.on(eventKey, function (result) {
        emitter.emit(eventKey, result)
      })
    }.bind(this))
  }

  return CustomEventEmitter;
})()
<|endoftext|>


<commit_before>'use strict';
var BaseEvent = require('./base_event');
var ModuleEvent = require('./module_event');
var util = require('util');
var Application = require('hoist-model').Application;
var hoistErrors = require('hoist-errors');
var BBPromise = require('bluebird');
var _ = require('lodash');

function ApplicationEvent(brokeredMessageOrProperties) {
  BaseEvent.call(this, brokeredMessageOrProperties);
}

util.inherits(ApplicationEvent, BaseEvent);

ApplicationEvent.QueueName = 'application.event';

ApplicationEvent.prototype.convertToBrokeredMessage = function () {
  var brokeredMessage = BaseEvent.prototype.convertToBrokeredMessage.call(this);
  brokeredMessage.customProperties = {
    applicationid: this.applicationId,
    environment: this.environment,
    eventname: this.eventName,
    sessionid: this.sessionId
  };
  for (var i in brokeredMessage.customProperties) {
    if (brokeredMessage.customProperties[i] === null || brokeredMessage.customProperties[i] === undefined) {
      // test[i] === undefined is probably not very useful here
      delete brokeredMessage.customProperties[i];
    }
  }
  if (this.payload) {
    brokeredMessage.body = JSON.stringify(this.payload);
  }
  return brokeredMessage;
};
ApplicationEvent.prototype.initWithBrokeredMessage = function (brokeredMessage) {
  /* istanbul ignore if */
  if (!brokeredMessage) {
    return;
  }
  BaseEvent.prototype.initWithBrokeredMessage.call(this, brokeredMessage);
  /* istanbul ignore else */
  if (brokeredMessage.customProperties) {
    this.applicationId = brokeredMessage.customProperties.applicationid;
    this.eventName = brokeredMessage.customProperties.eventname;
    this.environment = brokeredMessage.customProperties.environment;
    this.sessionId = brokeredMessage.customProperties.sessionid;
  }
  if (brokeredMessage.body) {
    this.payload = JSON.parse(brokeredMessage.body);
  }
};
ApplicationEvent.prototype.initWithProperties = function (properties) {
  BaseEvent.prototype.initWithProperties.call(this, properties);
  this.applicationId = properties.applicationId;
  this.eventName = properties.eventName;
  this.environment = properties.environment;
  this.sessionId = properties.sessionId;
  this.payload = properties.payload;
};

ApplicationEvent.prototype.toJSON = function () {
  var jsonObj = BaseEvent.prototype.toJSON.call(this);
  jsonObj.eventName = this.eventName;
  jsonObj.applicationId = this.applicationId;
  jsonObj.environment = this.environment;
  jsonObj.sessionId = this.sessionId;
  jsonObj.payload = this.payload;
  return jsonObj;
};

ApplicationEvent.prototype.process = function (callback) {
  var self = this;
  console.log('processing application event',this);
  return BBPromise.try(function emitStart() {
    self.emit('log.step', 'message:received');
  }).then(function lookUpApplication() {
    return Application.findOneAsync({
      _id: self.applicationid
    });
  }).then(function lookUpEvent(application) {
    console.log('loaded application',application);
    if (!application) {
      var error = new hoistErrors.model.application.NotFoundError();
      throw error;
    }
    var settings = application.settings[self.environment];
    console.log('loaded settings',settings);
    return settings.on[self.eventName];
  }).then(function processEvent(ev) {
    console.log('loaded event',ev);
    if (ev) {
      var moduleMapper = function (module) {
        var moduleEvent = new ModuleEvent({
          moduleName: module,
          correlationId: self.correlationId,
          applicationId: self.applicationId,
          environment: self.environment,
          sessionId: self.sessionId,
          eventName: self.eventName,
          payload: self.payload
        });
        self.emit('createEvent', moduleEvent);
        self.emit('publishEvent', moduleEvent);
      };
      return BBPromise.all(
        _.map(ev.modules, moduleMapper)
      );
    }
  }).then(function () {
    self.emit('log.step', 'message:processed');
  }).then(function () {
    self.emit('done');
  }).catch(function (err) {
    console.log(err);
    if (err instanceof hoistErrors.model.NotFoundError) {
      self.emit('log.error', err);
    } else {
      throw err;
    }
  }).nodeify(callback);
};
module.exports = ApplicationEvent;
<commit_msg>log the first step in the chain.. are we even getting that far<commit_after>'use strict';
var BaseEvent = require('./base_event');
var ModuleEvent = require('./module_event');
var util = require('util');
var Application = require('hoist-model').Application;
var hoistErrors = require('hoist-errors');
var BBPromise = require('bluebird');
var _ = require('lodash');

function ApplicationEvent(brokeredMessageOrProperties) {
  BaseEvent.call(this, brokeredMessageOrProperties);
}

util.inherits(ApplicationEvent, BaseEvent);

ApplicationEvent.QueueName = 'application.event';

ApplicationEvent.prototype.convertToBrokeredMessage = function () {
  var brokeredMessage = BaseEvent.prototype.convertToBrokeredMessage.call(this);
  brokeredMessage.customProperties = {
    applicationid: this.applicationId,
    environment: this.environment,
    eventname: this.eventName,
    sessionid: this.sessionId
  };
  for (var i in brokeredMessage.customProperties) {
    if (brokeredMessage.customProperties[i] === null || brokeredMessage.customProperties[i] === undefined) {
      // test[i] === undefined is probably not very useful here
      delete brokeredMessage.customProperties[i];
    }
  }
  if (this.payload) {
    brokeredMessage.body = JSON.stringify(this.payload);
  }
  return brokeredMessage;
};
ApplicationEvent.prototype.initWithBrokeredMessage = function (brokeredMessage) {
  /* istanbul ignore if */
  if (!brokeredMessage) {
    return;
  }
  BaseEvent.prototype.initWithBrokeredMessage.call(this, brokeredMessage);
  /* istanbul ignore else */
  if (brokeredMessage.customProperties) {
    this.applicationId = brokeredMessage.customProperties.applicationid;
    this.eventName = brokeredMessage.customProperties.eventname;
    this.environment = brokeredMessage.customProperties.environment;
    this.sessionId = brokeredMessage.customProperties.sessionid;
  }
  if (brokeredMessage.body) {
    this.payload = JSON.parse(brokeredMessage.body);
  }
};
ApplicationEvent.prototype.initWithProperties = function (properties) {
  BaseEvent.prototype.initWithProperties.call(this, properties);
  this.applicationId = properties.applicationId;
  this.eventName = properties.eventName;
  this.environment = properties.environment;
  this.sessionId = properties.sessionId;
  this.payload = properties.payload;
};

ApplicationEvent.prototype.toJSON = function () {
  var jsonObj = BaseEvent.prototype.toJSON.call(this);
  jsonObj.eventName = this.eventName;
  jsonObj.applicationId = this.applicationId;
  jsonObj.environment = this.environment;
  jsonObj.sessionId = this.sessionId;
  jsonObj.payload = this.payload;
  return jsonObj;
};

ApplicationEvent.prototype.process = function (callback) {
  var self = this;
  console.log('processing application event',this);
  return BBPromise.try(function emitStart() {
    console.log('emiting log step');
    self.emit('log.step', 'message:received');
  }).then(function lookUpApplication() {
    return Application.findOneAsync({
      _id: self.applicationid
    });
  }).then(function lookUpEvent(application) {
    console.log('loaded application',application);
    if (!application) {
      var error = new hoistErrors.model.application.NotFoundError();
      throw error;
    }
    var settings = application.settings[self.environment];
    console.log('loaded settings',settings);
    return settings.on[self.eventName];
  }).then(function processEvent(ev) {
    console.log('loaded event',ev);
    if (ev) {
      var moduleMapper = function (module) {
        var moduleEvent = new ModuleEvent({
          moduleName: module,
          correlationId: self.correlationId,
          applicationId: self.applicationId,
          environment: self.environment,
          sessionId: self.sessionId,
          eventName: self.eventName,
          payload: self.payload
        });
        self.emit('createEvent', moduleEvent);
        self.emit('publishEvent', moduleEvent);
      };
      return BBPromise.all(
        _.map(ev.modules, moduleMapper)
      );
    }
  }).then(function () {
    self.emit('log.step', 'message:processed');
  }).then(function () {
    self.emit('done');
  }).catch(function (err) {
    console.log(err);
    if (err instanceof hoistErrors.model.NotFoundError) {
      self.emit('log.error', err);
    } else {
      throw err;
    }
  }).nodeify(callback);
};
module.exports = ApplicationEvent;
<|endoftext|>


<commit_before>
// { key, i in items} -> { key, i, items }
function loopKeys(expr) {
  var b0 = brackets(0),
      els = expr.slice(b0.length).match(/^\s*(\S+?)\s*(?:,\s*(\S+))?\s+in\s+(.+)$/)
  return els ? { key: els[1], pos: els[2], val: b0 + els[3] } : { val: expr }
}

function mkitem(expr, key, val) {
  var item = {}
  item[expr.key] = key
  if (expr.pos) item[expr.pos] = val
  return item
}

/* Beware: heavy stuff */
function _each(dom, parent, expr) {

  remAttr(dom, 'each')

  var tagName = getTagName(dom),
      template = dom.outerHTML,
      hasImpl = !!tagImpl[tagName],
      impl = tagImpl[tagName] || {
        tmpl: template
      },
      root = dom.parentNode,
      placeholder = document.createComment('riot placeholder'),
      tags = [],
      child = getTag(dom),
      checksum

  root.insertBefore(placeholder, dom)

  expr = loopKeys(expr)

  // clean template code
  parent
    .one('premount', function () {
      if (root.stub) root = parent.root
      // remove the original DOM node
      dom.parentNode.removeChild(dom)
    })
    .on('update', function () {
      var items = tmpl(expr.val, parent)

      // object loop. any changes cause full redraw
      if (!isArray(items)) {

        checksum = items ? JSON.stringify(items) : ''

        items = !items ? [] :
          Object.keys(items).map(function (key) {
            return mkitem(expr, key, items[key])
          })
      }

      var frag = document.createDocumentFragment(),
          i = tags.length,
          j = items.length

      // unmount leftover items
      while (i > j) {
        tags[--i].unmount()
        tags.splice(i, 1)
      }

      for (i = 0; i < j; ++i) {
        var _item = !checksum && !!expr.key ? mkitem(expr, items[i], i) : items[i]

        if (!tags[i]) {
          // mount new
          (tags[i] = new Tag(impl, {
              parent: parent,
              isLoop: true,
              hasImpl: hasImpl,
              root: hasImpl ? dom.cloneNode() : root,
              item: _item
            }, dom.innerHTML)
          ).mount()

          frag.appendChild(tags[i].root)
        } else
          tags[i].update(_item)

        tags[i]._item = _item

      }

      root.insertBefore(frag, placeholder)

      if (child) parent.tags[tagName] = tags

    }).one('updated', function() {
      var keys = Object.keys(parent)// only set new values
      walk(root, function(node) {
        // only set element node and not isLoop
        if (node.nodeType == 1 && !node.isLoop && !node._looped) {
          node._visited = false // reset _visited for loop node
          node._looped = true // avoid set multiple each
          setNamed(node, parent, keys)
        }
      })
    })

}
<commit_msg>Fix issue #947<commit_after>
// { key, i in items} -> { key, i, items }
function loopKeys(expr) {
  var b0 = brackets(0),
      els = expr.slice(b0.length).trim().match(/^(\S+?)\s*(?:,\s*(\S+))?\s+in\s+(.+)$/)
  return els ? { key: els[1], pos: els[2], val: b0 + els[3] } : { val: expr }
}

function mkitem(expr, key, val) {
  var item = {}
  item[expr.key] = key
  if (expr.pos) item[expr.pos] = val
  return item
}

/* Beware: heavy stuff */
function _each(dom, parent, expr) {

  remAttr(dom, 'each')

  var tagName = getTagName(dom),
      template = dom.outerHTML,
      hasImpl = !!tagImpl[tagName],
      impl = tagImpl[tagName] || {
        tmpl: template
      },
      root = dom.parentNode,
      placeholder = document.createComment('riot placeholder'),
      tags = [],
      child = getTag(dom),
      checksum

  root.insertBefore(placeholder, dom)

  expr = loopKeys(expr)

  // clean template code
  parent
    .one('premount', function () {
      if (root.stub) root = parent.root
      // remove the original DOM node
      dom.parentNode.removeChild(dom)
    })
    .on('update', function () {
      var items = tmpl(expr.val, parent)

      // object loop. any changes cause full redraw
      if (!isArray(items)) {

        checksum = items ? JSON.stringify(items) : ''

        items = !items ? [] :
          Object.keys(items).map(function (key) {
            return mkitem(expr, key, items[key])
          })
      }

      var frag = document.createDocumentFragment(),
          i = tags.length,
          j = items.length

      // unmount leftover items
      while (i > j) {
        tags[--i].unmount()
        tags.splice(i, 1)
      }

      for (i = 0; i < j; ++i) {
        var _item = !checksum && !!expr.key ? mkitem(expr, items[i], i) : items[i]

        if (!tags[i]) {
          // mount new
          (tags[i] = new Tag(impl, {
              parent: parent,
              isLoop: true,
              hasImpl: hasImpl,
              root: hasImpl ? dom.cloneNode() : root,
              item: _item
            }, dom.innerHTML)
          ).mount()

          frag.appendChild(tags[i].root)
        } else
          tags[i].update(_item)

        tags[i]._item = _item

      }

      root.insertBefore(frag, placeholder)

      if (child) parent.tags[tagName] = tags

    }).one('updated', function() {
      var keys = Object.keys(parent)// only set new values
      walk(root, function(node) {
        // only set element node and not isLoop
        if (node.nodeType == 1 && !node.isLoop && !node._looped) {
          node._visited = false // reset _visited for loop node
          node._looped = true // avoid set multiple each
          setNamed(node, parent, keys)
        }
      })
    })

}
<|endoftext|>


<commit_before>import { isArray } from './../common/util/check'
import { remAttr, getAttr, getOuterHTML, createDOMPlaceholder, safeInsert, createFrag } from './../common/util/dom'
import { defineProperty, each, contains, extend } from './../common/util/misc'
import { tmpl } from 'riot-tmpl'
import Tag from './tag'

import {
  T_STRING,
  T_OBJECT,
  __TAG_IMPL,
  RE_SPECIAL_TAGS,
  CONDITIONAL_DIRECTIVE,
  LOOP_DIRECTIVE,
  LOOP_NO_REORDER_DIRECTIVE
} from './../common/global-variables'

import {
  moveChildTag,
  getTag,
  getTagName,
  arrayishAdd,
  arrayishRemove,
  makeVirtual,
  moveVirtual
} from './../common/util/tags'

/**
 * Convert the item looped into an object used to extend the child tag properties
 * @param   { Object } expr - object containing the keys used to extend the children tags
 * @param   { * } key - value to assign to the new object returned
 * @param   { * } val - value containing the position of the item in the array
 * @param   { Object } base - prototype object for the new item
 * @returns { Object } - new object containing the values of the original item
 *
 * The variables 'key' and 'val' are arbitrary.
 * They depend on the collection type looped (Array, Object)
 * and on the expression used on the each tag
 *
 */
function mkitem(expr, key, val, base) {
  var item = base ? Object.create(base) : {}
  item[expr.key] = key
  if (expr.pos) item[expr.pos] = val
  return item
}

/**
 * Unmount the redundant tags
 * @param   { Array } items - array containing the current items to loop
 * @param   { Array } tags - array containing all the children tags
 * @param   { String } tagName - key used to identify the type of tag
 */
function unmountRedundant(items, tags, tagName) {
  var i = tags.length,
    j = items.length

  while (i > j) {
    remove.apply(tags[i], [tags, i, tagName])
  }
}

/**
 * Move the nested custom tags in non custom loop tags
 * @this Tag
 * @param   { Number } i - current position of the loop tag
 */
function moveNestedTags(i) {
  each(Object.keys(this.tags), (tagName) => {
    var tag = this.tags[tagName]
    if (isArray(tag))
      each(tag, function (t) {
        moveChildTag.apply(t, [tagName, i])
      })
    else
      moveChildTag.apply(tag, [tagName, i])
  })
}

/**
 * Remove a child tag
 * @this Tag
 * @param   { Array } tags - tags collection
 * @param   { Number } i - index of the tag to remove
 * @param   { String } tagName - key used to identify the type of tag
 */
function remove(tags, i, tagName) {
  tags.splice(i, 1)
  this.unmount()
  arrayishRemove(this.parent, tagName, this, true)
}

/**
 * Move a child tag
 * @this Tag
 * @param   { HTMLElement } root - dom node containing all the loop children
 * @param   { Tag } nextTag - instance of the next tag preceding the one we want to move
 * @param   { Boolean } isVirtual - is it a virtual tag?
 */
function move(root, nextTag, isVirtual) {
  if (isVirtual)
    moveVirtual.apply(this, [root, nextTag])
  else
    safeInsert(root, this.root, nextTag.root)
}

/**
 * Insert and mount a child tag
 * @this Tag
 * @param   { HTMLElement } root - dom node containing all the loop children
 * @param   { Tag } nextTag - instance of the next tag preceding the one we want to insert
 * @param   { Boolean } isVirtual - is it a virtual tag?
 */
function insert(root, nextTag, isVirtual) {
  if (isVirtual)
    makeVirtual.apply(this, [root, nextTag])
  else
    safeInsert(root, this.root, nextTag.root)
}

/**
 * Append a new tag into the DOM
 * @this Tag
 * @param   { HTMLElement } root - dom node containing all the loop children
 * @param   { Boolean } isVirtual - is it a virtual tag?
 */
function append(root, isVirtual) {
  if (isVirtual)
    makeVirtual.call(this, root)
  else
    root.appendChild(this.root)
}

/**
 * Manage tags having the 'each'
 * @param   { HTMLElement } dom - DOM node we need to loop
 * @param   { Tag } parent - parent tag instance where the dom node is contained
 * @param   { String } expr - string contained in the 'each' attribute
 * @returns { Object } expression object for this each loop
 */
export default function _each(dom, parent, expr) {

  // remove the each property from the original tag
  remAttr(dom, LOOP_DIRECTIVE)

  var mustReorder = typeof getAttr(dom, LOOP_NO_REORDER_DIRECTIVE) !== T_STRING || remAttr(dom, LOOP_NO_REORDER_DIRECTIVE),
    tagName = getTagName(dom),
    impl = __TAG_IMPL[tagName] || { tmpl: getOuterHTML(dom) },
    useRoot = RE_SPECIAL_TAGS.test(tagName),
    parentNode = dom.parentNode,
    ref = createDOMPlaceholder(),
    child = getTag(dom),
    ifExpr = getAttr(dom, CONDITIONAL_DIRECTIVE),
    tags = [],
    oldItems = [],
    hasKeys,
    isLoop = true,
    isAnonymous = !__TAG_IMPL[tagName],
    isVirtual = dom.tagName === 'VIRTUAL'

  // parse the each expression
  expr = tmpl.loopKeys(expr)
  expr.isLoop = true

  if (ifExpr) remAttr(dom, CONDITIONAL_DIRECTIVE)

  // insert a marked where the loop tags will be injected
  parentNode.insertBefore(ref, dom)
  parentNode.removeChild(dom)

  expr.update = function updateEach() {

    // get the new items collection
    var items = tmpl(expr.val, parent),
      frag = createFrag(),
      olsItemsLength = oldItems.length,
      isObject = !isArray(items),
      root = ref.parentNode

    // object loop. any changes cause full redraw
    if (isObject) {
      hasKeys = items || false
      items = hasKeys ?
        Object.keys(items).map(function (key) {
          return mkitem(expr, items[key], key)
        }) : []
    } else {
      hasKeys = false
    }

    if (ifExpr) {
      items = items.filter(function(item, i) {
        if (expr.key && !isObject)
          return !!tmpl(ifExpr, mkitem(expr, item, i, parent))

        return !!tmpl(ifExpr, extend(Object.create(parent), item))
      })
    }

    // loop all the new items
    each(items, function(item, i) {
      // reorder only if the items are objects
      var
        doReorder = mustReorder && typeof item === T_OBJECT && !hasKeys,
        oldPos = oldItems.indexOf(item),
        isNew = !~oldPos,
        pos = !isNew && doReorder ? oldPos : i,
        // does a tag exist in this position?
        tag = tags[pos],
        mustAppend = i >= olsItemsLength,
        mustCreate = doReorder && isNew || !doReorder && !tag

      item = !hasKeys && expr.key ? mkitem(expr, item, i) : item

      // new tag
      if (mustCreate) {
        tag = new Tag(impl, {
          parent,
          isLoop,
          isAnonymous,
          root: useRoot ? root : dom.cloneNode(),
          item
        }, dom.innerHTML)

        // mount the tag
        tag.mount()

        if (mustAppend) {
          append.apply(tag, [frag || root, isVirtual])
        } else {
          insert.apply(tag, [root, tags[i], isVirtual])
        }

        if (!mustAppend) oldItems.splice(i, 0, item)
        tags.splice(i, 0, tag)
        if (child) arrayishAdd(parent.tags, tagName, tag, true)
      } else if (pos !== i) {
        // move the old tag
        if (contains(items, oldItems[i])) {
          move.apply(tag, [root, tags[i], isVirtual])
          // move the old tag instance
          tags.splice(i, 0, tags.splice(pos, 1)[0])
          // move the old item
          oldItems.splice(i, 0, oldItems.splice(pos, 1)[0])
          // update the position attribute if it exists
          if (expr.pos) tag[expr.pos] = i
          // if the loop tags are not custom
          // we need to move all their custom tags into the right position
          if (!child && tag.tags) moveNestedTags.call(tag, i)
        } else {
          // remove the tags that do not belong to the collection anymore
          remove.apply(tag, [tags, i, tagName])
          // noo need to proceed with the other stuff
          return
        }
      }

      // update the tag
      if (!mustCreate) tag.update()

      // cache the original item to use it in the events bound to this node
      // and its children
      defineProperty(tag, '_item', item)
      // cache the real parent tag internally
      defineProperty(tag, '_parent', parent)
    })

    // remove the redundant tags
    unmountRedundant(items, tags, tagName)

    // clone the items array
    oldItems = items.slice()

    root.insertBefore(frag, ref)
  }

  expr.unmount = function() {
    each(tags, function(t) { t.unmount() })
  }

  return expr
}
<commit_msg>updated: still refactoring the each method<commit_after>import { isArray } from './../common/util/check'
import { remAttr, getAttr, getOuterHTML, createDOMPlaceholder, safeInsert, createFrag } from './../common/util/dom'
import { defineProperty, each, contains, extend } from './../common/util/misc'
import { tmpl } from 'riot-tmpl'
import Tag from './tag'

import {
  T_STRING,
  T_OBJECT,
  __TAG_IMPL,
  RE_SPECIAL_TAGS,
  CONDITIONAL_DIRECTIVE,
  LOOP_DIRECTIVE,
  LOOP_NO_REORDER_DIRECTIVE
} from './../common/global-variables'

import {
  moveChildTag,
  getTag,
  getTagName,
  arrayishAdd,
  arrayishRemove,
  makeVirtual,
  moveVirtual
} from './../common/util/tags'

/**
 * Convert the item looped into an object used to extend the child tag properties
 * @param   { Object } expr - object containing the keys used to extend the children tags
 * @param   { * } key - value to assign to the new object returned
 * @param   { * } val - value containing the position of the item in the array
 * @param   { Object } base - prototype object for the new item
 * @returns { Object } - new object containing the values of the original item
 *
 * The variables 'key' and 'val' are arbitrary.
 * They depend on the collection type looped (Array, Object)
 * and on the expression used on the each tag
 *
 */
function mkitem(expr, key, val, base) {
  var item = base ? Object.create(base) : {}
  item[expr.key] = key
  if (expr.pos) item[expr.pos] = val
  return item
}

/**
 * Unmount the redundant tags
 * @param   { Array } items - array containing the current items to loop
 * @param   { Array } tags - array containing all the children tags
 * @param   { String } tagName - key used to identify the type of tag
 */
function unmountRedundant(items, tags, tagName) {
  var i = tags.length,
    j = items.length

  while (i > j) {
    i--
    remove.apply(tags[i], [tags, i, tagName])
  }
}

/**
 * Remove a child tag
 * @this Tag
 * @param   { Array } tags - tags collection
 * @param   { Number } i - index of the tag to remove
 * @param   { String } tagName - key used to identify the type of tag
 */
function remove(tags, i, tagName) {
  tags.splice(i, 1)
  this.unmount()
  arrayishRemove(this.parent, tagName, this, true)
}

/**
 * Move the nested custom tags in non custom loop tags
 * @this Tag
 * @param   { Number } i - current position of the loop tag
 */
function moveNestedTags(i) {
  each(Object.keys(this.tags), (tagName) => {
    var tag = this.tags[tagName]
    if (isArray(tag))
      each(tag, function (t) {
        moveChildTag.apply(t, [tagName, i])
      })
    else
      moveChildTag.apply(tag, [tagName, i])
  })
}

/**
 * Move a child tag
 * @this Tag
 * @param   { HTMLElement } root - dom node containing all the loop children
 * @param   { Tag } nextTag - instance of the next tag preceding the one we want to move
 * @param   { Boolean } isVirtual - is it a virtual tag?
 */
function move(root, nextTag, isVirtual) {
  if (isVirtual)
    moveVirtual.apply(this, [root, nextTag])
  else
    safeInsert(root, this.root, nextTag.root)
}

/**
 * Insert and mount a child tag
 * @this Tag
 * @param   { HTMLElement } root - dom node containing all the loop children
 * @param   { Tag } nextTag - instance of the next tag preceding the one we want to insert
 * @param   { Boolean } isVirtual - is it a virtual tag?
 */
function insert(root, nextTag, isVirtual) {
  if (isVirtual)
    makeVirtual.apply(this, [root, nextTag])
  else
    safeInsert(root, this.root, nextTag.root)
}

/**
 * Append a new tag into the DOM
 * @this Tag
 * @param   { HTMLElement } root - dom node containing all the loop children
 * @param   { Boolean } isVirtual - is it a virtual tag?
 */
function append(root, isVirtual) {
  if (isVirtual)
    makeVirtual.call(this, root)
  else
    root.appendChild(this.root)
}

/**
 * Manage tags having the 'each'
 * @param   { HTMLElement } dom - DOM node we need to loop
 * @param   { Tag } parent - parent tag instance where the dom node is contained
 * @param   { String } expr - string contained in the 'each' attribute
 * @returns { Object } expression object for this each loop
 */
export default function _each(dom, parent, expr) {

  // remove the each property from the original tag
  remAttr(dom, LOOP_DIRECTIVE)

  var mustReorder = typeof getAttr(dom, LOOP_NO_REORDER_DIRECTIVE) !== T_STRING || remAttr(dom, LOOP_NO_REORDER_DIRECTIVE),
    tagName = getTagName(dom),
    impl = __TAG_IMPL[tagName] || { tmpl: getOuterHTML(dom) },
    useRoot = RE_SPECIAL_TAGS.test(tagName),
    parentNode = dom.parentNode,
    ref = createDOMPlaceholder(),
    child = getTag(dom),
    ifExpr = getAttr(dom, CONDITIONAL_DIRECTIVE),
    tags = [],
    oldItems = [],
    hasKeys,
    isLoop = true,
    isAnonymous = !__TAG_IMPL[tagName],
    isVirtual = dom.tagName === 'VIRTUAL'

  // parse the each expression
  expr = tmpl.loopKeys(expr)
  expr.isLoop = true

  if (ifExpr) remAttr(dom, CONDITIONAL_DIRECTIVE)

  // insert a marked where the loop tags will be injected
  parentNode.insertBefore(ref, dom)
  parentNode.removeChild(dom)

  expr.update = function updateEach() {

    // get the new items collection
    var items = tmpl(expr.val, parent),
      frag = createFrag(),
      oldItemsLength = oldItems.length,
      isObject = !isArray(items),
      root = ref.parentNode

    // object loop. any changes cause full redraw
    if (isObject) {
      hasKeys = items || false
      items = hasKeys ?
        Object.keys(items).map(function (key) {
          return mkitem(expr, items[key], key)
        }) : []
    } else {
      hasKeys = false
    }

    if (ifExpr) {
      items = items.filter(function(item, i) {
        if (expr.key && !isObject)
          return !!tmpl(ifExpr, mkitem(expr, item, i, parent))

        return !!tmpl(ifExpr, extend(Object.create(parent), item))
      })
    }

    // loop all the new items
    each(items, function(item, i) {
      // reorder only if the items are objects
      var
        doReorder = mustReorder && typeof item === T_OBJECT && !hasKeys,
        oldPos = oldItems.indexOf(item),
        isNew = !~oldPos,
        pos = !isNew && doReorder ? oldPos : i,
        // does a tag exist in this position?
        tag = tags[pos],
        mustAppend = i >= oldItemsLength,
        mustCreate =  doReorder && isNew || !doReorder && !tag

      item = !hasKeys && expr.key ? mkitem(expr, item, i) : item

      // new tag
      if (mustCreate) {
        tag = new Tag(impl, {
          parent,
          isLoop,
          isAnonymous,
          root: useRoot ? root : dom.cloneNode(),
          item
        }, dom.innerHTML)

        // mount the tag
        tag.mount()

        if (mustAppend)
          append.apply(tag, [frag || root, isVirtual])
        else
          insert.apply(tag, [root, tags[i], isVirtual])

        if (!mustAppend) oldItems.splice(i, 0, item)
        tags.splice(i, 0, tag)
        if (child) arrayishAdd(parent.tags, tagName, tag, true)
        pos = i // handled here so no move
      } else if (pos !== i && doReorder) {
        // #closes 2040
        if (contains(items, oldItems[i])) {
          move.apply(tag, [root, tags[i], isVirtual])
          // move the old tag instance
          tags.splice(i, 0, tags.splice(pos, 1)[0])
          // move the old item
          oldItems.splice(i, 0, oldItems.splice(pos, 1)[0])
        }

        // TODO: handle the unmount here?

        // update the position attribute if it exists
        if (expr.pos) tag[expr.pos] = i

        // if the loop tags are not custom
        // we need to move all their custom tags into the right position
        if (!child && tag.tags) moveNestedTags.call(tag, i)
      }

      if (!mustCreate) tag.update(item)

      // cache the original item to use it in the events bound to this node
      // and its children
      defineProperty(tag, '_item', item)
      // cache the real parent tag internally
      defineProperty(tag, '_parent', parent)
    })

    // remove the redundant tags
    unmountRedundant(items, tags, tagName)

    // clone the items array
    oldItems = items.slice()

    root.insertBefore(frag, ref)
  }

  expr.unmount = function() {
    each(tags, function(t) { t.unmount() })
  }

  return expr
}<|endoftext|>


<commit_before>var path            = require('path');
var through         = require('through2');
var trackFilenames  = require('gulp-track-filenames');
var transformTools  = require('browserify-transform-tools');
var browserify      = require('browserify');
var gutil           = require('gulp-util');
var es6ify          = require('es6ify');
var moldSourceMap   = require('mold-source-map');
var slash           = require('gulp-slash');

/**
 *
Find a unique list of parameters of functions immediately preceded by annotation

 */
function getAnnotatedParameters(annotation, text) {
  'use strict';
  var SPLIT       = /(\/\*|\*\/)/g; // split by and capture comments
  var FUNCTION    = /^[\r\n\s]*(?:(?:return|export|default|function)\s+)*(?:[\w\$]+\s*)?\(\s*(.*)\s*\)[\r\n\s]*\{/m;
  var result      = [ ];
  var isComment   = false;
  var isAnnotated = false;
  text.split(SPLIT).forEach(function(value) {
    switch(value) {

      // start comment block (or commented comment, which will split the comment text)
      case '/*':
        isComment = true;
        break;

      // end comment block
      case '*/':
        isComment = false;
        break;

      // text between
      default:

        // where comment text is split any annotation is accepted
        if (isComment) {
          isAnnotated = isAnnotated || (value.indexOf(annotation) >= 0);

        // code text will not be split
        } else if (isAnnotated) {
          var analysis = FUNCTION.exec(value);
          if (analysis) {

            // add function parameters uniquely to the pending list
            analysis[1].split(/\s*,\s*/).forEach(function (candidate) {
              if (result.indexOf(candidate) < 0) {
                result.push(candidate);
              }
            });
          }
          isAnnotated = false;
        }
    }
  });
  return result;
}

/**
 * @param {number} [bannerWidth] The width of banner comment, zero or omitted for none
 */
module.exports = function (bannerWidth) {
  'use strict';
  var sourcesFwd = trackFilenames();
  var sourcesInt = trackFilenames();
  var reserved   = [ ];
  var count      = 0;
  var self       = {

    /**
     * Mark source files in preparation for transpile.
     * Outputs a stream of the same files.
     * @returns {stream.Through} A through stream that performs the operation of a gulp stream
     */
    sources: function () {
      var sessionFwd = sourcesFwd.create();
      var sessionInt = sourcesInt.create();
      return through.obj(function (file, encoding, done) {
        var importName = file.relative.replace(path.extname(file.path), '');
        var zeroPadded = ((new Array(file.path.length)).join('0') + String(count++)).slice(file.path.length * -1);
        sessionFwd.define(file.path, importName);
        sessionInt.define(zeroPadded, file.path);
        this.push(file);
        done();
      });
    },

    /**
     * Detect @ngAnnotate comments immediately preceding methods and reserve their parameters
     * @returns {stream.Through} A through stream that performs the operation of a gulp stream
     */
    reserve: function() {
      var logging = [ ];

      // detect @ngInject tags and reserve function parameters
      return through.obj(function(file, encoding, done) {
        var ANNOTATION = '@ngInject';
        var pending = getAnnotatedParameters(ANNOTATION, file.contents.toString());
        if (pending.length) {
          pending.sort();
          var importName = file.relative.replace(path.extname(file.path), '');
          logging.push([ ANNOTATION, importName, pending.join(', ') ]);
        }
        pending.forEach(function(candidate) {
          if (reserved.indexOf(candidate) < 0) {
            reserved.push(candidate);
          }
        });
        done(null, file);

      // report to console last so that we can equalise column widths
      }, function(done) {
        var columnWidths = [ ];
        logging.forEach(function(line) {
          line.forEach(function(column, i) {
            columnWidths[i] = Math.max(column.length, (columnWidths[i] || 0));
          });
        });
        logging.forEach(function(line) {
          line.forEach(function(column, i, array) {
            while (array[i].length < columnWidths[i]) {
              array[i] += ' ';
            }
          });
          gutil.log.apply(gutil, line);
        });
        done();
      });
    },

    /**
     * Create a transform that makes the given replacements in jasmine files
     * @param {object} replacements Replacement text keyed by the jasmine string to match
     * @returns {Function} A browserify transform
     */
    getJasmineTransform: function (replacements) {
      var expressions = { };
      if (typeof replacements === 'object') {
        for (var key in replacements) {
          var source = '((?:describe|module)\\s*\\(\\s*)(?:\'' + key + '\'|"' + key + '")';
          expressions[source] = replacements[key];
        }
      }
      return function(filename) {
        var text = '';
        return through.obj(function(contents, encoding, done) {
          text += contents.toString();
          done();
        }, function(done) {
          var lines = text.split('\n');
          for (var source in expressions) {
            var expression = new RegExp(source, 'g');
            var target     = expressions[source];
            for (var i = 0; i < lines.length; i++) {
              var analysis;
              do {
                analysis = expression.exec(lines[i]);
                if (analysis) {
                  var line     = i + 1;
                  var char     = expression.lastIndex - analysis[0].length;
                  var isMethod = (typeof target === 'function');
                  var value    = isMethod ? target(filename, line, char) : target;
                  lines[i] =
                    lines[i].slice(0, char) + analysis[1] +
                    '\'' + String(value).replace(/\\/g, '\\\\') + '\'' +
                    lines[i].slice(expression.lastIndex);
                }
              } while (analysis);
              expression.lastIndex = 0;
            }
          }
          this.push(new Buffer(lines.join('\n')));
          done();
        });
      };
    },

    /**
     * ES6ify transform
     */
    es6ifyTransform: require('es6ify'),

    /**
     * Convert import paths to absolute file paths
     */
    requireTransform: transformTools.makeRequireTransform('requireTransform', null, function(args, opts, done) {
      return done(null, 'require("' + sourcesFwd.replace(args[0], '^', '$') + '")');
    }),

    /**
     * Use es6ify to compile the files of the input stream.
     * Use the sources previously identified to satisfy any module imports.
     * @param {...string|function} transforms Any number of browserify transforms
     * @returns {stream.Through} A through stream that performs the operation of a gulp stream
     */
    compile: function () {
      var transforms = Array.prototype.slice.call(arguments);
      var output     = [ ];

      /**
       * Flush the error queue to stdout
       */
      function flushErrors() {
        if (output.length > 0) {
          var width = Number(bannerWidth) || 0;
          var hr    = new Array(width + 1);   // this is a good trick to repeat a character N times
          var start = (width > 0) ? (hr.join('\u25BC') + '\n') : '';
          var stop  = (width > 0) ? (hr.join('\u25B2') + '\n') : '';
          process.stdout.write(start + '\n' + output.join('\n\n') + '\n' + stop);
        }
      }

      /**
       * Determine the root relative form of the given file path
       * @param {string} filePath Full file path
       * @returns {string} Give path relative to process.cwd()
       */
      function rootRelative(filePath) {
        return '/' + slash(path.relative(process.cwd(), filePath));
      }

      /**
       * Compile any number of files into a bundle
       * @param {stream.Through} stream A stream to push files to
       * @param {Array.<string>|string} files Any number of files to bundle
       * @param {string} bundlename The name for the output file
       * @param {function|boolean} [minifiy] Determines whether minification is performed
       * @param {function} done Callback for completion
       */
      function bundle(stream, files, bundlename, minifiy, done) {

        // setup
        var cwd      = process.cwd();
        var outPath  = path.join(cwd, bundlename);
        var mapPath  = path.basename(bundlename) + '.map';
        var isMinify = (minifiy) && ((typeof minifiy !== 'function') || minifiy(bundlename));
        var bundler  = browserify({
          debug: true
        });

        // error handler
        function errorHandler(error) {
          var text = error.toString();
          var analysis;
          var message;

          // Error: <file>:<line>:<column>: <reason>
          if (analysis = /^\s*Error\:\s*(.*\:\d+:\d+\:\s*[^:]*).*\s*$/.exec(text)) {
            message = analysis[1] + '\n';

          // Error: <reason> from '<file>'
          } else if (analysis = /^\s*Error\:\s*(.*)\s*from\s*\'(.*)\'\s*$/.exec(text)) {
            message = analysis[2] + ':0:0: ' + analysis[1] + '\n';

          // Unknown
          } else {
            message = 'TODO parse this error\n' + text + '\n';
          }

          // add unique
          if (output.indexOf(message) < 0) {
            output.push(message);
          }

          // complete overall (once only)
          if (done) {
            done();
            done = null;
          }
        }

        // stream output
        function pushFileToStream(path, text) {
          stream.push(new gutil.File({
            cwd: cwd,
            base: cwd,
            path: path,
            contents: new Buffer(text)
          }));
        }

        // transforms
        transforms.concat(self.requireTransform).forEach(function (item) {
          bundler.transform(item);
        });

        // require statements
        [ ].concat(files).forEach(function (item) {
          bundler.require(item, { entry: true });
        });

        // minify requires callback style
        if (isMinify) {
          require('minifyify')(bundler, {
            map:    mapPath,
            uglify: {
              mangle: {
                toplevel: true,
                except:   reserved.join(',')
              }
            }
          });
          bundler.bundle(function (error, code, map) {
            if (!error) {
              var anonymised = sourcesInt.replace(code, '"', '"');  // anonymise module paths
              var sourcemap  = JSON.parse(map);
              sourcemap.sources = sourcemap.sources.map(rootRelative);
              delete sourcemap.file;
              delete sourcemap.sourcesContent;
              pushFileToStream(outPath + '.map', JSON.stringify(sourcemap, null, 2));
              pushFileToStream(outPath, anonymised);
            }
            done(); // complete overall
          })
            .on('error', errorHandler);

        // non-minify requires stream style
        } else {
          console.log('!!!!HRE!!!')
          bundler.bundle()
            .on('error', errorHandler)
            .pipe(moldSourceMap.transform(function (molder, complete) {
              molder.mapSources(rootRelative);
              molder.sourcemap.setProperty('file');
              molder.sourcemap.setProperty('sourcesContent');
              molder.sourcemap.setProperty('sourceRoot');
              pushFileToStream(outPath + '.map', molder.sourcemap.toJSON(2));
              complete('//# sourceMappingURL=' + mapPath);
            }))
            .on('data', function (contents) {
              pushFileToStream(outPath, contents);
              done(); // complete overall
            });
        }
      }

      // return a set of streams
      return {

        /**
         * A stream that produces a bundle for each file in the stream
         * @param {function|boolean} [isMinify] Determines whether minification is performed
         * @returns {stream.Through}
         */
        each: function (isMinify) {
          return through.obj(function (file, encoding, done) {
            bundle(this, [ file.path ], file.relative, isMinify, done);
          }, function(done) {
            flushErrors();
            done();
          });
        },

        /**
         * A stream that produces a bundle containing all files in the stream
         * @param {string} outPath A relative path for the output file
         * @param {function|boolean} [isMinify] Determines whether minification is performed
         * @returns {stream.Through}
         */
        all: function (outPath, isMinify) {
          var pending = [ ];
          return through.obj(function (file, encoding, done) {
            pending.push(file.path);
            done();
          }, function (done) {
            if (pending.length) {
              bundle(this, pending, outPath, isMinify, function() {
                flushErrors();
                done();
              });
            } else {
              done(); // no files
            }
          });
        }
      };
    }
  };
  return self;
};

/**
 * The relative path to the traceur runtime
 * @type {string}
 */
module.exports.RUNTIME = es6ify.runtime.replace(process.cwd(), '').slice(1);
<commit_msg>fixed double callback problem in browserify stream<commit_after>var path            = require('path');
var through         = require('through2');
var trackFilenames  = require('gulp-track-filenames');
var transformTools  = require('browserify-transform-tools');
var browserify      = require('browserify');
var gutil           = require('gulp-util');
var es6ify          = require('es6ify');
var moldSourceMap   = require('mold-source-map');
var slash           = require('gulp-slash');

/**
 *
Find a unique list of parameters of functions immediately preceded by annotation

 */
function getAnnotatedParameters(annotation, text) {
  'use strict';
  var SPLIT       = /(\/\*|\*\/)/g; // split by and capture comments
  var FUNCTION    = /^[\r\n\s]*(?:(?:return|export|default|function)\s+)*(?:[\w\$]+\s*)?\(\s*(.*)\s*\)[\r\n\s]*\{/m;
  var result      = [ ];
  var isComment   = false;
  var isAnnotated = false;
  text.split(SPLIT).forEach(function(value) {
    switch(value) {

      // start comment block (or commented comment, which will split the comment text)
      case '/*':
        isComment = true;
        break;

      // end comment block
      case '*/':
        isComment = false;
        break;

      // text between
      default:

        // where comment text is split any annotation is accepted
        if (isComment) {
          isAnnotated = isAnnotated || (value.indexOf(annotation) >= 0);

        // code text will not be split
        } else if (isAnnotated) {
          var analysis = FUNCTION.exec(value);
          if (analysis) {

            // add function parameters uniquely to the pending list
            analysis[1].split(/\s*,\s*/).forEach(function (candidate) {
              if (result.indexOf(candidate) < 0) {
                result.push(candidate);
              }
            });
          }
          isAnnotated = false;
        }
    }
  });
  return result;
}

/**
 * @param {number} [bannerWidth] The width of banner comment, zero or omitted for none
 */
module.exports = function (bannerWidth) {
  'use strict';
  var sourcesFwd = trackFilenames();
  var sourcesInt = trackFilenames();
  var reserved   = [ ];
  var count      = 0;
  var self       = {

    /**
     * Mark source files in preparation for transpile.
     * Outputs a stream of the same files.
     * @returns {stream.Through} A through stream that performs the operation of a gulp stream
     */
    sources: function () {
      var sessionFwd = sourcesFwd.create();
      var sessionInt = sourcesInt.create();
      return through.obj(function (file, encoding, done) {
        var importName = file.relative.replace(path.extname(file.path), '');
        var zeroPadded = ((new Array(file.path.length)).join('0') + String(count++)).slice(file.path.length * -1);
        sessionFwd.define(file.path, importName);
        sessionInt.define(zeroPadded, file.path);
        this.push(file);
        done();
      });
    },

    /**
     * Detect @ngAnnotate comments immediately preceding methods and reserve their parameters
     * @returns {stream.Through} A through stream that performs the operation of a gulp stream
     */
    reserve: function() {
      var logging = [ ];

      // detect @ngInject tags and reserve function parameters
      return through.obj(function(file, encoding, done) {
        var ANNOTATION = '@ngInject';
        var pending = getAnnotatedParameters(ANNOTATION, file.contents.toString());
        if (pending.length) {
          pending.sort();
          var importName = file.relative.replace(path.extname(file.path), '');
          logging.push([ ANNOTATION, importName, pending.join(', ') ]);
        }
        pending.forEach(function(candidate) {
          if (reserved.indexOf(candidate) < 0) {
            reserved.push(candidate);
          }
        });
        done(null, file);

      // report to console last so that we can equalise column widths
      }, function(done) {
        var columnWidths = [ ];
        logging.forEach(function(line) {
          line.forEach(function(column, i) {
            columnWidths[i] = Math.max(column.length, (columnWidths[i] || 0));
          });
        });
        logging.forEach(function(line) {
          line.forEach(function(column, i, array) {
            while (array[i].length < columnWidths[i]) {
              array[i] += ' ';
            }
          });
          gutil.log.apply(gutil, line);
        });
        done();
      });
    },

    /**
     * Create a transform that makes the given replacements in jasmine files
     * @param {object} replacements Replacement text keyed by the jasmine string to match
     * @returns {Function} A browserify transform
     */
    getJasmineTransform: function (replacements) {
      var expressions = { };
      if (typeof replacements === 'object') {
        for (var key in replacements) {
          var source = '((?:describe|module)\\s*\\(\\s*)(?:\'' + key + '\'|"' + key + '")';
          expressions[source] = replacements[key];
        }
      }
      return function(filename) {
        var text = '';
        return through.obj(function(contents, encoding, done) {
          text += contents.toString();
          done();
        }, function(done) {
          var lines = text.split('\n');
          for (var source in expressions) {
            var expression = new RegExp(source, 'g');
            var target     = expressions[source];
            for (var i = 0; i < lines.length; i++) {
              var analysis;
              do {
                analysis = expression.exec(lines[i]);
                if (analysis) {
                  var line     = i + 1;
                  var char     = expression.lastIndex - analysis[0].length;
                  var isMethod = (typeof target === 'function');
                  var value    = isMethod ? target(filename, line, char) : target;
                  lines[i] =
                    lines[i].slice(0, char) + analysis[1] +
                    '\'' + String(value).replace(/\\/g, '\\\\') + '\'' +
                    lines[i].slice(expression.lastIndex);
                }
              } while (analysis);
              expression.lastIndex = 0;
            }
          }
          this.push(new Buffer(lines.join('\n')));
          done();
        });
      };
    },

    /**
     * ES6ify transform
     */
    es6ifyTransform: require('es6ify'),

    /**
     * Convert import paths to absolute file paths
     */
    requireTransform: transformTools.makeRequireTransform('requireTransform', null, function(args, opts, done) {
      return done(null, 'require("' + sourcesFwd.replace(args[0], '^', '$') + '")');
    }),

    /**
     * Use es6ify to compile the files of the input stream.
     * Use the sources previously identified to satisfy any module imports.
     * @param {...string|function} transforms Any number of browserify transforms
     * @returns {stream.Through} A through stream that performs the operation of a gulp stream
     */
    compile: function () {
      var transforms = Array.prototype.slice.call(arguments);
      var output     = [ ];

      /**
       * Flush the error queue to stdout
       */
      function flushErrors() {
        if (output.length > 0) {
          var width = Number(bannerWidth) || 0;
          var hr    = new Array(width + 1);   // this is a good trick to repeat a character N times
          var start = (width > 0) ? (hr.join('\u25BC') + '\n') : '';
          var stop  = (width > 0) ? (hr.join('\u25B2') + '\n') : '';
          process.stdout.write(start + '\n' + output.map(groupByFilename).join('\n') + '\n' + stop);
        }
      }

      /**
       * Mapping function that injects new-line return between dissimilar messages
       */
      function groupByFilename(value, i, array) {
        var current      = String(value).split(/\:\d+/).shift();
        var previous     = String(array[i-1]).split(/\:\d+/).shift();
        var isDissimilar = (i > 1) && (i < array.length) && (current !== previous);
        var result       = isDissimilar ? ('\n' + value) : value;
        return result;
      }

      /**
       * Determine the root relative form of the given file path
       * @param {string} filePath Full file path
       * @returns {string} Give path relative to process.cwd()
       */
      function rootRelative(filePath) {
        return '/' + slash(path.relative(process.cwd(), filePath));
      }

      /**
       * Compile any number of files into a bundle
       * @param {stream.Through} stream A stream to push files to
       * @param {Array.<string>|string} files Any number of files to bundle
       * @param {string} bundlename The name for the output file
       * @param {function|boolean} [minifiy] Determines whether minification is performed
       * @param {function} done Callback for completion
       */
      function bundle(stream, files, bundlename, minifiy, done) {

        // setup
        var cwd      = process.cwd();
        var outPath  = path.join(cwd, bundlename);
        var mapPath  = path.basename(bundlename) + '.map';
        var isMinify = (minifiy) && ((typeof minifiy !== 'function') || minifiy(bundlename));
        var bundler  = browserify({
          debug: true
        });

        // error handler
        var timeout;
        function errorHandler(error) {
          var text = error.toString();
          var analysis;
          var message;

          // Error: <file>:<line>:<column>: <reason>
          if (analysis = /^\s*Error\:\s*(.*\:\d+:\d+\:\s*[^:]*).*\s*$/.exec(text)) {
            message = analysis[1] + '\n';

          // Error: <reason> from '<file>'
          } else if (analysis = /^\s*Error\:\s*(.*)\s*from\s*\'(.*)\'\s*$/.exec(text)) {
            message = analysis[2] + ':0:0: ' + analysis[1] + '\n';

          // Unknown
          } else {
            message = 'TODO parse this error\n' + text + '\n';
          }

          // add unique
          if (output.indexOf(message) < 0) {
            output.push(message);
          }

          // complete overall only once there are no further errors
          clearTimeout(timeout);
          timeout = setTimeout(function() {
            if (done) {
              done();
              done = null;
            }
          }, 100);
        }

        // stream output
        function pushFileToStream(path, text) {
          stream.push(new gutil.File({
            cwd: cwd,
            base: cwd,
            path: path,
            contents: new Buffer(text)
          }));
        }

        // transforms
        transforms.concat(self.requireTransform).forEach(function (item) {
          bundler.transform(item);
        });

        // require statements
        [ ].concat(files).forEach(function (item) {
          bundler.require(item, { entry: true });
        });

        // minify requires callback style
        if (isMinify) {
          require('minifyify')(bundler, {
            map:    mapPath,
            uglify: {
              mangle: {
                toplevel: true,
                except:   reserved.join(',')
              }
            }
          });
          bundler.bundle(function (error, code, map) {
            if (!error) {
              var anonymised = sourcesInt.replace(code, '"', '"');  // anonymise module paths
              var sourcemap  = JSON.parse(map);
              sourcemap.sources = sourcemap.sources.map(rootRelative);
              delete sourcemap.file;
              delete sourcemap.sourcesContent;
              pushFileToStream(outPath + '.map', JSON.stringify(sourcemap, null, 2));
              pushFileToStream(outPath, anonymised);
            }
            done(); // complete overall
          })
            .on('error', errorHandler);

        // non-minify requires stream style
        } else {
          bundler.bundle()
            .on('error', errorHandler)
            .pipe(moldSourceMap.transform(function (molder, complete) {
              molder.mapSources(rootRelative);
              molder.sourcemap.setProperty('file');
              molder.sourcemap.setProperty('sourcesContent');
              molder.sourcemap.setProperty('sourceRoot');
              pushFileToStream(outPath + '.map', molder.sourcemap.toJSON(2));
              complete('//# sourceMappingURL=' + mapPath);
            }))
            .on('data', function (contents) {
              pushFileToStream(outPath, contents);
              done(); // complete overall
            });
        }
      }

      // return a set of streams
      return {

        /**
         * A stream that produces a bundle for each file in the stream
         * @param {function|boolean} [isMinify] Determines whether minification is performed
         * @returns {stream.Through}
         */
        each: function (isMinify) {
          return through.obj(function (file, encoding, done) {
            bundle(this, [ file.path ], file.relative, isMinify, done);
          }, function(done) {
            flushErrors();
            done();
          });
        },

        /**
         * A stream that produces a bundle containing all files in the stream
         * @param {string} outPath A relative path for the output file
         * @param {function|boolean} [isMinify] Determines whether minification is performed
         * @returns {stream.Through}
         */
        all: function (outPath, isMinify) {
          var pending = [ ];
          return through.obj(function (file, encoding, done) {
            pending.push(file.path);
            done();
          }, function (done) {
            if (pending.length) {
              bundle(this, pending, outPath, isMinify, function() {
                flushErrors();
                done();
              });
            } else {
              done(); // no files
            }
          });
        }
      };
    }
  };
  return self;
};

/**
 * The relative path to the traceur runtime
 * @type {string}
 */
module.exports.RUNTIME = es6ify.runtime.replace(process.cwd(), '').slice(1);
<|endoftext|>


<commit_before>exports.config = {
  sauceUser: process.env.SAUCE_USERNAME,
  sauceKey: process.env.SAUCE_ACCESS_KEY,
  framework: 'jasmine2',
  sauceSeleniumAddress: 'localhost:4444/wd/hub',
  baseUrl: 'http://localhost:2000',
  // Selector for the element housing the angular app - this defaults to
  // body, but is necessary if ng-app is on a descendant of <body>
  // solved intermintent fails
  rootElement: 'html',
  specs: ['*[sS]pec.js'],
  //  maxSessions: 1,
  multiCapabilities: [{
    browserName: 'chrome',
    platform: 'Windows 7',
  }, {
    browserName: 'firefox',
    platform: 'Windows 7',
  }, {
    browserName: 'internet explorer',
    platform: 'Windows 7',
    version: '9.0'
  }, {
    browserName: 'safari',
    platform: 'OS X 10.10',
  }],
  onPrepare: function() {
    browser.driver.manage().window().maximize();
    return browser.getCapabilities().then(function(cap) {
      browser.browserName = cap.caps_.browserName;
    });
  }
};
<commit_msg>port fix for spec<commit_after>exports.config = {
  sauceUser: process.env.SAUCE_USERNAME,
  sauceKey: process.env.SAUCE_ACCESS_KEY,
  framework: 'jasmine2',
  sauceSeleniumAddress: 'localhost:4444/wd/hub',
  baseUrl: 'http://localhost:8000',
  // Selector for the element housing the angular app - this defaults to
  // body, but is necessary if ng-app is on a descendant of <body>
  // solved intermintent fails
  rootElement: 'html',
  specs: ['*[sS]pec.js'],
  //  maxSessions: 1,
  multiCapabilities: [{
    browserName: 'chrome',
    platform: 'Windows 7',
  }, {
    browserName: 'firefox',
    platform: 'Windows 7',
  }, {
    browserName: 'internet explorer',
    platform: 'Windows 7',
    version: '9.0'
  }, {
    browserName: 'safari',
    platform: 'OS X 10.10',
  }],
  onPrepare: function() {
    browser.driver.manage().window().maximize();
    return browser.getCapabilities().then(function(cap) {
      browser.browserName = cap.caps_.browserName;
    });
  }
};
<|endoftext|>


<commit_before>(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else {
        root.sd = factory();
    }
}(this, function () {
<commit_msg>build: slightly improve start fragment<commit_after>(function (global, factory) {
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else {
        global.sd = factory();
    }
}(typeof window !== "undefined" ? window : this, function () {
<|endoftext|>


<commit_before>'use strict';

var redis = require("redis");

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

/**
 * Caching implementation that uses Redis as data storage.
 * @constructor
 * @param {string=} [host='localhost']
 * @param {number=} [port=6379]
 * @param {number=} [db=0]
 */
function RedisStore(opt){
  this._options = opt || {};
  this.redis = RedisStore._createClient(opt);
  this.redis.debug_mode = /redis/i.test(process.env.DEBUG);
}

RedisStore._createClient = function createRedisClient(opt){
  var conn = (opt && opt.connection) || {};
  return redis.createClient(conn.host, conn.port, opt.options);
};

RedisStore.prototype.get = function (key, cb){
  this.redis.get(key, function(err, entry){
    return cb(err, !entry ? null : CacheEntry.parse(JSON.parse(entry)));
  });
};

RedisStore.prototype.set = function (key, val, cb){
  var entry = JSON.stringify(val);
  this.redis.set(key, entry, cb);
  if (this._options.ttl){
    this.redis.expire(key, this._options.ttl);
  }
};

RedisStore.prototype.delete = function (key, cb){
  this.redis.del(key, cb);
};

RedisStore.prototype.clear = function (cb){
  this.redis.flushdb(cb);
};

RedisStore.prototype.size = function (cb){
  this.redis.dbsize(cb);
};

module.exports = RedisStore;<commit_msg>fix #45<commit_after>'use strict';

var redis = require("redis");

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

/**
 * Caching implementation that uses Redis as data storage.
 * @constructor
 * @param {string=} [host='localhost']
 * @param {number=} [port=6379]
 * @param {number=} [db=0]
 */
function RedisStore(opt){
  this._options = opt || {};
  this.redis = RedisStore._createClient(opt);
  this.redis.debug_mode = /redis/i.test(process.env.DEBUG);
}

RedisStore._createClient = function createRedisClient(opt){
  var conn = (opt && opt.connection) || {};
  return redis.createClient(conn.port, conn.host, opt.options);
};

RedisStore.prototype.get = function (key, cb){
  this.redis.get(key, function(err, entry){
    return cb(err, !entry ? null : CacheEntry.parse(JSON.parse(entry)));
  });
};

RedisStore.prototype.set = function (key, val, cb){
  var entry = JSON.stringify(val);
  this.redis.set(key, entry, cb);
  if (this._options.ttl){
    this.redis.expire(key, this._options.ttl);
  }
};

RedisStore.prototype.delete = function (key, cb){
  this.redis.del(key, cb);
};

RedisStore.prototype.clear = function (cb){
  this.redis.flushdb(cb);
};

RedisStore.prototype.size = function (cb){
  this.redis.dbsize(cb);
};

module.exports = RedisStore;<|endoftext|>


<commit_before>/* Helpers */

// Convert unix-timestamp to HH:MM format
function HHmm(time) {
	var dt = new Date(time * 1000);

	var hours = dt.getHours();
	var minutes = dt.getMinutes();

	if ( minutes < 10) {
		minutes = "0"+minutes;
	};
	if ( hours < 10) {
		hours = "0"+hours;
	};

	return hours +":"+ minutes;
};

function make_urls(text) {
	var regex = /(https?:\/\/[^\s]+)/g;
	var regex2 = /(.*).(jpg|gif|jpeg|png)$/;

	return text.replace(regex, function(url) {
		if (url.match(regex2)) {
			return '' + url + '';
		} else {
			return '' + url + '';
		};
	});
};
<commit_msg>refactoring<commit_after>/* Helpers */

// Convert unix-timestamp to HH:MM format
function HHmm(time) {
	var dt = new Date(time * 1000);

	var hours = dt.getHours();
	var minutes = dt.getMinutes();

	if ( minutes < 10) {
		minutes = "0"+minutes;
	};
	if ( hours < 10) {
		hours = "0"+hours;
	};

	return hours +":"+ minutes;
};

function make_urls(text) {
	var regex = /(https?:\/\/[^\s]+)/g;

	return text.replace(regex, function(url) {
		if (url.match(/(.*).(jpg|gif|jpeg|png)$/)) {
			return '' + url + '';
		} else {
			return '' + url + '';
		};
	});
};
<|endoftext|>


<commit_before>/**
 * We.js default controller prototype
 *
 * All controllers is instance of this Controller prototype and have all actions defined here
 */
var _ = require('lodash');

/**
 * Constructor
 */
function Controller(attrs) {
  for(var attr in attrs) {
    if (attrs[attr].bind) {
      this[attr] = attrs[attr].bind(this);
    } else {
      this[attr] = attrs[attr];
    }
  }
}

/**
 * Default find action
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.find = function findAll(req, res) {
  return res.locals.Model.findAndCountAll(res.locals.query)
  .then(function (record) {
    res.locals.metadata.count = record.count;
    res.locals.data = record.rows;
    return res.ok();
  }).catch(res.queryError);
}

/**
 * Default findOne action
 *
 * Record is preloaded in context loader by default and is avaible as res.locals.data
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.findOne = function findOne(req, res, next) {
  if (!res.locals.data) return next();
  return res.ok();
};

/**
 * Create and create page actions
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.create = function create(req, res) {
  if (!res.locals.template) res.locals.template = res.locals.model + '/' + 'create';

  if (!res.locals.data) res.locals.data = {};

   _.merge(res.locals.data, req.query);

  if (req.method === 'POST') {
    if (req.isAuthenticated()) req.body.creatorId = req.user.id;

    _.merge(res.locals.data, req.body);

    return res.locals.Model.create(req.body)
    .then(function (record) {
      res.locals.data = record;
      res.created();
    }).catch(res.queryError);
  } else {
    res.locals.data = req.query;
    res.ok();
  }
};

/**
 * Edit, edit page and update action
 *
 * Record is preloaded in context loader by default and is avaible as res.locals.data
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.edit = function edit(req, res) {
  if (!res.locals.template) res.locals.template = res.local.model + '/' + 'edit';

  var record = res.locals.data;

  if (req.we.config.updateMethods.indexOf(req.method) >-1) {
    if (!record) return res.notFound();

    record.updateAttributes(req.body)
    .then(function() {
      res.locals.data = record;
      return res.updated();
    }).catch(res.queryError);
  } else {
    res.ok();
  }
};

/**
 * Delete and delete action
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.delete = function deletePage(req, res) {
  if (!res.locals.template)
    res.locals.template = res.local.model + '/' + 'delete';

  var record = res.locals.data;
  if (!record) return res.notFound();

  res.locals.deleteMsg = res.locals.model+'.delete.confirm.msg';

  if (req.method === 'POST' || req.method === 'DELETE') {
    record.destroy().then(function() {
      res.locals.deleted = true;
      return res.deleted();
    }).catch(res.queryError);
  } else {
    return res.ok();
  }
}

// TODO
//
// Controller.prototype.getAttribute = function getAttribute(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.updateAttribute = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.deleteAttribute = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.addRecord = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.removeRecord = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.getRecord = function(req, res, next) {
//   console.log('TODO');  next();
// };

module.exports = Controller;
<commit_msg>remove uneed query param setter in default record create<commit_after>/**
 * We.js default controller prototype
 *
 * All controllers is instance of this Controller prototype and have all actions defined here
 */
var _ = require('lodash');

/**
 * Constructor
 */
function Controller(attrs) {
  for(var attr in attrs) {
    if (attrs[attr].bind) {
      this[attr] = attrs[attr].bind(this);
    } else {
      this[attr] = attrs[attr];
    }
  }
}

/**
 * Default find action
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.find = function findAll(req, res) {
  return res.locals.Model.findAndCountAll(res.locals.query)
  .then(function (record) {
    res.locals.metadata.count = record.count;
    res.locals.data = record.rows;
    return res.ok();
  }).catch(res.queryError);
}

/**
 * Default findOne action
 *
 * Record is preloaded in context loader by default and is avaible as res.locals.data
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.findOne = function findOne(req, res, next) {
  if (!res.locals.data) return next();
  return res.ok();
};

/**
 * Create and create page actions
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.create = function create(req, res) {
  if (!res.locals.template) res.locals.template = res.locals.model + '/' + 'create';

  if (!res.locals.data) res.locals.data = {};

  if (req.method === 'POST') {
    if (req.isAuthenticated()) req.body.creatorId = req.user.id;

    _.merge(res.locals.data, req.body);

    return res.locals.Model.create(req.body)
    .then(function (record) {
      res.locals.data = record;
      res.created();
    }).catch(res.queryError);
  } else {
    res.locals.data = req.query;
    res.ok();
  }
};

/**
 * Edit, edit page and update action
 *
 * Record is preloaded in context loader by default and is avaible as res.locals.data
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.edit = function edit(req, res) {
  if (!res.locals.template) res.locals.template = res.local.model + '/' + 'edit';

  var record = res.locals.data;

  if (req.we.config.updateMethods.indexOf(req.method) >-1) {
    if (!record) return res.notFound();

    record.updateAttributes(req.body)
    .then(function() {
      res.locals.data = record;
      return res.updated();
    }).catch(res.queryError);
  } else {
    res.ok();
  }
};

/**
 * Delete and delete action
 *
 * @param  {Object} req express.js request
 * @param  {Object} res express.js response
 */
Controller.prototype.delete = function deletePage(req, res) {
  if (!res.locals.template)
    res.locals.template = res.local.model + '/' + 'delete';

  var record = res.locals.data;
  if (!record) return res.notFound();

  res.locals.deleteMsg = res.locals.model+'.delete.confirm.msg';

  if (req.method === 'POST' || req.method === 'DELETE') {
    record.destroy().then(function() {
      res.locals.deleted = true;
      return res.deleted();
    }).catch(res.queryError);
  } else {
    return res.ok();
  }
}

// TODO
//
// Controller.prototype.getAttribute = function getAttribute(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.updateAttribute = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.deleteAttribute = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.addRecord = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.removeRecord = function(req, res, next) {
//   console.log('TODO');  next();
// };

// Controller.prototype.getRecord = function(req, res, next) {
//   console.log('TODO');  next();
// };

module.exports = Controller;
<|endoftext|>


<commit_before>var gateway = require(__dirname+'/../../');

module.exports = gateway.api.stop;

<commit_msg>[FIX] Actually stop gatewayd processes.<commit_after>var gateway = require(__dirname+'/../../');

module.exports = gateway.api.stopGateway;

<|endoftext|>