<commit_before>/*jslint nodejs: true*/

var should = require('should'),
    cors = require('../lib'),
    fakeRequest = function(){
      var _headers = {
        'origin': 'request.com',
        'access-control-request-headers': 'requestedHeader1,requestedHeader2'
      };
      return {
        header: function(key){
          var value = _headers[key.toLowerCase()];
          return value;
        }
      };
    },
    fakeResponse = function(){
      var _headers = {};
      return {
        header: function(key, value){
          if(value === undefined){
            var value = _headers[key];
            return value;
          }else{
            _headers[key] = value;
            return;
          }
        }
      };
    };

describe('cors', function(){
  it('passes control to next middleware', function(done){
    // arrange
    var req = fakeRequest();
    var res = fakeResponse();
    var next = function(){
      done();
    };

    // act
    cors()(req, res, next);
  });

  it('shortcircuits preflight requests', function(done){
    // arrange
    var req = fakeRequest();
    req.method = 'OPTIONS';
    var res = fakeResponse();
    res.send = function(code){
      // assert
      code.should.equal(204);
      done();
    };
    var next = function(){
      // assert
      done('should not be called');
    };

    // act
    cors()(req, res, next);
  });

  it('can disabled shortcircuiting preflight requests', function(done){
    // arrange
    var options = {
      enablePreflight: false
    };
    var req = fakeRequest();
    req.method = 'OPTIONS';
    var res = fakeResponse();
    res.send = function(code){
      // assert
      done('should not be called');
    };
    var next = function(){
      // assert
      done();
    };

    // act
    cors(options)(req, res, next);
  });

  it('no options enables default CORS to all origins and methods', function(done){
    // arrange
    var req = fakeRequest();
    var res = fakeResponse();
    var next = function(){
      // assert
      res.header('Access-Control-Allow-Origin').should.equal('*');
      res.header('Access-Control-Allow-Methods').should.equal('GET,PUT,POST,DELETE');
      done();
    };

    // act
    cors()(req, res, next);
  });

  describe('passing static options', function(){
    it('overrides defaults', function(done){
      // arrange
      var options = {
        origin: 'example.com',
        methods: ['FOO', 'bar'],
        headers: ['FIZZ', 'buzz'],
        credentials: true,
        maxAge: 123
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        res.header('Access-Control-Allow-Origin').should.equal('example.com');
        res.header('Access-Control-Allow-Methods').should.equal('FOO,bar');
        res.header('Access-Control-Allow-Headers').should.equal('FIZZ,buzz');
        res.header('Access-Control-Allow-Credentials').should.equal('true');
        res.header('Access-Control-Allow-Max-Age').should.equal('123');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('origin of false disables cors', function(done){
      // arrange
      var options = {
        origin: false,
        methods: ['FOO', 'bar'],
        headers: ['FIZZ', 'buzz'],
        credentials: true,
        maxAge: 123
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        should.not.exist(res.header('Access-Control-Allow-Origin'));
        should.not.exist(res.header('Access-Control-Allow-Methods'));
        should.not.exist(res.header('Access-Control-Allow-Headers'));
        should.not.exist(res.header('Access-Control-Allow-Credentials'));
        should.not.exist(res.header('Access-Control-Allow-Max-Age'));
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('can override origin', function(done){
      // arrange
      var options = {
        origin: 'example.com'
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        res.header('Access-Control-Allow-Origin').should.equal('example.com');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('origin defaults to *', function(done){
      // arrange
      var options = {
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        res.header('Access-Control-Allow-Origin').should.equal('*');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('specifying true for origin reflects requesting origin', function(done){
      // arrange
      var options = {
        origin: true
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        res.header('Access-Control-Allow-Origin').should.equal('request.com');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('can override methods', function(done){
      // arrange
      var options = {
        methods: ['method1', 'method2']
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        res.header('Access-Control-Allow-Methods').should.equal('method1,method2');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('methods defaults to GET, PUT, POST, DELETE', function(done){
      // arrange
      var options = {
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        res.header('Access-Control-Allow-Methods').should.equal('GET,PUT,POST,DELETE');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('can specify headers', function(done){
      // arrange
      var options = {
        headers: ['header1', 'header2']
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        res.header('Access-Control-Allow-Headers').should.equal('header1,header2');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('specifying an empty list or string of headers will result in no response header for headers', function(done){
      // arrange
      var options = {
        headers: []
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        should.not.exist(res.header('Access-Control-Allow-Headers'));
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('if no headers are specified, defaults to requested headers', function(done){
      // arrange
      var options = {
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        res.header('Access-Control-Allow-Headers').should.equal('requestedHeader1,requestedHeader2');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('includes credentials if explicitly enabled', function(done){
      // arrange
      var options = {
        credentials: true
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        res.header('Access-Control-Allow-Credentials').should.equal('true');
        //should.not.exist(res.header('Access-Control-Allow-Credentials'));
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('does not includes credentials unless explicitly enabled', function(done){
      // arrange
      var options = {
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        should.not.exist(res.header('Access-Control-Allow-Credentials'));
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('includes maxAge when specified', function(done){
      // arrange
      var options = {
        maxAge: 456
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        res.header('Access-Control-Allow-Max-Age').should.equal('456');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('does not includes maxAge unless specified', function(done){
      // arrange
      var options = {
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        should.not.exist(res.header('Access-Control-Allow-Max-Age'));
        done();
      };

      // act
      cors(options)(req, res, next);
    });
  });

  describe('passing a function to build options', function(){
    it('handles options specified via callback', function(done){
      // arrange
      var delegate = function(req, cb){
        cb(null, {
          origin: 'delegate.com'
        });
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(){
        // assert
        res.header('Access-Control-Allow-Origin').should.equal('delegate.com');
        done();
      };

      // act
      cors(delegate)(req, res, next);
    });

    it('handles error specified via callback', function(done){
      // arrange
      var delegate = function(req, cb){
        cb('some error');
      };
      var req = fakeRequest();
      var res = fakeResponse();
      var next = function(err){
        // assert
        err.should.equal('some error');
        done();
      };

      // act
      cors(delegate)(req, res, next);
    });
  });
});
<commit_msg>tests now pass LINT<commit_after>/*jslint nodejs: true*/
/*global describe: true, it: true*/

var should = require('should'),
    cors = require('../lib'),
    fakeRequest = function(){
      var _headers = {
        'origin': 'request.com',
        'access-control-request-headers': 'requestedHeader1,requestedHeader2'
      };
      return {
        header: function(key){
          var value = _headers[key.toLowerCase()];
          return value;
        }
      };
    },
    fakeResponse = function(){
      var _headers = {};
      return {
        header: function(key, value){
          if(value === undefined){
            var retval = _headers[key];
            return retval;
          }else{
            _headers[key] = value;
            return;
          }
        }
      };
    };

describe('cors', function(){
  it('passes control to next middleware', function(done){
    // arrange
    var req, res, next;
    req = fakeRequest();
    res = fakeResponse();
    next = function(){
      done();
    };

    // act
    cors()(req, res, next);
  });

  it('shortcircuits preflight requests', function(done){
    // arrange
    var req, res, next;
    req = fakeRequest();
    req.method = 'OPTIONS';
    res = fakeResponse();
    res.send = function(code){
      // assert
      code.should.equal(204);
      done();
    };
    next = function(){
      // assert
      done('should not be called');
    };

    // act
    cors()(req, res, next);
  });

  it('can disabled shortcircuiting preflight requests', function(done){
    // arrange
    var req, res, next, options;
    options = {
      enablePreflight: false
    };
    req = fakeRequest();
    req.method = 'OPTIONS';
    res = fakeResponse();
    res.send = function(code){
      // assert
      done('should not be called');
    };
    next = function(){
      // assert
      done();
    };

    // act
    cors(options)(req, res, next);
  });

  it('no options enables default CORS to all origins and methods', function(done){
    // arrange
    var req, res, next;
    req = fakeRequest();
    res = fakeResponse();
    next = function(){
      // assert
      res.header('Access-Control-Allow-Origin').should.equal('*');
      res.header('Access-Control-Allow-Methods').should.equal('GET,PUT,POST,DELETE');
      done();
    };

    // act
    cors()(req, res, next);
  });

  describe('passing static options', function(){
    it('overrides defaults', function(done){
      // arrange
      var req, res, next, options;
      options = {
        origin: 'example.com',
        methods: ['FOO', 'bar'],
        headers: ['FIZZ', 'buzz'],
        credentials: true,
        maxAge: 123
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        res.header('Access-Control-Allow-Origin').should.equal('example.com');
        res.header('Access-Control-Allow-Methods').should.equal('FOO,bar');
        res.header('Access-Control-Allow-Headers').should.equal('FIZZ,buzz');
        res.header('Access-Control-Allow-Credentials').should.equal('true');
        res.header('Access-Control-Allow-Max-Age').should.equal('123');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('origin of false disables cors', function(done){
      // arrange
      var req, res, next, options;
      options = {
        origin: false,
        methods: ['FOO', 'bar'],
        headers: ['FIZZ', 'buzz'],
        credentials: true,
        maxAge: 123
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        should.not.exist(res.header('Access-Control-Allow-Origin'));
        should.not.exist(res.header('Access-Control-Allow-Methods'));
        should.not.exist(res.header('Access-Control-Allow-Headers'));
        should.not.exist(res.header('Access-Control-Allow-Credentials'));
        should.not.exist(res.header('Access-Control-Allow-Max-Age'));
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('can override origin', function(done){
      // arrange
      var req, res, next, options;
      options = {
        origin: 'example.com'
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        res.header('Access-Control-Allow-Origin').should.equal('example.com');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('origin defaults to *', function(done){
      // arrange
      var req, res, next, options;
      options = {
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        res.header('Access-Control-Allow-Origin').should.equal('*');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('specifying true for origin reflects requesting origin', function(done){
      // arrange
      var req, res, next, options;
      options = {
        origin: true
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        res.header('Access-Control-Allow-Origin').should.equal('request.com');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('can override methods', function(done){
      // arrange
      var req, res, next, options;
      options = {
        methods: ['method1', 'method2']
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        res.header('Access-Control-Allow-Methods').should.equal('method1,method2');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('methods defaults to GET, PUT, POST, DELETE', function(done){
      // arrange
      var req, res, next, options;
      options = {
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        res.header('Access-Control-Allow-Methods').should.equal('GET,PUT,POST,DELETE');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('can specify headers', function(done){
      // arrange
      var req, res, next, options;
      options = {
        headers: ['header1', 'header2']
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        res.header('Access-Control-Allow-Headers').should.equal('header1,header2');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('specifying an empty list or string of headers will result in no response header for headers', function(done){
      // arrange
      var req, res, next, options;
      options = {
        headers: []
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        should.not.exist(res.header('Access-Control-Allow-Headers'));
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('if no headers are specified, defaults to requested headers', function(done){
      // arrange
      var req, res, next, options;
      options = {
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        res.header('Access-Control-Allow-Headers').should.equal('requestedHeader1,requestedHeader2');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('includes credentials if explicitly enabled', function(done){
      // arrange
      var req, res, next, options;
      options = {
        credentials: true
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        res.header('Access-Control-Allow-Credentials').should.equal('true');
        //should.not.exist(res.header('Access-Control-Allow-Credentials'));
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('does not includes credentials unless explicitly enabled', function(done){
      // arrange
      var req, res, next, options;
      options = {
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        should.not.exist(res.header('Access-Control-Allow-Credentials'));
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('includes maxAge when specified', function(done){
      // arrange
      var req, res, next, options;
      options = {
        maxAge: 456
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        res.header('Access-Control-Allow-Max-Age').should.equal('456');
        done();
      };

      // act
      cors(options)(req, res, next);
    });

    it('does not includes maxAge unless specified', function(done){
      // arrange
      var req, res, next, options;
      options = {
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        should.not.exist(res.header('Access-Control-Allow-Max-Age'));
        done();
      };

      // act
      cors(options)(req, res, next);
    });
  });

  describe('passing a function to build options', function(){
    it('handles options specified via callback', function(done){
      // arrange
      var req, res, next, delegate;
      delegate = function(req, cb){
        cb(null, {
          origin: 'delegate.com'
        });
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(){
        // assert
        res.header('Access-Control-Allow-Origin').should.equal('delegate.com');
        done();
      };

      // act
      cors(delegate)(req, res, next);
    });

    it('handles error specified via callback', function(done){
      // arrange
      var req, res, next, delegate;
      delegate = function(req, cb){
        cb('some error');
      };
      req = fakeRequest();
      res = fakeResponse();
      next = function(err){
        // assert
        err.should.equal('some error');
        done();
      };

      // act
      cors(delegate)(req, res, next);
    });
  });
});
<|endoftext|>


<commit_before>//
//   Copyright 2009-2015 Ilkka Oksanen <iao@iki.fi>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing,
//   software distributed under the License is distributed on an "AS
//   IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
//   express or implied.  See the License for the specific language
//   governing permissions and limitations under the License.
//

'use strict';

/* globals moment, $ */

import Ember from 'ember';

export default Ember.TextArea.extend({
    pendingSubmit: false,

    keyPress(e) {
        if (e.keyCode == 13 && e.shiftKey === false) {
            this.pendingSubmit = true;
        }
    },

    input() {
        this._updateHeight();

        if (this.pendingSubmit) {
            this.sendAction('sendMessage', this.get('value'));
            this.set('value', '');
            this.$().height('100%');

            this.pendingSubmit = false;
        }
    },

    _updateHeight(height) {
        let contentHeight = this.$().prop('scrollHeight');
        let newHeight = Math.min(contentHeight, 300);

        if (newHeight < 35) {
            newHeight = '100%';
        }

        this.$().height(newHeight);
        console.log(newHeight);
    }
});
<commit_msg>Improve message-input component<commit_after>//
//   Copyright 2009-2015 Ilkka Oksanen <iao@iki.fi>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing,
//   software distributed under the License is distributed on an "AS
//   IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
//   express or implied.  See the License for the specific language
//   governing permissions and limitations under the License.
//

'use strict';

import Ember from 'ember';

export default Ember.TextArea.extend({
    pendingSubmit: false,

    keyPress(e) {
        if (e.keyCode === 13 && !e.shiftKey) {
            this.pendingSubmit = true;
        }
    },

    input() {
        this._updateHeight();

        if (this.pendingSubmit) {
            this.sendAction('sendMessage', this.get('value'));
            this.set('value', '');
            this.$().height('100%');

            this.pendingSubmit = false;
        }
    },

    _updateHeight(height) {
        let contentHeight = this.$().prop('scrollHeight');
        let newHeight = Math.min(contentHeight, 300);

        if (newHeight < 35) {
            newHeight = '100%';
        }

        this.$().height(newHeight);
    }
});
<|endoftext|>


<commit_before>/**
 * Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {ConfiguredRuntime} from '../src/runtime/runtime';
import {
  Entitlements,
  Entitlement,
} from '../src/api/entitlements';
import {Fetcher} from '../src/runtime/fetcher';
import {SubscribeResponse} from '../src/api/subscribe-response';
import {ClientEventManagerApi,ClientEvent,FilterResult}
    from '../src/api/client-event-manager-api';
import {AnalyticsEvent,EventOriginator} from '../src/proto/api_messages';

export {
  ConfiguredRuntime,
  Entitlements,
  Entitlement,
  Fetcher,
  SubscribeResponse,
  ClientEventManagerApi,
  ClientEvent,
  FilterResult,
  AnalyticsEvent,
  EventOriginator,
};
<commit_msg>export deferred account creation classes to help with testing in amp version of feature (#1054)<commit_after>/**
 * Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {AnalyticsEvent, EventOriginator} from '../src/proto/api_messages';
import {
  ClientEvent,
  ClientEventManagerApi,
  FilterResult,
} from '../src/api/client-event-manager-api';
import {ConfiguredRuntime} from '../src/runtime/runtime';
import {
  DeferredAccountCreationResponse,
  PurchaseData,
  UserData,
} from '../src/proto/deferred-account-creation';
import {Entitlement, Entitlements} from '../src/api/entitlements';
import {Fetcher} from '../src/runtime/fetcher';
import {SubscribeResponse} from '../src/api/subscribe-response';

export {
  ConfiguredRuntime,
  Entitlements,
  Entitlement,
  Fetcher,
  SubscribeResponse,
  ClientEventManagerApi,
  ClientEvent,
  FilterResult,
  AnalyticsEvent,
  EventOriginator,
  DeferredAccountCreationResponse,
  PurchaseData,
  UserData,
};
<|endoftext|>


<commit_before>var canvasBuffer = require('electron-canvas-to-buffer')
var fs = require('fs')

jQuery(function($) {
    'use strict';

    var BOOTH = {
        curStream: null,
        snap: 0,
        videoSources: [],

        init: function() {
            BOOTH.bind();
            BOOTH.getVideoSources();
            BOOTH.getCamera();

        },

        bind: function() {
            $('.modal-trigger').leanModal();
            $('#moreBtn').on('click', BOOTH.onMore);
            $('#snapBtn').on('click', BOOTH.onSnaps);
            $('select').on('change', BOOTH.streamChange);
            BOOTH.canvas = [
                document.getElementById("snapShot1").getContext("2d"),
                document.getElementById("snapShot2").getContext("2d"),
                document.getElementById("snapShot3").getContext("2d"),
                document.getElementById("snapShot4").getContext("2d")
            ];
            BOOTH.canvasId = [
                document.getElementById("snapShot1"),
                document.getElementById("snapShot2"),
                document.getElementById("snapShot3"),
                document.getElementById("snapShot4")
            ];

            BOOTH.video = document.getElementById("feed");

        },
        onMore: function(e) {
            e.preventDefault();
            $('.step1').css('height', '100vh');
            $('.step2').css('height', 0);
        },
        onSnaps: function(e) {
            e.preventDefault();
            BOOTH.snap = 0;
            BOOTH.theNextPicture();
        },
        theNextPicture: function() {
            if (BOOTH.snap < 4) {
                COUNTDOWN.addTimer();
                setTimeout(function() {
                    BOOTH.snap++;
                    BOOTH.theNextPicture();
                }, 6000);
            } else if (BOOTH.snap == 4) {
                $('.step1').css('height', 0);
                $('.step2').css('height', '100vh');

                BOOTH.canvasId.forEach(function(canva) {
                    var buffer = canvasBuffer(canva, 'image/png')
                    var d = new Date();
                    var n = d.getTime();
                    // write canvas to file
                    fs.writeFile('./party/' + n + '.png', buffer, function(err) {
                        throw err;
                    })
                })
            }
        },
        takePicture: function() {

            BOOTH.canvas[BOOTH.snap].drawImage(BOOTH.video, 0, 0, 1280, 720, 0, 0, 1280, 720);
            BOOTH.canvas[BOOTH.snap].globalCompositeOperation = "source-over";
            BOOTH.canvas[BOOTH.snap].drawImage(document.getElementById('moji' + BOOTH.snap), 0, 0, 1280, 720, 0, 0, 1280, 720);

        },

        streamChange: function() {
            BOOTH.curStream = $('#camSelect').value;
            BOOTH.getCamera();
        },

        getCamera: function() {
            navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;

            // constraints allow us to select a specific video source
            var constraints = {
                video: {
                    mandatory: {
                        minWidth: 1280,
                        minHeight: 720
                    },
                    optional: [{
                        sourceId: $('#camSelect').value
                    }]
                },
                audio: false
            }

            navigator.getUserMedia(constraints, function(stream) {
                var videoElm = document.querySelector('video');
                videoElm.src = URL.createObjectURL(stream);

                //                stream.onended = function() {};

                videoElm.onplay = function() {
                    if (BOOTH.curStream !== null) BOOTH.curStream.stop;
                    BOOTH.curStream = stream;
                };

            }, function(e) {
                console.error(e);
            });
        },

        getVideoSources: function(callback) {
            var ddl = $('#camSelect');

            callback = callback || function() {};

            if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
                console.log("enumerateDevices() not supported.");
                return;
            }

            navigator.mediaDevices.enumerateDevices()
                .then(function(devices) {
                    devices.forEach(function(device) {
                        // console.log(device.kind + ": " + device.label +	" id = " + device.deviceId);
                        if (device.kind === 'videoinput') {
                            // we only need to enlist video sources
                            BOOTH.videoSources.push({
                                id: device.deviceId,
                                label: device.label || 'Camera ' + (BOOTH.videoSources.length + 1)
                            });
                            $('<option>').val(device.deviceId).text(device.label).appendTo(ddl);
                            BOOTH.curStream = BOOTH.videoSources[0].id;
                        }
                    });
                })
                .catch(function(err) {
                    console.log(err.name + ": " + err.message);
                });
        }
    };

    var COUNTDOWN = {
        timerTxt: "

4

",

        init: function() {
            COUNTDOWN.bind();
            //            COUNTDOWN.addTimer();
        },

        bind: function() {
            COUNTDOWN.$timer = $('.timer');
        },

        addTimer: function() {

            COUNTDOWN.$timer.html(COUNTDOWN.timerTxt);
            COUNTDOWN.timeVal = 4;
            COUNTDOWN.$interval = setInterval(COUNTDOWN.tick, 1000);
        },

        tick: function() {
            if (COUNTDOWN.timeVal >= 0) {
                $('.count').html(COUNTDOWN.timeVal);
            }
            if (COUNTDOWN.timeVal === 0) {
                clearInterval(COUNTDOWN.$interval);
                BOOTH.takePicture();
                COUNTDOWN.$timer.html('');
            }
            COUNTDOWN.timeVal--;
        }
    };

    COUNTDOWN.init();
    BOOTH.init();
}($));
<commit_msg>fixed multiple cameras<commit_after>var canvasBuffer = require('electron-canvas-to-buffer')
var fs = require('fs')

jQuery(function($) {
    'use strict';

    var BOOTH = {
        curStream: null,
        snap: 0,
        videoSources: [],

        init: function() {
            BOOTH.bind();
            BOOTH.getVideoSources();
            BOOTH.getCamera();

        },

        bind: function() {
            $('.modal-trigger').leanModal();
            $('#moreBtn').on('click', BOOTH.onMore);
            $('#snapBtn').on('click', BOOTH.onSnaps);
            $('select').on('change', BOOTH.streamChange);
            BOOTH.canvas = [
                document.getElementById("snapShot1").getContext("2d"),
                document.getElementById("snapShot2").getContext("2d"),
                document.getElementById("snapShot3").getContext("2d"),
                document.getElementById("snapShot4").getContext("2d")
            ];
            BOOTH.canvasId = [
                document.getElementById("snapShot1"),
                document.getElementById("snapShot2"),
                document.getElementById("snapShot3"),
                document.getElementById("snapShot4")
            ];

            BOOTH.video = document.getElementById("feed");

        },
        onMore: function(e) {
            e.preventDefault();
            $('.step1').css('height', '100vh');
            $('.step2').css('height', 0);
        },
        onSnaps: function(e) {
            e.preventDefault();
            BOOTH.snap = 0;
            BOOTH.theNextPicture();
        },
        theNextPicture: function() {
            if (BOOTH.snap < 4) {
                COUNTDOWN.addTimer();
                setTimeout(function() {
                    BOOTH.snap++;
                    BOOTH.theNextPicture();
                }, 6000);
            } else if (BOOTH.snap == 4) {
                $('.step1').css('height', 0);
                $('.step2').css('height', '100vh');

                BOOTH.canvasId.forEach(function(canva) {
                    var buffer = canvasBuffer(canva, 'image/png')
                    var d = new Date();
                    var n = d.getTime();
                    // write canvas to file
                    fs.writeFile('./party/' + n + '.png', buffer, function(err) {
                        throw err;
                    })
                })
            }
        },
        takePicture: function() {

            BOOTH.canvas[BOOTH.snap].drawImage(BOOTH.video, 0, 0, 1280, 720, 0, 0, 1280, 720);
            BOOTH.canvas[BOOTH.snap].globalCompositeOperation = "source-over";
            BOOTH.canvas[BOOTH.snap].drawImage(document.getElementById('moji' + BOOTH.snap), 0, 0, 1280, 720, 0, 0, 1280, 720);

        },

        streamChange: function() {
            // BOOTH.curStream = $('#camSelect').value;
            BOOTH.getCamera();
        },

        getCamera: function() {
            navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;

            // constraints allow us to select a specific video source
            var constraints = {
                video: {
                    mandatory: {
                        minWidth: 1280,
                        minHeight: 720
                    },
                    optional: [{
                        sourceId: $('#camSelect')[0].value
                    }]
                },
                audio: false
            }

            navigator.getUserMedia(constraints, function(stream) {
                var videoElm = document.querySelector('video');
                videoElm.src = URL.createObjectURL(stream);

                //                stream.onended = function() {};

                videoElm.onplay = function() {
                    // if (BOOTH.curStream !== null) BOOTH.curStream.getTracks()[0].stop();
                    BOOTH.curStream = stream;
                };

            }, function(e) {
                console.error(e);
            });
        },

        getVideoSources: function(callback) {
            var ddl = $('#camSelect');

            callback = callback || function() {};

            if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
                console.log("enumerateDevices() not supported.");
                return;
            }

            navigator.mediaDevices.enumerateDevices()
                .then(function(devices) {
                    devices.forEach(function(device) {
                        // console.log(device.kind + ": " + device.label +	" id = " + device.deviceId);
                        if (device.kind === 'videoinput') {
                            // we only need to enlist video sources
                            BOOTH.videoSources.push({
                                id: device.deviceId,
                                label: device.label || 'Camera ' + (BOOTH.videoSources.length + 1)
                            });
                            $('<option>').val(device.deviceId).text(device.label).appendTo(ddl);
                            // BOOTH.curStream = BOOTH.videoSources[0].id;
                        }
                    });
                })
                .catch(function(err) {
                    console.log(err.name + ": " + err.message);
                });
        }
    };

    var COUNTDOWN = {
        timerTxt: "

4

",

        init: function() {
            COUNTDOWN.bind();
            //            COUNTDOWN.addTimer();
        },

        bind: function() {
            COUNTDOWN.$timer = $('.timer');
        },

        addTimer: function() {

            COUNTDOWN.$timer.html(COUNTDOWN.timerTxt);
            COUNTDOWN.timeVal = 4;
            COUNTDOWN.$interval = setInterval(COUNTDOWN.tick, 1000);
        },

        tick: function() {
            if (COUNTDOWN.timeVal >= 0) {
                $('.count').html(COUNTDOWN.timeVal);
            }
            if (COUNTDOWN.timeVal === 0) {
                clearInterval(COUNTDOWN.$interval);
                BOOTH.takePicture();
                COUNTDOWN.$timer.html('');
            }
            COUNTDOWN.timeVal--;
        }
    };

    COUNTDOWN.init();
    BOOTH.init();
}($));
<|endoftext|>


<commit_before>(function(window) {

  /** Use a single load function */
  var load = typeof require == 'function' ? require : window.load;

  /** Load Benchmark.js */
  var Benchmark =
    window.Benchmark || (
      Benchmark = load('../vendor/benchmark.js/benchmark.js') || window.Benchmark,
      Benchmark.Benchmark || Benchmark
    );

  /** Load Lo-Dash */
  var lodash =
    window.lodash || (
      lodash = load('../lodash.js') || window._,
      lodash = lodash._ || lodash,
      lodash.noConflict()
    );

  /** Load Underscore */
  var _ =
    window._ || (
      _ = load('../vendor/underscore/underscore.js') || window._,
      _._ || _
    );

  /** Used to access the Firebug Lite panel */
  var fbPanel = (fbPanel = window.document && document.getElementById('FirebugUI')) &&
    (fbPanel = (fbPanel = fbPanel.contentWindow || fbPanel.contentDocument).document || fbPanel) &&
    fbPanel.getElementById('fbPanel1');

  /** Used to score Lo-Dash and Underscore performance */
  var score = { 'lodash': 0, 'underscore': 0 };

  /** Used to queue benchmark suites */
  var suites = [];

  /** Add `console.log()` support for Narwhal and RingoJS */
  window.console || (window.console = { 'log': window.print });

  /** Expose functions to the global object */
  window._ = _;
  window.Benchmark = Benchmark;
  window.lodash = lodash;

  /*--------------------------------------------------------------------------*/

  /**
   * Logs text to the console.
   *
   * @private
   * @param {String} text The text to log.
   */
  function log(text) {
    console.log(text);
    if (fbPanel) {
      // scroll down the Firebug Lite panel
      fbPanel.scrollTop = fbPanel.scrollHeight;
    }
  }

  /*--------------------------------------------------------------------------*/

  lodash.extend(Benchmark.options, {
    'async': true,
    'setup': function() {
      var window = Function('return this || global')(),
          _ = window._,
          lodash = window.lodash;

      var numbers = [],
          object = {},
          fourNumbers = [5, 25, 10, 30],
          nestedNumbers = [1, [2], [3, [[4]]]],
          twoNumbers = [12, 21],
          words = [
            'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
            'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
            'seventeen', 'eighteen', 'nineteen', 'twenty'
          ];

      var ctor = function() { },
          func = function(greeting) { return greeting + ': ' + this.name; };

      var lodashBoundNormal = lodash.bind(func, { 'name': 'moe' }),
          lodashBoundCtor = lodash.bind(ctor, { 'name': 'moe' }),
          lodashBoundPartial = lodash.bind(func, { 'name': 'moe' }, 'hi');

      var _boundNormal = _.bind(func, { 'name': 'moe' }),
          _boundCtor = _.bind(ctor, { 'name': 'moe' }),
          _boundPartial = _.bind(func, { 'name': 'moe' }, 'hi');

      for (var index = 0; index < 20; index++) {
        numbers[index] = index;
        object['key' + index] = index;
      }

      var objects = lodash.map(numbers, function(n) {
        return { 'num': n };
      });
    }
  });

  lodash.extend(Benchmark.Suite.options, {
    'onStart': function() {
      log('\n' + this.name + ':');
    },
    'onCycle': function(event) {
      log(event.target + '');
    },
    'onComplete': function() {
      var formatNumber = Benchmark.formatNumber,
          fastest = this.filter('fastest'),
          slowest = this.filter('slowest'),
          lodashHz = 1 / (this[0].stats.mean + this[0].stats.moe),
          underscoreHz = 1 / (this[1].stats.mean + this[1].stats.moe);

      if (fastest.length > 1) {
        log('It\'s too close to call.');
        lodashHz = underscoreHz = Math.min(lodashHz, underscoreHz);
      }
      else {
        var fastestHz = fastest[0] == this[0] ? lodashHz : underscoreHz,
            slowestHz = slowest[0] == this[0] ? lodashHz : underscoreHz,
            percent = formatNumber(Math.round(((fastestHz / slowestHz) - 1) * 100));

        log(fastest[0].name + ' is ' + percent + '% faster.');
      }
      // add score adjusted for margin of error
      score.lodash += lodashHz;
      score.underscore += underscoreHz;

      // remove current suite from queue
      suites.shift();

      if (suites.length) {
        // run next suite
        suites[0].run();
      }
      else {
        var fastestTotalHz = Math.max(score.lodash, score.underscore),
            slowestTotalHz = Math.min(score.lodash, score.underscore),
            totalPercent = formatNumber(Math.round(((fastestTotalHz  / slowestTotalHz) - 1) * 100)),
            totalX = formatNumber((fastestTotalHz / slowestTotalHz).toFixed(2)),
            message = ' is ' + totalPercent + '% (' + totalX + 'x) faster than ';

        // report results
        if (score.lodash >= score.underscore) {
          log('\nLo-Dash' + message + 'Underscore.');
        } else {
          log('\nUnderscore' + message + 'Lo-Dash.');
        }
      }
    }
  });

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('bind call')
      .add('Lo-Dash', function() {
        lodash.bind(func, { 'name': 'moe' }, 'hi');
      })
      .add('Underscore', function() {
        _.bind(func, { 'name': 'moe' }, 'hi');
      })
  );

  suites.push(
    Benchmark.Suite('bound normal')
      .add('Lo-Dash', function() {
        lodashBoundNormal();
      })
      .add('Underscore', function() {
        _boundNormal();
      })
  );

  suites.push(
    Benchmark.Suite('bound partial')
      .add('Lo-Dash', function() {
        lodashBoundPartial();
      })
      .add('Underscore', function() {
        _boundPartial();
      })
  );

  suites.push(
    Benchmark.Suite('bound constructor')
      .add('Lo-Dash', function() {
        new lodashBoundCtor();
      })
      .add('Underscore', function() {
        new _boundCtor();
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('each array')
      .add('Lo-Dash', function() {
        var timesTwo = [];
        lodash.each(numbers, function(num) {
          timesTwo.push(num * 2);
        });
      })
      .add('Underscore', function() {
        var timesTwo = [];
        _.each(numbers, function(num) {
          timesTwo.push(num * 2);
        });
      })
  );

  suites.push(
    Benchmark.Suite('each object')
      .add('Lo-Dash', function() {
        var timesTwo = [];
        lodash.each(object, function(num) {
          timesTwo.push(num * 2);
        });
      })
      .add('Underscore', function() {
        var timesTwo = [];
        _.each(object, function(num) {
          timesTwo.push(num * 2);
        });
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('find')
      .add('Lo-Dash', function() {
        lodash.find(numbers, function(num) {
          return num === 19;
        });
      })
      .add('Underscore', function() {
        _.find(numbers, function(num) {
          return num === 19;
        });
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('flatten deep')
      .add('Lo-Dash', function() {
        lodash.flatten(nestedNumbers);
      })
      .add('Underscore', function() {
        _.flatten(nestedNumbers);
      })
  );

  suites.push(
    Benchmark.Suite('flatten shallow')
      .add('Lo-Dash', function() {
        lodash.flatten(nestedNumbers, true);
      })
      .add('Underscore', function() {
        _.flatten(nestedNumbers, true);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('difference')
      .add('Lo-Dash', function() {
        lodash.difference(numbers, fourNumbers);
      })
      .add('Underscore', function() {
        _.difference(numbers, fourNumbers);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('groupBy callback')
      .add('Lo-Dash', function() {
        lodash.groupBy(numbers, function(num) { return Math.floor(num); });
      })
      .add('Underscore', function() {
        _.groupBy(numbers, function(num) { return Math.floor(num); });
      })
  );

  suites.push(
    Benchmark.Suite('groupBy property name')
      .add('Lo-Dash', function() {
        lodash.groupBy(words, 'length');
      })
      .add('Underscore', function() {
        _.groupBy(words, 'length');
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('intersection')
      .add('Lo-Dash', function() {
        lodash.intersection(numbers, fourNumbers, twoNumbers);
      })
      .add('Underscore', function() {
        _.intersection(numbers, fourNumbers, twoNumbers);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('keys')
      .add('Lo-Dash', function() {
        lodash.keys(object);
      })
      .add('Underscore', function() {
        _.keys(object);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('map')
      .add('Lo-Dash', function() {
        lodash.map(objects, function(obj) {
          return obj.num;
        });
      })
      .add('Underscore', function() {
        _.map(objects, function(obj) {
          return obj.num;
        });
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('max')
      .add('Lo-Dash', function() {
        lodash.max(numbers);
      })
      .add('Underscore', function() {
        _.max(numbers);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('min')
      .add('Lo-Dash', function() {
        lodash.min(numbers);
      })
      .add('Underscore', function() {
        _.min(numbers);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('pick')
      .add('Lo-Dash', function() {
        lodash.pick(object, 'key6', 'key13');
      })
      .add('Underscore', function() {
        _.pick(object, 'key6', 'key13');
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('pluck')
      .add('Lo-Dash', function() {
        lodash.pluck(objects, 'num');
      })
      .add('Underscore', function() {
        _.pluck(objects, 'num');
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('union')
      .add('Lo-Dash', function() {
        lodash.union(numbers, fourNumbers, twoNumbers);
      })
      .add('Underscore', function() {
        _.union(numbers, fourNumbers, twoNumbers);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('values')
      .add('Lo-Dash', function() {
        lodash.values(objects);
      })
      .add('Underscore', function() {
        _.values(objects);
      })
  );

  /*--------------------------------------------------------------------------*/

  if (Benchmark.platform + '') {
    log(Benchmark.platform + '');
  }
  // start suites
  suites[0].run();

}(typeof global == 'object' && global || this));
<commit_msg>Add more benchmarks.<commit_after>(function(window) {

  /** Use a single load function */
  var load = typeof require == 'function' ? require : window.load;

  /** Load Benchmark.js */
  var Benchmark =
    window.Benchmark || (
      Benchmark = load('../vendor/benchmark.js/benchmark.js') || window.Benchmark,
      Benchmark.Benchmark || Benchmark
    );

  /** Load Lo-Dash */
  var lodash =
    window.lodash || (
      lodash = load('../lodash.js') || window._,
      lodash = lodash._ || lodash,
      lodash.noConflict()
    );

  /** Load Underscore */
  var _ =
    window._ || (
      _ = load('../vendor/underscore/underscore.js') || window._,
      _._ || _
    );

  /** Used to access the Firebug Lite panel */
  var fbPanel = (fbPanel = window.document && document.getElementById('FirebugUI')) &&
    (fbPanel = (fbPanel = fbPanel.contentWindow || fbPanel.contentDocument).document || fbPanel) &&
    fbPanel.getElementById('fbPanel1');

  /** Used to score Lo-Dash and Underscore performance */
  var score = { 'lodash': 0, 'underscore': 0 };

  /** Used to queue benchmark suites */
  var suites = [];

  /** Add `console.log()` support for Narwhal and RingoJS */
  window.console || (window.console = { 'log': window.print });

  /** Expose functions to the global object */
  window._ = _;
  window.Benchmark = Benchmark;
  window.lodash = lodash;

  /*--------------------------------------------------------------------------*/

  /**
   * Logs text to the console.
   *
   * @private
   * @param {String} text The text to log.
   */
  function log(text) {
    console.log(text);
    if (fbPanel) {
      // scroll down the Firebug Lite panel
      fbPanel.scrollTop = fbPanel.scrollHeight;
    }
  }

  /*--------------------------------------------------------------------------*/

  lodash.extend(Benchmark.options, {
    'async': true,
    'setup': function() {
      var window = Function('return this || global')(),
          _ = window._,
          lodash = window.lodash;

      var length = 20,
          numbers = [],
          object = {},
          fourNumbers = [5, 25, 10, 30],
          nestedNumbers = [1, [2], [3, [[4]]]],
          twoNumbers = [12, 21],
          words = [
            'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
            'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
            'seventeen', 'eighteen', 'nineteen', 'twenty'
          ];

      var ctor = function() { },
          func = function(greeting) { return greeting + ': ' + this.name; };

      var lodashBoundNormal = lodash.bind(func, { 'name': 'moe' }),
          lodashBoundCtor = lodash.bind(ctor, { 'name': 'moe' }),
          lodashBoundPartial = lodash.bind(func, { 'name': 'moe' }, 'hi');

      var _boundNormal = _.bind(func, { 'name': 'moe' }),
          _boundCtor = _.bind(ctor, { 'name': 'moe' }),
          _boundPartial = _.bind(func, { 'name': 'moe' }, 'hi');

      for (var index = 0; index < length; index++) {
        numbers[index] = index;
        object['key' + index] = index;
      }

      var objects = lodash.map(numbers, function(num) {
        return { 'num': num };
      });
    }
  });

  lodash.extend(Benchmark.Suite.options, {
    'onStart': function() {
      log('\n' + this.name + ':');
    },
    'onCycle': function(event) {
      log(event.target + '');
    },
    'onComplete': function() {
      var formatNumber = Benchmark.formatNumber,
          fastest = this.filter('fastest'),
          slowest = this.filter('slowest'),
          lodashHz = 1 / (this[0].stats.mean + this[0].stats.moe),
          underscoreHz = 1 / (this[1].stats.mean + this[1].stats.moe);

      if (fastest.length > 1) {
        log('It\'s too close to call.');
        lodashHz = underscoreHz = Math.min(lodashHz, underscoreHz);
      }
      else {
        var fastestHz = fastest[0] == this[0] ? lodashHz : underscoreHz,
            slowestHz = slowest[0] == this[0] ? lodashHz : underscoreHz,
            percent = formatNumber(Math.round(((fastestHz / slowestHz) - 1) * 100));

        log(fastest[0].name + ' is ' + percent + '% faster.');
      }
      // add score adjusted for margin of error
      score.lodash += lodashHz;
      score.underscore += underscoreHz;

      // remove current suite from queue
      suites.shift();

      if (suites.length) {
        // run next suite
        suites[0].run();
      }
      else {
        var fastestTotalHz = Math.max(score.lodash, score.underscore),
            slowestTotalHz = Math.min(score.lodash, score.underscore),
            totalPercent = formatNumber(Math.round(((fastestTotalHz  / slowestTotalHz) - 1) * 100)),
            totalX = formatNumber((fastestTotalHz / slowestTotalHz).toFixed(2)),
            message = ' is ' + totalPercent + '% (' + totalX + 'x) faster than ';

        // report results
        if (score.lodash >= score.underscore) {
          log('\nLo-Dash' + message + 'Underscore.');
        } else {
          log('\nUnderscore' + message + 'Lo-Dash.');
        }
      }
    }
  });

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('bind call')
      .add('Lo-Dash', function() {
        lodash.bind(func, { 'name': 'moe' }, 'hi');
      })
      .add('Underscore', function() {
        _.bind(func, { 'name': 'moe' }, 'hi');
      })
  );

  suites.push(
    Benchmark.Suite('bound')
      .add('Lo-Dash', function() {
        lodashBoundNormal();
      })
      .add('Underscore', function() {
        _boundNormal();
      })
  );

  suites.push(
    Benchmark.Suite('bound partial')
      .add('Lo-Dash', function() {
        lodashBoundPartial();
      })
      .add('Underscore', function() {
        _boundPartial();
      })
  );

  suites.push(
    Benchmark.Suite('bound constructor')
      .add('Lo-Dash', function() {
        new lodashBoundCtor();
      })
      .add('Underscore', function() {
        new _boundCtor();
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('each array')
      .add('Lo-Dash', function() {
        var result = [];
        lodash.each(numbers, function(num) { result.push(num * 2); });
      })
      .add('Underscore', function() {
        var result = [];
        _.each(numbers, function(num) { result.push(num * 2); });
      })
  );

  suites.push(
    Benchmark.Suite('each array thisArg')
      .add('Lo-Dash', function() {
        var result = [];
        lodash.each(numbers, function(num, index) {
          result.push(num + this['key' + index]);
        }, object);
      })
      .add('Underscore', function() {
        var result = [];
        _.each(numbers, function(num, index) {
          result.push(num + this['key' + index]);
        }, object);
      })
  );

  suites.push(
    Benchmark.Suite('each object')
      .add('Lo-Dash', function() {
        var result = [];
        lodash.each(object, function(num) {
          result.push(num * 2);
        });
      })
      .add('Underscore', function() {
        var result = [];
        _.each(object, function(num) {
          result.push(num * 2);
        });
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('find')
      .add('Lo-Dash', function() {
        lodash.find(numbers, function(num) {
          return num === 19;
        });
      })
      .add('Underscore', function() {
        _.find(numbers, function(num) {
          return num === 19;
        });
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('flatten deep')
      .add('Lo-Dash', function() {
        lodash.flatten(nestedNumbers);
      })
      .add('Underscore', function() {
        _.flatten(nestedNumbers);
      })
  );

  suites.push(
    Benchmark.Suite('flatten shallow')
      .add('Lo-Dash', function() {
        lodash.flatten(nestedNumbers, true);
      })
      .add('Underscore', function() {
        _.flatten(nestedNumbers, true);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('difference')
      .add('Lo-Dash', function() {
        lodash.difference(numbers, fourNumbers);
      })
      .add('Underscore', function() {
        _.difference(numbers, fourNumbers);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('groupBy callback')
      .add('Lo-Dash', function() {
        lodash.groupBy(numbers, function(num) { return num >> 1; });
      })
      .add('Underscore', function() {
        _.groupBy(numbers, function(num) { return num >> 1; });
      })
  );

  suites.push(
    Benchmark.Suite('groupBy property name')
      .add('Lo-Dash', function() {
        lodash.groupBy(words, 'length');
      })
      .add('Underscore', function() {
        _.groupBy(words, 'length');
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('indexOf')
      .add('Lo-Dash', function() {
        lodash.indexOf(numbers, 9);
      })
      .add('Underscore', function() {
        _.indexOf(numbers, 9);
      })
  );

  suites.push(
    Benchmark.Suite('indexOf isSorted')
      .add('Lo-Dash', function() {
        lodash.indexOf(numbers, 9, true);
      })
      .add('Underscore', function() {
        _.indexOf(numbers, 9, true);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('intersection')
      .add('Lo-Dash', function() {
        lodash.intersection(numbers, fourNumbers, twoNumbers);
      })
      .add('Underscore', function() {
        _.intersection(numbers, fourNumbers, twoNumbers);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('keys')
      .add('Lo-Dash', function() {
        lodash.keys(object);
      })
      .add('Underscore', function() {
        _.keys(object);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('lastIndexOf')
      .add('Lo-Dash', function() {
        lodash.lastIndexOf(numbers, 9);
      })
      .add('Underscore', function() {
        _.lastIndexOf(numbers, 9);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('map')
      .add('Lo-Dash', function() {
        lodash.map(objects, function(value) {
          return value.num;
        });
      })
      .add('Underscore', function() {
        _.map(objects, function(value) {
          return value.num;
        });
      })
  );

  suites.push(
    Benchmark.Suite('map thisArg')
      .add('Lo-Dash', function() {
        lodash.map(objects, function(value, index) {
          return this['key' + index] + value.num;
        }, object);
      })
      .add('Underscore', function() {
        _.map(objects, function(value, index) {
          return this['key' + index] + value.num;
        }, object);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('max')
      .add('Lo-Dash', function() {
        lodash.max(numbers);
      })
      .add('Underscore', function() {
        _.max(numbers);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('min')
      .add('Lo-Dash', function() {
        lodash.min(numbers);
      })
      .add('Underscore', function() {
        _.min(numbers);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('pick')
      .add('Lo-Dash', function() {
        lodash.pick(object, 'key6', 'key13');
      })
      .add('Underscore', function() {
        _.pick(object, 'key6', 'key13');
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('pluck')
      .add('Lo-Dash', function() {
        lodash.pluck(objects, 'num');
      })
      .add('Underscore', function() {
        _.pluck(objects, 'num');
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('sortBy callback')
      .add('Lo-Dash', function() {
        lodash.sortBy(numbers, function(num) { return Math.sin(num); });
      })
      .add('Underscore', function() {
        _.sortBy(numbers, function(num) { return Math.sin(num); });
      })
  );

  suites.push(
    Benchmark.Suite('sortBy callback thisArg')
      .add('Lo-Dash', function() {
        lodash.sortBy(numbers, function(num) { return this.sin(num); }, Math);
      })
      .add('Underscore', function() {
        _.sortBy(numbers, function(num) { return this.sin(num); }, Math);
      })
  );

  suites.push(
    Benchmark.Suite('sortBy property name')
      .add('Lo-Dash', function() {
        lodash.sortBy(words, 'length');
      })
      .add('Underscore', function() {
        _.sortBy(words, 'length');
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('times')
      .add('Lo-Dash', function() {
        var result = [];
        lodash.times(length, function(n) { result.push(n); });
      })
      .add('Underscore', function() {
        var result = [];
        _.times(length, function(n) { result.push(n); });
      })
  );

  suites.push(
    Benchmark.Suite('times thisArg')
      .add('Lo-Dash', function() {
        var result = [];
        lodash.times(length, function(n) { result.push(this.sin(n)); }, Math);
      })
      .add('Underscore', function() {
        var result = [];
        _.times(length, function(n) { result.push(this.sin(n)); }, Math);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('union')
      .add('Lo-Dash', function() {
        lodash.union(numbers, fourNumbers, twoNumbers);
      })
      .add('Underscore', function() {
        _.union(numbers, fourNumbers, twoNumbers);
      })
  );

  /*--------------------------------------------------------------------------*/

  suites.push(
    Benchmark.Suite('values')
      .add('Lo-Dash', function() {
        lodash.values(objects);
      })
      .add('Underscore', function() {
        _.values(objects);
      })
  );

  /*--------------------------------------------------------------------------*/

  if (Benchmark.platform + '') {
    log(Benchmark.platform + '');
  }
  // start suites
  suites[0].run();

}(typeof global == 'object' && global || this));
<|endoftext|>


<commit_before>function initMap() {
	//Die Karte wird in der index-html in das Div mit der id "mymap" gezeichnet
	map = new L.Map("map");

	var min = 11; //minimale Zoomstufe
	var max = 16; //maximale Zoomstufe

        var baseurl = '/bbs/static/'
        var myTiles = "http://tiles.jochenklar.de/mamanoke-bezirke/{z}/{x}/{y}.png";
	//myTiles = "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"; //hier wird angegeben von wo die Tiles für die Karte geladen werden sollen
	osmCopyright = "Map data © 2012 OpenStreetMap contributors"; //Copyrigth, das unten rechts erscheint
	myLayer = new L.TileLayer(myTiles, { minZoom:min, maxZoom: max, attribution: osmCopyright, zIndex:0, reuseTiles:true } ); //Nun wird mit diesen tiles eine ebene erstellt (hier gibt es nur eine Ebene, es sind aber auch mehrere Ebenen möglich)
	map.addLayer( myLayer ); //Füge die Ebene der Karte hinzu

    //52.484766470498954, 13.363323211669922
	var center = new L.LatLng(52.51, 13.37628); //Fokus der Karte
	map.setView(center, min);

	var fernsehturm = L.icon({
        iconUrl: baseurl + '/img/Fernsehturm_grau_26px3.png',
        iconSize:     [27, 125], // size of the icon
        iconAnchor:   [8,111] // point of the icon which will correspond to marker's location
	});

	var fernsehturmMarker = L.marker([52.520841,13.409405],{icon: fernsehturm}).addTo(map);

	var funkturm = L.icon({
        iconUrl: baseurl + '/img/Funkturm_36px_neu.png',
        iconSize:     [36, 110], // size of the icon
        iconAnchor:   [16,108] // point of the icon which will correspond to marker's location
	});
	var funkturmMarker = L.marker([52.5050681,13.278211400000032],{icon: funkturm}).addTo(map);

	var greenIcon = L.icon({
        iconUrl: baseurl + '/img/marker_green.png',
        iconSize:     [21, 32], // size of the icon width,height
        iconAnchor:   [14, 45], // point of the icon which will correspond to marker's location
        popupAnchor:  [4, -20] // point from which the popup should open relative to the iconAnchor
	});

    var redIcon = L.icon({
        iconUrl: baseurl + '/img/marker_red.png',
        iconSize:     [21, 32], // size of the icon width,height
        iconAnchor:   [14, 45], // point of the icon which will correspond to marker's location
        popupAnchor:  [4, -20] // point from which the popup should open relative to the iconAnchor
	});

	var html = '
';
    $.each(bbps, function(key,bbp){
        var lon = bbp.fields.lon;
        var lat = bbp.fields.lat;
        var t = bbp.fields.vorhaben;
        var link = bbp.fields.link;
        html += '
' + t + '
';
        var marker = L.marker([lat,lon],{icon: redIcon}).addTo(map);

        popuptext = "' + t + "";
        marker.bindPopup(popuptext);

    });

    $.each(projects, function(key,project){
        var lon = project.fields.lon;
        var lat = project.fields.lat;
        var t = project.fields.titel;
        html += '
' + t + '
';
        var marker = L.marker([lat,lon],{icon: greenIcon}).addTo(map);
        marker.bindPopup(t);
    });
    html += '
';
    $('#sidebar-content').append(html);

}

function moveOutSidebar(){
    $('#sidebar-button').unbind('click');
    $('#sidebar').removeClass('sidebar-shadow');
    $('#sidebar').animate(
        {left: '-=300'},
        'fast',
        function(){});
    $('#sidebar-button').animate(
        {left: '-=300'},
        'fast',
        function(){
            $('#sidebar-button').click(moveInSidebar);
            $('i', '#sidebar-button').remove();
            $('#sidebar-button').append('');
	    $('#sidebar').removeClass('sidebar-shadow');
        }
    );
}

function moveInSidebar(){
    $('#sidebar-button').unbind('click');
    $('#sidebar').addClass('sidebar-shadow');
    $('#sidebar').animate(
        {left: '+=300'},
        'fast',
        function(){});
    $('#sidebar-button').animate(
        {left: '+=300'},
        'fast',
        function(){
            $('#sidebar-button').click(moveOutSidebar);
            $('i', '#sidebar-button').remove();
            $('#sidebar-button').append('');
        }
    );
}

$(document).ready(function() {
    setTimeout('initMap()',100);
    $('#sidebar-button').click(moveInSidebar);
});<commit_msg>Neue Tiles<commit_after>function initMap() {
	//Die Karte wird in der index-html in das Div mit der id "mymap" gezeichnet
	map = new L.Map("map");

	var min = 11; //minimale Zoomstufe
	var max = 15; //maximale Zoomstufe

        var baseurl = '/bbs/static/'
        var myTiles = "http://tiles.jochenklar.de/pinkoding-bbs/{z}/{x}/{y}.png";
	osmCopyright = "Map data © 2012 OpenStreetMap contributors"; //Copyrigth, das unten rechts erscheint
	myLayer = new L.TileLayer(myTiles, { minZoom:min, maxZoom: max, attribution: osmCopyright, zIndex:0, reuseTiles:true } ); //Nun wird mit diesen tiles eine ebene erstellt (hier gibt es nur eine Ebene, es sind aber auch mehrere Ebenen möglich)
	map.addLayer( myLayer ); //Füge die Ebene der Karte hinzu

    //52.484766470498954, 13.363323211669922
	var center = new L.LatLng(52.51, 13.37628); //Fokus der Karte
	map.setView(center, min);

	var fernsehturm = L.icon({
        iconUrl: baseurl + '/img/Fernsehturm_grau_26px3.png',
        iconSize:     [27, 125], // size of the icon
        iconAnchor:   [8,111] // point of the icon which will correspond to marker's location
	});

	var fernsehturmMarker = L.marker([52.520841,13.409405],{icon: fernsehturm}).addTo(map);

	var funkturm = L.icon({
        iconUrl: baseurl + '/img/Funkturm_36px_neu.png',
        iconSize:     [36, 110], // size of the icon
        iconAnchor:   [16,108] // point of the icon which will correspond to marker's location
	});
	var funkturmMarker = L.marker([52.5050681,13.278211400000032],{icon: funkturm}).addTo(map);

	var greenIcon = L.icon({
        iconUrl: baseurl + '/img/marker_green.png',
        iconSize:     [21, 32], // size of the icon width,height
        iconAnchor:   [14, 45], // point of the icon which will correspond to marker's location
        popupAnchor:  [4, -20] // point from which the popup should open relative to the iconAnchor
	});

    var redIcon = L.icon({
        iconUrl: baseurl + '/img/marker_red.png',
        iconSize:     [21, 32], // size of the icon width,height
        iconAnchor:   [14, 45], // point of the icon which will correspond to marker's location
        popupAnchor:  [4, -20] // point from which the popup should open relative to the iconAnchor
	});

	var html = '
';
    $.each(bbps, function(key,bbp){
        var lon = bbp.fields.lon;
        var lat = bbp.fields.lat;
        var t = bbp.fields.vorhaben;
        var link = bbp.fields.link;
        html += '
' + t + '
';
        var marker = L.marker([lat,lon],{icon: redIcon}).addTo(map);

        popuptext = "' + t + "";
        marker.bindPopup(popuptext);

    });

    $.each(projects, function(key,project){
        var lon = project.fields.lon;
        var lat = project.fields.lat;
        var t = project.fields.titel;
        html += '
' + t + '
';
        var marker = L.marker([lat,lon],{icon: greenIcon}).addTo(map);
        marker.bindPopup(t);
    });
    html += '
';
    $('#sidebar-content').append(html);

}

function moveOutSidebar(){
    $('#sidebar-button').unbind('click');
    $('#sidebar').removeClass('sidebar-shadow');
    $('#sidebar').animate(
        {left: '-=300'},
        'fast',
        function(){});
    $('#sidebar-button').animate(
        {left: '-=300'},
        'fast',
        function(){
            $('#sidebar-button').click(moveInSidebar);
            $('i', '#sidebar-button').remove();
            $('#sidebar-button').append('');
	    $('#sidebar').removeClass('sidebar-shadow');
        }
    );
}

function moveInSidebar(){
    $('#sidebar-button').unbind('click');
    $('#sidebar').addClass('sidebar-shadow');
    $('#sidebar').animate(
        {left: '+=300'},
        'fast',
        function(){});
    $('#sidebar-button').animate(
        {left: '+=300'},
        'fast',
        function(){
            $('#sidebar-button').click(moveOutSidebar);
            $('i', '#sidebar-button').remove();
            $('#sidebar-button').append('');
        }
    );
}

$(document).ready(function() {
    setTimeout('initMap()',100);
    $('#sidebar-button').click(moveInSidebar);
});<|endoftext|>


<commit_before>var replayContext;

function initReplay() {
    replayContext = new RenderContext("replayCanvas");
    replayContext.setCameraPosition(0, 0, 30);
    replayCreateLights();

    replayContext.createTiles(() => arrange());
}

function arrange() {
    const tileWidth = 0.97;
    const tileHeight = 1.3;
    const gap = 0.2;
    const a = -(17 * tileWidth + tileHeight + gap) / 2;
    var tileId = 0;
    for (let i = 0; i < 4; i++) {
        //let x = -8.5 * tileWidth + 0.5 * tileWidth;
        //const y = -8.5 * tileWidth - 0.5 * tileHeight;
        let x = a + 0.5 * tileWidth + tileHeight + gap;
        const y = a + 0.5 * tileHeight;
        for (let j = 0; j < 17; j++) {
            const number = numberFromTileId(tileId);
            const suit = suitFromTileId(tileId);
            const mesh = replayContext.createTileMesh(number, suit);

            mesh.rotateZ(Math.PI * 0.5 * i);
            mesh.translateX(x);
            mesh.translateY(y);
            mesh.rotateX(Math.PI * 0.5);
            mesh.rotateY(Math.PI);

            replayContext.scene.add(mesh);
            x += tileWidth;
            tileId += 1;
        }
    }
}

function suitFromTileId(tileId) {
    return Math.floor(tileId / 34);
}

function numberFromTileId(tileId) {
    if (tileId === 4 * 4 || tileId === 16 + 9 * 4 || tileId === 16 + 9 * 4 * 2)
        return 0;
    return 1 + Math.floor((tileId % (9 * 4)) / 4);
}

function replayCreateLights() {
    const light = new THREE.AmbientLight(0x999999);
    replayContext.scene.add(light);
    const pointLight = new THREE.PointLight(0x555555);
    pointLight.position.x = 100;
    pointLight.position.y = 100;
    pointLight.position.z = 700;
    replayContext.scene.add(pointLight);
}
<commit_msg>second layer of walls<commit_after>var replayContext;

function initReplay() {
    replayContext = new RenderContext("replayCanvas");
    replayContext.setCameraPosition(0, 0, 25);
    replayCreateLights();

    replayContext.createTiles(() => arrange());
}

function arrange() {
    const tileDepth = 0.78;
    const tileWidth = 0.97;
    const tileHeight = 1.3;
    const gap = 0.2;
    const a = -(17 * tileWidth + tileHeight + gap) / 2;
    var tileId = 0;
    for (let i = 0; i < 4; i++) {
        //let x = -8.5 * tileWidth + 0.5 * tileWidth;
        //const y = -8.5 * tileWidth - 0.5 * tileHeight;
        let x = a + 0.5 * tileWidth + tileHeight + gap;
        const y = a + 0.5 * tileHeight;
        for (let j = 0; j < 17; j++) {
            for (let k = 0; k < 2; k++) {
                const number = numberFromTileId(tileId);
                const suit = suitFromTileId(tileId);
                const mesh = replayContext.createTileMesh(number, suit);

                mesh.rotateZ(Math.PI * 0.5 * i);
                mesh.translateX(x);
                mesh.translateY(y);
                mesh.translateZ(k * tileDepth);
                mesh.rotateX(Math.PI * 0.5);
                mesh.rotateY(Math.PI);

                replayContext.scene.add(mesh);
                tileId += 1;
            }
            x += tileWidth;
        }
    }
}

function suitFromTileId(tileId) {
    return Math.floor(tileId / (9 * 4));
}

function numberFromTileId(tileId) {
    if (tileId === 4 * 4 || tileId === 16 + 9 * 4 || tileId === 16 + 9 * 4 * 2)
        return 0;
    return 1 + Math.floor((tileId % (9 * 4)) / 4);
}

function replayCreateLights() {
    const light = new THREE.AmbientLight(0x999999);
    replayContext.scene.add(light);
    const pointLight = new THREE.PointLight(0x555555);
    pointLight.position.x = 100;
    pointLight.position.y = 100;
    pointLight.position.z = 700;
    replayContext.scene.add(pointLight);
}
<|endoftext|>


<commit_before>/**
 * @flow
 * All About Olaf
 * Balances page
 */

import React from 'react'
import {StyleSheet, ScrollView, View, Text, RefreshControl} from 'react-native'
import {TabBarIcon} from '../components/tabbar-icon'
import {connect} from 'react-redux'
import {Cell, TableView, Section} from 'react-native-tableview-simple'

import {updateBalances} from '../../flux/parts/sis'

import isNil from 'lodash/isNil'
import * as c from '../components/colors'

import type {TopLevelViewPropsType} from '../types'

class BalancesView extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Balances',
    tabBarIcon: TabBarIcon('card'),
  }

  props: TopLevelViewPropsType & {
    flex: ?number,
    ole: ?number,
    print: ?number,
    weeklyMeals: ?number,
    dailyMeals: ?number,
    credentialsValid: boolean,
    message: ?string,

    updateBalances: boolean => any,
  }

  state = {
    loading: false,
  }

  fetchData = () => {
    return this.props.updateBalances(true)
  }

  openSettings = () => {
    this.props.navigation.navigate('SettingsView')
  }

  render() {
    let {flex, ole, print, dailyMeals, weeklyMeals} = this.props
    let {loading} = this.state

    return (
      <ScrollView
        contentContainerStyle={styles.stage}
        refreshControl={
          <RefreshControl refreshing={loading} onRefresh={this.fetchData} />
        }
      >
        <TableView>

            <View style={styles.balancesRow}>
              <FormattedValueCell
                label="Flex"
                value={flex}
                indeterminate={loading}
                formatter={getFormattedCurrency}
              />

              <FormattedValueCell
                label="Ole"
                value={ole}
                indeterminate={loading}
                formatter={getFormattedCurrency}
              />

              <FormattedValueCell
                label="Copy/Print"
                value={print}
                indeterminate={loading}
                formatter={getFormattedCurrency}
                style={styles.finalCell}
              />
            </View>

            <View style={styles.balancesRow}>
              <FormattedValueCell
                label="Daily Meals Left"
                value={dailyMeals}
                indeterminate={loading}
                formatter={getFormattedMealsRemaining}
              />

              <FormattedValueCell
                label="Weekly Meals Left"
                value={weeklyMeals}
                indeterminate={loading}
                formatter={getFormattedMealsRemaining}
                style={styles.finalCell}
              />
            </View>

          {!this.props.credentialsValid || this.props.message
            ?

                {!this.props.credentialsValid
                  ? <Cell
                      cellStyle="Basic"
                      title="Log in with Carleton"
                      accessory="DisclosureIndicator"
                      onPress={this.openSettings}
                    />
                  : null}

                {this.props.message
                  ? <Cell cellStyle="Basic" title={this.props.message} />
                  : null}

            : null}
        </TableView>
      </ScrollView>
    )
  }
}

function mapStateToProps(state) {
  return {
    flex: state.sis.balances.flex,
    ole: state.sis.balances.ole,
    print: state.sis.balances.print,
    weeklyMeals: state.sis.balances.weekly,
    dailyMeals: state.sis.balances.daily,
    message: state.sis.balances.message,

    credentialsValid: state.settings.credentials.valid,
  }
}

function mapDispatchToProps(dispatch) {
  return {
    updateBalances: force => dispatch(updateBalances(force)),
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(BalancesView)

let cellMargin = 10
let cellSidePadding = 10
let cellEdgePadding = 10

let styles = StyleSheet.create({
  stage: {
    backgroundColor: c.iosLightBackground,
    paddingTop: 20,
    paddingBottom: 20,
  },

  common: {
    backgroundColor: c.white,
  },

  balances: {
    borderRightWidth: StyleSheet.hairlineWidth,
    borderRightColor: c.iosSeparator,
  },

  finalCell: {
    borderRightWidth: 0,
  },

  balancesRow: {
    flexDirection: 'row',
    marginTop: 0,
    marginBottom: -10,
  },

  rectangle: {
    height: 88,
    flex: 1,
    alignItems: 'center',
    paddingTop: cellSidePadding,
    paddingBottom: cellSidePadding,
    paddingRight: cellEdgePadding,
    paddingLeft: cellEdgePadding,
    marginBottom: cellMargin,
  },

  // Text styling
  financialText: {
    paddingTop: 8,
    color: c.iosDisabledText,
    textAlign: 'center',
    fontWeight: '200',
    fontSize: 23,
  },
  rectangleButtonText: {
    paddingTop: 15,
    color: c.black,
    textAlign: 'center',
    fontSize: 16,
  },
})

function getFormattedCurrency(value: ?number): string {
  if (isNil(value)) {
    return 'N/A'
  }
  return '$' + (((value: any): number) / 100).toFixed(2)
}

function getFormattedMealsRemaining(value: ?number): string {
  if (isNil(value)) {
    return 'N/A'
  }
  return (value: any).toString()
}

function FormattedValueCell({
  indeterminate,
  label,
  value,
  style,
  formatter,
}: {
  indeterminate: boolean,
  label: string,
  value: ?number,
  style?: any,
  formatter: (?number) => string,
}) {
  return (
    <View style={[styles.rectangle, styles.common, styles.balances, style]}>
      <Text
        selectable={true}
        style={styles.financialText}
        autoAdjustsFontSize={true}
      >
        {indeterminate ? '…' : formatter(value)}
      </Text>
      <Text style={styles.rectangleButtonText} autoAdjustsFontSize={true}>
        {label}
      </Text>
    </View>
  )
}
<commit_msg>display carleton balances<commit_after>/**
 * @flow
 * All About Olaf
 * Balances page
 */

import React from 'react'
import {StyleSheet, ScrollView, View, Text, RefreshControl} from 'react-native'
import {TabBarIcon} from '../components/tabbar-icon'
import {connect} from 'react-redux'
import {Cell, TableView, Section} from 'react-native-tableview-simple'

import {updateBalances} from '../../flux/parts/sis'

import isNil from 'lodash/isNil'
import * as c from '../components/colors'

import type {TopLevelViewPropsType} from '../types'

class BalancesView extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Balances',
    tabBarIcon: TabBarIcon('card'),
  }

  props: TopLevelViewPropsType & {
    flex: ?number,
    ole: ?number,
    print: ?number,
    weeklyMeals: ?number,
    dailyMeals: ?number,
    credentialsValid: boolean,
    message: ?string,

    updateBalances: boolean => any,
  }

  state = {
    loading: false,
  }

  fetchData = () => {
    return this.props.updateBalances(true)
  }

  openSettings = () => {
    this.props.navigation.navigate('SettingsView')
  }

  render() {
    const {
      schillers,
      dining,
      print,
      dailyMeals,
      weeklyMeals,
      loading,
    } = this.props

    return (
      <ScrollView
        contentContainerStyle={styles.stage}
        refreshControl={
          <RefreshControl refreshing={loading} onRefresh={this.fetchData} />
        }
      >
        <TableView>

            <View style={styles.balancesRow}>
              <FormattedValueCell
                label="Schillers"
                value={schillers}
                indeterminate={loading}
                formatter={getFormattedCurrency}
              />

              <FormattedValueCell
                label="Dining"
                value={dining}
                indeterminate={loading}
                formatter={getFormattedCurrency}
              />

              {/*<FormattedValueCell
                label="Copy/Print"
                value={print}
                indeterminate={loading}
                formatter={getFormattedCurrency}
                style={styles.finalCell}
              />*/}
            </View>

            <View style={styles.balancesRow}>
              <FormattedValueCell
                label="Daily Meals Left"
                value={dailyMeals}
                indeterminate={loading}
                formatter={getFormattedMealsRemaining}
              />

              <FormattedValueCell
                label="Weekly Meals Left"
                value={weeklyMeals}
                indeterminate={loading}
                formatter={getFormattedMealsRemaining}
                style={styles.finalCell}
              />
            </View>

          {!this.props.credentialsValid || this.props.message
            ?

                {!this.props.credentialsValid
                  ? <Cell
                      cellStyle="Basic"
                      title="Log in with Carleton"
                      accessory="DisclosureIndicator"
                      onPress={this.openSettings}
                    />
                  : null}

                {this.props.message
                  ? <Cell cellStyle="Basic" title={this.props.message} />
                  : null}

            : null}
        </TableView>
      </ScrollView>
    )
  }
}

function mapStateToProps(state) {
  return {
    schillers: state.sis.balances.schillers,
    dining: state.sis.balances.dining,
    print: state.sis.balances.print,
    weeklyMeals: state.sis.balances.weekly,
    dailyMeals: state.sis.balances.daily,
    message: state.sis.balances.message,
    loading: state.sis.balances.loading,

    credentialsValid: state.settings.credentials.valid,
  }
}

function mapDispatchToProps(dispatch) {
  return {
    updateBalances: force => dispatch(updateBalances(force)),
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(BalancesView)

let cellMargin = 10
let cellSidePadding = 10
let cellEdgePadding = 10

let styles = StyleSheet.create({
  stage: {
    backgroundColor: c.iosLightBackground,
    paddingTop: 20,
    paddingBottom: 20,
  },

  common: {
    backgroundColor: c.white,
  },

  balances: {
    borderRightWidth: StyleSheet.hairlineWidth,
    borderRightColor: c.iosSeparator,
  },

  finalCell: {
    borderRightWidth: 0,
  },

  balancesRow: {
    flexDirection: 'row',
    marginTop: 0,
    marginBottom: -10,
  },

  rectangle: {
    height: 88,
    flex: 1,
    alignItems: 'center',
    paddingTop: cellSidePadding,
    paddingBottom: cellSidePadding,
    paddingRight: cellEdgePadding,
    paddingLeft: cellEdgePadding,
    marginBottom: cellMargin,
  },

  // Text styling
  financialText: {
    paddingTop: 8,
    color: c.iosDisabledText,
    textAlign: 'center',
    fontWeight: '200',
    fontSize: 23,
  },
  rectangleButtonText: {
    paddingTop: 15,
    color: c.black,
    textAlign: 'center',
    fontSize: 16,
  },
})

function getFormattedCurrency(value: ?number): string {
  if (isNil(value)) {
    return 'N/A'
  }
  return '$' + (((value: any): number) / 100).toFixed(2)
}

function getFormattedMealsRemaining(value: ?number): string {
  if (isNil(value)) {
    return 'N/A'
  }
  return (value: any).toString()
}

function FormattedValueCell({
  indeterminate,
  label,
  value,
  style,
  formatter,
}: {
  indeterminate: boolean,
  label: string,
  value: ?number,
  style?: any,
  formatter: (?number) => string,
}) {
  return (
    <View style={[styles.rectangle, styles.common, styles.balances, style]}>
      <Text
        selectable={true}
        style={styles.financialText}
        autoAdjustsFontSize={true}
      >
        {indeterminate ? '…' : formatter(value)}
      </Text>
      <Text style={styles.rectangleButtonText} autoAdjustsFontSize={true}>
        {label}
      </Text>
    </View>
  )
}
<|endoftext|>