<commit_before>describe('Dancer', function () {

  var
    dancer = null,
    song  = 'lib/test.ogg';

  beforeEach(function () {
    dancer = new Dancer(song);
  });

  afterEach(function () {
    dancer.stop();
  });

  // TODO WTF http://www.w3.org/2011/audio/track/issues/3?changelog
  it('WEBKIT CANNOT DELETE AUDIO CONTEXTS?', function () {
    expect(navigator.userAgent.match(/WebKit/)).toBeFalsy();
  });

  describe('Init', function () {
    it('Should use the correct audio adapter', function () {
      var adapter = navigator.userAgent.match(/WebKit/) ?
        Dancer.adapters.webkit :
        Dancer.adapters.moz;
      expect(dancer.audioAdapter instanceof adapter).toBeTruthy();
    });

    it('Should bind an update event', function () {
      expect(dancer.events.update).toBeDefined();
    });
  });

  describe('Controls', function () {
    it("Should call adapter's play/stop method via dancer.play(), dancer.stop()", function () {
      spyOn(dancer.audioAdapter, 'play');
      spyOn(dancer.audioAdapter, 'stop');
      dancer.play();
      expect(dancer.audioAdapter.play).toHaveBeenCalled();
      dancer.stop();
      expect(dancer.audioAdapter.stop).toHaveBeenCalled();
    });

    it("Should return dancer instance when calling dancer.play(), dancer.stop()", function() {
      var
        playReturn = dancer.play(),
        stopReturn = dancer.stop();
      expect(playReturn).toBe(dancer);
      expect(stopReturn).toBe(dancer);
    });
  });

  describe('Create Beat', function () {

  });

  // TODO async test for getTime();
  describe('Getters', function () {
    it("Should call adapter's getTime() function from getTime()", function () {
      dancer.play();
      spyOn(dancer.audioAdapter, 'getTime');

      waitsFor(function () {
        return dancer.isLoaded();
      }, 'Song was never loaded', 3000);

      runs(function () {
        var t = dancer.getTime();
        expect(dancer.audioAdapter.getTime).toHaveBeenCalled();
        expect(t).toBeGreaterThan(0);
      });
    });

    it("Should call audioAdapter's getSpectrum() method from spectrum()", function () {
      spyOn(dancer.audioAdapter, 'getSpectrum');
      dancer.spectrum();
      expect(dancer.audioAdapter.getSpectrum).toHaveBeenCalled();
    });

    it("Should call adapter's loaded boolean from isLoaded()", function () {
      dancer.audioAdapter.loaded = true;
      expect(dancer.isLoaded()).toBeTruthy();
      dancer.audioAdapter.loaded = false;
      expect(dancer.isLoaded()).toBeFalsy();
    });

    it("Should return the magnitude of the spectrum via frequency(x), and average for frequency(x,y)", function () {
      var mockSpectrum = [ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ];
      dancer.spectrum = function() { return mockSpectrum; };
      expect(dancer.frequency(3)).toEqual(8);
      expect(dancer.frequency(3, 7)).toEqual(10);
    });

  });

  // TODO async tests for sections
  describe('Sections', function () {

  });

  // TODO test the prebindings of 'update' and 'loaded'
  describe('Pub/Sub Bindings', function () {
    var
      fn1 = jasmine.createSpy(),
      fn2 = jasmine.createSpy(),
      fn3 = jasmine.createSpy();

    beforeEach(function () {
        dancer.bind('eventA', fn1);
        dancer.bind('eventA', fn2);
        dancer.bind('eventB', fn3);
    });

    describe('Bind', function () {
      it('Should bind several events under the same name and different names', function () {
        expect(dancer.events.eventA[0]).toBe(fn1);
        expect(dancer.events.eventA[1]).toBe(fn2);
        expect(dancer.events.eventB[0]).toBe(fn3);
      });
    });

    describe('Unbind', function () {
      it('Should unbind all events of a shared name', function () {
        dancer.unbind('eventA');
        expect(dancer.events.eventA).toBeFalsy();
        expect(dancer.events.eventB[0]).toBe(fn3);
      });
    });

    describe('Trigger', function () {
      it('Should call all events of a shared name, and no others', function () {
        dancer.trigger('eventA');
        expect(fn1).toHaveBeenCalled();
        expect(fn2).toHaveBeenCalled();
        expect(fn3).not.toHaveBeenCalled();
      });
    });
  });

  describe('Add Plugin', function () {
    it('Should add a method to the prototype if not in the chain', function () {
      var fn = jasmine.createSpy();
      Dancer.addPlugin('pluginname', fn);
      dancer.pluginname('arggg');
      expect(fn).toHaveBeenCalledWith('arggg');
    });

    it('Should pass the dancer instance as the "this" context', function () {
      Dancer.addPlugin('pluginname2', function() { return this; });
      expect(dancer.pluginname2()).toBe(dancer);
    });

    it('Should not allow a rebinding of a preexisting prototype method or plugin', function () {
      var
        origMethod = Dancer.prototype.play,
        newMethod = function() { };
      Dancer.addPlugin('play', newMethod);
      Dancer.addPlugin('pluginname', newMethod); // Used in previous test
      expect(dancer.play).toBe(origMethod);
      expect(dancer.pluginname).not.toBe(newMethod);
    });
  });
});
<commit_msg>Clean up specs, good tests for frequency/spectrum, implicit testing of getTime(), isLoaded()<commit_after>describe('Dancer', function () {

  var
    song  = 'lib/440hz_100amp.ogg',
    dancer = new Dancer(song);

/*
  beforeEach(function () {
    dancer = new Dancer(song);
  });

  afterEach(function () {
    dancer.stop();
  });
*/
  // TODO WTF http://www.w3.org/2011/audio/track/issues/3?changelog
  it('WEBKIT CANNOT DELETE AUDIO CONTEXTS?', function () {
    expect(navigator.userAgent.match(/WebKit/)).toBeFalsy();
  });

  describe('Init', function () {
    it('Should use the correct audio adapter', function () {
      var adapter = navigator.userAgent.match(/WebKit/) ?
        Dancer.adapters.webkit :
        Dancer.adapters.moz;
      expect(dancer.audioAdapter instanceof adapter).toBeTruthy();
    });

    it('Should bind an update event', function () {
      expect(dancer.events.update).toBeDefined();
    });
  });

  describe('Controls', function () {
    it("Should call adapter's play/stop method via dancer.play(), dancer.stop()", function () {
      spyOn(dancer.audioAdapter, 'play');
      spyOn(dancer.audioAdapter, 'stop');
      dancer.play();
      expect(dancer.audioAdapter.play).toHaveBeenCalled();
      dancer.stop();
      expect(dancer.audioAdapter.stop).toHaveBeenCalled();
    });

    it("Should return dancer instance when calling dancer.play(), dancer.stop()", function() {
      var
        playReturn = dancer.play(),
        stopReturn = dancer.stop();
      expect(playReturn).toBe(dancer);
      expect(stopReturn).toBe(dancer);
    });
  });

  describe('Create Beat', function () {

  });

  // TODO async test for getTime();
  describe('Getters', function () {
    it("getTime() should return current time", function () {
      dancer.play();

      waitsFor(function () {
        return dancer.isLoaded() && dancer.getTime() > 1;
      }, 'Song was never loaded', 4000);

      // TODO should compare with audio file's time
      runs(function () {

      });
    });

    describe("getSpectrum()", function () {
      var s;
      waitsFor(function () {
        return dancer.isLoaded() && dancer.getTime() > 1;
      }, 'Song never progressed', 3000);

      runs(function () {
        it("should return a Float32Array(1024)", function () {
          s = dancer.getSpectrum();
          expect(s.length).toEqual(1024);
          expect(s instanceof Float32Array).toBeTruthy();
        });

        it("should return a correct amplitude for the 440hz pitch (11/1024)", function () {
          s= dancer.getSpectrum()[10];
          expect(s).toBeGreaterThan(0.5);
          expect(s).toBeLessThan(1);
        });

        it("should return a correct amplitude for the 440hz pitch (51/1024)", function () {
          s = dancer.getSpectrum()[50];
          expect(s).toBeLessThan(0.1);
        });
      });
    });

    describe("getFrequency()", function () {
      var f;
      waitsFor(function () {
        return dancer.isLoaded() && dancer.getTime() > 1;
      }, 'Song never progressed', 3000);

      runs(function () {
        it("should return a correct amplitude for the 440hz pitch (11/1024)", function () {
          f = dancer.getFrequency(10);
          expect(f).toBeGreaterThan(0.5);
        });

        it("should return a correct amplitude for the 440hz pitch (51/1024)", function () {
          f = dancer.getFrequency(50);
          expect(f).toBeLessThan(0.1);
        });

        it("Should return the average amplitude over a range of the 440hz pitch", function () {
          f = dancer.getFrequency(10, 50);
          expect(f).toBeGreaterThan(0.04);
          expect(f).toBeLessThan(0.07);
        });
      });
    });

    // Also tested implicitly via other tests
    it("Should call adapter's loaded boolean from isLoaded()", function () {
      dancer.audioAdapter.loaded = true;
      expect(dancer.isLoaded()).toBeTruthy();
      dancer.audioAdapter.loaded = false;
      expect(dancer.isLoaded()).toBeFalsy();
    });
  });

  // TODO async tests for sections
  describe('Sections', function () {

  });

  describe('Pub/Sub Bindings', function () {
    var
      fn1 = jasmine.createSpy(),
      fn2 = jasmine.createSpy(),
      fn3 = jasmine.createSpy(),
      fn4 = jasmine.createSpy();

    beforeEach(function () {
      dancer.bind('eventA', fn1);
      dancer.bind('eventA', fn2);
      dancer.bind('eventB', fn3);
      dancer.bind('update', fn4);
    });

    describe('Bind', function () {
      it('Should bind several events under the same name and different names', function () {
        expect(dancer.events.eventA[0]).toBe(fn1);
        expect(dancer.events.eventA[1]).toBe(fn2);
        expect(dancer.events.eventB[0]).toBe(fn3);
      });
    });

    describe('Unbind', function () {
      it('Should unbind all events of a shared name', function () {
        dancer.unbind('eventA');
        expect(dancer.events.eventA).toBeFalsy();
        expect(dancer.events.eventB[0]).toBe(fn3);
      });
    });

    describe('Trigger', function () {
      it('Should call all events of a shared name, and no others', function () {
        dancer.trigger('eventA');
        expect(fn1).toHaveBeenCalled();
        expect(fn2).toHaveBeenCalled();
        expect(fn3).not.toHaveBeenCalled();
      });
    });

    describe('Update Trigger', function () {
      it('Should trigger update events as the audio plays', function () {
        expect(fn4).toHaveBeenCalled();
      });
    });
  });

  describe('Add Plugin', function () {
    it('Should add a method to the prototype if not in the chain', function () {
      var fn = jasmine.createSpy();
      Dancer.addPlugin('pluginname', fn);
      dancer.pluginname('arggg');
      expect(fn).toHaveBeenCalledWith('arggg');
    });

    it('Should pass the dancer instance as the "this" context', function () {
      Dancer.addPlugin('pluginname2', function() { return this; });
      expect(dancer.pluginname2()).toBe(dancer);
    });

    it('Should not allow a rebinding of a preexisting prototype method or plugin', function () {
      var
        origMethod = Dancer.prototype.play,
        newMethod = function() { };
      Dancer.addPlugin('play', newMethod);
      Dancer.addPlugin('pluginname', newMethod); // Used in previous test
      expect(dancer.play).toBe(origMethod);
      expect(dancer.pluginname).not.toBe(newMethod);
    });
  });
});
<|endoftext|>


<commit_before>import Ember from 'ember';

var computed = Ember.computed;
var alias = computed.alias;

/**
 * @class GoogleMapMarkerController
 * @extends Ember.Controller
 */
export default Ember.Controller.extend({
  title:                  alias('model.title'),
  opacity:                alias('model.opacity'),
  zIndex:                 alias('model.zIndex'),
  isVisible:              alias('model.isVisible'),
  isDraggable:            alias('model.isDraggable'),
  isClickable:            alias('model.isClickable'),
  isOptimized:            alias('model.isOptimized'),
  icon:                   alias('model.icon'),
  lat:                    alias('model.lat'),
  lng:                    alias('model.lng'),
  infoWindowTemplateName: alias('model.infoWindowTemplateName'),
  isInfoWindowVisible:    alias('model.isInfoWindowVisible'),
  hasInfoWindow:          alias('model.hasInfoWindow')
});
<commit_msg>alias marker.description<commit_after>import Ember from 'ember';

var computed = Ember.computed;
var alias = computed.alias;

/**
 * @class GoogleMapMarkerController
 * @extends Ember.Controller
 */
export default Ember.Controller.extend({
  title:                  alias('model.title'),
  description:            alias('model.description'),
  opacity:                alias('model.opacity'),
  zIndex:                 alias('model.zIndex'),
  isVisible:              alias('model.isVisible'),
  isDraggable:            alias('model.isDraggable'),
  isClickable:            alias('model.isClickable'),
  isOptimized:            alias('model.isOptimized'),
  icon:                   alias('model.icon'),
  lat:                    alias('model.lat'),
  lng:                    alias('model.lng'),
  infoWindowTemplateName: alias('model.infoWindowTemplateName'),
  isInfoWindowVisible:    alias('model.isInfoWindowVisible'),
  hasInfoWindow:          alias('model.hasInfoWindow')
});
<|endoftext|>


<commit_before>export default class DataCleaner {

  adjustNames(node) {
    if (node.kind === 'anonymous class' && node.name === '$anon') {
      node.name = 'unnamed class';
      node.displayName = node.name;
    }

    if (node.kind === 'value' && node.name.indexOf('qual$') === 0) {
      node.name = 'unnamed value';
      node.displayName = node.name;
    }

    if (node.kind === 'constructor' && node.name === '<init>') {
      node.name = 'constructor';
      node.displayName = node.name;
    }

    if (node.kind === 'method' && node.name.indexOf('<init>$default$') === 0) {
      node.name = 'default argument';
      node.displayName = node.name;
    }

    if (node.kind === 'value' && node.name.indexOf('x0$') === 0) { // a block argument
      node.name = 'a block argument';
      node.displayName = node.name;
    }

    if (node.kind === 'lazy value') { // because showing laziness seems a little over of scope...
      node.kind = 'value';
    }
  }

  clean(nodes) {
    nodes.forEach(node => this.adjustNames(node));
    return nodes;
  }

}
<commit_msg>add one more condition to node naming<commit_after>export default class DataCleaner {

  adjustNames(node) {
    if (node.kind === 'anonymous class' && node.name === '$anon') {
      node.name = 'unnamed class';
      node.displayName = node.name;
    }

    if (node.kind === 'value' && node.name.indexOf('qual$') === 0) {
      node.name = 'unnamed value';
      node.displayName = node.name;
    }

    if (node.kind === 'constructor' && node.name === '<init>') {
      node.name = 'constructor';
      node.displayName = node.name;
    }

    if (node.kind === 'method' && node.name.indexOf('<init>$default$') === 0) {
      node.name = 'default argument';
      node.displayName = node.name;
    }

    if (node.kind === 'value' && node.name.indexOf('x0$') === 0) { // a block argument
      node.name = 'a block argument';
      node.displayName = node.name;
    }

    if (node.kind === 'lazy value') { // because showing laziness seems a little over of scope...
      node.kind = 'value';
    }

    if (node.displayName === undefined) {
      node.displayName = node.kind + ' ' + node.name;
    }
  }

  clean(nodes) {
    nodes.forEach(node => this.adjustNames(node));
    return nodes;
  }

}
<|endoftext|>


<commit_before>'use strict'

var ui = require('../utils/ui')

var $ = window.jQuery

module.exports = HeadFoot

/**
 * Abstract class to inherit Header and Footer sub classes from.
 * @constructor
 * @param {Editor} editor The current editor
 * @param {DOMElement} documentBody The document body for this documentBody
 * @param {DOMNode} [existingElement] The optional existing element that constitute a header of a footer and should be loaded from it
 * @property {Editor} _editor The current editor
 * @property {DOMElement}  _documentBody The body element of the current document
 * @property {DOMNode} node The header/footer's node element
 */
function HeadFoot (editor, documentBody, existingElement) {
  // bind useful vars
  var that = this
  this._editor = editor
  this._documentBody = documentBody
  this.pluginPaginate = editor.plugins.paginate

  // load the existing element if it exists or create a new one.
  if (existingElement) {
    this.node = existingElement
  } else {
    this._createNode()
  }

  var $thisNode = $(this.node)
  // live the node and implements the double click handler to switch the contentEditable mode.
  this.isActive = false
  this.liveNode()
  $thisNode.dblclick(this.enterNode.bind(this))
  $(this._documentBody).on('EnterNode', function (evt) {
    if (that.node !== evt.target) {
      that.liveNode()
    }
  })
}

/**
 * Create a new node for an header or a footer.
 * @private
 * @method
 */
HeadFoot.prototype._createNode = function () {
  var placeholder = '
'
  placeholder += 'Double-click to edit this content'
  placeholder += '
'

  this.node = $('
')
    .attr('data-headfoot', true)
    .attr('data-headfoot-pristine', true)
    .html(placeholder)[0]
}

/**
 * Disable the page edition and enable the edition for the header or the footers
 * @method
 * @returns void
 */
HeadFoot.prototype.enterNode = function () {
  var that = this
  var headfootContent
  var currentPageContent
  var $thisNode = $(this.node)

  this.isActive = true
  $thisNode.trigger('EnterNode', this.node)

  // disable paginator watching
  if (this.pluginPaginate) {
    this.pluginPaginate.disableWatchPage()

    // toggle elements states (contentEditable or not)
    $.each(this.pluginPaginate.paginator.getPages(), function () {
      ui.lockNode.call(this)
    })
  }

  ui.unlockNode.call(this.node)

  // select the unlocked node content or not
  headfootContent = this.node.firstChild
  if (!headfootContent) {
    throw new Error('no child is not allowed in a headfoot')
  }
  this._editor.selection.select(headfootContent)
  this._editor.selection.collapse(true)
  if ($thisNode.attr('data-headfoot-pristine')) {
    $thisNode.removeAttr('data-headfoot-pristine')
  }

  if (this.pluginPaginate) {
    // bind a click handler to the current page to toggle contentEditable state between header/footer and the page
    currentPageContent = this.pluginPaginate.getCurrentPage().content()
    $(currentPageContent).click(that.liveNode.bind(that))
  }
}

/**
 * Do the inverse of .enterNode(). Disable edition for the header or footer, and re-enable it for the current page.
 * @method
 * @returns void
 */
HeadFoot.prototype.liveNode = function () {
  this.isActive = false
  $(this.node).trigger('LiveNode', this.node)
  if (this.pluginPaginate) {
    this.pluginPaginate.enableWatchPage()
    $.each(this.pluginPaginate.paginator.getPages(), function () {
      ui.unlockNode.call(this)
    })
  }
  ui.lockNode.call(this.node)
}
<commit_msg>do not enter in a node if it is already active<commit_after>'use strict'

var ui = require('../utils/ui')

var $ = window.jQuery

module.exports = HeadFoot

/**
 * Abstract class to inherit Header and Footer sub classes from.
 * @constructor
 * @param {Editor} editor The current editor
 * @param {DOMElement} documentBody The document body for this documentBody
 * @param {DOMNode} [existingElement] The optional existing element that constitute a header of a footer and should be loaded from it
 * @property {Editor} _editor The current editor
 * @property {DOMElement}  _documentBody The body element of the current document
 * @property {DOMNode} node The header/footer's node element
 */
function HeadFoot (editor, documentBody, existingElement) {
  // bind useful vars
  var that = this
  this._editor = editor
  this._documentBody = documentBody
  this.pluginPaginate = editor.plugins.paginate

  // load the existing element if it exists or create a new one.
  if (existingElement) {
    this.node = existingElement
  } else {
    this._createNode()
  }

  var $thisNode = $(this.node)
  // live the node and implements the double click handler to switch the contentEditable mode.
  this.isActive = false
  this.liveNode()
  $thisNode.dblclick(this.enterNode.bind(this))
  $(this._documentBody).on('EnterNode', function (evt) {
    if (that.node !== evt.target) {
      that.liveNode()
    }
  })
}

/**
 * Create a new node for an header or a footer.
 * @private
 * @method
 */
HeadFoot.prototype._createNode = function () {
  var placeholder = '
'
  placeholder += 'Double-click to edit this content'
  placeholder += '
'

  this.node = $('
')
    .attr('data-headfoot', true)
    .attr('data-headfoot-pristine', true)
    .html(placeholder)[0]
}

/**
 * Disable the page edition and enable the edition for the header or the footers
 * @method
 * @returns void
 */
HeadFoot.prototype.enterNode = function () {
  if (!this.isActive) {
    var that = this
    var headfootContent
    var currentPageContent
    var $thisNode = $(this.node)

    this.isActive = true
    $thisNode.trigger('EnterNode', this.node)

    // disable paginator watching
    if (this.pluginPaginate) {
      this.pluginPaginate.disableWatchPage()

      // toggle elements states (contentEditable or not)
      $.each(this.pluginPaginate.paginator.getPages(), function () {
        ui.lockNode.call(this)
      })
    }

    ui.unlockNode.call(this.node)

    // select the unlocked node content or not
    headfootContent = this.node.firstChild
    if (!headfootContent) {
      throw new Error('no child is not allowed in a headfoot')
    }
    this._editor.selection.select(headfootContent)
    this._editor.selection.collapse(true)
    if ($thisNode.attr('data-headfoot-pristine')) {
      $thisNode.removeAttr('data-headfoot-pristine')
    }

    if (this.pluginPaginate) {
      // bind a click handler to the current page to toggle contentEditable state between header/footer and the page
      currentPageContent = this.pluginPaginate.getCurrentPage().content()
      $(currentPageContent).click(that.liveNode.bind(that))
    }
  }
}

/**
 * Do the inverse of .enterNode(). Disable edition for the header or footer, and re-enable it for the current page.
 * @method
 * @returns void
 */
HeadFoot.prototype.liveNode = function () {
  this.isActive = false
  $(this.node).trigger('LiveNode', this.node)
  if (this.pluginPaginate) {
    this.pluginPaginate.enableWatchPage()
    $.each(this.pluginPaginate.paginator.getPages(), function () {
      ui.unlockNode.call(this)
    })
  }
  ui.lockNode.call(this.node)
}
<|endoftext|>


<commit_before>'use strict'

var ui = require('../utils/ui')

var $ = window.jQuery

module.exports = HeadFoot

/**
 * Abstract class to inherit Header and Footer sub classes from.
 * @constructor
 * @param {Editor} editor The current editor
 * @param {DOMElement} documentBody The document body for this documentBody
 * @param {DOMNode} [existingElement] The optional existing element that constitute a header of a footer and should be loaded from it
 * @property {Editor} _editor The current editor
 * @property {DOMElement}  _documentBody The body element of the current document
 * @property {DOMNode} node The header/footer's node element
 */
function HeadFoot (editor, documentBody, existingElement) {
  // bind useful vars
  var that = this
  this._editor = editor
  this._documentBody = documentBody

  // load the existing element if it exists or create a new one.
  if (existingElement) {
    this.node = existingElement
  } else {
    this._createNode()
  }

  // live the node and implements the double click handler to switch the contentEditable mode.
  this.liveNode()
  $(this.node).dblclick(function () {
    console.log('double click on node', that.node)
    that.enterNode()
  })
}

/**
 * Create a new node for an header or a footer.
 * @private
 * @method
 */
HeadFoot.prototype._createNode = function () {
  this.node = $('<section>')
    .attr('data-headfoot', true)
    .attr('data-headfoot-pristine', true)
    .html('Double-click to edit this content')[0]
}

/**
 * Disable the page edition and enable the edition for the header or the footers
 * @method
 * @returns void
 */
HeadFoot.prototype.enterNode = function () {
  var that = this
  var headfootContent
  var currentPageContent

  this._editor.plugins.paginate.disableWatchPage()
  ui.lockNode.call(this._editor.plugins.paginate.getCurrentPage().content())
  ui.unlockNode.call(this.node)

  headfootContent = this.node.firstChild
  if (!headfootContent) {
    throw new Error('no child is not allowed in a headfoot')
  }
  this._editor.selection.select(headfootContent)
  if ($(this.node).attr('data-headfoot-pristine')) {
    // this._editor.selection.setContent('')
    $(this.node).removeAttr('data-headfoot-pristine')
  } else {
    this._editor.selection.collapse(true)
  }
  console.log('configure livenode', this._editor.plugins.paginate.getCurrentPage().content())
  currentPageContent = this._editor.plugins.paginate.getCurrentPage().content()
  $(currentPageContent).click(function () {
    console.log('paginate.getCurrentPage().content() clicked')
    that.liveNode()
  })
}

/**
 * Do the inverse of .enterNode(). Disable edition for the header or footer, and re-enable it for the current page.
 * @method
 * @returns void
 */
HeadFoot.prototype.liveNode = function () {
  console.info('living node'); console.log(this.node)
  this._editor.plugins.paginate.enableWatchPage()
  ui.lockNode.call(this.node)
  ui.unlockNode.call(this._editor.plugins.paginate.getCurrentPage().content())
}
<commit_msg>remove dev logs<commit_after>'use strict'

var ui = require('../utils/ui')

var $ = window.jQuery

module.exports = HeadFoot

/**
 * Abstract class to inherit Header and Footer sub classes from.
 * @constructor
 * @param {Editor} editor The current editor
 * @param {DOMElement} documentBody The document body for this documentBody
 * @param {DOMNode} [existingElement] The optional existing element that constitute a header of a footer and should be loaded from it
 * @property {Editor} _editor The current editor
 * @property {DOMElement}  _documentBody The body element of the current document
 * @property {DOMNode} node The header/footer's node element
 */
function HeadFoot (editor, documentBody, existingElement) {
  // bind useful vars
  var that = this
  this._editor = editor
  this._documentBody = documentBody

  // load the existing element if it exists or create a new one.
  if (existingElement) {
    this.node = existingElement
  } else {
    this._createNode()
  }

  // live the node and implements the double click handler to switch the contentEditable mode.
  this.liveNode()
  $(this.node).dblclick(function () {
    console.log('double click on node', that.node)
    that.enterNode()
  })
}

/**
 * Create a new node for an header or a footer.
 * @private
 * @method
 */
HeadFoot.prototype._createNode = function () {
  this.node = $('<section>')
    .attr('data-headfoot', true)
    .attr('data-headfoot-pristine', true)
    .html('Double-click to edit this content')[0]
}

/**
 * Disable the page edition and enable the edition for the header or the footers
 * @method
 * @returns void
 */
HeadFoot.prototype.enterNode = function () {
  var that = this
  var headfootContent
  var currentPageContent

  this._editor.plugins.paginate.disableWatchPage()
  ui.lockNode.call(this._editor.plugins.paginate.getCurrentPage().content())
  ui.unlockNode.call(this.node)

  headfootContent = this.node.firstChild
  if (!headfootContent) {
    throw new Error('no child is not allowed in a headfoot')
  }
  this._editor.selection.select(headfootContent)
  if ($(this.node).attr('data-headfoot-pristine')) {
    // this._editor.selection.setContent('')
    $(this.node).removeAttr('data-headfoot-pristine')
  } else {
    this._editor.selection.collapse(true)
  }
  console.log('configure livenode', this._editor.plugins.paginate.getCurrentPage().content())
  currentPageContent = this._editor.plugins.paginate.getCurrentPage().content()
  $(currentPageContent).click(function () {
    console.log('paginate.getCurrentPage().content() clicked')
    that.liveNode()
  })
}

/**
 * Do the inverse of .enterNode(). Disable edition for the header or footer, and re-enable it for the current page.
 * @method
 * @returns void
 */
HeadFoot.prototype.liveNode = function () {
  this._editor.plugins.paginate.enableWatchPage()
  ui.lockNode.call(this.node)
  ui.unlockNode.call(this._editor.plugins.paginate.getCurrentPage().content())
}
<|endoftext|>


<commit_before>const exEuclidean = require('./extended_euclidean');
const fastExp = require('./fast_exp');

/**
 * Calculates modular inverse of a number
 *
 * @param  {Number} a Number for which inverse needs to be found
 * @param  {Number} m Mod val
 * @return {Number}   Modular Inverse
 */
const modularInverse = (a, m) => {
  const result = exEuclidean(a, m);
  if (result.gcd !== 1) {
    return null;
  }

  console.log(result);

  return (result.x + m) % m;
};

module.exports = modularInverse;

/**
 * Calculates modular inverse of a number using Fermet's theorem
 *
 * @param  {Number} a Number for which inverse needs to be found
 * @param  {Number} m Mod val
 * @return {Number}   Modular Inverse
 */
const fermetModularInverse = (a, m) => fastExp(a, m - 2, m);

module.exports = fermetModularInverse;
<commit_msg>Modular Inverse: Fix modular bugs<commit_after>const exEuclidean = require('./extended_euclidean');
const fastExp = require('./fast_exp');

/**
 * Calculates modular inverse of a number using Fermet's theorem
 *
 * @param  {Number} a Number for which inverse needs to be found
 * @param  {Number} m Mod val
 * @return {Number}   Modular Inverse
 */
const fermetModularInverse = (a, m) => {
  if (a === 0 || m === 0) {
    return null;
  }

  return fastExp(a, m - 2, m);
};

/**
 * Calculates modular inverse of a number
 *
 * @param  {Number} a Number for which inverse needs to be found
 * @param  {Number} m Mod val
 * @return {Number}   Modular Inverse
 */
const modularInverse = (a, m) => {
  if (a === 0 || m === 0) {
    return null;
  }

  const result = exEuclidean(a, m);

  if (result.gcd !== 1) {
    return null;
  }

  return (result.x + m) % m;
};

module.exports = {
  fermetModularInverse,
  modularInverse
};
<|endoftext|>


<commit_before>export default class Directory {
  getUsers(directoryUrl, filterFunction) {
    return fetch(directoryUrl)
      .then(res => res.json())
      .then(users => {
        if (filterFunction) {
          return users.filter(x => filterFunction(x));
        }

        return users;
      });
  }
}
<commit_msg>Use same-origin credentials when fetching directory info<commit_after>export default class Directory {
  getUsers(directoryUrl, filterFunction) {
    return fetch(directoryUrl, {
      credentials: 'same-origin'
    })
      .then(res => res.json())
      .then(users => {
        if (filterFunction) {
          return users.filter(x => filterFunction(x));
        }

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


<commit_before>/*
 * Directive to enable the permissions required for the app to function properly.
 */

angular.module('emission.appstatus.permissioncheck',
    [])
.directive('permissioncheck', function() {
    return {
        scope: {
        },
        controller: "PermissionCheckControl",
        templateUrl: "templates/appstatus/permissioncheck.html"
    };
}).
controller("PermissionCheckControl", function($scope, $element, $attrs,
        $ionicPlatform, $ionicPopup, $window, $translate) {
    console.log("PermissionCheckControl initialized");

    $scope.setupLocChecks = function(platform, version) {
        if (platform.toLowerCase() == "android") {
            return $scope.setupAndroidLocChecks(version);
        } else if (platform.toLowerCase() == "ios") {
            return $scope.setupIOSLocChecks(version);
        } else {
            alert("Unknown platform, no tracking");
        }
    }

    $scope.setupFitnessChecks = function(platform, version) {
        if (platform.toLowerCase() == "android") {
            return $scope.setupAndroidFitnessChecks(version);
        } else if (platform.toLowerCase() == "ios") {
            return $scope.setupIOSFitnessChecks(version);
        } else {
            alert("Unknown platform, no tracking");
        }
    }

    $scope.recomputeLocStatus = function() {
        let iconMap = (statusState) => statusState? "✅" : "❌";
        let classMap = (statusState) => statusState? "status-green" : "status-red";
        $scope.locChecks.forEach((lc) => {
            lc.statusIcon = iconMap(lc.statusState);
            lc.statusClass = classMap(lc.statusState)
        });
        $scope.overallLocStatus = $scope.locChecks.map((lc) => lc.statusState).reduce((pv, cv) => pv && cv);
        console.log("overallLocStatus = "+$scope.overallLocStatus+" from ", $scope.locChecks);
        $scope.overallLocStatusIcon = iconMap($scope.overallLocStatus);
        $scope.overallLocStatusClass = classMap($scope.overallLocStatus);
    }

    $scope.setupAndroidLocChecks = function(platform, version) {
        let checkOrFix = function(checkObj, nativeFn, showError=true) {
            return nativeFn()
                .then((status) => {
                    console.log("availability ", status)
                    $scope.$apply(() => {
                        checkObj.statusState = true;
                        $scope.recomputeLocStatus();
                    });
                    return status;
                }).catch((error) => {
                    console.log("Error", error)
                    if (showError) {
                        $ionicPopup.alert({
                            title: "Error in location settings",
                            template: "
"+error+"
",
                            okText: "Please fix again"
                        });
                    };
                    $scope.$apply(() => {
                        checkObj.statusState = false;
                        $scope.recomputeLocStatus();
                    });
                    return error;
                });
        }
        let fixSettings = function() {
            console.log("Fix and refresh location settings");
            return checkOrFix(locSettingsCheck, $window.cordova.plugins.BEMDataCollection.fixLocationSettings, showError=true);
        };
        let checkSettings = function() {
            console.log("Refresh location settings");
            return checkOrFix(locSettingsCheck, $window.cordova.plugins.BEMDataCollection.isValidLocationSettings, showError=false);
        };
        let fixPerms = function() {
            console.log("fix and refresh location permissions");
            return checkOrFix(locPermissionsCheck, $window.cordova.plugins.BEMDataCollection.fixLocationPermissions, showError=true);
        };
        let checkPerms = function() {
            console.log("fix and refresh location permissions");
            return checkOrFix(locPermissionsCheck, $window.cordova.plugins.BEMDataCollection.isValidLocationPermissions, showError=false);
        };
        var androidSettingsDescTag = "intro.appstatus.locsettings.description.android-gte-9";
        if (version < 9) {
            androidSettingsDescTag = "intro.appstatus.locsettings.description.android-lt-9";
        }
        var androidPermDescTag = "intro.appstatus.locperms.description.android-gte-11";
        if($scope.osver < 6) {
            androidPermDescTag = 'intro.appstatus.locperms.description.android-lt-6';
        } else if ($scope.osver < 10) {
            androidPermDescTag = "intro.appstatus.locperms.description.android-6-9";
        } else if ($scope.osver < 11) {
            androidPermDescTag= "intro.appstatus.locperms.description.android-10";
        }
        console.log("description tags are "+androidSettingsDescTag+" "+androidPermDescTag);
        // location settings
        let locSettingsCheck = {
            name: $translate.instant("intro.appstatus.locsettings.name"),
            desc: $translate.instant(androidSettingsDescTag),
            statusState: false,
            fix: fixSettings,
            refresh: checkSettings
        }
        let locPermissionsCheck = {
            name: $translate.instant("intro.appstatus.locperms.name"),
            desc: $translate.instant(androidPermDescTag),
            statusState: false,
            fix: fixPerms,
            refresh: checkPerms
        }
        $scope.locChecks = [locSettingsCheck, locPermissionsCheck];
        let locCheckPromises = $scope.locChecks.map((lc) => lc.refresh());
        console.log(locCheckPromises);
        Promise.all(locCheckPromises)
            .then((result) => $scope.recomputeLocStatus())
            .catch((error) => $scope.recomputeLocStatus())
    }

    $scope.setupAndroidFitnessChecks = function(platform, version) {
        $scope.fitnessPermNeeded = ($scope.osver >= 10);

        let fixAndRefreshPermissionsPlaceholder = function() {
            console.log("Fix and refresh fitnessation permissions");
        };
        let fitnessPermissionsCheck = {
            name: $translate.instant("intro.appstatus.fitnessperms.name"),
            desc: $translate.instant("intro.appstatus.fitnessperms.description.android"),
            statusIcon: "✅",
            statusClass: "status-green",
            fix: fixAndRefreshPermissionsPlaceholder,
            refresh: fixAndRefreshPermissionsPlaceholder
        }
        $scope.fitnessChecks = [fitnessPermissionsCheck];
        $scope.overallFitnessStatusIcon = "✅";
        $scope.overallFitnessStatusClass = "status-green";
    }

    $scope.setupPermissionText = function() {
        if($scope.platform.toLowerCase() == "ios") {
          if($scope.osver < 13) {
              $scope.locationPermExplanation = $translate.instant("intro.permissions.locationPermExplanation-ios-lt-13");
          } else {
              $scope.locationPermExplanation = $translate.instant("intro.permissions.locationPermExplanation-ios-gte-13");
          }
        }

        $scope.backgroundRestricted = false;
        if($window.device.manufacturer.toLowerCase() == "samsung") {
          $scope.backgroundRestricted = true;
          $scope.allowBackgroundInstructions = $translate.instant("intro.allow_background.samsung");
        }

        console.log("Explanation = "+$scope.locationPermExplanation);
    }

    $scope.checkLocationServicesEnabled = function() {
        console.log("About to see if location services are enabled");
    }
    $ionicPlatform.ready().then(function() {
        console.log("app is launched, should refresh");
        $scope.platform = $window.device.platform;
        $scope.osver = $window.device.version.split(".")[0];
        $scope.setupPermissionText();
        $scope.setupLocChecks($scope.platform, $scope.osver);
        $scope.setupFitnessChecks($scope.platform, $scope.osver);
    });

    $ionicPlatform.on("resume", function() {
        console.log("app has resumed, should refresh");
    });
});
<commit_msg>Adding in the fitness permission as well<commit_after>/*
 * Directive to enable the permissions required for the app to function properly.
 */

angular.module('emission.appstatus.permissioncheck',
    [])
.directive('permissioncheck', function() {
    return {
        scope: {
        },
        controller: "PermissionCheckControl",
        templateUrl: "templates/appstatus/permissioncheck.html"
    };
}).
controller("PermissionCheckControl", function($scope, $element, $attrs,
        $ionicPlatform, $ionicPopup, $window, $translate) {
    console.log("PermissionCheckControl initialized");

    $scope.setupLocChecks = function(platform, version) {
        if (platform.toLowerCase() == "android") {
            return $scope.setupAndroidLocChecks(version);
        } else if (platform.toLowerCase() == "ios") {
            return $scope.setupIOSLocChecks(version);
        } else {
            alert("Unknown platform, no tracking");
        }
    }

    $scope.setupFitnessChecks = function(platform, version) {
        if (platform.toLowerCase() == "android") {
            return $scope.setupAndroidFitnessChecks(version);
        } else if (platform.toLowerCase() == "ios") {
            return $scope.setupIOSFitnessChecks(version);
        } else {
            alert("Unknown platform, no tracking");
        }
    }

    let iconMap = (statusState) => statusState? "✅" : "❌";
    let classMap = (statusState) => statusState? "status-green" : "status-red";

    $scope.recomputeLocStatus = function() {
        $scope.locChecks.forEach((lc) => {
            lc.statusIcon = iconMap(lc.statusState);
            lc.statusClass = classMap(lc.statusState)
        });
        $scope.overallLocStatus = $scope.locChecks.map((lc) => lc.statusState).reduce((pv, cv) => pv && cv);
        console.log("overallLocStatus = "+$scope.overallLocStatus+" from ", $scope.locChecks);
        $scope.overallLocStatusIcon = iconMap($scope.overallLocStatus);
        $scope.overallLocStatusClass = classMap($scope.overallLocStatus);
    }

    $scope.recomputeFitnessStatus = function() {
        $scope.fitnessChecks.forEach((fc) => {
            fc.statusIcon = iconMap(fc.statusState);
            fc.statusClass = classMap(fc.statusState)
        });
        $scope.overallFitnessStatus = $scope.fitnessChecks.map((fc) => fc.statusState).reduce((pv, cv) => pv && cv);
        console.log("overallFitnessStatus = "+$scope.overallFitnessStatus+" from ", $scope.fitnessChecks);
        $scope.overallFitnessStatusIcon = iconMap($scope.overallFitnessStatus);
        $scope.overallFitnessStatusClass = classMap($scope.overallFitnessStatus);
    }

    let checkOrFix = function(checkObj, nativeFn, recomputeFn, showError=true) {
        return nativeFn()
            .then((status) => {
                console.log("availability ", status)
                $scope.$apply(() => {
                    checkObj.statusState = true;
                    recomputeFn();
                });
                return status;
            }).catch((error) => {
                console.log("Error", error)
                if (showError) {
                    $ionicPopup.alert({
                        title: "Error",
                        template: "
"+error+"
",
                        okText: "Please fix again"
                    });
                };
                $scope.$apply(() => {
                    checkObj.statusState = false;
                    recomputeFn();
                });
                return error;
            });
    }

    $scope.setupAndroidLocChecks = function(platform, version) {
        let fixSettings = function() {
            console.log("Fix and refresh location settings");
            return checkOrFix(locSettingsCheck, $window.cordova.plugins.BEMDataCollection.fixLocationSettings,
                $scope.recomputeLocStatus, showError=true);
        };
        let checkSettings = function() {
            console.log("Refresh location settings");
            return checkOrFix(locSettingsCheck, $window.cordova.plugins.BEMDataCollection.isValidLocationSettings,
                $scope.recomputeLocStatus, showError=false);
        };
        let fixPerms = function() {
            console.log("fix and refresh location permissions");
            return checkOrFix(locPermissionsCheck, $window.cordova.plugins.BEMDataCollection.fixLocationPermissions,
                $scope.recomputeLocStatus, showError=true);
        };
        let checkPerms = function() {
            console.log("fix and refresh location permissions");
            return checkOrFix(locPermissionsCheck, $window.cordova.plugins.BEMDataCollection.isValidLocationPermissions,
                $scope.recomputeLocStatus, showError=false);
        };
        var androidSettingsDescTag = "intro.appstatus.locsettings.description.android-gte-9";
        if (version < 9) {
            androidSettingsDescTag = "intro.appstatus.locsettings.description.android-lt-9";
        }
        var androidPermDescTag = "intro.appstatus.locperms.description.android-gte-11";
        if($scope.osver < 6) {
            androidPermDescTag = 'intro.appstatus.locperms.description.android-lt-6';
        } else if ($scope.osver < 10) {
            androidPermDescTag = "intro.appstatus.locperms.description.android-6-9";
        } else if ($scope.osver < 11) {
            androidPermDescTag= "intro.appstatus.locperms.description.android-10";
        }
        console.log("description tags are "+androidSettingsDescTag+" "+androidPermDescTag);
        // location settings
        let locSettingsCheck = {
            name: $translate.instant("intro.appstatus.locsettings.name"),
            desc: $translate.instant(androidSettingsDescTag),
            statusState: false,
            fix: fixSettings,
            refresh: checkSettings
        }
        let locPermissionsCheck = {
            name: $translate.instant("intro.appstatus.locperms.name"),
            desc: $translate.instant(androidPermDescTag),
            statusState: false,
            fix: fixPerms,
            refresh: checkPerms
        }
        $scope.locChecks = [locSettingsCheck, locPermissionsCheck];
        let locCheckPromises = $scope.locChecks.map((lc) => lc.refresh());
        console.log(locCheckPromises);
        Promise.all(locCheckPromises)
            .then((result) => $scope.recomputeLocStatus())
            .catch((error) => $scope.recomputeLocStatus())
    }

    $scope.setupAndroidFitnessChecks = function(platform, version) {
        $scope.fitnessPermNeeded = ($scope.osver >= 10);

        let fixPerms = function() {
            console.log("fix and refresh fitness permissions");
            return checkOrFix(fitnessPermissionsCheck, $window.cordova.plugins.BEMDataCollection.fixFitnessPermissions,
                $scope.recomputeFitnessStatus, showError=true);
        };
        let checkPerms = function() {
            console.log("fix and refresh fitness permissions");
            return checkOrFix(fitnessPermissionsCheck, $window.cordova.plugins.BEMDataCollection.isValidFitnessPermissions,
                $scope.recomputeFitnessStatus, showError=false);
        };

        let fitnessPermissionsCheck = {
            name: $translate.instant("intro.appstatus.fitnessperms.name"),
            desc: $translate.instant("intro.appstatus.fitnessperms.description.android"),
            fix: fixPerms,
            refresh: checkPerms
        }
        $scope.fitnessChecks = [fitnessPermissionsCheck];
        let fitnessCheckPromises = $scope.fitnessChecks.map((fc) => fc.refresh());
        console.log(fitnessCheckPromises);
        Promise.all(fitnessCheckPromises)
            .then((result) => $scope.recomputeFitnessStatus())
            .catch((error) => $scope.recomputeFitnessStatus())
    }

    $scope.setupPermissionText = function() {
        if($scope.platform.toLowerCase() == "ios") {
          if($scope.osver < 13) {
              $scope.locationPermExplanation = $translate.instant("intro.permissions.locationPermExplanation-ios-lt-13");
          } else {
              $scope.locationPermExplanation = $translate.instant("intro.permissions.locationPermExplanation-ios-gte-13");
          }
        }

        $scope.backgroundRestricted = false;
        if($window.device.manufacturer.toLowerCase() == "samsung") {
          $scope.backgroundRestricted = true;
          $scope.allowBackgroundInstructions = $translate.instant("intro.allow_background.samsung");
        }

        console.log("Explanation = "+$scope.locationPermExplanation);
    }

    $scope.checkLocationServicesEnabled = function() {
        console.log("About to see if location services are enabled");
    }
    $ionicPlatform.ready().then(function() {
        console.log("app is launched, should refresh");
        $scope.platform = $window.device.platform;
        $scope.osver = $window.device.version.split(".")[0];
        $scope.setupPermissionText();
        $scope.setupLocChecks($scope.platform, $scope.osver);
        $scope.setupFitnessChecks($scope.platform, $scope.osver);
    });

    $ionicPlatform.on("resume", function() {
        console.log("app has resumed, should refresh");
    });
});
<|endoftext|>


<commit_before>import ContractAddress from "../fixtures/contractAddress.js";
import ContractStructure from "../fixtures/contractStructure.js";

if (typeof web3 === 'undefined') {
    var web3 = require('ethereum.js');
    window.web3 = web3;
}

var listeners = [];

class EthClient {
    constructor() {
        try {
            let url = null;
            if (window.localStorage && window.localStorage.getItem('rpc_url')) {
                url = window.localStorage.getItem('rpc_url');
            }
            this.setJsonRPCUrl(url || 'http://localhost:8080');

            let WorkerDispatcher = web3.eth.contract(ContractStructure.WorkerDispatcher);
            this.contract = new WorkerDispatcher(ContractAddress);
            this.identity = web3.shh.newIdentity();
            this._worker = this.isWorker();
        }
        catch(e) {
            console.err(e);
            console.log("Could not contact " + this.getJsonRPCUrl());
        }
    }
    getCoinbase(success) {
        success(web3.eth.coinbase);
    }

    formatBalance(wei) {
        let unit = 'wei';

        if (wei > 10e18) {
            unit = 'ether';
        } else if (wei > 10e15) {
            unit = 'finney';
        }

        return (unit !== 'wei' ? web3.fromWei(wei, unit) : wei) + ' ' + unit;
    }

    getChain(success) {
        var createContent = function() {
            return {
                items: [
                    {label: "Coinbase", value: web3.eth.coinbase},
                    {label: "Accounts", value: web3.eth.accounts},
                    {
                        label: "Balance",
                        value: this.formatBalance(web3.eth.getBalance(web3.eth.coinbase))
                    }
                ]
            }
        }.bind(this);

        var checkForWork = function() {
            let workAgreement = this.contract.workersInfo(web3.eth.coinbase)[3];
            console.log(workAgreement);
        }.bind(this);

        success(createContent());
        web3.eth.filter('chain').watch(function() {
            success(createContent());
            if (this._worker) {
                checkForWork();
            }
        }.bind(this));
    }

    getPending(success) {
        let contract = this.contract;
        function createContent() {
            let workers = contract.numWorkers();
            let latestBlock = web3.eth.blockNumber;
            let code = web3.eth.getCode(ContractAddress);
            if (code.length > 50) {
                code = code.substring(0, 60) + '…';
            }
            return {
                items: [
                    {label: "Latest block", value: latestBlock},
                    {
                        label: "Latest block hash",
                        value: web3.eth.getBlock(latestBlock).hash
                    },
                    {
                        label: "Latest block timestamp",
                        value: Date(web3.eth.getBlock(latestBlock).timestamp)
                    },
                    {label: "Contract address", value: ContractAddress},
                    {label: "Number of workers", value: workers.toString()},
                    {label: "Code", value: code}
                ]
            }
        }
        success(createContent());
        web3.eth.filter('pending').watch(function() {
            success(createContent());
        });
    }

    unregisterAll() {
        web3.reset();
        // web3.eth.filter('chain').stopWatching();
        // web3.eth.filter('pending').stopWatching();
    }

    registerWorker(maxLength, price, name) {
        this.contract.registerWorker(maxLength, price, name);
        this._worker = true;
    }

    changeWorkerPrice(newPrice) {
        this.contract.changeWorkerPrice(newPrice);
    }

    buyContract(worker, redundancy, price, length) {
        let options = {
            value: length * price,
            gas: 500000
        };
        this.contract.sendTransaction(options).buyContract(worker, redundancy,
                                                           length);

        let filter = web3.eth.filter('chain');
        filter.watch(function() {
            let workAgreement = this.contract.workersInfo(worker)[3];
            console.log(workAgreement);
            filter.stopWatching();
        }.bind(this));
    }

    bigNumberToInt(bigNumber) {
        return bigNumber.c[0];
    }

    isWorker() {
        let numWorkers = this.bigNumberToInt(this.contract.numWorkers());
        for (let i = 0; i < numWorkers; i++) {
            if (web3.eth.coinbase === this.contract.workerList(i)) {
                return true;
            }
        }
        return false;
    }

    findWorkers(length, price, success) {
        let numWorkers = this.bigNumberToInt(this.contract.numWorkers());
        let workers = [];
        for (let i = 0; i < numWorkers; i++) {
            let address = this.contract.workerList(i);
            let info = this.contract.workersInfo(address);
            let workerLength = this.bigNumberToInt(info[1]);
            let workerPrice = this.bigNumberToInt(info[2]);
            if (length <= workerLength && price >= workerPrice) {
                workers[workers.length] = {
                    pubkey: address,
                    name: info[0],
                    length: workerLength,
                    price: workerPrice
                };
            }
        }

        success(workers);
    }

    registerListener(callback) {
        listeners.push(callback);
    }

    unregisterListener(callback) {
        listeners = listeners.filter((a) => a != callback);
    }

    getJsonRPCUrl() {
        return this._jsonRpcUrl;
    }

    setJsonRPCUrl(url) {
        if (!url.startsWith('http')) {
            url = 'http://' + url;
        }
        this._jsonRpcUrl = url;
        if (window.localStorage) {
            window.localStorage.setItem('rpc_url', this._jsonRpcUrl);
        }
        listeners.forEach((func) => {
            func(this._jsonRpcUrl);
        });
        web3.setProvider(new web3.providers.HttpProvider(this._jsonRpcUrl));
    }

    sendMsg(to, data) {
        web3.shh.post({
            "from": this.identity,
            "to": to,
            "payload": [ web3.fromAscii(data) ],
        });
    }

    askWorker(workerAddress, contractAddress) {
        web3.shh.post({
            "from": this.identity,
            "topic": workerAddress,
            "payload": [ contractAddress ],
        });
    }
}

let ethclient = new EthClient();

export default ethclient;
<commit_msg>Fixed typo<commit_after>import ContractAddress from "../fixtures/contractAddress.js";
import ContractStructure from "../fixtures/contractStructure.js";

if (typeof web3 === 'undefined') {
    var web3 = require('ethereum.js');
    window.web3 = web3;
}

var listeners = [];

class EthClient {
    constructor() {
        try {
            let url = null;
            if (window.localStorage && window.localStorage.getItem('rpc_url')) {
                url = window.localStorage.getItem('rpc_url');
            }
            this.setJsonRPCUrl(url || 'http://localhost:8080');

            let WorkerDispatcher = web3.eth.contract(ContractStructure.WorkerDispatcher);
            this.contract = new WorkerDispatcher(ContractAddress);
            this.identity = web3.shh.newIdentity();
            this._worker = this.isWorker();
        }
        catch(e) {
            console.error(e);
            console.log("Could not contact " + this.getJsonRPCUrl());
        }
    }
    getCoinbase(success) {
        success(web3.eth.coinbase);
    }

    formatBalance(wei) {
        let unit = 'wei';

        if (wei > 10e18) {
            unit = 'ether';
        } else if (wei > 10e15) {
            unit = 'finney';
        }

        return (unit !== 'wei' ? web3.fromWei(wei, unit) : wei) + ' ' + unit;
    }

    getChain(success) {
        var createContent = function() {
            return {
                items: [
                    {label: "Coinbase", value: web3.eth.coinbase},
                    {label: "Accounts", value: web3.eth.accounts},
                    {
                        label: "Balance",
                        value: this.formatBalance(web3.eth.getBalance(web3.eth.coinbase))
                    }
                ]
            }
        }.bind(this);

        var checkForWork = function() {
            let workAgreement = this.contract.workersInfo(web3.eth.coinbase)[3];
            console.log(workAgreement);
        }.bind(this);

        success(createContent());
        web3.eth.filter('chain').watch(function() {
            success(createContent());
            if (this._worker) {
                checkForWork();
            }
        }.bind(this));
    }

    getPending(success) {
        let contract = this.contract;
        function createContent() {
            let workers = contract.numWorkers();
            let latestBlock = web3.eth.blockNumber;
            let code = web3.eth.getCode(ContractAddress);
            if (code.length > 50) {
                code = code.substring(0, 60) + '…';
            }
            return {
                items: [
                    {label: "Latest block", value: latestBlock},
                    {
                        label: "Latest block hash",
                        value: web3.eth.getBlock(latestBlock).hash
                    },
                    {
                        label: "Latest block timestamp",
                        value: Date(web3.eth.getBlock(latestBlock).timestamp)
                    },
                    {label: "Contract address", value: ContractAddress},
                    {label: "Number of workers", value: workers.toString()},
                    {label: "Code", value: code}
                ]
            }
        }
        success(createContent());
        web3.eth.filter('pending').watch(function() {
            success(createContent());
        });
    }

    unregisterAll() {
        web3.reset();
        // web3.eth.filter('chain').stopWatching();
        // web3.eth.filter('pending').stopWatching();
    }

    registerWorker(maxLength, price, name) {
        this.contract.registerWorker(maxLength, price, name);
        this._worker = true;
    }

    changeWorkerPrice(newPrice) {
        this.contract.changeWorkerPrice(newPrice);
    }

    buyContract(worker, redundancy, price, length) {
        let options = {
            value: length * price,
            gas: 500000
        };
        this.contract.sendTransaction(options).buyContract(worker, redundancy,
                                                           length);

        let filter = web3.eth.filter('chain');
        filter.watch(function() {
            let workAgreement = this.contract.workersInfo(worker)[3];
            console.log(workAgreement);
            filter.stopWatching();
        }.bind(this));
    }

    bigNumberToInt(bigNumber) {
        return bigNumber.c[0];
    }

    isWorker() {
        let numWorkers = this.bigNumberToInt(this.contract.numWorkers());
        for (let i = 0; i < numWorkers; i++) {
            if (web3.eth.coinbase === this.contract.workerList(i)) {
                return true;
            }
        }
        return false;
    }

    findWorkers(length, price, success) {
        let numWorkers = this.bigNumberToInt(this.contract.numWorkers());
        let workers = [];
        for (let i = 0; i < numWorkers; i++) {
            let address = this.contract.workerList(i);
            let info = this.contract.workersInfo(address);
            let workerLength = this.bigNumberToInt(info[1]);
            let workerPrice = this.bigNumberToInt(info[2]);
            if (length <= workerLength && price >= workerPrice) {
                workers[workers.length] = {
                    pubkey: address,
                    name: info[0],
                    length: workerLength,
                    price: workerPrice
                };
            }
        }

        success(workers);
    }

    registerListener(callback) {
        listeners.push(callback);
    }

    unregisterListener(callback) {
        listeners = listeners.filter((a) => a != callback);
    }

    getJsonRPCUrl() {
        return this._jsonRpcUrl;
    }

    setJsonRPCUrl(url) {
        if (!url.startsWith('http')) {
            url = 'http://' + url;
        }
        this._jsonRpcUrl = url;
        if (window.localStorage) {
            window.localStorage.setItem('rpc_url', this._jsonRpcUrl);
        }
        listeners.forEach((func) => {
            func(this._jsonRpcUrl);
        });
        web3.setProvider(new web3.providers.HttpProvider(this._jsonRpcUrl));
    }

    sendMsg(to, data) {
        web3.shh.post({
            "from": this.identity,
            "to": to,
            "payload": [ web3.fromAscii(data) ],
        });
    }

    askWorker(workerAddress, contractAddress) {
        web3.shh.post({
            "from": this.identity,
            "topic": workerAddress,
            "payload": [ contractAddress ],
        });
    }
}

let ethclient = new EthClient();

export default ethclient;
<|endoftext|>


<commit_before>"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("@angular/core");
var rider_service_1 = require("../services/rider.service");
var RiderComponent = (function () {
    function RiderComponent(riderService) {
        this.riderService = riderService;
    }
    RiderComponent.prototype.ngOnInit = function () {
        this.getRiders();
    };
    RiderComponent.prototype.getRiders = function () {
        this.riders = this.riderService.getRiders();
    };
    return RiderComponent;
}());
RiderComponent = __decorate([
    core_1.Component({
        moduleId: module.id,
        selector: 'riders',
        templateUrl: 'riders.component.html'
    }),
    __metadata("design:paramtypes", [rider_service_1.RiderService])
], RiderComponent);
exports.RiderComponent = RiderComponent;
//# sourceMappingURL=riders.component.js.map<commit_msg>Delete riders.component.js<commit_after><|endoftext|>


<commit_before>var global = require('./global');
var joystick = new VirtualJoystick()

class Canvas {
    constructor(params) {
        this.directionLock = false;
        this.target = global.target;
        this.reenviar = true;
        this.socket = global.socket;
        this.directions = [];
        var self = this;

        this.cv = document.getElementById('cvs');
        this.cv.width = global.screenWidth;
        this.cv.height = global.screenHeight;
        this.cv.addEventListener('mousemove', this.gameInput, false);
        this.cv.addEventListener('mouseout', this.outOfBounds, false);
        this.cv.addEventListener('keypress', this.keyInput, false);
        this.cv.addEventListener('keyup', function(event) {
            self.reenviar = true;
            self.directionUp(event);
        }, false);
        this.cv.addEventListener('keydown', this.directionDown, false);
        this.cv.addEventListener('touchstart', this.touchInput, false);
        this.cv.addEventListener('touchmove', this.touchInput, false);
        //Register joystick movements
        joystick.addEventListener ('up', function (event){
        	self.reenviar = true;
            self.directionUp (event);
        },false);
        this.cv.parent = self;
        global.canvas = this;
    }

    // Function called when a key is pressed, will change direction if arrow key.
    directionDown(event) {
    	var key = event.which || event.keyCode;
        var self = this.parent; // have to do this so we are not using the cv object
    	if (self.directional(key)) {
    		self.directionLock = true;
    		if (self.newDirection(key, self.directions, true)) {
    			self.updateTarget(self.directions);
    			self.socket.emit('0', self.target);
    		}
    	}
    }

    // Function called when a key is lifted, will change direction if arrow key.
    directionUp(event) {
    	var key = event.which || event.keyCode;
    	if (this.directional(key)) { // this == the actual class
    		if (this.newDirection(key, this.directions, false)) {
    			this.updateTarget(this.directions);
    			if (this.directions.length === 0) this.directionLock = false;
    			this.socket.emit('0', this.target);
    		}
    	}
    }

    // Updates the direction array including information about the new direction.
    newDirection(direction, list, isAddition) {
    	var result = false;
    	var found = false;
    	for (var i = 0, len = list.length; i < len; i++) {
    		if (list[i] == direction) {
    			found = true;
    			if (!isAddition) {
    				result = true;
    				// Removes the direction.
    				list.splice(i, 1);
    			}
    			break;
    		}
    	}
    	// Adds the direction.
    	if (isAddition && found === false) {
    		result = true;
    		list.push(direction);
    	}

    	return result;
    }

    // Updates the target according to the directions in the directions array.
    updateTarget(list) {
    	this.target = { x : 0, y: 0 };
    	var directionHorizontal = 0;
    	var directionVertical = 0;
    	for (var i = 0, len = list.length; i < len; i++) {
    		if (directionHorizontal === 0) {
    			if (list[i] == global.KEY_LEFT) directionHorizontal -= Number.MAX_VALUE;
    			else if (list[i] == global.KEY_RIGHT) directionHorizontal += Number.MAX_VALUE;
    		}
    		if (directionVertical === 0) {
    			if (list[i] == global.KEY_UP) directionVertical -= Number.MAX_VALUE;
    			else if (list[i] == global.KEY_DOWN) directionVertical += Number.MAX_VALUE;
    		}
    	}
    	this.target.x += directionHorizontal;
    	this.target.y += directionVertical;
        global.target = this.target;
    }

    directional(key) {
    	return this.horizontal(key) || this.vertical(key);
    }

    horizontal(key) {
    	return key == global.KEY_LEFT || key == global.KEY_RIGHT;
    }

    vertical(key) {
    	return key == global.KEY_DOWN || key == global.KEY_UP;
    }

    // Register when the mouse goes off the canvas.
    outOfBounds() {
        if (!global.continuity) {
            this.parent.target = { x : 0, y: 0 };
            global.target = this.parent.target;
        }
    }

    gameInput(mouse) {
    	if (!this.directionLock) {
    		this.parent.target.x = mouse.clientX - this.width / 2;
    		this.parent.target.y = mouse.clientY - this.height / 2;
            global.target = this.parent.target;
    	}
    }

    touchInput(touch) {
        touch.preventDefault();
        touch.stopPropagation();
    	if (!this.directionLock) {
    		this.parent.target.x = touch.touches[0].clientX - this.width / 2;
    		this.parent.target.y = touch.touches[0].clientY - this.height / 2;
            global.target = this.parent.target;
    	}
    }

    // Chat command callback functions.
    keyInput(event) {
    	var key = event.which || event.keyCode;
    	if (key === global.KEY_FIREFOOD && this.parent.reenviar) {
            this.parent.socket.emit('1');
            this.parent.reenviar = false;
        }
        else if (key === global.KEY_SPLIT && this.parent.reenviar) {
            document.getElementById('split_cell').play();
            this.parent.socket.emit('2');
            this.parent.reenviar = false;
        }
        else if (key === global.KEY_CHAT) {
            document.getElementById('chatInput').focus();
        }
    }
}

module.exports = Canvas;
<commit_msg>Update canvas.js<commit_after>var global = require('./global');
var joystick = new VirtualJoystick()

class Canvas {
    constructor(params) {
        this.directionLock = false;
        this.target = global.target;
        this.reenviar = true;
        this.socket = global.socket;
        this.directions = [];
        var self = this;

        this.cv = document.getElementById('cvs');
        this.cv.width = global.screenWidth;
        this.cv.height = global.screenHeight;
        this.cv.addEventListener('mousemove', this.gameInput, false);
        this.cv.addEventListener('mouseout', this.outOfBounds, false);
        this.cv.addEventListener('keypress', this.keyInput, false);
        this.cv.addEventListener('keyup', function(event) {
            self.reenviar = true;
            self.directionUp(event);
        }, false);
        this.cv.addEventListener('keydown', this.directionDown, false);
        this.cv.addEventListener('touchstart', this.touchInput, false);
        this.cv.addEventListener('touchmove', this.touchInput, false);
        //Register joystick movements

        this.cv.parent = self;
        global.canvas = this;
    }

    // Function called when a key is pressed, will change direction if arrow key.
    directionDown(event) {
    	var key = event.which || event.keyCode;
        var self = this.parent; // have to do this so we are not using the cv object
    	if (self.directional(key)) {
    		self.directionLock = true;
    		if (self.newDirection(key, self.directions, true)) {
    			self.updateTarget(self.directions);
    			self.socket.emit('0', self.target);
    		}
    	}
    }

    // Function called when a key is lifted, will change direction if arrow key.
    directionUp(event) {
    	var key = event.which || event.keyCode;
    	if (this.directional(key)) { // this == the actual class
    		if (this.newDirection(key, this.directions, false)) {
    			this.updateTarget(this.directions);
    			if (this.directions.length === 0) this.directionLock = false;
    			this.socket.emit('0', this.target);
    		}
    	}
    }

    // Updates the direction array including information about the new direction.
    newDirection(direction, list, isAddition) {
    	var result = false;
    	var found = false;
    	for (var i = 0, len = list.length; i < len; i++) {
    		if (list[i] == direction) {
    			found = true;
    			if (!isAddition) {
    				result = true;
    				// Removes the direction.
    				list.splice(i, 1);
    			}
    			break;
    		}
    	}
    	// Adds the direction.
    	if (isAddition && found === false) {
    		result = true;
    		list.push(direction);
    	}

    	return result;
    }

    // Updates the target according to the directions in the directions array.
    updateTarget(list) {
    	this.target = { x : 0, y: 0 };
    	var directionHorizontal = 0;
    	var directionVertical = 0;
    	for (var i = 0, len = list.length; i < len; i++) {
    		if (directionHorizontal === 0) {
    			if (list[i] == global.KEY_LEFT) directionHorizontal -= Number.MAX_VALUE;
    			else if (list[i] == global.KEY_RIGHT) directionHorizontal += Number.MAX_VALUE;
    		}
    		if (directionVertical === 0) {
    			if (list[i] == global.KEY_UP) directionVertical -= Number.MAX_VALUE;
    			else if (list[i] == global.KEY_DOWN) directionVertical += Number.MAX_VALUE;
    		}
    	}
    	this.target.x += directionHorizontal;
    	this.target.y += directionVertical;
        global.target = this.target;
    }

    directional(key) {
    	return this.horizontal(key) || this.vertical(key);
    }

    horizontal(key) {
    	return key == global.KEY_LEFT || key == global.KEY_RIGHT;
    }

    vertical(key) {
    	return key == global.KEY_DOWN || key == global.KEY_UP;
    }

    // Register when the mouse goes off the canvas.
    outOfBounds() {
        if (!global.continuity) {
            this.parent.target = { x : 0, y: 0 };
            global.target = this.parent.target;
        }
    }

    gameInput(mouse) {
    	if (!this.directionLock) {
    		this.parent.target.x = mouse.clientX - this.width / 2;
    		this.parent.target.y = mouse.clientY - this.height / 2;
            global.target = this.parent.target;
    	}
    }

    touchInput(touch) {
        touch.preventDefault();
        touch.stopPropagation();
    	if (!this.directionLock) {
    		this.parent.target.x = touch.touches[0].clientX - this.width / 2;
    		this.parent.target.y = touch.touches[0].clientY - this.height / 2;
            global.target = this.parent.target;
    	}
    }

    // Chat command callback functions.
    keyInput(event) {
    	var key = event.which || event.keyCode;
    	if (key === global.KEY_FIREFOOD && this.parent.reenviar) {
            this.parent.socket.emit('1');
            this.parent.reenviar = false;
        }
        else if (key === global.KEY_SPLIT && this.parent.reenviar) {
            document.getElementById('split_cell').play();
            this.parent.socket.emit('2');
            this.parent.reenviar = false;
        }
        else if (key === global.KEY_CHAT) {
            document.getElementById('chatInput').focus();
        }
    }
}

module.exports = Canvas;
<|endoftext|>


<commit_before>'use strict';

import angular from 'angular';

class SignInService {
  constructor($http, $q) {
    this.http = $http;
    this.deferred = $q.defer();
  };

  authenticate(authData) {
    console.log('Log: Authenticate Service');
    this.http({
      method: 'POST',
      url: '/api/v1/authenticate',
      data: authData
    }).then((response) => {
      console.log('Log: Success Callback');
      this.deferred.resolve(response);
    }, (response) => {
      console.log('Log: Error Callback');
      this.deferred.reject(response);
    });

    return this.deferred.promise;
  }
};

export default angular.module('service.signin', [])
  .service('SignInService', SignInService)
  .name;
<commit_msg>Fixes promise cache bug<commit_after>'use strict';

import angular from 'angular';

class SignInService {
  constructor($http, $q) {
    this.http = $http;
    this.q = $q;
  };

  authenticate(authData) {
    let deferred = this.q.defer();

    this.http({
      method: 'POST',
      url: '/api/v1/authenticate',
      data: authData
    }).then((response) => {
      console.log('Service: ', response.data);
      deferred.resolve(response.data);
    }, (response) => {
      deferred.reject(response);
    });

    return deferred.promise;
  }
};

export default angular.module('service.signin', [])
  .service('SignInService', SignInService)
  .name;
<|endoftext|>


<commit_before>define([
  'underscore',
  './interval'
],
function (_, Interval) {
  'use strict';

  var ts = {};

  // map compatable parseInt
  function base10Int(val) {
    return parseInt(val, 10);
  }

  // trim the ms off of a time, but return it with empty ms.
  function getDatesTime(date) {
    return Math.floor(date.getTime() / 1000)*1000;
  }

  /**
   * Certain graphs require 0 entries to be specified for them to render
   * properly (like the line graph). So with this we will caluclate all of
   * the expected time measurements, and fill the missing ones in with 0
   * @param {object} opts  An object specifying some/all of the options
   *
   * OPTIONS:
   * @opt   {string}   interval    The interval notion describing the expected spacing between
   *                                each data point.
   * @opt   {date}     start_date  (optional) The start point for the time series, setting this and the
   *                                end_date will ensure that the series streches to resemble the entire
   *                                expected result
   * @opt   {date}     end_date    (optional) The end point for the time series, see start_date
   * @opt   {string}   fill_style  Either "minimal", or "all" describing the strategy used to zero-fill
   *                                the series.
   */
  ts.ZeroFilled = function (opts) {
    opts = _.defaults(opts, {
      interval: '10m',
      start_date: null,
      end_date: null,
      fill_style: 'minimal'
    });

    // the expected differenece between readings.
    this.interval = new Interval(opts.interval);

    // will keep all values here, keyed by their time
    this._data = {};
    this.start_time = opts.start_date && getDatesTime(opts.start_date);
    this.end_time = opts.end_date && getDatesTime(opts.end_date);
    this.opts = opts;
  };

  /**
   * Add a row
   * @param {int}  time  The time for the value, in
   * @param {any}  value The value at this time
   */
  ts.ZeroFilled.prototype.addValue = function (time, value) {
    if (time instanceof Date) {
      time = getDatesTime(time);
    } else {
      time = base10Int(time);
    }
    if (!isNaN(time)) {
      this._data[time] = (_.isUndefined(value) ? 0 : value);
    }
    this._cached_times = null;
  };

  /**
   * Get an array of the times that have been explicitly set in the series
   * @param  {array} include (optional) list of timestamps to include in the response
   * @return {array} An array of integer times.
   */
  ts.ZeroFilled.prototype.getOrderedTimes = function (include) {
    var times = _.map(_.keys(this._data), base10Int);
    if (_.isArray(include)) {
      times = times.concat(include);
    }
    return _.uniq(times.sort(function (a, b) {
      // decending numeric sort
      return a - b;
    }), true);
  };

  /**
   * return the rows in the format:
   * [ [time, value], [time, value], ... ]
   *
   * Heavy lifting is done by _get(Min|Default|All)FlotPairs()
   * @param  {array} required_times  An array of timestamps that must be in the resulting pairs
   * @return {array}
   */
  ts.ZeroFilled.prototype.getFlotPairs = function (required_times) {
    var times = this.getOrderedTimes(required_times),
      strategy,
      pairs;

    if(this.opts.fill_style === 'all') {
      strategy = this._getAllFlotPairs;
    } else if(this.opts.fill_style === 'null') {
      strategy = this._getNullFlotPairs;
    } else if(this.opts.fill_style === 'no') {
      strategy = this._getNoZeroFlotPairs;
    } else {
      strategy = this._getMinFlotPairs;
    }

    pairs = _.reduce(
      times,    // what
      strategy, // how
      [],       // where
      this      // context
    );

    // if the first or last pair is inside either the start or end time,
    // add those times to the series with null values so the graph will stretch to contain them.
    // Removing, flot 0.8.1's max/min params satisfy this
    /*
    if (this.start_time && (pairs.length === 0 || pairs[0][0] > this.start_time)) {
      pairs.unshift([this.start_time, null]);
    }
    if (this.end_time && (pairs.length === 0 || pairs[pairs.length - 1][0] < this.end_time)) {
      pairs.push([this.end_time, null]);
    }
    */

    return pairs;
  };

  /**
   * ** called as a reduce stragegy in getFlotPairs() **
   * Fill zero's on either side of the current time, unless there is already a measurement there or
   * we are looking at an edge.
   * @return {array} An array of points to plot with flot
   */
  ts.ZeroFilled.prototype._getMinFlotPairs = function (result, time, i, times) {
    var next, expected_next, prev, expected_prev;

    // check for previous measurement
    if (i > 0) {
      prev = times[i - 1];
      expected_prev = this.interval.before(time);
      if (prev < expected_prev) {
        result.push([expected_prev, 0]);
      }
    }

    // add the current time
    result.push([ time, this._data[time] || 0]);

    // check for next measurement
    if (times.length > i) {
      next = times[i + 1];
      expected_next = this.interval.after(time);
      if (next > expected_next) {
        result.push([expected_next, 0]);
      }
    }

    return result;
  };

  /**
   * ** called as a reduce stragegy in getFlotPairs() **
   * Fill zero's to the right of each time, until the next measurement is reached or we are at the
   * last measurement
   * @return {array}  An array of points to plot with flot
   */
  ts.ZeroFilled.prototype._getAllFlotPairs = function (result, time, i, times) {
    var next, expected_next;

    result.push([ times[i], this._data[times[i]] || 0 ]);
    next = times[i + 1];
    expected_next = this.interval.after(time);
    for(; times.length > i && next > expected_next; expected_next = this.interval.after(expected_next)) {
      result.push([expected_next, 0]);
    }

    return result;
  };

  /**
   * ** called as a reduce stragegy in getFlotPairs() **
   * Same as min, but fills with nulls
   * @return {array}  An array of points to plot with flot
   */
  ts.ZeroFilled.prototype._getNullFlotPairs = function (result, time, i, times) {
    var next, expected_next, prev, expected_prev;

    // check for previous measurement
    if (i > 0) {
      prev = times[i - 1];
      expected_prev = this.interval.before(time);
      if (prev < expected_prev) {
        result.push([expected_prev, null]);
      }
    }

    // add the current time
    result.push([ time, this._data[time] || null]);

    // check for next measurement
    if (times.length > i) {
      next = times[i + 1];
      expected_next = this.interval.after(time);
      if (next > expected_next) {
        result.push([expected_next, null]);
      }
    }

    return result;
  };

  /**
   * ** called as a reduce stragegy in getFlotPairs() **
   * Not fill zero's on either side of the current time, only the current time
   * @return {array}  An array of points to plot with flot
   */
  ts.ZeroFilled.prototype._getNoZeroFlotPairs = function (result, time, i, times) {
    var next, expected_next, prev, expected_prev;

    // add the current time
    result.push([ time, this._data[time] || 0 ]);

    return result;
  };

  return ts;
});<commit_msg>modify the function so that does not show 0, when two or more lines are drawn.<commit_after>define([
  'underscore',
  './interval'
],
function (_, Interval) {
  'use strict';

  var ts = {};

  // map compatable parseInt
  function base10Int(val) {
    return parseInt(val, 10);
  }

  // trim the ms off of a time, but return it with empty ms.
  function getDatesTime(date) {
    return Math.floor(date.getTime() / 1000)*1000;
  }

  /**
   * Certain graphs require 0 entries to be specified for them to render
   * properly (like the line graph). So with this we will caluclate all of
   * the expected time measurements, and fill the missing ones in with 0
   * @param {object} opts  An object specifying some/all of the options
   *
   * OPTIONS:
   * @opt   {string}   interval    The interval notion describing the expected spacing between
   *                                each data point.
   * @opt   {date}     start_date  (optional) The start point for the time series, setting this and the
   *                                end_date will ensure that the series streches to resemble the entire
   *                                expected result
   * @opt   {date}     end_date    (optional) The end point for the time series, see start_date
   * @opt   {string}   fill_style  Either "minimal", or "all" describing the strategy used to zero-fill
   *                                the series.
   */
  ts.ZeroFilled = function (opts) {
    opts = _.defaults(opts, {
      interval: '10m',
      start_date: null,
      end_date: null,
      fill_style: 'minimal'
    });

    // the expected differenece between readings.
    this.interval = new Interval(opts.interval);

    // will keep all values here, keyed by their time
    this._data = {};
    this.start_time = opts.start_date && getDatesTime(opts.start_date);
    this.end_time = opts.end_date && getDatesTime(opts.end_date);
    this.opts = opts;
  };

  /**
   * Add a row
   * @param {int}  time  The time for the value, in
   * @param {any}  value The value at this time
   */
  ts.ZeroFilled.prototype.addValue = function (time, value) {
    if (time instanceof Date) {
      time = getDatesTime(time);
    } else {
      time = base10Int(time);
    }
    if (!isNaN(time)) {
      this._data[time] = (_.isUndefined(value) ? 0 : value);
    }
    this._cached_times = null;
  };

  /**
   * Get an array of the times that have been explicitly set in the series
   * @param  {array} include (optional) list of timestamps to include in the response
   * @return {array} An array of integer times.
   */
  ts.ZeroFilled.prototype.getOrderedTimes = function (include) {
    var times = _.map(_.keys(this._data), base10Int);
    if (_.isArray(include)) {
      times = times.concat(include);
    }
    return _.uniq(times.sort(function (a, b) {
      // decending numeric sort
      return a - b;
    }), true);
  };

  /**
   * return the rows in the format:
   * [ [time, value], [time, value], ... ]
   *
   * Heavy lifting is done by _get(Min|Default|All)FlotPairs()
   * @param  {array} required_times  An array of timestamps that must be in the resulting pairs
   * @return {array}
   */
  ts.ZeroFilled.prototype.getFlotPairs = function (required_times) {
    var times = this.getOrderedTimes(required_times),
      strategy,
      pairs;

    if(this.opts.fill_style === 'all') {
      strategy = this._getAllFlotPairs;
    } else if(this.opts.fill_style === 'null') {
      strategy = this._getNullFlotPairs;
    } else if(this.opts.fill_style === 'no') {
      strategy = this._getNoZeroFlotPairs;
    } else {
      strategy = this._getMinFlotPairs;
    }

    pairs = _.reduce(
      times,    // what
      strategy, // how
      [],       // where
      this      // context
    );

    // if the first or last pair is inside either the start or end time,
    // add those times to the series with null values so the graph will stretch to contain them.
    // Removing, flot 0.8.1's max/min params satisfy this
    /*
    if (this.start_time && (pairs.length === 0 || pairs[0][0] > this.start_time)) {
      pairs.unshift([this.start_time, null]);
    }
    if (this.end_time && (pairs.length === 0 || pairs[pairs.length - 1][0] < this.end_time)) {
      pairs.push([this.end_time, null]);
    }
    */

    return pairs;
  };

  /**
   * ** called as a reduce stragegy in getFlotPairs() **
   * Fill zero's on either side of the current time, unless there is already a measurement there or
   * we are looking at an edge.
   * @return {array} An array of points to plot with flot
   */
  ts.ZeroFilled.prototype._getMinFlotPairs = function (result, time, i, times) {
    var next, expected_next, prev, expected_prev;

    // check for previous measurement
    if (i > 0) {
      prev = times[i - 1];
      expected_prev = this.interval.before(time);
      if (prev < expected_prev) {
        result.push([expected_prev, 0]);
      }
    }

    // add the current time
    result.push([ time, this._data[time] || 0]);

    // check for next measurement
    if (times.length > i) {
      next = times[i + 1];
      expected_next = this.interval.after(time);
      if (next > expected_next) {
        result.push([expected_next, 0]);
      }
    }

    return result;
  };

  /**
   * ** called as a reduce stragegy in getFlotPairs() **
   * Fill zero's to the right of each time, until the next measurement is reached or we are at the
   * last measurement
   * @return {array}  An array of points to plot with flot
   */
  ts.ZeroFilled.prototype._getAllFlotPairs = function (result, time, i, times) {
    var next, expected_next;

    result.push([ times[i], this._data[times[i]] || 0 ]);
    next = times[i + 1];
    expected_next = this.interval.after(time);
    for(; times.length > i && next > expected_next; expected_next = this.interval.after(expected_next)) {
      result.push([expected_next, 0]);
    }

    return result;
  };

  /**
   * ** called as a reduce stragegy in getFlotPairs() **
   * Same as min, but fills with nulls
   * @return {array}  An array of points to plot with flot
   */
  ts.ZeroFilled.prototype._getNullFlotPairs = function (result, time, i, times) {
    var next, expected_next, prev, expected_prev;

    // check for previous measurement
    if (i > 0) {
      prev = times[i - 1];
      expected_prev = this.interval.before(time);
      if (prev < expected_prev) {
        result.push([expected_prev, null]);
      }
    }

    // add the current time
    result.push([ time, this._data[time] || null]);

    // check for next measurement
    if (times.length > i) {
      next = times[i + 1];
      expected_next = this.interval.after(time);
      if (next > expected_next) {
        result.push([expected_next, null]);
      }
    }

    return result;
  };

  /**
   * ** called as a reduce stragegy in getFlotPairs() **
   * Not fill zero's on either side of the current time, only the current time
   * @return {array}  An array of points to plot with flot
   */
  ts.ZeroFilled.prototype._getNoZeroFlotPairs = function (result, time, i, times) {
    var next, expected_next, prev, expected_prev;

    // add the current time
    if(this._data[time]){
      result.push([ time, this._data[time]]);
    }

    return result;
  };

  return ts;
});<|endoftext|>


<commit_before>var Hit = require("./Hit.js");
var winston = require("winston")
/*
 * LogCtx represents an application or service
 * Hits derive from a LogCtx
 * LogCtx is used to setup where logs actually go
*/

module.exports = LogCtx;

function LogCtx(name, logLvl) {
    this.name = name;
	this.logLvl = logLvl || Hit.LOG_LVL_NORM;
	this.history = [];
	this.logger = new (winston.Logger)({
		transports: [
			new (winston.transports.Console)(),
			new (winston.transports.File)({ filename: name + '.log' })
		]
	});

	this.lvl_to_winston = {
		3: this.logger.info,
		1: this.logger.error,
		5: this.logger.debug
	};

};

LogCtx.prototype.newHit = function (id) {
	id = id || gen_uniq_id();
	return new Hit(this, id);
};

LogCtx.prototype.emit = function (hit, lvl, now, msg, o) {
	this.lvl_to_winston[lvl](msg)
};

function gen_uniq_id() {
	function s4() {
		return Math.floor((1 + Math.random()) * 0x10000)
			.toString(16)
			.substring(1);
	}
	return s4() + s4();
}

<commit_msg>added more output on console<commit_after>var Hit = require("./Hit.js");
var winston = require("winston")
/*
 * LogCtx represents an application or service
 * Hits derive from a LogCtx
 * LogCtx is used to setup where logs actually go
*/

module.exports = LogCtx;

function LogCtx(name, logLvl) {
    this.name = name;
	this.logLvl = logLvl || Hit.LOG_LVL_NORM;
	this.history = [];
	this.logger = new (winston.Logger)({
		transports: [
			new (winston.transports.Console)({
				colorize: true,
				level: "debug",
				timestamp: true,
				prettyPrint: true
			}),
			new (winston.transports.File)({ filename: name + '.log' })
		]
	});

	this.lvl_to_winston = {
		3: this.logger.info,
		1: this.logger.error,
		5: this.logger.debug
	};

};

LogCtx.prototype.newHit = function (id) {
	id = id || gen_uniq_id();
	return new Hit(this, id);
};

LogCtx.prototype.emit = function (hit, lvl, now, msg, o) {
	this.lvl_to_winston[lvl](msg)
};

function gen_uniq_id() {
	function s4() {
		return Math.floor((1 + Math.random()) * 0x10000)
			.toString(16)
			.substring(1);
	}
	return s4() + s4();
}

<|endoftext|>


<commit_before>/* global angular Firebase */
( function() {
  'use strict';

  var app = angular.module( 'dolmen' );
      app.controller( 'PoLoginController', function() {

      var ref = new Firebase( 'https://dolmen.firebaseio.com/dashboard' );
      var authData = ref.getAuth();
      if (authData) {
        console.log( 'Property Owner is in!', authData.uid );
      }

      this.login = function( ) {
        ref.authWithOAuthRedirect( 'google', function( error ) {
          if ( error ) {
            console.log( "Failed!", error );
          } else {
            console.log( "Way to go!", authData );
            //Totally not getting here EVAH'
          }
        }, {
          remember: 'sessionOnly',
          scope: 'email'
        });
      };

    }); //End of PoLoginController
})(); //end of IIFE
<commit_msg>structuring user login  data in firebase<commit_after>/* global angular Firebase */
( function() {
  'use strict';

  var app = angular.module( 'dolmen' );
      app.controller( 'PoLoginController', function() {

      var newPropertyOwner = true;
      var ref = new Firebase( 'https://dolmen.firebaseio.com/users' );
      var authData = ref.getAuth();
      if (authData) {
        console.log( 'Property Owner is in!', authData.uid );
      }

      this.login = function( ) {
        ref.authWithOAuthRedirect( 'google', function( error ) {
          if ( error ) {
            console.log( "Failed!", error );
          } else {
            console.log( "Way to go!", authData );
            //Totally not getting here EVAH'
          }
        }, {
          remember: 'sessionOnly',
          scope: 'email'
        });
      };

      ref.onAuth( function() {
        if ( authData && newPropertyOwner ) {
          ref.child( 'users' ).child( authData.uid ).set({
            provider: authData.provider,
            name: authData.google.displayName
          });
        }
      });

    }); //End of PoLoginController
})(); //end of IIFE
<|endoftext|>


<commit_before>var ipc = require('ipc');
var watchlistParser = require('../../page_parser').watchlist;
var Promise = require('bluebird');
var util = require('../utils');

function WatchlistHandler(sessionHandler) {
    this.session_handler = sessionHandler;
    this.cache = require('../db')('watchlist-cache');
    this.app = require('../../../main');
}

WatchlistHandler.prototype.loadWatchlist = function() {
    return this.session_handler.openRequest(PROXER_BASE_URL + PROXER_PATHS.WATCHLIST, true)
        .then(watchlistParser.parseWatchlist);
};

WatchlistHandler.prototype.checkUpdates = function() {
    var self = this;
    this.loadWatchlist().then(function(result) {
        var old = self.cache.find({ type: 'watchlist-cache' });
        if(!old) {
            self.cache.push({
                type: 'watchlist-cache',
                anime: result.anime,
                manga: result.manga
            });
            return result;
        }

        var updates = {};
        updates.anime = util.getOnlineDiff(old.anime, result.anime);
        updates.manga = util.getOnlineDiff(old.manga, result.manga);
        self.cache.chain().find({ type: 'watchlist-cache' }).merge({ anime: result.anime, manga: result.manga }).value();
        return updates;
    }).then(function(updates) {
        Object.keys(updates).forEach(function(type) {
            updates[type].forEach(function(update) {
                self.app.getWindow().send('new-' + type + '-ep', update);
            });
        });
    });
};

WatchlistHandler.prototype.register = function() {
    var self = this;
    ipc.on('watchlist', function(event) {
        self.loadWatchlist().then(function(result) {
            event.sender.send('watchlist', result);
        });
    });

    ipc.on('watchlist-update', function(event) {
        self.checkUpdates();
    });
};

module.exports = WatchlistHandler;
<commit_msg>Added periodic check for watchlist updates.<commit_after>var ipc = require('ipc');
var watchlistParser = require('../../page_parser').watchlist;
var Promise = require('bluebird');
var util = require('../utils');

function WatchlistHandler(sessionHandler) {
    this.session_handler = sessionHandler;
    this.cache = require('../db')('watchlist-cache');
    this.app = require('../../../main');
    this.settings = require('../settings');
}

WatchlistHandler.prototype.loadWatchlist = function() {
    return this.session_handler.openRequest(PROXER_BASE_URL + PROXER_PATHS.WATCHLIST, true)
        .then(watchlistParser.parseWatchlist);
};

WatchlistHandler.prototype.checkUpdates = function() {
    var self = this;
    LOG.info("Checking for new watchlist updates");
    this.lastCheck = new Date().getTime();
    this.loadWatchlist().then(function(result) {
        var old = self.cache.find({ type: 'watchlist-cache' });
        if(!old) {
            self.cache.push({
                type: 'watchlist-cache',
                anime: result.anime,
                manga: result.manga
            });
            return result;
        }

        var updates = {};
        updates.anime = util.getOnlineDiff(old.anime, result.anime);
        updates.manga = util.getOnlineDiff(old.manga, result.manga);
        self.cache.chain().find({ type: 'watchlist-cache' }).merge({ anime: result.anime, manga: result.manga }).value();
        return updates;
    }).then(function(updates) {
        Object.keys(updates).forEach(function(type) {
            updates[type].forEach(function(update) {
                self.app.getWindow().send('new-' + type + '-ep', update);
            });
        });
    });
};

WatchlistHandler.prototype.register = function() {
    var self = this;
    ipc.on('watchlist', function(event) {
        self.loadWatchlist().then(function(result) {
            event.sender.send('watchlist', result);
        });
    });

    ipc.on('watchlist-update', function(event) {
        self.checkUpdates();
    });

    this.watchLoop();
};

WatchlistHandler.prototype.watchLoop = function() {
    var self = this;
    setTimeout(function() {
        var time = self.settings.getWatchlistSettings().check_interval;
        if(new Date().getTime() - self.lastCheck > time * 55000) {
            self.checkUpdates();
        }

        self.watchLoop();
    }, 30000);
};

module.exports = WatchlistHandler;
<|endoftext|>


<commit_before>function loader( loadFunction ) {

	var loaded = {},
		loading = {};

	return function( options , callback ) {

		var _options = {},
			callbacks,
			url = options[ STR_URL ],
			key;

		if ( options[ STR_CACHE ] === FALSE ) {

			for ( key in options ) {
				_options[ key ] = options[ key ];
			}

			options = _options;

			options[ STR_URL ] += ( /\?/.test( url ) ? "&" : "?" ) + "_=" + ( new Date() ).getTime();

			loadFunction( options , callback );

		} else if ( loaded[ url ] ) {

			callback();

		} else if ( callbacks = loading[ url ] ) {

			callbacks.push( callback );

		} else {

			loading[ url ] = callbacks = [ callback ];

			loadFunction( options , function() {

				while( callbacks[ STR_LENGTH ] ) {

					( callbacks.shift() )();

				}

				delete loading[ url ];
				loaded[ url ] = TRUE;

			} )

		}

	}
}

<commit_msg>Added some missing semicolons.<commit_after>function loader( loadFunction ) {

	var loaded = {},
		loading = {};

	return function( options , callback ) {

		var _options = {},
			callbacks,
			url = options[ STR_URL ],
			key;

		if ( options[ STR_CACHE ] === FALSE ) {

			for ( key in options ) {
				_options[ key ] = options[ key ];
			}

			options = _options;

			options[ STR_URL ] += ( /\?/.test( url ) ? "&" : "?" ) + "_=" + ( new Date() ).getTime();

			loadFunction( options , callback );

		} else if ( loaded[ url ] ) {

			callback();

		} else if ( callbacks = loading[ url ] ) {

			callbacks.push( callback );

		} else {

			loading[ url ] = callbacks = [ callback ];

			loadFunction( options , function() {

				while( callbacks[ STR_LENGTH ] ) {

					( callbacks.shift() )();

				}

				delete loading[ url ];
				loaded[ url ] = TRUE;

			} );

		}

	};
}

<|endoftext|>