<commit_before>describe('The Mox library', function () {

  beforeEach(function () {
    angular.module('test', ['test1a'])
      .constant('constant', 'c1')
      .directive('directive', function () {
        return {
          scope: {
            key: '='
          },
          priority: 2,
          restrict: 'AE',
          template: '
Directive {{key}}
',
          link: angular.noop
        };
      })
      .directive('directive', function () {
        return {
          restrict: 'AEC',
          template: '
Second directive
'
        };
      })
      .directive('directive2', function () {
        return {
          restrict: 'A',
          template: '
Directive 2
'
        };
      })
      .factory('factory', function () {
        return {
          methodA: angular.noop,
          methodB: angular.noop
        };
      })
      .controller('controller', function ($scope) {
        $scope.name = 'testController';
      })
      .controller('controller2', function ($scope) {
        $scope.name = 'testController2';
      });
    angular.module('test1a', []);
    angular.module('test2', []);
  });

  describe('module()', function () {
    it('should pass the module functions to angular-mock.module', function () {
      spyOn(angular.mock.module, 'apply').and.callThrough();

      var configFn = function ($provide) {};
      mox.module('test', configFn, 'test2').run();
      expect(angular.mock.module.apply).toHaveBeenCalledWith(window, ['test', configFn, 'test2']);
    });

    it('should initialize the injector', function () {
      spyOn(angular.mock, 'inject').and.callThrough();
      mox.module('test', function ($provide) {}, 'test2').run();
      expect(angular.mock.inject).toHaveBeenCalled();
    });

  });

  describe('mockConstants()', function () {
    it('should mock a constant which is mocked for the same module as the original constant', function () {
      mox
        .module('test')
        .mockConstants('constant', 'newConstant')
        .run();

      expect(mox.inject('constant')).toEqual('newConstant');
    });
  });

  describe('mockDirectives()', function () {
    it('should mock the first registered directive with its "light" version', function () {

      mox
        .module('test')
        .mockDirectives('directive')
        .run();

      // All but the next directive properties are stripped
      expect(mox.inject('directiveDirective')[0]).toEqual(jasmine.objectContaining({
        name: 'directive',
        scope: {
          key: '='
        },
        priority: 2,
        index: 0,
        restrict: 'AE'
      }));
    });

    it('should mock a the first registered directive with a newly defined version with some additional properties (name, scope, restrict and priority are not overwritable)', function () {
      var newLinkFn = angular.noop;
      mox
        .module('test')
        .mockDirectives({
          name: 'directive',
          scope: {
            otherKey: '='
          },
          restrict: 'A',
          priority: 3,
          template: '
New template
',
          link: newLinkFn
        })
        .run();

      expect(mox.inject('directiveDirective')[0]).toEqual(jasmine.objectContaining({
        name: 'directive',
        scope: {
          key: '='
        },
        priority: 2,
        index: 0,
        restrict: 'AE',
        template: '
New template
',
        link: newLinkFn
      }));
    });

    describe('when there are multiple directives registered under the same name', function () {
      it('should remove al original directives except for the first', function () {
        mox
          .module('test')
          .mockDirectives('directive')
          .run();

        expect(mox.inject('directiveDirective')).toHaveLength(1);
        expect(mox.inject('directiveDirective')[0].restrict).toBe('AE');
      });
    });

    it('should mock multiple directives when passing multiple names or objects', function () {
      var newLinkFn = angular.noop;
      mox
        .module('test')
        .mockDirectives('directive', { name: 'directive2', link: newLinkFn })
        .run();

      // The restrict property is unique in this test example, so for readibility this property is used to identify mock
      expect(mox.inject('directiveDirective')[0].restrict).toBe('AE');
      expect(mox.inject('directive2Directive')[0].link).toBe(newLinkFn);
    });

    it('should throw an error when passing no arguments to mockDirectives', function () {
      expect(mox.mockDirectives).toThrow(Error('Please provide arguments'));
    });

  });

  describe('disableDirectives()', function () {
    it('should mock al the directives with this name with an empty implementation', function () {
      mox
        .module('test')
        .disableDirectives('directive')
        .run();

      expect(mox.inject('directiveDirective')).toHaveLength(1);
      expect(mox.inject('directiveDirective')).toEqual({});
    });

    it('should mock multiple directives', function () {
      mox
        .module('test')
        .disableDirectives('directive', 'directive2')
        .run();

      expect(mox.inject('directiveDirective')).toEqual({});
      expect(mox.inject('directive2Directive')).toEqual({});
    });
  });

  describe('mockControllers()', function () {
    it('should mock a controller with an empty implementation', function () {
      mox
        .module('test')
        .mockControllers('controller')
        .run();

      var $scope = createScope();
      mox.inject('$controller')('controller', $scope); // Controller sets $scope.name = 'testController';
      expect($scope.name).toBeUndefined();
    });

    it('should mock multiple controllers', function () {
      mox
        .module('test')
        .mockControllers('controller', 'controller2')
        .run();

      var $scope = createScope();
      mox.inject('$controller')('controller', $scope); // Controller sets $scope.name = 'testController';
      expect($scope.name).toBeUndefined();
      mox.inject('$controller')('controller2', $scope); // Controller sets $scope.name = 'testController2';
      expect($scope.name).toBeUndefined();
    });
  });

  describe('saveMock()', function () {
    var
      $provide,
      mockedFactory = 'mockedFactory',
      mockedConstant = 'mockedConstant';

    beforeEach(function () {
      mox
        .module('test', function (_$provide_) {
          $provide = _$provide_;
          spyOn($provide, 'value').and.callThrough();
          mox.save($provide, 'factory', mockedFactory);
          mox.save($provide, 'constant', mockedConstant, 'constant');
        })
        .run();
    });

    it('should register the mock as a value by default', function () {
      expect($provide.value).toHaveBeenCalledWith('factory', mockedFactory);
      expect(mox.inject('factory')).toBe(mockedFactory);
    });

    it('should register the mock with a specified recipe', function () {
      expect(mox.inject('constant')).toBe(mockedConstant);
    });

    it('should save the mock in the Mox cache', function () {
      expect(mox.get.constant).toBe(mockedConstant);
      expect(mox.get.factory).toBe(mockedFactory);
    });
  });

  describe('createMock()', function () {
    beforeEach(function () {
      jasmine.addMatchers({
        toBeSpy: function toBeSpy() {
          return {
            compare: function compareToBeSpy(actual) {
              var pass = false, message;
              if (angular.isFunction(actual)) {
                actual();
                if (actual.calls && actual.calls.any && actual.calls.any()) {
                  pass = true;
                  message = 'Expected ' + jasmine.pp(actual) + ' not to be a spy';
                } else {
                  message = 'Expected ' + jasmine.pp(actual) + ' to be a spy';
                }
              } else {
                message = 'Expected ' + jasmine.pp(actual) + ' to be a spy, but it is no function';
              }
              return {
                pass: pass,
                message: message
              };
            }
          };
        }
      });
    });

    it('should create a mock object with spy functions', function () {
      var mock = mox.createMock('factory', ['methodA', 'methodB'])();
      expect(mock.methodA).toBeSpy();
    });

    it('should create a function mock', function () {
      var mock = mox.createMock('filter')();
      expect(angular.noop).not.toBeSpy();
    });

    it('should create a constant/value mock', function () {
      var mock = mox.createMock('constant', false)();
      expect(mock).toBeUndefined();
    });

    describe('when provided $provide', function () {

      var $provide;

      beforeEach(function () {
        mox.module('test', function (_$provide_) {
          $provide = _$provide_;
        }).run();
        spyOn(mox, 'save');
      });

      it('should register the mock with Mox under its own name', function () {
        var mock = mox.createMock('filter')($provide);
        expect(mox.save).toHaveBeenCalledWith($provide, 'filter', mock, undefined);
      });

      it('should register the mock with Mox under an alias', function () {
        var mock = mox.createMock('filter')($provide, 'alias');
        expect(mox.save).toHaveBeenCalledWith($provide, 'alias', mock, undefined);
      });

      it('should register a constant mock as constant', function () {
        var mock = mox.createMock('constant', false)($provide);
        expect(mox.save).toHaveBeenCalledWith($provide, 'constant', mock, 'constant');
      });

    });

  });
});
<commit_msg>Added specs for mox.mockServices (services and filters). Also adding tests for providing no arguments for other mox methods.<commit_after>angular.extend(moxConfig, {
  factory2: mox.createMock('factory', ['methodA'])
});

describe('The Mox library', function () {

  beforeEach(function () {
    angular.module('test', ['test1a'])
      .constant('constant', 'c1')
      .directive('directive', function () {
        return {
          scope: {
            key: '='
          },
          priority: 2,
          restrict: 'AE',
          template: '
Directive {{key}}
',
          link: angular.noop
        };
      })
      .directive('directive', function () {
        return {
          restrict: 'AEC',
          template: '
Second directive
'
        };
      })
      .directive('directive2', function () {
        return {
          restrict: 'A',
          template: '
Directive 2
'
        };
      })
      .factory('factory', function () {
        return {
          methodA: function () {
            return 'realValue';
          },
          methodB: angular.noop
        };
      })
      .filter('filter2', function () {
        return 'filterResult';
      })
      .controller('controller', function ($scope) {
        $scope.name = 'testController';
      })
      .controller('controller2', function ($scope) {
        $scope.name = 'testController2';
      });
    angular.module('test1a', []);
    angular.module('test2', []);
  });

  describe('module()', function () {
    it('should pass the module functions to angular-mock.module', function () {
      spyOn(angular.mock.module, 'apply').and.callThrough();

      var configFn = function ($provide) {};
      mox.module('test', configFn, 'test2').run();
      expect(angular.mock.module.apply).toHaveBeenCalledWith(window, ['test', configFn, 'test2']);
    });

    it('should initialize the injector', function () {
      spyOn(angular.mock, 'inject').and.callThrough();
      mox.module('test', function ($provide) {}, 'test2').run();
      expect(angular.mock.inject).toHaveBeenCalled();
    });

  });

  describe('mockServices()', function () {
    describe('when mocking a service', function () {
      it('should manually mock a service that is in moxConfig using the mock factory function', function () {
        mox
          .module('test')
          .mockServices('factory2')
          .run();

        var spyA = mox.inject('factory').methodA;

        expect(spyA()).toBeUndefined();
        expect(spyA).toEqual(jasmine.any(Function));
        expect(mox.inject('factory').methodB).toBeUndefined();
      });

      it('should automatically mock a service that is in moxConfig using the original service', function () {
        mox
          .module('test')
          .mockServices('factory')
          .run();

        var
          spyA = mox.inject('factory').methodA,
          spyB = mox.inject('factory').methodB;

        expect(spyA()).toBeUndefined();
        expect(spyB()).toBeUndefined();
        expect(spyA).toEqual(jasmine.any(Function));
        expect(spyB).toEqual(jasmine.any(Function));
      });
    });

    it('should replace the service with a mock instead of spying on the methods, which unsupports "calling through" the spies', function () {
      mox
        .module('test')
        .mockServices('factory')
        .run();

      // Issue #9 addresses missing calling through support
      var spy = mox.inject('factory').methodA;
      spy.and.callThrough();
      expect(spy()).toBeUndefined();
    });

    describe('when mocking filters (and other functions)', function () {
      var filter;

      beforeEach(function () {
        mox
          .module('test')
          .mockServices('filter2Filter')
          .run();
        filter = mox.inject('filter2Filter');
      });

      it('should mock the filter with a spy', function () {
        expect(filter()).toBeUndefined();
      });

      it('should not support calling through', function () {
        // See issue #9
        filter.and.callThrough();
        expect(filter()).toBeUndefined();
      });
    });

    it('should throw an error when providing no arguments', function () {
      expect(mox.mockServices).toThrow(Error('Please provide arguments'));
    });
  });

  describe('mockConstants()', function () {
    it('should mock a constant which is mocked for the same module as the original constant', function () {
      mox
        .module('test')
        .mockConstants('constant', 'newConstant')
        .run();

      expect(mox.inject('constant')).toEqual('newConstant');
    });

    it('should throw an error when providing no arguments', function () {
      expect(mox.mockConstants).toThrow(Error('Please provide arguments'));
    });
  });

  describe('mockDirectives()', function () {
    it('should mock the first registered directive with its "light" version', function () {

      mox
        .module('test')
        .mockDirectives('directive')
        .run();

      // All but the next directive properties are stripped
      expect(mox.inject('directiveDirective')[0]).toEqual(jasmine.objectContaining({
        name: 'directive',
        scope: {
          key: '='
        },
        priority: 2,
        index: 0,
        restrict: 'AE'
      }));
    });

    it('should mock a the first registered directive with a newly defined version with some additional properties (name, scope, restrict and priority are not overwritable)', function () {
      var newLinkFn = angular.noop;
      mox
        .module('test')
        .mockDirectives({
          name: 'directive',
          scope: {
            otherKey: '='
          },
          restrict: 'A',
          priority: 3,
          template: '
New template
',
          link: newLinkFn
        })
        .run();

      expect(mox.inject('directiveDirective')[0]).toEqual(jasmine.objectContaining({
        name: 'directive',
        scope: {
          key: '='
        },
        priority: 2,
        index: 0,
        restrict: 'AE',
        template: '
New template
',
        link: newLinkFn
      }));
    });

    describe('when there are multiple directives registered under the same name', function () {
      it('should remove al original directives except for the first', function () {
        mox
          .module('test')
          .mockDirectives('directive')
          .run();

        expect(mox.inject('directiveDirective')).toHaveLength(1);
        expect(mox.inject('directiveDirective')[0].restrict).toBe('AE');
      });
    });

    it('should mock multiple directives when passing multiple names or objects', function () {
      var newLinkFn = angular.noop;
      mox
        .module('test')
        .mockDirectives('directive', { name: 'directive2', link: newLinkFn })
        .run();

      // The restrict property is unique in this test example, so for readibility this property is used to identify mock
      expect(mox.inject('directiveDirective')[0].restrict).toBe('AE');
      expect(mox.inject('directive2Directive')[0].link).toBe(newLinkFn);
    });

    it('should throw an error when passing no arguments to mockDirectives', function () {
      expect(mox.mockDirectives).toThrow(Error('Please provide arguments'));
    });

  });

  describe('disableDirectives()', function () {
    it('should mock al the directives with this name with an empty implementation', function () {
      mox
        .module('test')
        .disableDirectives('directive')
        .run();

      expect(mox.inject('directiveDirective')).toHaveLength(1);
      expect(mox.inject('directiveDirective')).toEqual({});
    });

    it('should mock multiple directives', function () {
      mox
        .module('test')
        .disableDirectives('directive', 'directive2')
        .run();

      expect(mox.inject('directiveDirective')).toEqual({});
      expect(mox.inject('directive2Directive')).toEqual({});
    });

    it('should throw an error when providing no arguments', function () {
      expect(mox.disableDirectives).toThrow(Error('Please provide arguments'));
    });
  });

  describe('mockControllers()', function () {
    it('should mock a controller with an empty implementation', function () {
      mox
        .module('test')
        .mockControllers('controller')
        .run();

      var $scope = createScope();
      mox.inject('$controller')('controller', $scope); // Controller sets $scope.name = 'testController';
      expect($scope.name).toBeUndefined();
    });

    it('should mock multiple controllers', function () {
      mox
        .module('test')
        .mockControllers('controller', 'controller2')
        .run();

      var $scope = createScope();
      mox.inject('$controller')('controller', $scope); // Controller sets $scope.name = 'testController';
      expect($scope.name).toBeUndefined();
      mox.inject('$controller')('controller2', $scope); // Controller sets $scope.name = 'testController2';
      expect($scope.name).toBeUndefined();
    });

    it('should throw an error when providing no arguments', function () {
      expect(mox.mockControllers).toThrow(Error('Please provide arguments'));
    });
  });

  describe('saveMock()', function () {
    var
      $provide,
      mockedFactory = 'mockedFactory',
      mockedConstant = 'mockedConstant';

    beforeEach(function () {
      mox
        .module('test', function (_$provide_) {
          $provide = _$provide_;
          spyOn($provide, 'value').and.callThrough();
          mox.save($provide, 'factory', mockedFactory);
          mox.save($provide, 'constant', mockedConstant, 'constant');
        })
        .run();
    });

    it('should register the mock as a value by default', function () {
      expect($provide.value).toHaveBeenCalledWith('factory', mockedFactory);
      expect(mox.inject('factory')).toBe(mockedFactory);
    });

    it('should register the mock with a specified recipe', function () {
      expect(mox.inject('constant')).toBe(mockedConstant);
    });

    it('should save the mock in the Mox cache', function () {
      expect(mox.get.constant).toBe(mockedConstant);
      expect(mox.get.factory).toBe(mockedFactory);
    });
  });

  describe('createMock()', function () {
    beforeEach(function () {
      jasmine.addMatchers({
        toBeSpy: function toBeSpy() {
          return {
            compare: function compareToBeSpy(actual) {
              var pass = false, message;
              if (angular.isFunction(actual)) {
                actual();
                if (actual.calls && actual.calls.any && actual.calls.any()) {
                  pass = true;
                  message = 'Expected ' + jasmine.pp(actual) + ' not to be a spy';
                } else {
                  message = 'Expected ' + jasmine.pp(actual) + ' to be a spy';
                }
              } else {
                message = 'Expected ' + jasmine.pp(actual) + ' to be a spy, but it is no function';
              }
              return {
                pass: pass,
                message: message
              };
            }
          };
        }
      });
    });

    it('should create a mock object with spy functions', function () {
      var mock = mox.createMock('factory', ['methodA', 'methodB'])();
      expect(mock.methodA).toBeSpy();
    });

    it('should create a function mock', function () {
      var mock = mox.createMock('filter')();
      expect(angular.noop).not.toBeSpy();
    });

    it('should create a constant/value mock', function () {
      var mock = mox.createMock('constant', false)();
      expect(mock).toBeUndefined();
    });

    describe('when provided $provide', function () {

      var $provide;

      beforeEach(function () {
        mox.module('test', function (_$provide_) {
          $provide = _$provide_;
        }).run();
        spyOn(mox, 'save');
      });

      it('should register the mock with Mox under its own name', function () {
        var mock = mox.createMock('filter')($provide);
        expect(mox.save).toHaveBeenCalledWith($provide, 'filter', mock, undefined);
      });

      it('should register the mock with Mox under an alias', function () {
        var mock = mox.createMock('filter')($provide, 'alias');
        expect(mox.save).toHaveBeenCalledWith($provide, 'alias', mock, undefined);
      });

      it('should register a constant mock as constant', function () {
        var mock = mox.createMock('constant', false)($provide);
        expect(mox.save).toHaveBeenCalledWith($provide, 'constant', mock, 'constant');
      });

    });

  });
});
<|endoftext|>


<commit_before>var painless = require('../../assertion/painless')
var test = painless.createGroup('Test time/now')
var t = painless.assert

var now = require('../../../src/time/now')

var past = now()

test('should return an integer', function () {
  var b = now()
  t.is(b.toFixed('0'), b + '')
})

test('should be greater than first call', function () {
  t.assert(now() > past)
})<commit_msg>lint test time/now<commit_after>var painless = require('../../assertion/painless')
var test = painless.createGroup('Test time/now')
var t = painless.assert

var now = require('../../../src/time/now')

var past = now()

test('should return an integer', function () {
  var b = now()
  t.is(b.toFixed('0'), b + '')
})

test('should be greater than first call', function () {
  t.assert(now() > past)
})
<|endoftext|>


<commit_before>/* global describe, it, expect, before */
/* jshint expr: true */

var chai = require('chai')
  , FacebookStrategy = require('../lib/strategy');

describe('Strategy', function() {

  var strategy = new FacebookStrategy({
      clientID: 'ABC123',
      clientSecret: 'secret'
    },
    function() {});

  it('should be named facebook', function() {
    expect(strategy.name).to.equal('facebook');
  });

  describe('handling a return request in which authorization was denied by user', function() {
    var info;

    before(function(done) {
      chai.passport.use(strategy)
        .fail(function(i) {
          info = i;
          done();
        })
        .req(function(req) {
          req.query = {};
          req.query.error = 'access_denied';
          req.query.error_code = '200';
          req.query.error_description  = 'Permissions error';
          req.query.error_reason = 'user_denied';
        })
        .authenticate();
    });

    it('should fail with info', function() {
      expect(info).to.not.be.undefined;
      expect(info.message).to.equal('Permissions error');
    });
  });

  describe('handling a return request in which authorization has failed with an error', function() {
    var err;

    before(function(done) {
      chai.passport.use(strategy)
        .error(function(e) {
          err = e;
          done();
        })
        .req(function(req) {
          req.query = {};
          req.query.error_code = '901';
          req.query.error_message = 'This app is in sandbox mode.  Edit the app configuration at http://developers.facebook.com/apps to make the app publicly visible.';
        })
        .authenticate();
    });

    it('should error', function() {
      expect(err.constructor.name).to.equal('FacebookAuthorizationError');
      expect(err.message).to.equal('This app is in sandbox mode.  Edit the app configuration at http://developers.facebook.com/apps to make the app publicly visible.');
      expect(err.code).to.equal(901);
      expect(err.status).to.equal(500);
    });
  });

});
<commit_msg>Clarify tests.<commit_after>/* global describe, it, expect, before */
/* jshint expr: true */

var chai = require('chai')
  , FacebookStrategy = require('../lib/strategy');

describe('Strategy', function() {

  describe('constructed', function() {
    var strategy = new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});

    it('should be named facebook', function() {
      expect(strategy.name).to.equal('facebook');
    });
  })

  describe('constructed with undefined options', function() {
    it('should throw', function() {
      expect(function() {
        var strategy = new FacebookStrategy(undefined, function(){});
      }).to.throw(Error);
    });
  })

  describe('failure caused by user denying request', function() {
    var strategy = new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      }, function() {});

    var info;

    before(function(done) {
      chai.passport.use(strategy)
        .fail(function(i) {
          info = i;
          done();
        })
        .req(function(req) {
          req.query = {};
          req.query.error = 'access_denied';
          req.query.error_code = '200';
          req.query.error_description  = 'Permissions error';
          req.query.error_reason = 'user_denied';
        })
        .authenticate();
    });

    it('should fail with info', function() {
      expect(info).to.not.be.undefined;
      expect(info.message).to.equal('Permissions error');
    });
  });

  describe('error caused by app being in sandbox mode', function() {
    var strategy = new FacebookStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      }, function() {});

    var err;

    before(function(done) {
      chai.passport.use(strategy)
        .error(function(e) {
          err = e;
          done();
        })
        .req(function(req) {
          req.query = {};
          req.query.error_code = '901';
          req.query.error_message = 'This app is in sandbox mode.  Edit the app configuration at http://developers.facebook.com/apps to make the app publicly visible.';
        })
        .authenticate();
    });

    it('should error', function() {
      expect(err.constructor.name).to.equal('FacebookAuthorizationError');
      expect(err.message).to.equal('This app is in sandbox mode.  Edit the app configuration at http://developers.facebook.com/apps to make the app publicly visible.');
      expect(err.code).to.equal(901);
      expect(err.status).to.equal(500);
    });
  });

});
<|endoftext|>


<commit_before>/**
 * app.js
 *
 * This is the entry file for the application, only setup and boilerplate
 * code.
 */
import 'babel-polyfill';

/* eslint-disable import/no-unresolved, import/extensions */
// Load the manifest.json file and the .htaccess file
import '!file?name=[name].[ext]!./manifest.json';
import 'file?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */

// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import LanguageProvider from 'containers/LanguageProvider';
import configureStore from './store';

// Import i18n messages
import { translationMessages } from './i18n';

// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/sanitize.css';

// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);

// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
import { selectLocationState } from 'containers/App/selectors';
const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: selectLocationState(),
});

// Set up the router, wrapping all Routes in the App component
import App from 'containers/App';
import createRoutes from './routes';
const rootRoute = {
  component: App,
  childRoutes: createRoutes(store),
};

const render = (translatedMessages) => {
  ReactDOM.render(
    <Provider store={store}>
      <LanguageProvider messages={translatedMessages}>
        <Router
          history={history}
          routes={rootRoute}
          render={
            // Scroll to top when going to a new page, imitating default browser
            // behaviour
            applyRouterMiddleware(useScroll())
          }
        />
      </LanguageProvider>
    </Provider>,
    document.getElementById('app')
  );
};

// Hot reloadable translation json files
if (module.hot) {
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept('./i18n', () => {
    render(translationMessages);
  });
}

// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
  (new Promise((resolve) => {
    resolve(System.import('intl'));
  }))
    .then(() => Promise.all([
      System.import('intl/locale-data/jsonp/de.js'),
    ]))
    .then(() => render(translationMessages))
    .catch((err) => {
      throw err;
    });
} else {
  render(translationMessages);
}

// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
import { install } from 'offline-plugin/runtime';
install();
<commit_msg>fix(example): Fix default Intl polyfill language (#1208)<commit_after>/**
 * app.js
 *
 * This is the entry file for the application, only setup and boilerplate
 * code.
 */
import 'babel-polyfill';

/* eslint-disable import/no-unresolved, import/extensions */
// Load the manifest.json file and the .htaccess file
import '!file?name=[name].[ext]!./manifest.json';
import 'file?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */

// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import LanguageProvider from 'containers/LanguageProvider';
import configureStore from './store';

// Import i18n messages
import { translationMessages } from './i18n';

// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/sanitize.css';

// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);

// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
import { selectLocationState } from 'containers/App/selectors';
const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: selectLocationState(),
});

// Set up the router, wrapping all Routes in the App component
import App from 'containers/App';
import createRoutes from './routes';
const rootRoute = {
  component: App,
  childRoutes: createRoutes(store),
};

const render = (translatedMessages) => {
  ReactDOM.render(
    <Provider store={store}>
      <LanguageProvider messages={translatedMessages}>
        <Router
          history={history}
          routes={rootRoute}
          render={
            // Scroll to top when going to a new page, imitating default browser
            // behaviour
            applyRouterMiddleware(useScroll())
          }
        />
      </LanguageProvider>
    </Provider>,
    document.getElementById('app')
  );
};

// Hot reloadable translation json files
if (module.hot) {
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept('./i18n', () => {
    render(translationMessages);
  });
}

// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
  (new Promise((resolve) => {
    resolve(System.import('intl'));
  }))
    .then(() => Promise.all([
      System.import('intl/locale-data/jsonp/en.js'),
    ]))
    .then(() => render(translationMessages))
    .catch((err) => {
      throw err;
    });
} else {
  render(translationMessages);
}

// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
import { install } from 'offline-plugin/runtime';
install();
<|endoftext|>


<commit_before>var tv = require('intervalometer/time-value.js');
var interpolate = require('intervalometer/interpolate.js');

var exp = {};
var local = {};
exp.status = {};
exp.config = {};

exp.init = function(minEv, maxEv, nightCompensation) {
    if (nightCompensation === null) nightCompensation = 'auto';

    if(nightCompensation != 'auto') {
        nightCompensation = parseFloat(nightCompensation);
    }

    local = {
        lumArray: [],
        evArray: [],
        historyArray: [],
        rateHistoryArray: [],
        targetLum: null,
        first: true
    };

    exp.status = {
        rampEv: null,
        rate: null,
        direction: null
    };

    exp.config = {
        sunrise: {
            p: 0.9,
            i: 0.4,
            d: 0.6,
            targetTimeSeconds: 300,
            evIntegrationSeconds: 300,
            historyIntegrationSeconds: 480,
        },
        sunset: {
            p: 1.1,
            i: 0.6,
            d: 0.4,
            targetTimeSeconds: 480,
            evIntegrationSeconds: 480,
            historyIntegrationSeconds: 480,
        },
        maxEv: maxEv,
        minEv: minEv,
        maxRate: 30,
        hysteresis: 0.4,
        nightCompensationDayEv: 10,
        nightCompensationNightEv: -2,
        nightCompensation: nightCompensation
    };

    return exp.config;
}

exp.calculate = function(algorithm, direction, currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv) {
    if(minEv != null) exp.config.minEv = minEv;
    if(maxEv != null) exp.config.maxEv = maxEv;

    console.log("LRT: direction = ", direction);
    if(['auto', 'sunset', 'sunrise'].indexOf(direction) === -1) direction = 'auto';

    if(algorithm == "lrt") {
        return exp.calculate_LRTtimelapse(currentEv, direction, lastPhotoLum, lastPhotoHistogram, minEv, maxEv);
    } else {
        return exp.calculate_TLPAuto(currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv);
    }
}

exp.calculate_LRTtimelapse = function(currentEv, direction, lastPhotoLum, lastPhotoHistogram, minEv, maxEv) {
    var lum = 0;
    for(var i = 0; i < 256; i++) {
        lum += Math.pow(i, i / 256) / 256 * lastPhotoHistogram[i];
    }

    lum -= (lum * getEvOffsetScale(currentEv, lastPhotoLum)) / 2; // apply night compensation

    if(local.targetLum === null) {  // first time
        exp.status.rampEv = currentEv;
        local.lrtLumArray = [];
        local.targetLum = lum;

        if(direction == 'sunrise') {
            local.direction = 1;
        } else if(direction == 'sunset') {
            local.direction = -1;
        } else {
            local.direction = 0;
        }
    }

    local.lrtLumArray.push(lum);
    if(local.lrtLumArray.length > 5) {
        local.lrtLumArray.shift();
    }
    lum = (local.lrtLumArray.reduce(function(sum, l) { return sum + l; }, 0)) / local.lrtLumArray.length;

    var directionFactor;

    directionFactor = local.direction >= 0 ? 1 : 8;
    if((direction == 'auto' || direction == 'sunrise') && lum > local.targetLum * (1 + 0.2 * directionFactor)) {
        exp.status.rampEv = currentEv + 1/3;
        local.direction = 1;
    }
    directionFactor = local.direction <= 0 ? 1 : 8;
    if((direction == 'auto' || direction == 'sunset') && lum < local.targetLum / (1 + 0.2 * directionFactor)) {
        exp.status.rampEv = currentEv -  1/3;
        local.direction = -1;
    }

    console.log("LRT Lum:", lum, local.direction, local.targetLum, " currentEv:", currentEv, ", newEv:", exp.status.rampEv, ", Dir:", direction);

    return exp.status.rampEv;
}

exp.calculate_TLPAuto = function(currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv) {
    // measure the interval
    exp.status.intervalSeconds = 0;
    var thisPhotoTime = new Date();
    if (local.lastPhotoTime) {
        exp.status.intervalSeconds = (thisPhotoTime - local.lastPhotoTime) / 1000;
    }
    local.lastPhotoTime = thisPhotoTime;

    // get config based on rate up/down
    var config = exp.config.sunset;
    if (exp.status.direction && exp.status.direction > 0) {
        config = exp.config.sunrise;
    }

    // get the current rate of change
    exp.status.rate = calculateRate(currentEv, lastPhotoLum, config);
    console.log("rate: ", exp.status.rate);

    // don't change if within hysteresis setting
    if (Math.abs(exp.status.rate) < exp.config.hysteresis) exp.status.rate = 0;

    // limit to max rate
    if(exp.status.rate > exp.config.maxRate) exp.status.rate = exp.config.maxRate;
    if(exp.status.rate < -exp.config.maxRate) exp.status.rate = -exp.config.maxRate;

    // don't swing quickly past zero (stops oscillation)
    if (exp.status.rate > 3 && exp.status.direction < -0.5) exp.status.rate = 0;
    if (exp.status.rate < -3 && exp.status.direction > 0.5) exp.status.rate = 0;

    // adjust exposure according to rate in stops/hour
    exp.status.rampEv += (exp.status.rate / 3600) * exp.status.intervalSeconds;

    console.log("status: ", exp.status);
    //console.log("local: ", local);

    return exp.status.rampEv;
}

// ******* Private Functions ******* //

function filteredMean(tvArr, trim) {
    if (!trim) trim = 1;
    return tv.mean(tv.insideArray(tvArr, trim));
}

function filteredSlope(tvArr, trim) {
    if (!trim) trim = 1;
    return tv.mean(tv.insideArray(tv.slopes(tvArr), trim));
}

function calculateRate(currentEv, lastPhotoLum, config) {
    var diff = calculateDelta(currentEv, lastPhotoLum, config);
    exp.status.targetEv = currentEv + diff;
    if (exp.status.targetEv < exp.config.minEv) exp.status.targetEv = exp.config.minEv;
    if (exp.status.targetEv > exp.config.maxEv) exp.status.targetEv = exp.config.maxEv;
    if (exp.status.rampEv === null) exp.status.rampEv = exp.status.targetEv;
    var delta = exp.status.targetEv - exp.status.rampEv;
    local.historyArray.push({
        val: delta,
        time: new Date()
    });
    local.historyArray = tv.purgeArray(local.historyArray, config.historyIntegrationSeconds);

    exp.status.pastError = tv.mean(local.historyArray);

    exp.status.pComponent = delta * config.p;
    exp.status.iComponent = exp.status.pastError * config.i;
    exp.status.dComponent = exp.status.evSlope * config.d;

    delta *= config.p;
    delta += exp.status.pastError * config.i;
    delta += exp.status.evSlope * config.d;

    var rate = delta * (3600 / config.targetTimeSeconds);

    local.rateHistoryArray.push({
        val: rate,
        time: new Date()
    });
    local.rateHistoryArray = tv.purgeArray(local.rateHistoryArray, config.historyIntegrationSeconds);
    exp.status.direction = tv.mean(local.rateHistoryArray);

    return rate;
}

function calculateDelta(currentEv, lastPhotoLum, config) {
    local.lumArray.push({
        val: lastPhotoLum,
        time: new Date()
    });

    local.evArray.push({
        val: currentEv + lastPhotoLum,
        time: new Date()
    });

    if (local.first) {
        exp.status.offsetEv = lastPhotoLum - getEvOffsetScale(currentEv, lastPhotoLum);
        local.first = false;
    }

    local.lumArray = tv.purgeArray(local.lumArray, config.evIntegrationSeconds);
    local.evArray = tv.purgeArray(local.evArray, config.evIntegrationSeconds);

    var trim = 1;
    if (exp.status.intervalSeconds) {
        trim = Math.ceil((config.evIntegrationSeconds / exp.status.intervalSeconds) * 0.2); // trim outer 20% from sorted array
    }

    exp.status.evMean = filteredMean(local.lumArray, trim);
    exp.status.evSlope = filteredSlope(local.evArray, trim) * config.targetTimeSeconds;

    return lastPhotoLum - exp.status.offsetEv - getEvOffsetScale(currentEv, lastPhotoLum);
}

function getEvOffsetScale(ev, lastPhotoLum, noAuto) {
    var evScale
    if(exp.config.nightCompensation == 'auto') {
        if(noAuto) { // for LRT algorithm
            evScale = [{
                ev: exp.config.nightCompensationNightEv,
                offset: -1.333333
            }, {
                ev: exp.config.nightCompensationDayEv,
                offset: 0
            }]
        } else { // auto calculate night exposure
            evScale = [{
                ev: exp.config.nightCompensationNightEv,
                offset: -(lastPhotoLum - -1.5)
            }, {
                ev: exp.config.nightCompensationDayEv,
                offset: -(lastPhotoLum - 0.0)
            }]
        }
    } else {
        evScale = [{
            ev: exp.config.nightCompensationNightEv,
            offset: exp.config.nightCompensation
        }, {
            ev: exp.config.nightCompensationDayEv,
            offset: 0
        }]
    }

    var values = evScale.map(function(item) {
        return {
            x: item.ev,
            y: item.offset
        }
    });
    return interpolate.linear(values, ev);
}

module.exports = exp;<commit_msg>lrt update debug<commit_after>var tv = require('intervalometer/time-value.js');
var interpolate = require('intervalometer/interpolate.js');

var exp = {};
var local = {};
exp.status = {};
exp.config = {};

exp.init = function(minEv, maxEv, nightCompensation) {
    if (nightCompensation === null) nightCompensation = 'auto';

    if(nightCompensation != 'auto') {
        nightCompensation = parseFloat(nightCompensation);
    }

    local = {
        lumArray: [],
        evArray: [],
        historyArray: [],
        rateHistoryArray: [],
        targetLum: null,
        first: true
    };

    exp.status = {
        rampEv: null,
        rate: null,
        direction: null
    };

    exp.config = {
        sunrise: {
            p: 0.9,
            i: 0.4,
            d: 0.6,
            targetTimeSeconds: 300,
            evIntegrationSeconds: 300,
            historyIntegrationSeconds: 480,
        },
        sunset: {
            p: 1.1,
            i: 0.6,
            d: 0.4,
            targetTimeSeconds: 480,
            evIntegrationSeconds: 480,
            historyIntegrationSeconds: 480,
        },
        maxEv: maxEv,
        minEv: minEv,
        maxRate: 30,
        hysteresis: 0.4,
        nightCompensationDayEv: 10,
        nightCompensationNightEv: -2,
        nightCompensation: nightCompensation
    };

    return exp.config;
}

exp.calculate = function(algorithm, direction, currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv) {
    if(minEv != null) exp.config.minEv = minEv;
    if(maxEv != null) exp.config.maxEv = maxEv;

    if(['auto', 'sunset', 'sunrise'].indexOf(direction) === -1) direction = 'auto';

    if(algorithm == "lrt") {
        return exp.calculate_LRTtimelapse(currentEv, direction, lastPhotoLum, lastPhotoHistogram, minEv, maxEv);
    } else {
        return exp.calculate_TLPAuto(currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv);
    }
}

exp.calculate_LRTtimelapse = function(currentEv, direction, lastPhotoLum, lastPhotoHistogram, minEv, maxEv) {
    var lum = 0;
    for(var i = 0; i < 256; i++) {
        lum += Math.pow(i, i / 256) / 256 * lastPhotoHistogram[i];
    }

    var lum1 = lum;

    lum -= (lum * getEvOffsetScale(currentEv, lastPhotoLum)) / 2; // apply night compensation

    var lum2 = lum;

    if(local.targetLum === null) {  // first time
        exp.status.rampEv = currentEv;
        local.lrtLumArray = [];
        local.targetLum = lum;

        if(direction == 'sunrise') {
            local.direction = 1;
        } else if(direction == 'sunset') {
            local.direction = -1;
        } else {
            local.direction = 0;
        }
    }

    local.lrtLumArray.push(lum);
    if(local.lrtLumArray.length > 5) {
        local.lrtLumArray.shift();
    }
    lum = (local.lrtLumArray.reduce(function(sum, l) { return sum + l; }, 0)) / local.lrtLumArray.length;

    var lum3 = lum;

    var directionFactor;

    directionFactor = local.direction >= 0 ? 1 : 8;
    if((direction == 'auto' || direction == 'sunrise') && lum > local.targetLum * (1 + 0.2 * directionFactor)) {
        exp.status.rampEv = currentEv + 1/3;
        local.direction = 1;
    }
    directionFactor = local.direction <= 0 ? 1 : 8;
    if((direction == 'auto' || direction == 'sunset') && lum < local.targetLum / (1 + 0.2 * directionFactor)) {
        exp.status.rampEv = currentEv -  1/3;
        local.direction = -1;
    }

    console.log("LRT LumX:", lum1, lum2, lum3);

    console.log("LRT Lum:", lum, local.direction, local.targetLum, " currentEv:", currentEv, ", newEv:", exp.status.rampEv, ", Dir:", direction);

    return exp.status.rampEv;
}

exp.calculate_TLPAuto = function(currentEv, lastPhotoLum, lastPhotoHistogram, minEv, maxEv) {
    // measure the interval
    exp.status.intervalSeconds = 0;
    var thisPhotoTime = new Date();
    if (local.lastPhotoTime) {
        exp.status.intervalSeconds = (thisPhotoTime - local.lastPhotoTime) / 1000;
    }
    local.lastPhotoTime = thisPhotoTime;

    // get config based on rate up/down
    var config = exp.config.sunset;
    if (exp.status.direction && exp.status.direction > 0) {
        config = exp.config.sunrise;
    }

    // get the current rate of change
    exp.status.rate = calculateRate(currentEv, lastPhotoLum, config);
    console.log("rate: ", exp.status.rate);

    // don't change if within hysteresis setting
    if (Math.abs(exp.status.rate) < exp.config.hysteresis) exp.status.rate = 0;

    // limit to max rate
    if(exp.status.rate > exp.config.maxRate) exp.status.rate = exp.config.maxRate;
    if(exp.status.rate < -exp.config.maxRate) exp.status.rate = -exp.config.maxRate;

    // don't swing quickly past zero (stops oscillation)
    if (exp.status.rate > 3 && exp.status.direction < -0.5) exp.status.rate = 0;
    if (exp.status.rate < -3 && exp.status.direction > 0.5) exp.status.rate = 0;

    // adjust exposure according to rate in stops/hour
    exp.status.rampEv += (exp.status.rate / 3600) * exp.status.intervalSeconds;

    console.log("status: ", exp.status);
    //console.log("local: ", local);

    return exp.status.rampEv;
}

// ******* Private Functions ******* //

function filteredMean(tvArr, trim) {
    if (!trim) trim = 1;
    return tv.mean(tv.insideArray(tvArr, trim));
}

function filteredSlope(tvArr, trim) {
    if (!trim) trim = 1;
    return tv.mean(tv.insideArray(tv.slopes(tvArr), trim));
}

function calculateRate(currentEv, lastPhotoLum, config) {
    var diff = calculateDelta(currentEv, lastPhotoLum, config);
    exp.status.targetEv = currentEv + diff;
    if (exp.status.targetEv < exp.config.minEv) exp.status.targetEv = exp.config.minEv;
    if (exp.status.targetEv > exp.config.maxEv) exp.status.targetEv = exp.config.maxEv;
    if (exp.status.rampEv === null) exp.status.rampEv = exp.status.targetEv;
    var delta = exp.status.targetEv - exp.status.rampEv;
    local.historyArray.push({
        val: delta,
        time: new Date()
    });
    local.historyArray = tv.purgeArray(local.historyArray, config.historyIntegrationSeconds);

    exp.status.pastError = tv.mean(local.historyArray);

    exp.status.pComponent = delta * config.p;
    exp.status.iComponent = exp.status.pastError * config.i;
    exp.status.dComponent = exp.status.evSlope * config.d;

    delta *= config.p;
    delta += exp.status.pastError * config.i;
    delta += exp.status.evSlope * config.d;

    var rate = delta * (3600 / config.targetTimeSeconds);

    local.rateHistoryArray.push({
        val: rate,
        time: new Date()
    });
    local.rateHistoryArray = tv.purgeArray(local.rateHistoryArray, config.historyIntegrationSeconds);
    exp.status.direction = tv.mean(local.rateHistoryArray);

    return rate;
}

function calculateDelta(currentEv, lastPhotoLum, config) {
    local.lumArray.push({
        val: lastPhotoLum,
        time: new Date()
    });

    local.evArray.push({
        val: currentEv + lastPhotoLum,
        time: new Date()
    });

    if (local.first) {
        exp.status.offsetEv = lastPhotoLum - getEvOffsetScale(currentEv, lastPhotoLum);
        local.first = false;
    }

    local.lumArray = tv.purgeArray(local.lumArray, config.evIntegrationSeconds);
    local.evArray = tv.purgeArray(local.evArray, config.evIntegrationSeconds);

    var trim = 1;
    if (exp.status.intervalSeconds) {
        trim = Math.ceil((config.evIntegrationSeconds / exp.status.intervalSeconds) * 0.2); // trim outer 20% from sorted array
    }

    exp.status.evMean = filteredMean(local.lumArray, trim);
    exp.status.evSlope = filteredSlope(local.evArray, trim) * config.targetTimeSeconds;

    return lastPhotoLum - exp.status.offsetEv - getEvOffsetScale(currentEv, lastPhotoLum);
}

function getEvOffsetScale(ev, lastPhotoLum, noAuto) {
    var evScale
    if(exp.config.nightCompensation == 'auto') {
        if(noAuto) { // for LRT algorithm
            evScale = [{
                ev: exp.config.nightCompensationNightEv,
                offset: -1.333333
            }, {
                ev: exp.config.nightCompensationDayEv,
                offset: 0
            }]
        } else { // auto calculate night exposure
            evScale = [{
                ev: exp.config.nightCompensationNightEv,
                offset: -(lastPhotoLum - -1.5)
            }, {
                ev: exp.config.nightCompensationDayEv,
                offset: -(lastPhotoLum - 0.0)
            }]
        }
    } else {
        evScale = [{
            ev: exp.config.nightCompensationNightEv,
            offset: exp.config.nightCompensation
        }, {
            ev: exp.config.nightCompensationDayEv,
            offset: 0
        }]
    }

    var values = evScale.map(function(item) {
        return {
            x: item.ev,
            y: item.offset
        }
    });
    return interpolate.linear(values, ev);
}

module.exports = exp;<|endoftext|>


<commit_before>// Note: this file is to be run by casperjs, not node.

var casper = require('casper').create();

var fs = require('fs');
var fname = new Date().getTime() + '.txt';
var x = require('casper').selectXPath;
var save = fs.pathJoin(fs.workingDirectory, 'execisejson', fname);
var log = require('../logger');

casper.userAgent('Mozilla/4.0 (comptible; MSIE 6.0; Windows NT 5.1)');

casper.start('https://www.exercise.com/users/sign_in');

casper.then(function(){

	this.sendKeys('#user_email', casper.cli.get('uname'));
	this.sendKeys('#user_password', casper.cli.get('pword'));

});

casper.thenClick(x('//*[@id="new_user"]/div[4]/input'), function() {

});

casper.wait(20000, function(){

});

var apiURL = 'https://www.exercise.com/api/v2/workouts?all_fields=true';

casper.thenOpen(apiURL, function(){
	casper.wait(5000, function(){

	//base64encode makes an http request
	var contents = atob(this.base64encode(apiURL));

	log.verbose(contents);

	});
});

casper.run();
<commit_msg>fixed catastophic error of doom in casperjs<commit_after>// Note: this file is to be run by casperjs, not node.

var casper = require('casper').create();

var fs = require('fs');
var fname = new Date().getTime() + '.txt';
var x = require('casper').selectXPath;
var save = fs.pathJoin(fs.workingDirectory, 'execisejson', fname);

casper.userAgent('Mozilla/4.0 (comptible; MSIE 6.0; Windows NT 5.1)');

casper.start('https://www.exercise.com/users/sign_in');

casper.then(function(){

	this.sendKeys('#user_email', casper.cli.get('uname'));
	this.sendKeys('#user_password', casper.cli.get('pword'));

});

casper.thenClick(x('//*[@id="new_user"]/div[4]/input'), function() {

});

casper.wait(20000, function(){

});

var apiURL = 'https://www.exercise.com/api/v2/workouts?all_fields=true';

casper.thenOpen(apiURL, function(){
	casper.wait(5000, function(){

	//base64encode makes an http request
	var contents = atob(this.base64encode(apiURL));

	console.log(contents);

	});
});

casper.run();
<|endoftext|>


<commit_before>angular.module('rifiuti.services.utili', [])

.factory('Conf', function() {

    return {
        showNews: function() {
            return SHOW_NEWS;
        }
    };
})

.factory('ConnectionErrorService', function($ionicPopup,$filter) {
  return {
    show : function() {
        var popup = $ionicPopup.show({
            title: ''+$filter("translate")("dev_mode")+'',
            template: $filter("translate")("connection_error"),
            buttons: [
                {
                    text: 'OK'
                }
            ]
        });
     }
   }
})

.factory('LoaderService', function($rootScope, $ionicLoading, $filter) {
  return {

        showToastByTime : function(alertMsg, time){
            $ionicLoading.show({
                template:  $filter("translate")(alertMsg),
                noBackdrop: true,
                duration: time });
        },

        showToast : function(alertMsg){
            $ionicLoading.show({
                template:  $filter("translate")(alertMsg),
                noBackdrop: true,
                duration: 3000 });
        },

        show : function() {

            $rootScope.loading = $ionicLoading.show({

              // The text to display in the loading indicator
              content: ' Loading',

              // The animation to use
              animation: 'fade-in',

              // Will a dark overlay or backdrop cover the entire view
              showBackdrop: true,

              // The maximum width of the loading indicator
              // Text will be wrapped if longer than maxWidth
              maxWidth: 200,

              // The delay in showing the indicator
              showDelay: 10
            });
        },

        hide : function(){
            if ($rootScope.loading) {
                $ionicLoading.hide();
            }
        }
    }
})

.factory('Utili', function () {
  var mesi = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"];
  var giorni = ["DOM", "LUN", "MAR", "MER", "GIO", "VEN", "SAB"];
  var giorniC = ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"];
  var giorniShort = ["dom", "lun", "mar", "mer", "gio", "ven", "sab"];

  var DOW = {"DOM":6, "LUN":0, "MAR":1, "MER":2, "GIO":3, "VEN":4, "SAB":5};

  var daysInMonth = function(month, year) {
      return new Date(year, month + 1, 0).getDate();
  };
  var dayIndex = function(day) {
          return DOW[day];
  };

  var format = function(date) {
    return date.getFullYear()+'-'+(date.getMonth() < 9 ? '0'+(date.getMonth()+1):(date.getMonth()+1))+'-'+(date.getDate() < 10 ? '0'+date.getDate():date.getDate());
  };

  var generateDOWDates = function(da, a, dow, ecc) {
      var res = [];
      var currFrom = new Date(da.getTime());
      currFrom.setDate(currFrom.getDate()-dayIndex(giorni[currFrom.getDay()])+dow);
      while (currFrom.getTime() <= a.getTime()) {
        if (currFrom.getTime() >= da.getTime()) {
          var dStr = format(currFrom);
          if (!ecc || ecc.indexOf(dStr) < 0) res.push(dStr);
        }
        // move to next week
        currFrom.setDate(currFrom.getDate()+7);
      }
      return res;
  };

  /**
   * generate a list of date string for the specified period, date, definition, and list of exceptions (format dd/MM[/yyyy])
   * definition is space-separated elements, where element is either DOW (e.g., lunedi) or date (format dd/MM[/yyyy])
   */
  var calToDates = function(da, a, il, ecc) {
    if (!il) return [];

    var arr = il.trim().split(' ');
    var dates = [];
    var eccDates = calToDates(da, a, ecc, null);
    for (var i = 0; i < arr.length; i++) {
      var elem = arr[i];
      var idx = giorniC.indexOf(elem);
      // DOW case
      if (idx >= 0) {
        dates = dates.concat(generateDOWDates(da, a, DOW[giorni[idx]], eccDates));
      // date case
      } else {
        var dElems = elem.split('/');
        if (dElems.length < 2 || dElems.length > 3) return;
        if (dElems.length == 2) dElems.push(''+da.getFullYear());
        var dStr = format(new Date(dElems[2], dElems[1]-1, dElems[0]));
        if (!ecc || ecc.indexOf(dStr) < 0) dates.push(dStr);
      }
    }
    dates.sort();
    return dates;
  };

  var iconType = function(tipologia) {
    if (tipologia in ICON_POINT_MAP) return ICON_POINT_MAP[tipologia];
    return null;
  };

  var rgbColor = function(colore) {
      if (colore in ICON_COLOR_MAP) return ICON_COLOR_MAP[colore];
      return 'grey';
  }

  return {
    jsDOWToShortText: function(dow) {
      return giorni[dow];
    },
    jsDOWToDOW: function(dow) {
      return DOW[giorni[dow]];
    },
    DOWTextToDOW: function(dow) {
      return DOW[dow];
    },
    dayIndex: dayIndex,
    textToDOW: function(txt) {
      return DOW[giorni[giorniC.indexOf(txt)]];
    },
    dayToDOW: function(day) {
      return dayIndex(giorni[day]);
    },
    monthYear: function(a, b) {
        return mesi[a] + " " + b
    },
    isLastDayInMonth : function(dt) {
        return new Date(dt.getTime() + 86400000).getDate() === 1;
    },
    lastDateOfMonth: function(date) {
        return new Date(date.getFullYear(), date.getMonth() + 1, 0);
    },
    calToDates: calToDates,
    expandOrarioApertura: function(cal) {
      if (!cal.il || cal.dates) return;
      var max = new Date(Date.parse(cal.dataA));
      var min = new Date(Date.parse(cal.dataDa));
      cal.dates = calToDates(min,max, cal.il, cal.eccezione);
    },

    getRGBColor: function(rgbColor) {
        var c = rgbColor;
        if (c == 'white') {
            return 'grey';
        }
        return c;
    },
    iconFromRegola: function(regola) {
      return this.icon(regola.tipologiaPuntoRaccolta, regola.colore);
    },
//    icon: function(tipologia, colore) {
//      var icona = iconType(tipologia);
//      return (!!icona?'img/ic_'+icona+'_'+this.getRGBColor(colore)+'.png':null);
//    },
    icon: function(icona,colorById) {
      //var icona = iconType(tipologia);
      if (colorById=='white') {
        return icona + '-outline';
      }
      return icona;
    },
    poiIcon: function(icona, colore) {
      //var icona = iconType(tipologia);
      return (!!icona?'img/ic_poi_'+icona+'.png':null);
    },
    belongsTo: function(pr, area, profile) {
      return profile.aree.indexOf(area) != -1
          //&& (pr.tipologiaPuntiRaccolta=='CRM' || pr.tipologiaPuntiRaccolta=='CRZ' || !pr.zona || profile.comuni.indexOf(pr.zona)!=-1)
        ;
    },
    isPaP: function(tipoPuntoRaccolta) {
      return !!tipoPuntoRaccolta && !!tipoPuntoRaccolta.type && (tipoPuntoRaccolta.type == 'PP' || !!CUSTOM_PAP && CUSTOM_PAP.indexOf(tipoPuntoRaccolta.type) >= 0);
    },
      //return !!tipologia && (tipologia.toLowerCase().indexOf('porta a porta') == 0 || !!CUSTOM_PAP && CUSTOM_PAP.indexOf(tipologia) >= 0);
	fullDateFormat: function(d,transf) {
		return transf(giorniShort[d.getDay()])+ ' ' +d.getDate()+' '+transf(mesi[d.getMonth()])+' '+d.getFullYear();
	},
//    filterCharacteristics: function(pdr) {
//        if (!ISOLA_MAPPING) return false;
//        if (!pdr.caratteristiche) return false;
//        for (var key in pdr.caratteristiche) {
//            if (pdr.caratteristiche[key]) return true;
//        }
//        return false;
//    },
    pdrCharacteristicApplies: function(pdr, tipo) {
        var mapping = null;
        try {
            mapping = ISOLA_MAPPING;
        }catch(e) {
        }
        if (mapping != null && pdr.caratteristiche && !pdr.caratteristiche[mapping[tipo]]) return false;
        return true;
    }
  }
})
<commit_msg>issue #50, Some exceptions days seems to be discarded, fixed<commit_after>angular.module('rifiuti.services.utili', [])

.factory('Conf', function() {

    return {
        showNews: function() {
            return SHOW_NEWS;
        }
    };
})

.factory('ConnectionErrorService', function($ionicPopup,$filter) {
  return {
    show : function() {
        var popup = $ionicPopup.show({
            title: ''+$filter("translate")("dev_mode")+'',
            template: $filter("translate")("connection_error"),
            buttons: [
                {
                    text: 'OK'
                }
            ]
        });
     }
   }
})

.factory('LoaderService', function($rootScope, $ionicLoading, $filter) {
  return {

        showToastByTime : function(alertMsg, time){
            $ionicLoading.show({
                template:  $filter("translate")(alertMsg),
                noBackdrop: true,
                duration: time });
        },

        showToast : function(alertMsg){
            $ionicLoading.show({
                template:  $filter("translate")(alertMsg),
                noBackdrop: true,
                duration: 3000 });
        },

        show : function() {

            $rootScope.loading = $ionicLoading.show({

              // The text to display in the loading indicator
              content: ' Loading',

              // The animation to use
              animation: 'fade-in',

              // Will a dark overlay or backdrop cover the entire view
              showBackdrop: true,

              // The maximum width of the loading indicator
              // Text will be wrapped if longer than maxWidth
              maxWidth: 200,

              // The delay in showing the indicator
              showDelay: 10
            });
        },

        hide : function(){
            if ($rootScope.loading) {
                $ionicLoading.hide();
            }
        }
    }
})

.factory('Utili', function () {
  var mesi = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"];
  var giorni = ["DOM", "LUN", "MAR", "MER", "GIO", "VEN", "SAB"];
  var giorniC = ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"];
  var giorniShort = ["dom", "lun", "mar", "mer", "gio", "ven", "sab"];

  var DOW = {"DOM":6, "LUN":0, "MAR":1, "MER":2, "GIO":3, "VEN":4, "SAB":5};

  var daysInMonth = function(month, year) {
      return new Date(year, month + 1, 0).getDate();
  };
  var dayIndex = function(day) {
          return DOW[day];
  };

  var format = function(date) {
    return date.getFullYear()+'-'+(date.getMonth() < 9 ? '0'+(date.getMonth()+1):(date.getMonth()+1))+'-'+(date.getDate() < 10 ? '0'+date.getDate():date.getDate());
  };

  var generateDOWDates = function(da, a, dow, ecc) {
      var res = [];
      var currFrom = new Date(da.getTime());
      currFrom.setDate(currFrom.getDate()-dayIndex(giorni[currFrom.getDay()])+dow);
      while (currFrom.getTime() <= a.getTime()) {
        if (currFrom.getTime() >= da.getTime()) {
          var dStr = format(currFrom);
          if (!ecc || ecc.indexOf(dStr) < 0) res.push(dStr);
        }
        // move to next week
        currFrom.setDate(currFrom.getDate()+7);
      }
      return res;
  };

  /**
   * generate a list of date string for the specified period, date, definition, and list of exceptions (format dd/MM[/yyyy])
   * definition is space-separated elements, where element is either DOW (e.g., lunedi) or date (format dd/MM[/yyyy])
   */
  var calToDates = function(da, a, il, ecc) {
    if (!il) return [];

    var arr = il.trim().split(' ');
    var dates = [];
    var eccDates = calToDates(da, a, ecc, null);
    for (var i = 0; i < arr.length; i++) {
      var elem = arr[i];
      if (elem == "") continue;
      var idx = giorniC.indexOf(elem);
      // DOW case
      if (idx >= 0) {
        dates = dates.concat(generateDOWDates(da, a, DOW[giorni[idx]], eccDates));
      // date case
      } else {
        var dElems = elem.split('/');
        if (dElems.length < 2 || dElems.length > 3) return;
        if (dElems.length == 2) dElems.push(''+da.getFullYear());
        var dStr = format(new Date(dElems[2], dElems[1]-1, dElems[0]));
        if (!ecc || ecc.indexOf(dStr) < 0) dates.push(dStr);
      }
    }
    dates.sort();
    return dates;
  };

  var iconType = function(tipologia) {
    if (tipologia in ICON_POINT_MAP) return ICON_POINT_MAP[tipologia];
    return null;
  };

  var rgbColor = function(colore) {
      if (colore in ICON_COLOR_MAP) return ICON_COLOR_MAP[colore];
      return 'grey';
  }

  return {
    jsDOWToShortText: function(dow) {
      return giorni[dow];
    },
    jsDOWToDOW: function(dow) {
      return DOW[giorni[dow]];
    },
    DOWTextToDOW: function(dow) {
      return DOW[dow];
    },
    dayIndex: dayIndex,
    textToDOW: function(txt) {
      return DOW[giorni[giorniC.indexOf(txt)]];
    },
    dayToDOW: function(day) {
      return dayIndex(giorni[day]);
    },
    monthYear: function(a, b) {
        return mesi[a] + " " + b
    },
    isLastDayInMonth : function(dt) {
        return new Date(dt.getTime() + 86400000).getDate() === 1;
    },
    lastDateOfMonth: function(date) {
        return new Date(date.getFullYear(), date.getMonth() + 1, 0);
    },
    calToDates: calToDates,
    expandOrarioApertura: function(cal) {
      if (!cal.il || cal.dates) return;
      var max = new Date(Date.parse(cal.dataA));
      var min = new Date(Date.parse(cal.dataDa));
      cal.dates = calToDates(min,max, cal.il, cal.eccezione);
    },

    getRGBColor: function(rgbColor) {
        var c = rgbColor;
        if (c == 'white') {
            return 'grey';
        }
        return c;
    },
    iconFromRegola: function(regola) {
      return this.icon(regola.tipologiaPuntoRaccolta, regola.colore);
    },
//    icon: function(tipologia, colore) {
//      var icona = iconType(tipologia);
//      return (!!icona?'img/ic_'+icona+'_'+this.getRGBColor(colore)+'.png':null);
//    },
    icon: function(icona,colorById) {
      //var icona = iconType(tipologia);
      if (colorById=='white') {
        return icona + '-outline';
      }
      return icona;
    },
    poiIcon: function(icona, colore) {
      //var icona = iconType(tipologia);
      return (!!icona?'img/ic_poi_'+icona+'.png':null);
    },
    belongsTo: function(pr, area, profile) {
      return profile.aree.indexOf(area) != -1
          //&& (pr.tipologiaPuntiRaccolta=='CRM' || pr.tipologiaPuntiRaccolta=='CRZ' || !pr.zona || profile.comuni.indexOf(pr.zona)!=-1)
        ;
    },
    isPaP: function(tipoPuntoRaccolta) {
      return !!tipoPuntoRaccolta && !!tipoPuntoRaccolta.type && (tipoPuntoRaccolta.type == 'PP' || !!CUSTOM_PAP && CUSTOM_PAP.indexOf(tipoPuntoRaccolta.type) >= 0);
    },
      //return !!tipologia && (tipologia.toLowerCase().indexOf('porta a porta') == 0 || !!CUSTOM_PAP && CUSTOM_PAP.indexOf(tipologia) >= 0);
	fullDateFormat: function(d,transf) {
		return transf(giorniShort[d.getDay()])+ ' ' +d.getDate()+' '+transf(mesi[d.getMonth()])+' '+d.getFullYear();
	},
//    filterCharacteristics: function(pdr) {
//        if (!ISOLA_MAPPING) return false;
//        if (!pdr.caratteristiche) return false;
//        for (var key in pdr.caratteristiche) {
//            if (pdr.caratteristiche[key]) return true;
//        }
//        return false;
//    },
    pdrCharacteristicApplies: function(pdr, tipo) {
        var mapping = null;
        try {
            mapping = ISOLA_MAPPING;
        }catch(e) {
        }
        if (mapping != null && pdr.caratteristiche && !pdr.caratteristiche[mapping[tipo]]) return false;
        return true;
    }
  }
})
<|endoftext|>


<commit_before>function  StochasticOptimisation(){
// Returns the parameterisation that has been optimised in the format that it was handed to the original function
	this.Function;
	this.PArray=[];

	this.ParamNow;// indicates the parameter that is currently being modified

	this.CurrentParameterArray=[];
	this.CurrentParameter={};

	this.SeedValue;// The seed value is used to reset the seed each time for the random number

	this.Update;// this is a function that is run at the end of each round to, for example.

// start values
// start percentage change
// max/min values
// error function
// stop after x iterations/y seconds

	this.OptimisedParam;

	this.NumberOfSamplesPerRound=10;

	this.StopTime=1e9;//standard stop time of 1e9 seconds

	this.Help='formats for structure\n Function(ParamForOptimisation) \n Update(TrialNumber, Error)';
}
StochasticOptimisation.prototype.AddParameter=function(P){
	var A=new StochasticOptimisationParameter;
	A.Name=P.Name;
	A.StartValue=P.StartValue;
	A.CurrentValue=P.StartValue;
	A.FractionalChange=P.FractionalChange;
	A.Min=P.Min;
	A.Max=P.Max;

	// Add this parameter to the list of parameters to optimise
	this.PArray.push(A);
}

// This optimisation cycles through each of the parameters individually, adjusts it a little, runs and returns the results
// Note that if there is a dependence of one on the other, this must be programmed into the function that does the optimisation

StochasticOptimisation.prototype.Run= function (){
	//Set up the simulation for the first time
	for key in A {
		Parameter[Key].CurrentValue=
	}
	// Run the first sims to get the baseline error
	this.BestError=this.Function(Constants

	// Keep running until time, number of sims runs out, or absolute error is reached, or precision is reached in all variables

}

StochasticOptimisation.prototype.BuildParameter= function (){
	var ParamStruct={};
	for ( in this.PArray){

	}

	return ParamStruct;
}

function StochasticOptimisationParameter(){
	this.StartValue;
	this.FractionalChange;
	this.Min;
	this.Max;
	this.CurrentValue=[];//vector that stores all the current values
	this.BestValue;// the best value in the overall simulation
}

StochasticOptimisationParameter.prototype.StartValue= function (){
	this.StartValue=this.Min+(this.Max-this.Min)Rand.Value();
}

StochasticOptimisationParameter.prototype.Vary= function (){
	if (typeof this.CurrentValue===undefined){
		this.CurrentValue=this.StartValue;
	}
	else{
		//try to vary

	}
}<commit_msg>Improving stochastic optimisation<commit_after>function  StochasticOptimisation(){
// Returns the parameterisation that has been optimised in the format that it was handed to the original function
	this.Function;
	this.PArray=[];

	this.ParamNow;// indicates the parameter that is currently being modified

	this.CurrentParameterArray=[];
	this.CurrentParameter={};

	this.SeedValue;// The seed value is used to reset the seed each time for the random number

	this.Update;// this is a function that is run at the end of each round to, for example.

// start values
// start percentage change
// max/min values
// error function
// stop after x iterations/y seconds

	this.OptimisedParam;

	this.NumberOfSamplesPerRound=10;

	this.StopTime=1e9;//standard stop time of 1e9 seconds

	this.Help='formats for structure\n Function(ParamForOptimisation) \n Update(TrialNumber, Error)';
}
StochasticOptimisation.prototype.AddParameter=function(P){
	var A=new StochasticOptimisationParameter;
	A.Name=P.Name;
	A.StartValue=P.StartValue;
	A.CurrentValue=P.StartValue;
	A.FractionalChange=P.FractionalChange;
	A.Min=P.Min;
	A.Max=P.Max;

	// Add this parameter to the list of parameters to optimise
	this.PArray.push(A);
}

// This optimisation cycles through each of the parameters individually, adjusts it a little, runs and returns the results
// Note that if there is a dependence of one on the other, this must be programmed into the function that does the optimisation

StochasticOptimisation.prototype.Run= function (){
	//Set up the simulation for the first time
	for key in A {
		Parameter[Key].CurrentValue=
	}
	// Run the first sims to get the baseline error
	this.BestError=this.Function(Constants

	// Keep running until time, number of sims runs out, or absolute error is reached, or precision is reached in all variables

}

StochasticOptimisation.prototype.BuildParameter= function (){
	var ParamStruct={};
	for ( in this.PArray){

	}

	return ParamStruct;
}

function StochasticOptimisationParameter(){
	this.Min;
	this.Max;
	this.CurrentRange;
	this.AverageDistance;
	this.CurrentVec=[];//vector that stores all the current values
	this.BestVec=[];
	this.BestValue;// the best value in the overall simulation
}

StochasticOptimisationParameter.prototype.StartValue= function (){
	this.StartValue=this.Min+(this.Max-this.Min)Rand.Value();
}

StochasticOptimisationParameter.prototype.Vary= function (){
	if (typeof this.CurrentValue===undefined){
		this.CurrentValue=this.StartValue;
	}
	else{
		//try to vary

	}
}<|endoftext|>


<commit_before>// @flow

import * as React from 'react'
import {StyleSheet} from 'react-native'
import * as c from '../../../components/colors'
// import SearchBar from 'react-native-material-design-searchbar'
import SearchBar from 'react-native-searchbar'
import Icon from 'react-native-vector-icons/MaterialIcons'

const iconStyles = StyleSheet.create({
	icon: {
		color: c.gray,
	},
})

const searchIcon = <Icon name="search" size={28} style={iconStyles.icon} />
const backIcon = <Icon name="arrow-back" size={28} style={iconStyles.icon} />

const styles = StyleSheet.create({
	searchbar: {
		backgroundColor: c.white,
		height: 44,
	},
})

type Props = {
	getRef?: any,
	style?: any,
	placeholder?: string,
	onChangeText: string => any,
	onCancel: () => any,
	onFocus: () => any,
	onSearchButtonPress: string => any,
	searchActive: boolean,
}

type State = {
	input: string,
}

export class CourseSearchBar extends React.PureComponent<Props, State> {
	state = {
		input: '',
	}

	updateText = input => {
		this.setState({input: input})
	}

	render() {
		const backButton = this.props.searchActive ? backIcon : searchIcon
		return (
			<SearchBar
				ref={this.props.getRef}
				backButton={backButton}
				focusOnLayout={false}
				handleChangeText={this.updateText}
				onBack={this.props.onCancel}
				onFocus={this.props.onFocus}
				onHide={text => console.log(text)}
				onSubmitEditing={() => {
					this.props.onSearchButtonPress(this.state.input)
				}}
				placeholder={this.props.placeholder || 'Search'}
				showOnLoad={true}
				style={[styles.searchbar, this.props.style]}
			/>
		)
	}
}
<commit_msg>switch to Ionicons<commit_after>// @flow

import * as React from 'react'
import {StyleSheet} from 'react-native'
import * as c from '../../../components/colors'
// import SearchBar from 'react-native-material-design-searchbar'
import SearchBar from 'react-native-searchbar'
import Icon from 'react-native-vector-icons/Ionicons'

const iconStyles = StyleSheet.create({
	icon: {
		color: c.gray,
	},
})

const searchIcon = <Icon name="md-search" size={28} style={iconStyles.icon} />
const backIcon = <Icon name="md-arrow-back" size={28} style={iconStyles.icon} />

const styles = StyleSheet.create({
	searchbar: {
		backgroundColor: c.white,
		height: 44,
	},
})

type Props = {
	getRef?: any,
	style?: any,
	placeholder?: string,
	onChangeText: string => any,
	onCancel: () => any,
	onFocus: () => any,
	onSearchButtonPress: string => any,
	searchActive: boolean,
}

type State = {
	input: string,
}

export class CourseSearchBar extends React.PureComponent<Props, State> {
	state = {
		input: '',
	}

	updateText = input => {
		this.setState({input: input})
	}

	render() {
		const backButton = this.props.searchActive ? backIcon : searchIcon
		return (
			<SearchBar
				ref={this.props.getRef}
				backButton={backButton}
				focusOnLayout={false}
				handleChangeText={this.updateText}
				onBack={this.props.onCancel}
				onFocus={this.props.onFocus}
				onHide={text => console.log(text)}
				onSubmitEditing={() => {
					this.props.onSearchButtonPress(this.state.input)
				}}
				placeholder={this.props.placeholder || 'Search'}
				showOnLoad={true}
				style={[styles.searchbar, this.props.style]}
			/>
		)
	}
}
<|endoftext|>


<commit_before>/*   Riassence Framework
 *   Copyright 2006 Riassence Inc.
 *   http://riassence.com/
 *
 *   You should have received a copy of the GNU General Public License along
 *   with this software package. If not, contact licensing@riassence.com
 */

/*** = Description
  ** Defines a minimal +HValue+ responder interface.
  ** It's implemented by default by +HControl+.
***/
HValueResponder = HClass.extend({

/** = Description
  * Binds an HValue compatible instance to the component's valueObj. Also
  * calls +setValue+. It should not be called from user code, instead
  * use the +HValue+ instance method +bind+.
  *
  * = Parameter
  * +_aValueObj+:: The HValue instance object to bind.
  *
  * = Returns
  * +self+
  *
  **/
  setValueObj: function(_valueObj) {
    this.valueObj = _valueObj;
    if(this['value'] === undefined || (this.value === null && _valueObj.value !== null)){
      this.value = _valueObj.value;
    }
    this.setValue(_valueObj.value);
    return this;
  },

/** = Description
  * Checks, if the value given as parameter differs from +value+.
  *
  * = Parameters
  * +_value+:: The value to be tested.
  *
  * = Returns
  * A boolean true (different) or false (same).
  *
  **/
  valueDiffers: function(_value){
    return (COMM.Values.encode(_value) !== COMM.Values.encode(this.value));
  },

/** = Description
  * Assigns the object a new value.
  * Extend it, if your component needs to do validation of the new value.
  * For +HControl+ instances, extend HControl#refreshValue to do something when
  * the +value+ has been set.
  *
  * = Parameter
  * +_value+::  The new value. Allowed values depend on the component type
  *             and other usage of the bound +HValue+ instance +self.valueObj+.
  *
  * = Returns
  * +self+
  *
  **/
  setValue: function(_value) {
    if(_value !== undefined && this['valueObj'] && this.valueDiffers(_value)) {
      var _valueManager = COMM.Values;
      this.value = _value;
      if( _valueManager._builtins.indexOf( _valueManager.type(_value) ) === -1 ){
        this.valueObj.set( _valueManager.clone( _value ) );
      }
      else {
        this.valueObj.set( _value );
      }
      (this['refresh'] !== undefined) && (typeof this.refresh === 'function') && this.refresh();
    }
    return this;
  }

});<commit_msg>Actually, the last change hurt: reverted back.<commit_after>/*   Riassence Framework
 *   Copyright 2006 Riassence Inc.
 *   http://riassence.com/
 *
 *   You should have received a copy of the GNU General Public License along
 *   with this software package. If not, contact licensing@riassence.com
 */

/*** = Description
  ** Defines a minimal +HValue+ responder interface.
  ** It's implemented by default by +HControl+.
***/
HValueResponder = HClass.extend({

/** = Description
  * Binds an HValue compatible instance to the component's valueObj. Also
  * calls +setValue+. It should not be called from user code, instead
  * use the +HValue+ instance method +bind+.
  *
  * = Parameter
  * +_aValueObj+:: The HValue instance object to bind.
  *
  * = Returns
  * +self+
  *
  **/
  setValueObj: function(_valueObj) {
    this.valueObj = _valueObj;
    this.setValue(_valueObj.value);
    return this;
  },

/** = Description
  * Checks, if the value given as parameter differs from +value+.
  *
  * = Parameters
  * +_value+:: The value to be tested.
  *
  * = Returns
  * A boolean true (different) or false (same).
  *
  **/
  valueDiffers: function(_value){
    return (COMM.Values.encode(_value) !== COMM.Values.encode(this.value));
  },

/** = Description
  * Assigns the object a new value.
  * Extend it, if your component needs to do validation of the new value.
  * For +HControl+ instances, extend HControl#refreshValue to do something when
  * the +value+ has been set.
  *
  * = Parameter
  * +_value+::  The new value. Allowed values depend on the component type
  *             and other usage of the bound +HValue+ instance +self.valueObj+.
  *
  * = Returns
  * +self+
  *
  **/
  setValue: function(_value) {
    if(_value !== undefined && this['valueObj'] && this.valueDiffers(_value)) {
      var _valueManager = COMM.Values;
      this.value = _value;
      if( _valueManager._builtins.indexOf( _valueManager.type(_value) ) === -1 ){
        this.valueObj.set( _valueManager.clone( _value ) );
      }
      else {
        this.valueObj.set( _value );
      }
      (this['refresh'] !== undefined) && (typeof this.refresh === 'function') && this.refresh();
    }
    return this;
  }

});<|endoftext|>


<commit_before>import { expect } from 'chai';

import renderTemplate, { init as initTemplates } from '../lib/template';
import { readFile } from '../lib/util';

describe('template', () => {

	describe('render', () => {
		it('should render template to HTML', () => {
			initTemplates('test/samples');
			let result = renderTemplate('test/samples/template.ect', {world: 'world'});
			expect(result).to.eql(readFile('test/expected/template.html'));
		});
	});

});
<commit_msg>Fix template tests.<commit_after>import { expect } from 'chai';

import renderTemplate, { init as initTemplates } from '../lib/template';
import { readFile } from '../lib/util';

describe('template', () => {

	describe('render', () => {
		it('should render template to HTML', () => {
			initTemplates({root: 'test/samples'});
			let result = renderTemplate('template', {world: 'world'});
			expect(result).to.eql(readFile('test/expected/template.html'));
		});
	});

});
<|endoftext|>


<commit_before>/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          ______     ______     ______   __  __     __     ______
          /\  == \   /\  __ \   /\__  _\ /\ \/ /    /\ \   /\__  _\
          \ \  __<   \ \ \/\ \  \/_/\ \/ \ \  _"-.  \ \ \  \/_/\ \/
          \ \_____\  \ \_____\    \ \_\  \ \_\ \_\  \ \_\    \ \_\
           \/_____/   \/_____/     \/_/   \/_/\/_/   \/_/     \/_/

This is a sample Slack bot built with Botkit.

This bot demonstrates many of the core features of Botkit:

* Connect to Slack using the real time API
* Receive messages based on "spoken" patterns
* Send a message with attachments
* Send a message via direct message (instead of in a public channel)

# RUN THE BOT:

  Get a Bot token from Slack:

    -> http://my.slack.com/services/new/bot

  Run your bot from the command line:

    token=<MY TOKEN> node demo_bot.js

# USE THE BOT:

  Find your bot inside Slack to send it a direct message.

  Say: "Hello"

  The bot will reply "Hello!"

  Say: "Attach"

  The bot will send a message with a multi-field attachment.

  Send: "dm"

  The bot will reply with a direct message.

  Make sure to invite your bot into other channels using /invite @<my bot>!

# EXTEND THE BOT:

  Botkit is has many features for building cool and useful bots!

  Read all about it here:

    -> http://howdy.ai/botkit

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

var Botkit = require('../lib/Botkit.js');

if (!process.env.token) {
  console.log('Error: Specify token in environment');
  process.exit(1);
}

var controller = Botkit.slackbot({
 debug: false
});

controller.spawn({
  token: process.env.token
}).startRTM(function(err) {
  if (err) {
    throw new Error(err);
  }
});

controller.hears(['hello','hi'],'direct_message,direct_mention,mention',function(bot,message) {
    bot.reply(message,"Hello.");
})

controller.hears(['attach'],'direct_message,direct_mention',function(bot,message) {

  var attachments = [];
  var attachment = {
    title: 'This is an attachment',
    color: '#FFCC99',
    fields: [],
  }

  attachment.fields.push({
    label: 'Field',
    value: 'A longish value',
    short: false,
  })

  attachment.fields.push({
    label: 'Field',
    value: 'Value',
    short: true,
  })

  attachment.fields.push({
    label: 'Field',
    value: 'Value',
    short: true,
  })

  attachments.push(attachment);

  bot.reply(message,{
    text: 'See below...',
    attachments: attachments,
  },function(err,resp) {
    console.log(err,resp);
  });
});

controller.hears(['dm me'],'direct_message,direct_mention',function(bot,message) {
  bot.startConversation(message,function(err,convo) {
    convo.say('Heard ya');
  });

  bot.startPrivateConversation(message,function(err,dm) {
    dm.say('Private reply!');
  })

});
<commit_msg>Replaces 'a,b,c' notation with ['a','b','c'] notation in demo_bot.js<commit_after>/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          ______     ______     ______   __  __     __     ______
          /\  == \   /\  __ \   /\__  _\ /\ \/ /    /\ \   /\__  _\
          \ \  __<   \ \ \/\ \  \/_/\ \/ \ \  _"-.  \ \ \  \/_/\ \/
          \ \_____\  \ \_____\    \ \_\  \ \_\ \_\  \ \_\    \ \_\
           \/_____/   \/_____/     \/_/   \/_/\/_/   \/_/     \/_/

This is a sample Slack bot built with Botkit.

This bot demonstrates many of the core features of Botkit:

* Connect to Slack using the real time API
* Receive messages based on "spoken" patterns
* Send a message with attachments
* Send a message via direct message (instead of in a public channel)

# RUN THE BOT:

  Get a Bot token from Slack:

    -> http://my.slack.com/services/new/bot

  Run your bot from the command line:

    token=<MY TOKEN> node demo_bot.js

# USE THE BOT:

  Find your bot inside Slack to send it a direct message.

  Say: "Hello"

  The bot will reply "Hello!"

  Say: "Attach"

  The bot will send a message with a multi-field attachment.

  Send: "dm"

  The bot will reply with a direct message.

  Make sure to invite your bot into other channels using /invite @<my bot>!

# EXTEND THE BOT:

  Botkit is has many features for building cool and useful bots!

  Read all about it here:

    -> http://howdy.ai/botkit

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

var Botkit = require('../lib/Botkit.js');

if (!process.env.token) {
  console.log('Error: Specify token in environment');
  process.exit(1);
}

var controller = Botkit.slackbot({
 debug: false
});

controller.spawn({
  token: process.env.token
}).startRTM(function(err) {
  if (err) {
    throw new Error(err);
  }
});

controller.hears(['hello','hi'],['direct_message','direct_mention','mention'],function(bot,message) {
    bot.reply(message,"Hello.");
})

controller.hears(['attach'],['direct_message','direct_mention'],function(bot,message) {

  var attachments = [];
  var attachment = {
    title: 'This is an attachment',
    color: '#FFCC99',
    fields: [],
  }

  attachment.fields.push({
    label: 'Field',
    value: 'A longish value',
    short: false,
  })

  attachment.fields.push({
    label: 'Field',
    value: 'Value',
    short: true,
  })

  attachment.fields.push({
    label: 'Field',
    value: 'Value',
    short: true,
  })

  attachments.push(attachment);

  bot.reply(message,{
    text: 'See below...',
    attachments: attachments,
  },function(err,resp) {
    console.log(err,resp);
  });
});

controller.hears(['dm me'],['direct_message','direct_mention'],function(bot,message) {
  bot.startConversation(message,function(err,convo) {
    convo.say('Heard ya');
  });

  bot.startPrivateConversation(message,function(err,dm) {
    dm.say('Private reply!');
  })

});
<|endoftext|>


<commit_before>import React from 'react';
import FocusTrap from 'focus-trap-react';
import {Cropper} from 'react-image-cropper';
import changeUserData from '../../../actions/user/userprofile/changeUserData';
import { Button, Icon, Modal, Container, Segment, Menu,Label,Input,Divider, TextArea} from 'semantic-ui-react';

class ChangePictureModal extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            openModal: false,
            activeTrap: false
        };

        this.handleOpen = this.handleOpen.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.unmountTrap = this.unmountTrap.bind(this);
        this.uploadCroppedPicture = this.uploadCroppedPicture.bind(this);
    }

    handleOpen(){
        $('#app').attr('aria-hidden','true');
        this.setState({
            modalOpen:true,
            activeTrap:true
        });
    }

    handleClose(){
        $('#app').attr('aria-hidden','false');
        this.setState({
            modalOpen:false,
            activeTrap: false
        });
    }

    unmountTrap(){
        if(this.state.activeTrap){
            this.setState({ activeTrap: false });
            $('#app').attr('aria-hidden','false');
        }
    }

    uploadCroppedPicture(e) {
        let payload = {};
        Object.assign(payload, this.props.user);
        payload.picture = this.refs.cropper.crop({ maxWidth: 170 });
        if(payload.picture.length > 50){ //check if this is a picture or not - if not, the base64 repesentation is about 5 chars
            this.context.executeAction(changeUserData, payload);
            this.handleClose();
        } else {
            this.handleClose();
            swal({
                title: 'A wild error has been spotted!',
                text: 'There it is. You catched it! - Seems like we can not handle your picture. Please try another one.',
                type: 'error',
                confirmButtonClass: 'ui primary button',
                buttonsStyling: false
            });
        }
    }

    render() {
        return (
          <Modal trigger={
                  <Button tabIndex='-1' id="ChangePictureModalOpenButton" aria-hidden={this.state.modalOpen} basic onClick={this.handleOpen} style={{'display': 'none'}}/>
                 }
              open={this.state.modalOpen}
              onClose={this.handleClose}
              size="large"
              role="dialog"
              id="ChangePictureModal"
              aria-labelledby="ChangePictureModalHeader"
              aria-describedby="ChangePictureModalDescription"
              tabIndex="0">
              <FocusTrap
                  id='focus-trap-ChangePictureModal'
                  className = "header"
                  active={this.state.activeTrap}
                  focusTrapOptions={{
                      onDeactivate: this.unmountTrap,
                      clickOutsideDeactivates: false,
                      initialFocus: '#ChangePictureModalCancelButton',
                  }}>
                  <Modal.Header className="ui left aligned" as="h1" id="ChangePictureModalHeader">
                      Crop your image
                  </Modal.Header>
                  <Modal.Content>
                      <Divider />
                      <TextArea className="sr-only" id="ChangePictureModalDescription" value="This modal is used to crop and save a picture meant to be used as a user-profile picture." />
                      <Cropper src={this.props.filePath} ref="cropper" fixedRatio={true} rate={1}/>
                      <Divider />
                      <Modal.Actions className="ui center aligned" as="div" style={{'textAlign': 'right'}}>
                        <Button id="ChangePictureModalCancelButton" color='red' tabIndex="0" type="button" aria-label="Cancel" onClick={this.handleClose} icon="minus circle" labelPosition='left' content="Cancel"/>
                        <Button color="green" tabIndex="0" type="button" aria-label="Save" onClick={this.uploadCroppedPicture} icon="save" labelPosition='left' content="Save"/>
                      </Modal.Actions>
                  </Modal.Content>
              </FocusTrap>
          </Modal>
        );
    }
}

ChangePictureModal.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};

export default ChangePictureModal;
<commit_msg>Changed initial focus of the modal to the save button<commit_after>import React from 'react';
import FocusTrap from 'focus-trap-react';
import {Cropper} from 'react-image-cropper';
import changeUserData from '../../../actions/user/userprofile/changeUserData';
import { Button, Icon, Modal, Container, Segment, Menu,Label,Input,Divider, TextArea} from 'semantic-ui-react';

class ChangePictureModal extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            openModal: false,
            activeTrap: false
        };

        this.handleOpen = this.handleOpen.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.unmountTrap = this.unmountTrap.bind(this);
        this.uploadCroppedPicture = this.uploadCroppedPicture.bind(this);
    }

    handleOpen(){
        $('#app').attr('aria-hidden','true');
        this.setState({
            modalOpen:true,
            activeTrap:true
        });
    }

    handleClose(){
        $('#app').attr('aria-hidden','false');
        this.setState({
            modalOpen:false,
            activeTrap: false
        });
    }

    unmountTrap(){
        if(this.state.activeTrap){
            this.setState({ activeTrap: false });
            $('#app').attr('aria-hidden','false');
        }
    }

    uploadCroppedPicture(e) {
        let payload = {};
        Object.assign(payload, this.props.user);
        payload.picture = this.refs.cropper.crop({ maxWidth: 170 });
        if(payload.picture.length > 50){ //check if this is a picture or not - if not, the base64 repesentation is about 5 chars
            this.context.executeAction(changeUserData, payload);
            this.handleClose();
        } else {
            this.handleClose();
            swal({
                title: 'A wild error has been spotted!',
                text: 'There it is. You catched it! - Seems like we can not handle your picture. Please try another one.',
                type: 'error',
                confirmButtonClass: 'ui primary button',
                buttonsStyling: false
            });
        }
    }

    render() {
        return (
          <Modal trigger={
                  <Button tabIndex='-1' id="ChangePictureModalOpenButton" aria-hidden={this.state.modalOpen} basic onClick={this.handleOpen} style={{'display': 'none'}}/>
                 }
              open={this.state.modalOpen}
              onClose={this.handleClose}
              size="large"
              role="dialog"
              id="ChangePictureModal"
              aria-labelledby="ChangePictureModalHeader"
              aria-describedby="ChangePictureModalDescription"
              tabIndex="0">
              <FocusTrap
                  id='focus-trap-ChangePictureModal'
                  className = "header"
                  active={this.state.activeTrap}
                  focusTrapOptions={{
                      onDeactivate: this.unmountTrap,
                      clickOutsideDeactivates: false,
                      initialFocus: '#ChangePictureModalSaveButton',
                  }}>
                  <Modal.Header className="ui left aligned" as="h1" id="ChangePictureModalHeader">
                      Crop your image
                  </Modal.Header>
                  <Modal.Content>
                      <Divider />
                      <TextArea className="sr-only" id="ChangePictureModalDescription" value="This modal is used to crop and save a picture meant to be used as a user-profile picture." />
                      <Cropper src={this.props.filePath} ref="cropper" fixedRatio={true} rate={1}/>
                      <Divider />
                      <Modal.Actions className="ui center aligned" as="div" style={{'textAlign': 'right'}}>
                        <Button color='red' tabIndex="0" type="button" aria-label="Cancel" onClick={this.handleClose} icon="minus circle" labelPosition='left' content="Cancel"/>
                        <Button id="ChangePictureModalSaveButton" color="green" tabIndex="0" type="button" aria-label="Save" onClick={this.uploadCroppedPicture} icon="save" labelPosition='left' content="Save"/>
                      </Modal.Actions>
                  </Modal.Content>
              </FocusTrap>
          </Modal>
        );
    }
}

ChangePictureModal.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};

export default ChangePictureModal;
<|endoftext|>