<commit_before>import React, { Component, PropTypes } from 'react';

import ActionDelete from 'material-ui/svg-icons/action/delete';
import IconButton from 'material-ui/IconButton';
import { List, ListItem } from 'material-ui/List';
import { red700 } from 'material-ui/styles/colors';

import ModuleListDialog from '../ModuleListDialog';

class ModuleTable extends Component {
  // modules,
  // removeModule,
  state = {
    isDialogOpen: false,
    selectedModule: {},
    startIndex: 0,
  }

  handleOpen = (module) => {
    this.setState({ isDialogOpen: true, selectedModule: module.moduleDetail });
  }

  handleClose = () => (this.setState({ isDialogOpen: false }))

  render() {
    const { isDialogOpen, selectedModule } = this.state;
    const { modules, removeModule } = this.props;

    return (

        <List style={{ width: '100%', paddingLeft: '15%' }}>
          {modules.map(module =>
            <ListItem
              key={module.ModuleCode}
              rightIconButton={
                <IconButton
                  onTouchTap={() => removeModule(module.ModuleCode)}
                  touch
                  tooltip="Remove module"
                  tooltipPosition="bottom-left"
                >
                  <ActionDelete color={red700} />
                </IconButton>
              }
              primaryText={module.ModuleCode}
              secondaryText={module.ModuleTitle}
              onTouchTap={() => this.handleOpen(module)}
            />
          )}
        </List>
        <ModuleListDialog
          module={selectedModule}
          open={isDialogOpen}
          handleClose={this.handleClose}
        />

    );
  }
}

ModuleTable.propTypes = {
  modules: PropTypes.array.isRequired,
  removeModule: PropTypes.func.isRequired,
};

export default ModuleTable;
<commit_msg>fix name of module<commit_after>import React, { Component, PropTypes } from 'react';

import ActionDelete from 'material-ui/svg-icons/action/delete';
import IconButton from 'material-ui/IconButton';
import { List, ListItem } from 'material-ui/List';
import { red700 } from 'material-ui/styles/colors';

import ModuleListDialog from '../ModuleListDialog';

class ModuleTable extends Component {
  // modules,
  // removeModule,
  state = {
    isDialogOpen: false,
    selectedModule: {},
    startIndex: 0,
  }

  handleOpen = (module) => {
    this.setState({ isDialogOpen: true, selectedModule: module.moduleDetail });
  }

  handleClose = () => (this.setState({ isDialogOpen: false }))

  render() {
    const { isDialogOpen, selectedModule } = this.state;
    const { modules, removeModule } = this.props;
    return (

        <List style={{ width: '100%', paddingLeft: '15%' }}>
          {modules.map(module =>
            <ListItem
              key={module.moduleDetail.code}
              rightIconButton={
                <IconButton
                  onTouchTap={() => removeModule(module.moduleDetail.code)}
                  touch
                  tooltip="Remove module"
                  tooltipPosition="bottom-left"
                >
                  <ActionDelete color={red700} />
                </IconButton>
              }
              primaryText={module.moduleDetail.code}
              secondaryText={module.moduleDetail.title}
              onTouchTap={() => this.handleOpen(module)}
            />
          )}
        </List>
        <ModuleListDialog
          module={selectedModule}
          open={isDialogOpen}
          handleClose={this.handleClose}
        />

    );
  }
}

ModuleTable.propTypes = {
  modules: PropTypes.array.isRequired,
  removeModule: PropTypes.func.isRequired,
};

export default ModuleTable;
<|endoftext|>


<commit_before>/**
 *
 */
var assert=require('assert');
assert.equal(true, true);
var EchoTest=require('./echo.js');

var ws=require('ws');

var series=require("async").series(
		[
function(callback){
	//test direct load
	EchoTest(require('node-rproxy').AutoConnect, require('node-rproxy').Bridge, {echo:9001, bridge:9002, count:20, eachClient:function(client, i){
		client.on('message',function(m){
			console.log('test 0, client '+i+' success');
		});
	}}, function(err, message){

		if(err){
			assert.fail(err);
		}

		callback(null);

	});
},
function(callback){

	var port=9003
	console.log('Running bridge with custom http server: '+port);
	var http=require('http');
	var server = http.createServer(function(request, response){
		response.end('Http Server: ' + request.url);
	});

	var Bridge= require('node-rproxy').Bridge;
	new Bridge({server:server},function(){
		console.log('hello world server: http+ws');
		server.close();
		callback(null);
	}, function(){

		assert.fail('should not have connected');

	});

	server.listen(port, function(){

		console.log('listening on: '+port);

		http.get("http://localhost:"+port, function(res) {
			console.log("success: " + res.statusCode);
		}).on('error', function(e) {
			assert.fail("Got error: " + e.message)
		});

		(new ws('ws://localhost:'+port)).client.on('open', function(){

			console.log('connected client');

		}).on('close', function(code, message){

			console.log('close client');

		}).on('error',function(error){
			console.log('error client');
		});

	});

}

],
function(err, results) {
			if(err){
				assert.fail(err.message||err);
			}
			console.log('tests completed successfully');
			process.exit(0);
		});

<commit_msg>oops variable <commit_after>/**
 *
 */
var assert=require('assert');
assert.equal(true, true);
var EchoTest=require('./echo.js');

var ws=require('ws');

var series=require("async").series(
		[
function(callback){
	//test direct load
	EchoTest(require('node-rproxy').AutoConnect, require('node-rproxy').Bridge, {echo:9001, bridge:9002, count:20, eachClient:function(client, i){
		client.on('message',function(m){
			console.log('test 0, client '+i+' success');
		});
	}}, function(err, message){

		if(err){
			assert.fail(err);
		}

		callback(null);

	});
},
function(callback){

	var port=9003
	console.log('Running bridge with custom http server: '+port);
	var http=require('http');
	var server = http.createServer(function(request, response){
		response.end('Http Server: ' + request.url);
	});

	var Bridge= require('node-rproxy').Bridge;
	new Bridge({server:server},function(){
		console.log('hello world server: http+ws');
		server.close();
		callback(null);
	}, function(){

		assert.fail('should not have connected');

	});

	server.listen(port, function(){

		console.log('listening on: '+port);

		http.get("http://localhost:"+port, function(res) {
			console.log("success: " + res.statusCode);
		}).on('error', function(e) {
			assert.fail("Got error: " + e.message)
		});

		(new ws('ws://localhost:'+port)).on('open', function(){

			console.log('connected client');

		}).on('close', function(code, message){

			console.log('close client');

		}).on('error',function(error){
			console.log('error client');
		});

	});

}

],
function(err, results) {
			if(err){
				assert.fail(err.message||err);
			}
			console.log('tests completed successfully');
			process.exit(0);
		});

<|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@kadira/react-native-storybook';

import TutorialVideo from './TutorialVideo';

storiesOf('components/TutorialVideo', module).add('placeholder', () => (
  <TutorialVideo video={require('../assets/video/video.mp4')} />
));
<commit_msg>TutorialVideo: naming<commit_after>import React from 'react';
import { storiesOf } from '@kadira/react-native-storybook';

import TutorialVideo from './TutorialVideo';

storiesOf('components/TutorialVideo', module).add('placeholder', () => (
  <TutorialVideo video={require('../assets/videos/placeholder.mp4')} />
));
<|endoftext|>


<commit_before>jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;

function ngWebAudioTest(fallback) {
  var wa;

  beforeAll(function() {
    if (fallback) {
      window.AudioContext = null;
      window.webkitAudioContext = null;
    }
  });

  beforeEach(module('ngWebAudio'));
  beforeEach(inject(function(WebAudio) {
    wa = WebAudio('base/tests/test.mp3');
  }));

  it('test mode', function() {
    if (fallback) expect(wa.audioSrc).toBeDefined();
    else if (window.AudioContext) expect(wa.audioSrc).toBeUndefined();
  });

  it('should play audio', function(done) {
    wa.play();

    wa.onPlay = function() {
      setTimeout(function() {
        expect(wa.offset()).toBeGreaterThan(0);
        expect(wa.stopped).toBe(false);
      }, 2000);
    };

    wa.onEnd = function() {
      expect(wa.offset()).toBe(0);
      expect(wa.stopped).toBe(true);

      setTimeout(function() {
        expect(wa.offset()).toBe(0);
        expect(wa.stopped).toBe(true);
        done();
      }, 500);
    };
  });

  it('should loop audio', function(done) {
    wa.options.loop = true;
    wa.play();

    wa.onPlay = function() {
      setTimeout(function() {
        expect(wa.onEnd).not.toHaveBeenCalled();
        wa.stop();
        expect(wa.onEnd).toHaveBeenCalled();
        done();
      }, 8000);
    };

    wa.onEnd = function() {};
    spyOn(wa, 'onEnd');
  });

  it('should stop audio', function(done) {
    wa.play();

    wa.onPlay = function() {
      setTimeout(function() {
        expect(wa.onEnd).not.toHaveBeenCalled();
        expect(wa.offset()).toBeGreaterThan(0);
        expect(wa.stopped).toBe(false);
        wa.stop();
        expect(wa.offset()).toBe(0);
        expect(wa.stopped).toBe(true);
      }, 1000);
    };

    wa.onEnd = function () {
      setTimeout(function() {
        done();
      }, 100);
    };

    spyOn(wa, 'onEnd').and.callThrough();
  });

  it('should pause audio', function(done) {
    wa.play();

    wa.onPlay = function() {
      var offset1, offset2;
      wa.onPlay = null;

      setTimeout(function () {
        wa.pause();
        offset1 = wa.offset();
      }, 1000);

      setTimeout(function () {
        expect(wa.offset()).toBeCloseTo(offset1, 10);
        wa.play();
      }, 2000);

      setTimeout(function () {
        wa.pause();
        offset2 = wa.offset();
      }, 3000);

      setTimeout(function () {
        expect(wa.offset()).toBeCloseTo(offset2, 10);
        expect(offset1).toBeLessThan(offset2);
        wa.play();
      }, 4000);
    };

    wa.onEnd = function() {
      setTimeout(function() {
        done();
      }, 100);
    };
  });

  it('offset should be increasing', function(done) {
    var lastOffset = 0;
    wa.play();
    expect(wa.offset()).toBe(0);

    wa.onPlay = function() {
      for (var i = 1; i < 10; i++) {
        setTimeout(function () {
          var offset;
          expect(offset = wa.offset()).toBeGreaterThan(lastOffset);
          lastOffset = offset;
        }, 100 * i);
      }
    };

    wa.onEnd = function() {
      setTimeout(function() {
        done();
      }, 100);
      done();
    };
  });
}

describe('ngWebAudio', ngWebAudioTest);
describe('ngWebAudioFallback', function() {
  ngWebAudioTest(true);
});
<commit_msg>Added onBuffered event tests<commit_after>jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;

function ngWebAudioTest(fallback) {
  var WebAudio, wa;

  beforeAll(function() {
    if (fallback) {
      window.AudioContext = null;
      window.webkitAudioContext = null;
    }
  });

  beforeEach(module('ngWebAudio'));
  beforeEach(inject(function(_WebAudio_) {
    WebAudio = _WebAudio_;
    wa = WebAudio('base/tests/test.mp3');
  }));

  it('test mode', function() {
    var AudioContext = window.AudioContext || window.webkitAudioContext;
    if (fallback) expect(wa.audioSrc).toBeDefined();
    else if (AudioContext) expect(wa.audioSrc).toBeUndefined();
  });

  it('should play audio', function(done) {
    wa.play();

    wa.onPlay = function() {
      setTimeout(function() {
        expect(wa.offset()).toBeGreaterThan(0);
        expect(wa.stopped).toBe(false);
      }, 2000);
    };

    wa.onEnd = function() {
      expect(wa.offset()).toBe(0);
      expect(wa.stopped).toBe(true);

      setTimeout(function() {
        expect(wa.offset()).toBe(0);
        expect(wa.stopped).toBe(true);
        done();
      }, 500);
    };
  });

  it('should loop audio', function(done) {
    wa.options.loop = true;
    wa.play();

    wa.onPlay = function() {
      setTimeout(function() {
        expect(wa.onEnd).not.toHaveBeenCalled();
        wa.stop();
        expect(wa.onEnd).toHaveBeenCalled();
        done();
      }, 8000);
    };

    wa.onEnd = function() {};
    spyOn(wa, 'onEnd');
  });

  it('should stop audio', function(done) {
    wa.play();

    wa.onPlay = function() {
      setTimeout(function() {
        expect(wa.onEnd).not.toHaveBeenCalled();
        expect(wa.offset()).toBeGreaterThan(0);
        expect(wa.stopped).toBe(false);
        wa.stop();
        expect(wa.offset()).toBe(0);
        expect(wa.stopped).toBe(true);
      }, 1000);
    };

    wa.onEnd = function () {
      setTimeout(function() {
        done();
      }, 100);
    };

    spyOn(wa, 'onEnd').and.callThrough();
  });

  it('should pause audio', function(done) {
    wa.play();

    wa.onPlay = function() {
      var offset1, offset2;
      wa.onPlay = null;

      setTimeout(function () {
        wa.pause();
        offset1 = wa.offset();
      }, 1000);

      setTimeout(function () {
        expect(wa.offset()).toBeCloseTo(offset1, 10);
        wa.play();
      }, 2000);

      setTimeout(function () {
        wa.pause();
        offset2 = wa.offset();
      }, 3000);

      setTimeout(function () {
        expect(wa.offset()).toBeCloseTo(offset2, 10);
        expect(offset1).toBeLessThan(offset2);
        wa.play();
      }, 4000);
    };

    wa.onEnd = function() {
      setTimeout(function() {
        done();
      }, 100);
    };
  });

  it('offset should be increasing', function(done) {
    var lastOffset = 0;
    wa.play();
    expect(wa.offset()).toBe(0);

    wa.onPlay = function() {
      for (var i = 1; i < 10; i++) {
        setTimeout(function () {
          var offset;
          expect(offset = wa.offset()).toBeGreaterThan(lastOffset);
          lastOffset = offset;
        }, 100 * i);
      }
    };

    wa.onEnd = function() {
      setTimeout(function() {
        done();
      }, 100);
      done();
    };
  });

  it('should cache', function(done) {
    // Caching is not handled by us in fallback (HTML Audio)
    if (!wa.isWebAudio) {
      done();
      return;
    }

    expect(wa.isCached).not.toBeUndefined();
    expect(wa.isCached()).toBe(false);

    wa.onBuffered = function() {
      var wa_cached = WebAudio(wa.src);

      expect(wa.isCached()).toBe(true);
      expect(wa_cached.isCached()).toBe(true);

      wa_cached.onBuffered = function() {
        expect(wa.isCached()).toBe(true);
        expect(wa_cached.isCached()).toBe(true);
        done();
      };
    };
  });

  describe('onBuffered event', function() {
    it('should fire if not buffered', function(done) {
      wa.onBuffered = function() { done(); };
    });

    it('should fire if already buffered', function(done) {
      wa.onBuffered = function() {
        var wa_cached = WebAudio(wa.src);
        wa_cached.onBuffered = function() { done(); };
      };
    });
  });
}

describe('ngWebAudio', ngWebAudioTest);
describe('ngWebAudioFallback', function() {
  ngWebAudioTest(true);
});
<|endoftext|>


<commit_before>var deepEquals = require("assert").deepEqual,
    CSSwhat = require("../");

var tests = [
	["div", [ [ { type: 'tag', name: 'div' } ] ], "simple tag"],
	["*", 	[ [ { type: 'universal' } ] ], "universal"],

	//traversal
	["div div", [ [ { type: 'tag', name: 'div' },
    { type: 'descendant' },
    { type: 'tag', name: 'div' } ] ], "descendant"],
    ["div\t \n \tdiv", [ [ { type: 'tag', name: 'div' },
    { type: 'descendant' },
    { type: 'tag', name: 'div' } ] ], "descendant /w whitespace"],
    ["div + div", [ [ { type: 'tag', name: 'div' },
    { type: 'adjacent' },
    { type: 'tag', name: 'div' } ] ], "adjacent"],
    ["div ~ div", [ [ { type: 'tag', name: 'div' },
    { type: 'sibling' },
    { type: 'tag', name: 'div' } ] ], "sibling"],

    //attributes
    [".foo", [ [ { type: 'class', value: 'foo' } ] ], "simple class"]

    //TODO
];

tests.forEach(function(arr){
	arr[0] = CSSwhat(arr[0]);
	deepEquals.apply(null, arr);
	console.log(arr[2], "passed");
});<commit_msg>added a couple of escaped attribute tests<commit_after>var deepEquals = require("assert").deepEqual,
    CSSwhat = require("../");

var tests = [
	["div", [ [ { type: 'tag', name: 'div' } ] ], "simple tag"],
	["*", 	[ [ { type: 'universal' } ] ], "universal"],

	//traversal
	["div div", [ [ { type: 'tag', name: 'div' },
    { type: 'descendant' },
    { type: 'tag', name: 'div' } ] ], "descendant"],
    ["div\t \n \tdiv", [ [ { type: 'tag', name: 'div' },
    { type: 'descendant' },
    { type: 'tag', name: 'div' } ] ], "descendant /w whitespace"],
    ["div + div", [ [ { type: 'tag', name: 'div' },
    { type: 'adjacent' },
    { type: 'tag', name: 'div' } ] ], "adjacent"],
    ["div ~ div", [ [ { type: 'tag', name: 'div' },
    { type: 'sibling' },
    { type: 'tag', name: 'div' } ] ], "sibling"],

    //attributes
    [".foo", [ [ { type: 'class', value: 'foo' } ] ], "simple class"],
    ["[name^='foo[']",[[{"type":"attribute","name":"name","action":"start","value":"foo[","ignoreCase":false}]],"escaped attribute"],
    ["[name^='foo[bar]']",[[{"type":"attribute","name":"name","action":"start","value":"foo[bar]","ignoreCase":false}]],"escaped attribute"],
    ["[name$='[bar]']",[[{"type":"attribute","name":"name","action":"end","value":"[bar]","ignoreCase":false}]],"escaped attribute"],
    ["[href *= 'google']",[[{"type":"attribute","name":"href","action":"any","value":"google","ignoreCase":false}]],"escaped attribute"],
    ["[name=foo\\.baz]",[[{"type":"attribute","name":"name","action":"equals","value":"foo.baz","ignoreCase":false}]],"escaped attribute"],
    ["[name=foo\\[bar\\]]",[[{"type":"attribute","name":"name","action":"equals","value":"foo[bar]","ignoreCase":false}]],"escaped attribute"],
    ["[xml\\:test]",[[{"type":"attribute","name":"xml:test","action":"exists","value":"","ignoreCase":false}]],"escaped attribute"]

    //TODO
];

tests.forEach(function(arr){
	arr[0] = CSSwhat(arr[0]);
	deepEquals.apply(null, arr);
	console.log(arr[2], "passed");
});<|endoftext|>


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

  // PRE RELEASE
  // TODO(jelbourn): Documentation
  // TODO(jelbourn): Demo that uses moment.js

  // POST RELEASE
  // TODO(jelbourn): make sure this plays well with validation and ngMessages.
  // TODO(jelbourn): calendar pane doesn't open up outside of visible viewport.
  // TODO(jelbourn): forward more attributes to the internal input (required, autofocus, etc.)
  // TODO(jelbourn): error state
  // TODO(jelbourn): something better for mobile (calendar panel takes up entire screen?)
  // TODO(jelbourn): input behavior (masking? auto-complete?)
  // TODO(jelbourn): UTC mode
  // TODO(jelbourn): RTL

  angular.module('material.components.datepicker')
      .directive('mdDatepicker', datePickerDirective);

  /**
   * @ngdoc directive
   * @name mdDatepicker
   * @module material.components.datepicker
   *
   * @param {Date} ng-model The component's model. Uses a JavaScript Date object.
   * @param {boolean=} disabled Whether the datepicker is disabled.
   *
   * @description
   * `<md-datepicker>` is a component used to select a single date.
   * For information on how to configure internationalization for the date piicker,
   * see `$mdDateLocaleProvider`.
   *
   * @usage
   * <hljs lang="html">
   *   <md-datepicker ng-model="birthday"></md-datepicker>
   * </hljs>
   *
   */
  function datePickerDirective() {
    return {
      template:
          // Buttons are not in the tab order because users can open the calendar via keyboard
          // interaction on the text input, and multiple tab stops for one component (picker)
          // may be confusing.
          '<md-button class="md-datepicker-button md-icon-button" type="button" ' +
              'tabindex="-1" aria-hidden="true" ' +
              'ng-click="ctrl.openCalendarPane($event)">' +
            '<md-icon class="md-datepicker-calendar-icon" md-svg-icon="md-calendar"></md-icon>' +
          '</md-button>' +
          '
' +
            '<input class="md-datepicker-input" aria-haspopup="true">' +

            '<md-button md-no-ink class="md-datepicker-triangle-button md-icon-button" ' +
                'ng-click="ctrl.openCalendarPane($event)" ' +
                'aria-label="{{::ctrl.dateLocale.msgOpenCalendar}}">' +
              '

' +
            '</md-button>' +
          '
' +

          // This pane will be detached from here and re-attached to the document body.
          '
' +
            '

' +
            '
' +
              '<md-calendar role="dialog" aria-label="{{::ctrl.dateLocale.msgCalendar}}" ' +
                  'ng-model="ctrl.date" ng-if="ctrl.isCalendarOpen"></md-calendar>' +
            '
' +
          '
',
      require: ['ngModel', 'mdDatepicker'],
      scope: {
        placeholder: '@mdPlaceholder'
      },
      controller: DatePickerCtrl,
      controllerAs: 'ctrl',
      bindToController: true,
      link: function(scope, element, attr, controllers) {
        var ngModelCtrl = controllers[0];
        var mdDatePickerCtrl = controllers[1];

        mdDatePickerCtrl.configureNgModel(ngModelCtrl);
      }
    };
  }

  /** Additional offset for the input's `size` attribute, which is updated based on its content. */
  var EXTRA_INPUT_SIZE = 3;

  /**
   * Controller for md-datepicker.
   *
   * @ngInject @constructor
   */
  function DatePickerCtrl($scope, $element, $attrs, $compile, $timeout, $mdConstant, $mdTheming,
      $mdUtil, $mdDateLocale, $$mdDateUtil, $$rAF) {
    /** @final */
    this.$compile = $compile;

    /** @final */
    this.$timeout = $timeout;

    /** @final */
    this.dateLocale = $mdDateLocale;

    /** @final */
    this.dateUtil = $$mdDateUtil;

    /** @final */
    this.$mdConstant = $mdConstant;

    /* @final */
    this.$mdUtil = $mdUtil;

    /** @final */
    this.$$rAF = $$rAF;

    /** @type {!angular.NgModelController} */
    this.ngModelCtrl = null;

    /** @type {HTMLInputElement} */
    this.inputElement = $element[0].querySelector('input');

    /** @type {HTMLElement} */
    this.inputContainer = $element[0].querySelector('.md-datepicker-input-container');

    /** @type {HTMLElement} Floating calendar pane. */
    this.calendarPane = $element[0].querySelector('.md-datepicker-calendar-pane');

    /** @type {HTMLElement} Calendar icon button. */
    this.calendarButton = $element[0].querySelector('.md-datepicker-button');

    /** @final {!angular.JQLite} */
    this.$element = $element;

    /** @final {!angular.Scope} */
    this.$scope = $scope;

    /** @type {Date} */
    this.date = null;

    /** @type {boolean} */
    this.isDisabled;
    this.setDisabled($element[0].disabled || angular.isString($attrs['disabled']));

    /** @type {boolean} Whether the date-picker's calendar pane is open. */
    this.isCalendarOpen = false;

    /**
     * Element from which the calendar pane was opened. Keep track of this so that we can return
     * focus to it when the pane is closed.
     * @type {HTMLElement}
     */
    this.calendarPaneOpenedFrom = null;

    this.calendarPane.id = 'md-date-pane' + $mdUtil.nextUid();

    $mdTheming($element);

    /** Pre-bound click handler is saved so that the event listener can be removed. */
    this.bodyClickHandler = angular.bind(this, this.handleBodyClick);

    // Unless the user specifies so, the datepicker should not be a tab stop.
    // This is necessary because ngAria might add a tabindex to anything with an ng-model
    // (based on whether or not the user has turned that particular feature on/off).
    if (!$attrs['tabindex']) {
      $element.attr('tabindex', '-1');
    }

    this.installPropertyInterceptors();
    this.attachChangeListeners();
    this.attachInterationListeners();

    var self = this;
    $scope.$on('$destroy', function() {
      self.detachCalendarPane();
    });
  }

  /**
   * Sets up the controller's reference to ngModelController.
   * @param {!angular.NgModelController} ngModelCtrl
   */
  DatePickerCtrl.prototype.configureNgModel = function(ngModelCtrl) {
    this.ngModelCtrl = ngModelCtrl;

    var self = this;
    ngModelCtrl.$render = function() {
      self.date = self.ngModelCtrl.$viewValue;
      self.inputElement.value = self.dateLocale.formatDate(self.date);
      self.inputElement.size = self.inputElement.value.length + EXTRA_INPUT_SIZE;
    };
  };

  /**
   * Attach event listeners for both the text input and the md-calendar.
   * Events are used instead of ng-model so that updates don't infinitely update the other
   * on a change. This should also be more performant than using a $watch.
   */
  DatePickerCtrl.prototype.attachChangeListeners = function() {
    var self = this;

    self.$scope.$on('md-calendar-change', function(event, date) {
      self.ngModelCtrl.$setViewValue(date);
      self.inputElement.value = self.dateLocale.formatDate(date);
      self.closeCalendarPane();
    });

    // TODO(jelbourn): Debounce this input event.
    self.inputElement.addEventListener('input', function() {
      var inputString = self.inputElement.value;
      var parsedDate = self.dateLocale.parseDate(inputString);

      self.inputElement.size = inputString.length + EXTRA_INPUT_SIZE;

      if (self.dateUtil.isValidDate(parsedDate) && self.dateLocale.isDateComplete(inputString)) {
        self.date = parsedDate;
        self.$scope.$apply();
      }
    });
  };

  /** Attach event listeners for user interaction. */
  DatePickerCtrl.prototype.attachInterationListeners = function() {
    var self = this;
    var $scope = this.$scope;
    var keyCodes = this.$mdConstant.KEY_CODE;

    // Add event listener through angular so that we can triggerHandler in unit tests.
    angular.element(self.inputElement).on('keydown', function(event) {
      if (event.altKey && event.keyCode == keyCodes.DOWN_ARROW) {
        self.openCalendarPane(event);
        $scope.$digest();
      }
    });

    $scope.$on('md-calendar-close', function() {
      self.closeCalendarPane();
    });
  };

  /**
   * Capture properties set to the date-picker and imperitively handle internal changes.
   * This is done to avoid setting up additional $watches.
   */
  DatePickerCtrl.prototype.installPropertyInterceptors = function() {
    var self = this;

    // Intercept disabled on the date-picker element to disable the internal input.
    // This avoids two bindings (outer scope to ctrl, ctrl to input).
    Object.defineProperty(this.$element[0], 'disabled', {
      get: function() { return self.isDisabled; },
      set: angular.bind(self, self.setDisabled)
    });

    Object.defineProperty(this, 'placeholder', {
      get: function() { return self.inputElement.placeholder },
      set: function(value) { self.inputElement.placeholder = value; }
    });
  };

  /**
   * Sets whether the date-picker is disabled.
   * @param {boolean} isDisabled
   */
  DatePickerCtrl.prototype.setDisabled = function(isDisabled) {
    this.isDisabled = isDisabled;
    this.inputElement.disabled = isDisabled;
    this.calendarButton.disabled = isDisabled;
  };

  /** Position and attach the floating calendar to the document. */
  DatePickerCtrl.prototype.attachCalendarPane = function() {
    var calendarPane = this.calendarPane;
    this.$element.addClass('md-datepicker-open');

    var elementRect = this.inputContainer.getBoundingClientRect();
    var bodyRect = document.body.getBoundingClientRect();

    calendarPane.style.left = (elementRect.left - bodyRect.left) + 'px';
    calendarPane.style.top = (elementRect.top - bodyRect.top) + 'px';
    document.body.appendChild(this.calendarPane);

    // Add CSS class after one frame to trigger open animation.
    this.$$rAF(function() {
      calendarPane.classList.add('md-pane-open');
    });
  };

  /** Detach the floating calendar pane from the document. */
  DatePickerCtrl.prototype.detachCalendarPane = function() {
    this.$element.removeClass('md-datepicker-open');
    this.calendarPane.classList.remove('md-pane-open');

    // Use native DOM removal because we do not want any of the angular state of this element
    // to be disposed.
    this.calendarPane.parentNode.removeChild(this.calendarPane);
  };

  /**
   * Open the floating calendar pane.
   * @param {Event} event
   */
  DatePickerCtrl.prototype.openCalendarPane = function(event) {
    if (!this.isCalendarOpen && !this.isDisabled) {
      this.isCalendarOpen = true;
      this.calendarPaneOpenedFrom = event.target;
      this.attachCalendarPane();
      this.focusCalendar();

      // Because the calendar pane is attached directly to the body, it is possible that the
      // rest of the component (input, etc) is in a different scrolling container, such as
      // an md-content. This means that, if the container is scrolled, the pane would remain
      // stationary. To remedy this, we disable scrolling while the calendar pane is open, which
      // also matches the native behavior for things like `<select>` on Mac and Windows.
      this.$mdUtil.disableScrollAround(this.calendarPane);

      // Attach click listener inside of a timeout because, if this open call was triggered by a
      // click, we don't want it to be immediately propogated up to the body and handled.
      var self = this;
      this.$mdUtil.nextTick(function() {
        document.body.addEventListener('click', self.bodyClickHandler);
      }, false);
    }
  };

  /** Close the floating calendar pane. */
  DatePickerCtrl.prototype.closeCalendarPane = function() {
    this.isCalendarOpen = false;
    this.detachCalendarPane();
    this.calendarPaneOpenedFrom.focus();
    this.calendarPaneOpenedFrom = null;
    this.$mdUtil.enableScrolling();

    document.body.removeEventListener('click', this.bodyClickHandler);
  };

  /** Gets the controller instance for the calendar in the floating pane. */
  DatePickerCtrl.prototype.getCalendarCtrl = function() {
    return angular.element(this.calendarPane.querySelector('md-calendar')).controller('mdCalendar');
  };

  /** Focus the calendar in the floating pane. */
  DatePickerCtrl.prototype.focusCalendar = function() {
    // Use a timeout in order to allow the calendar to be rendered, as it is gated behind an ng-if.
    var self = this;
    this.$mdUtil.nextTick(function() {
      self.getCalendarCtrl().focus();
    }, false);
  };

  /**
   * Handles a click on the document body when the floating calendar pane is open.
   * Closes the floating calendar pane if the click is not inside of it.
   * @param {MouseEvent} event
   */
  DatePickerCtrl.prototype.handleBodyClick = function(event) {
    if (this.isCalendarOpen) {
      // TODO(jelbourn): way want to also include the md-datepicker itself in this check.
      var isInCalendar = this.$mdUtil.getClosest(event.target, 'md-calendar');
      if (!isInCalendar) {
        this.closeCalendarPane();
      }

      this.$scope.$digest();
    }
  };
})();
<commit_msg>fix(calendar): Update ngModel instead of ctrl.date on input change<commit_after>(function() {
  'use strict';

  // PRE RELEASE
  // TODO(jelbourn): Documentation
  // TODO(jelbourn): Demo that uses moment.js

  // POST RELEASE
  // TODO(jelbourn): make sure this plays well with validation and ngMessages.
  // TODO(jelbourn): calendar pane doesn't open up outside of visible viewport.
  // TODO(jelbourn): forward more attributes to the internal input (required, autofocus, etc.)
  // TODO(jelbourn): error state
  // TODO(jelbourn): something better for mobile (calendar panel takes up entire screen?)
  // TODO(jelbourn): input behavior (masking? auto-complete?)
  // TODO(jelbourn): UTC mode
  // TODO(jelbourn): RTL

  angular.module('material.components.datepicker')
      .directive('mdDatepicker', datePickerDirective);

  /**
   * @ngdoc directive
   * @name mdDatepicker
   * @module material.components.datepicker
   *
   * @param {Date} ng-model The component's model. Uses a JavaScript Date object.
   * @param {boolean=} disabled Whether the datepicker is disabled.
   *
   * @description
   * `<md-datepicker>` is a component used to select a single date.
   * For information on how to configure internationalization for the date piicker,
   * see `$mdDateLocaleProvider`.
   *
   * @usage
   * <hljs lang="html">
   *   <md-datepicker ng-model="birthday"></md-datepicker>
   * </hljs>
   *
   */
  function datePickerDirective() {
    return {
      template:
          // Buttons are not in the tab order because users can open the calendar via keyboard
          // interaction on the text input, and multiple tab stops for one component (picker)
          // may be confusing.
          '<md-button class="md-datepicker-button md-icon-button" type="button" ' +
              'tabindex="-1" aria-hidden="true" ' +
              'ng-click="ctrl.openCalendarPane($event)">' +
            '<md-icon class="md-datepicker-calendar-icon" md-svg-icon="md-calendar"></md-icon>' +
          '</md-button>' +
          '
' +
            '<input class="md-datepicker-input" aria-haspopup="true">' +

            '<md-button md-no-ink class="md-datepicker-triangle-button md-icon-button" ' +
                'ng-click="ctrl.openCalendarPane($event)" ' +
                'aria-label="{{::ctrl.dateLocale.msgOpenCalendar}}">' +
              '

' +
            '</md-button>' +
          '
' +

          // This pane will be detached from here and re-attached to the document body.
          '
' +
            '

' +
            '
' +
              '<md-calendar role="dialog" aria-label="{{::ctrl.dateLocale.msgCalendar}}" ' +
                  'ng-model="ctrl.date" ng-if="ctrl.isCalendarOpen"></md-calendar>' +
            '
' +
          '
',
      require: ['ngModel', 'mdDatepicker'],
      scope: {
        placeholder: '@mdPlaceholder'
      },
      controller: DatePickerCtrl,
      controllerAs: 'ctrl',
      bindToController: true,
      link: function(scope, element, attr, controllers) {
        var ngModelCtrl = controllers[0];
        var mdDatePickerCtrl = controllers[1];

        mdDatePickerCtrl.configureNgModel(ngModelCtrl);
      }
    };
  }

  /** Additional offset for the input's `size` attribute, which is updated based on its content. */
  var EXTRA_INPUT_SIZE = 3;

  /**
   * Controller for md-datepicker.
   *
   * @ngInject @constructor
   */
  function DatePickerCtrl($scope, $element, $attrs, $compile, $timeout, $mdConstant, $mdTheming,
      $mdUtil, $mdDateLocale, $$mdDateUtil, $$rAF) {
    /** @final */
    this.$compile = $compile;

    /** @final */
    this.$timeout = $timeout;

    /** @final */
    this.dateLocale = $mdDateLocale;

    /** @final */
    this.dateUtil = $$mdDateUtil;

    /** @final */
    this.$mdConstant = $mdConstant;

    /* @final */
    this.$mdUtil = $mdUtil;

    /** @final */
    this.$$rAF = $$rAF;

    /** @type {!angular.NgModelController} */
    this.ngModelCtrl = null;

    /** @type {HTMLInputElement} */
    this.inputElement = $element[0].querySelector('input');

    /** @type {HTMLElement} */
    this.inputContainer = $element[0].querySelector('.md-datepicker-input-container');

    /** @type {HTMLElement} Floating calendar pane. */
    this.calendarPane = $element[0].querySelector('.md-datepicker-calendar-pane');

    /** @type {HTMLElement} Calendar icon button. */
    this.calendarButton = $element[0].querySelector('.md-datepicker-button');

    /** @final {!angular.JQLite} */
    this.$element = $element;

    /** @final {!angular.Scope} */
    this.$scope = $scope;

    /** @type {Date} */
    this.date = null;

    /** @type {boolean} */
    this.isDisabled;
    this.setDisabled($element[0].disabled || angular.isString($attrs['disabled']));

    /** @type {boolean} Whether the date-picker's calendar pane is open. */
    this.isCalendarOpen = false;

    /**
     * Element from which the calendar pane was opened. Keep track of this so that we can return
     * focus to it when the pane is closed.
     * @type {HTMLElement}
     */
    this.calendarPaneOpenedFrom = null;

    this.calendarPane.id = 'md-date-pane' + $mdUtil.nextUid();

    $mdTheming($element);

    /** Pre-bound click handler is saved so that the event listener can be removed. */
    this.bodyClickHandler = angular.bind(this, this.handleBodyClick);

    // Unless the user specifies so, the datepicker should not be a tab stop.
    // This is necessary because ngAria might add a tabindex to anything with an ng-model
    // (based on whether or not the user has turned that particular feature on/off).
    if (!$attrs['tabindex']) {
      $element.attr('tabindex', '-1');
    }

    this.installPropertyInterceptors();
    this.attachChangeListeners();
    this.attachInterationListeners();

    var self = this;
    $scope.$on('$destroy', function() {
      self.detachCalendarPane();
    });
  }

  /**
   * Sets up the controller's reference to ngModelController.
   * @param {!angular.NgModelController} ngModelCtrl
   */
  DatePickerCtrl.prototype.configureNgModel = function(ngModelCtrl) {
    this.ngModelCtrl = ngModelCtrl;

    var self = this;
    ngModelCtrl.$render = function() {
      self.date = self.ngModelCtrl.$viewValue;
      self.inputElement.value = self.dateLocale.formatDate(self.date);
      self.inputElement.size = self.inputElement.value.length + EXTRA_INPUT_SIZE;
    };
  };

  /**
   * Attach event listeners for both the text input and the md-calendar.
   * Events are used instead of ng-model so that updates don't infinitely update the other
   * on a change. This should also be more performant than using a $watch.
   */
  DatePickerCtrl.prototype.attachChangeListeners = function() {
    var self = this;

    self.$scope.$on('md-calendar-change', function(event, date) {
      self.ngModelCtrl.$setViewValue(date);
      self.inputElement.value = self.dateLocale.formatDate(date);
      self.closeCalendarPane();
    });

    // TODO(jelbourn): Debounce this input event.
    self.inputElement.addEventListener('input', function() {
      var inputString = self.inputElement.value;
      var parsedDate = self.dateLocale.parseDate(inputString);

      self.inputElement.size = inputString.length + EXTRA_INPUT_SIZE;

      if (self.dateUtil.isValidDate(parsedDate) && self.dateLocale.isDateComplete(inputString)) {
        self.ngModelCtrl.$setViewValue(parsedDate);
        self.$scope.$apply();
      }
    });
  };

  /** Attach event listeners for user interaction. */
  DatePickerCtrl.prototype.attachInterationListeners = function() {
    var self = this;
    var $scope = this.$scope;
    var keyCodes = this.$mdConstant.KEY_CODE;

    // Add event listener through angular so that we can triggerHandler in unit tests.
    angular.element(self.inputElement).on('keydown', function(event) {
      if (event.altKey && event.keyCode == keyCodes.DOWN_ARROW) {
        self.openCalendarPane(event);
        $scope.$digest();
      }
    });

    $scope.$on('md-calendar-close', function() {
      self.closeCalendarPane();
    });
  };

  /**
   * Capture properties set to the date-picker and imperitively handle internal changes.
   * This is done to avoid setting up additional $watches.
   */
  DatePickerCtrl.prototype.installPropertyInterceptors = function() {
    var self = this;

    // Intercept disabled on the date-picker element to disable the internal input.
    // This avoids two bindings (outer scope to ctrl, ctrl to input).
    Object.defineProperty(this.$element[0], 'disabled', {
      get: function() { return self.isDisabled; },
      set: angular.bind(self, self.setDisabled)
    });

    Object.defineProperty(this, 'placeholder', {
      get: function() { return self.inputElement.placeholder },
      set: function(value) { self.inputElement.placeholder = value; }
    });
  };

  /**
   * Sets whether the date-picker is disabled.
   * @param {boolean} isDisabled
   */
  DatePickerCtrl.prototype.setDisabled = function(isDisabled) {
    this.isDisabled = isDisabled;
    this.inputElement.disabled = isDisabled;
    this.calendarButton.disabled = isDisabled;
  };

  /** Position and attach the floating calendar to the document. */
  DatePickerCtrl.prototype.attachCalendarPane = function() {
    var calendarPane = this.calendarPane;
    this.$element.addClass('md-datepicker-open');

    var elementRect = this.inputContainer.getBoundingClientRect();
    var bodyRect = document.body.getBoundingClientRect();

    calendarPane.style.left = (elementRect.left - bodyRect.left) + 'px';
    calendarPane.style.top = (elementRect.top - bodyRect.top) + 'px';
    document.body.appendChild(this.calendarPane);

    // Add CSS class after one frame to trigger open animation.
    this.$$rAF(function() {
      calendarPane.classList.add('md-pane-open');
    });
  };

  /** Detach the floating calendar pane from the document. */
  DatePickerCtrl.prototype.detachCalendarPane = function() {
    this.$element.removeClass('md-datepicker-open');
    this.calendarPane.classList.remove('md-pane-open');

    // Use native DOM removal because we do not want any of the angular state of this element
    // to be disposed.
    this.calendarPane.parentNode.removeChild(this.calendarPane);
  };

  /**
   * Open the floating calendar pane.
   * @param {Event} event
   */
  DatePickerCtrl.prototype.openCalendarPane = function(event) {
    if (!this.isCalendarOpen && !this.isDisabled) {
      this.isCalendarOpen = true;
      this.calendarPaneOpenedFrom = event.target;
      this.attachCalendarPane();
      this.focusCalendar();

      // Because the calendar pane is attached directly to the body, it is possible that the
      // rest of the component (input, etc) is in a different scrolling container, such as
      // an md-content. This means that, if the container is scrolled, the pane would remain
      // stationary. To remedy this, we disable scrolling while the calendar pane is open, which
      // also matches the native behavior for things like `<select>` on Mac and Windows.
      this.$mdUtil.disableScrollAround(this.calendarPane);

      // Attach click listener inside of a timeout because, if this open call was triggered by a
      // click, we don't want it to be immediately propogated up to the body and handled.
      var self = this;
      this.$mdUtil.nextTick(function() {
        document.body.addEventListener('click', self.bodyClickHandler);
      }, false);
    }
  };

  /** Close the floating calendar pane. */
  DatePickerCtrl.prototype.closeCalendarPane = function() {
    this.isCalendarOpen = false;
    this.detachCalendarPane();
    this.calendarPaneOpenedFrom.focus();
    this.calendarPaneOpenedFrom = null;
    this.$mdUtil.enableScrolling();

    document.body.removeEventListener('click', this.bodyClickHandler);
  };

  /** Gets the controller instance for the calendar in the floating pane. */
  DatePickerCtrl.prototype.getCalendarCtrl = function() {
    return angular.element(this.calendarPane.querySelector('md-calendar')).controller('mdCalendar');
  };

  /** Focus the calendar in the floating pane. */
  DatePickerCtrl.prototype.focusCalendar = function() {
    // Use a timeout in order to allow the calendar to be rendered, as it is gated behind an ng-if.
    var self = this;
    this.$mdUtil.nextTick(function() {
      self.getCalendarCtrl().focus();
    }, false);
  };

  /**
   * Handles a click on the document body when the floating calendar pane is open.
   * Closes the floating calendar pane if the click is not inside of it.
   * @param {MouseEvent} event
   */
  DatePickerCtrl.prototype.handleBodyClick = function(event) {
    if (this.isCalendarOpen) {
      // TODO(jelbourn): way want to also include the md-datepicker itself in this check.
      var isInCalendar = this.$mdUtil.getClosest(event.target, 'md-calendar');
      if (!isInCalendar) {
        this.closeCalendarPane();
      }

      this.$scope.$digest();
    }
  };
})();
<|endoftext|>


<commit_before>ReactiveLocalStorage = (function () {
	'use strict'

	var deps = {}
	for (var i = 0; i < localStorage.length; i++) {
		var key = localStorage.key(i)
		deps[key] = new Tracker.Dependency()
	}

	function getDep (key) {
		if (deps[key] === undefined) {
			deps[key] = new Tracker.Dependency()
		}
		return deps[key]
	}

	window.addEventListener('storage', function (event) {
		getDep(event.key).changed()
	})

	var ReactiveLocalStorage = function (key, val) {
		var dep = getDep(key)

		if (val !== undefined) {
			localStorage[key] = JSON.stringify(val)
			dep.changed()
		}

		dep.depend()

		var res = localStorage[key]
		try {
			return JSON.parse(res)
		} catch (e) {
			return res
		}
	}

	ReactiveLocalStorage.removeItem = function (key) {
		localStorage.removeItem(key)

		var dep = getDep(key)
		if (dep.hasDependents()) {
			dep.changed()
		} else {
			delete deps[key]
		}
	}

	return ReactiveLocalStorage
})()
<commit_msg>remove unnecessary deps initialisation<commit_after>ReactiveLocalStorage = (function () {
	'use strict'
	var deps = {}

	function getDep (key) {
		if (deps[key] === undefined) {
			deps[key] = new Tracker.Dependency()
		}
		return deps[key]
	}

	window.addEventListener('storage', function (event) {
		getDep(event.key).changed()
	})

	var ReactiveLocalStorage = function (key, val) {
		var dep = getDep(key)

		if (val !== undefined) {
			localStorage[key] = JSON.stringify(val)
			dep.changed()
		}

		dep.depend()

		var res = localStorage[key]
		try {
			return JSON.parse(res)
		} catch (e) {
			return res
		}
	}

	ReactiveLocalStorage.removeItem = function (key) {
		localStorage.removeItem(key)

		var dep = getDep(key)
		if (dep.hasDependents()) {
			dep.changed()
		} else {
			delete deps[key]
		}
	}

	return ReactiveLocalStorage
})()
<|endoftext|>


<commit_before>function toAnnotations(peaks, options = {}) {
  var { fillColor = 'green', strokeColor = 'red' } = options;

  if (!peaks) return [];
  let shouldRefresh = false;
  let annotations = peaks.map((peak) => {
    if (!peak._highlight) {
      Object.defineProperty(peak, '_highlight', {
        enumerable: false,
        writable: true
      });
      peak._highlight = Math.random();
      shouldRefresh = true;
    }
    var annotation = {
      line: 1,
      _highlight: [peak._highlight],
      type: 'rect',
      strokeColor: strokeColor,
      strokeWidth: 0,
      fillColor: fillColor
    };
    annotation.label = [
      {
        text: peak.kind,
        size: '18px',
        anchor: 'middle',
        color: 'red',
        position: {
          x: peak.wavelength,
          y: peak.transmittance,
          dy: '-22px'
        }
      }
    ];
    annotation.position = [
      {
        x: peak.wavelength - 10,
        y: peak.transmittance,
        dy: '-20px'
      },
      {
        x: peak.wavelength + 10,
        y: peak.transmittance,
        dy: '-10px'
      }
    ];
    return annotation;
  });

  if (shouldRefresh) {
    peaks.triggerChange();
  }
  return annotations;
}

module.exports = toAnnotations;
<commit_msg>fix eslint<commit_after>function toAnnotations(peaks, options = {}) {
  var { fillColor = 'green', strokeColor = 'red' } = options;

  if (!peaks) return [];
  let shouldRefresh = false;
  let annotations = peaks.map((peak) => {
    if (!peak._highlight) {
      Object.defineProperty(peak, '_highlight', {
        enumerable: false,
        writable: true
      });
      peak._highlight = Math.random();
      shouldRefresh = true;
    }
    var annotation = {
      line: 1,
      _highlight: [peak._highlight],
      type: 'rect',
      strokeColor: strokeColor,
      strokeWidth: 0,
      fillColor: fillColor
    };
    annotation.label = [
      {
        text: peak.kind,
        size: '18px',
        anchor: 'middle',
        color: 'red',
        position: {
          x: peak.wavelength,
          y: peak.transmittance,
          dy: '-22px'
        }
      }
    ];
    annotation.position = [
      {
        x: peak.wavelength - 10,
        y: peak.transmittance,
        dy: '-20px'
      },
      {
        x: peak.wavelength + 10,
        y: peak.transmittance,
        dy: '-10px'
      }
    ];
    return annotation;
  });

  if (shouldRefresh && peaks.triggerChange) {
    peaks.triggerChange();
  }
  return annotations;
}

module.exports = toAnnotations;
<|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@storybook/react';
import { select } from '@storybook/addon-knobs';
import OptionsHelper from '../../utils/helpers/options-helper';
import Filter from './filter';
import Textbox from '../textbox';

storiesOf('Filter', module)
  .addParameters({
    info: {
      propTablesExclude: [Textbox]
    }
  })
  .add('default', () => {
    const align = select('labelAlign', OptionsHelper.alignBinary);

    return (
      <Filter
        align={ align }
      >
        <Textbox
          label='First Name'
        />
        <Textbox
          label='Last Name'
        />
      </Filter>
    );
  });
<commit_msg>Renames Filter Story to Prevent Storybook Error<commit_after>import React from 'react';
import { storiesOf } from '@storybook/react';
import { select } from '@storybook/addon-knobs';
import OptionsHelper from '../../utils/helpers/options-helper';
import Filter from './filter';
import Textbox from '../textbox';

storiesOf('Filter Component', module)
  .addParameters({
    info: {
      propTablesExclude: [Textbox]
    }
  })
  .add('default', () => {
    const align = select('labelAlign', OptionsHelper.alignBinary);

    return (
      <Filter
        align={ align }
      >
        <Textbox
          label='First Name'
        />
        <Textbox
          label='Last Name'
        />
      </Filter>
    );
  });
<|endoftext|>


<commit_before>import test from 'ava';
import path from 'path';
import childProcess from 'child_process';
import pify from 'pify';

const exec = pify(childProcess.exec);

test('shows help on --help', async t => {
	const stdout = await exec('../bin/init.js --help');
	t.is(stdout.trim(), 'Usage: init [options]\n\n  Create a MERN app in current directory!\n\n  Options:\n\n    -h, --help  output usage information');
});

test('shows help on --h', async t => {
	const stdout = await exec('../bin/init.js --help');
	t.is(stdout.trim(), 'Usage: init [options]\n\n  Create a MERN app in current directory!\n\n  Options:\n\n    -h, --help  output usage information');
});

<commit_msg>fix tests<commit_after>import test from 'ava';
import path from 'path';
import childProcess from 'child_process';
import pify from 'pify';

const exec = pify(childProcess.exec);

test('shows help on --help', async t => {
	const stdout = await exec('../bin/init.js --help');
	t.is(stdout.trim(), 'Usage: init [options]\n\n  Create a MERN app in current directory!\n\n  Options:\n\n    -h, --help     output usage information\n    -V, --version  output the version number\n    -v, --version  check version');
});

test('shows help on --h', async t => {
	const stdout = await exec('../bin/init.js --help');
	t.is(stdout.trim(), 'Usage: init [options]\n\n  Create a MERN app in current directory!\n\n  Options:\n\n    -h, --help     output usage information\n    -V, --version  output the version number\n    -v, --version  check version');
});

<|endoftext|>


<commit_before>var express = require('express');
var fs = require('fs');
var TAFFY = require('taffy');
// load json file with db
var myData = require('./db.json');

var jsondb = JSON.stringify(myData);
var db = TAFFY(''+jsondb);

var app = express();

app.use(express.static( __dirname + '/public'))

app.get('/', function(request, response){

	response.sendFile('index.html')
});

app.get('/philae', function(request, response, next){

	db.insert(
    	{
      		"id": 2,
      		"title": "first-trip",
      		"locations": [
        		{
          			"time": "now",
          			"latitud": "sur"
        		}
      		]
    	}
  	,function(err){
  		if(err){
  			return next({message: 'failed to query db (insert)', status: 500});
  		}

  	});

	console.log(db().get());

	try {

		fs.writeFileSync("db.json", JSON.stringify(db().get(), null, 4));

	} catch (err) {

  		return next({message: 'failed to query db (Sync)', status: 500});
	}

	response.send(200);
});

app.get('/viewer', function(request, response){

	// Show philae position tracking
	// Get info with json and send to view

	response.setHeader('Content-Type', 'application/json');
    response.send(JSON.stringify(db().get(), null, 4));
});

app.listen(3000, function(){

	console.log('listen port 3000');
});
<commit_msg>ISSUE #4 Fix small linting issues on server code<commit_after>var express = require('express');
var fs = require('fs');
var TAFFY = require('taffy');
// load json file with db
var myData = require('./db.json');

var jsondb = JSON.stringify(myData);
var db = TAFFY(''+jsondb);

var app = express();

app.use(express.static( __dirname + '/public'));

app.get('/', function(request, response){

	response.sendFile('index.html');
});

app.get('/philae', function(request, response, next){

	db.insert(
    	{
      		"id": 2,
      		"title": "first-trip",
      		"locations": [
        		{
          			"time": "now",
          			"latitud": "sur"
        		}
      		]
    	},
  	  function(err){
  		if(err){
  			return next({message: 'failed to query db (insert)', status: 500});
  		}

  	});

	console.log(db().get());

	try {

		fs.writeFileSync("db.json", JSON.stringify(db().get(), null, 4));

	} catch (err) {

  		return next({message: 'failed to query db (Sync)', status: 500});
	}

	response.send(200);
});

app.get('/viewer', function(request, response){

	// Show philae position tracking
	// Get info with json and send to view

	response.setHeader('Content-Type', 'application/json');
    response.send(JSON.stringify(db().get(), null, 4));
});

app.listen(3000, function(){

	console.log('listen port 3000');
});
<|endoftext|>


<commit_before>/**
 *
 */

var assert=require('assert');
assert.equal(true, true);

var ws=require('ws');

// a ws server that just echos back all messages...
var echo=(new ws.Server({
	port: 9001
})).on('connection', function(wsclient){

	wsclient.on('message',function(message){
		wsclient.send(message);
	})

});

// a bridge server.
var bridge=(new (require('../WSBridgeProxy.js').WSBridgeProxy)({port:9002}));

var autoconnect=(new (require('../WSAutoconnectProxy.js').WSAutoconnectProxy)({source:'ws://localhost:9002', destination:'ws://localhost:9001'}));

var client=(new ws('ws://localhost:9002')).on('open', function(){

	this.on('message',function(message){

		assert.equal(message,'hello world');

	});
	this.send('hello world');

});<commit_msg>remove .classname<commit_after>/**
 *
 */

var assert=require('assert');
assert.equal(true, true);

var ws=require('ws');

// a ws server that just echos back all messages...
var echo=(new ws.Server({
	port: 9001
})).on('connection', function(wsclient){

	wsclient.on('message',function(message){
		wsclient.send(message);
	})

});

// a bridge server.
var bridge=(new (require('../bridgeproxy.js'))({port:9002}));

var autoconnect=(new (require('../autoconnectproxy.js'))({source:'ws://localhost:9002', destination:'ws://localhost:9001'}));

var client=(new ws('ws://localhost:9002')).on('open', function(){

	this.on('message',function(message){

		assert.equal(message,'hello world');

	});
	this.send('hello world');

});<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { Link } from 'react-router'
import classNames from 'classnames'
import Avatar from '../assets/Avatar'
import { UserDrawer } from '../users/UserRenderables'
import ContentWarningButton from '../posts/ContentWarningButton'
import PostToolsContainer from '../../containers/PostToolsContainer'
import { HeartIcon, RepostIcon } from '../posts/PostIcons'
import RelationshipContainer from '../../containers/RelationshipContainer'
import { postLovers, postReposters } from '../../networking/api'
import StreamContainer from '../../containers/StreamContainer'
import { loadComments } from '../../actions/posts'
import { RegionItems } from '../regions/RegionRenderables'

function getPostDetailPath(author, post) {
  return `/${author.get('username')}/post/${post.get('token')}`
}

export const PostLoversDrawer = ({ post }) =>
  <UserDrawer
    endpoint={postLovers(post.get('id'))}
    icon={<HeartIcon />}
    key={`userAvatarsLovers_${post.get('id')}${post.get('lovesCount')}`}
    post={post}
    resultType="love"
  />
PostLoversDrawer.propTypes = {
  post: PropTypes.object.isRequired,
}

export const PostRepostersDrawer = ({ post }) =>
  <UserDrawer
    endpoint={postReposters(post.get('id'))}
    icon={<RepostIcon />}
    key={`userAvatarsReposters_${post.get('id')}${post.get('repostsCount')}`}
    post={post}
    resultType="repost"
  />
PostRepostersDrawer.propTypes = {
  post: PropTypes.object.isRequired,
}

export const CommentStream = ({ post, author }) =>

    <StreamContainer
      className="CommentStreamContainer isFullWidth"
      action={loadComments(post)}
      ignoresScrollPosition
    >
      {post.get('commentsCount') > 10 ?
        <Link
          to={{
            pathname: getPostDetailPath(author, post),
            state: { didComeFromSeeMoreCommentsLink: true },
          }}
          className="CommentsLink"
        >
          See More
        </Link>
        : null
      }
    </StreamContainer>

CommentStream.propTypes = {
  author: PropTypes.object.isRequired,
  post: PropTypes.object.isRequired,
}

const PostHeaderTimeAgoLink = ({ to, createdAt }) =>
  <Link className="PostHeaderTimeAgoLink" to={to}>
    {new Date(createdAt).timeAgoInWords()}
  </Link>
PostHeaderTimeAgoLink.propTypes = {
  createdAt: PropTypes.string.isRequired,
  to: PropTypes.string.isRequired,
}

export const PostHeader = ({ post, author, isPostDetail }) => {
  const postDetailPath = getPostDetailPath(author, post)
  return (
    <header className="PostHeader" key={`PostHeader_${post.get('id')}`}>

        <Link className="PostHeaderLink" to={`/${author.get('username')}`}>
          <Avatar
            priority={author.get('relationshipPriority')}
            sources={author.get('avatar')}
            userId={`${author.get('id')}`}
            username={author.get('username')}
          />

            {isPostDetail && author.get('name') ?

                {author.get('name')}
                @{author.get('username')}

              :
              `@${author.get('username')}`
            }

        </Link>

      <RelationshipContainer className="isInHeader" user={author} />
      <PostHeaderTimeAgoLink to={postDetailPath} createdAt={post.get('createdAt')} />

  )
}
PostHeader.propTypes = {
  author: PropTypes.object.isRequired,
  isPostDetail: PropTypes.bool,
  post: PropTypes.object.isRequired,
}
PostHeader.defaultProps = {
  isPostDetail: false,
}

export const CategoryHeader = ({ post, author, categoryName, categoryPath }) => {
  if (!post || !author) { return null }
  const postDetailPath = getPostDetailPath(author, post)
  return (
    <header className="CategoryHeader" key={`CategoryHeader_${post.get('id')}`}>

        <Link className="PostHeaderLink" to={`/${author.get('username')}`}>
          <Avatar
            priority={author.get('relationshipPriority')}
            sources={author.get('avatar')}
            userId={`${author.get('id')}`}
            username={author.get('username')}
          />

            {`@${author.get('username')}`}

        </Link>

      <RelationshipContainer className="isInHeader" user={author} />

        <Link className="PostHeaderLink" to={categoryPath}>
          in
          {categoryName}
        </Link>

      <PostHeaderTimeAgoLink to={postDetailPath} createdAt={post.get('createdAt')} />

  )
}
CategoryHeader.propTypes = {
  author: PropTypes.object.isRequired,
  categoryName: PropTypes.string.isRequired,
  categoryPath: PropTypes.string.isRequired,
  post: PropTypes.object.isRequired,
}

export const RepostHeader = ({ post, repostAuthor, repostedBy, inUserDetail }) => {
  const postDetailPath = getPostDetailPath(repostedBy, post)
  return (
    <header className={classNames('RepostHeader', { inUserDetail })} key={`RepostHeader_${post.get('id')}`}>

        <Link className="PostHeaderLink" to={`/${repostAuthor.get('username')}`}>
          <Avatar
            priority={repostAuthor.get('relationshipPriority')}
            sources={repostAuthor.get('avatar')}
            userId={`${repostAuthor.get('id')}`}
            username={repostAuthor.get('username')}
          />

            {`@${repostAuthor.get('username')}`}

        </Link>

      <RelationshipContainer className="isInHeader" user={repostAuthor} />

        <Link className="PostHeaderLink" to={`/${repostedBy.get('username')}`}>
          <RepostIcon />

            {` by @${repostedBy.get('username')}`}

        </Link>

      <PostHeaderTimeAgoLink to={postDetailPath} createdAt={post.get('createdAt')} />

  )
}
RepostHeader.propTypes = {
  inUserDetail: PropTypes.bool,
  post: PropTypes.object.isRequired,
  repostAuthor: PropTypes.object.isRequired,
  repostedBy: PropTypes.object.isRequired,
}
RepostHeader.defaultProps = {
  inUserDetail: false,
}

export const PostBody = (props) => {
  const { assets, author, columnWidth, commentOffset, contentWarning,
    contentWidth, innerHeight, isGridMode, post } = props
  const cells = []
  const postDetailPath = getPostDetailPath(author, post)

  if (contentWarning) {
    cells.push(<ContentWarningButton key={`contentWarning_${post.get('id')}`} post={post} />)
  }

  const regionProps = {
    assets,
    columnWidth,
    commentOffset,
    contentWidth,
    innerHeight,
    isGridMode,
    postDetailPath,
  }
  if (post.get('repostContent') && post.get('repostContent').size) {
    // this is weird, but the post summary is
    // actually the repost summary on reposts
    if (isGridMode) {
      regionProps.content = post.get('summary')
      cells.push(<RegionItems {...regionProps} key={`RegionItems_${post.get('id')}`} />)
    } else {
      regionProps.content = post.get('repostContent')
      cells.push(<RegionItems {...regionProps} key={`RegionItems_${post.get('id')}`} />)
      if (post.get('content') && post.get('content').size) {
        regionProps.content = post.content
        cells.push(
          <div className="PostBody RepostedBody" key={`RepostedBody_${post.get('id')}`}>
            <Avatar
              priority={author.get('relationshipPriority')}
              sources={author.get('avatar')}
              to={`/${author.get('username')}`}
              userId={`${author.get('id')}`}
              username={author.get('username')}
            />
            <RegionItems {...regionProps} />

,
        )
      }
    }
  } else {
    regionProps.content = isGridMode ? post.get('summary') : post.get('content')
    cells.push(<RegionItems {...regionProps} key={`RegionItems_${post.get('id')}`} />)
  }
  return (
    <div className="PostBody" key={`PostBody_${post.get('id')}`}>
      {cells}

  )
}
PostBody.propTypes = {
  assets: PropTypes.object,
  author: PropTypes.object.isRequired,
  columnWidth: PropTypes.number,
  commentOffset: PropTypes.number,
  contentWarning: PropTypes.string,
  contentWidth: PropTypes.number,
  innerHeight: PropTypes.number,
  isGridMode: PropTypes.bool,
  post: PropTypes.object.isRequired,
}
PostBody.defaultProps = {
  assets: null,
  columnWidth: 0,
  commentOffset: 0,
  contentWarning: null,
  contentWidth: 0,
  innerHeight: 0,
  isGridMode: false,
}

export const PostFooter = ({ post, author, isGridMode, isRepostAnimating }) => {
  if (!author) { return null }
  return (
    <PostToolsContainer
      author={author}
      post={post}
      isGridMode={isGridMode}
      isRepostAnimating={isRepostAnimating}
      key={`PostTools_${post.get('id')}`}
    />
  )
}

PostFooter.propTypes = {
  author: PropTypes.object.isRequired,
  isGridMode: PropTypes.bool,
  isRepostAnimating: PropTypes.bool,
  post: PropTypes.object.isRequired,
}
PostFooter.defaultProps = {
  isGridMode: false,
  isRepostAnimating: false,
}

<commit_msg>Fixes repost content rendering<commit_after>import React, { PropTypes } from 'react'
import { Link } from 'react-router'
import classNames from 'classnames'
import Avatar from '../assets/Avatar'
import { UserDrawer } from '../users/UserRenderables'
import ContentWarningButton from '../posts/ContentWarningButton'
import PostToolsContainer from '../../containers/PostToolsContainer'
import { HeartIcon, RepostIcon } from '../posts/PostIcons'
import RelationshipContainer from '../../containers/RelationshipContainer'
import { postLovers, postReposters } from '../../networking/api'
import StreamContainer from '../../containers/StreamContainer'
import { loadComments } from '../../actions/posts'
import { RegionItems } from '../regions/RegionRenderables'

function getPostDetailPath(author, post) {
  return `/${author.get('username')}/post/${post.get('token')}`
}

export const PostLoversDrawer = ({ post }) =>
  <UserDrawer
    endpoint={postLovers(post.get('id'))}
    icon={<HeartIcon />}
    key={`userAvatarsLovers_${post.get('id')}${post.get('lovesCount')}`}
    post={post}
    resultType="love"
  />
PostLoversDrawer.propTypes = {
  post: PropTypes.object.isRequired,
}

export const PostRepostersDrawer = ({ post }) =>
  <UserDrawer
    endpoint={postReposters(post.get('id'))}
    icon={<RepostIcon />}
    key={`userAvatarsReposters_${post.get('id')}${post.get('repostsCount')}`}
    post={post}
    resultType="repost"
  />
PostRepostersDrawer.propTypes = {
  post: PropTypes.object.isRequired,
}

export const CommentStream = ({ post, author }) =>

    <StreamContainer
      className="CommentStreamContainer isFullWidth"
      action={loadComments(post)}
      ignoresScrollPosition
    >
      {post.get('commentsCount') > 10 ?
        <Link
          to={{
            pathname: getPostDetailPath(author, post),
            state: { didComeFromSeeMoreCommentsLink: true },
          }}
          className="CommentsLink"
        >
          See More
        </Link>
        : null
      }
    </StreamContainer>

CommentStream.propTypes = {
  author: PropTypes.object.isRequired,
  post: PropTypes.object.isRequired,
}

const PostHeaderTimeAgoLink = ({ to, createdAt }) =>
  <Link className="PostHeaderTimeAgoLink" to={to}>
    {new Date(createdAt).timeAgoInWords()}
  </Link>
PostHeaderTimeAgoLink.propTypes = {
  createdAt: PropTypes.string.isRequired,
  to: PropTypes.string.isRequired,
}

export const PostHeader = ({ post, author, isPostDetail }) => {
  const postDetailPath = getPostDetailPath(author, post)
  return (
    <header className="PostHeader" key={`PostHeader_${post.get('id')}`}>

        <Link className="PostHeaderLink" to={`/${author.get('username')}`}>
          <Avatar
            priority={author.get('relationshipPriority')}
            sources={author.get('avatar')}
            userId={`${author.get('id')}`}
            username={author.get('username')}
          />

            {isPostDetail && author.get('name') ?

                {author.get('name')}
                @{author.get('username')}

              :
              `@${author.get('username')}`
            }

        </Link>

      <RelationshipContainer className="isInHeader" user={author} />
      <PostHeaderTimeAgoLink to={postDetailPath} createdAt={post.get('createdAt')} />

  )
}
PostHeader.propTypes = {
  author: PropTypes.object.isRequired,
  isPostDetail: PropTypes.bool,
  post: PropTypes.object.isRequired,
}
PostHeader.defaultProps = {
  isPostDetail: false,
}

export const CategoryHeader = ({ post, author, categoryName, categoryPath }) => {
  if (!post || !author) { return null }
  const postDetailPath = getPostDetailPath(author, post)
  return (
    <header className="CategoryHeader" key={`CategoryHeader_${post.get('id')}`}>

        <Link className="PostHeaderLink" to={`/${author.get('username')}`}>
          <Avatar
            priority={author.get('relationshipPriority')}
            sources={author.get('avatar')}
            userId={`${author.get('id')}`}
            username={author.get('username')}
          />

            {`@${author.get('username')}`}

        </Link>

      <RelationshipContainer className="isInHeader" user={author} />

        <Link className="PostHeaderLink" to={categoryPath}>
          in
          {categoryName}
        </Link>

      <PostHeaderTimeAgoLink to={postDetailPath} createdAt={post.get('createdAt')} />

  )
}
CategoryHeader.propTypes = {
  author: PropTypes.object.isRequired,
  categoryName: PropTypes.string.isRequired,
  categoryPath: PropTypes.string.isRequired,
  post: PropTypes.object.isRequired,
}

export const RepostHeader = ({ post, repostAuthor, repostedBy, inUserDetail }) => {
  const postDetailPath = getPostDetailPath(repostedBy, post)
  return (
    <header className={classNames('RepostHeader', { inUserDetail })} key={`RepostHeader_${post.get('id')}`}>

        <Link className="PostHeaderLink" to={`/${repostAuthor.get('username')}`}>
          <Avatar
            priority={repostAuthor.get('relationshipPriority')}
            sources={repostAuthor.get('avatar')}
            userId={`${repostAuthor.get('id')}`}
            username={repostAuthor.get('username')}
          />

            {`@${repostAuthor.get('username')}`}

        </Link>

      <RelationshipContainer className="isInHeader" user={repostAuthor} />

        <Link className="PostHeaderLink" to={`/${repostedBy.get('username')}`}>
          <RepostIcon />

            {` by @${repostedBy.get('username')}`}

        </Link>

      <PostHeaderTimeAgoLink to={postDetailPath} createdAt={post.get('createdAt')} />

  )
}
RepostHeader.propTypes = {
  inUserDetail: PropTypes.bool,
  post: PropTypes.object.isRequired,
  repostAuthor: PropTypes.object.isRequired,
  repostedBy: PropTypes.object.isRequired,
}
RepostHeader.defaultProps = {
  inUserDetail: false,
}

export const PostBody = (props) => {
  const { assets, author, columnWidth, commentOffset, contentWarning,
    contentWidth, innerHeight, isGridMode, post } = props
  const cells = []
  const postDetailPath = getPostDetailPath(author, post)

  if (contentWarning) {
    cells.push(<ContentWarningButton key={`contentWarning_${post.get('id')}`} post={post} />)
  }

  const regionProps = {
    assets,
    columnWidth,
    commentOffset,
    contentWidth,
    innerHeight,
    isGridMode,
    postDetailPath,
  }
  if (post.get('repostContent') && post.get('repostContent').size) {
    // this is weird, but the post summary is
    // actually the repost summary on reposts
    if (isGridMode) {
      regionProps.content = post.get('summary')
      cells.push(<RegionItems {...regionProps} key={`RegionItems_${post.get('id')}`} />)
    } else {
      regionProps.content = post.get('repostContent')
      cells.push(<RegionItems {...regionProps} key={`RegionItems_${post.get('id')}`} />)
      if (post.get('content') && post.get('content').size) {
        regionProps.content = post.get('content')
        cells.push(
          <div className="PostBody RepostedBody" key={`RepostedBody_${post.get('id')}`}>
            <Avatar
              priority={author.get('relationshipPriority')}
              sources={author.get('avatar')}
              to={`/${author.get('username')}`}
              userId={`${author.get('id')}`}
              username={author.get('username')}
            />
            <RegionItems {...regionProps} />

,
        )
      }
    }
  } else {
    regionProps.content = isGridMode ? post.get('summary') : post.get('content')
    cells.push(<RegionItems {...regionProps} key={`RegionItems_${post.get('id')}`} />)
  }
  return (
    <div className="PostBody" key={`PostBody_${post.get('id')}`}>
      {cells}

  )
}
PostBody.propTypes = {
  assets: PropTypes.object,
  author: PropTypes.object.isRequired,
  columnWidth: PropTypes.number,
  commentOffset: PropTypes.number,
  contentWarning: PropTypes.string,
  contentWidth: PropTypes.number,
  innerHeight: PropTypes.number,
  isGridMode: PropTypes.bool,
  post: PropTypes.object.isRequired,
}
PostBody.defaultProps = {
  assets: null,
  columnWidth: 0,
  commentOffset: 0,
  contentWarning: null,
  contentWidth: 0,
  innerHeight: 0,
  isGridMode: false,
}

export const PostFooter = ({ post, author, isGridMode, isRepostAnimating }) => {
  if (!author) { return null }
  return (
    <PostToolsContainer
      author={author}
      post={post}
      isGridMode={isGridMode}
      isRepostAnimating={isRepostAnimating}
      key={`PostTools_${post.get('id')}`}
    />
  )
}

PostFooter.propTypes = {
  author: PropTypes.object.isRequired,
  isGridMode: PropTypes.bool,
  isRepostAnimating: PropTypes.bool,
  post: PropTypes.object.isRequired,
}
PostFooter.defaultProps = {
  isGridMode: false,
  isRepostAnimating: false,
}

<|endoftext|>


<commit_before>/**
 * @class GelatoRouter
 * @extends {Backbone.Router}
 */
var GelatoRouter = Backbone.Router.extend({
    /**
     * @property page
     * @type {String}
     */
    page: null,
    /**
     * @method go
     * @param {String} path
     * @param {Object} [options]
     * @returns {GelatoPage}
     */
    go: function(path, options) {
        if (this.page) {
            this.page.remove();
        }
        window.scrollTo(0, 0);
        this.page = new (require(path + '/view'))(options);
        return this.page.render();
    },
    /**
     * @method start
     * @returns {Boolean}
     */
    start: function() {
        return Backbone.history.start({
            pushState: app.isWebsite(),
            root: '/'
        });
    }
});

module.exports = GelatoRouter;
<commit_msg>Add options parameter to router start with defaults.<commit_after>/**
 * @class GelatoRouter
 * @extends {Backbone.Router}
 */
var GelatoRouter = Backbone.Router.extend({
    /**
     * @property page
     * @type {String}
     */
    page: null,
    /**
     * @method go
     * @param {String} path
     * @param {Object} [options]
     * @returns {GelatoPage}
     */
    go: function(path, options) {
        if (this.page) {
            this.page.remove();
        }
        window.scrollTo(0, 0);
        this.page = new (require(path + '/view'))(options);
        return this.page.render();
    },
    /**
     * @method start
     * @param {Object} [options]
     * @returns {Boolean}
     */
    start: function(options) {
        options = _.defaults(
            options || {},
            {
                pushState: app.isWebsite(),
                root: '/'
            }
        );
        return Backbone.history.start({
            pushState: options.pushState,
            root: options.root
        });
    }
});

module.exports = GelatoRouter;
<|endoftext|>


<commit_before>import 'polyfill';
import 'asset/style/screen.scss';
import 'modernizr';

import Vue from 'vue';
import filter from 'filter';
import directive from 'directive';
import component from 'component';
import setupRouter from 'router';
import setupStore from 'store';
import startUp from 'control/startUp';
import getLocaleConfig from 'config/localeConfig';
import VueI18nManager from 'vue-i18n-manager';
import { sync } from 'vuex-router-sync';
import setupInjects from 'util/setupInjects';
import App from 'App';
import localeLoader from './util/localeLoader';

// register filters globally
Object.keys(filter).forEach(key => Vue.filter(key, filter[key]));

// register directives globally
Object.keys(directive).forEach(key => Vue.directive(key, directive[key]));

// register components globally
Object.keys(component).forEach(key => Vue.component(key, component[key]));

setupInjects();

const router = setupRouter();
const store = setupStore();
const localeConfig = getLocaleConfig();

localeLoader.setLoadCallback((locale) => {
	console.log('locale loaded', locale);
});

if (localeConfig.localeEnabled) {
	Vue.use(VueI18nManager, {
		store,
		router,
		config: localeConfig.config,
		proxy: localeLoader,
	});

	Vue.initI18nManager();
}

// sync router data to store
sync(store, router);

// Init new vue app
const app = new Vue({
	router,
	store,
	render: h => h(App),
});

// Mount the app after startUp
startUp(store).then(() => app.$mount('#app'));
<commit_msg>remove debug function<commit_after>import 'polyfill';
import 'asset/style/screen.scss';
import 'modernizr';

import Vue from 'vue';
import filter from 'filter';
import directive from 'directive';
import component from 'component';
import setupRouter from 'router';
import setupStore from 'store';
import startUp from 'control/startUp';
import getLocaleConfig from 'config/localeConfig';
import VueI18nManager from 'vue-i18n-manager';
import { sync } from 'vuex-router-sync';
import setupInjects from 'util/setupInjects';
import App from 'App';
import localeLoader from './util/localeLoader';

// register filters globally
Object.keys(filter).forEach(key => Vue.filter(key, filter[key]));

// register directives globally
Object.keys(directive).forEach(key => Vue.directive(key, directive[key]));

// register components globally
Object.keys(component).forEach(key => Vue.component(key, component[key]));

setupInjects();

const router = setupRouter();
const store = setupStore();
const localeConfig = getLocaleConfig();

if (localeConfig.localeEnabled) {
	Vue.use(VueI18nManager, {
		store,
		router,
		config: localeConfig.config,
		proxy: localeLoader,
	});

	Vue.initI18nManager();
}

// sync router data to store
sync(store, router);

// Init new vue app
const app = new Vue({
	router,
	store,
	render: h => h(App),
});

// Mount the app after startUp
startUp(store).then(() => app.$mount('#app'));
<|endoftext|>


<commit_before>const commander = require('commander')
const Web3 = require('web3')
const RemixTests = require('./index.js')
const fs = require('fs')
const signale = require('signale')

const Provider = require('remix-simulator').Provider

commander.action(function (filename) {
  let web3 = new Web3()
  // web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'))
  web3.setProvider(new Provider())
  // web3.setProvider(new web3.providers.WebsocketProvider('ws://localhost:8546'))

  let isDirectory = fs.lstatSync(filename).isDirectory()
  RemixTests.runTestFiles(filename, isDirectory, web3)
})

if (!process.argv.slice(2).length) {
  signale.fatal('Please specify a filename')
  process.exit()
}

commander.parse(process.argv)
<commit_msg>Add initial message<commit_after>const commander = require('commander')
const Web3 = require('web3')
const RemixTests = require('./index.js')
const fs = require('fs')
const { Signale } = require('signale')
const Provider = require('remix-simulator').Provider
require('colors')

// signale configuration
const options = {
  types: {
    greet: {
      badge: '\n👁',
      label: '',
      color: 'yellow'
    }
  }
}
const signale = new Signale(options)

commander.action(function (filename) {
  signale.greet(('Running remix-tests: Unit testing for solidity.\n').yellow)
  let web3 = new Web3()
  // web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'))
  web3.setProvider(new Provider())
  // web3.setProvider(new web3.providers.WebsocketProvider('ws://localhost:8546'))

  let isDirectory = fs.lstatSync(filename).isDirectory()
  RemixTests.runTestFiles(filename, isDirectory, web3)
})

if (!process.argv.slice(2).length) {
  signale.fatal('Please specify a filename')
  process.exit()
}

commander.parse(process.argv)
<|endoftext|>


<commit_before>'use strict';

var app = angular.module( 'app', ['ui.Waterfull'] );

app.controller( 'ctrl', [ '$scope', '$timeout', function( $scope, $timeout ) {
  var count = Math.floor(( Math.random() * 50 ) + 10 );
  $scope.items = [];

  for( var i = 0; i < count; i++ ) {
    var bgc = 'rgba(' + getRandom( 255, 0 ) + ', ' + getRandom( 255, 0 ) + ', ' + getRandom( 255, 0 ) + ', ' + getRandom( 100, 0 ) / 100 + ')';
    var h = getRandom( 100, 10 );

    $scope.items.push( {
      count: i,
      type: 'template/flow-item.html',
      data: { bgc: bgc, h: h }
    });
  }

  function getRandom( range, init ) {
    if( typeof init == 'undefined' ) init = 1;
    return Math.floor(( Math.random() * range ) + init );
  }
}]);<commit_msg>delete use strict<commit_after>var app = angular.module( 'app', ['ui.Waterfull'] );

app.controller( 'ctrl', [ '$scope', '$timeout', function( $scope, $timeout ) {
  var count = Math.floor(( Math.random() * 50 ) + 10 );
  $scope.items = [];

  for( var i = 0; i < count; i++ ) {
    var bgc = 'rgba(' + getRandom( 255, 0 ) + ', ' + getRandom( 255, 0 ) + ', ' + getRandom( 255, 0 ) + ', ' + getRandom( 100, 0 ) / 100 + ')';
    var h = getRandom( 100, 10 );

    $scope.items.push( {
      count: i,
      type: 'template/flow-item.html',
      data: { bgc: bgc, h: h }
    });
  }

  function getRandom( range, init ) {
    if( typeof init == 'undefined' ) init = 1;
    return Math.floor(( Math.random() * range ) + init );
  }
}]);<|endoftext|>


<commit_before>var w = screen.width * 0.30,
h = screen.height * 0.40,
r = 380,
x = d3.scale.linear().range([0, r]),
y = d3.scale.linear().range([0, r]),
p = 15,
label_rad = 25,
node,
root,
fc1,fc2,fc3,
chart_dyn,
chart_type;

if (typeof String.prototype.startsWith != 'function') {
    // see below for better implementation!
    String.prototype.startsWith = function (str){
        return this.indexOf(str) == 0;
    };
}

var colorMap = {"Wet Storage": "#1f77b4",
                "Dry Storage": "#aec7e8",
                "Repository": "#ffbb78",
                "Reprocessed Fuel": "#2ca02c"
               }

function colorPicker(s) {
    var c = "white";
    for (var key in colorMap) {
        if (s.startsWith(key)) {
            c = colorMap[key];
            break;
        };
    };
    return c;
}

function wrap(text, width) {
    text.each(function() {
        var text = d3.select(this),
        lines = text.text().split(/\n/).reverse(),
        line,
        lineNumber = 0,
        lineHeight = 1.1, // ems
        x = text.attr("x"),
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", x)
            .attr("y", y).attr("dy", dy + "em");
        lineNumber = - Math.floor(lines.length / 2);
        while (line = lines.pop()) {
            tspan = text.append("tspan").attr("x", x)
                .attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em")
                .text(line);
        }
    });
}

var pack = d3.layout.pack()
    .size([r, r])
    .value(function(d) { return d.size;})
    .padding(p);

function load_data(chart_node,json_data)
{
    d3.json(json_data, function(data) {
        node = root = data;
        var nodes = pack.nodes(root);
        chart_node.selectAll("circle")
            .remove();
        chart_node.selectAll("circle")
            .data(nodes)
            .enter().append("svg:circle")
            .attr("class", function(d) { return d.children ? "parent" : "child"; })
            .attr("cx", function(d) { return d.x; })
            .attr("cy", function(d) { return d.y; })
            .attr("r", function(d) { return d.r; })
            .style("stroke-width",function(d) {if (d.children && !chart_dyn && d.children[0].children)
                                               {return 0}; return 1;})
            .style("fill", function(d){return colorPicker(d.name)});

        chart_node.selectAll("text")
            .remove();
        chart_node.selectAll("text")
            .data(nodes)
            .enter().append("svg:text")
            .attr("class", function(d) { return d.children ? "parent" : "child"; })
            .attr("x", function(d) { return d.x; })
            .attr("y", function(d) { if (d.children) {return d.y - d.r - 20;}; return d.y; })
            .attr("dy", ".35em")
            .attr("text-anchor", "middle")
//            .style("opacity", function(d) { return d.r > label_rad ? 1 : 0; })
            .text(function(d) { if (d.children) {return d.name;}; return d.name; })
            .call(wrap);
    });
}

function add_info(chart_id)
{

    var new_chart = d3.select(chart_id + " svg")
        .attr("width", w)
        .attr("height", h)
        .append("svg:g")
        .attr("transform", "translate(" + (w - r) / 2 + "," + (h - r) / 2 + ")");

    return new_chart;
}

function load_static(kind)
{
    var cost_ver = "";

    if (kind == "cost")
    {
        cost_ver = "-new";
    }
    load_data(fc1,"info-raw-data-run1" + cost_ver + "-2000_2050_2100-" + kind + ".json");
    load_data(fc2,"info-raw-data-run3" + cost_ver + "-2000_2050_2100-" + kind + ".json");
    load_data(fc3,"info-raw-data-run5" + cost_ver + "-2000_2050_2100-" + kind + ".json");
}

function load_fcs(kind,year) {
    var cost_ver = "";

    if (kind == "cost")
    {
        cost_ver = "-new";
    }
    load_data(fc1,"years/info-raw-data-run1" + cost_ver + "-" + year + "-" + kind + ".json");
    load_data(fc2,"years/info-raw-data-run3" + cost_ver + "-" + year + "-" + kind + ".json");
    load_data(fc3,"years/info-raw-data-run5" + cost_ver + "-" + year + "-" + kind + ".json");
}

function yearUpdate(year) {
    document.querySelector('#yearlabel').value = year;
    load_fcs(chart_type,year);
}

function info(dynamic,kind)
{
    chart_type = kind;
    chart_dyn = dynamic;

    fc1 = add_info("#chart1");
    fc2 = add_info("#chart2");
    fc3 = add_info("#chart3");

    if (dynamic)
    {
        load_fcs(kind,2000);
    }
    else
    {
        load_static(kind);
    }
}

<commit_msg>remove category label again and shift up<commit_after>var w = screen.width * 0.30,
h = screen.height * 0.40,
r = 380,
x = d3.scale.linear().range([0, r]),
y = d3.scale.linear().range([0, r]),
p = 15,
label_rad = 25,
node,
root,
fc1,fc2,fc3,
chart_dyn,
chart_type;

if (typeof String.prototype.startsWith != 'function') {
    // see below for better implementation!
    String.prototype.startsWith = function (str){
        return this.indexOf(str) == 0;
    };
}

var colorMap = {"Wet Storage": "#1f77b4",
                "Dry Storage": "#aec7e8",
                "Repository": "#ffbb78",
                "Reprocessed Fuel": "#2ca02c"
               }

function colorPicker(s) {
    var c = "white";
    for (var key in colorMap) {
        if (s.startsWith(key)) {
            c = colorMap[key];
            break;
        };
    };
    return c;
}

function wrap(text, width) {
    text.each(function() {
        var text = d3.select(this),
        lines = text.text().split(/\n/).reverse(),
        line,
        lineNumber = 0,
        lineHeight = 1.1, // ems
        x = text.attr("x"),
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", x)
            .attr("y", y).attr("dy", dy + "em");
        lineNumber = - Math.floor(lines.length / 2);
        while (line = lines.pop()) {
            tspan = text.append("tspan").attr("x", x)
                .attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em")
                .text(line);
        }
    });
}

var pack = d3.layout.pack()
    .size([r, r])
    .value(function(d) { return d.size;})
    .padding(p);

function load_data(chart_node,json_data)
{
    d3.json(json_data, function(data) {
        node = root = data;
        var nodes = pack.nodes(root);
        chart_node.selectAll("circle")
            .remove();
        chart_node.selectAll("circle")
            .data(nodes)
            .enter().append("svg:circle")
            .attr("class", function(d) { return d.children ? "parent" : "child"; })
            .attr("cx", function(d) { return d.x; })
            .attr("cy", function(d) { return d.y; })
            .attr("r", function(d) { return d.r; })
            .style("stroke-width",function(d) {if (d.children && !chart_dyn && d.children[0].children)
                                               {return 0}; return 1;})
            .style("fill", function(d){return colorPicker(d.name)});

        chart_node.selectAll("text")
            .remove();
        chart_node.selectAll("text")
            .data(nodes)
            .enter().append("svg:text")
            .attr("class", function(d) { return d.children ? "parent" : "child"; })
            .attr("x", function(d) { return d.x; })
            .attr("y", function(d) { if (d.children) {return d.y - d.r - 20;}; return d.y; })
//            .attr("dy", ".35em")
            .attr("text-anchor", "middle")
//            .style("opacity", function(d) { return d.r > label_rad ? 1 : 0; })
            .text(function(d) { if (d.children) {return d.name;}; return d.name.split('\n')[1]; })
            .call(wrap);
    });
}

function add_info(chart_id)
{

    var new_chart = d3.select(chart_id + " svg")
        .attr("width", w)
        .attr("height", h)
        .append("svg:g")
        .attr("transform", "translate(" + (w - r) / 2 + "," + (h - r) / 2 + ")");

    return new_chart;
}

function load_static(kind)
{
    var cost_ver = "";

    if (kind == "cost")
    {
        cost_ver = "-new";
    }
    load_data(fc1,"info-raw-data-run1" + cost_ver + "-2000_2050_2100-" + kind + ".json");
    load_data(fc2,"info-raw-data-run3" + cost_ver + "-2000_2050_2100-" + kind + ".json");
    load_data(fc3,"info-raw-data-run5" + cost_ver + "-2000_2050_2100-" + kind + ".json");
}

function load_fcs(kind,year) {
    var cost_ver = "";

    if (kind == "cost")
    {
        cost_ver = "-new";
    }
    load_data(fc1,"years/info-raw-data-run1" + cost_ver + "-" + year + "-" + kind + ".json");
    load_data(fc2,"years/info-raw-data-run3" + cost_ver + "-" + year + "-" + kind + ".json");
    load_data(fc3,"years/info-raw-data-run5" + cost_ver + "-" + year + "-" + kind + ".json");
}

function yearUpdate(year) {
    document.querySelector('#yearlabel').value = year;
    load_fcs(chart_type,year);
}

function info(dynamic,kind)
{
    chart_type = kind;
    chart_dyn = dynamic;

    fc1 = add_info("#chart1");
    fc2 = add_info("#chart2");
    fc3 = add_info("#chart3");

    if (dynamic)
    {
        load_fcs(kind,2000);
    }
    else
    {
        load_static(kind);
    }
}

<|endoftext|>