<commit_before>/*
 * AngularJS modules to be used together with
 * https://github.com/jrief/django-angular
 *
 * Copyright (c) 2014 Jacob Rief
 * Licensed under the MIT license.
 */

(function(angular, undefined) {
'use strict';

// Correct Angular's form.FormController behavior after rendering bound forms.
angular.module('ng.django.forms', []).directive('form', function() {
	return {
		restrict: 'E',
		scope: 'isolate',
		priority: -1,
		link: function(scope, element, attrs) {
			var form = scope[attrs.name];
			var fields = angular.element(element).find('input');
			angular.forEach(fields, function(field) {
				if (form[field.name] !== undefined) {
					// restore the field's content from the rendered content of bound fields
					form[field.name].$setViewValue(field.defaultValue);
				}
			});
			// restore the form's pristine state
			form.$setPristine();
		}
	};
}).provider('djangoForm', function() {
	var NON_FIELD_ERRORS = '__all__';

	function isNotEmpty(obj) {
		for (var p in obj) {
			if (obj.hasOwnProperty(p))
				return true;
		}
		return false;
	}

	this.$get = function() {
		return {
			// setErrors takes care of updating prepared placeholder fields for displaying form errors
			// deteced by an AJAX submission. Returns true if errors have been added to the form.
			setErrors: function(form, errors) {
				// remove errors from this form, which may have been rejected by an earlier validation
				form.$message = '';
				if (form.$error.hasOwnProperty('rejected')) {
					var old_keys = [];
					angular.forEach(form.$error.rejected, function(rejected) {
						old_keys.push(rejected.$name);
					});
					angular.forEach(old_keys, function(key) {
						form[key].$message = '';
						form[key].$setValidity('rejected', true);
					});
				}
				// add the new upstream errors
				angular.forEach(errors, function(errors, key) {
					if (errors.length > 0) {
						if (key === NON_FIELD_ERRORS) {
							form.$message = errors[0];
						} else {
							form[key].$message = errors[0];
							form[key].$setValidity('rejected', false);
						}
					}
				});
				// reset into pristine state, since the customer restarts with the form
				form.$setPristine();
				return isNotEmpty(errors);
			}
		};
	};
});

// Add three-way data-binding for AngularJS with Django using websockets.
angular.module('ng.django.websocket', []).provider('djangoWebsocket', function() {
	var _prefix;
	var _console = { log: noop, warn: noop, error: noop };

	function noop() {}

	this.prefix = function(prefix) {
		_prefix = prefix;
		return this;
	};

	this.debug = function(debug) {
		if (debug) {
			_console = console;
		}
		return this;
	};

	this.$get = ['$window', '$q', '$timeout', function($window, $q, $timeout) {
		var ws, deferred, timer = null, interval = null, scope, channels, collection;

		function connect(uri) {
			try {
				_console.log("Connecting to "+uri);
				deferred = $q.defer();
				ws = new WebSocket(uri);
				ws.onopen = on_open;
				ws.onmessage = on_message;
				ws.onerror = on_error;
				ws.onclose = on_close;
				timer = null;
			} catch (err) {
				deferred.reject(new Error(err));
			}
		}

		function on_open(evt) {
			_console.log('Connected');
			interval = 500;
			deferred.resolve();
		}

		function on_close(evt) {
			_console.log("Connection closed");
			if (!timer && interval) {
				timer = $timeout(function() {
					connect(ws.url);
				}, interval);
				interval = Math.min(interval + 500, 5000);
			}
		}

		function on_error(evt) {
			_console.error("Websocket connection is broken!");
			deferred.reject(new Error(evt));
		}

		function on_message(evt) {
			try {
				var server_data = JSON.parse(evt.data);
				scope.$apply(function() {
					angular.extend(scope[collection], server_data);
				});
			} catch(e) {
				_console.warn('Data received by server is invalid JSON: ' + evt.data);
			}
		}

		function listener(newValue, oldValue) {
			if (newValue !== undefined) {
				ws.send(JSON.stringify(newValue));
			}
		}

		return {
			connect: function(scope_, channels_, collection_) {
				var parts = [], location = $window.location;
				scope = scope_;
				channels = channels_;
				collection = collection_;
				parts.push(location.protocol === 'https' ? 'wss:' : 'ws:');
				parts.push('//');
				parts.push(location.host);
				parts.push(_prefix);
				parts.push(location.pathname);
				parts.push('?');
				parts.push(channels.join('&'));
				connect(parts.join(''));
				scope[collection] = scope[collection] || {};
				deferred.promise.then(function() {
					scope.$watchCollection(collection, listener);
				});
				return deferred.promise;
			}
		};
	}];
});

})(window.angular);
<commit_msg>Added heartbeat message sending<commit_after>/*
 * AngularJS modules to be used together with
 * https://github.com/jrief/django-angular
 *
 * Copyright (c) 2014 Jacob Rief
 * Licensed under the MIT license.
 */

(function(angular, undefined) {
'use strict';

// Correct Angular's form.FormController behavior after rendering bound forms.
angular.module('ng.django.forms', []).directive('form', function() {
	return {
		restrict: 'E',
		scope: 'isolate',
		priority: -1,
		link: function(scope, element, attrs) {
			var form = scope[attrs.name];
			var fields = angular.element(element).find('input');
			angular.forEach(fields, function(field) {
				if (form[field.name] !== undefined) {
					// restore the field's content from the rendered content of bound fields
					form[field.name].$setViewValue(field.defaultValue);
				}
			});
			// restore the form's pristine state
			form.$setPristine();
		}
	};
}).provider('djangoForm', function() {
	var NON_FIELD_ERRORS = '__all__';

	function isNotEmpty(obj) {
		for (var p in obj) {
			if (obj.hasOwnProperty(p))
				return true;
		}
		return false;
	}

	this.$get = function() {
		return {
			// setErrors takes care of updating prepared placeholder fields for displaying form errors
			// deteced by an AJAX submission. Returns true if errors have been added to the form.
			setErrors: function(form, errors) {
				// remove errors from this form, which may have been rejected by an earlier validation
				form.$message = '';
				if (form.$error.hasOwnProperty('rejected')) {
					var old_keys = [];
					angular.forEach(form.$error.rejected, function(rejected) {
						old_keys.push(rejected.$name);
					});
					angular.forEach(old_keys, function(key) {
						form[key].$message = '';
						form[key].$setValidity('rejected', true);
					});
				}
				// add the new upstream errors
				angular.forEach(errors, function(errors, key) {
					if (errors.length > 0) {
						if (key === NON_FIELD_ERRORS) {
							form.$message = errors[0];
						} else {
							form[key].$message = errors[0];
							form[key].$setValidity('rejected', false);
						}
					}
				});
				// reset into pristine state, since the customer restarts with the form
				form.$setPristine();
				return isNotEmpty(errors);
			}
		};
	};
});

// Add three-way data-binding for AngularJS with Django using websockets.
angular.module('ng.django.websocket', []).provider('djangoWebsocket', function() {
	var _prefix;
	var _console = { log: noop, warn: noop, error: noop };

	function noop() {}

	this.prefix = function(prefix) {
		_prefix = prefix;
		return this;
	};

	this.debug = function(debug) {
		if (debug) {
			_console = console;
		}
		return this;
	};

	this.$get = ['$window', '$q', '$timeout', '$interval', function($window, $q, $timeout, $interval) {
		var ws, deferred, timer_promise = null, wait_for = null, scope, channels, collection;
		var heartbeat_msg = '--heartbeat--', heartbeat_promise = null, missed_heartbeats = 0;

		function connect(uri) {
			try {
				_console.log("Connecting to "+uri);
				deferred = $q.defer();
				ws = new WebSocket(uri);
				ws.onopen = on_open;
				ws.onmessage = on_message;
				ws.onerror = on_error;
				ws.onclose = on_close;
				timer_promise = null;
			} catch (err) {
				deferred.reject(new Error(err));
			}
		}

		function on_open(evt) {
			_console.log('Connected');
			wait_for = 500;
			deferred.resolve();
			if (heartbeat_promise === null) {
				missed_heartbeats = 0;
				heartbeat_promise = $interval(send_heartbeat, 5000);
			}
		}

		function on_close(evt) {
			_console.log("Connection closed");
			if (!timer_promise && wait_for) {
				timer_promise = $timeout(function() {
					connect(ws.url);
				}, wait_for);
				wait_for = Math.min(wait_for + 500, 5000);
			}
		}

		function on_error(evt) {
			_console.error("Websocket connection is broken!");
			deferred.reject(new Error(evt));
		}

		function on_message(evt) {
			try {
				var server_data = JSON.parse(evt.data);
				scope.$apply(function() {
					angular.extend(scope[collection], server_data);
				});
			} catch(e) {
				_console.warn('Data received by server is invalid JSON: ' + evt.data);
			}
		}

		function send_heartbeat() {
			try {
				missed_heartbeats++;
				if (missed_heartbeats > 3)
					throw new Error("Too many missed heartbeats.");
				ws.send(heartbeat_msg);
				console.log('heartbeat');
			} catch(e) {
				$interval.cancel(heartbeat_promise);
				heartbeat_promise = null;
				_console.warn("Closing connection. Reason: " + e.message);
				ws.close();
			}
		}

		function listener(newValue, oldValue) {
			if (newValue !== undefined) {
				ws.send(JSON.stringify(newValue));
			}
		}

		return {
			connect: function(scope_, channels_, collection_) {
				var parts = [], location = $window.location;
				scope = scope_;
				channels = channels_;
				collection = collection_;
				parts.push(location.protocol === 'https' ? 'wss:' : 'ws:');
				parts.push('//');
				parts.push(location.host);
				parts.push(_prefix);
				parts.push(location.pathname);
				parts.push('?');
				parts.push(channels.join('&'));
				connect(parts.join(''));
				scope[collection] = scope[collection] || {};
				deferred.promise.then(function() {
					scope.$watchCollection(collection, listener);
				});
				return deferred.promise;
			}
		};
	}];
});

})(window.angular);
<|endoftext|>


<commit_before>'use strict';
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

// ----------------
// ENV
const development = process.env.NODE_ENV === 'development';
const testing = process.env.NODE_ENV === 'testing';
const staging = process.env.NODE_ENV === 'staging';
const production = process.env.NODE_ENV === 'production';
console.log('ENVIRONMENT \x1b[36m%s\x1b[0m', process.env.NODE_ENV);

// ----------------
// SOURCE MAP CONF

const sourceMapType = (development) ? 'inline-source-map' : false;

// ----------------
// BASE CONFIG

let config = {
  devtool: sourceMapType,
  context: __dirname,
  entry: {
    site: './src/site.js',
    preflight: './src/preflight.js'
  },
  output: {
    path: path.join(__dirname, 'public/assets'),
    filename: '[name].js'
  },
  resolve: {
    modules: [
      path.resolve('./src/'),
      'src',
      'node_modules',
      'bower_components'
    ]
  }
};

// ----------------
// MODULE RULES

config.module = {
  rules: [
    {
      test: /\.(css)$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          {
            loader: 'css-loader',
            options: {
              importLoaders: 2,
              sourceMap: true
            }
          },
          {
            loader: 'postcss-loader',
            options: {
              sourceMap: true
            }
          },
          {
            loader: 'resolve-url-loader',
            options: {
              keepQuery: true
            }
          }
        ]
      })
    },
    {
      test: /\.(scss)$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          {
            loader: 'css-loader',
            options: {
              importLoaders: 3,
              sourceMap: true
            }
          },
          {
            loader: 'postcss-loader',
            options: {
              sourceMap: true
            }
          },
          {
            loader: 'resolve-url-loader',
            options: {
              keepQuery: true
            }
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true,
              data: `$env: ${JSON.stringify(process.env.NODE_ENV || 'development')};`
            }
          }
        ]
      })
    },
    // raster and vector images (we need to exclude possible svg webfont)
    {
      test: /\.(png|jpg|jpeg|gif|svg)$/,
      exclude: /.-webfont\.svg$/,
      use: [
        {
          loader: 'url-loader',
          options: {
            limit: 10000
          }
        },
        (production)
          ? {
            loader: 'image-webpack-loader'
          }
          : null
      ].filter((e) => e !== null)
    },
    // webfont files always have to be ended with *-webfont.ext
    {
      test: /.-webfont\.eot(\?v=\d+\.\d+\.\d+)?$/,
      use: 'url-loader?limit=100&mimetype=application/vnd.ms-fontobject'
    },
    {
      test: /.-webfont\.woff2(\?v=\d+\.\d+\.\d+)?$/,
      use: 'url-loader?limit=100&mimetype=application/font-woff2'
    },
    {
      test: /.-webfont\.woff(\?v=\d+\.\d+\.\d+)?$/,
      use: 'url-loader?limit=100&mimetype=application/font-woff'
    },
    {
      test: /.-webfont\.ttf(\?v=\d+\.\d+\.\d+)?$/,
      use: 'url-loader?limit=100&mimetype=application/x-font-ttf'
    },
    {
      test: /.-webfont\.svg(\?v=\d+\.\d+\.\d+)?$/,
      use: 'url-loader?limit=100&mimetype=image/svg+xml'
    }
  ]
};

// ----------------
// PLUGINS
config.plugins = [];

// ----------------
// WEBPACK DEFINE PLUGIN
// define environmental variables into scripts

config.plugins.push(new webpack.DefinePlugin({
  'process.env': {
    'NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
  },
  __CLIENT__: true,
  __SERVER__: false,
  __DEVELOPMENT__: development,
  __TESTING__: testing,
  __STAGING__: staging,
  __PRODUCTION__: production,
  __DEVTOOLS__: development
}));

// ----------------
// WEBPACK BUILT IN OPTIMIZATION

if (production) {
  config.plugins.push(new webpack.optimize.OccurrenceOrderPlugin());
  config.plugins.push(new webpack.optimize.LimitChunkCountPlugin({maxChunks: 15}));
  config.plugins.push(new webpack.optimize.MinChunkSizePlugin({minChunkSize: 10000}));
  config.plugins.push(new webpack.optimize.UglifyJsPlugin({
    compress: {
      sequences: true,
      dead_code: true,
      conditionals: true,
      booleans: true,
      unused: true,
      if_return: true,
      join_vars: true,
      drop_console: true,
      warnings: false
    },
    mangle: false,
    beautify: false,
    output: {
      space_colon: false,
      comments: false
    },
    extractComments: false,
    sourceMap: sourceMapType
  }));
}

// ----------------
// ExtractTextPlugin CONFIG

config.plugins.push(new ExtractTextPlugin({
  filename: '[name].css',
  disable: false, // always enabled for now
  allChunks: true
}));

// ----------------
// POSTCSS LOADER CONFIG

// defined in .postcssrc.js

// ----------------
// BROWSERLIST CONFIG

// defined in .browserslistrc

module.exports = config;
<commit_msg>add note about browserslist<commit_after>'use strict';
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

// ----------------
// ENV
const development = process.env.NODE_ENV === 'development';
const testing = process.env.NODE_ENV === 'testing';
const staging = process.env.NODE_ENV === 'staging';
const production = process.env.NODE_ENV === 'production';
console.log('ENVIRONMENT \x1b[36m%s\x1b[0m', process.env.NODE_ENV);

// ----------------
// SOURCE MAP CONF

const sourceMapType = (development) ? 'inline-source-map' : false;

// ----------------
// BASE CONFIG

let config = {
  devtool: sourceMapType,
  context: __dirname,
  entry: {
    site: './src/site.js',
    preflight: './src/preflight.js'
  },
  output: {
    path: path.join(__dirname, 'public/assets'),
    filename: '[name].js'
  },
  resolve: {
    modules: [
      path.resolve('./src/'),
      'src',
      'node_modules',
      'bower_components'
    ]
  }
};

// ----------------
// MODULE RULES

config.module = {
  rules: [
    {
      test: /\.(css)$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          {
            loader: 'css-loader',
            options: {
              importLoaders: 2,
              sourceMap: true
            }
          },
          {
            loader: 'postcss-loader',
            options: {
              sourceMap: true
            }
          },
          {
            loader: 'resolve-url-loader',
            options: {
              keepQuery: true
            }
          }
        ]
      })
    },
    {
      test: /\.(scss)$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          {
            loader: 'css-loader',
            options: {
              importLoaders: 3,
              sourceMap: true
            }
          },
          {
            loader: 'postcss-loader',
            options: {
              sourceMap: true
            }
          },
          {
            loader: 'resolve-url-loader',
            options: {
              keepQuery: true
            }
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true,
              data: `$env: ${JSON.stringify(process.env.NODE_ENV || 'development')};`
            }
          }
        ]
      })
    },
    // raster and vector images (we need to exclude possible svg webfont)
    {
      test: /\.(png|jpg|jpeg|gif|svg)$/,
      exclude: /.-webfont\.svg$/,
      use: [
        {
          loader: 'url-loader',
          options: {
            limit: 10000
          }
        },
        (production)
          ? {
            loader: 'image-webpack-loader'
          }
          : null
      ].filter((e) => e !== null)
    },
    // webfont files always have to be ended with *-webfont.ext
    {
      test: /.-webfont\.eot(\?v=\d+\.\d+\.\d+)?$/,
      use: 'url-loader?limit=100&mimetype=application/vnd.ms-fontobject'
    },
    {
      test: /.-webfont\.woff2(\?v=\d+\.\d+\.\d+)?$/,
      use: 'url-loader?limit=100&mimetype=application/font-woff2'
    },
    {
      test: /.-webfont\.woff(\?v=\d+\.\d+\.\d+)?$/,
      use: 'url-loader?limit=100&mimetype=application/font-woff'
    },
    {
      test: /.-webfont\.ttf(\?v=\d+\.\d+\.\d+)?$/,
      use: 'url-loader?limit=100&mimetype=application/x-font-ttf'
    },
    {
      test: /.-webfont\.svg(\?v=\d+\.\d+\.\d+)?$/,
      use: 'url-loader?limit=100&mimetype=image/svg+xml'
    }
  ]
};

// ----------------
// PLUGINS
config.plugins = [];

// ----------------
// WEBPACK DEFINE PLUGIN
// define environmental variables into scripts

config.plugins.push(new webpack.DefinePlugin({
  'process.env': {
    'NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
  },
  __CLIENT__: true,
  __SERVER__: false,
  __DEVELOPMENT__: development,
  __TESTING__: testing,
  __STAGING__: staging,
  __PRODUCTION__: production,
  __DEVTOOLS__: development
}));

// ----------------
// WEBPACK BUILT IN OPTIMIZATION

if (production) {
  config.plugins.push(new webpack.optimize.OccurrenceOrderPlugin());
  config.plugins.push(new webpack.optimize.LimitChunkCountPlugin({maxChunks: 15}));
  config.plugins.push(new webpack.optimize.MinChunkSizePlugin({minChunkSize: 10000}));
  config.plugins.push(new webpack.optimize.UglifyJsPlugin({
    compress: {
      sequences: true,
      dead_code: true,
      conditionals: true,
      booleans: true,
      unused: true,
      if_return: true,
      join_vars: true,
      drop_console: true,
      warnings: false
    },
    mangle: false,
    beautify: false,
    output: {
      space_colon: false,
      comments: false
    },
    extractComments: false,
    sourceMap: sourceMapType
  }));
}

// ----------------
// ExtractTextPlugin CONFIG

config.plugins.push(new ExtractTextPlugin({
  filename: '[name].css',
  disable: false, // always enabled for now
  allChunks: true
}));

// ----------------
// POSTCSS LOADER CONFIG

// defined in .postcssrc.js

// ----------------
// BROWSERLIST CONFIG

// currently defined "inline" in .postcssrc.js
// will be defined in .browserslistrc in later guide steps

module.exports = config;
<|endoftext|>


<commit_before>module.exports = function(app){ //Define das rotas - chamada de paginas
app.get('/contas/deleteConta/:uid', function (req, res) {

 var connection = app.infra.connectionFactory(); //abre conexao
    var contasDAO =  new app.infra.ContasDAO(connection);
    contasDAO.deleta(req.params.uid, function(erros,resultados){
       console.log(erros);
        res.redirect('/contas');
        });
connection.end();
});

app.get('/contas/edita/:uid', function (req, res) {

 var connection = app.infra.connectionFactory(); //abre conexao
    var contasDAO =  new app.infra.ContasDAO(connection);
    contasDAO.selecionaConta(req.params.uid, function(erros,resultados){
	var resultado = resultados[0];

       console.log(resultado);

 res.render('contas/edit',
            {errosValidacao:{},contas: {'id': resultado.id, 'descricao': resultado.descricao, 'valor': resultado.valor, 'categoria': resultado.nomeCategoria ,'categoriaId': resultado.categoria }});

        });
connection.end();
});

    app.get('/contas',function(req,res,next){
    var connection = app.infra.connectionFactory(); //abre conexao
    var contasDAO =  new app.infra.ContasDAO(connection);
    var categoriasDAO = new app.infra.CategoriasDAO(connection);

    contasDAO.lista(function(erros,resultados){
        if(erros){
            return next(erros);
        }
        res.format({
            html: function(){
                res.render('contas/lista',{lista:resultados});
            },
            json: function(){
                res.json(resultados);
            }
        });
    });

        connection.end(); //fecha conexao

    // categoriasDAO.lista(function(erros,resultados){
//         if(erros){
//             return next(erros);
//         }
//         res.format({
//             html: function(){
//                 res.render('contas/form',{lista:resultados});

//             },
//             json: function(){
//                 res.json(resultados);
//             }
//         });
//     });

//     connection.end(); //fecha conexao
 });

    app.get('/contas/form', function(req,res){
	var connection = app.infra.connectionFactory(); //abre conexao
    var categoriasDAO =  new app.infra.CategoriasDAO(connection);
    categoriasDAO.lista(function(erros,resultados){
        if(erros){
            return next(erros);
        }
        res.format({
            html: function(){
                res.render('contas/form',{contas:{}, listaCategorias : resultados,errosValidacao:{}});
            },
            json: function(){
                res.json(resultados);
            }
        });
    });

    connection.end(); //fecha conexao

});

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

    var contas = req.body;
    console.log(contas);
   req.assert('descricao','Descricao é obrigatoria').notEmpty();
   req.assert('valor','Formato invalido').isFloat();

   var erros = req.validationErrors();
   if(erros){
       res.format({
            html: function(){
                 res.status(400).render('contas/edit',{errosValidacao:erros,contas:contas});
            },
            json: function(){
                res.status(400).json(erros);
            }
        });
        return;
   }

    var connection = app.infra.connectionFactory(); //abre conexao
    var contasDAO =  new app.infra.ContasDAO(connection);
    contasDAO.atualizaConta(contas, function(erros,resultados){
       console.log(erros);
        res.redirect('/contas');
        });
connection.end();
});

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

    var contas = req.body;

   req.assert('descricao','Descricao é obrigatoria').notEmpty();
   req.assert('valor','Formato invalido').isFloat();

   var erros = req.validationErrors();
   if(erros){
       res.format({
            html: function(){
                 res.status(400).render('contas/form',{errosValidacao:erros,contas:contas});
            },
            json: function(){
                res.status(400).json(erros);
            }
        });
        return;
   }

    var connection = app.infra.connectionFactory(); //abre conexao
    var contasDAO =  new app.infra.ContasDAO(connection);
    contasDAO.salva(contas, function(erros,resultados){
       console.log(erros);
        res.redirect('/contas');
        });
});
}

// app.get('contas/remove',function(){
//     var connection = app.infra.connectionFactory();
//     var contasBanco = app.infra.contasBanco(connection);
//     var contas = contasBanco.carrega(id,callback);

//     if(contas){
//         contasBanco.remove(contas,callback);
//     }
// })
<commit_msg>Update contas.js<commit_after>module.exports = function(app){ //Define das rotas - chamada de paginas
app.get('/contas/deleteConta/:uid', function (req, res) {

 var connection = app.infra.connectionFactory(); //abre conexao
    var contasDAO =  new app.infra.ContasDAO(connection);
    contasDAO.deleta(req.params.uid, function(erros,resultados){
       console.log(erros);
        res.redirect('/contas');
        });
connection.end();
});

app.get('/contas/edita/:uid', function (req, res) {

 var connection = app.infra.connectionFactory(); //abre conexao
    var contasDAO =  new app.infra.ContasDAO(connection);
    contasDAO.selecionaConta(req.params.uid, function(erros,resultados){
	var resultado = resultados[0];

       console.log(resultado);

 res.render('contas/edit',
            {errosValidacao:{},contas: {'id': resultado.id, 'descricao': resultado.descricao, 'valor': resultado.valor, 'categoria': resultado.nomeCategoria ,'categoriaId': resultado.categoria }});

        });
connection.end();
});

    app.get('/contas',function(req,res,next){
    var connection = app.infra.connectionFactory(); //abre conexao
    var contasDAO =  new app.infra.ContasDAO(connection);
    var categoriasDAO = new app.infra.CategoriasDAO(connection);

    contasDAO.lista(function(erros,resultados){
        if(erros){
            return next(erros);
        }
        res.format({
            html: function(){
                res.render('contas/lista',{lista:resultados});
            },
            json: function(){
                res.json(resultados);
            }
        });
    });

        connection.end(); //fecha conexao

 });

    app.get('/contas/form', function(req,res){
	var connection = app.infra.connectionFactory(); //abre conexao
    var categoriasDAO =  new app.infra.CategoriasDAO(connection);
    categoriasDAO.lista(function(erros,resultados){
        if(erros){
            return next(erros);
        }
        res.format({
            html: function(){
                res.render('contas/form',{contas:{}, listaCategorias : resultados,errosValidacao:{}});
            },
            json: function(){
                res.json(resultados);
            }
        });
    });

    connection.end(); //fecha conexao

});

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

    var contas = req.body;
    console.log(contas);
   req.assert('descricao','Descricao é obrigatoria').notEmpty();
   req.assert('valor','Formato invalido').isFloat();

   var erros = req.validationErrors();
   if(erros){
       res.format({
            html: function(){
                 res.status(400).render('contas/edit',{errosValidacao:erros,contas:contas});
            },
            json: function(){
                res.status(400).json(erros);
            }
        });
        return;
   }

    var connection = app.infra.connectionFactory(); //abre conexao
    var contasDAO =  new app.infra.ContasDAO(connection);
    contasDAO.atualizaConta(contas, function(erros,resultados){
       console.log(erros);
        res.redirect('/contas');
        });
connection.end();
});

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

    var contas = req.body;

   req.assert('descricao','Descricao é obrigatoria').notEmpty();
   req.assert('valor','Formato invalido').isFloat();

   var erros = req.validationErrors();
   if(erros){
       res.format({
            html: function(){
                 res.status(400).render('contas/form',{errosValidacao:erros,contas:contas});
            },
            json: function(){
                res.status(400).json(erros);
            }
        });
        return;
   }

    var connection = app.infra.connectionFactory(); //abre conexao
    var contasDAO =  new app.infra.ContasDAO(connection);
    contasDAO.salva(contas, function(erros,resultados){
       console.log(erros);
        res.redirect('/contas');
        });
});
}

<|endoftext|>


<commit_before>import Ember from 'ember';
import ENUMS from 'irene/enums';
import ENV from 'irene/config/environment';
import { translationMacro as t } from 'ember-i18n';

const ProjectPreferencesComponent = Ember.Component.extend({

  project: null,
  selectVersion: 0,
  isSavingPreference: false,
  i18n: Ember.inject.service(),
  store: Ember.inject.service(),
  ajax: Ember.inject.service(),
  notify: Ember.inject.service('notification-messages-service'),
  selectedDeviceType: ENUMS.DEVICE_TYPE.NO_PREFERENCE,
  deviceTypes: ENUMS.DEVICE_TYPE.CHOICES.slice(1, -1),

  tDeviceSelected: t("deviceSelected"),
  tPleaseTryAgain: t("pleaseTryAgain"),

  devices: (function() {
    const store = this.get("store");
    store.findAll("device");
  }).property(),

  availableDevices: Ember.computed.filter('devices', function(device) {
    return device.get("platform") === this.get("project.platform");
  }),

  filteredDevices: Ember.computed("availableDevices", "selectedDeviceType", function() {
    const availableDevices = this.get("availableDevices");
    const selectedDeviceType = this.get("selectedDeviceType");
    return availableDevices.filter(function(device) {
      switch (selectedDeviceType) {
        case ENUMS.DEVICE_TYPE.NO_PREFERENCE:
          return true;
        case ENUMS.DEVICE_TYPE.TABLET_REQUIRED:
          return device.get("isTablet");
        case ENUMS.DEVICE_TYPE.PHONE_REQUIRED:
          return !device.get("isTablet");
      }
    });
  }),

  uniqueDevices: Ember.computed.uniqBy("filteredDevices", 'version'),

  actions: {

    selectDeviceType() {
      this.set("selectedDeviceType", parseInt(this.$('#project-device-preference').val()));
      this.set("selectVersion", 0);
    },

    selectVersion() {
      this.set("selectVersion", this.$('#project-version-preference').val());
    },

    versionSelected() {
      const selectVersion = this.get("selectVersion");
      const tDeviceSelected = this.get("tDeviceSelected");
      const tPleaseTryAgain = this.get("tPleaseTryAgain");
      const selectedDeviceType = this.get("selectedDeviceType");

      const projectId = this.get("project.id");
      const devicePreferences = [ENV.endpoints.devicePreferences, projectId].join('/');
      const that = this;
      const data = {
        deviceType: selectedDeviceType,
        platformVersion: selectVersion
      };
      this.set("isSavingPreference", true);
      this.get("ajax").post(devicePreferences, {data})
      .then(function() {
        that.get("notify").success(tDeviceSelected);
        if(!that.isDestroyed) {
          that.set("isSavingPreference", false);
          that.set("projectPreferenceModal", false);
        }
      })
      .catch(function() {
        if(!that.isDestroyed) {
          that.set("isSavingPreference", false);
          that.get("notify").error(tPleaseTryAgain);
        }
      });
    },

    openProjectPreferenceModal() {
      this.set("projectPreferenceModal", true);
    },

    closeProjectPreferenceModal() {
      this.set("projectPreferenceModal", false);
    }
  }
});

export default ProjectPreferencesComponent;
<commit_msg>fix: show device versions<commit_after>import Ember from 'ember';
import ENUMS from 'irene/enums';
import ENV from 'irene/config/environment';
import { translationMacro as t } from 'ember-i18n';

const ProjectPreferencesComponent = Ember.Component.extend({

  project: null,
  selectVersion: 0,
  isSavingPreference: false,
  i18n: Ember.inject.service(),
  ajax: Ember.inject.service(),
  notify: Ember.inject.service('notification-messages-service'),
  selectedDeviceType: ENUMS.DEVICE_TYPE.NO_PREFERENCE,
  deviceTypes: ENUMS.DEVICE_TYPE.CHOICES.slice(1, -1),

  tDeviceSelected: t("deviceSelected"),
  tPleaseTryAgain: t("pleaseTryAgain"),

  devices: (function() {
    return this.get("store").findAll("device");
  }).property(),

  availableDevices: Ember.computed.filter('devices', function(device) {
    return device.get("platform") === this.get("project.platform");
  }),

  filteredDevices: Ember.computed("availableDevices", "selectedDeviceType", function() {
    const availableDevices = this.get("availableDevices");
    const selectedDeviceType = this.get("selectedDeviceType");
    return availableDevices.filter(function(device) {
      switch (selectedDeviceType) {
        case ENUMS.DEVICE_TYPE.NO_PREFERENCE:
          return true;
        case ENUMS.DEVICE_TYPE.TABLET_REQUIRED:
          return device.get("isTablet");
        case ENUMS.DEVICE_TYPE.PHONE_REQUIRED:
          return !device.get("isTablet");
      }
    });
  }),

  uniqueDevices: Ember.computed.uniqBy("filteredDevices", 'version'),

  actions: {

    selectDeviceType() {
      this.set("selectedDeviceType", parseInt(this.$('#project-device-preference').val()));
      this.set("selectVersion", 0);
    },

    selectVersion() {
      this.set("selectVersion", this.$('#project-version-preference').val());
    },

    versionSelected() {
      const selectVersion = this.get("selectVersion");
      const tDeviceSelected = this.get("tDeviceSelected");
      const tPleaseTryAgain = this.get("tPleaseTryAgain");
      const selectedDeviceType = this.get("selectedDeviceType");

      const projectId = this.get("project.id");
      const devicePreferences = [ENV.endpoints.devicePreferences, projectId].join('/');
      const that = this;
      const data = {
        deviceType: selectedDeviceType,
        platformVersion: selectVersion
      };
      this.set("isSavingPreference", true);
      this.get("ajax").post(devicePreferences, {data})
      .then(function() {
        that.get("notify").success(tDeviceSelected);
        if(!that.isDestroyed) {
          that.set("isSavingPreference", false);
          that.set("projectPreferenceModal", false);
        }
      })
      .catch(function() {
        if(!that.isDestroyed) {
          that.set("isSavingPreference", false);
          that.get("notify").error(tPleaseTryAgain);
        }
      });
    },

    openProjectPreferenceModal() {
      this.set("projectPreferenceModal", true);
    },

    closeProjectPreferenceModal() {
      this.set("projectPreferenceModal", false);
    }
  }
});

export default ProjectPreferencesComponent;
<|endoftext|>


<commit_before>import { createSelector } from 'reselect';

/**
 * Direct selector to the sitesView state domain
 */
const selectSitesViewDomain = () => (state) => state.get('sitesView');

/**
 * Other specific selectors
 */

/**
 * Default selector used by SitesView
 */

const makeSelectSitesView = () => createSelector(
  selectSitesViewDomain(),
  (substate) => substate.toJS()
);

export default makeSelectSitesView;
export {
  selectSitesViewDomain,
};
<commit_msg>Add selector<commit_after>import { createSelector } from 'reselect';

/**
 * Direct selector to the sitesView state domain
 */
const selectSitesViewDomain = () => (state) => state.get('sitesView');

/**
 * Other specific selectors
 */

const makeSelectSite = () => createSelector(
  selectSitesViewDomain(),
  (sitesViewState) => sitesViewState.get('sitesView')
);

/**
 * Default selector used by SitesView
 */

const makeSelectSitesView = () => createSelector(
  selectSitesViewDomain(),
  (substate) => substate.toJS()
);

export default makeSelectSitesView;
export {
  selectSitesViewDomain,
  makeSelectSite,
};
<|endoftext|>


<commit_before>Element.prototype.hasClassName = function(name) {
  return new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)").test(this.className);
};

Element.prototype.addClassName = function(name) {
  if (!this.hasClassName(name)) {
    this.className = this.className ? [this.className, name].join(' ') : name;
  }
};

Element.prototype.removeClassName = function(name) {
  if (this.hasClassName(name)) {
    var c = this.className;
    this.className = c.replace(new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)", "g"), "");
  }
};

(function() {
  let currentService, currentPlatform;

  const serviceLinks = $$('.service-select a');
  const platformLinks = $$('.platform-select a');

  // Header animation
  setInterval(function() {
    let serviceLink = serviceLinks[Math.floor(Math.random()*serviceLinks.length)];
    let platformLink = platformLinks[Math.floor(Math.random()*platformLinks.length)];
    $('.getstarted-heading__service').innerHTML = serviceLink.getAttribute('data-name');
    $('.getstarted-heading__platform').innerHTML = platformLink.getAttribute('data-name');
  }, 1000)

  // Click handlers for services/platforms
  let addClickHandlers = function(links, type) {
    Array.prototype.forEach.call(links, link => {
      link.addEventListener('click', function (e) {
        e.preventDefault();
        if(type === 'service') currentService = {name: e.currentTarget.getAttribute('data-name'), doc: e.currentTarget.getAttribute('data-doc')};
        if(type === 'platform') currentPlatform = {name: e.currentTarget.getAttribute('data-name'), doc: e.currentTarget.getAttribute('data-doc')};
        nextStep();
      });
    })
  }

  // Setup initial values
  addClickHandlers(serviceLinks, 'service');
  addClickHandlers(platformLinks, 'platform');
  $('.step1').setAttribute('style', 'pointer-events: none;');
  $('.step2').setAttribute('style', 'pointer-events: none;');

  // Convenience method to find a link
  let findItemIn = function(links, term) {
    return Array.prototype.find.call(links, link => { return link.getAttribute('data-name').toLowerCase() === term});
  }

  // Set values back when you click on the first step
  $('.step1').addEventListener('click', function(e) {
    e.preventDefault();
    $('.step1').setAttribute('style', 'pointer-events: none;');
    $('.step2').setAttribute('style', 'pointer-events: none;');
    $('.step1 h3').innerHTML = 'Select a service';
    $('.step2 h3').innerHTML = 'Select a platform';

    $('.service-select').removeAttribute('style');
    $('.platform-select').setAttribute('style', 'display: none;');
    $('.install').setAttribute('style', 'display: none;');

    $('.step1').removeClassName('step-inactive');
    $('.step2').addClassName('step-inactive');
    $('.step3').addClassName('step-inactive');

    currentService = undefined;
    currentPlatform = undefined;
    window.location.hash = '!';
  });

  // Set values back when you click on the second step
  $('.step2').addEventListener('click', function(e) {
    e.preventDefault();
    $('.step2').setAttribute('style', 'pointer-events: none;');
    $('.step2 h3').innerHTML = 'Select a platform';

    $('.platform-select').removeAttribute('style');
    $('.install').setAttribute('style', 'display: none;');

    $('.step2').removeClassName('step-inactive');
    $('.step3').addClassName('step-inactive');

    currentPlatform = undefined;

    window.location.hash = `${currentService.name}`.toLowerCase();
  });

  // Returns the actual md files
  let getDocs = function(servicePath, platformPath) {
    return new Promise(function(resolve, reject) {
      let serviceDoc, platformDoc;
      let gotADoc = function () {
        if(serviceDoc != undefined && platformDoc != undefined) resolve({service: serviceDoc, platform: platformDoc});
      }

      fetch(`/docs/${servicePath}`)
        .then(response => response.text())
        .then(body => {
          serviceDoc = body;
          gotADoc()
        })

      fetch(`/docs/${platformPath}`)
        .then(response => response.text())
        .then(body => {
          platformDoc = body;
          gotADoc()
        })
    })
  }

  // Go to a specific step
  let step = function(cur) {
    if(cur === 1) {
      // show platform
      $('.service-select').setAttribute('style', 'display: none;');
      $('.platform-select').removeAttribute('style');
      $('.install').setAttribute('style', 'display: none;');
      $('.step1').removeAttribute('style');

      $('.step1').addClassName('step-inactive');
      $('.step2').removeClassName('step-inactive');

      $('.step1 h3').innerHTML = currentService.name;
      window.location.hash = `${currentService.name}`.toLowerCase();
    } else if(cur === 2) {
      // show docs
      $('.service-select').setAttribute('style', 'display: none;');
      $('.platform-select').setAttribute('style', 'display: none;');
      $('.install').removeAttribute('style');
      $('.step2').removeAttribute('style');

      $('.step1').addClassName('step-inactive');
      $('.step2').addClassName('step-inactive');
      $('.step3').removeClassName('step-inactive');

      $('.step1 h3').innerHTML = currentService.name;
      $('.step2 h3').innerHTML = currentPlatform.name;
      window.location.hash = `${currentService.name}#${currentPlatform.name}`.toLowerCase();

      getDocs(currentService.doc, currentPlatform.doc)
        .then(docs => {
          $('.install').innerHTML = `${docs.service}\n${docs.platform}`;
        })
    }
  }

  // Set the next step depending on what has been selected
  let nextStep = function () {
    if(currentService != undefined && currentPlatform === undefined) {
      step(1);
    } else if(currentService != undefined && currentPlatform != undefined) {
      step(2);
    }
  }

  // Set the steps according to the location hash
  if(window.location.hash != "") {
    let serviceHash = window.location.hash.split('#')[1];
    let platformHash = window.location.hash.split('#')[2];
    if(serviceHash) {
      let result = findItemIn(serviceLinks, serviceHash);
      if(result) currentService = {name: result.getAttribute('data-name'), doc: result.getAttribute('data-doc')};
      $('.step1').removeAttribute('style');
    }
    if(platformHash) {
       let result = findItemIn(platformLinks, platformHash);
       if(result) currentPlatform = {name: result.getAttribute('data-name'), doc: result.getAttribute('data-doc')};
       $('.step2').removeAttribute('style');
    }
    nextStep();
  }

})();<commit_msg>Hotfix: resolve to right html file<commit_after>Element.prototype.hasClassName = function(name) {
  return new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)").test(this.className);
};

Element.prototype.addClassName = function(name) {
  if (!this.hasClassName(name)) {
    this.className = this.className ? [this.className, name].join(' ') : name;
  }
};

Element.prototype.removeClassName = function(name) {
  if (this.hasClassName(name)) {
    var c = this.className;
    this.className = c.replace(new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)", "g"), "");
  }
};

(function() {
  let currentService, currentPlatform;

  const serviceLinks = $$('.service-select a');
  const platformLinks = $$('.platform-select a');

  // Header animation
  setInterval(function() {
    let serviceLink = serviceLinks[Math.floor(Math.random()*serviceLinks.length)];
    let platformLink = platformLinks[Math.floor(Math.random()*platformLinks.length)];
    $('.getstarted-heading__service').innerHTML = serviceLink.getAttribute('data-name');
    $('.getstarted-heading__platform').innerHTML = platformLink.getAttribute('data-name');
  }, 1000)

  // Click handlers for services/platforms
  let addClickHandlers = function(links, type) {
    Array.prototype.forEach.call(links, link => {
      link.addEventListener('click', function (e) {
        e.preventDefault();
        if(type === 'service') currentService = {name: e.currentTarget.getAttribute('data-name'), doc: e.currentTarget.getAttribute('data-doc')};
        if(type === 'platform') currentPlatform = {name: e.currentTarget.getAttribute('data-name'), doc: e.currentTarget.getAttribute('data-doc')};
        nextStep();
      });
    })
  }

  // Setup initial values
  addClickHandlers(serviceLinks, 'service');
  addClickHandlers(platformLinks, 'platform');
  $('.step1').setAttribute('style', 'pointer-events: none;');
  $('.step2').setAttribute('style', 'pointer-events: none;');

  // Convenience method to find a link
  let findItemIn = function(links, term) {
    return Array.prototype.find.call(links, link => { return link.getAttribute('data-name').toLowerCase() === term});
  }

  // Set values back when you click on the first step
  $('.step1').addEventListener('click', function(e) {
    e.preventDefault();
    $('.step1').setAttribute('style', 'pointer-events: none;');
    $('.step2').setAttribute('style', 'pointer-events: none;');
    $('.step1 h3').innerHTML = 'Select a service';
    $('.step2 h3').innerHTML = 'Select a platform';

    $('.service-select').removeAttribute('style');
    $('.platform-select').setAttribute('style', 'display: none;');
    $('.install').setAttribute('style', 'display: none;');

    $('.step1').removeClassName('step-inactive');
    $('.step2').addClassName('step-inactive');
    $('.step3').addClassName('step-inactive');

    currentService = undefined;
    currentPlatform = undefined;
    window.location.hash = '!';
  });

  // Set values back when you click on the second step
  $('.step2').addEventListener('click', function(e) {
    e.preventDefault();
    $('.step2').setAttribute('style', 'pointer-events: none;');
    $('.step2 h3').innerHTML = 'Select a platform';

    $('.platform-select').removeAttribute('style');
    $('.install').setAttribute('style', 'display: none;');

    $('.step2').removeClassName('step-inactive');
    $('.step3').addClassName('step-inactive');

    currentPlatform = undefined;

    window.location.hash = `${currentService.name}`.toLowerCase();
  });

  // Returns the actual md files
  let getDocs = function(servicePath, platformPath) {
    return new Promise(function(resolve, reject) {
      let serviceDoc, platformDoc;
      let gotADoc = function () {
        if(serviceDoc != undefined && platformDoc != undefined) resolve({service: serviceDoc, platform: platformDoc});
      }

      fetch(`/docs/${servicePath}.html`)
        .then(response => response.text())
        .then(body => {
          serviceDoc = body;
          gotADoc()
        })

      fetch(`/docs/${platformPath}.html`)
        .then(response => response.text())
        .then(body => {
          platformDoc = body;
          gotADoc()
        })
    })
  }

  // Go to a specific step
  let step = function(cur) {
    if(cur === 1) {
      // show platform
      $('.service-select').setAttribute('style', 'display: none;');
      $('.platform-select').removeAttribute('style');
      $('.install').setAttribute('style', 'display: none;');
      $('.step1').removeAttribute('style');

      $('.step1').addClassName('step-inactive');
      $('.step2').removeClassName('step-inactive');

      $('.step1 h3').innerHTML = currentService.name;
      window.location.hash = `${currentService.name}`.toLowerCase();
    } else if(cur === 2) {
      // show docs
      $('.service-select').setAttribute('style', 'display: none;');
      $('.platform-select').setAttribute('style', 'display: none;');
      $('.install').removeAttribute('style');
      $('.step2').removeAttribute('style');

      $('.step1').addClassName('step-inactive');
      $('.step2').addClassName('step-inactive');
      $('.step3').removeClassName('step-inactive');

      $('.step1 h3').innerHTML = currentService.name;
      $('.step2 h3').innerHTML = currentPlatform.name;
      window.location.hash = `${currentService.name}#${currentPlatform.name}`.toLowerCase();

      getDocs(currentService.doc, currentPlatform.doc)
        .then(docs => {
          $('.install').innerHTML = `${docs.service}\n${docs.platform}`;
        })
    }
  }

  // Set the next step depending on what has been selected
  let nextStep = function () {
    if(currentService != undefined && currentPlatform === undefined) {
      step(1);
    } else if(currentService != undefined && currentPlatform != undefined) {
      step(2);
    }
  }

  // Set the steps according to the location hash
  if(window.location.hash != "") {
    let serviceHash = window.location.hash.split('#')[1];
    let platformHash = window.location.hash.split('#')[2];
    if(serviceHash) {
      let result = findItemIn(serviceLinks, serviceHash);
      if(result) currentService = {name: result.getAttribute('data-name'), doc: result.getAttribute('data-doc')};
      $('.step1').removeAttribute('style');
    }
    if(platformHash) {
       let result = findItemIn(platformLinks, platformHash);
       if(result) currentPlatform = {name: result.getAttribute('data-name'), doc: result.getAttribute('data-doc')};
       $('.step2').removeAttribute('style');
    }
    nextStep();
  }

})();<|endoftext|>


<commit_before>// Description:
//   遊ぶ
// Commands:
//   quest attack {user} - attack
//   quest cure {user} - cure
//   quest raise|ザオリク {user} - ふっかつ
//

var DarkQuest   = require("node-quest");
var Game        = DarkQuest.Game;
var Equipment   = DarkQuest.Equipment;
var Parameter   = DarkQuest.Parameter;
var Weapon      = DarkQuest.Weapon;
var User        = DarkQuest.User;

var INITIAL_ATTACK_DAMANE   = 70;
var INITIAL_CURE_POINT      = 30;
var MAX_HP                  = 1000;

module.exports = function(robot) {
    var game = new Game(0, MAX_HP);
    var toGameUser = function(users) {
        return Object.keys(users).map(function(id) {
            var user    = users[id];
            var eq      = new Equipment(new Weapon(30, 12));
            var p       = new Parameter(20, 10);
            return new User(user.id, user.name, game.defaultStatus(), eq, p);
        });
    };
    var users = robot.adapter.client ? toGameUser(robot.adapter.client.users) : [];
    game.setUsers(users);

    robot.hear(/attack (.+)/i, function(res){
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else if (target.isDead()) {
            res.send( "[DEAD] こうかがない・・・" + target.name + "はただのしかばねのようだ・・・");
        } else {
            var before      = target.status.currentHp;
            var afterStatus = actor.attack(target, INITIAL_ATTACK_DAMANE);
            var after       = afterStatus.currentHp
            res.send( "[ATTACK] " + actor.name + "のこうげき！" + target.name + "に" + (before - after) + "のダメージ！ 残り:" + after + " / " + MAX_HP);
            if (target.isDead()) {
                res.send( "[DEAD] " + target.name + "はしんでしまった");
            }
        };
    });

    robot.hear(/cure (.+)/i, function(res){
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else if (target.isDead()) {
            res.send( "[DEAD] しかし こうかがなかった・・・");
        } else {
            actor.cure(target, INITIAL_CURE_POINT);
            res.send("[CURE] " + target.name + "のキズがかいふくした！残り: " + target.status.currentHp + " / " + MAX_HP);
        };
    });

    robot.hear(/ザオリク (.+)/i, function(res) {
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else {
            if(!target.isDead()) {
                res.send("しかし なにも おこらなかった！");
            } else {
                actor.fullCare(target);
                res.send("[CURE] " + target.name + "は いきかえった！");
            }
        };
    });

    robot.hear(/raise (.+)/i, function(res) {
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else {
            if(!target.isDead()) {
                res.send("しかし なにも おこらなかった！");
            } else {
                actor.fullCare(target);
                res.send("[CURE] " + target.name + "は いきかえった！");
            }
        };
    });

    var shakai  = new User(0, "社会", game.defaultStatus(), new Equipment(new Weapon(30, 12)), game.defaultStatus());
    var negativeWords = ["つらい", "かなしい", "悲しい", "悲しい", "つかれる", "疲れる", "ねむい", "眠い"];
    robot.hear(/.*/, function(res) {
        var tokens = res.message.tokenized;
        if(tokens === undefined) {
            return
        }
        var length = tokens.length;
        var negativeCount = 0;
        tokens.forEach(function(token, idx) {
            if(negativeWords.indexOf(token.basic_form) !== -1) {
                negativeCount++;
                if(idx + 1 < length && tokens[idx + 1].basic_form === 'ない') {
                    negativeCount--;
                }
            };

            if(token.basic_form === '帰れる' || token.basic_form === 'かえれる') {
                if(idx + 1 < length && tokens[idx + 1].basic_form === 'ない') {
                    negativeCount++;
                }
            }
        });

        var target = game.findUser(res.message.user.name);
        if(negativeCount > 0 && target) {
            var before      = target.status.currentHp;
            var afterStatus;
            for(var i=0;i<negativeCount;i++) {
                afterStatus = shakai.attack(target, INITIAL_ATTACK_DAMANE);
            }
            var after       = afterStatus.currentHp

            res.send( "[ATTACK] '社会'のこうげき！" + target.name + "に" + (after - before) + "のダメージ！ 残り:" + after + " / " + MAX_HP + " NegativeWord数: " + negativeCount);
        }
    });
}
<commit_msg>add 辛い<commit_after>// Description:
//   遊ぶ
// Commands:
//   quest attack {user} - attack
//   quest cure {user} - cure
//   quest raise|ザオリク {user} - ふっかつ
//

var DarkQuest   = require("node-quest");
var Game        = DarkQuest.Game;
var Equipment   = DarkQuest.Equipment;
var Parameter   = DarkQuest.Parameter;
var Weapon      = DarkQuest.Weapon;
var User        = DarkQuest.User;

var INITIAL_ATTACK_DAMANE   = 70;
var INITIAL_CURE_POINT      = 30;
var MAX_HP                  = 1000;

module.exports = function(robot) {
    var game = new Game(0, MAX_HP);
    var toGameUser = function(users) {
        return Object.keys(users).map(function(id) {
            var user    = users[id];
            var eq      = new Equipment(new Weapon(30, 12));
            var p       = new Parameter(20, 10);
            return new User(user.id, user.name, game.defaultStatus(), eq, p);
        });
    };
    var users = robot.adapter.client ? toGameUser(robot.adapter.client.users) : [];
    game.setUsers(users);

    robot.hear(/attack (.+)/i, function(res){
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else if (target.isDead()) {
            res.send( "[DEAD] こうかがない・・・" + target.name + "はただのしかばねのようだ・・・");
        } else {
            var before      = target.status.currentHp;
            var afterStatus = actor.attack(target, INITIAL_ATTACK_DAMANE);
            var after       = afterStatus.currentHp
            res.send( "[ATTACK] " + actor.name + "のこうげき！" + target.name + "に" + (before - after) + "のダメージ！ 残り:" + after + " / " + MAX_HP);
            if (target.isDead()) {
                res.send( "[DEAD] " + target.name + "はしんでしまった");
            }
        };
    });

    robot.hear(/cure (.+)/i, function(res){
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else if (target.isDead()) {
            res.send( "[DEAD] しかし こうかがなかった・・・");
        } else {
            actor.cure(target, INITIAL_CURE_POINT);
            res.send("[CURE] " + target.name + "のキズがかいふくした！残り: " + target.status.currentHp + " / " + MAX_HP);
        };
    });

    robot.hear(/ザオリク (.+)/i, function(res) {
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else {
            if(!target.isDead()) {
                res.send("しかし なにも おこらなかった！");
            } else {
                actor.fullCare(target);
                res.send("[CURE] " + target.name + "は いきかえった！");
            }
        };
    });

    robot.hear(/raise (.+)/i, function(res) {
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else {
            if(!target.isDead()) {
                res.send("しかし なにも おこらなかった！");
            } else {
                actor.fullCare(target);
                res.send("[CURE] " + target.name + "は いきかえった！");
            }
        };
    });

    var shakai  = new User(0, "社会", game.defaultStatus(), new Equipment(new Weapon(30, 12)), game.defaultStatus());
    var negativeWords = ["つらい", "辛い", "かなしい", "悲しい", "悲しい", "つかれる", "疲れる", "ねむい", "眠い"];
    robot.hear(/.*/, function(res) {
        var tokens = res.message.tokenized;
        if(tokens === undefined) {
            return
        }
        var length = tokens.length;
        var negativeCount = 0;
        tokens.forEach(function(token, idx) {
            if(negativeWords.indexOf(token.basic_form) !== -1) {
                negativeCount++;
                if(idx + 1 < length && tokens[idx + 1].basic_form === 'ない') {
                    negativeCount--;
                }
            };

            if(token.basic_form === '帰れる' || token.basic_form === 'かえれる') {
                if(idx + 1 < length && tokens[idx + 1].basic_form === 'ない') {
                    negativeCount++;
                }
            }
        });

        var target = game.findUser(res.message.user.name);
        if(negativeCount > 0 && target) {
            var before      = target.status.currentHp;
            var afterStatus;
            for(var i=0;i<negativeCount;i++) {
                afterStatus = shakai.attack(target, INITIAL_ATTACK_DAMANE);
            }
            var after       = afterStatus.currentHp

            res.send( "[ATTACK] '社会'のこうげき！" + target.name + "に" + (after - before) + "のダメージ！ 残り:" + after + " / " + MAX_HP + " NegativeWord数: " + negativeCount);
        }
    });
}
<|endoftext|>


<commit_before>// Description:
//   遊ぶ
// Commands:
//   quest attack {user} - attack
//   quest cure {user} - cure
//   quest raise|ザオリク {user} - ふっかつ
//

var DarkQuest   = require("node-quest");
var Game        = DarkQuest.Game;
var Equipment   = DarkQuest.Equipment;
var Parameter   = DarkQuest.Parameter;
var Weapon      = DarkQuest.Weapon;
var User        = DarkQuest.User;

var INITIAL_ATTACK_DAMANE   = 70;
var INITIAL_CURE_POINT      = 30;
var MAX_HP                  = 1000;

module.exports = function(robot) {
    var game = new Game(0, MAX_HP);
    var toGameUser = function(users) {
        return Object.keys(users).map(function(id) {
            var user    = users[id];
            var eq      = new Equipment(new Weapon(30, 12));
            var p       = new Parameter(20, 10);
            return new User(user.id, user.name, game.defaultStatus(), eq, p);
        });
    };
    var users = robot.adapter.client ? toGameUser(robot.adapter.client.users) : [];
    game.setUsers(users);

    robot.hear(/attack (.+)/i, function(res){
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else if (target.isDead()) {
            res.send( "[DEAD] こうかがない・・・" + target.name + "はただのしかばねのようだ・・・");
        } else {
            var before      = target.status.currentHp;
            var afterStatus = actor.attack(target, INITIAL_ATTACK_DAMANE);
            var after       = afterStatus.currentHp
            res.send( "[ATTACK] " + actor.name + "のこうげき！" + target.name + "に" + (before - after) + "のダメージ！ 残り:" + after + " / " + MAX_HP);
            if (target.isDead()) {
                res.send( "[DEAD] " + target.name + "はしんでしまった");
            }
        };
    });

    robot.hear(/cure (.+)/i, function(res){
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else if (target.isDead()) {
            res.send( "[DEAD] しかし こうかがなかった・・・");
        } else {
            actor.cure(target, INITIAL_CURE_POINT);
            res.send("[CURE] " + target.name + "のキズがかいふくした！残り: " + target.status.currentHp + " / " + MAX_HP);
        };
    });

    robot.hear(/ザオリク (.+)/i, function(res) {
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else {
            if(!target.isDead()) {
                res.send("しかし なにも おこらなかった！");
            } else {
                actor.fullCare(target);
                res.send("[CURE] " + target.name + "は いきかえった！");
            }
        };
    });

    robot.hear(/raise (.+)/i, function(res) {
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else {
            if(!target.isDead()) {
                res.send("しかし なにも おこらなかった！");
            } else {
                actor.fullCare(target);
                res.send("[CURE] " + target.name + "は いきかえった！");
            }
        };
    });

    var shakai  = new User(0, "社会", game.defaultStatus(), new Equipment(new Weapon(30, 12)), game.defaultStatus());
    var negativeWords = ["つらい", "辛い", "かなしい", "悲しい", "悲しい", "つかれる", "疲れる", "ねむい", "眠い"];
    robot.hear(/.*/, function(res) {
        var tokens = res.message.tokenized;
        if(tokens === undefined) {
            return
        }
        var length = tokens.length;
        var negativeCount = 0;
        tokens.forEach(function(token, idx) {
            if(negativeWords.indexOf(token.basic_form) !== -1) {
                negativeCount++;
                if(idx + 1 < length && tokens[idx + 1].basic_form === 'ない') {
                    negativeCount--;
                }
            };

            if(token.basic_form === '帰れる' || token.basic_form === 'かえれる') {
                if(idx + 1 < length && tokens[idx + 1].basic_form === 'ない') {
                    negativeCount++;
                }
            }
        });

        var target = game.findUser(res.message.user.name);
        if(negativeCount > 0 && target) {
            var before      = target.status.currentHp;
            var afterStatus;
            for(var i=0;i<negativeCount;i++) {
                afterStatus = shakai.attack(target, INITIAL_ATTACK_DAMANE);
            }
            var after       = afterStatus.currentHp

            res.send( "[ATTACK] '社会'のこうげき！" + target.name + "に" + (after - before) + "のダメージ！ 残り:" + after + " / " + MAX_HP + " NegativeWord数: " + negativeCount);
        }
    });
}
<commit_msg>Add status api<commit_after>// Description:
//   遊ぶ
// Commands:
//   quest attack {user} - attack
//   quest cure {user} - cure
//   quest raise|ザオリク {user} - ふっかつ
//

var DarkQuest   = require("node-quest");
var Game        = DarkQuest.Game;
var Equipment   = DarkQuest.Equipment;
var Parameter   = DarkQuest.Parameter;
var Weapon      = DarkQuest.Weapon;
var User        = DarkQuest.User;

var INITIAL_ATTACK_DAMANE   = 70;
var INITIAL_CURE_POINT      = 30;
var MAX_HP                  = 1000;

module.exports = function(robot) {
    var game = new Game(0, MAX_HP);
    var toGameUser = function(users) {
        return Object.keys(users).map(function(id) {
            var user    = users[id];
            var eq      = new Equipment(new Weapon(30, 12));
            var p       = new Parameter(20, 10);
            return new User(user.id, user.name, game.defaultStatus(), eq, p);
        });
    };
    var users = robot.adapter.client ? toGameUser(robot.adapter.client.users) : [];
    game.setUsers(users);

    robot.hear(/attack (.+)/i, function(res){
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else if (target.isDead()) {
            res.send( "[DEAD] こうかがない・・・" + target.name + "はただのしかばねのようだ・・・");
        } else {
            var before      = target.status.currentHp;
            var afterStatus = actor.attack(target, INITIAL_ATTACK_DAMANE);
            var after       = afterStatus.currentHp
            res.send( "[ATTACK] " + actor.name + "のこうげき！" + target.name + "に" + (before - after) + "のダメージ！ 残り:" + after + " / " + MAX_HP);
            if (target.isDead()) {
                res.send( "[DEAD] " + target.name + "はしんでしまった");
            }
        };
    });

    robot.hear(/cure (.+)/i, function(res){
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else if (target.isDead()) {
            res.send( "[DEAD] しかし こうかがなかった・・・");
        } else {
            actor.cure(target, INITIAL_CURE_POINT);
            res.send("[CURE] " + target.name + "のキズがかいふくした！残り: " + target.status.currentHp + " / " + MAX_HP);
        };
    });

    robot.hear(/ザオリク (.+)/i, function(res) {
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else {
            if(!target.isDead()) {
                res.send("しかし なにも おこらなかった！");
            } else {
                actor.fullCare(target);
                res.send("[CURE] " + target.name + "は いきかえった！");
            }
        };
    });

    robot.hear(/raise (.+)/i, function(res) {
        var actor = game.findUser(res.message.user.name);
        var target = game.findUser(res.match[1]);

        if(actor === null || target === null) {
            res.send("しかし だれもいなかった・・・");
        } else if (actor.isDead() ) {
            res.send( "[DEAD] おぉ" + actor.name + "！死んでしまうとはふがいない");
        } else {
            if(!target.isDead()) {
                res.send("しかし なにも おこらなかった！");
            } else {
                actor.fullCare(target);
                res.send("[CURE] " + target.name + "は いきかえった！");
            }
        };
    });

    robot.hear(/status (.+)/i, function(res) {
        var target = game.findUser(res.match[1]);
        if(target === null) {
            res.send("しかし だれもいなかった・・・");
        } else {
            res.send("現在のHP: " + target.status.currentHp + " / " + MAX_HP);
        };
    });

    var shakai  = new User(0, "社会", game.defaultStatus(), new Equipment(new Weapon(30, 12)), game.defaultStatus());
    var negativeWords = ["つらい", "辛い", "かなしい", "悲しい", "悲しい", "つかれる", "疲れる", "ねむい", "眠い"];
    robot.hear(/.*/, function(res) {
        var tokens = res.message.tokenized;
        if(tokens === undefined) {
            return
        }
        var length = tokens.length;
        var negativeCount = 0;
        tokens.forEach(function(token, idx) {
            if(negativeWords.indexOf(token.basic_form) !== -1) {
                negativeCount++;
                if(idx + 1 < length && tokens[idx + 1].basic_form === 'ない') {
                    negativeCount--;
                }
            };

            if(token.basic_form === '帰れる' || token.basic_form === 'かえれる') {
                if(idx + 1 < length && tokens[idx + 1].basic_form === 'ない') {
                    negativeCount++;
                }
            }
        });

        var target = game.findUser(res.message.user.name);
        if(negativeCount > 0 && target) {
            var before      = target.status.currentHp;
            var afterStatus;
            for(var i=0;i<negativeCount;i++) {
                afterStatus = shakai.attack(target, INITIAL_ATTACK_DAMANE);
            }
            var after       = afterStatus.currentHp

            res.send( "[ATTACK] '社会'のこうげき！" + target.name + "に" + (after - before) + "のダメージ！ 残り:" + after + " / " + MAX_HP + " NegativeWord数: " + negativeCount);
        }
    });
}
<|endoftext|>


<commit_before>import routes from "config/routes";
import appConfig from "config/app";
import authConfig from "config/auth";
import * as entities from "config/entities";
import Backend from "i18next-xhr-backend";
import {Router} from "aurelia-router";
import {AuthorizeStep} from "aurelia-authentication";
import {TWBootstrapViewStrategy} from "aurelia-validation/strategies/twbootstrap-view-strategy";
import "bootstrap";

export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()

    /* @see http://aurelia-api.spoonx.org/configuration.html */
    .plugin('aurelia-api', builder => {
      // Register endpoint for each endpoint in the config.
      appConfig.endpoints.forEach(endpoint => {
        builder.registerEndpoint(endpoint.name, endpoint.endpoint, endpoint.config);

        if (endpoint.default) {
          builder.setDefaultEndpoint(endpoint.name);
        }
      });
    })

    /* @see http://aurelia-authentication.spoonx.org/configuration.html */
    .plugin('aurelia-authentication', baseConfig => {
      baseConfig.configure(authConfig);
    })

    /* @see http://aurelia-orm.spoonx.org/configuration.html */
    .plugin('aurelia-orm', builder => {
      builder.registerEntities(entities);
    })

    /* @see https://github.com/SpoonX/aurelia-notification */
    .plugin('aurelia-notification', config => {
      config.configure({
        notifications: {
          'success': 'humane-jackedup-success',
          'error'  : 'humane-jackedup-error',
          'info'   : 'humane-jackedup-info'
        }
      });
    })

    /* @see https://github.com/aurelia/i18n */
    .plugin('aurelia-i18n', instance => {
      // adapt options to your needs (see http://i18next.com/pages/doc_init.html)

      instance.i18next.use(Backend);

      instance.setup({
        backend:     {
          loadPath: 'scripts/config/locale/{{lng}}/{{ns}}.json'
        },
        lng        : appConfig.defaultLocale.language,
        attributes : ['t'],
        fallbackLng: appConfig.defaultLocale.language,
        debug      : false
      });
    })

    /* @see https://github.com/spoonx/aurelia-datatable */
    .plugin('aurelia-datatable')

    /* @see https://github.com/spoonx/aurelia-pager */
    .plugin('aurelia-pager')

    /* @see https://github.com/spoonx/aurelia-form */
    .plugin('aurelia-form')

    /* global resources */
    .globalResources('component/value-converters/date-format');

  aurelia.use.developmentLogging();

  aurelia.start().then(a => {
    a.container.get(Router).configure(configureRouter);
    a.setRoot('app');
  });
}

function configureRouter(config) {
  config.title = appConfig.title;

  config.addPipelineStep('authorize', AuthorizeStep);

  config.map(routes);
}
<commit_msg>fix(project): import fetch polyfill<commit_after>import routes from "config/routes";
import appConfig from "config/app";
import authConfig from "config/auth";
import * as entities from "config/entities";
import Backend from "i18next-xhr-backend";
import {Router} from "aurelia-router";
import {AuthorizeStep} from "aurelia-authentication";
import {TWBootstrapViewStrategy} from "aurelia-validation/strategies/twbootstrap-view-strategy";
import "bootstrap";
import "fetch";

export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()

    /* @see http://aurelia-api.spoonx.org/configuration.html */
    .plugin('aurelia-api', builder => {
      // Register endpoint for each endpoint in the config.
      appConfig.endpoints.forEach(endpoint => {
        builder.registerEndpoint(endpoint.name, endpoint.endpoint, endpoint.config);

        if (endpoint.default) {
          builder.setDefaultEndpoint(endpoint.name);
        }
      });
    })

    /* @see http://aurelia-authentication.spoonx.org/configuration.html */
    .plugin('aurelia-authentication', baseConfig => {
      baseConfig.configure(authConfig);
    })

    /* @see http://aurelia-orm.spoonx.org/configuration.html */
    .plugin('aurelia-orm', builder => {
      builder.registerEntities(entities);
    })

    /* @see https://github.com/SpoonX/aurelia-notification */
    .plugin('aurelia-notification', config => {
      config.configure({
        notifications: {
          'success': 'humane-jackedup-success',
          'error'  : 'humane-jackedup-error',
          'info'   : 'humane-jackedup-info'
        }
      });
    })

    /* @see https://github.com/aurelia/i18n */
    .plugin('aurelia-i18n', instance => {
      // adapt options to your needs (see http://i18next.com/pages/doc_init.html)

      instance.i18next.use(Backend);

      instance.setup({
        backend:     {
          loadPath: 'scripts/config/locale/{{lng}}/{{ns}}.json'
        },
        lng        : appConfig.defaultLocale.language,
        attributes : ['t'],
        fallbackLng: appConfig.defaultLocale.language,
        debug      : false
      });
    })

    /* @see https://github.com/spoonx/aurelia-datatable */
    .plugin('aurelia-datatable')

    /* @see https://github.com/spoonx/aurelia-pager */
    .plugin('aurelia-pager')

    /* @see https://github.com/spoonx/aurelia-form */
    .plugin('aurelia-form')

    /* global resources */
    .globalResources('component/value-converters/date-format');

  aurelia.use.developmentLogging();

  aurelia.start().then(a => {
    a.container.get(Router).configure(configureRouter);
    a.setRoot('app');
  });
}

function configureRouter(config) {
  config.title = appConfig.title;

  config.addPipelineStep('authorize', AuthorizeStep);

  config.map(routes);
}
<|endoftext|>


<commit_before>/* eslint-disable no-unused-expressions, no-var, func-names */
/* globals c3 */
!(function() {
  var chart;
  var outlet1;
  var outlet2;
  var reset;

  function get( url ) {
    return fetch(url || '/numbers')
      .then(function( res ) {
        return res.json();
      });
  }

  function put( url ) {
    return fetch(url, { method: 'put' });
  }

  function plot() {
    get().then(function( res ) {
      chart.flow({
        columns: [
          ['x', new Date()],
          ['Outlet 1'].concat(res.outlet1),
          ['Outlet 2'].concat(res.outlet2),
        ],
        duration: 1000,
        length: 0,
        done: function() {
          setTimeout(function() {
            get().then(function( res2 ) {
              chart.flow({
                columns: [
                  ['x', new Date()],
                  ['Outlet 1'].concat(res2.outlet1),
                  ['Outlet 2'].concat(res2.outlet2),
                ],
                duration: 1000,
                length: 1,
              });
            });
          }, 1000);
        },
      });
    });
  }

  function addRemoveClass( el, add, remove ) {
    el.classList.add(add);
    el.classList.remove(remove);
  }

  function togglePower( el ) {
    if ( el.classList.contains('on') ) {
      return addRemoveClass(el, 'off', 'on');
    }

    addRemoveClass(el, 'on', 'off');
  }

  function getById( id ) {
    return document.getElementById(id);
  }

  function outlets() {
    get('/power')
      .then(function( res ) {
        addRemoveClass(outlet1, res.outlet1);
        addRemoveClass(outlet2, res.outlet2);
      });
  }

  outlet1 = getById('outlet1');
  outlet2 = getById('outlet2');
  reset   = getById('reset');

  outlet1.addEventListener('click', function() {
    put('/power/outlet1')
      .then(function() {
        togglePower(outlet1);
      });
  });

  outlet2.addEventListener('click', function() {
    put('/power/outlet2')
      .then(function() {
        togglePower(outlet2);
      });
  });

  reset.addEventListener('click', function() {
    put('/reset')
      .then(function() {
        chart.load({
          columns: [
            ['x', new Date()],
            ['Outlet 1', 0],
            ['Outlet 2', 0],
          ],
          duration: 1000,
          length: 0,
        });
      });
  });

  chart = c3.generate({
    axis: {
      x: {
        tick: {
          format: function( date ) {
            return date.toLocaleTimeString();
          },
        },
        type: 'timeseries',
      },
      y: {
        label: 'Milliamps',
      },
    },
    bindto: '#chart',
    data: {
      columns: [
        ['x', new Date()],
        ['Outlet 1', 0],
        ['Outlet 2', 0],
      ],
      type: 'spline',
      x: 'x',
    },
  });

  setInterval(plot, 5000);

  plot();
  outlets();
}());
<commit_msg>Query outlet power status regularly<commit_after>/* eslint-disable no-unused-expressions, no-var, func-names */
/* globals c3 */
!(function() {
  var chart;
  var outlet1;
  var outlet2;
  var reset;

  function get( url ) {
    return fetch(url || '/numbers')
      .then(function( res ) {
        return res.json();
      });
  }

  function put( url ) {
    return fetch(url, { method: 'put' });
  }

  function plot() {
    get().then(function( res ) {
      chart.flow({
        columns: [
          ['x', new Date()],
          ['Outlet 1'].concat(res.outlet1),
          ['Outlet 2'].concat(res.outlet2),
        ],
        duration: 1000,
        length: 0,
        done: function() {
          setTimeout(function() {
            get().then(function( res2 ) {
              chart.flow({
                columns: [
                  ['x', new Date()],
                  ['Outlet 1'].concat(res2.outlet1),
                  ['Outlet 2'].concat(res2.outlet2),
                ],
                duration: 1000,
                length: 1,
              });
            });
          }, 1000);
        },
      });
    });
  }

  function addRemoveClass( el, add, remove ) {
    el.classList.add(add);
    el.classList.remove(remove);
  }

  function togglePower( el ) {
    if ( el.classList.contains('on') ) {
      return addRemoveClass(el, 'off', 'on');
    }

    addRemoveClass(el, 'on', 'off');
  }

  function getById( id ) {
    return document.getElementById(id);
  }

  function outlets() {
    get('/power')
      .then(function( res ) {
        addRemoveClass(outlet1, res.outlet1);
        addRemoveClass(outlet2, res.outlet2);
      });
  }

  outlet1 = getById('outlet1');
  outlet2 = getById('outlet2');
  reset   = getById('reset');

  outlet1.addEventListener('click', function() {
    put('/power/outlet1')
      .then(function() {
        togglePower(outlet1);
      });
  });

  outlet2.addEventListener('click', function() {
    put('/power/outlet2')
      .then(function() {
        togglePower(outlet2);
      });
  });

  reset.addEventListener('click', function() {
    put('/reset')
      .then(function() {
        chart.load({
          columns: [
            ['x', new Date()],
            ['Outlet 1', 0],
            ['Outlet 2', 0],
          ],
          duration: 1000,
          length: 0,
        });
      });
  });

  chart = c3.generate({
    axis: {
      x: {
        tick: {
          format: function( date ) {
            return date.toLocaleTimeString();
          },
        },
        type: 'timeseries',
      },
      y: {
        label: 'Milliamps',
      },
    },
    bindto: '#chart',
    data: {
      columns: [
        ['x', new Date()],
        ['Outlet 1', 0],
        ['Outlet 2', 0],
      ],
      type: 'spline',
      x: 'x',
    },
  });

  setInterval(plot, 5000);
  setInterval(outlets, 5000);

  plot();
  outlets();
}());
<|endoftext|>


<commit_before>core.controller('AbstractController', function ($scope, StorageService) {

	$scope.isAssumed = function() {
		return StorageService.get("assumed");
	};

	$scope.isAssuming = function() {
		return StorageService.get("assuming");
	};

	$scope.isAnonymous = function() {
		return (sessionStorage.role == "ROLE_ANONYMOUS");
	};

	$scope.isUser = function() {
		return (sessionStorage.role == "ROLE_USER");
	};

	$scope.isAnnotator = function() {
		return (sessionStorage.role == "ROLE_ANNOTATOR");
	};

	$scope.isManager = function() {
		return (sessionStorage.role == "ROLE_MANAGER");
	};

	$scope.isAdmin = function() {
		return (sessionStorage.role == "ROLE_ADMIN");
	};

});
<commit_msg>Put storage service on scope for abstract controller.<commit_after>core.controller('AbstractController', function ($scope, StorageService) {

	$scope.storage = StorageService;

	$scope.isAssumed = function() {
		return StorageService.get("assumed");
	};

	$scope.isAssuming = function() {
		return StorageService.get("assuming");
	};

	$scope.isAnonymous = function() {
		return (sessionStorage.role == "ROLE_ANONYMOUS");
	};

	$scope.isUser = function() {
		return (sessionStorage.role == "ROLE_USER");
	};

	$scope.isAnnotator = function() {
		return (sessionStorage.role == "ROLE_ANNOTATOR");
	};

	$scope.isManager = function() {
		return (sessionStorage.role == "ROLE_MANAGER");
	};

	$scope.isAdmin = function() {
		return (sessionStorage.role == "ROLE_ADMIN");
	};

});
<|endoftext|>


<commit_before>function NetworkInformation(){
  this.googleInformation = null;
  this.ipApiInformation = null;
  this.currentOs = "Unknown";
  this.networkType = "Unknown";
  this.coordinates = [0, 0];

  this.getGoogleInfo = function(lat, lon){
    try{
      var geocoder;
      geocoder = new google.maps.Geocoder();
      var latlng = new google.maps.LatLng(lat, lon);
      var selfNetwork = this;
      geocoder.geocode(
        {'latLng': latlng},
        function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
              var add= results[0].formatted_address ;
              var  value=add.split(",");
              selfNetwork.googleInformation = value;
            }
          }
        }
      );
    }
    catch(err){
      ;
    }
  }

  this.setInformation = function(readyMethod){
    var selfNetwork = this;

    getHtml5Geolocation = function(tail_method, callbackfunction){
      var success = function(data){
        selfNetwork.coordinates = [data.coords.latitude, data.coords.longitude];
        if(selfNetwork.coordinates[0] != 0 && selfNetwork.coordinates[1] != 0){
          selfNetwork.getGoogleInfo(data.coords.latitude, data.coords.longitude);
        }
        tail_method(callbackfunction);
      }
      var failure = function(data){
        tail_method(callbackfunction);
      }
      var geo_options = {
        enableHighAccuracy: true,
        maximumAge        : 10000,
        timeout           : 17000
      };
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, failure, geo_options);
      }
      else{
        tail_method(callbackfunction);
      }
    }

    getIpApiInformation = function(callbackfunction){
      var setData = function(data){
        selfNetwork.ipApiInformation = data;
        callbackfunction();
      }
      $.getJSON("http://ip-api.com/json/?callback=?&lang=es&fields=262111", setData);
    }

    getHtml5Geolocation(getIpApiInformation, readyMethod);

    setTimeout(function () {
      if(selfNetwork.googleInformation == null && selfNetwork.ipApiInformation == null){
        window.console.log("No hubo confirmación o se declinó.");
        getIpApiInformation(readyMethod);
      }else{
        window.console.log("Localización exitosa.");
      }
    }, 18000);
  }

  this.getAS = function(){
    return this.ipApiInformation.as;
  }

  this.getCity = function(){
    if(this.googleInformation){
      return this.googleInformation[1];
    }
    else{
      return this.ipApiInformation.city;
    }
  }

  this.getCountry = function(){
    if(this.googleInformation){
      return this.googleInformation[4];
    }
    else{
      return this.ipApiInformation.country;
    }
  }

  this.getCountryCode = function(){
    return this.ipApiInformation.countryCode;
  }

  this.getIsp = function(){
    return this.ipApiInformation.isp;
  }

  this.getCoordinates = function(){
    if(this.coordinates[0] === 0 && this.coordinates[1] === 0){
      this.coordinates = [this.ipApiInformation.lat, this.ipApiInformation.lon];
    }
    return this.coordinates;
  }

  this.getOrganization = function(){
    return this.ipApiInformation.org;
  }

  this.useProxy = function(){
    if(this.googleInformation == null){
      return false;
    }
    var countryIpAPi = this.ipApiInformation.country;
    countryIpAPi = (countryIpAPi.toLowerCase()).trim();
    var countryGoogle = this.googleInformation[4];
    countryGoogle = (countryGoogle.toLowerCase()).trim();
    if(countryIpAPi === countryGoogle){
      return false;
    }
    else {
      return true;
    }
  }

  this.getIp = function(){
    return this.ipApiInformation.query;
  }

  this.getRegion = function(){
    if(this.googleInformation){
      return this.googleInformation[3];
    }
    else{
      return this.ipApiInformation.region;
    }
  }

  this.getRegionName = function(){
    if(this.googleInformation){
      return this.googleInformation[3];
    }
    else{
      return this.ipApiInformation.regionName;
    }
  }

  this.getReverseDNS = function(){
    return this.ipApiInformation.reverse;
  }

  this.isSuccessful = function(){
    if(this.ipApiInformation.status == "success"){
      return true;
    }
    else{
      return false;
    }
  }

  this.getTimezone = function(){
    return this.ipApiInformation.timezone;
  }

  this.isAndroid = function(){
    return /Android/i.test(navigator.userAgent);
  }

  this.isMobile = function(){
    var device = navigator.userAgent;
    return /Android|BlackBerry|iPhone|iPad|iPod|IEMobile/i.test(device);
  }

  this.checkConnectionType = function(){
    var connection =  navigator.connection || navigator.mozConnection || navigator.webkitConnection;
    if(connection == undefined){
      return "Unknown";
    }
    else{
      return connection.type;
    }
  }

  this.getOS = function(){
    var os = "Unknown";
    var device = navigator.userAgent;
    if(/Windows/i.test(device)){
      os = "Windows";
    }
    else if (/Linux/i.test(device)) {
      os = "Linux";
    }
    else if(/Mac/i.test(device)){
      os = "Mac";
    }
    else if (this.isMobile()) {
      os = "Mobile";
    }
    else{;}
    return os;
  }

  this.currentOs = this.getOS();
  this.networkType = this.checkConnectionType();

}
<commit_msg>Added JSDoc<commit_after>/**
* @author Michel Llorens http://michotastico.github.io
* @version 1.0.0
*/

/**
 * NetworkInformation - Class who get the information of the client network
 * @class NetworkInformation
 * @classdesc Class who get the information of the client network
 *
 */
function NetworkInformation(){
  this.googleInformation = null;
  this.ipApiInformation = null;
  this.currentOs = "Unknown";
  this.networkType = "Unknown";
  this.coordinates = [0, 0];

  /**
   * getGoogleInfo - receive the data from google and set in the internal vars
   *
   * @param  {number} lat latitude
   * @param  {number} lon longitude
   * @return {undefined}
   */
  this.getGoogleInfo = function(lat, lon){
    try{
      var geocoder;
      geocoder = new google.maps.Geocoder();
      var latlng = new google.maps.LatLng(lat, lon);
      var selfNetwork = this;
      geocoder.geocode(
        {'latLng': latlng},
        function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
              var add= results[0].formatted_address ;
              var  value=add.split(",");
              selfNetwork.googleInformation = value;
            }
          }
        }
      );
    }
    catch(err){
      ;
    }
  }

  /**
   * setInformation - Set all the information to the class. Requesting to the navigator, google and ip-api
   *
   * @param  {function} readyMethod function called when the information was setted
   * @return {undefined}
   */
  this.setInformation = function(readyMethod){
    var selfNetwork = this;

    /**
     * getHtml5Geolocation - get the geolocalitation from the navigator
     *
     * @param  {function} tail_method      next function to be called.
     * @param  {function} callbackfunction callback function
     * @return {undefined}
     */
    getHtml5Geolocation = function(tail_method, callbackfunction){
      var success = function(data){
        selfNetwork.coordinates = [data.coords.latitude, data.coords.longitude];
        if(selfNetwork.coordinates[0] != 0 && selfNetwork.coordinates[1] != 0){
          selfNetwork.getGoogleInfo(data.coords.latitude, data.coords.longitude);
        }
        tail_method(callbackfunction);
      }
      var failure = function(data){
        tail_method(callbackfunction);
      }
      var geo_options = {
        enableHighAccuracy: true,
        maximumAge        : 10000,
        timeout           : 17000
      };
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, failure, geo_options);
      }
      else{
        tail_method(callbackfunction);
      }
    }

    /**
     * getIpApiInformation - get the network information from ip-api
     *
     * @param  {function} callbackfunction callback function
     * @return {undefined}
     */
    getIpApiInformation = function(callbackfunction){
      var setData = function(data){
        selfNetwork.ipApiInformation = data;
        callbackfunction();
      }
      $.getJSON("http://ip-api.com/json/?callback=?&lang=es&fields=262111", setData);
    }

    getHtml5Geolocation(getIpApiInformation, readyMethod);

    /**
     * anonymous function - Timeout to call getIpApiInformation function because a bug in navigator.geolocation.getCurrentPosition method
     *
     * @return {undefined}
     */
    setTimeout(function () {
      if(selfNetwork.googleInformation == null && selfNetwork.ipApiInformation == null){
        window.console.log("No hubo confirmación o se declinó.");
        getIpApiInformation(readyMethod);
      }else{
        window.console.log("Localización exitosa.");
      }
    }, 18000);
  }

  /**
   * getAS - Get Autonomous system
   *
   * @return {string}  Autonomous system
   */
  this.getAS = function(){
    return this.ipApiInformation.as;
  }

  /**
   * getCity - Get city
   *
   * @return {string}  city
   */
  this.getCity = function(){
    if(this.googleInformation){
      return this.googleInformation[1];
    }
    else{
      return this.ipApiInformation.city;
    }
  }

  /**
   * getCountry - Get country
   *
   * @return {string} country
   */
  this.getCountry = function(){
    if(this.googleInformation){
      return this.googleInformation[4];
    }
    else{
      return this.ipApiInformation.country;
    }
  }

  /**
   * getCountryCode - Get country code
   *
   * @return {string} country code
   */
  this.getCountryCode = function(){
    return this.ipApiInformation.countryCode;
  }

  /**
   * getIsp - Get the ISP
   *
   * @return {string} ISP
   */
  this.getIsp = function(){
    return this.ipApiInformation.isp;
  }

  /**
   * getCoordinates - Get Latlong of client.
   *
   * @return {Array}  [Latitude, Longitude]
   */
  this.getCoordinates = function(){
    if(this.coordinates[0] === 0 && this.coordinates[1] === 0){
      this.coordinates = [this.ipApiInformation.lat, this.ipApiInformation.lon];
    }
    return this.coordinates;
  }

  /**
   * getOrganization - Get organization (or ISP if didn't exists)
   *
   * @return {string}  organization
   */
  this.getOrganization = function(){
    return this.ipApiInformation.org;
  }

  /**
   * useProxy - Check if the user use a proxy
   *
   * @return {boolean} True if the user use a proxy
   */
  this.useProxy = function(){
    if(this.googleInformation == null){
      return false;
    }
    var countryIpAPi = this.ipApiInformation.country;
    countryIpAPi = (countryIpAPi.toLowerCase()).trim();
    var countryGoogle = this.googleInformation[4];
    countryGoogle = (countryGoogle.toLowerCase()).trim();
    if(countryIpAPi === countryGoogle){
      return false;
    }
    else {
      return true;
    }
  }

  /**
   * getIp - Get IP
   *
   * @return {string}  IP
   */
  this.getIp = function(){
    return this.ipApiInformation.query;
  }

  /**
   * getRegion - Get region
   *
   * @return {string}  Region
   */
  this.getRegion = function(){
    if(this.googleInformation){
      return this.googleInformation[3];
    }
    else{
      return this.ipApiInformation.region;
    }
  }

  /**
   * getRegionName - Get region's name
   *
   * @return {string}  Region's name
   */
  this.getRegionName = function(){
    if(this.googleInformation){
      return this.googleInformation[3];
    }
    else{
      return this.ipApiInformation.regionName;
    }
  }

  /**
   * getReverseDNS - Get the reverse of the DNS
   *
   * @return {string}  Reverse of the DNS
   */
  this.getReverseDNS = function(){
    return this.ipApiInformation.reverse;
  }

  /**
   * isSuccessful - Check if the connection was successful
   *
   * @return {boolean}  True if the connection was successful
   */
  this.isSuccessful = function(){
    if(this.ipApiInformation.status == "success"){
      return true;
    }
    else{
      return false;
    }
  }

  /**
   * getTimezone - Get timezone
   *
   * @return {string} Timezone
   */
  this.getTimezone = function(){
    return this.ipApiInformation.timezone;
  }

  /**
   * isAndroid - Check if the device is Android
   *
   * @return {boolean} True if the device is Android
   */
  this.isAndroid = function(){
    return /Android/i.test(navigator.userAgent);
  }

    /**
     * isMobile - Check if the device is mobile
     *
     * @return {boolean} True if the device is mobile
     */
  this.isMobile = function(){
    var device = navigator.userAgent;
    return /Android|BlackBerry|iPhone|iPad|iPod|IEMobile/i.test(device);
  }

    /**
     * checkConnectionType - If its avalaible, check the connection type. (Only work on Android)
     *
     * @return {string}  Connection Type
     */
  this.checkConnectionType = function(){
    var connection =  navigator.connection || navigator.mozConnection || navigator.webkitConnection;
    if(connection == undefined){
      return "Unknown";
    }
    else{
      return connection.type;
    }
  }

    /**
     * getOS - Get the OS of the client
     *
     * @return {string}  Operative System
     */
  this.getOS = function(){
    var os = "Unknown";
    var device = navigator.userAgent;
    if(/Windows/i.test(device)){
      os = "Windows";
    }
    else if (/Linux/i.test(device)) {
      os = "Linux";
    }
    else if(/Mac/i.test(device)){
      os = "Mac";
    }
    else if (this.isMobile()) {
      os = "Mobile";
    }
    else{;}
    return os;
  }

  this.currentOs = this.getOS();
  this.networkType = this.checkConnectionType();

}
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

// Workaround for an issue where RxJS cannot be used with UMD bundles only. This is because
// rxjs only ships one UMD bundle and expects everyone to only use the named "rxjs" AMD module.
// Since our code internally loads operators from "rxjs/operators/index", we need to make sure
// that we re-export all operators from the UMD module. This is a small trade-off for not loading
// all rxjs files individually.

if (typeof define === 'function' && define.amd) {
  define(['exports', 'rxjs'], (exports, rxjs) => {
    // Re-export all operators in this AMD module.
    Object.assign(exports, rxjs.operators);
  });
}
<commit_msg>build: fix dev app not working in IE11 (#16932)<commit_after>/**
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

// Workaround for an issue where RxJS cannot be used with UMD bundles only. This is because
// rxjs only ships one UMD bundle and expects everyone to only use the named "rxjs" AMD module.
// Since our code internally loads operators from "rxjs/operators/index", we need to make sure
// that we re-export all operators from the UMD module. This is a small trade-off for not loading
// all rxjs files individually.

if (typeof define === 'function' && define.amd) {
  // Note that this needs to be in ES5, because we load it
  // directly into the browser without transpiling.
  define(['exports', 'rxjs'], function(exports, rxjs) {
    // Re-export all operators in this AMD module.
    Object.assign(exports, rxjs.operators);
  });
}
<|endoftext|>