<commit_before>/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = require('../../registry');
var Lib = require('../../lib');
var colorscaleDefaults = require('../../components/colorscale/defaults');
var attributes = require('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    // read in face/vertex properties
    function readComponents(array) {
        var ret = array.map(function(attr) {
            var result = coerce(attr);

            if(result && Lib.isArrayOrTypedArray(result)) return result;
            return null;
        });

        return ret.every(function(x) {
            return x && x.length === ret[0].length;
        }) && ret;
    }

    var coords = readComponents(['x', 'y', 'z']);
    var indices = readComponents(['i', 'j', 'k']);

    if(!coords) {
        traceOut.visible = false;
        return;
    }

    if(indices) {
        // otherwise, convert all face indices to ints
        indices.forEach(function(index) {
            for(var i = 0; i < index.length; ++i) index[i] |= 0;
        });
    }

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout);

    // Coerce remaining properties
    [
        'lighting.ambient',
        'lighting.diffuse',
        'lighting.specular',
        'lighting.roughness',
        'lighting.fresnel',
        'lighting.vertexnormalsepsilon',
        'lighting.facenormalsepsilon',
        'lightposition.x',
        'lightposition.y',
        'lightposition.z',
        'contour.show',
        'contour.color',
        'contour.width',
        'colorscale',
        'reversescale',
        'flatshading',
        'alphahull',
        'delaunayaxis',
        'opacity'
    ].forEach(function(x) { coerce(x); });

    if('intensity' in traceIn) {
        coerce('intensity');
        colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'});
    } else {
        traceOut.showscale = false;

        if('facecolor' in traceIn) coerce('facecolor');
        else if('vertexcolor' in traceIn) coerce('vertexcolor');
        else coerce('color', defaultColor);
    }

    coerce('text');

    // disable 1D transforms
    // x/y/z should match lengths, and i/j/k should match as well, but
    // the two sets have different lengths so transforms wouldn't work.
    traceOut._length = null;
};
<commit_msg>removed indices convert<commit_after>/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = require('../../registry');
var Lib = require('../../lib');
var colorscaleDefaults = require('../../components/colorscale/defaults');
var attributes = require('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    // read in face/vertex properties
    function readComponents(array) {
        var ret = array.map(function(attr) {
            var result = coerce(attr);

            if(result && Lib.isArrayOrTypedArray(result)) return result;
            return null;
        });

        return ret.every(function(x) {
            return x && x.length === ret[0].length;
        }) && ret;
    }

    var coords = readComponents(['x', 'y', 'z']);
    var indices = readComponents(['i', 'j', 'k']);

    if(!coords) {
        traceOut.visible = false;
        return;
    }

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout);

    // Coerce remaining properties
    [
        'lighting.ambient',
        'lighting.diffuse',
        'lighting.specular',
        'lighting.roughness',
        'lighting.fresnel',
        'lighting.vertexnormalsepsilon',
        'lighting.facenormalsepsilon',
        'lightposition.x',
        'lightposition.y',
        'lightposition.z',
        'contour.show',
        'contour.color',
        'contour.width',
        'colorscale',
        'reversescale',
        'flatshading',
        'alphahull',
        'delaunayaxis',
        'opacity'
    ].forEach(function(x) { coerce(x); });

    if('intensity' in traceIn) {
        coerce('intensity');
        colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'});
    } else {
        traceOut.showscale = false;

        if('facecolor' in traceIn) coerce('facecolor');
        else if('vertexcolor' in traceIn) coerce('vertexcolor');
        else coerce('color', defaultColor);
    }

    coerce('text');

    // disable 1D transforms
    // x/y/z should match lengths, and i/j/k should match as well, but
    // the two sets have different lengths so transforms wouldn't work.
    traceOut._length = null;
};
<|endoftext|>


<commit_before>$(function(){
    var socialBar = $('.social');
    $.get('https://graph.facebook.com/?id=' + socialBar.data('url'), function(data) {
        $('.facebook .count', socialBar).html(data['shares']);
    })
    .fail(function() {
        $('.facebook .count', socialBar).html('0');
    });
    $.getJSON('https://urls.api.twitter.com/1/urls/count.json?callback=?', {'url': socialBar.data('url')}, function(data) {
        $('.twitter .count', socialBar).html(data['count']);
    })
    .fail(function() {
        $('.twitter .count', socialBar).html('0');
    });

});
<commit_msg>Social share numbers URL fix.<commit_after>$(function(){
    var socialBar = $('.social[data-url]');
    $.get('https://graph.facebook.com/?id=' + socialBar.data('url'), function(data) {
        $('.facebook .count', socialBar).html(data['shares']);
    })
    .fail(function() {
        $('.facebook .count', socialBar).html('0');
    });
    $.getJSON('https://urls.api.twitter.com/1/urls/count.json?callback=?', {'url': socialBar.data('url')}, function(data) {
        $('.twitter .count', socialBar).html(data['count']);
    })
    .fail(function() {
        $('.twitter .count', socialBar).html('0');
    });

});
<|endoftext|>


<commit_before>SirTrevor.Blocks.Products = SirTrevor.Blocks.Abstract.extend({
  type: 'products',
  title: 'Products',
  blockHtml: _.template(
    `

Products

        ${SpreeCmsForm.getInputTemplate('new_sku', 'New SKU')}
        <button class="js-blockProductsAddSku">Add</button>

        <% if (data.products && data.products.length) { %>

                  SKU
                  Remove

              <% _.each(data.products, function(product, index) { %>

                  <%= product %>

              <% }); %>

        <% } %>

      <input class="js-blockProductsInputProducts js-scms-value" type="hidden" name="products" value="<%- data.products ? data.products.join(',') : '' %>">
      <input class="js-state" type="hidden" name="state" value="<%- state || "" %>">

`
  ),

  getProductList: function() {
    var list = this.getProductListInput().val().split(',');
    return list.filter(function(item) {
      return item !== '' && item !== null;
    });
  },

  getProductListInput: function() {
    return this.$editor.find('.js-blockProductsInputProducts');
  },

  loadData: function(data) {
    data.products = data.products ? data.products.split(',') : [];
    var renderedHtml = this.blockHtml({
      data: data,
      state: 'edited',
      header: this.header
    });

    this.$editor.html(renderedHtml).show();
    this.$editor.find('.js-blockProductsAddSku').click(this.onSkuAdd.bind(this));
    this.$editor.find('.js-blockProductsRemoveSku').click(this.onSkuRemove.bind(this));
    this.tableSortable();
  },

  onSkuAdd: function(ev) {
    ev.preventDefault();
    var sku = this.getData().data.new_sku;
    if (!sku) {
      return false;
    }
    sku = sku.trim();

    var productList = this.getProductList();
    if (productList.indexOf(sku) == -1) {
      productList.push(sku);
      this.$editor.find('[name="new_sku"]').val('');
      this.getProductListInput().val(productList.join(','));
      this.reRenderProductList();
    }
  },

  onSkuRemove: function(ev) {
    ev.preventDefault();
    var sku = ev.currentTarget.parentNode.parentNode.querySelector('.js-blockProductsSku').innerHTML;
    var productList = this.getProductList().filter(function(item) {
      return item !== sku;
    });

    this.getProductListInput().val(productList.join(','));
    this.reRenderProductList();
  },

  reRenderProductList() {
    var data = this.getData().data;
    data.products = $('.js-blockProductsInputProducts').val();
    this.loadData(data);
  },

  tableSortable() {
    // Based on spree_backend-3.3.2/app/assets/javascripts/spree/backend/admin.js:325
    var fixHelper = function(e, ui) {
      ui.children().each(function() {
          $(this).width($(this).width());
      });
      return ui;
    };

    var table = this.$editor.find('.js-blockProductsTable');
    var td_count = table.find('tbody tr:first-child td').length;
    var productListInput = this.getProductListInput();
    table.find('tbody').sortable(
      {
        handle: '.handle',
        helper: fixHelper,
        placeholder: 'ui-sortable-placeholder',
        update: function(event, ui) {
          var tbody = this;
          positions = {};
          $.each($('tr', tbody), function(position, obj){
            reg = /spree_(\w+_?)+_(\d+)/;
            parts = reg.exec($(obj).prop('id'));
            if (parts) {
              positions['positions['+parts[2]+']'] = position+1;
            }
          });
          var newProductList = $.map(table.find('.js-blockProductsSku'), function(el) {
            return el.innerHTML;
          });

          productListInput.val(newProductList.join(','));
        },
        start: function (event, ui) {
          // Set correct height for placehoder (from dragged tr)
          ui.placeholder.height(ui.item.height())
          // Fix placeholder content to make it correct width
          ui.placeholder.html("		")
        },
        stop: function (event, ui) {
          // Fix odd/even classes after reorder
          table.find("tr:even").removeClass("odd even").addClass("even");
          table.find("tr:odd").removeClass("odd even").addClass("odd");
        }

      });
  }
});
<commit_msg>Read saved products from local editor<commit_after>SirTrevor.Blocks.Products = SirTrevor.Blocks.Abstract.extend({
  type: 'products',
  title: 'Products',
  blockHtml: _.template(
    `

Products

        ${SpreeCmsForm.getInputTemplate('new_sku', 'New SKU')}
        <button class="js-blockProductsAddSku">Add</button>

        <% if (data.products && data.products.length) { %>

                  SKU
                  Remove

              <% _.each(data.products, function(product, index) { %>

                  <%= product %>

              <% }); %>

        <% } %>

      <input class="js-blockProductsInputProducts js-scms-value" type="hidden" name="products" value="<%- data.products ? data.products.join(',') : '' %>">
      <input class="js-state" type="hidden" name="state" value="<%- state || "" %>">

`
  ),

  getProductList: function() {
    var list = this.getProductListInput().val().split(',');
    return list.filter(function(item) {
      return item !== '' && item !== null;
    });
  },

  getProductListInput: function() {
    return this.$editor.find('.js-blockProductsInputProducts');
  },

  loadData: function(data) {
    data.products = data.products ? data.products.split(',') : [];
    var renderedHtml = this.blockHtml({
      data: data,
      state: 'edited',
      header: this.header
    });

    this.$editor.html(renderedHtml).show();
    this.$editor.find('.js-blockProductsAddSku').click(this.onSkuAdd.bind(this));
    this.$editor.find('.js-blockProductsRemoveSku').click(this.onSkuRemove.bind(this));
    this.tableSortable();
  },

  onSkuAdd: function(ev) {
    ev.preventDefault();
    var sku = this.getData().data.new_sku;
    if (!sku) {
      return false;
    }
    sku = sku.trim();

    var productList = this.getProductList();
    if (productList.indexOf(sku) == -1) {
      productList.push(sku);
      this.$editor.find('[name="new_sku"]').val('');
      this.getProductListInput().val(productList.join(','));
      this.reRenderProductList();
    }
  },

  onSkuRemove: function(ev) {
    ev.preventDefault();
    var sku = ev.currentTarget.parentNode.parentNode.querySelector('.js-blockProductsSku').innerHTML;
    var productList = this.getProductList().filter(function(item) {
      return item !== sku;
    });

    this.getProductListInput().val(productList.join(','));
    this.reRenderProductList();
  },

  reRenderProductList() {
    var data = this.getData().data;
    data.products = this.$editor.find('.js-blockProductsInputProducts').val();
    this.loadData(data);
  },

  tableSortable() {
    // Based on spree_backend-3.3.2/app/assets/javascripts/spree/backend/admin.js:325
    var fixHelper = function(e, ui) {
      ui.children().each(function() {
          $(this).width($(this).width());
      });
      return ui;
    };

    var table = this.$editor.find('.js-blockProductsTable');
    var td_count = table.find('tbody tr:first-child td').length;
    var productListInput = this.getProductListInput();
    table.find('tbody').sortable(
      {
        handle: '.handle',
        helper: fixHelper,
        placeholder: 'ui-sortable-placeholder',
        update: function(event, ui) {
          var tbody = this;
          positions = {};
          $.each($('tr', tbody), function(position, obj){
            reg = /spree_(\w+_?)+_(\d+)/;
            parts = reg.exec($(obj).prop('id'));
            if (parts) {
              positions['positions['+parts[2]+']'] = position+1;
            }
          });
          var newProductList = $.map(table.find('.js-blockProductsSku'), function(el) {
            return el.innerHTML;
          });

          productListInput.val(newProductList.join(','));
        },
        start: function (event, ui) {
          // Set correct height for placehoder (from dragged tr)
          ui.placeholder.height(ui.item.height())
          // Fix placeholder content to make it correct width
          ui.placeholder.html("		")
        },
        stop: function (event, ui) {
          // Fix odd/even classes after reorder
          table.find("tr:even").removeClass("odd even").addClass("even");
          table.find("tr:odd").removeClass("odd even").addClass("odd");
        }

      });
  }
});
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  db: 'mongodb://localhost/mean-test',
  port: 3001,
  app: {
    name: 'MEAN - A Modern Stack - Test'
  },
  facebook: {
    clientID: 'APP_ID',
    clientSecret: 'APP_SECRET',
    callbackURL: 'http://localhost:3000/auth/facebook/callback'
  },
  twitter: {
    clientID: 'CONSUMER_KEY',
    clientSecret: 'CONSUMER_SECRET',
    callbackURL: 'http://localhost:3000/auth/twitter/callback'
  },
  github: {
    clientID: 'APP_ID',
    clientSecret: 'APP_SECRET',
    callbackURL: 'http://localhost:3000/auth/github/callback'
  },
  google: {
    clientID: 'APP_ID',
    clientSecret: 'APP_SECRET',
    callbackURL: 'http://localhost:3000/auth/google/callback'
  },
  linkedin: {
    clientID: 'API_KEY',
    clientSecret: 'SECRET_KEY',
    callbackURL: 'http://localhost:3000/auth/linkedin/callback'
  },
  emailFrom: 'SENDER EMAIL ADDRESS', // sender address like ABC <abc@example.com>
  mailer: {
    service: 'SERVICE_PROVIDER',
    auth: {
      user: 'EMAIL_ID',
      pass: 'PASSWORD'
    }
  }
};
<commit_msg>Trivial change to test Heroku deployment fix<commit_after>'use strict';

module.exports = {
  db: 'mongodb://localhost/mean-test',
  port: 3001,
  app: {
    name: 'Adopt a Street'
  },
  facebook: {
    clientID: 'APP_ID',
    clientSecret: 'APP_SECRET',
    callbackURL: 'http://localhost:3000/auth/facebook/callback'
  },
  twitter: {
    clientID: 'CONSUMER_KEY',
    clientSecret: 'CONSUMER_SECRET',
    callbackURL: 'http://localhost:3000/auth/twitter/callback'
  },
  github: {
    clientID: 'APP_ID',
    clientSecret: 'APP_SECRET',
    callbackURL: 'http://localhost:3000/auth/github/callback'
  },
  google: {
    clientID: 'APP_ID',
    clientSecret: 'APP_SECRET',
    callbackURL: 'http://localhost:3000/auth/google/callback'
  },
  linkedin: {
    clientID: 'API_KEY',
    clientSecret: 'SECRET_KEY',
    callbackURL: 'http://localhost:3000/auth/linkedin/callback'
  },
  emailFrom: 'SENDER EMAIL ADDRESS', // sender address like ABC <abc@example.com>
  mailer: {
    service: 'SERVICE_PROVIDER',
    auth: {
      user: 'EMAIL_ID',
      pass: 'PASSWORD'
    }
  }
};
<|endoftext|>


<commit_before>'use strict'

const net = require('net');
var express = require("express");
var bodyParser = require("body-parser");
var mongoose = require('mongoose');
var Promise = require('es6-promise').Promise;
let sockets = []

var app = express();
app.use(express.static(__dirname + "/app"));
app.use(bodyParser.json());

mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;

var userSchema = mongoose.Schema({
  name: String
});
var msgSchema = mongoose.Schema({
  msg: {
    type: String,
    default: ''
  },
  user: {
    type: mongoose.Schema.ObjectId,
    ref: 'StellaUser',
    required: true
  }
},
{ timestamps: true });
var User = mongoose.model('StellaUser', userSchema);
var Message = mongoose.model('StellaMessage', msgSchema);

db.once('open', function () {
  console.log('DB open!');

  const server = net.createServer((socket) => {
    // 'connection' listener
    socket.identity = socket.remoteAddress + ":" + socket.remotePort
    sockets.push(socket)
    console.log('New person in the chat room!' + socket.identity);

    socket.write('Welcome to the chat room');

    // socket.on('data', function(data){
    //   sockets.forEach(function(s){
    //     if (s == socket) return;
    //     //s.write(data);
    //   })
    // });
    // socket.on('end', (deadsocket) => {
    //   console.log('person left the room');
    //   let index = sockets.indexOf(deadsocket);
    //   sockets.splice(index, 1);
    // });

  });
  server.on('error', (err) => {
    throw err;
  });
  server.listen(8124, () => {
    console.log('Chat room is now open!!');
  });
  app.listen(8080, function () {
    console.log("App now running on port 8080");
  });

  function getUsersById(name, callback) {
    User.findOne({name: name}, function(err, obj) {
      if(err) { return callback(err, null); }
      if (obj == null){
        var newuser = new User({ name: name });
        newuser.save(function (err, user) {
          if (err) return callback(err, null);
          return callback(null, newuser);
        });
      }
      else {
        return callback(null, obj)
      }
    });
  }

  app.get('/', function (req, res) {
    res.sendfile(__dirname + '/app/index.html');
  });

  app.get('/messages', function(req, res){
    Message.find({}, {}, { sort: { 'createdAt' : -1 } }, function (err, messages) {
      if (err) return console.error(err);
      res.setHeader('Content-Type', 'application/json');
      res.send(JSON.stringify(messages));
    }).limit(6);
  })

  app.post('/messages', function(req, res){

    getUsersById(req.body.data.user, function(err, user){
      if (err == null){
        var newMessage = Message({
          msg: req.body.data.content,
          user: user.id
        });
        newMessage.save(function (err, fluffy) {
          if (err) return console.error(err);
          res.send({'status':'success'});
        });
      }
    });
  });
});
<commit_msg>tidy up<commit_after>'use strict'

const net = require('net');
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require('mongoose');
let sockets = []

var app = express();
app.use(express.static(__dirname + "/app"));
app.use(bodyParser.json());

mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;

var userSchema = mongoose.Schema({
  name: String
});
var msgSchema = mongoose.Schema({
  msg: {
    type: String,
    default: ''
  },
  user: {
    type: mongoose.Schema.ObjectId,
    ref: 'StellaUser',
    required: true
  }
},
{ timestamps: true });
var User = mongoose.model('StellaUser', userSchema);
var Message = mongoose.model('StellaMessage', msgSchema);

db.once('open', function () {
  console.log('DB open!');

  const server = net.createServer((socket) => {
    // 'connection' listener
    socket.identity = socket.remoteAddress + ":" + socket.remotePort
    sockets.push(socket)
    console.log('New person in the chat room!' + socket.identity);

    socket.write('Welcome to the chat room');

    // socket.on('data', function(data){
    //   sockets.forEach(function(s){
    //     if (s == socket) return;
    //     //s.write(data);
    //   })
    // });
    // socket.on('end', (deadsocket) => {
    //   console.log('person left the room');
    //   let index = sockets.indexOf(deadsocket);
    //   sockets.splice(index, 1);
    // });

  });
  server.on('error', (err) => {
    throw err;
  });
  server.listen(8124, () => {
    console.log('Chat room is now open!!');
  });
  app.listen(8080, function () {
    console.log("App now running on port 8080");
  });

  function getUsersById(name, callback) {
    User.findOne({name: name}, function(err, obj) {
      if(err) { return callback(err, null); }
      if (obj == null){
        var newuser = new User({ name: name });
        newuser.save(function (err, user) {
          if (err) return callback(err, null);
          return callback(null, newuser);
        });
      }
      else {
        return callback(null, obj)
      }
    });
  }

  app.get('/', function (req, res) {
    res.sendfile(__dirname + '/app/index.html');
  });

  app.get('/messages', function(req, res){
    Message.find({}, {}, { sort: { 'createdAt' : -1 } }, function (err, messages) {
      if (err) return console.error(err);
      res.setHeader('Content-Type', 'application/json');
      res.send(JSON.stringify(messages));
    }).limit(6);
  })

  app.post('/messages', function(req, res){

    getUsersById(req.body.data.user, function(err, user){
      if (err == null){
        var newMessage = Message({
          msg: req.body.data.content,
          user: user.id
        });
        newMessage.save(function (err, fluffy) {
          if (err) return console.error(err);
          res.send({'status':'success'});
        });
      }
    });
  });
});
<|endoftext|>


<commit_before>/**
 * @file - handle information from vip. @see openagency.addi.dk
 * Internally (DBC) we use vipcore : http://vipcore.iscrum-vip-prod.svc.cloud.dbc.dk:8080/1.0/api
 * For documentation @see https://dbcjira.atlassian.net/wiki/spaces/IS/pages/884998162/VipCore+API+beskrivelse
 *
 * Bssically this transformer gets ALL pickupagencies and orderparameters from vipcore. When a single
 * library/branch is requested it returns a filtered result of the pickupagencies.
 *
 */

import * as IsilUtils from './utils/isil.utils';

const timeout = 60 * 60 * 1000;
let cache;
let timestamp;

/**
 * Insert orderparameters in the list of pickupagencies.
 *
 * @param results
 *   all the pickupagencies retrieved from vipcore
 * @param agencyKeys
 *    agencyIds of all pickupagencies
 * @param orderParameters
 *    order parameters (eg. userid, username ...) to insert
 * @returns {*}
 */
function orderParameterPromiseHandler(results, agencyKeys, orderParameters) {
  const agencyOrderParameters = {};
  for (let i = 0; i < agencyKeys.length; ++i) {
    agencyOrderParameters[agencyKeys[i]] = orderParameters[i];
  }
  for (let i = 0; i < results.length; ++i) {
    results[i].orderParameters = agencyOrderParameters[results[i].agencyId];
  }
  cache = results;
  timestamp = Date.now();
  return results;
}

/**
 * Do a call to vipcore service endpoint
 * e.g http://vipcore.iscrum-vip-prod.svc.cloud.dbc.dk/1.0/api/service/710100/userOrderParameters/
 * Parse and return orderparamters from service
 *
 * @param context
 * @param agencyId
 * @returns {*}
 */
function getOrderParameters(context, agencyId) {
  const service = context.get('services.openagency');
  const path = `/service/${agencyId}/userOrderParameters/`;
  const api = service + path;

  return context.call(api, {}).then(response => {
    const result = [];

    // @TODO datacheck - service may return an error e.g service_unavailable

    let parameters = response.data.userOrderParameters.userParameter
      ? response.data.userOrderParameters.userParameter
      : null;

    // map selected parameters
    const parameterMap = {
      userName: 'name',
      userAddress: 'address',
      userMail: 'email',
      userTelephone: 'phone'
    };

    if (parameters) {
      for (let i = 0; i < parameters.length; ++i) {
        if (parameters[i].parameterRequired === true) {
          let parameter = parameters[i].userParameterType;
          parameter = parameterMap[parameter] || parameter;
          result.push(parameter);
        }
      }
    }

    return Promise.resolve(result);
  });
}

function libraryFilter(key, library) {
  // which fields to change - for all of them - they are in an array - get the danish value
  const keysToChange = [
    'branchName',
    'branchShortName',
    'openingHours',
    'illOrderReceiptText',
    'temporarilyClosedReason'
  ];

  if (keysToChange.includes(key)) {
    return (
      library[key]
        // filter on language
        .filter(field => field.language === 'dan')
        // return the value
        .map(field => {
          return field.value;
        })
    );
  }

  return library[key];
}

/**
 * Parse response from findlibrary/all endpoint. Filter out ncip info.
 * Bind getOrderParameters to add order parameters to result.
 * @param context
 * @param response
 * @returns {Promise<unknown[]>}
 */
function openAgencyPromiseHandler(context, response) {
  const results = response.data.pickupAgency.map(library => {
    const result = {};

    // filter out ncip info
    Object.keys(library)
      .filter(
        libraryKey =>
          libraryKey !== '@' &&
          libraryKey.indexOf('ncip') !== 0 &&
          library[libraryKey] !== null
      )
      .forEach(key => (result[key] = libraryFilter(key, library)));

    // check if mainagencyid is set - it might not be the case for single branch
    // libraries
    if (!result.agencyId) {
      result.agencyId = result.branchId;
    }

    return result;
  });

  // collect agencyids as keys for getOrderParameters service call
  const agencies = {};
  for (let i = 0; i < results.length; ++i) {
    agencies[results[i].agencyId] = true;
  }
  const agencyKeys = Object.keys(agencies);
  // iterate agencyIds - get orderparameters
  const agencyPromises = agencyKeys.map(getOrderParameters.bind(null, context));
  return Promise.all(agencyPromises).then(
    orderParameterPromiseHandler.bind(null, results, agencyKeys)
  );
}

/**
 * Do a call to findlibrary/all endpoint.
 * @param context
 * @returns {*}
 */
function getLibraries(context) {
  const service = context.get('services.openagency');
  const path = '/findlibrary/all';
  const api = service + path;

  return context
    .call(api, {})
    .then(response => openAgencyPromiseHandler(context, response));
}

/**
 * Handle the request.
 * @param params
 *   May hold one or more branch/agency - ids to filter on
 * @param context
 *   @see context.json
 * @param libraries
 *   a list of pickupagencies - from service or cache
 * @returns {{data, statusCode: number}}
 */
function getLibrariesTransformPromiseHandler(params, context, libraries) {
  if (Date.now() - timestamp > timeout) {
    setTimeout(() => getLibraries(context), 1000);
    timestamp = Date.now();
  }

  if (Array.isArray(params.agencyIds)) {
    const agencies = {};
    for (let i = 0; i < params.agencyIds.length; ++i) {
      agencies[IsilUtils.getIdFromIsil(params.agencyIds[i])] = true;
    }

    libraries = libraries.filter(o => agencies[o.agencyId]);
  }

  if (Array.isArray(params.branchIds)) {
    const branches = {};
    for (let i = 0; i < params.branchIds.length; ++i) {
      branches[IsilUtils.getIdFromIsil(params.branchIds[i])] = true;
    }

    libraries = libraries.filter(o => branches[o.branchId]);
  }

  return { statusCode: 200, data: libraries };
}

/**
 * Entrypoint for this transformer.
 * @param params
 * @param context
 * @returns {Promise<any>}
 */
export default function getLibrariesTransform(params, context) {
  let promise;

  if (cache) {
    promise = Promise.resolve(cache);
  } else {
    promise = getLibraries(context);
  }

  return promise.then(
    getLibrariesTransformPromiseHandler.bind(null, params, context)
  );
}
<commit_msg>transform some fields to match output from openagency.2.34<commit_after>/**
 * @file - handle information from vip. @see openagency.addi.dk
 * Internally (DBC) we use vipcore : http://vipcore.iscrum-vip-prod.svc.cloud.dbc.dk:8080/1.0/api
 * For documentation @see https://dbcjira.atlassian.net/wiki/spaces/IS/pages/884998162/VipCore+API+beskrivelse
 *
 * Bssically this transformer gets ALL pickupagencies and orderparameters from vipcore. When a single
 * library/branch is requested it returns a filtered result of the pickupagencies.
 *
 */

import * as IsilUtils from './utils/isil.utils';

const timeout = 60 * 60 * 1000;
let cache;
let timestamp;

/**
 * Insert orderparameters in the list of pickupagencies.
 *
 * @param results
 *   all the pickupagencies retrieved from vipcore
 * @param agencyKeys
 *    agencyIds of all pickupagencies
 * @param orderParameters
 *    order parameters (eg. userid, username ...) to insert
 * @returns {*}
 */
function orderParameterPromiseHandler(results, agencyKeys, orderParameters) {
  const agencyOrderParameters = {};
  for (let i = 0; i < agencyKeys.length; ++i) {
    agencyOrderParameters[agencyKeys[i]] = orderParameters[i];
  }
  for (let i = 0; i < results.length; ++i) {
    results[i].orderParameters = agencyOrderParameters[results[i].agencyId];
  }
  cache = results;
  timestamp = Date.now();
  return results;
}

/**
 * Do a call to vipcore service endpoint
 * e.g http://vipcore.iscrum-vip-prod.svc.cloud.dbc.dk/1.0/api/service/710100/userOrderParameters/
 * Parse and return orderparamters from service
 *
 * @param context
 * @param agencyId
 * @returns {*}
 */
function getOrderParameters(context, agencyId) {
  const service = context.get('services.openagency');
  const path = `/service/${agencyId}/userOrderParameters/`;
  const api = service + path;

  return context.call(api, {}).then(response => {
    const result = [];

    // @TODO datacheck - service may return an error e.g service_unavailable

    let parameters = response.data.userOrderParameters.userParameter
      ? response.data.userOrderParameters.userParameter
      : null;

    // map selected parameters
    const parameterMap = {
      userName: 'name',
      userAddress: 'address',
      userMail: 'email',
      userTelephone: 'phone'
    };

    if (parameters) {
      for (let i = 0; i < parameters.length; ++i) {
        if (parameters[i].parameterRequired === true) {
          let parameter = parameters[i].userParameterType;
          parameter = parameterMap[parameter] || parameter;
          result.push(parameter);
        }
      }
    }

    return Promise.resolve(result);
  });
}

function libraryFilter(key, library) {
  // which fields to change - for all of them - they are in an array - get the danish value
  const keysToChange = [
    'branchName',
    'branchShortName',
    'openingHours',
    'illOrderReceiptText',
    'temporarilyClosedReason'
  ];

  if (keysToChange.includes(key)) {
    return (
      library[key]
        // filter on language
        .filter(field => field.language === 'dan')
        // return the value
        .map(field => {
          return field.value;
        })
    );
  }

  return library[key];
}

/**
 * Parse response from findlibrary/all endpoint. Filter out ncip info.
 * Bind getOrderParameters to add order parameters to result.
 * @param context
 * @param response
 * @returns {Promise<unknown[]>}
 */
function openAgencyPromiseHandler(context, response) {
  const results = response.data.pickupAgency.map(library => {
    const result = {};

    // filter out ncip info
    Object.keys(library)
      .filter(
        libraryKey =>
          libraryKey !== '@' &&
          libraryKey.indexOf('ncip') !== 0 &&
          library[libraryKey] !== null
      )
      .forEach(key => (result[key] = libraryFilter(key, library)));

    // check if mainagencyid is set - it might not be the case for single branch
    // libraries
    if (!result.agencyId) {
      result.agencyId = result.branchId;
    }

    return result;
  });

  // collect agencyids as keys for getOrderParameters service call
  const agencies = {};
  for (let i = 0; i < results.length; ++i) {
    agencies[results[i].agencyId] = true;
  }
  const agencyKeys = Object.keys(agencies);
  // iterate agencyIds - get orderparameters
  const agencyPromises = agencyKeys.map(getOrderParameters.bind(null, context));
  return Promise.all(agencyPromises).then(
    orderParameterPromiseHandler.bind(null, results, agencyKeys)
  );
}

/**
 * Do a call to findlibrary/all endpoint.
 * @param context
 * @returns {*}
 */
function getLibraries(context) {
  const service = context.get('services.openagency');
  const path = '/findlibrary/all';
  const api = service + path;

  return context
    .call(api, {})
    .then(response => openAgencyPromiseHandler(context, response));
}

/**
 * Handle the request.
 * @param params
 *   May hold one or more branch/agency - ids to filter on
 * @param context
 *   @see context.json
 * @param libraries
 *   a list of pickupagencies - from service or cache
 * @returns {{data, statusCode: number}}
 */
function getLibrariesTransformPromiseHandler(params, context, libraries) {
  if (Date.now() - timestamp > timeout) {
    setTimeout(() => getLibraries(context), 1000);
    timestamp = Date.now();
  }

  if (Array.isArray(params.agencyIds)) {
    const agencies = {};
    for (let i = 0; i < params.agencyIds.length; ++i) {
      agencies[IsilUtils.getIdFromIsil(params.agencyIds[i])] = true;
    }

    libraries = libraries.filter(o => agencies[o.agencyId]);
  }

  if (Array.isArray(params.branchIds)) {
    const branches = {};
    for (let i = 0; i < params.branchIds.length; ++i) {
      branches[IsilUtils.getIdFromIsil(params.branchIds[i])] = true;
    }

    libraries = libraries.filter(o => branches[o.branchId]);
  }

  return {statusCode: 200, data: libraries};
}

/**
 * Entrypoint for this transformer.
 * @param params
 * @param context
 * @returns {Promise<any>}
 */
export default function getLibrariesTransform(params, context) {
  let promise;

  if (cache) {
    promise = Promise.resolve(cache);
  } else {
    promise = getLibraries(context);
  }

  return promise.then(
    getLibrariesTransformPromiseHandler.bind(null, params, context)
  );
}
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var PersonaStrategy = require('passport-persona').Strategy;
var _ = require('lodash');

var conf = require('./server/conf');
var logger = conf.logger;
var assets = require('./server/assets');
var accessControl = require('./server/accessControl');

var app = express();

app.use(express.favicon('public/favicon.ico'));
if (conf.env === 'production') {
  app.use(express.logger());
}
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
  secret: conf.settings.SESSION_SECRET,
  cookie: {
    path: '/',
    httpOnly: true,
    maxAge: null
//    secure: conf.env === 'production' // force HTTPS, this should be turned on after development
  }
}));
app.use(require('connect-flash')());

var csrf = express.csrf();
app.use(function (req, res, next) {
  if (req.method === 'POST' && /^\/kibana\/es(\/|$)/.test(req.path)) {
    // Kibana's POST requests to elasticsearch don't need CSRF tokens since they don't mutate state and we don't
    // want to patch Kibana
    next();
  } else {
    csrf(req, res, next);
  }
});

app.use(assets.anonymous());

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function (user, done) {
  // store entire user object in session so we don't have to deserialize it from data store
  // this won't scale to large number of concurrent users, but it will be faster for small deployments
  done(null, user);
});
passport.deserializeUser(function (user, done) {
  // no need to deserialize, we store entire user in memory
  done(null, user);
});

passport.use(new PersonaStrategy({
  audience: 'http://localhost:9000'
}, function (email, done) {
  // TODO whitelist emails here
  logger.info('%s logged in', email);
  return done(null, {
    email: email
    // other attributes can come from DB
  });
}));

// variables for views, this must be before router in the middleware chain
app.use(function (req, res, next) {
  res.locals.user = req.user;
  if (req.csrfToken) { // not every request has CSRF token
    res.locals.csrfToken = req.csrfToken();
  }
  next();
});

app.use(app.router);

app.use(require('./server/error').middleware);

app.engine('html', function (path, options, callback) {
  options = _.assign({
    open: '{{', // htmlmin likes to escape <
    close: '}}'
  }, options);
  require('ejs').renderFile(path, options, callback);
});
app.set('views', require('./server/views')(conf.env));

app.get('/', function (req, res) {
  // single page, even login view is handled by client
  res.render('index.html');
});

app.post('/session', function (req, res) {
  // 307 means client should send another POST
  res.redirect(307, '/session/browserid');
});

app.post('/session/browserid', function (req, res, next) {
  passport.authenticate('persona', function (err, user) {
    if (err) {
      next(err);
      return;
    }

    if (user) {
      req.login(user, function (err) {
        if (err) {
          next(err);
          return;
        }

        res.json(200, {
          // whitelist user properties that are OK to send to client
          email: user.email
        });
      });
    } else {
      res.json(401, {
        message: 'Bad credentials'
      });
    }
  })(req, res, next);
});

// all routes below this require authenticating
app.all('*', accessControl.denyAnonymousAccess);

app.delete('/session', function (req, res) {
  res.redirect(307, '/session/browserid');
});

app.delete('/session/browserid', function (req, res) {
  logger.info('%s logged out', req.user.email);
  req.logout();
  res.send(204); // No Content
});

var esProxy = require('./server/es/proxy');
app.use('/es', esProxy);
app.use('/kibana/es', esProxy);
app.use('/kibana', assets.kibana());

// this MUST be the last route
app.use(require('./server/error').notFound);

if (!module.parent) {
  logger.info('Running in %s mode', conf.env);

  var port = process.env.PORT || 9000;

  app.listen(port, function () {
    // must log to stdout (some 3rd party tools read stdout to know when web server is up)
    console.log('Listening on port ' + port);

    // if we have a parent, tell them we started
    if (process.send) {
      process.send({
        started: true,
        url: 'http://localhost:' + port
      });
    }
  });
}
<commit_msg>HTTP compression<commit_after>'use strict';

var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var PersonaStrategy = require('passport-persona').Strategy;
var _ = require('lodash');

var conf = require('./server/conf');
var logger = conf.logger;
var assets = require('./server/assets');
var accessControl = require('./server/accessControl');

var app = express();

app.use(express.compress());
app.use(express.favicon('public/favicon.ico'));
if (conf.env === 'production') {
  app.use(express.logger());
}
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
  secret: conf.settings.SESSION_SECRET,
  cookie: {
    path: '/',
    httpOnly: true,
    maxAge: null
//    secure: conf.env === 'production' // force HTTPS, this should be turned on after development
  }
}));
app.use(require('connect-flash')());

var csrf = express.csrf();
app.use(function (req, res, next) {
  if (req.method === 'POST' && /^\/kibana\/es(\/|$)/.test(req.path)) {
    // Kibana's POST requests to elasticsearch don't need CSRF tokens since they don't mutate state and we don't
    // want to patch Kibana
    next();
  } else {
    csrf(req, res, next);
  }
});

app.use(assets.anonymous());

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function (user, done) {
  // store entire user object in session so we don't have to deserialize it from data store
  // this won't scale to large number of concurrent users, but it will be faster for small deployments
  done(null, user);
});
passport.deserializeUser(function (user, done) {
  // no need to deserialize, we store entire user in memory
  done(null, user);
});

passport.use(new PersonaStrategy({
  audience: 'http://localhost:9000'
}, function (email, done) {
  // TODO whitelist emails here
  logger.info('%s logged in', email);
  return done(null, {
    email: email
    // other attributes can come from DB
  });
}));

// variables for views, this must be before router in the middleware chain
app.use(function (req, res, next) {
  res.locals.user = req.user;
  if (req.csrfToken) { // not every request has CSRF token
    res.locals.csrfToken = req.csrfToken();
  }
  next();
});

app.use(app.router);

app.use(require('./server/error').middleware);

app.engine('html', function (path, options, callback) {
  options = _.assign({
    open: '{{', // htmlmin likes to escape <
    close: '}}'
  }, options);
  require('ejs').renderFile(path, options, callback);
});
app.set('views', require('./server/views')(conf.env));

app.get('/', function (req, res) {
  // single page, even login view is handled by client
  res.render('index.html');
});

app.post('/session', function (req, res) {
  // 307 means client should send another POST
  res.redirect(307, '/session/browserid');
});

app.post('/session/browserid', function (req, res, next) {
  passport.authenticate('persona', function (err, user) {
    if (err) {
      next(err);
      return;
    }

    if (user) {
      req.login(user, function (err) {
        if (err) {
          next(err);
          return;
        }

        res.json(200, {
          // whitelist user properties that are OK to send to client
          email: user.email
        });
      });
    } else {
      res.json(401, {
        message: 'Bad credentials'
      });
    }
  })(req, res, next);
});

// all routes below this require authenticating
app.all('*', accessControl.denyAnonymousAccess);

app.delete('/session', function (req, res) {
  res.redirect(307, '/session/browserid');
});

app.delete('/session/browserid', function (req, res) {
  logger.info('%s logged out', req.user.email);
  req.logout();
  res.send(204); // No Content
});

var esProxy = require('./server/es/proxy');
app.use('/es', esProxy);
app.use('/kibana/es', esProxy);
app.use('/kibana', assets.kibana());

// this MUST be the last route
app.use(require('./server/error').notFound);

if (!module.parent) {
  logger.info('Running in %s mode', conf.env);

  var port = process.env.PORT || 9000;

  app.listen(port, function () {
    // must log to stdout (some 3rd party tools read stdout to know when web server is up)
    console.log('Listening on port ' + port);

    // if we have a parent, tell them we started
    if (process.send) {
      process.send({
        started: true,
        url: 'http://localhost:' + port
      });
    }
  });
}
<|endoftext|>


<commit_before>var express = require("express"),
    app = express(),
    server = require("http").createServer(app),
    env = process.env.NODE_ENV || "development",
    io = require("socket.io").listen(server),
    Twitter = require('ntwitter'),
    feelings = require('./lib/feelings.js'),
    feelingsList = feelings.feelings,
    feelingsColors = feelings.feelingColors;

if (env === "development") {
  // keys-sample.js is included. rename to keys.js and update with your own keys.
  var keys = require('./lib/keys.js');
}

// app configuration
app.configure(function () {
  app.use(express.static(__dirname + "/public"));
  app.set("view engine", "jade");
  app.set("view options", {layout: false});
  app.set("views", __dirname + "/views");
  app.use(express.logger("dev"));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  if (env === "development") {
    // app.use(express.errorHandler());
  }
});

var getTweets = function () {

  // ntwitter setup
  var twit = new Twitter({
    consumer_key: process.env.TWITTER_CONSUMER_KEY || keys.TWITTER_CONSUMER_KEY,
    consumer_secret: process.env.TWITTER_CONSUMER_SECRET || keys.TWITTER_CONSUMER_SECRET,
    access_token_key: process.env.TWITTER_ACCESS_TOKEN || keys.TWITTER_ACCESS_TOKEN,
    access_token_secret: process.env.TWITTER_TOKEN_SECRET || keys.TWITTER_TOKEN_SECRET
  });

  twit.stream('statuses/filter', {'track':'feel,feeling,felt', 'language':'en', 'filter_level': 'medium'}, function(stream) {
    stream.on('data', function (data) {

      if (data.text) {
        // eligible words span 2 words before and 5 after feel/feeling/felt
        // 2 words before "how bad I felt"
        // 5 words after "I felt oh so very incredibly shitty"
        var tokenizedText = tokenizeText(data.text),
            feelingIndex = findFeelingIndex(tokenizedText),
            eligibleWords = tokenizedText.slice(Math.max(0, feelingIndex - 2), Math.min(feelingIndex + 5, tokenizedText.length)).join(" ");

        // look for legitimate feeling words
        matchingFeelings = new RegExp(feelingsList.join("|")).exec(eligibleWords);

        if (matchingFeelings) {
          // strip spaces from matching feeling
          firstFeeling = matchingFeelings[0].replace(/ /g, "");
          data.feeling = firstFeeling;
          data.feelingColor = feelingsColors[firstFeeling];
          io.sockets.emit('feelingTweet', data);
          console.log("feeling tweet: " + data.text);
          console.log("feeling: " + data.feeling);
          console.log(data);
        }
        else {
          console.log(data);
          console.log("not a real feeling: " + data.text);
        }
      } else {
        console.log("no data.text?!");
      }

      stream.on('end', function (response) {
        getTweets();
      });
      stream.on('destroy', function (response) {
        getTweets();
      });

    });
  });
};

getTweets();

// routes
app.get("/?", function (request, response) {
  response.render("index");
});

app.get("/about", function (request, response) {
  response.render("about");
});

app.get("*", function (request, response) {
  response.status(404);
  if (request.accepts('html')) {
    response.render('404', { url: request.url });
    return;
  }
  if (request.accepts('json')) {
    response.send({ error: 'Not found' });
    return;
  }
});

// replace punctuation with spaces, collapse multiple
// consecutive spaces, and split into words
var tokenizeText = function (text) {
  text = text.toLowerCase().replace(/[\.\?\"\n,-\/#!$%\^&\*;:{}=\-_`~()]/g," ");
  text = text.replace(/\s{2,}/g," ");
  return text.split(" ");
};

// find location of feel, feeling, or felt
var findFeelingIndex = function (tokenizedText) {
  if (tokenizedText.indexOf("feel") > -1) {
    return tokenizedText.indexOf("feel");
  } else if (tokenizedText.indexOf("feeling") > -1) {
    return tokenizedText.indexOf("feeling");
  } else {
    return tokenizedText.indexOf("felt");
  }
};

server.listen(process.env.PORT || 3000);<commit_msg>stream end and destroy functions shouldn't be inside stream data function<commit_after>var express = require("express"),
    app = express(),
    server = require("http").createServer(app),
    env = process.env.NODE_ENV || "development",
    io = require("socket.io").listen(server),
    Twitter = require('ntwitter'),
    feelings = require('./lib/feelings.js'),
    feelingsList = feelings.feelings,
    feelingsColors = feelings.feelingColors;

if (env === "development") {
  // keys-sample.js is included. rename to keys.js and update with your own keys.
  var keys = require('./lib/keys.js');
}

// app configuration
app.configure(function () {
  app.use(express.static(__dirname + "/public"));
  app.set("view engine", "jade");
  app.set("view options", {layout: false});
  app.set("views", __dirname + "/views");
  app.use(express.logger("dev"));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  if (env === "development") {
    // app.use(express.errorHandler());
  }
});

var getTweets = function () {

  // ntwitter setup
  var twit = new Twitter({
    consumer_key: process.env.TWITTER_CONSUMER_KEY || keys.TWITTER_CONSUMER_KEY,
    consumer_secret: process.env.TWITTER_CONSUMER_SECRET || keys.TWITTER_CONSUMER_SECRET,
    access_token_key: process.env.TWITTER_ACCESS_TOKEN || keys.TWITTER_ACCESS_TOKEN,
    access_token_secret: process.env.TWITTER_TOKEN_SECRET || keys.TWITTER_TOKEN_SECRET
  });

  twit.stream('statuses/filter', {'track':'feel,feeling,felt', 'language':'en', 'filter_level': 'medium'}, function(stream) {
    stream.on('data', function (data) {

      if (data.text) {
        // eligible words span 2 words before and 5 after feel/feeling/felt
        // 2 words before "how bad I felt"
        // 5 words after "I felt oh so very incredibly shitty"
        var tokenizedText = tokenizeText(data.text),
            feelingIndex = findFeelingIndex(tokenizedText),
            eligibleWords = tokenizedText.slice(Math.max(0, feelingIndex - 2), Math.min(feelingIndex + 5, tokenizedText.length)).join(" ");

        // look for legitimate feeling words
        matchingFeelings = new RegExp(feelingsList.join("|")).exec(eligibleWords);

        if (matchingFeelings) {
          // strip spaces from matching feeling
          firstFeeling = matchingFeelings[0].replace(/ /g, "");
          data.feeling = firstFeeling;
          data.feelingColor = feelingsColors[firstFeeling];
          io.sockets.emit('feelingTweet', data);
          console.log("feeling tweet: " + data.text);
          console.log("feeling: " + data.feeling);
          console.log(data);
        }
        else {
          console.log(data);
          console.log("not a real feeling: " + data.text);
        }
      } else {
        console.log("no data.text?!");
      }

    });

    stream.on('end', function (response) {
      getTweets();
    });
    stream.on('destroy', function (response) {
      getTweets();
    });

  });
};

getTweets();

// routes
app.get("/?", function (request, response) {
  response.render("index");
});

app.get("/about", function (request, response) {
  response.render("about");
});

app.get("*", function (request, response) {
  response.status(404);
  if (request.accepts('html')) {
    response.render('404', { url: request.url });
    return;
  }
  if (request.accepts('json')) {
    response.send({ error: 'Not found' });
    return;
  }
});

// replace punctuation with spaces, collapse multiple
// consecutive spaces, and split into words
var tokenizeText = function (text) {
  text = text.toLowerCase().replace(/[\.\?\"\n,-\/#!$%\^&\*;:{}=\-_`~()]/g," ");
  text = text.replace(/\s{2,}/g," ");
  return text.split(" ");
};

// find location of feel, feeling, or felt
var findFeelingIndex = function (tokenizedText) {
  if (tokenizedText.indexOf("feel") > -1) {
    return tokenizedText.indexOf("feel");
  } else if (tokenizedText.indexOf("feeling") > -1) {
    return tokenizedText.indexOf("feeling");
  } else {
    return tokenizedText.indexOf("felt");
  }
};

server.listen(process.env.PORT || 3000);<|endoftext|>


<commit_before>"use strict";

// increase the libuv threadpool size to 1.5x the number of logical CPUs.
process.env.UV_THREADPOOL_SIZE = process.env.UV_THREADPOOL_SIZE || Math.ceil(Math.max(4, require('os').cpus().length * 1.5));

require('memwatch').on("leak", console.log);

var path = require("path");
var raven = require("raven");

var onHeaders = require('on-headers');

var tessera = require("tessera"),
    express = require("express"),
    cors = require("cors"),
    tilelive = require("tilelive-cache")(require("tilelive"), {
      size: process.env.CACHE_SIZE,
      sources: process.env.SOURCE_CACHE_SIZE
    });

var app = express().disable("x-powered-by");

require("tessera/modules")(tilelive, {});

var loggingThreshold = +(process.env.LOG_MS || 5000);
var slowLogger = function(req, res, next) {
    var startAt = process.hrtime()

    onHeaders(res, function () {
      if (this.getHeader('X-Response-Time')) return;

      var diff = process.hrtime(startAt)
      var ms = diff[0] * 1e3 + diff[1] * 1e-6

      if (ms > loggingThreshold) {
        console.log("SLOW REQUEST ", req.originalUrl, " ", ms, " ms");
      }
      this.setHeader('X-Response-Time', ms.toFixed(3) + 'ms')
    })

    next()
  }

var config = require("./tessera.json");
Object.keys(config).forEach(function(prefix) {
  if (config[prefix].timing !== false) {
    app.use(prefix, slowLogger);
  }

  if (config[prefix].cors !== false) {
    app.use(prefix, cors());
  }

  app.use(raven.middleware.express(process.env.SENTRY_DSN));
  app.use(prefix, express.static(path.join(__dirname, "node_modules/tessera/public")));
  app.use(prefix, express.static(path.join(__dirname, "node_modules/tessera/bower_components")));
  app.use(prefix, tessera(tilelive, config[prefix]));
});

app.listen(process.env.PORT || 8080, function() {
  console.log("Listening at http://%s:%d/", this.address().address, this.address().port);
});
<commit_msg>Formatting<commit_after>"use strict";

// increase the libuv threadpool size to 1.5x the number of logical CPUs.
process.env.UV_THREADPOOL_SIZE = process.env.UV_THREADPOOL_SIZE || Math.ceil(Math.max(4, require('os').cpus().length * 1.5));

require('memwatch').on("leak", console.log);

var path = require("path");
var raven = require("raven");

var onHeaders = require('on-headers');

var tessera = require("tessera"),
    express = require("express"),
    cors = require("cors"),
    tilelive = require("tilelive-cache")(require("tilelive"), {
      size: process.env.CACHE_SIZE,
      sources: process.env.SOURCE_CACHE_SIZE
    });

var app = express().disable("x-powered-by");

require("tessera/modules")(tilelive, {});

var loggingThreshold = +(process.env.LOG_MS || 5000);
var slowLogger = function(req, res, next) {
  var startAt = process.hrtime();

  onHeaders(res, function () {
    if (this.getHeader('X-Response-Time')) {
      return;
    }

    var diff = process.hrtime(startAt);
    var ms = diff[0] * 1e3 + diff[1] * 1e-6;

    if (ms > loggingThreshold) {
      console.log("SLOW REQUEST ", req.originalUrl, " ", ms, " ms");
    }
    this.setHeader('X-Response-Time', ms.toFixed(3) + 'ms');
  });

  next();
};

var config = require("./tessera.json");
Object.keys(config).forEach(function(prefix) {
  if (config[prefix].timing !== false) {
    app.use(prefix, slowLogger);
  }

  if (config[prefix].cors !== false) {
    app.use(prefix, cors());
  }

  app.use(raven.middleware.express(process.env.SENTRY_DSN));
  app.use(prefix, express.static(path.join(__dirname, "node_modules/tessera/public")));
  app.use(prefix, express.static(path.join(__dirname, "node_modules/tessera/bower_components")));
  app.use(prefix, tessera(tilelive, config[prefix]));
});

app.listen(process.env.PORT || 8080, function() {
  console.log("Listening at http://%s:%d/", this.address().address, this.address().port);
});
<|endoftext|>


<commit_before>var Botkit   = require('botkit');
var httpRequest  = require('request');
var Firebase = require('firebase');

var accessToken = process.env.FACEBOOK_PAGE_ACCESS_TOKEN
var verifyToken = process.env.FACEBOOK_VERIFY_TOKEN
var port        = process.env.PORT

Firebase.initializeApp({
  serviceAccount: "iReport-Dev-d295383b217f.json",
  databaseURL: "https://ireport-dev.firebaseio.com/"
});

var fbDB = Firebase.database();
var ref = fbDB.ref("/messages");
ref.once("value", function(snapshot){
  console.log(snapshot.val());
})

if (!accessToken) throw new Error('FACEBOOK_PAGE_ACCESS_TOKEN is required but missing')
if (!verifyToken) throw new Error('FACEBOOK_VERIFY_TOKEN is required but missing')
if (!port) throw new Error('PORT is required but missing')

var controller = Botkit.facebookbot({
  access_token: accessToken,
  verify_token: verifyToken
})

var bot = controller.spawn()

controller.setupWebserver(port, function(err, webserver){
  if(err) return console.log(err);

  controller.createWebhookEndpoints(webserver, bot, function(){
    console.log('Ready Player 1');
  })

})

controller.hears(['hello', 'hi'], 'message_received', function (bot, message){
  bot.reply(message, 'Ey man!')
  bot.reply(message, "What's good?")
  bot.reply(message, {
    attachment:{
      type: 'template',
      payload: {
        template_type: 'button',
        text: 'Which do you prefer',
        buttons: [
          {
            type: 'postback',
            title: 'Cats',
            payload: 'show_cat'
          },
          {
            type: 'postback',
            title: 'Dogs',
            payload: 'show_dog'
          }
      ]
      }
    }
  })
})

controller.on('facebook_postback', function(bot, message){
  switch (message.payload) {
    case 'show_cat':
      bot.reply(message, {
        attachment: {
          type: 'image',
          payload:{
            url: 'https://media.giphy.com/media/F69JmzpmSaffi/giphy.gif'
          }
        }
      })
      break;

    case 'show_dog':
      bot.reply(message, {
        attachment: {
          type: 'image',
          payload:{
            url: 'https://media.giphy.com/media/J3ODsTxAB7U7m/giphy.gif'
          }
        }
      })
      break;

  }
})

controller.on('message_received', function(bot, message) {
  // console.log("BOT: ", bot);
  console.log("MESSAGE: ", JSON.stringify(message));

  var author    = message.user
  var timestamp = message.timestamp
  var text      = message.text

  ref.child("chats").push({
    author: author,
    timestamp: timestamp,
    text: text
  })

    // carefully examine and
    // handle the message here!
    // Note: Platforms such as Slack send many kinds of messages, not all of which contain a text field!
});

function processLocation(sender, coords){

}

function processImages(sender, image){

}
<commit_msg>location and image catching<commit_after>var Botkit   = require('botkit');
var httpRequest  = require('request');
var Firebase = require('firebase');

var accessToken = process.env.FACEBOOK_PAGE_ACCESS_TOKEN
var verifyToken = process.env.FACEBOOK_VERIFY_TOKEN
var port        = process.env.PORT

Firebase.initializeApp({
  serviceAccount: "iReport-Dev-d295383b217f.json",
  databaseURL: "https://ireport-dev.firebaseio.com/"
});

var fbDB = Firebase.database();
var ref = fbDB.ref("/messages");
ref.once("value", function(snapshot){
  console.log(snapshot.val());
})

if (!accessToken) throw new Error('FACEBOOK_PAGE_ACCESS_TOKEN is required but missing')
if (!verifyToken) throw new Error('FACEBOOK_VERIFY_TOKEN is required but missing')
if (!port) throw new Error('PORT is required but missing')

var controller = Botkit.facebookbot({
  access_token: accessToken,
  verify_token: verifyToken
})

var bot = controller.spawn()

controller.setupWebserver(port, function(err, webserver){
  if(err) return console.log(err);

  controller.createWebhookEndpoints(webserver, bot, function(){
    console.log('Ready Player 1');
  })

})

controller.hears(['hello', 'hi'], 'message_received', function (bot, message){
  bot.reply(message, 'Ey man!')
  bot.reply(message, "What's good?")
  bot.reply(message, {
    attachment:{
      type: 'template',
      payload: {
        template_type: 'button',
        text: 'Which do you prefer',
        buttons: [
          {
            type: 'postback',
            title: 'Cats',
            payload: 'show_cat'
          },
          {
            type: 'postback',
            title: 'Dogs',
            payload: 'show_dog'
          }
      ]
      }
    }
  })
})

controller.on('facebook_postback', function(bot, message){
  switch (message.payload) {
    case 'show_cat':
      bot.reply(message, {
        attachment: {
          type: 'image',
          payload:{
            url: 'https://media.giphy.com/media/F69JmzpmSaffi/giphy.gif'
          }
        }
      })
      break;

    case 'show_dog':
      bot.reply(message, {
        attachment: {
          type: 'image',
          payload:{
            url: 'https://media.giphy.com/media/J3ODsTxAB7U7m/giphy.gif'
          }
        }
      })
      break;

  }
})

controller.on('message_received', function(bot, message) {
  var image     = false,
      location  = false,
      attachment,
      author    = message.user,
      timestamp = message.timestamp,
      text      = = message.text;

  console.log("MESSAGE: ", JSON.stringify(message));

  if (message.attachments && message.attachments.length > 0) {
    attachment = message.attachments[0];

    if (attachment.type === 'image') {
      if (message.text == "undefined")
        var text = false

        var image = attachment.payload.url
    }

    if (message.attachments.type == 'location' ) {
      location = attachment.payload.coordinates
    }

  }

  ref.child("chats").push({
    author: author,
    timestamp: timestamp,
    text: text,
    image: image,
    location: location
  }, function(err){
    console.log("ERROR: ", err);
  })

    // carefully examine and
    // handle the message here!
    // Note: Platforms such as Slack send many kinds of messages, not all of which contain a text field!
});

function processLocation(sender, coords){

}

function processImages(sender, image){

}
<|endoftext|>


<commit_before>var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('Hello Sorin!');
});

app.listen(80);
<commit_msg>Updated text to Hello World!<commit_after>var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('Hello World!');
});

app.listen(80);
<|endoftext|>


<commit_before>'use strict';

const app = require('express')();
const PORT = process.env.PORT || 3000;

app.get('/hello', (req, res) => {
 const msg = `
Hello World!

Goodbye World!
`;

  res.writeHead(200, {
    'Content-Type': 'text/html'
  });

  // chunk response by character
  msg.split('').forEach((char, i) => {
    setTimeout(() => {
      res.write(char);
    }, 1000 * i);
  });

  // wait for all characters to be sent
  setTimeout(() => {
    res.end();
  }, msg.length * 1000 + 2000);
});

app.get('/random', (req, res) => {
  res.end(Math.random().toString());
});

app.all('*', (req, res) => {
  res.writeHead(403);
  res.end('Access Denied!');
});

app.listen(PORT, () => {
  console.log(`Node.js server started. Listening on port ${PORT}`);
});
<commit_msg>prefer more natrual express syntax<commit_after>'use strict';

const app = require('express')();
const PORT = process.env.PORT || 3000;

app.get('/hello', (req, res) => {
 const msg = `
Hello World!

Goodbye World!
`;

  res.writeHead(200, {
    'Content-Type': 'text/html'
  });

  // chunk response by character
  msg.split('').forEach((char, i) => {
    setTimeout(() => {
      res.write(char);
    }, 1000 * i);
  });

  // wait for all characters to be sent
  setTimeout(() => {
    res.end();
  }, msg.length * 1000 + 2000);
});

app.get('/random', (req, res) => {
  res.send(Math.random().toString());
});

app.all('*', (req, res) => {
  res
    .status(403)
    .send('Access Denied!');
});

app.listen(PORT, () => {
  console.log(`Node.js server started. Listening on port ${PORT}`);
});
<|endoftext|>


<commit_before>'use strict'
var DropdownPanel = require('./DropdownPanel')
var yo = require('yo-yo')

function FullStoragesChanges (_parent, _traceManager, _storageResolver) {
  this.storageResolver = _storageResolver
  this.parent = _parent
  this.traceManager = _traceManager
  this.addresses = []
  this.view
  this.traceLength
  this.basicPanel = new DropdownPanel('Full Storages Changes', {json: true})
  this.init()
}

FullStoragesChanges.prototype.render = function () {
  var view = yo`<div id='fullstorageschangespanel' >${this.basicPanel.render()}</div>`
  if (!this.view) {
    this.view = view
  }
  return view
}

FullStoragesChanges.prototype.init = function () {
  var self = this
  this.parent.event.register('newTraceLoaded', this, function (length) {
    self.panels = []
    self.traceManager.getAddresses(function (error, addresses) {
      if (!error) {
        self.addresses = addresses
        self.basicPanel.update({})
      }
    })

    self.traceManager.getLength(function (error, length) {
      if (!error) {
        self.traceLength = length
      }
    })
  })

  this.parent.event.register('indexChanged', this, function (index) {
    if (index < 0) return
    if (self.parent.currentStepIndex !== index) return

    if (index === self.traceLength - 1) {
      var storageJSON = {}
      for (var k in self.addresses) {
        var address = self.addresses[k]
        self.storageResolver.storageRange(function (error, result) {
          if (!error) {
            storageJSON[address] = result
            self.basicPanel.update(storageJSON)
          }
        })
      }
    } else {
      self.basicPanel.update({})
    }
  })
}

module.exports = FullStoragesChanges
<commit_msg>use storageViewer in fullstorageChanges.js<commit_after>'use strict'
var DropdownPanel = require('./DropdownPanel')
var StorageViewer = require('../storage/storageViewer')
var yo = require('yo-yo')

function FullStoragesChanges (_parent, _traceManager, _storageResolver) {
  this.storageResolver = _storageResolver
  this.parent = _parent
  this.traceManager = _traceManager
  this.addresses = []
  this.view
  this.traceLength
  this.basicPanel = new DropdownPanel('Full Storages Changes', {json: true})
  this.init()
}

FullStoragesChanges.prototype.render = function () {
  var view = yo`<div id='fullstorageschangespanel' >${this.basicPanel.render()}</div>`
  if (!this.view) {
    this.view = view
  }
  return view
}

FullStoragesChanges.prototype.init = function () {
  var self = this
  this.parent.event.register('newTraceLoaded', this, function (length) {
    self.panels = []
    self.traceManager.getAddresses(function (error, addresses) {
      if (!error) {
        self.addresses = addresses
        self.basicPanel.update({})
      }
    })

    self.traceManager.getLength(function (error, length) {
      if (!error) {
        self.traceLength = length
      }
    })
  })

  this.parent.event.register('indexChanged', this, function (index) {
    if (index < 0) return
    if (self.parent.currentStepIndex !== index) return

    if (index === self.traceLength - 1) {
      var storageJSON = {}
      for (var k in self.addresses) {
        var address = self.addresses[k]
        var storageViewer = new StorageViewer({
          stepIndex: self.parent.currentStepIndex,
          tx: self.parent.tx
        }, self.storageResolver)
        storageViewer.storageRange(function (error, result) {
          if (!error) {
            storageJSON[address] = result
            self.basicPanel.update(storageJSON)
          }
        })
      }
    } else {
      self.basicPanel.update({})
    }
  })
}

module.exports = FullStoragesChanges
<|endoftext|>


<commit_before>var app = require('http').createServer(function(){
  // Do nothing...
});
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
var ip = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';

var io = require('socket.io').listen(app);
io.set("origins","*");
app.listen(port, ip);

var request = require('request');
var xml2js = require('xml2js');
var parser = new xml2js.Parser();

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

io.sockets.on('connection', function (socket) {
  console.log('on connection');
  socket.on('searchInput:changed', function (data) {
    var suggestions = {
      google: [],
      bing: []
    };
    var complete = {
      google: false,
      bing: false
    };

    var timeout = setTimeout(function() {
      complete.google = true;
      complete.bing = true;
      maybeEmit();
    }, 5000);

    function maybeEmit() {
      if (complete.google && complete.bing)  {
        clearTimeout(timeout);
        socket.emit('suggestions:received', suggestions);
      }
    }

    var getSuggestions = {
      google: function(search) {
        this.get('http://www.google.com/complete/search?output=toolbar&q=' + encodeURIComponent(search), 'google', function(data, next) {
          parser.parseString(data, function (err, result) {
            var suggestions = [];
            if (result.toplevel && result.toplevel.CompleteSuggestion) {
              suggestions = result.toplevel.CompleteSuggestion;
              for (var i = 0; i < suggestions.length; i++) {
                var suggestion = suggestions[i];
                if (suggestion && suggestion.suggestion &&
                  suggestion.suggestion[0] &&
                  suggestion.suggestion[0]['$'] && suggestion.suggestion[0]['$'].data) {

                  suggestions[i] = suggestion.suggestion[0]['$'].data;
                } else {
                  suggestions[i] = '';
                }
              }
            }
            next(suggestions);
          });
        });
      },
      bing: function(search) {
        this.get('http://api.bing.com/osjson.aspx?query=' + encodeURIComponent(search), 'bing', function(data, next) {
          var suggestions = [];
          data = JSON.parse(data);
          if (data[1]) {
            suggestions = data[1].slice(0, 10);
          }
          next(suggestions);
        });
      },
      getAll: function(search) {
        if (search) {
          this.google(search);
          this.bing(search);
        }
      },
      get: function(url, provider, alterData) {
        function done() {
          complete[provider] = true;
          maybeEmit();
        }

        request(url, function(err, res, body) {
          if (err) {
            done();
          }
          alterData(body, function(data) {
            suggestions[provider] = data;
            done();
          });
        });
      }
    };

    getSuggestions.getAll(data.search);

  });
});

<commit_msg>Changing origin to include port...<commit_after>var app = require('http').createServer(function(){
  // Do nothing...
});
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
var ip = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';

var io = require('socket.io').listen(app);
io.set('origins', '*:*');
app.listen(port, ip);

var request = require('request');
var xml2js = require('xml2js');
var parser = new xml2js.Parser();

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

io.sockets.on('connection', function (socket) {
  console.log('on connection');
  socket.on('searchInput:changed', function (data) {
    var suggestions = {
      google: [],
      bing: []
    };
    var complete = {
      google: false,
      bing: false
    };

    var timeout = setTimeout(function() {
      complete.google = true;
      complete.bing = true;
      maybeEmit();
    }, 5000);

    function maybeEmit() {
      if (complete.google && complete.bing)  {
        clearTimeout(timeout);
        socket.emit('suggestions:received', suggestions);
      }
    }

    var getSuggestions = {
      google: function(search) {
        this.get('http://www.google.com/complete/search?output=toolbar&q=' + encodeURIComponent(search), 'google', function(data, next) {
          parser.parseString(data, function (err, result) {
            var suggestions = [];
            if (result.toplevel && result.toplevel.CompleteSuggestion) {
              suggestions = result.toplevel.CompleteSuggestion;
              for (var i = 0; i < suggestions.length; i++) {
                var suggestion = suggestions[i];
                if (suggestion && suggestion.suggestion &&
                  suggestion.suggestion[0] &&
                  suggestion.suggestion[0]['$'] && suggestion.suggestion[0]['$'].data) {

                  suggestions[i] = suggestion.suggestion[0]['$'].data;
                } else {
                  suggestions[i] = '';
                }
              }
            }
            next(suggestions);
          });
        });
      },
      bing: function(search) {
        this.get('http://api.bing.com/osjson.aspx?query=' + encodeURIComponent(search), 'bing', function(data, next) {
          var suggestions = [];
          data = JSON.parse(data);
          if (data[1]) {
            suggestions = data[1].slice(0, 10);
          }
          next(suggestions);
        });
      },
      getAll: function(search) {
        if (search) {
          this.google(search);
          this.bing(search);
        }
      },
      get: function(url, provider, alterData) {
        function done() {
          complete[provider] = true;
          maybeEmit();
        }

        request(url, function(err, res, body) {
          if (err) {
            done();
          }
          alterData(body, function(data) {
            suggestions[provider] = data;
            done();
          });
        });
      }
    };

    getSuggestions.getAll(data.search);

  });
});

<|endoftext|>


<commit_before>
$(document).ready(function () {
	if (!window.bestest_timer) {
		return;
	}

	var cleanState = {
		started: null,
		descr: null,
		project: null,
		issue: null,
		activity: null,
		comment: null,
		activities: null,
	};

	var state;
	var stateKey = 'bestest_timer/' + bestest_timer.user_id;
	var button   = $('<button class="bestest_timer_button"></button>');
	var dialog   = null;

	function updateUI() {
		button.text(state.started ? t('recording') : t('start'))
			.attr('title',
			state.started ? t('logging_since', { descr: state.descr, time: toTime(new Date(state.started)) }) : null);
	}

	function loadState() {
		state = JSON.parse(localStorage.getItem(stateKey) || JSON.stringify(cleanState));
		updateUI();
	}

	function clearState() {
		state = JSON.parse(JSON.stringify(cleanState));
		saveState();
	}

	function saveState() {
		localStorage.setItem(stateKey, JSON.stringify(state));
		updateUI();
	}

	$(window).bind('storage', function(event) {
		if (event.originalEvent.key === stateKey) {
			loadState();

			if (!state.started && dialog) {
				dialog.dialog('close');
			}
		}
	});

	function toTime(date) {
		return date.toLocaleTimeString(undefined, { hour: 'numeric', minute: 'numeric' });
	}

	function start() {
		if (!bestest_timer.api_key) {
			alert(t('need_rest_api'));
		}
		else if (!bestest_timer.project && !bestest_timer.issue) {
			alert(t('nothing_inferred'));
		}
		else if (!bestest_timer.access) {
			alert(t('no_permission', { project: bestest_timer.project.name }));
		}
		else {
			state.started = Date.now();
			state.descr = t(bestest_timer.issue ? 'state_descr_issue' : 'state_descr', {
				project: bestest_timer.project.name,
				issue: bestest_timer.issue && bestest_timer.issue.id
			});
			state.project = bestest_timer.project.id;
			state.issue = bestest_timer.issue && bestest_timer.issue.id;
			state.activity = (bestest_timer.activities.filter(function (activity) { return activity.is_default; })[0] || { id: null }).id;
			state.activities = bestest_timer.activities;
			saveState();
		}
	}

	function commit() {
		var stopped = new Date();
		var comment = ((state.comment || '') + ' [' + toTime(new Date(state.started)) + '-' + toTime(stopped) + ']').trim();

		$.ajax(bestest_timer.timelog_url, {
			method: 'POST',
			data: JSON.stringify({
				time_entry: {
					project_id: state.project,
					issue_id: state.issue,
					activity_id: state.activity,
					hours: (stopped - state.started) / 1000 / 60 / 60,
					comments: comment,
				}
			}),
			contentType: 'application/json',
			headers: {
				'X-Redmine-API-Key': bestest_timer.api_key,
			},
		})
		.done(function (response) {
			var te = response.time_entry;
			displayNotification(t('notification_title', { hours: te.hours, descr: state.descr }), te.comments, te.id);
			clearState();
		})
		.fail(function ($xhr) {
			console.log(arguments);
			alert(t('submit_failed', { error: $xhr.responseJSON && $xhr.responseJSON.errors }));
		});
	}

	function discard() {
		clearState();
	}

	function openDialog() {
		if (dialog) {
			dialog.dialog('destroy');
		}

		var form       = $('<form/>').submit(false);
		var activities = $('<fieldset>').append($('<legend/>').text(t('activity')));
		var labels     = $('<div>', { "class": "bestest_timer_activities" }).appendTo(activities);

		state.activities.forEach(function (activity) {
			$('<label/>')
				.append($('<input/>', { type: 'radio', name: 'activity', value: activity.id, checked: activity.id === state.activity })
					.click(function() {
						state.activity = Number(this.value);
					})
				)
				.append(document.createTextNode(activity.name))
				.appendTo(labels);
		});

		[
			$('<fieldset/>').append($('<legend/>').text(t('status'))).append(document.createTextNode(button.attr('title'))),
			activities,
			$('<fieldset/>').append($('<legend/>').text(t('comment'))).append(
				$('<input id="bestest_timer_comment" type="text" autocomplete="off" autofocus />').attr('value', state.comment)
					.change(function () {
						state.comment = this.value;
					})
					.keyup(function (event) {
						if (event.keyCode === 13) {
							commit();
							dialog.dialog('close');
						}
					})
			)
		].forEach(function (elem) {
			form.append(elem);
		});

		dialog = form.dialog({
			dialogClass: 'bestest_timer_dialog',
			position: { my: 'right top', at: 'right bottom', of: button },
			width: 400,
			draggable: false,
			modal: true,
			hide: 200,
			show: 200,
			title: t('plugin_name'),

			open: function() { // Hack to remove black line in Safari
				if (/Apple/.test(window.navigator.vendor)) {
					$('.bestest_timer_dialog').each(function(idx, elem) {
						elem.style.background = window.getComputedStyle(elem).backgroundColor;
					});
				}
			},

			buttons: [
				{
					text: t('commit'), icons: { primary: 'ui-icon-clock' }, click: function () {
						commit();
						dialog.dialog('close');
					}
				},
				{
					text: t('discard'), icons: { primary: 'ui-icon-trash' }, click: function () {
						discard();
						dialog.dialog('close');
					}
				},
				{
					text: t('close'), icons: { primary: 'ui-icon-close' }, click: function () {
						saveState();
						dialog.dialog('close');
					}
				},
			]
		});
	}

	function displayNotification(title, message, idx) {
		if (!window.Notification) {
			alert(title + ': ' + message);
		}
		else if (Notification.permission === 'granted') {
			$(new Notification(title, { body: message })).click(function () {
				window.location.href = bestest_timer.timelog_idx.replace('XXX', idx);
			});
		}
		else if (Notification.permission !== 'denied') {
			Notification.requestPermission(function (permission) {
				if (permission === 'granted') {
					displayNotification(title, message, idx);
				}
			});
		}
	}

	function t(key, props) {
		return (bestest_timer.lang[key] || key).replace(/%{([^}]+)}/g, function(_, prop) {
			return String(Object(props)[prop]);
		});
	}

	button.click(function () {
		if (!state.started) {
			start();
		}
		else {
			openDialog();
		}
	});

	loadState();

	$('#quick-search').append(button);
});

<commit_msg>Force ISO time format.<commit_after>
$(document).ready(function () {
	if (!window.bestest_timer) {
		return;
	}

	var cleanState = {
		started: null,
		descr: null,
		project: null,
		issue: null,
		activity: null,
		comment: null,
		activities: null,
	};

	var state;
	var stateKey = 'bestest_timer/' + bestest_timer.user_id;
	var button   = $('<button class="bestest_timer_button"></button>');
	var dialog   = null;

	function updateUI() {
		button.text(state.started ? t('recording') : t('start'))
			.attr('title',
			state.started ? t('logging_since', { descr: state.descr, time: toTime(new Date(state.started)) }) : null);
	}

	function loadState() {
		state = JSON.parse(localStorage.getItem(stateKey) || JSON.stringify(cleanState));
		updateUI();
	}

	function clearState() {
		state = JSON.parse(JSON.stringify(cleanState));
		saveState();
	}

	function saveState() {
		localStorage.setItem(stateKey, JSON.stringify(state));
		updateUI();
	}

	$(window).bind('storage', function(event) {
		if (event.originalEvent.key === stateKey) {
			loadState();

			if (!state.started && dialog) {
				dialog.dialog('close');
			}
		}
	});

	function toTime(date) {
		return date.toLocaleTimeString('en-GB', { hour: 'numeric', minute: 'numeric' });
	}

	function start() {
		if (!bestest_timer.api_key) {
			alert(t('need_rest_api'));
		}
		else if (!bestest_timer.project && !bestest_timer.issue) {
			alert(t('nothing_inferred'));
		}
		else if (!bestest_timer.access) {
			alert(t('no_permission', { project: bestest_timer.project.name }));
		}
		else {
			state.started = Date.now();
			state.descr = t(bestest_timer.issue ? 'state_descr_issue' : 'state_descr', {
				project: bestest_timer.project.name,
				issue: bestest_timer.issue && bestest_timer.issue.id
			});
			state.project = bestest_timer.project.id;
			state.issue = bestest_timer.issue && bestest_timer.issue.id;
			state.activity = (bestest_timer.activities.filter(function (activity) { return activity.is_default; })[0] || { id: null }).id;
			state.activities = bestest_timer.activities;
			saveState();
		}
	}

	function commit() {
		var stopped = new Date();
		var comment = ((state.comment || '') + ' [' + toTime(new Date(state.started)) + '-' + toTime(stopped) + ']').trim();

		$.ajax(bestest_timer.timelog_url, {
			method: 'POST',
			data: JSON.stringify({
				time_entry: {
					project_id: state.project,
					issue_id: state.issue,
					activity_id: state.activity,
					hours: (stopped - state.started) / 1000 / 60 / 60,
					comments: comment,
				}
			}),
			contentType: 'application/json',
			headers: {
				'X-Redmine-API-Key': bestest_timer.api_key,
			},
		})
		.done(function (response) {
			var te = response.time_entry;
			displayNotification(t('notification_title', { hours: te.hours, descr: state.descr }), te.comments, te.id);
			clearState();
		})
		.fail(function ($xhr) {
			console.log(arguments);
			alert(t('submit_failed', { error: $xhr.responseJSON && $xhr.responseJSON.errors }));
		});
	}

	function discard() {
		clearState();
	}

	function openDialog() {
		if (dialog) {
			dialog.dialog('destroy');
		}

		var form       = $('<form/>').submit(false);
		var activities = $('<fieldset>').append($('<legend/>').text(t('activity')));
		var labels     = $('<div>', { "class": "bestest_timer_activities" }).appendTo(activities);

		state.activities.forEach(function (activity) {
			$('<label/>')
				.append($('<input/>', { type: 'radio', name: 'activity', value: activity.id, checked: activity.id === state.activity })
					.click(function() {
						state.activity = Number(this.value);
					})
				)
				.append(document.createTextNode(activity.name))
				.appendTo(labels);
		});

		[
			$('<fieldset/>').append($('<legend/>').text(t('status'))).append(document.createTextNode(button.attr('title'))),
			activities,
			$('<fieldset/>').append($('<legend/>').text(t('comment'))).append(
				$('<input id="bestest_timer_comment" type="text" autocomplete="off" autofocus />').attr('value', state.comment)
					.change(function () {
						state.comment = this.value;
					})
					.keyup(function (event) {
						if (event.keyCode === 13) {
							commit();
							dialog.dialog('close');
						}
					})
			)
		].forEach(function (elem) {
			form.append(elem);
		});

		dialog = form.dialog({
			dialogClass: 'bestest_timer_dialog',
			position: { my: 'right top', at: 'right bottom', of: button },
			width: 400,
			draggable: false,
			modal: true,
			hide: 200,
			show: 200,
			title: t('plugin_name'),

			open: function() { // Hack to remove black line in Safari
				if (/Apple/.test(window.navigator.vendor)) {
					$('.bestest_timer_dialog').each(function(idx, elem) {
						elem.style.background = window.getComputedStyle(elem).backgroundColor;
					});
				}
			},

			buttons: [
				{
					text: t('commit'), icons: { primary: 'ui-icon-clock' }, click: function () {
						commit();
						dialog.dialog('close');
					}
				},
				{
					text: t('discard'), icons: { primary: 'ui-icon-trash' }, click: function () {
						discard();
						dialog.dialog('close');
					}
				},
				{
					text: t('close'), icons: { primary: 'ui-icon-close' }, click: function () {
						saveState();
						dialog.dialog('close');
					}
				},
			]
		});
	}

	function displayNotification(title, message, idx) {
		if (!window.Notification) {
			alert(title + ': ' + message);
		}
		else if (Notification.permission === 'granted') {
			$(new Notification(title, { body: message })).click(function () {
				window.location.href = bestest_timer.timelog_idx.replace('XXX', idx);
			});
		}
		else if (Notification.permission !== 'denied') {
			Notification.requestPermission(function (permission) {
				if (permission === 'granted') {
					displayNotification(title, message, idx);
				}
			});
		}
	}

	function t(key, props) {
		return (bestest_timer.lang[key] || key).replace(/%{([^}]+)}/g, function(_, prop) {
			return String(Object(props)[prop]);
		});
	}

	button.click(function () {
		if (!state.started) {
			start();
		}
		else {
			openDialog();
		}
	});

	loadState();

	$('#quick-search').append(button);
});

<|endoftext|>


<commit_before>var sys = require("sys"),
my_http = require("http");
my_http.createServer(function(request,response){
    sys.puts("solicitud recibida");
    response.writeHeader(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}).listen(8080);
sys.puts("Server Running on 8080");
<commit_msg>add Moment.js<commit_after>
var moment = require('moment');
var sys = require("sys"),
my_http = require("http");
my_http.createServer(function(request,response){
    sys.puts("solicitud recibida");
	response.writeHeader(200, {"Content-Type": "text/plain"});
	response.write("Hello World! La fecha y hora actual es: ");
	response.write(moment().locale('es').format('LLLL'));
	response.end();
}).listen(8080);
sys.puts("Server Running on 8080");
<|endoftext|>


<commit_before>'use strict';

const bodyParser = require('body-parser');
const express = require('express');
const mongoose = require('mongoose');

const app = express();
const port = process.env.PORT || 3000;

app.set('view engine', 'jade');

app.use(bodyParser.urlencoded({
  extended: false
}));

app.get('/', (req, res) => {
  res.send('server route');
});

app.get('/notes/new', (req, res) => {
  res.render('new-note');
});

app.post('/notes', (req, res) => {
  res.redirect('/');
});

app.listen(3000, () => {
  console.log(`nodenotes server running on port: ${port}`)
});<commit_msg>Notes are being saved to the database.<commit_after>'use strict';

const bodyParser = require('body-parser');
const express = require('express');
const mongoose = require('mongoose');

const app = express();
const port = process.env.PORT || 3000;
const Note = mongoose.model('notes', mongoose.Schema({
  title: String,
  text: String
}));

app.set('view engine', 'jade');

app.use(bodyParser.urlencoded({
  extended: false
}));

app.get('/', (req, res) => {
  res.send('server route');
});

app.get('/notes/new', (req, res) => {
  res.render('new-note');
});

app.post('/notes', (req, res) => {
  Note.create(req.body, (err, note) => {
    if (err) throw err;
  });
  console.log(req.body);
  res.redirect('/');
});

mongoose.connect('mongodb://localhost:27017/evernode', (err) => {
  if (err) throw err;

  app.listen(port, () => {
    console.log(`nodenotes server running on port: ${port}`)
  });
});<|endoftext|>


<commit_before>import TopComponent from '../../components/TopComponent/TopComponent';

import UserService from '../../services/UserService/UserService';
import router from '../../modules/Router/Router';
import GameManager from '../../game/GameManager/GameManager';
import loading from '../../components/Loading/Loading';

import './Game.scss';

const preGameData = {
    buttons: [
        {
            text: 'Продолжить',
            url: '',
            class: 'button-main'
        },
        {
            text: 'Начать новую',
            url: '',
            class: 'button-main'
        }
    ]
};

export default class SinglePlayer extends TopComponent {
    constructor() {
        super('div', {class: 'game'}, preGameData);
    }

    show() {
        if (!(UserService.isLoggedIn())) {
            router.go('/');
            return;
        }

        if (this._gameManager) {
            this._gameManager.show();
        } else {
            this.build();
        }
    }

    hide() {
        loading.hide();
        if (this._gameManager) {
            this._gameManager.hide();
        }
    }

    build() {
        if (!(UserService.isLoggedIn())) {
            router.go('/');
            return;
        }

        this._gameManager = new GameManager('singleplayer');
    }
}
<commit_msg>refactor<commit_after>import TopComponent from '../../components/TopComponent/TopComponent';

import UserService from '../../services/UserService/UserService';
import router from '../../modules/Router/Router';
import GameManager from '../../game/GameManager/GameManager';
import loading from '../../components/Loading/Loading';

import './Game.scss';

export default class SinglePlayer extends TopComponent {
    constructor() {
        super('div', {class: 'game'});
    }

    show() {
        if (!(UserService.isLoggedIn())) {
            router.go('/');
            return;
        }

        if (this._gameManager) {
            this._gameManager.show();
        } else {
            this.build();
        }
    }

    hide() {
        loading.hide();
        if (this._gameManager) {
            this._gameManager.hide();
        }
    }

    build() {
        if (!(UserService.isLoggedIn())) {
            router.go('/');
            return;
        }

        this._gameManager = new GameManager('singleplayer');
    }
}
<|endoftext|>


<commit_before>jQuery.noConflict();
(function($) {
    //bootstrap fix noConflict with jquery-ui
    var bootstrapButton = $.fn.button.noConflict(); // return $.fn.button to previously assigned value
    $.fn.bootstrapBtn = bootstrapButton;            // give $().bootstrapBtn the Bootstrap functionality
})(jQuery);

jQuery(document).ready(function ($) {

    $(".chosen-select").chosen({width: "100%"});
    // Sending something...
    function CEMSAjaxCall(submitBtn, cems_action, form) {
        submitBtn.bootstrapBtn('loading');
        var $alert=$('#cems-alert');
        $alert.fadeOut('slow');
        $.post(wpdk_i18n.ajaxURL,
            "action="+cems_action+"&"+$(form).serialize(),
            function (result) {
                var response = new WPDKAjaxResponse(result);

                var textResponse='';
                if (empty(response.error)) {
                    // OK
                    textResponse=response.message+'
'+response.data;
                    $alert.removeClass('alert-danger').addClass('alert-success');
                }
                // Error
                else {
                    if ($(form).attr('name')=== 'subscription-form' )
                    {
                        $('#collapseSubscriptionForm').collapse('hide');
                        $('#customer-email').val($('#subscription-email').val());
                        $('#collapseCustomerForm').collapse('show');
                    }
                    textResponse=response.error;
                    $alert.removeClass('alert-success').addClass('alert-danger');
                }
                $alert.children('.error-response').html(textResponse);
                $alert.children('.book-title-result').text($('#book-title-request').text());
                $alert.fadeIn('slow');
            }
        ).always(function(){
            submitBtn.bootstrapBtn('reset');
        });
    }

    $("#subscription-form").bootstrapValidator({
        message:"Giá trị không hợp lệ",
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        submitHandler: function(validator, form, submitButton) {
            CEMSAjaxCall(submitButton, 'get_book_for_already_customer_action', form);
        },
        fields: {
            subscriptionEmail: {
                validators: {
                    emailAddress: {
                        message:'Địa chỉ email không hợp lệ'
                    },
                    notEmpty: {
                        message:'Email không được để trống'
                    }
                }
            }
        }
    });
    $("#customer-form").bootstrapValidator({
        message:"Giá trị không hợp lệ",
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        submitHandler: function(validator, form, submitButton) {
            CEMSAjaxCall(submitButton, 'register_new_customer_action', form);
        },
        fields: {
            customerName: {
                validators: {
                    notEmpty:{
                        message:'Họ và tên không được để trống'
                    }
                }
            },
            customerEmail: {
                validators: {
                    emailAddress: {
                        message:'Địa chỉ email không hợp lệ'
                    },
                    notEmpty: {
                        message:'Email không được để trống'
                    }
                }
            },
            customerPhone: {
                validators: {
                    notEmpty:{
                        message:'Số điện thoại không được để trống'
                    }
                }
            }
        }
    });
});<commit_msg>fix book title sync on ajax result<commit_after>jQuery.noConflict();
(function($) {
    //bootstrap fix noConflict with jquery-ui
    var bootstrapButton = $.fn.button.noConflict(); // return $.fn.button to previously assigned value
    $.fn.bootstrapBtn = bootstrapButton;            // give $().bootstrapBtn the Bootstrap functionality
})(jQuery);

jQuery(document).ready(function ($) {

    $(".chosen-select").chosen({width: "100%"});
    // Sending something...
    function CEMSAjaxCall(submitBtn, cems_action, form) {
        submitBtn.bootstrapBtn('loading');
        var $alert=$('#cems-alert');
        $alert.fadeOut('slow');
        $.post(wpdk_i18n.ajaxURL,
            "action="+cems_action+"&"+$(form).serialize(),
            function (result) {
                var response = new WPDKAjaxResponse(result);

                var textResponse='';
                if (empty(response.error)) {
                    // OK
                    textResponse=response.message+'
'+response.data;
                    $alert.removeClass('alert-danger').addClass('alert-success');
                }
                // Error
                else {
                    if ($(form).attr('name')=== 'subscription-form' )
                    {
                        $('#collapseSubscriptionForm').collapse('hide');
                        $('#customer-email').val($('#subscription-email').val());
                        $('#collapseCustomerForm').collapse('show');
                    }
                    textResponse=response.error;
                    $alert.removeClass('alert-success').addClass('alert-danger');
                }
                $alert.children('.error-response').html(textResponse);
                $alert.find('.book-title-result').text($('#book-title-request').text());
                $alert.fadeIn('slow');
            }
        ).always(function(){
            submitBtn.bootstrapBtn('reset');
        });
    }

    $("#subscription-form").bootstrapValidator({
        message:"Giá trị không hợp lệ",
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        submitHandler: function(validator, form, submitButton) {
            CEMSAjaxCall(submitButton, 'get_book_for_already_customer_action', form);
        },
        fields: {
            subscriptionEmail: {
                validators: {
                    emailAddress: {
                        message:'Địa chỉ email không hợp lệ'
                    },
                    notEmpty: {
                        message:'Email không được để trống'
                    }
                }
            }
        }
    });
    $("#customer-form").bootstrapValidator({
        message:"Giá trị không hợp lệ",
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        submitHandler: function(validator, form, submitButton) {
            CEMSAjaxCall(submitButton, 'register_new_customer_action', form);
        },
        fields: {
            customerName: {
                validators: {
                    notEmpty:{
                        message:'Họ và tên không được để trống'
                    }
                }
            },
            customerEmail: {
                validators: {
                    emailAddress: {
                        message:'Địa chỉ email không hợp lệ'
                    },
                    notEmpty: {
                        message:'Email không được để trống'
                    }
                }
            },
            customerPhone: {
                validators: {
                    notEmpty:{
                        message:'Số điện thoại không được để trống'
                    }
                }
            }
        }
    });
});<|endoftext|>