<commit_before>import 'bootstrap';
import 'bootstrap/css/bootstrap.css!';
import {ServiceLocator} from 'dash-core'
import * as dashComponent from 'dash-component'

export class App {

  constructor()
  {
    this.insertComponentModels();
    ServiceLocator.services.chromeComponentInfo.path = 'dash-component' + ServiceLocator.services.chromeComponentInfo.path;
  }

  insertComponentModels()
  {
    ServiceLocator.services.componentModelLoader.getModels()[1] = { id:1, configurationProperties : {}, layoutInfo : {} };
  }

  configureRouter(config, router){
    config.title = 'Aurelia';
    //config.addPipelineStep('modelbind',modelbind);
    config.map([
      { route: ['','b/:areaId'],  moduleId: './dashboards/dash/Dashboard',      nav: true, title:'Dash Dashboard' },
      { route: ['basicDashboard'],  moduleId: './dashboards/basic/basicDashboard',      nav: true, title:'Basic Dashboard' },
      { route: ['git'],  moduleId: './dashboards/git/gitDashboard',      nav: true, title:'Git Dashboard' }
    ]);

    this.router = router;
  }
}
<commit_msg>adding the mock area in the right place<commit_after>import 'bootstrap';
import 'bootstrap/css/bootstrap.css!';
import {ServiceLocator} from 'dash-core'
import * as dashComponent from 'dash-component'

export class App {

  constructor()
  {
    this.insertComponentModels();
    this.insertAreaModels();
    ServiceLocator.services.chromeComponentInfo.path = 'dash-component' + ServiceLocator.services.chromeComponentInfo.path;
  }

  insertAreaModels()
  {

    // ToDo: Update this as it's been pulled straight out of the baseAreaLoader

    //var mockAreaResponse = new AreaConfiguration();
    //
    //mockAreaResponse.areaLayout = new AreaLayout();
    //mockAreaResponse.areaLayout.viewModel = 'dash-component/layouts/floatLayout/floatLayout';
    //
    //var layoutConfig = new LayoutConfiguration();
    //layoutConfig.viewModel = 'dash-component/layouts/floatLayout/floatLayout';
    //layoutConfig.componentsForCompose = [
    //  {id: 1, viewModel:'dash-github/components/singleValueComponent/gitSingleValueComponent'},
    //  {id: 1, viewModel:'dash-github/components/imageGrid/imageGrid'}
    //];
    //
    //mockAreaResponse.layouts.push(layoutConfig);
    //
    //
    //layoutConfig = new LayoutConfiguration();
    //layoutConfig.viewModel = 'dash-component/layouts/floatLayout/floatLayout';
    //layoutConfig.componentsForCompose = [
    //  {id: 1, viewModel:'components/testComponent/testComponent'},
    //  {id: 1, viewModel:'components/testComponent/testComponent'},
    //  {id: 1, viewModel:'components/testComponent/testComponent'},
    //  {id: 1, viewModel:'components/testComponent/testComponent'},
    //  {id: 1, viewModel:'components/testComponent/testComponent'},
    //  {id: 1, viewModel:'components/testComponent/testComponent'},
    //  {id: 1, viewModel:'components/testComponent/testComponent'},
    //  {id: 1, viewModel:'components/testComponent/testComponent'},
    //  {id: 1, viewModel:'components/testComponent/testComponent'},
    //  {id: 1, viewModel:'components/testComponent/testComponent'},
    //  {id: 1, viewModel:'components/testComponent/testComponent'}
    //];
    //
    //mockAreaResponse.layouts.push(layoutConfig);
  }

  insertComponentModels()
  {
    ServiceLocator.services.componentModelLoader.getModels()[1] = { id:1, configurationProperties : {}, layoutInfo : {} };
  }

  configureRouter(config, router){
    config.title = 'Aurelia';
    //config.addPipelineStep('modelbind',modelbind);
    config.map([
      { route: ['','b/:areaId'],  moduleId: './dashboards/dash/Dashboard',      nav: true, title:'Dash Dashboard' },
      { route: ['basicDashboard'],  moduleId: './dashboards/basic/basicDashboard',      nav: true, title:'Basic Dashboard' },
      { route: ['git'],  moduleId: './dashboards/git/gitDashboard',      nav: true, title:'Git Dashboard' }
    ]);

    this.router = router;
  }
}
<|endoftext|>


<commit_before>var assert = require('assert')
var base58check = require('./base58check')
var networks = require('./networks')

function findScriptTypeByVersion(queryVersion) {
  for (var networkName in networks) {
    var network = networks[networkName]

    for (var versionName in network) {
      var version = network[versionName]

      if (version === queryVersion) {
        return versionName
      }
    }
  }

  throw new Error('Version has no corresponding network')
}

function Address(hash, version) {
  assert(Buffer.isBuffer(hash), 'First argument must be a Buffer')
  assert.strictEqual(hash.length, 20, 'Invalid hash length')
  assert.strictEqual(version & 0xFF, version, 'Invalid version byte')

  this.hash = hash
  this.version = version
}

// Import functions
Address.fromBase58Check = function(string) {
  var decode = base58check.decode(string)

  return new Address(decode.payload, decode.version)
}

Address.fromScriptPubKey = function(script, network) {
  network = network || networks.bitcoin

  var type = script.getOutType()

  // Pay-to-pubKeyHash
  if (type === 'pubkeyhash') {
    return new Address(new Buffer(script.chunks[2]), network.pubKeyHash)
  }

  // Pay-to-scriptHash
  else if (type === 'scripthash') {
    return new Address(new Buffer(script.chunks[1]), network.scriptHash)
  }

  throw new Error('Could not derive address from script')
}

// Export functions
Address.prototype.toBase58Check = function () {
  return base58check.encode(this.hash, this.version)
}

Address.prototype.toScriptPubKey = function() {
  var scriptType = findScriptTypeByVersion(this.version)

  // Pay-to-pubKeyHash
  if (scriptType === 'pubKeyHash') {
    return Script.createPubKeyHashScriptPubKey(this.hash)
  }

  // Pay-to-scriptHash
  else if (scriptType === 'scriptHash') {
    return Script.createP2SHScriptPubKey(this.hash)
  }

  throw new Error('Address has no matching script')
}

Address.prototype.toString = Address.prototype.toBase58Check

module.exports = Address

// http://stackoverflow.com/a/14098262
var Script = require('./script')
<commit_msg>Address: use Address.Error instead<commit_after>var assert = require('assert')
var base58check = require('./base58check')
var networks = require('./networks')

function findScriptTypeByVersion(queryVersion) {
  for (var networkName in networks) {
    var network = networks[networkName]

    for (var versionName in network) {
      var version = network[versionName]

      if (version === queryVersion) {
        return versionName
      }
    }
  }
}

function Address(hash, version) {
  assert(Buffer.isBuffer(hash), 'First argument must be a Buffer')
  assert.strictEqual(hash.length, 20, 'Invalid hash length')
  assert.strictEqual(version & 0xFF, version, 'Invalid version byte')

  this.hash = hash
  this.version = version
}

Address.Error = function(message) {
  this.name = 'AddressError'
  this.message = message
}
Address.Error.prototype = new Error()
Address.Error.prototype.constructor = Address.Error

// Import functions
Address.fromBase58Check = function(string) {
  var decode = base58check.decode(string)

  return new Address(decode.payload, decode.version)
}

Address.fromScriptPubKey = function(script, network) {
  network = network || networks.bitcoin

  var type = script.getOutType()

  // Pay-to-pubKeyHash
  if (type === 'pubkeyhash') {
    return new Address(new Buffer(script.chunks[2]), network.pubKeyHash)
  }

  // Pay-to-scriptHash
  else if (type === 'scripthash') {
    return new Address(new Buffer(script.chunks[1]), network.scriptHash)
  }

  throw new Address.Error(type + ' has no matching Address')
}

// Export functions
Address.prototype.toBase58Check = function () {
  return base58check.encode(this.hash, this.version)
}

Address.prototype.toScriptPubKey = function() {
  var scriptType = findScriptTypeByVersion(this.version)

  // Pay-to-pubKeyHash
  if (scriptType === 'pubKeyHash') {
    return Script.createPubKeyHashScriptPubKey(this.hash)
  }

  // Pay-to-scriptHash
  else if (scriptType === 'scriptHash') {
    return Script.createP2SHScriptPubKey(this.hash)
  }

  throw new Address.Error(this + ' has no matching script')
}

Address.prototype.toString = Address.prototype.toBase58Check

module.exports = Address

// http://stackoverflow.com/a/14098262
var Script = require('./script')
<|endoftext|>


<commit_before>const path = require('path')
const express = require('express')
const session = require('express-session')

const basic = require('./routes/index')
const auth = require('./routes/auth')
const getSites = require('./routes/sites/getSites')
const createSite = require('./routes/sites/createSite')
const deleteSite = require('./routes/sites/deleteSite')
const getImages = require('./routes/sites/getImages')

const bodyParser = require('body-parser')
const cors = require('cors')
// const port = process.env.PORT || 80
// const app = express()

// returns an instance of node-greenlock with additional helper methods
var lex = require('greenlock-express').create({
  server: 'staging', // set to https://acme-v01.api.letsencrypt.org/directory in production
  challenges: { 'http-01': require('le-challenge-fs').create({ webrootPath: '/tmp/acme-challenges' }) },
  store: require('le-store-certbot').create({ webrootPath: '/tmp/acme-challenges' }),
  approveDomains: approveDomains
})

function approveDomains (opts, certs, cb) {
  if (certs) {
    opts.domains = certs.altnames
  } else {
    opts.approveDomains = ['trig.dk']
    opts.email = 'casperfibaek@gmail.com'
    opts.agreeTos = true
  }
  cb(null, { options: opts, certs: certs })
}

require('http').createServer(lex.middleware(require('redirect-https')())).listen(80, function () {
  console.log('Listening for ACME http-01 challenges on', this.address())
})

var app = require('express')()
app.use(cors()) // Allow crossOrigin (remove after testing)
app.use(bodyParser.urlencoded({
  extended: true,
  parameterLimit: 10000,
  limit: 1024 * 1024 * 10 // 10mb
}))
app.use(bodyParser.json({
  extended: true,
  parameterLimit: 10000,
  limit: 1024 * 1024 * 10 // 10mb
}))
app.use(session({
  secret: 'un vie de file dleau',
  saveUninitialized: true,
  resave: true,
  name: 'sessionID'
}))
app.use(express.static(path.join(__dirname, 'public')))
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'hbs')
app.use('/', basic)
app.use('/', auth)
app.use('/', getSites)
app.use('/', createSite)
app.use('/', deleteSite)
app.use('/', getImages)
app.use(function (req, res, next) {
  res.status(404).render('error', {
    title: 'Page not found'
  })
})
// app.set('port', port)
// app.listen(app.get('port'), '0.0.0.0')

// handles your app
require('https').createServer(lex.httpsOptions, lex.middleware(app)).listen(443, function () {
  console.log('Listening for ACME tls-sni-01 challenges and serve app on', this.address())
})

// require('greenlock-express').create({
//   server: 'https://acme-v01.api.letsencrypt.org/directory',
//   email: 'casperfibaek@gmail.com',
//   agreeTos: true,
//   approveDomains: [ 'trig.dk/monitor' ],
//   app: require('express')()
//   .use(cors()) // Allow crossOrigin (remove after testing)
//   .use(bodyParser.urlencoded({
//     extended: true,
//     parameterLimit: 10000,
//     limit: 1024 * 1024 * 10 // 10mb
//   }))
//   .use(bodyParser.json({
//     extended: true,
//     parameterLimit: 10000,
//     limit: 1024 * 1024 * 10 // 10mb
//   }))
//   .use(session({
//     secret: 'un vie de file dleau',
//     saveUninitialized: true,
//     resave: true,
//     name: 'sessionID'
//   }))
//   .use(express.static(path.join(__dirname, 'public')))
//   .set('views', path.join(__dirname, 'views'))
//   .set('view engine', 'hbs')
//   .use('/', basic)
//   .use('/', auth)
//   .use('/', getSites)
//   .use('/', createSite)
//   .use('/', deleteSite)
//   .use('/', getImages)
//   .use(function (req, res, next) {
//     res.status(404).render('error', {
//       title: 'Page not found'
//     })
//   })
//
// }).listen(80, 443)

// app.use(cors()) // Allow crossOrigin (remove after testing)
// app.use(bodyParser.urlencoded({
//   extended: true,
//   parameterLimit: 10000,
//   limit: 1024 * 1024 * 10 // 10mb
// }))
// app.use(bodyParser.json({
//   extended: true,
//   parameterLimit: 10000,
//   limit: 1024 * 1024 * 10 // 10mb
// }))
// app.use(session({
//   secret: 'un vie de file dleau',
//   saveUninitialized: true,
//   resave: true,
//   name: 'sessionID'
// }))
// app.use(express.static(path.join(__dirname, 'public')))
// app.set('views', path.join(__dirname, 'views'))
// app.set('view engine', 'hbs')
// app.use('/', basic)
// app.use('/', auth)
// app.use('/', getSites)
// app.use('/', createSite)
// app.use('/', deleteSite)
// app.use('/', getImages)
// app.use(function (req, res, next) {
//   res.status(404).render('error', {
//     title: 'Page not found'
//   })
// })
// app.set('port', port)
// app.listen(app.get('port'), '0.0.0.0')
console.log('Monitor initialized..')
<commit_msg>https tests<commit_after>const path = require('path')
const express = require('express')
const session = require('express-session')

const basic = require('./routes/index')
const auth = require('./routes/auth')
const getSites = require('./routes/sites/getSites')
const createSite = require('./routes/sites/createSite')
const deleteSite = require('./routes/sites/deleteSite')
const getImages = require('./routes/sites/getImages')

const bodyParser = require('body-parser')
const cors = require('cors')
// const port = process.env.PORT || 80
// const app = express()

// returns an instance of node-greenlock with additional helper methods
var lex = require('greenlock-express').create({
  server: 'https://acme-v01.api.letsencrypt.org/directory', // set to https://acme-v01.api.letsencrypt.org/directory in production
  challenges: { 'http-01': require('le-challenge-fs').create({ webrootPath: '/tmp/acme-challenges' }) },
  store: require('le-store-certbot').create({ webrootPath: '/tmp/acme-challenges' }),
  approveDomains: approveDomains
})

function approveDomains (opts, certs, cb) {
  if (certs) {
    opts.domains = certs.altnames
    opts.approveDomains = ['trig.dk']
  } else {
    opts.approveDomains = ['trig.dk']
    opts.email = 'casperfibaek@gmail.com'
    opts.agreeTos = true
  }
  cb(null, { options: opts, certs: certs })
}

require('http').createServer(lex.middleware(require('redirect-https')())).listen(80, function () {
  console.log('Listening for ACME http-01 challenges on', this.address())
})

var app = require('express')()
app.use(cors()) // Allow crossOrigin (remove after testing)
app.use(bodyParser.urlencoded({
  extended: true,
  parameterLimit: 10000,
  limit: 1024 * 1024 * 10 // 10mb
}))
app.use(bodyParser.json({
  extended: true,
  parameterLimit: 10000,
  limit: 1024 * 1024 * 10 // 10mb
}))
app.use(session({
  secret: 'un vie de file dleau',
  saveUninitialized: true,
  resave: true,
  name: 'sessionID'
}))
app.use(express.static(path.join(__dirname, 'public')))
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'hbs')
app.use('/', basic)
app.use('/', auth)
app.use('/', getSites)
app.use('/', createSite)
app.use('/', deleteSite)
app.use('/', getImages)
app.use(function (req, res, next) {
  res.status(404).render('error', {
    title: 'Page not found'
  })
})
// app.set('port', port)
// app.listen(app.get('port'), '0.0.0.0')

// handles your app
require('https').createServer(lex.httpsOptions, lex.middleware(app)).listen(443, function () {
  console.log('Listening for ACME tls-sni-01 challenges and serve app on', this.address())
})

// require('greenlock-express').create({
//   server: 'https://acme-v01.api.letsencrypt.org/directory',
//   email: 'casperfibaek@gmail.com',
//   agreeTos: true,
//   approveDomains: [ 'trig.dk/monitor' ],
//   app: require('express')()
//   .use(cors()) // Allow crossOrigin (remove after testing)
//   .use(bodyParser.urlencoded({
//     extended: true,
//     parameterLimit: 10000,
//     limit: 1024 * 1024 * 10 // 10mb
//   }))
//   .use(bodyParser.json({
//     extended: true,
//     parameterLimit: 10000,
//     limit: 1024 * 1024 * 10 // 10mb
//   }))
//   .use(session({
//     secret: 'un vie de file dleau',
//     saveUninitialized: true,
//     resave: true,
//     name: 'sessionID'
//   }))
//   .use(express.static(path.join(__dirname, 'public')))
//   .set('views', path.join(__dirname, 'views'))
//   .set('view engine', 'hbs')
//   .use('/', basic)
//   .use('/', auth)
//   .use('/', getSites)
//   .use('/', createSite)
//   .use('/', deleteSite)
//   .use('/', getImages)
//   .use(function (req, res, next) {
//     res.status(404).render('error', {
//       title: 'Page not found'
//     })
//   })
//
// }).listen(80, 443)

// app.use(cors()) // Allow crossOrigin (remove after testing)
// app.use(bodyParser.urlencoded({
//   extended: true,
//   parameterLimit: 10000,
//   limit: 1024 * 1024 * 10 // 10mb
// }))
// app.use(bodyParser.json({
//   extended: true,
//   parameterLimit: 10000,
//   limit: 1024 * 1024 * 10 // 10mb
// }))
// app.use(session({
//   secret: 'un vie de file dleau',
//   saveUninitialized: true,
//   resave: true,
//   name: 'sessionID'
// }))
// app.use(express.static(path.join(__dirname, 'public')))
// app.set('views', path.join(__dirname, 'views'))
// app.set('view engine', 'hbs')
// app.use('/', basic)
// app.use('/', auth)
// app.use('/', getSites)
// app.use('/', createSite)
// app.use('/', deleteSite)
// app.use('/', getImages)
// app.use(function (req, res, next) {
//   res.status(404).render('error', {
//     title: 'Page not found'
//   })
// })
// app.set('port', port)
// app.listen(app.get('port'), '0.0.0.0')
console.log('Monitor initialized..')
<|endoftext|>


<commit_before>// TODO requires three.js, CANNON.js, settings.js, cardboard.js, WebVRApplication.js, CrapLoader.js, LeapTools.js, pyserver.js
var app;

var scene = CrapLoader.parse(JSON_SCENE);
var H_table = 0.74295; // TODO: coordinate w/ server

var avatar = avatar || new THREE.Object3D();
avatar.position.y = 1.2;
avatar.position.z = 1.9;

var ballMeshes       = [],
    ballStripeMeshes = [];
var stickMesh, tipBody, toolRoot, tipMesh;
var stickShadow, stickShadowMesh;
var dynamicBodies,
    ballBodies;

var mouseParticleGroup = new SPE.Group({
    texture: {value: THREE.ImageUtils.loadTexture('images/smokeparticle.png')}
});
var mouseParticleEmitter = new SPE.Emitter({maxAge: {value: 0.5},
                                            position: {value: new THREE.Vector3(),
                                                       spread: new THREE.Vector3()},
                                            velocity: {value: new THREE.Vector3(0, 0, 0),
                                                       spread: new THREE.Vector3(0.3, 0.3, 0.3)},
                                            color: {value: [new THREE.Color('white'), new THREE.Color('red')]},
                                            size: {value: 0.1},
                                            particleCount: 50});
mouseParticleGroup.addEmitter(mouseParticleEmitter);
var mousePointer = mouseParticleGroup.mesh;

function onLoad() {
    "use strict";
    pyserver.log("starting poolvr...");

    pyserver.log("POOLVR.config =\n" + JSON.stringify(POOLVR.config, undefined, 2));

    POOLVR.config.keyboardCommands = POOLVR.keyboardCommands;
    POOLVR.config.gamepadCommands = POOLVR.gamepadCommands;

    app = new WebVRApplication("poolvr", avatar, scene, POOLVR.config);
    avatar.add(app.camera);
    scene.add(avatar);

    function lockChangeAlert() {
        if ( document.pointerLockElement || document.mozPointerLockElement || document.webkitPointerLockElement ) {
            pyserver.log('pointer lock status is now locked');
            mousePointer.visible = true;
        } else {
            pyserver.log('pointer lock status is now unlocked');
            mousePointer.visible = false;
        }
    }
    if (app.config.mouseEnabled) {
        if ("onpointerlockchange" in document) {
          document.addEventListener('pointerlockchange', lockChangeAlert, false);
        } else if ("onmozpointerlockchange" in document) {
          document.addEventListener('mozpointerlockchange', lockChangeAlert, false);
        } else if ("onwebkitpointerlockchange" in document) {
          document.addEventListener('webkitpointerlockchange', lockChangeAlert, false);
        }
        avatar.add(mousePointer);
        mousePointer.position.set(0, 0, -2);
        app.mousePointer = mousePointer;
        app.mouseParticleGroup = mouseParticleGroup;
        var xMax = 2, xMin = -2,
            yMax = 1, yMin = -1;
        window.addEventListener("mousemove", function (evt) {
            if (!mousePointer.visible) return;
            var dx = evt.movementX,
                dy = evt.movementY;
            mousePointer.position.x += 0.0004*dx;
            mousePointer.position.y -= 0.0004*dy;
            if (mousePointer.position.x > xMax) mousePointer.position.x = xMax;
            else if (mousePointer.position.x < xMin) mousePointer.position.x = xMin;
            if (mousePointer.position.y > yMax) mousePointer.position.y = yMax;
            else if (mousePointer.position.y < yMin) mousePointer.position.y = yMin;
        });
    }

    if (!app.config.useBasicMaterials) {
        // would rather add the spot lights via three.py generated JSON_SCENE, but I'm having problems getting shadows frm them:
        var centerSpotLight = new THREE.SpotLight(0xffffee, 1, 10, 90);
        centerSpotLight.position.set(0, 3, 0);
        centerSpotLight.castShadow = true;
        centerSpotLight.shadowCameraNear = 0.01;
        centerSpotLight.shadowCameraFar = 4;
        centerSpotLight.shadowCameraFov = 90;
        scene.add(centerSpotLight);
        // var centerSpotLightHelper = new THREE.SpotLightHelper(centerSpotLight);
        // scene.add(centerSpotLightHelper);
        // centerSpotLightHelper.visible = false;
    }

    CrapLoader.CANNONize(scene, app.world);

    // TODO: load from JSON config
    var ballMaterial            = new CANNON.Material();
    var ballBallContactMaterial = new CANNON.ContactMaterial(ballMaterial, ballMaterial, {restitution: 0.91, friction: 0.08});
    app.world.addContactMaterial(ballBallContactMaterial);
    var playableSurfaceMaterial            = new CANNON.Material();
    var ballPlayableSurfaceContactMaterial = new CANNON.ContactMaterial(ballMaterial, playableSurfaceMaterial, {restitution: 0.3, friction: 0.1});
    app.world.addContactMaterial(ballPlayableSurfaceContactMaterial);
    var cushionMaterial            = new CANNON.Material();
    var ballCushionContactMaterial = new CANNON.ContactMaterial(ballMaterial, cushionMaterial, {restitution: 0.8, friction: 0.4});
    app.world.addContactMaterial(ballCushionContactMaterial);
    var floorMaterial            = new CANNON.Material();
    var floorBallContactMaterial = new CANNON.ContactMaterial(floorMaterial, ballMaterial, {restitution: 0.88, friction: 0.4});
    app.world.addContactMaterial(floorBallContactMaterial);

    scene.traverse(function (node) {
        if (node.name.startsWith('ballMesh')) {
            node.body.material = ballMaterial;
            ballMeshes.push(node);
        }
        else if (node.name.startsWith('ballStripeMesh')) {
            ballStripeMeshes.push(node);
        }
        else if (node.name.startsWith('playableSurfaceMesh')) {
            node.body.material = playableSurfaceMaterial;
        }
        else if (node.name.endsWith('CushionMesh')) {
            node.body.material = cushionMaterial;
        }
        else if (node.name === 'floorMesh') {
            node.body.material = floorMaterial;
        }
    });

    var toolOptions = {
        // ##### Desktop mode (default): #####
        transformOptions : app.config.transformOptions || {vr: 'desktop'},
        leapDisabled     : app.config.leapDisabled,
        leapHandsDisabled: app.config.leapHandsDisabled,
        useBasicMaterials: app.config.useBasicMaterials,
        toolLength       : app.config.toolLength || 0.5,
        toolRadius       : app.config.toolRadius || 0.013
    };
    // if (app.config.leapVR) {
    //     // ##### Leap Motion VR tracking mode: #####
    //     toolOptions.transformOptions = {vr: true, effectiveParent: app.camera};
    // }

    pyserver.log('adding tool...');
    pyserver.log('toolOptions =\n' + JSON.stringify(toolOptions, undefined, 2));

    var toolStuff = addTool(avatar, app.world, toolOptions);
    stickMesh = toolStuff.stickMesh;
    tipMesh   = toolStuff.tipMesh;
    tipBody   = toolStuff.tipBody;
    toolRoot  = toolStuff.toolRoot;

    if (!app.config.shadowMap) {
        // create shadow mesh from projection:
        stickShadow = new THREE.Object3D();
        stickShadow.position.y = -avatar.position.y - toolRoot.position.y + H_table + 0.001;
        stickShadow.scale.set(1, 0.0004, 1);
        toolRoot.add(stickShadow);

        var stickShadowMaterial = new THREE.MeshBasicMaterial({color: 0x002200});

        var stickShadowGeom = stickMesh.geometry.clone();
        var toolLength = toolOptions.toolLength || 0.5;
        stickShadowGeom.translate(0, -toolLength / 2, 0); // have to do this again because not buffergeometry???

        stickShadowMesh = new THREE.Mesh(stickShadowGeom, stickShadowMaterial);
        stickShadowMesh.quaternion.copy(stickMesh.quaternion);
        stickShadow.add(stickShadowMesh);

        tipMesh.geometry.computeBoundingSphere();
        var tipShadowGeom = new THREE.CircleBufferGeometry(tipMesh.geometry.boundingSphere.radius).rotateX(-Math.PI / 2);
        var tipShadowMesh = new THREE.Mesh(tipShadowGeom, stickShadowMaterial);
        stickShadow.add(tipShadowMesh);
    }

    dynamicBodies = app.world.bodies.filter(function(body) { return body.mesh && body.type !== CANNON.Body.STATIC; });
    ballBodies = dynamicBodies.filter(function(body) { return body.mesh.name.startsWith('ballMesh'); });

    var ballBallBuffer;
    var request = new XMLHttpRequest();
    request.responseType = 'arraybuffer';
    request.open('GET', 'sounds/ballBall.ogg', true);
    request.onload = function() {
        app.audioContext.decodeAudioData(request.response).then(function(buffer) {
            ballBallBuffer = buffer;
        });
    };
    request.send();
    app.playCollisionSound = function () {
        var source = app.audioContext.createBufferSource();
        source.connect(app.gainNode);
        source.buffer = ballBallBuffer;
        source.start(0);
    };

    app.start(animate);
}

var UP = new THREE.Vector3(0, 1, 0),
    RIGHT = new THREE.Vector3(1, 0, 0),
    pitchQuat = new THREE.Quaternion(),
    headingQuat = new THREE.Quaternion(),
    strafe,
    drive,
    floatUp,
    walkSpeed = 0.3,
    floatSpeed = 0.1,
    toolDrive, toolStrafe, toolFloat;
var raycaster = new THREE.Raycaster();
function animate(t) {
    "use strict";
    requestAnimationFrame(animate);
    var dt = (t - app.lt) * 0.001;
    app.lt = t;
    if (app.vrControls.enabled) {
        app.vrControls.update();
    }
    app.vrManager.render(app.scene, app.camera, t);
    app.keyboard.update(dt);
    app.gamepad.update(dt);

    floatUp = app.keyboard.getValue("floatUp") + app.keyboard.getValue("floatDown");
    drive = app.keyboard.getValue("driveBack") + app.keyboard.getValue("driveForward");
    strafe = app.keyboard.getValue("strafeRight") + app.keyboard.getValue("strafeLeft");
    avatar.heading += -0.8 * dt * (app.keyboard.getValue("turnLeft") + app.keyboard.getValue("turnRight"));
    if (avatar.floatMode) {
        floatUp += app.gamepad.getValue("float");
        strafe += app.gamepad.getValue("strafe");
    } else {
        drive += app.gamepad.getValue("drive");
        avatar.heading += 0.8 * dt * app.gamepad.getValue("dheading");
    }
    var cosHeading = Math.cos(avatar.heading),
        sinHeading = Math.sin(avatar.heading);
    if (!app.vrControls.enabled) {
        avatar.pitch -= 0.8 * dt * (app.keyboard.getValue("pitchUp") + app.keyboard.getValue("pitchDown"));
        pitchQuat.setFromAxisAngle(RIGHT, avatar.pitch);
    }
    var cosPitch = Math.cos(avatar.pitch),
        sinPitch = Math.sin(avatar.pitch);
    floatUp *= floatSpeed;
    if (strafe || drive) {
        var len = walkSpeed * Math.min(1, 1 / Math.sqrt(drive * drive +
            strafe * strafe));
        strafe *= len;
        drive *= len;
    } else {
        strafe = 0;
        drive = 0;
    }

    toolDrive = app.keyboard.getValue("moveToolForwards") - app.keyboard.getValue("moveToolBackwards");
    toolFloat = app.keyboard.getValue("moveToolUp") - app.keyboard.getValue("moveToolDown");
    toolStrafe = app.keyboard.getValue("moveToolRight") - app.keyboard.getValue("moveToolLeft");
    toolStrafe += app.gamepad.getValue("toolStrafe");
    if (avatar.toolMode) {
        toolFloat += app.gamepad.getValue("toolFloat");
    } else {
        toolDrive -= app.gamepad.getValue("toolDrive");
    }

    // TODO: resolve CANNON issues w/ initial low framerate
    app.world.step(Math.min(dt, 1/60));

    for (var j = 0; j < dynamicBodies.length; ++j) {
        var body = dynamicBodies[j];
        body.mesh.position.copy(body.position);
    }

    for (j = 0; j < ballStripeMeshes.length; j++) {
        var mesh = ballStripeMeshes[j];
        mesh.quaternion.copy(mesh.parent.body.quaternion);
    }

    avatar.quaternion.setFromAxisAngle(UP, avatar.heading);
    avatar.quaternion.multiply(pitchQuat);
    avatar.position.x += dt * (strafe * cosHeading + drive * sinHeading);
    avatar.position.z += dt * (drive * cosHeading - strafe * sinHeading);
    avatar.position.y += dt * floatUp;

    toolRoot.position.x += 0.25  * dt * toolStrafe;
    toolRoot.position.z += -0.25 * dt * toolDrive;
    toolRoot.position.y += 0.25  * dt * toolFloat;

    if (!app.config.shadowMap) {
        // if (tipBody.position[1] > H_table - 0.0666) {
            stickShadow.position.set(stickMesh.position.x,
                                     H_table + 0.001 - toolRoot.position.y - avatar.position.y,
                                     stickMesh.position.z);
            stickShadowMesh.quaternion.copy(stickMesh.quaternion);
        // }
    }

    for (j = 0; j < app.world.contacts.length; j++) {
        var contactEquation = app.world.contacts[j];
        var bi = contactEquation.bi,
            bj = contactEquation.bj;
        if (bi.material === bj.material) {
            app.playCollisionSound();
        }
    }

    if (app.mouseParticleGroup) app.mouseParticleGroup.tick(dt);

}

    // if (app.mousePointer && avatar.picking) {
    //     origin.set(0, 0, 0);
    //     direction.set(0, 0, 0);
    //     direction.subVectors(mousePointer.localToWorld(direction), camera.localToWorld(origin)).normalize();
    //     raycaster.set(origin, direction);
    //     var intersects = raycaster.intersectObjects(app.pickables);
    //     if (intersects.length > 0) {
    //         if (app.picked != intersects[0].object) {
    //             if (app.picked) app.picked.material.color.setHex(app.picked.currentHex);
    //             app.picked = intersects[0].object;
    //             app.picked.currentHex = app.picked.material.color.getHex();
    //             app.picked.material.color.setHex(0xff4444); //0x44ff44);
    //         }
    //     } else {
    //         if (app.picked) app.picked.material.color.setHex(app.picked.currentHex);
    //         app.picked = null;
    //     }
    // }

<commit_msg>Asdasfd<commit_after>// TODO requires three.js, CANNON.js, settings.js, cardboard.js, WebVRApplication.js, CrapLoader.js, LeapTools.js, pyserver.js
var app;

var scene = CrapLoader.parse(JSON_SCENE);
var H_table = 0.74295; // TODO: coordinate w/ server

var avatar = avatar || new THREE.Object3D();
avatar.position.y = 1.2;
avatar.position.z = 1.9;

var ballMeshes       = [],
    ballStripeMeshes = [];
var stickMesh, tipBody, toolRoot, tipMesh;
var stickShadow, stickShadowMesh;
var dynamicBodies,
    ballBodies;

var mouseParticleGroup = new SPE.Group({
    texture: {value: THREE.ImageUtils.loadTexture('images/particle.png')}
});
var mouseParticleEmitter = new SPE.Emitter({maxAge: {value: 0.5},
                                            position: {value: new THREE.Vector3(),
                                                       spread: new THREE.Vector3()},
                                            velocity: {value: new THREE.Vector3(0, 0, 0),
                                                       spread: new THREE.Vector3(0.3, 0.3, 0.3)},
                                            color: {value: [new THREE.Color('white'), new THREE.Color('red')]},
                                            size: {value: 0.1},
                                            particleCount: 50});
mouseParticleGroup.addEmitter(mouseParticleEmitter);
var mousePointer = mouseParticleGroup.mesh;

function onLoad() {
    "use strict";
    pyserver.log("starting poolvr...");

    pyserver.log("POOLVR.config =\n" + JSON.stringify(POOLVR.config, undefined, 2));

    POOLVR.config.keyboardCommands = POOLVR.keyboardCommands;
    POOLVR.config.gamepadCommands = POOLVR.gamepadCommands;

    app = new WebVRApplication("poolvr", avatar, scene, POOLVR.config);
    avatar.add(app.camera);
    scene.add(avatar);

    function lockChangeAlert() {
        if ( document.pointerLockElement || document.mozPointerLockElement || document.webkitPointerLockElement ) {
            pyserver.log('pointer lock status is now locked');
            mousePointer.visible = true;
        } else {
            pyserver.log('pointer lock status is now unlocked');
            mousePointer.visible = false;
        }
    }
    if (app.config.mouseEnabled) {
        if ("onpointerlockchange" in document) {
          document.addEventListener('pointerlockchange', lockChangeAlert, false);
        } else if ("onmozpointerlockchange" in document) {
          document.addEventListener('mozpointerlockchange', lockChangeAlert, false);
        } else if ("onwebkitpointerlockchange" in document) {
          document.addEventListener('webkitpointerlockchange', lockChangeAlert, false);
        }
        avatar.add(mousePointer);
        mousePointer.position.set(0, 0, -2);
        app.mousePointer = mousePointer;
        app.mouseParticleGroup = mouseParticleGroup;
        var xMax = 2, xMin = -2,
            yMax = 1, yMin = -1;
        window.addEventListener("mousemove", function (evt) {
            if (!mousePointer.visible) return;
            var dx = evt.movementX,
                dy = evt.movementY;
            mousePointer.position.x += 0.0004*dx;
            mousePointer.position.y -= 0.0004*dy;
            if (mousePointer.position.x > xMax) mousePointer.position.x = xMax;
            else if (mousePointer.position.x < xMin) mousePointer.position.x = xMin;
            if (mousePointer.position.y > yMax) mousePointer.position.y = yMax;
            else if (mousePointer.position.y < yMin) mousePointer.position.y = yMin;
        });
    }

    if (!app.config.useBasicMaterials) {
        // would rather add the spot lights via three.py generated JSON_SCENE, but I'm having problems getting shadows frm them:
        var centerSpotLight = new THREE.SpotLight(0xffffee, 1, 10, 90);
        centerSpotLight.position.set(0, 3, 0);
        centerSpotLight.castShadow = true;
        centerSpotLight.shadowCameraNear = 0.01;
        centerSpotLight.shadowCameraFar = 4;
        centerSpotLight.shadowCameraFov = 90;
        scene.add(centerSpotLight);
        // var centerSpotLightHelper = new THREE.SpotLightHelper(centerSpotLight);
        // scene.add(centerSpotLightHelper);
        // centerSpotLightHelper.visible = false;
    }

    CrapLoader.CANNONize(scene, app.world);

    // TODO: load from JSON config
    var ballMaterial            = new CANNON.Material();
    var ballBallContactMaterial = new CANNON.ContactMaterial(ballMaterial, ballMaterial, {restitution: 0.91, friction: 0.08});
    app.world.addContactMaterial(ballBallContactMaterial);
    var playableSurfaceMaterial            = new CANNON.Material();
    var ballPlayableSurfaceContactMaterial = new CANNON.ContactMaterial(ballMaterial, playableSurfaceMaterial, {restitution: 0.3, friction: 0.1});
    app.world.addContactMaterial(ballPlayableSurfaceContactMaterial);
    var cushionMaterial            = new CANNON.Material();
    var ballCushionContactMaterial = new CANNON.ContactMaterial(ballMaterial, cushionMaterial, {restitution: 0.8, friction: 0.4});
    app.world.addContactMaterial(ballCushionContactMaterial);
    var floorMaterial            = new CANNON.Material();
    var floorBallContactMaterial = new CANNON.ContactMaterial(floorMaterial, ballMaterial, {restitution: 0.88, friction: 0.4});
    app.world.addContactMaterial(floorBallContactMaterial);

    scene.traverse(function (node) {
        if (node.name.startsWith('ballMesh')) {
            node.body.material = ballMaterial;
            ballMeshes.push(node);
        }
        else if (node.name.startsWith('ballStripeMesh')) {
            ballStripeMeshes.push(node);
        }
        else if (node.name.startsWith('playableSurfaceMesh')) {
            node.body.material = playableSurfaceMaterial;
        }
        else if (node.name.endsWith('CushionMesh')) {
            node.body.material = cushionMaterial;
        }
        else if (node.name === 'floorMesh') {
            node.body.material = floorMaterial;
        }
    });

    var toolOptions = {
        // ##### Desktop mode (default): #####
        transformOptions : app.config.transformOptions || {vr: 'desktop'},
        leapDisabled     : app.config.leapDisabled,
        leapHandsDisabled: app.config.leapHandsDisabled,
        useBasicMaterials: app.config.useBasicMaterials,
        toolLength       : app.config.toolLength || 0.5,
        toolRadius       : app.config.toolRadius || 0.013
    };
    // if (app.config.leapVR) {
    //     // ##### Leap Motion VR tracking mode: #####
    //     toolOptions.transformOptions = {vr: true, effectiveParent: app.camera};
    // }

    pyserver.log('adding tool...');
    pyserver.log('toolOptions =\n' + JSON.stringify(toolOptions, undefined, 2));

    var toolStuff = addTool(avatar, app.world, toolOptions);
    stickMesh = toolStuff.stickMesh;
    tipMesh   = toolStuff.tipMesh;
    tipBody   = toolStuff.tipBody;
    toolRoot  = toolStuff.toolRoot;

    if (!app.config.shadowMap) {
        // create shadow mesh from projection:
        stickShadow = new THREE.Object3D();
        stickShadow.position.y = -avatar.position.y - toolRoot.position.y + H_table + 0.001;
        stickShadow.scale.set(1, 0.0004, 1);
        toolRoot.add(stickShadow);

        var stickShadowMaterial = new THREE.MeshBasicMaterial({color: 0x002200});

        var stickShadowGeom = stickMesh.geometry.clone();
        var toolLength = toolOptions.toolLength || 0.5;
        stickShadowGeom.translate(0, -toolLength / 2, 0); // have to do this again because not buffergeometry???

        stickShadowMesh = new THREE.Mesh(stickShadowGeom, stickShadowMaterial);
        stickShadowMesh.quaternion.copy(stickMesh.quaternion);
        stickShadow.add(stickShadowMesh);

        tipMesh.geometry.computeBoundingSphere();
        var tipShadowGeom = new THREE.CircleBufferGeometry(tipMesh.geometry.boundingSphere.radius).rotateX(-Math.PI / 2);
        var tipShadowMesh = new THREE.Mesh(tipShadowGeom, stickShadowMaterial);
        stickShadow.add(tipShadowMesh);
    }

    dynamicBodies = app.world.bodies.filter(function(body) { return body.mesh && body.type !== CANNON.Body.STATIC; });
    ballBodies = dynamicBodies.filter(function(body) { return body.mesh.name.startsWith('ballMesh'); });

    var ballBallBuffer;
    var request = new XMLHttpRequest();
    request.responseType = 'arraybuffer';
    request.open('GET', 'sounds/ballBall.ogg', true);
    request.onload = function() {
        app.audioContext.decodeAudioData(request.response).then(function(buffer) {
            ballBallBuffer = buffer;
        });
    };
    request.send();
    app.playCollisionSound = function () {
        var source = app.audioContext.createBufferSource();
        source.connect(app.gainNode);
        source.buffer = ballBallBuffer;
        source.start(0);
    };

    app.start(animate);
}

var UP = new THREE.Vector3(0, 1, 0),
    RIGHT = new THREE.Vector3(1, 0, 0),
    pitchQuat = new THREE.Quaternion(),
    headingQuat = new THREE.Quaternion(),
    strafe,
    drive,
    floatUp,
    walkSpeed = 0.3,
    floatSpeed = 0.1,
    toolDrive, toolStrafe, toolFloat;
var raycaster = new THREE.Raycaster();
function animate(t) {
    "use strict";
    requestAnimationFrame(animate);
    var dt = (t - app.lt) * 0.001;
    app.lt = t;
    if (app.vrControls.enabled) {
        app.vrControls.update();
    }
    app.vrManager.render(app.scene, app.camera, t);
    app.keyboard.update(dt);
    app.gamepad.update(dt);

    floatUp = app.keyboard.getValue("floatUp") + app.keyboard.getValue("floatDown");
    drive = app.keyboard.getValue("driveBack") + app.keyboard.getValue("driveForward");
    strafe = app.keyboard.getValue("strafeRight") + app.keyboard.getValue("strafeLeft");
    avatar.heading += -0.8 * dt * (app.keyboard.getValue("turnLeft") + app.keyboard.getValue("turnRight"));
    if (avatar.floatMode) {
        floatUp += app.gamepad.getValue("float");
        strafe += app.gamepad.getValue("strafe");
    } else {
        drive += app.gamepad.getValue("drive");
        avatar.heading += 0.8 * dt * app.gamepad.getValue("dheading");
    }
    var cosHeading = Math.cos(avatar.heading),
        sinHeading = Math.sin(avatar.heading);
    if (!app.vrControls.enabled) {
        avatar.pitch -= 0.8 * dt * (app.keyboard.getValue("pitchUp") + app.keyboard.getValue("pitchDown"));
        pitchQuat.setFromAxisAngle(RIGHT, avatar.pitch);
    }
    var cosPitch = Math.cos(avatar.pitch),
        sinPitch = Math.sin(avatar.pitch);
    floatUp *= floatSpeed;
    if (strafe || drive) {
        var len = walkSpeed * Math.min(1, 1 / Math.sqrt(drive * drive +
            strafe * strafe));
        strafe *= len;
        drive *= len;
    } else {
        strafe = 0;
        drive = 0;
    }

    toolDrive = app.keyboard.getValue("moveToolForwards") - app.keyboard.getValue("moveToolBackwards");
    toolFloat = app.keyboard.getValue("moveToolUp") - app.keyboard.getValue("moveToolDown");
    toolStrafe = app.keyboard.getValue("moveToolRight") - app.keyboard.getValue("moveToolLeft");
    toolStrafe += app.gamepad.getValue("toolStrafe");
    if (avatar.toolMode) {
        toolFloat += app.gamepad.getValue("toolFloat");
    } else {
        toolDrive -= app.gamepad.getValue("toolDrive");
    }

    // TODO: resolve CANNON issues w/ initial low framerate
    app.world.step(Math.min(dt, 1/60));

    for (var j = 0; j < dynamicBodies.length; ++j) {
        var body = dynamicBodies[j];
        body.mesh.position.copy(body.position);
    }

    for (j = 0; j < ballStripeMeshes.length; j++) {
        var mesh = ballStripeMeshes[j];
        mesh.quaternion.copy(mesh.parent.body.quaternion);
    }

    avatar.quaternion.setFromAxisAngle(UP, avatar.heading);
    avatar.quaternion.multiply(pitchQuat);
    avatar.position.x += dt * (strafe * cosHeading + drive * sinHeading);
    avatar.position.z += dt * (drive * cosHeading - strafe * sinHeading);
    avatar.position.y += dt * floatUp;

    toolRoot.position.x += 0.25  * dt * toolStrafe;
    toolRoot.position.z += -0.25 * dt * toolDrive;
    toolRoot.position.y += 0.25  * dt * toolFloat;

    if (!app.config.shadowMap) {
        // if (tipBody.position[1] > H_table - 0.0666) {
            stickShadow.position.set(stickMesh.position.x,
                                     H_table + 0.001 - toolRoot.position.y - avatar.position.y,
                                     stickMesh.position.z);
            stickShadowMesh.quaternion.copy(stickMesh.quaternion);
        // }
    }

    for (j = 0; j < app.world.contacts.length; j++) {
        var contactEquation = app.world.contacts[j];
        var bi = contactEquation.bi,
            bj = contactEquation.bj;
        if (bi.material === bj.material) {
            app.playCollisionSound();
        }
    }

    if (app.mouseParticleGroup) app.mouseParticleGroup.tick(dt);

}

    // if (app.mousePointer && avatar.picking) {
    //     origin.set(0, 0, 0);
    //     direction.set(0, 0, 0);
    //     direction.subVectors(mousePointer.localToWorld(direction), camera.localToWorld(origin)).normalize();
    //     raycaster.set(origin, direction);
    //     var intersects = raycaster.intersectObjects(app.pickables);
    //     if (intersects.length > 0) {
    //         if (app.picked != intersects[0].object) {
    //             if (app.picked) app.picked.material.color.setHex(app.picked.currentHex);
    //             app.picked = intersects[0].object;
    //             app.picked.currentHex = app.picked.material.color.getHex();
    //             app.picked.material.color.setHex(0xff4444); //0x44ff44);
    //         }
    //     } else {
    //         if (app.picked) app.picked.material.color.setHex(app.picked.currentHex);
    //         app.picked = null;
    //     }
    // }

<|endoftext|>


<commit_before>import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {removeExpense, addExpense, fetchExpenses} from './actions/index';
import moment from 'moment';
const css = require('./stylesheets/style.scss');
import { Link, withRouter } from 'react-router-dom';
import firebase from 'firebase';

import ExpenseItem from './components/expense-item';
import ExpenseItemLoading from './components/expense-item-loading';

class App extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      expenses: []
    }
    this.fetchExpenses = this.fetchExpenses.bind(this);
    this.categoryIcon = this.categoryIcon.bind(this);
  }
  componentDidMount(){
    this.fetchExpenses();
  }
  componentWillUnmount(){
    var ref = firebase.database().ref('expenses');
    ref.off();
  }
  removeExpense(key){
    this.props.removeExpense(key);
  }
  // Load Initial Data
  fetchExpenses(){
    var ref = firebase.database().ref('expenses');
    var self = this;
    ref.orderByChild('-id').limitToLast(10).on('value', snapshot => {
      var expenseData = [];
      snapshot.forEach(function(childSnapshot) {
        var childData = childSnapshot.val();
        expenseData.push(childData);
      });
      self.setState({expenses: expenseData}, function(){
        console.log(self.state.expenses);
      });
    })
  }
  // Goto Details Page
  gotoDetails(id){
    this.props.history.push(`/expense-details/${ id }`);
  }
  categoryIcon(icon){
    console.log("hi--");
    switch(icon) {
      case 'books':
        return "book";
      case 'cloths':
        return "restaurant_menu";
      case 'electricity':
        return "restaurant_menu";
      case 'food':
        return "restaurant_menu";
      case 'fruits':
        return "restaurant_menu";
      case 'grocery':
        return "local_grocery_store";
      case 'internet':
        return "wifi_tethering";
      case 'mobile':
        return "stay_current_portrait";
      case 'travelling':
        return "directions_bus";
      case 'uncategorized':
        return "local_offer";
      case 'vegetables':
        return "local_mall";
      default:
        return "local_offer";
     }
  }

  render(){
    let expenseArr = this.state.expenses;
    let renderExpenseItems;
    if(expenseArr.length < 1){
      renderExpenseItems = <ExpenseItemLoading />
    }else{
      renderExpenseItems = expenseArr.map((item) => (
        <ExpenseItem key={item.id} data={item} setCategoryIcon={this.categoryIcon}/>
      ))
    }
    return(

              Payee
              Date
              Comment
              Amount

            {renderExpenseItems}

    );
  }
}

function mapStateToProps(state) {
  return {
    expense: state
  };
}

function mapDispatchToProps(dispatch) {
  return (
    bindActionCreators({
      removeExpense : removeExpense
    }, dispatch)
  )
}
export default connect(mapStateToProps,mapDispatchToProps)(App);<commit_msg>Testing Firebase orderbychild<commit_after>import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {removeExpense, addExpense, fetchExpenses} from './actions/index';
import moment from 'moment';
const css = require('./stylesheets/style.scss');
import { Link, withRouter } from 'react-router-dom';
import firebase from 'firebase';

import ExpenseItem from './components/expense-item';
import ExpenseItemLoading from './components/expense-item-loading';

class App extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      expenses: []
    }
    this.fetchExpenses = this.fetchExpenses.bind(this);
    this.categoryIcon = this.categoryIcon.bind(this);
  }
  componentDidMount(){
    this.fetchExpenses();
  }
  componentWillUnmount(){
    var ref = firebase.database().ref('expenses');
    ref.off();
  }
  removeExpense(key){
    this.props.removeExpense(key);
  }
  // Load Initial Data
  fetchExpenses(){
    var ref = firebase.database().ref('expenses');
    var self = this;
    ref.orderByChild('date').limitToLast(10).on('value', snapshot => {
      var expenseData = [];
      snapshot.forEach(function(childSnapshot) {
        var childData = childSnapshot.val();
        expenseData.push(childData);
      });
      self.setState({expenses: expenseData}, function(){
        console.log(self.state.expenses);
      });
    })
  }
  // Goto Details Page
  gotoDetails(id){
    this.props.history.push(`/expense-details/${ id }`);
  }
  categoryIcon(icon){
    console.log("hi--");
    switch(icon) {
      case 'books':
        return "book";
      case 'cloths':
        return "restaurant_menu";
      case 'electricity':
        return "restaurant_menu";
      case 'food':
        return "restaurant_menu";
      case 'fruits':
        return "restaurant_menu";
      case 'grocery':
        return "local_grocery_store";
      case 'internet':
        return "wifi_tethering";
      case 'mobile':
        return "stay_current_portrait";
      case 'travelling':
        return "directions_bus";
      case 'uncategorized':
        return "local_offer";
      case 'vegetables':
        return "local_mall";
      default:
        return "local_offer";
     }
  }

  render(){
    let expenseArr = this.state.expenses;
    let renderExpenseItems;
    if(expenseArr.length < 1){
      renderExpenseItems = <ExpenseItemLoading />
    }else{
      renderExpenseItems = expenseArr.map((item) => (
        <ExpenseItem key={item.id} data={item} setCategoryIcon={this.categoryIcon}/>
      ))
    }
    return(

              Payee
              Date
              Comment
              Amount

            {renderExpenseItems}

    );
  }
}

function mapStateToProps(state) {
  return {
    expense: state
  };
}

function mapDispatchToProps(dispatch) {
  return (
    bindActionCreators({
      removeExpense : removeExpense
    }, dispatch)
  )
}
export default connect(mapStateToProps,mapDispatchToProps)(App);<|endoftext|>


<commit_before>'use strict';

const apiai = require('apiai');
const express = require('express');
const bodyParser = require('body-parser');
const uuid = require('node-uuid');
const request = require('request');
const JSONbig = require('json-bigint');
const async = require('async');

const REST_PORT = (process.env.PORT || 5000);
const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN;
const APIAI_LANG = process.env.APIAI_LANG || 'en';
const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN;

const apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"});
const sessionIds = new Map();

function processEvent(event) {
    var sender = event.sender.id.toString();

    if ((event.message && event.message.text) || (event.postback && event.postback.payload)) {
        var text = event.message ? event.message.text : event.postback.payload;
        // Handle a text message from this sender

        if (!sessionIds.has(sender)) {
            sessionIds.set(sender, uuid.v1());
        }

        console.log("Text", text);

        let apiaiRequest = apiAiService.textRequest(text,
            {
                sessionId: sessionIds.get(sender)
            });

        apiaiRequest.on('response', (response) => {
            if (isDefined(response.result)) {
                //asd
                let responseText = response.result.fulfillment.speech;
                let responseData = response.result.fulfillment.data;
                let action = response.result.action;
                console.log(responseText);
                console.log(responseData);
                console.log(action);
                if (isDefined(responseData) && isDefined(responseData.facebook)) {
                    if (!Array.isArray(responseData.facebook)) {
                        try {
                            console.log('Response as formatted message');
                            sendFBMessage(sender, responseData.facebook);
                        } catch (err) {
                            sendFBMessage(sender, {text: err.message});
                        }
                    } else {
                        responseData.facebook.forEach((facebookMessage) => {
                            try {
                                if (facebookMessage.sender_action) {
                                    console.log('Response as sender action');
                                    sendFBSenderAction(sender, facebookMessage.sender_action);
                                }
                                else {
                                    console.log('Response as formatted message');
                                    sendFBMessage(sender, facebookMessage);
                                }
                            } catch (err) {
                                sendFBMessage(sender, {text: err.message});
                            }
                        });
                    }
                //} else if (isDefined(responseText)) {
                } else if (isDefined(action) && isDefined(responseText)) {
                    console.log('Response as text message');
                    // facebook API limit for text length is 320,
                    // so we must split message if needed
                    var splittedText = splitResponse(responseText);
                    switch (action){
                        case 'show_prod':
                            console.log('generic');
                            async.eachSeries(splittedText, (textPart, callback) => {
                                sendFBMessage(sender, {text: textPart}, callback);
                            });
                            const generic_message = {
                                attachment: {
                                    type: "template",
                                    payload: {
                                        template_type: "generic",
                                        elements: [{
                                            title: "Margarita",
                                            subtitle: "Be carefull and don't eat your fingers!!!",
                                            item_url: "https://en.wikipedia.org/wiki/Pizza",
                                            image_url: "http://www.cbc.ca/inthekitchen/assets_c/2012/11/MargheritaPizza21-thumb-596x350-247022.jpg",
                                            buttons: [{
                                                type: "web_url",
                                                url: "https://en.wikipedia.org/wiki/Pizza",
                                                title: "Open Web URL"
                                            }/*, {
                                             type: "postback",
                                             title: "Call Postback",
                                             payload: "Payload for first bubble"
                                             }*/]
                                        }]
                                    }
                                }
                            };
                            sendFBMessage(sender, generic_message, null);
                            break;
                        default:
                            console.log('default');
                            async.eachSeries(splittedText, (textPart, callback) => {
                                sendFBMessage(sender, {text: textPart}, callback);
                            });
                    }
                }

            }
        });

        apiaiRequest.on('error', (error) => console.error(error));
        apiaiRequest.end();
    }
}

function splitResponse(str) {
    if (str.length <= 320) {
        return [str];
    }

    return chunkString(str, 300);
}

function chunkString(s, len) {
    var curr = len, prev = 0;

    var output = [];

    while (s[curr]) {
        if (s[curr++] == ' ') {
            output.push(s.substring(prev, curr));
            prev = curr;
            curr += len;
        }
        else {
            var currReverse = curr;
            do {
                if (s.substring(currReverse - 1, currReverse) == ' ') {
                    output.push(s.substring(prev, currReverse));
                    prev = currReverse;
                    curr = currReverse + len;
                    break;
                }
                currReverse--;
            } while (currReverse > prev)
        }
    }
    output.push(s.substr(prev));
    //console.log(output);
    //output = ['Length of param message[text] must be less than or equal to 320'];
    return output;
}

/*const generic_message = {
    attachment: {
        type: "template",
        payload: {
            template_type: "generic",
            elements: [{
                title: "rift",
                subtitle: "Next-generation virtual reality",
                item_url: "https://www.oculus.com/en-us/rift/",
                image_url: "http://messengerdemo.parseapp.com/img/rift.png",
                buttons: [{
                    type: "web_url",
                    url: "https://www.oculus.com/en-us/rift/",
                    title: "Open Web URL"
                }, {
                    type: "postback",
                    title: "Call Postback",
                    payload: "Payload for first bubble"
                }]
            }, {
                title: "touch",
                subtitle: "Your Hands, Now in VR",
                item_url: "https://www.oculus.com/en-us/touch/",
                image_url: "http://messengerdemo.parseapp.com/img/touch.png",
                buttons: [{
                    type: "web_url",
                    url: "https://www.oculus.com/en-us/touch/",
                    title: "Open Web URL"
                }, {
                    type: "postback",
                    title: "Call Postback",
                    payload: "Payload for second bubble"
                }]
            }]
        }
    }
};*/

function sendFBMessage(sender, messageData, callback) {
    //console.log(sender);
    request({
        url: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token: FB_PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: sender},
            message: messageData
            //message: generic_message
        }
    }, (error, response, body) => {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }

        if (callback) {
            callback();
        }
    });
}

function sendFBSenderAction(sender, action, callback) {
    setTimeout(() => {
        request({
            url: 'https://graph.facebook.com/v2.6/me/messages',
            qs: {access_token: FB_PAGE_ACCESS_TOKEN},
            method: 'POST',
            json: {
                recipient: {id: sender},
                sender_action: action
            }
        }, (error, response, body) => {
            if (error) {
                console.log('Error sending action: ', error);
            } else if (response.body.error) {
                console.log('Error: ', response.body.error);
            }
            if (callback) {
                callback();
            }
        });
    }, 1000);
}

function doSubscribeRequest() {
    request({
            method: 'POST',
            uri: "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" + FB_PAGE_ACCESS_TOKEN
        },
        (error, response, body) => {
            if (error) {
                console.error('Error while subscription: ', error);
            } else {
                console.log('Subscription result: ', response.body);
            }
        });
}

function isDefined(obj) {
    if (typeof obj == 'undefined') {
        return false;
    }

    if (!obj) {
        return false;
    }

    return obj != null;
}

const app = express();

app.use(bodyParser.text({type: 'application/json'}));

app.get('/webhook/', (req, res) => {
    if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) {
        res.send(req.query['hub.challenge']);

        setTimeout(() => {
            doSubscribeRequest();
        }, 3000);
    } else {
        res.send('Error, wrong validation token');
    }
});

app.post('/webhook/', (req, res) => {
    try {
        var data = JSONbig.parse(req.body);
        var asd = data;
        console.log(asd);
        if (data.entry) {
            let entries = data.entry;
            entries.forEach((entry) => {
                let messaging_events = entry.messaging;
                if (messaging_events) {
                    messaging_events.forEach((event) => {
                        if (event.message && !event.message.is_echo ||
                            event.postback && event.postback.payload) {
                            processEvent(event);
                        }
                    });
                }
            });
        }

        return res.status(200).json({
            status: "ok"
        });
    } catch (err) {
        return res.status(400).json({
            status: "error",
            error: err
        });
    }

});

app.post('/webhook_apiai/', (req, res) => {
    try {
        var data = JSONbig.parse(req.body);
        console.log(data);

        return res.status(200).json({
            speech: data.result.resolvedQuery,
            displayText: 'displayText',
            /*data: {
                facebook: 'asd'
            }*/
        })
    } catch (err) {
        return res.status(400).json({
            status: "error",
            error: err
        });
    }
});

app.listen(REST_PORT, () => {
    console.log('Rest service ready on port ' + REST_PORT);
});

doSubscribeRequest();
<commit_msg>'webhook_test'<commit_after>'use strict';

const apiai = require('apiai');
const express = require('express');
const bodyParser = require('body-parser');
const uuid = require('node-uuid');
const request = require('request');
const JSONbig = require('json-bigint');
const async = require('async');

const REST_PORT = (process.env.PORT || 5000);
const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN;
const APIAI_LANG = process.env.APIAI_LANG || 'en';
const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN;

const apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"});
const sessionIds = new Map();

function processEvent(event) {
    var sender = event.sender.id.toString();

    if ((event.message && event.message.text) || (event.postback && event.postback.payload)) {
        var text = event.message ? event.message.text : event.postback.payload;
        // Handle a text message from this sender

        if (!sessionIds.has(sender)) {
            sessionIds.set(sender, uuid.v1());
        }

        console.log("Text", text);

        let apiaiRequest = apiAiService.textRequest(text,
            {
                sessionId: sessionIds.get(sender)
            });

        apiaiRequest.on('response', (response) => {
            if (isDefined(response.result)) {
                //asd
                let responseText = response.result.fulfillment.speech;
                let responseData = response.result.fulfillment.data;
                let action = response.result.action;
                console.log(responseText);
                console.log(responseData);
                console.log(action);
                if (isDefined(responseData) && isDefined(responseData.facebook)) {
                    if (!Array.isArray(responseData.facebook)) {
                        try {
                            console.log('Response as formatted message');
                            sendFBMessage(sender, responseData.facebook);
                        } catch (err) {
                            sendFBMessage(sender, {text: err.message});
                        }
                    } else {
                        responseData.facebook.forEach((facebookMessage) => {
                            try {
                                if (facebookMessage.sender_action) {
                                    console.log('Response as sender action');
                                    sendFBSenderAction(sender, facebookMessage.sender_action);
                                }
                                else {
                                    console.log('Response as formatted message');
                                    sendFBMessage(sender, facebookMessage);
                                }
                            } catch (err) {
                                sendFBMessage(sender, {text: err.message});
                            }
                        });
                    }
                //} else if (isDefined(responseText)) {
                } else if (isDefined(action) && isDefined(responseText)) {
                    console.log('Response as text message');
                    // facebook API limit for text length is 320,
                    // so we must split message if needed
                    var splittedText = splitResponse(responseText);
                    switch (action){
                        case 'show_prod':
                            console.log('generic');
                            async.eachSeries(splittedText, (textPart, callback) => {
                                sendFBMessage(sender, {text: textPart}, callback);
                            });
                            const generic_message = {
                                attachment: {
                                    type: "template",
                                    payload: {
                                        template_type: "generic",
                                        elements: [{
                                            title: "Margarita",
                                            subtitle: "Be carefull and don't eat your fingers!!!",
                                            item_url: "https://en.wikipedia.org/wiki/Pizza",
                                            image_url: "http://www.cbc.ca/inthekitchen/assets_c/2012/11/MargheritaPizza21-thumb-596x350-247022.jpg",
                                            buttons: [{
                                                type: "web_url",
                                                url: "https://en.wikipedia.org/wiki/Pizza",
                                                title: "Open Web URL"
                                            }/*, {
                                             type: "postback",
                                             title: "Call Postback",
                                             payload: "Payload for first bubble"
                                             }*/]
                                        }]
                                    }
                                }
                            };
                            sendFBMessage(sender, generic_message, null);
                            break;
                        default:
                            console.log('default');
                            async.eachSeries(splittedText, (textPart, callback) => {
                                sendFBMessage(sender, {text: textPart}, callback);
                            });
                    }
                }

            }
        });

        apiaiRequest.on('error', (error) => console.error(error));
        apiaiRequest.end();
    }
}

function splitResponse(str) {
    if (str.length <= 320) {
        return [str];
    }

    return chunkString(str, 300);
}

function chunkString(s, len) {
    var curr = len, prev = 0;

    var output = [];

    while (s[curr]) {
        if (s[curr++] == ' ') {
            output.push(s.substring(prev, curr));
            prev = curr;
            curr += len;
        }
        else {
            var currReverse = curr;
            do {
                if (s.substring(currReverse - 1, currReverse) == ' ') {
                    output.push(s.substring(prev, currReverse));
                    prev = currReverse;
                    curr = currReverse + len;
                    break;
                }
                currReverse--;
            } while (currReverse > prev)
        }
    }
    output.push(s.substr(prev));
    //console.log(output);
    //output = ['Length of param message[text] must be less than or equal to 320'];
    return output;
}

/*const generic_message = {
    attachment: {
        type: "template",
        payload: {
            template_type: "generic",
            elements: [{
                title: "rift",
                subtitle: "Next-generation virtual reality",
                item_url: "https://www.oculus.com/en-us/rift/",
                image_url: "http://messengerdemo.parseapp.com/img/rift.png",
                buttons: [{
                    type: "web_url",
                    url: "https://www.oculus.com/en-us/rift/",
                    title: "Open Web URL"
                }, {
                    type: "postback",
                    title: "Call Postback",
                    payload: "Payload for first bubble"
                }]
            }, {
                title: "touch",
                subtitle: "Your Hands, Now in VR",
                item_url: "https://www.oculus.com/en-us/touch/",
                image_url: "http://messengerdemo.parseapp.com/img/touch.png",
                buttons: [{
                    type: "web_url",
                    url: "https://www.oculus.com/en-us/touch/",
                    title: "Open Web URL"
                }, {
                    type: "postback",
                    title: "Call Postback",
                    payload: "Payload for second bubble"
                }]
            }]
        }
    }
};*/

function sendFBMessage(sender, messageData, callback) {
    //console.log(sender);
    request({
        url: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token: FB_PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: sender},
            message: messageData
            //message: generic_message
        }
    }, (error, response, body) => {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }

        if (callback) {
            callback();
        }
    });
}

function sendFBSenderAction(sender, action, callback) {
    setTimeout(() => {
        request({
            url: 'https://graph.facebook.com/v2.6/me/messages',
            qs: {access_token: FB_PAGE_ACCESS_TOKEN},
            method: 'POST',
            json: {
                recipient: {id: sender},
                sender_action: action
            }
        }, (error, response, body) => {
            if (error) {
                console.log('Error sending action: ', error);
            } else if (response.body.error) {
                console.log('Error: ', response.body.error);
            }
            if (callback) {
                callback();
            }
        });
    }, 1000);
}

function doSubscribeRequest() {
    request({
            method: 'POST',
            uri: "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" + FB_PAGE_ACCESS_TOKEN
        },
        (error, response, body) => {
            if (error) {
                console.error('Error while subscription: ', error);
            } else {
                console.log('Subscription result: ', response.body);
            }
        });
}

function isDefined(obj) {
    if (typeof obj == 'undefined') {
        return false;
    }

    if (!obj) {
        return false;
    }

    return obj != null;
}

const app = express();

app.use(bodyParser.text({type: 'application/json'}));

app.get('/webhook/', (req, res) => {
    if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) {
        res.send(req.query['hub.challenge']);

        setTimeout(() => {
            doSubscribeRequest();
        }, 3000);
    } else {
        res.send('Error, wrong validation token');
    }
});

app.post('/webhook/', (req, res) => {
    try {
        var data = JSONbig.parse(req.body);
        var asd = data;
        console.log(asd);
        if (data.entry) {
            let entries = data.entry;
            entries.forEach((entry) => {
                let messaging_events = entry.messaging;
                if (messaging_events) {
                    messaging_events.forEach((event) => {
                        console.log(event);
                        if (event.message && !event.message.is_echo ||
                            event.postback && event.postback.payload) {
                            processEvent(event);
                        }
                    });
                }
            });
        }

        return res.status(200).json({
            status: "ok"
        });
    } catch (err) {
        return res.status(400).json({
            status: "error",
            error: err
        });
    }

});

app.post('/webhook_apiai/', (req, res) => {
    try {
        var data = JSONbig.parse(req.body);
        console.log(data);

        return res.status(200).json({
            speech: data.result.resolvedQuery,
            displayText: 'displayText',
            /*data: {
                facebook: 'asd'
            }*/
        })
    } catch (err) {
        return res.status(400).json({
            status: "error",
            error: err
        });
    }
});

app.listen(REST_PORT, () => {
    console.log('Rest service ready on port ' + REST_PORT);
});

doSubscribeRequest();
<|endoftext|>


<commit_before>import 'es6-promise';
import 'whatwg-fetch';
import React from 'react';
import ReactDOM from 'react-dom';
import { applyMiddleware, combineReducers, createStore } from 'redux';
import { Provider } from 'react-redux';
import logger from 'redux-logger';
import thunk from 'redux-thunk';

import AppContainer from './components/App/Container';
import * as Socket from './utils/Socket';
import { get as readSession } from './utils/Session';
import { initState, setJWT } from './actions/LoginActionCreators';
import { startTicking } from './actions/TickerActionCreators';

import * as reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware(
  thunk,
  logger({
    // avoid log spam
    predicate: (getState, action) => action.type !== 'tick'
  })
)(createStore);
const store = createStoreWithMiddleware(
  combineReducers(reducers)
);

if (module.hot) {
  module.hot.accept('./reducers/index', () => {
    store.replaceReducer(require('./reducers/index').default);
  });
}

const jwt = readSession();
if (jwt) {
  store.dispatch(setJWT(jwt));
}

// Material-UI dependency
require('react-tap-event-plugin')();

ReactDOM.render(
  <Provider store={store}>
    <AppContainer />
  </Provider>,
  document.getElementById('app')
);

store.dispatch(initState());
store.dispatch(startTicking());

Socket.connect(store);

window.debug = require('debug');
<commit_msg>redux: fix reducer hot reloading<commit_after>import 'es6-promise';
import 'whatwg-fetch';
import React from 'react';
import ReactDOM from 'react-dom';
import { applyMiddleware, combineReducers, createStore } from 'redux';
import { Provider } from 'react-redux';
import logger from 'redux-logger';
import thunk from 'redux-thunk';

import AppContainer from './components/App/Container';
import * as Socket from './utils/Socket';
import { get as readSession } from './utils/Session';
import { initState, setJWT } from './actions/LoginActionCreators';
import { startTicking } from './actions/TickerActionCreators';

import * as reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware(
  thunk,
  logger({
    // avoid log spam
    predicate: (getState, action) => action.type !== 'tick'
  })
)(createStore);
const store = createStoreWithMiddleware(
  combineReducers(reducers)
);

if (module.hot) {
  module.hot.accept('./reducers', () => {
    store.replaceReducer(combineReducers(
      require('./reducers')
    ));
  });
}

const jwt = readSession();
if (jwt) {
  store.dispatch(setJWT(jwt));
}

// Material-UI dependency
require('react-tap-event-plugin')();

ReactDOM.render(
  <Provider store={store}>
    <AppContainer />
  </Provider>,
  document.getElementById('app')
);

store.dispatch(initState());
store.dispatch(startTicking());

Socket.connect(store);

window.debug = require('debug');
<|endoftext|>


<commit_before>function run($rootScope, errorService) {
  /*
   * Error handler - whenever we hit an error resolving data in a state function
   * this function is called to display an error to the user and allow them to
   * refresh the page.
   */
  $rootScope.$on('$stateChangeError', function(e, toState, toParams, fromState, fromParams, error) {
    errorService.showError(error);
  });

  /*
   * We make use of the state change success event to set the page title.
   */
  $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
    if (angular.isDefined(toState.data.pageTitle)) {
      $rootScope.pageTitle = toState.data.pageTitle + ' | Angular Template' ;
    }
  });
}

angular.module('angularTemplate', [
  'templates-app',
  'templates-common',
  'angularTemplate.home',
  'ngAnimate',
  'ngCookies',
  'ngMaterial',
  'ngSanitize',
  'ui.router',
  'errors',
  'dataFactory'])
  .config(function($urlRouterProvider) {
    $urlRouterProvider.otherwise('/home');
  })
  .run(run);
<commit_msg>Separate the config function into a separate named function<commit_after>function run($rootScope, errorService) {
  /*
   * Error handler - whenever we hit an error resolving data in a state function
   * this function is called to display an error to the user and allow them to
   * refresh the page.
   */
  $rootScope.$on('$stateChangeError', function(e, toState, toParams, fromState, fromParams, error) {
    errorService.showError(error);
  });

  /*
   * We make use of the state change success event to set the page title.
   */
  $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
    if (angular.isDefined(toState.data.pageTitle)) {
      $rootScope.pageTitle = toState.data.pageTitle + ' | Story Book' ;
    }
  });
}

function config($urlRouterProvider, $stateProvider) {
  $urlRouterProvider.otherwise('/home');

  $stateProvider.state('app', {
    url: '/',
    abstract: true,
    templateUrl: 'parent.tpl.html',
    controller: function () {

    },
    controllerAs: 'app'
  });
}

angular.module('angularTemplate', [
  'templates-app',
  'templates-common',
  'angularTemplate.home',
  'ngAnimate',
  'ngCookies',
  'ngMaterial',
  'ngSanitize',
  'ui.router',
  'errors',
  'dataFactory'])
  .config(config)
  .run(run);
<|endoftext|>


<commit_before>/**
 * Import Node Modules
 */
import {
  express,
  path,
  favicon,
  logger,
  cookieParser,
  bodyParser,
  compression
} from './modules';

/**
 * Import Routes
 */
import {
  api,
  root
} from './routes';

// app setup
const app = express();
const staticpath = path.join(
  __dirname, '../node_modules/codepix-client/lib/public'
);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

// uncomment after placing your favicon in /public
app.use(compression({level: 9}));
app.use(favicon(path.join(staticpath, 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(staticpath));
app.use('/c0dez/data', express.static('data'));
app.use('/api', function (req, res, next) {
  if (app.get('rasterizer')) {
    req.rasterizer = app.get('rasterizer');
  }
  next();
});
app.use('/api', api);
app.use('/', root);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stack-traces leaked to user
app.use(function (err, req, res) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>remove compression<commit_after>/**
 * Import Node Modules
 */
import {
  express,
  path,
  favicon,
  logger,
  cookieParser,
  bodyParser
  // compression
} from './modules';

/**
 * Import Routes
 */
import {
  api,
  root
} from './routes';

// app setup
const app = express();
const staticpath = path.join(
  __dirname, '../node_modules/codepix-client/lib/public'
);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

// uncomment after placing your favicon in /public
// app.use(compression({level: 9}));
app.use(favicon(path.join(staticpath, 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(staticpath));
app.use('/c0dez/data', express.static('data'));
app.use('/api', function (req, res, next) {
  if (app.get('rasterizer')) {
    req.rasterizer = app.get('rasterizer');
  }
  next();
});
app.use('/api', api);
app.use('/', root);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stack-traces leaked to user
app.use(function (err, req, res) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<|endoftext|>


<commit_before>(function () {
  'use strict';
  angular.module('fsClone', [
    'fsCloneShared',
    'templates-app',
    'templates-common',
    'ui.bootstrap',
    'ui.router.state',
    'ui.router'
  ])
    .config(function($stateProvider, $urlRouterProvider) {
      $urlRouterProvider.otherwise('/');
    })

    .config(function(fsApiProvider) {
      fsApiProvider
        .setAppKey('WCQY-7J1Q-GKVV-7DNM-SQ5M-9Q5H-JX3H-CMJK')
        .setEnvironmentName('sandbox')
        .setAuthCallback('http://localhost:9000/#!/auth');
        //.setEnvironmentName('beta')
        //.setAuthCallback('http://demo.werelate.org/#/auth');
    })

    .config(function(fsLocationProvider) {
      var prefix = '/#';
      fsLocationProvider.configure({
        getPersonLocation: function(personId) {
          return {
            prefix: prefix,
            path: '/person/'+personId
          };
        },
        getCoupleLocation: function(coupleId) {
          return {
            prefix: prefix,
            path: '/couple/'+coupleId
          };
        },
        getParentsLocation: function(parentsId) {
          return {
            prefix: prefix,
            path: '/parents/' + parentsId
          };
        },
        getTreeLocation: function(personId) {
          return {
            prefix: prefix,
            path: '/tree/'+personId
          };
        },
        getFindAddLocation: function(opts) {
          return {
            prefix: prefix,
            path: '/find-add',
            search: opts
          };
        },
        getSourceBoxLocation: function(opts) {
          return {
            prefix: prefix,
            path: '/source-box',
            search: opts
          };
        }
      });
    })

    .run(function () {
    })

    .controller('AppController', function ($scope) {
      $scope.environment = 'Sandbox';
      //$scope.environment = 'Beta';

      // don't forget to edit index.html to add {Track:js} script on demo

      $scope.$on('$stateChangeStart', function(event, toState) {
        if (toState.resolve) {
          $scope.busy = true;
        }
      });
      $scope.$on('$stateChangeSuccess', function(event, toState) {
        $scope.busy = false;
      });
      $scope.$on('$stateChangeError', function(event, toState) {
        $scope.busy = false;
      });

    });

})();
<commit_msg>remove unused variables<commit_after>(function () {
  'use strict';
  angular.module('fsClone', [
    'fsCloneShared',
    'templates-app',
    'templates-common',
    'ui.bootstrap',
    'ui.router.state',
    'ui.router'
  ])
    .config(function($stateProvider, $urlRouterProvider) {
      $urlRouterProvider.otherwise('/');
    })

    .config(function(fsApiProvider) {
      fsApiProvider
        .setAppKey('WCQY-7J1Q-GKVV-7DNM-SQ5M-9Q5H-JX3H-CMJK')
        .setEnvironmentName('sandbox')
        .setAuthCallback('http://localhost:9000/#!/auth');
        //.setEnvironmentName('beta')
        //.setAuthCallback('http://demo.werelate.org/#/auth');
    })

    .config(function(fsLocationProvider) {
      var prefix = '/#';
      fsLocationProvider.configure({
        getPersonLocation: function(personId) {
          return {
            prefix: prefix,
            path: '/person/'+personId
          };
        },
        getCoupleLocation: function(coupleId) {
          return {
            prefix: prefix,
            path: '/couple/'+coupleId
          };
        },
        getParentsLocation: function(parentsId) {
          return {
            prefix: prefix,
            path: '/parents/' + parentsId
          };
        },
        getTreeLocation: function(personId) {
          return {
            prefix: prefix,
            path: '/tree/'+personId
          };
        },
        getFindAddLocation: function(opts) {
          return {
            prefix: prefix,
            path: '/find-add',
            search: opts
          };
        },
        getSourceBoxLocation: function(opts) {
          return {
            prefix: prefix,
            path: '/source-box',
            search: opts
          };
        }
      });
    })

    .run(function () {
    })

    .controller('AppController', function ($scope) {
      $scope.environment = 'Sandbox';
      //$scope.environment = 'Beta';

      // don't forget to edit index.html to add {Track:js} script on demo

      $scope.$on('$stateChangeStart', function(event, toState) {
        if (toState.resolve) {
          $scope.busy = true;
        }
      });
      $scope.$on('$stateChangeSuccess', function() {
        $scope.busy = false;
      });
      $scope.$on('$stateChangeError', function() {
        $scope.busy = false;
      });

    });

})();
<|endoftext|>