<commit_before>#!/usr/bin/env node

var blake = require('../lib/blake.js')
  , resolve = require('path').resolve

;(function () {
  var arg = process.argv.splice(2)
    , isValid = !(arg && arg.length >= 2)

  if (isValid) {
    return console.error('Usage: blake source_directory target_directory [source_file ...]');
  }

  var source = arg.shift()
    , target = arg.shift()
    , config = require(resolve(source, 'views', 'config.js'))
    , files = arg

  blake(source, target, config, files, function (err) {
    if (err) return console.error(err)
    console.log('OK')
  })
})()
<commit_msg>Update CLI<commit_after>#!/usr/bin/env node

var blake = require('../lib/blake.js')

;(function () {
  var arg = process.argv.splice(2)
    , isValid = !(arg && arg.length >= 2)

  if (isValid) {
    return console.error('Usage: blake source_directory target_directory [source_file ...]');
  }

  var source = arg.shift()
    , target = arg.shift()
    , files = arg

  blake(source, target, files, function (err) {
    if (err) return console.error(err)
    console.log('OK')
  })
})()
<|endoftext|>


<commit_before>const path = require('path');
const express = require('express');
const subdomain = require('express-subdomain');
const engines = require('consolidate');
const favicon = require('serve-favicon');
const db = require('./persistence/db');

const app = express();

app.use(favicon(path.join(__dirname, 'public/favicon.ico')));
app.use(require('cookie-parser')());

// configure views
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.engine('hbs', engines.handlebars);

app.set('x-powered-by', false);
app.set('json spaces', 2);

// local dev only
if (!process.env.PORT) {
  var config = require('./webpack.config.dev');
  var compiler = require('webpack')(config);

  app.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath
  }));

  app.use(require('webpack-hot-middleware')(compiler));
}

app.use('/public', express.static('public'));

const apiRouter = require('./routes/api');
app.use(subdomain('api', apiRouter));
app.use('/api', apiRouter);

const viewRouter = require('./routes/view');
app.use(subdomain('view', viewRouter));
app.use('/view', viewRouter);
app.use('/', viewRouter);

const editRouter = require('./routes/edit');
app.use(subdomain('edit', editRouter));
app.use('/edit', editRouter);

// the React app is the fallback for all routes
app.use(function (req, res) {
  res.sendFile(path.join(__dirname, 'routes', 'edit', 'index.html'));
});

module.exports = function (local, port) {
  port = port || process.env.PORT || 3000;

  db.open()
    .then(function () {
      app.listen(port, function () {
        console.log('Server listening at http://literasee.local:' + port);
      });
    });
};
<commit_msg>Provide better URL<commit_after>const path = require('path');
const express = require('express');
const subdomain = require('express-subdomain');
const engines = require('consolidate');
const favicon = require('serve-favicon');
const db = require('./persistence/db');

const app = express();

app.use(favicon(path.join(__dirname, 'public/favicon.ico')));
app.use(require('cookie-parser')());

// configure views
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.engine('hbs', engines.handlebars);

app.set('x-powered-by', false);
app.set('json spaces', 2);

// local dev only
if (!process.env.PORT) {
  var config = require('./webpack.config.dev');
  var compiler = require('webpack')(config);

  app.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath
  }));

  app.use(require('webpack-hot-middleware')(compiler));
}

app.use('/public', express.static('public'));

const apiRouter = require('./routes/api');
app.use(subdomain('api', apiRouter));
app.use('/api', apiRouter);

const viewRouter = require('./routes/view');
app.use(subdomain('view', viewRouter));
app.use('/view', viewRouter);
app.use('/', viewRouter);

const editRouter = require('./routes/edit');
app.use(subdomain('edit', editRouter));
app.use('/edit', editRouter);

// the React app is the fallback for all routes
app.use(function (req, res) {
  res.sendFile(path.join(__dirname, 'routes', 'edit', 'index.html'));
});

module.exports = function (local, port) {
  port = port || process.env.PORT || 3000;

  db.open()
    .then(function () {
      app.listen(port, function () {
        console.log('Server listening at http://edit.literasee.local:' + port);
      });
    });
};
<|endoftext|>


<commit_before>// var bodyParser = require('body-parser');
var request = require('request');

// all routs are in this file
module.exports = function(app) {
	var auth_url= 'http://auth.hasura/user/account/info';
	var headers = {
                 'Content-Type' : 'application/json',
                 'X-Hasura-Role' : 'admin',
       		 	 'X-Hasura-User-Id' : 1
            };

	app.get('/test', function (req, res) {
		var user_auth_token = req.headers['x-hasura-session-id'];
		res.send(user_auth_token);

		/*// Verify user token
		var options = {
			url : auth_url,
			method : 'POST',
			headers : headers
			body : JSON.stringify({
				type : 'select',
				args : {
					table : 'test',
					columns : ['*']
				}
			})
		}

		request(options, function(err, response, body){
			if(err) {
			  console.error("Could not connect to APIs : " + err);
			  res.status(500).send('Internal error : ' + err);
			  return;
			}

			if (response.statusCode !== 200) {
			  console.error('Auth API bad request');
			  res.status(500).send('Internal error : Could not connect to auth APIs');
			  return;
			}

			if (response.statusCode === 200) {
				let user = JSON.parse(body)

			}
		});*/

	});

	app.get('/', function (req, res) {
		res.render('base');
	});

	app.get('/app', function (req, res) {
		res.render('whiteboard');
	});

	app.get('/groups', function (req, res) {
		res.render('groups');
	});

	app.get('/profile', function(req,res) {
		res.render('profile');
	});

	app.get('/welcome-msg', function (req, res) {
		res.render('partials/welcome-msg');
	});
	app.get('/login-content', function (req, res) {
		res.render('partials/login-content');
	});
	app.get('/signup-content', function (req, res) {
		res.render('partials/signup-content');
	});
	app.get('/reset-pass-content', function (req, res) {
		res.render('partials/reset-pass-content');
	});

};
<commit_msg>Testing req headers 2<commit_after>// var bodyParser = require('body-parser');
var request = require('request');

// all routs are in this file
module.exports = function(app) {
	var auth_url= 'http://auth.hasura/user/account/info';
	var headers = {
                 'Content-Type' : 'application/json',
                 'X-Hasura-Role' : 'admin',
       		 	 'X-Hasura-User-Id' : 1
            };

	app.get('/test', function (req, res) {
		var user_id = req.headers['x-hasura-user-id'];
		var user_auth_token = req.headers['x-hasura-session-id'];
		res.send("User ID : " + user_id + " Auth token : " +  user_auth_token);

		/*// Verify user token
		var options = {
			url : auth_url,
			method : 'POST',
			headers : headers
			body : JSON.stringify({
				type : 'select',
				args : {
					table : 'test',
					columns : ['*']
				}
			})
		}

		request(options, function(err, response, body){
			if(err) {
			  console.error("Could not connect to APIs : " + err);
			  res.status(500).send('Internal error : ' + err);
			  return;
			}

			if (response.statusCode !== 200) {
			  console.error('Auth API bad request');
			  res.status(500).send('Internal error : Could not connect to auth APIs');
			  return;
			}

			if (response.statusCode === 200) {
				let user = JSON.parse(body)

			}
		});*/

	});

	app.get('/', function (req, res) {
		res.render('base');
	});

	app.get('/app', function (req, res) {
		res.render('whiteboard');
	});

	app.get('/groups', function (req, res) {
		res.render('groups');
	});

	app.get('/profile', function(req,res) {
		res.render('profile');
	});

	app.get('/welcome-msg', function (req, res) {
		res.render('partials/welcome-msg');
	});
	app.get('/login-content', function (req, res) {
		res.render('partials/login-content');
	});
	app.get('/signup-content', function (req, res) {
		res.render('partials/signup-content');
	});
	app.get('/reset-pass-content', function (req, res) {
		res.render('partials/reset-pass-content');
	});

};
<|endoftext|>


<commit_before>var name="Unused variables",
	description="Look for variables that were defined but not referenced";

// This plugin does **NOT** check for variables that are used incorrectly.
// TODO: FaultRules

// basic regex for finding variables
// TODO: handle objects -- right now just verify the highest level variable.
var varFinder = /{([^}\.]+?)(\.[^}]+?)??}/g;

// preload the symbol table with framework globals
var globalSymtab = [
	"proxy",
	"request",
	"response"
];

// errors that will be reported at the end of the process
var errors = [];

// warnings that will be reported at the end of the process
var warnings = [];

// Process proxyendpoints in the following order:
// 1. preflow - request [steps]
// 2. flow - request [steps]
// 3. postflow - request [steps]
// 4. routerules
//    - targetendpoint
//       . pre/flow/post
//       . pre - response
//       . flow - response
//       . post - response
// TODO: inspect things referenced by steps to populate symbol table and check for bad var references.
var onBundle = function (bundle) {
	bundle.getProxyEndpoints().forEach(function(endpoint){
		var localSymtab = [];
		evaluateSteps(endpoint.getPreFlow().getFlowRequest().getSteps(), localSymtab);
		endpoint.getFlows().forEach(function(flow) {
			evaluateSteps(flow.getFlowRequest().getSteps(), localSymtab);
		});
		evaluateSteps(endpoint.getPostFlow().getFlowRequest().getSteps(), localSymtab);

		var intermediateSymtab = localSymtab.slice(0); // don't update orig array references!
		// iterate through routerules now ...
		bundle.getTargetEndpoints().forEach(function(target){
			localSymtab = intermediateSymtab.slice(0); // reset the local symbol table

			// evaluate the target's inbound request flow(s)
			evaluateSteps(target.getPreFlow().getFlowRequest().getSteps(), localSymtab)
			target.getFlows().forEach(function(flow){
				evaluateSteps(flow.getFlowRequest().getSteps(), localSymtab);
			});
			evaluateSteps(target.getPostFlow().getFlowRequest().getSteps(), localSymtab);

			// assume the target was called, evalute the response flow(s)
			evaluateSteps(target.getPreFlow().getFlowResponse().getSteps(), localSymtab)
			target.getFlows().forEach(function(flow){
				evaluateSteps(flow.getFlowResponse().getSteps(), localSymtab);
			});
			evaluateSteps(target.getPostFlow().getFlowResponse().getSteps(), localSymtab);

			// finally, evalute the response flow(s) for the endpoint with this set of
			// 	local symbols...
			evaluateSteps(endpoint.getPreFlow().getFlowResponse().getSteps(), localSymtab)
			endpoint.getFlows().forEach(function(flow){
				evaluateSteps(flow.getFlowResponse().getSteps(), localSymtab);
			});
			evaluateSteps(endpoint.getPostFlow().getFlowResponse().getSteps(), localSymtab);
		});
	});
}

// TODO: evalute where symbols are added, and record them in our symbol table.
var evaluateSteps = function(steps, localSymtab) {
	steps.forEach( function(step) {
		if( step.getName()) {
			var badVars = getUndefinedVariables(step.getName(), localSymtab);
			badVars.forEach(function(badvar){
				step.err("Variable {" + badvar + "} was used in step name, but not previously defined");
			});
		} else {
			step.warn("Step does not seem to call anything (empty <Name> node)");
		}
		if( step.getCondition()) {
			var badVars = getUndefinedVariables(step.getCondition().getExpression());
			badVars.forEach(function(badvar){
				step.err("Variable {" + badvar + "} was used in step condition, but not previously defined");
			});
		}
	});
}

// return a list of variables referenced in this string
// that are undefined (may be empty)
var getUndefinedVariables = function (value, localSymtab) {
	var symtab = globalSymtab.concat(localSymtab);
	var undefinedVars = [];
	while((match = varFinder.exec(value)) != null) {
		var variable = match[1];
		if( ! (variable in symtab)) {
			undefinedVars.push(variable)
		}
	}
	return undefinedVars;
}

module.exports = {
	name,
	description,
	onBundle
};<commit_msg>now reports on variables defined but not used<commit_after>var name="Unused variables",
	description="Look for variables that were defined but not referenced";

// This plugin does **NOT** check for variables that are used incorrectly.
// TODO: FaultRules

// basic regex for finding variables
// TODO: handle objects -- right now just verify the highest level variable.
var varFinder = /{([^}\.]+?)(\.[^}]+?)??}/g;

// preload the symbol table with framework globals
var globalSymtab = [
	"proxy",
	"request",
	"response"
];

var usageMetrics = {};

// errors that will be reported at the end of the process
var errors = [];

// warnings that will be reported at the end of the process
var warnings = [];

// Process proxyendpoints in the following order:
// 1. preflow - request [steps]
// 2. flow - request [steps]
// 3. postflow - request [steps]
// 4. routerules
//    - targetendpoint
//       . pre/flow/post
//       . pre - response
//       . flow - response
//       . post - response
// TODO: inspect things referenced by steps to populate symbol table and check for bad var references.
var onBundle = function (bundle) {
	bundle.getProxyEndpoints().forEach(function(endpoint){
		var localSymtab = [];
		evaluateSteps(endpoint.getPreFlow().getFlowRequest().getSteps(), localSymtab);
		endpoint.getFlows().forEach(function(flow) {
			evaluateSteps(flow.getFlowRequest().getSteps(), localSymtab);
		});
		evaluateSteps(endpoint.getPostFlow().getFlowRequest().getSteps(), localSymtab);

		var intermediateSymtab = localSymtab.slice(0); // don't update orig array references!
		var intermediateUsage = JSON.parse(JSON.stringify(usageMetrics)); // save usage metrics
		// iterate through routerules now ...
		bundle.getTargetEndpoints().forEach(function(target){
			localSymtab = intermediateSymtab.slice(0); // reset the local symbol table
			usageMetrics = JSON.parse(JSON.stringify(intermediateUsage)); // reset usage for this iteration

			// evaluate the target's inbound request flow(s)
			evaluateSteps(target.getPreFlow().getFlowRequest().getSteps(), localSymtab)
			target.getFlows().forEach(function(flow){
				evaluateSteps(flow.getFlowRequest().getSteps(), localSymtab);
			});
			evaluateSteps(target.getPostFlow().getFlowRequest().getSteps(), localSymtab);

			// assume the target was called, evalute the response flow(s)
			evaluateSteps(target.getPreFlow().getFlowResponse().getSteps(), localSymtab)
			target.getFlows().forEach(function(flow){
				evaluateSteps(flow.getFlowResponse().getSteps(), localSymtab);
			});
			evaluateSteps(target.getPostFlow().getFlowResponse().getSteps(), localSymtab);

			// finally, evalute the response flow(s) for the endpoint with this set of
			// 	local symbols...
			evaluateSteps(endpoint.getPreFlow().getFlowResponse().getSteps(), localSymtab)
			endpoint.getFlows().forEach(function(flow){
				evaluateSteps(flow.getFlowResponse().getSteps(), localSymtab);
			});
			evaluateSteps(endpoint.getPostFlow().getFlowResponse().getSteps(), localSymtab);

			// TODO: report on variables defined but not used in this target flow
			localSymtab.forEach(function(symbol){
				if( !usageMetrics[symbol]) {
					target.warn("Target flow defines but does not use symbol " + symbol);
				}
			});
		});
	});
}

// TODO: evalute where symbols are added, and record them in our symbol table.
var evaluateSteps = function(steps, localSymtab) {
	steps.forEach( function(step) {
		if( step.getName()) {
			var badVars = analyzeVariables(step.getName(), localSymtab);
			badVars.forEach(function(badvar){
				step.err("Variable {" + badvar + "} was used in step name, but not previously defined");
			});
		} else {
			step.warn("Step does not seem to call anything (empty <Name> node)");
		}
		if( step.getCondition()) {
			var badVars = analyzeVariables(step.getCondition().getExpression());
			badVars.forEach(function(badvar){
				step.err("Variable {" + badvar + "} was used in step condition, but not previously defined");
			});
		}
	});
}

// return a list of variables referenced in this string
// that are undefined (may be empty)
var analyzeVariables = function (value, localSymtab) {
	var symtab = globalSymtab.concat(localSymtab);
	var undefinedVars = [];
	while((match = varFinder.exec(value)) != null) {
		var variable = match[1];
		usageMetrics[variable] = (usageMetrics[variable]||0) + 1;
		if( ! (variable in symtab)) {
			undefinedVars.push(variable)
		}
	}
	return undefinedVars;
}

module.exports = {
	name,
	description,
	onBundle
};<|endoftext|>


<commit_before>let dom = [
  '[0,0]',
  '[0,1]',
  '[0,2]',
  '[0,3]',
  '[0,4]',
  '[0,5]',
  '[0,6]',
  '[1,1]',
  '[1,2]',
  '[1,3]',
  '[1,4]',
  '[1,5]',
  '[1,6]',
  '[2,2]',
  '[2,3]',
  '[2,4]',
  '[2,5]',
  '[2,6]',
  '[3,3]',
  '[3,4]',
  '[3,5]',
  '[3,6]',
  '[4,4]',
  '[4,5]',
  '[4,6]',
  '[5,5]',
  '[5,6]',
  '[6,6]'
];
const express = require('express');
const socketIO = require('socket.io');
const path = require('path');
let usuarios = {};
let fichas = [],
  fichasS = [],
  fichaR = [];
let cont = 0,
  nUser = 0;

const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, 'public', 'index.html');

const server = express()
  .use(express.static(path.join(__dirname)))
  .use((req, res) => res.sendFile(INDEX))
  .listen(PORT, () => console.log(`Listening on ${ PORT }`));

const io = socketIO(server);

io.on('connection', (socket) => {
  if (nUser < 3) {
    console.log('Chat Message')
    socket.on('chatMessage', (from, msg) => {
      io.emit('chatMessage', from, msg);
    });
    socket.on('notifyUser', (user) => {
      io.emit('notifyUser', user);
    });
    socket.on('saveUser', (user) => {
      fichas = [];
      usuarios[user] = {};
      usuarios[user].fichas = [];
    });
    socket.on('sendDomino', (user) => {
      getDomino(user);
    });
    socket.on('serverDomino', (user, message) => {
      message = serverDomino();
      io.emit('serverDomino', user, "Ficha restante: " + message);
    });
    socket.on('showDomino', (user, message) => {
      message = showDomino(user);
      io.emit('showDomino', user, "Tus fichas son: " + message);
    });
    socket.on('reset', (user) => {
      cont = 0;
      fichasS = [];
      usuarios[user].fichas = [];
      console.log(usuarios)
    });
    socket.on('start', (user, message) => {
      getDomino(user);
    });
    nUser++;
    console.log(nUser);
  }
  socket.on('disconnect', function() {
    nUser--;
    console.log(nUser);
    io.emit('user disconnected');
  });

});

function getDomino(user) {
  while (cont < 9) {
    let a = Math.floor(Math.random() * (28 - 0)) - 0;
    if (((fichas.indexOf(dom[a])) === -1) && ((fichasS.indexOf(dom[a])) === -1)) {
      fichas.push(dom[a]);
      fichasS.push(dom[a]);
      cont++;
    }
  }
  cont = 0;
  usuarios[user].fichas = fichas;
  // console.log("Fichas dadas"+fichasS);
  console.log(usuarios);
  console.log(dom[5].charAt(3));
}

function serverDomino() {
  cont = 0;
  fichaR = [];
  while (cont < 28) {
    if ((fichasS.indexOf(dom[cont])) === -1) {
      fichaR.push(dom[cont]);
    }
    cont++;
  }
  return fichaR;
}

function showDomino(user) {
  return usuarios[user].fichas;
}
<commit_msg>Console.log to charAt deleted<commit_after>let dom = [
  '[0,0]',
  '[0,1]',
  '[0,2]',
  '[0,3]',
  '[0,4]',
  '[0,5]',
  '[0,6]',
  '[1,1]',
  '[1,2]',
  '[1,3]',
  '[1,4]',
  '[1,5]',
  '[1,6]',
  '[2,2]',
  '[2,3]',
  '[2,4]',
  '[2,5]',
  '[2,6]',
  '[3,3]',
  '[3,4]',
  '[3,5]',
  '[3,6]',
  '[4,4]',
  '[4,5]',
  '[4,6]',
  '[5,5]',
  '[5,6]',
  '[6,6]'
];
const express = require('express');
const socketIO = require('socket.io');
const path = require('path');
let usuarios = {};
let fichas = [],
  fichasS = [],
  fichaR = [];
let cont = 0,
  nUser = 0;

const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, 'public', 'index.html');

const server = express()
  .use(express.static(path.join(__dirname)))
  .use((req, res) => res.sendFile(INDEX))
  .listen(PORT, () => console.log(`Listening on ${ PORT }`));

const io = socketIO(server);

io.on('connection', (socket) => {
  if (nUser < 3) {
    console.log('Chat Message')
    socket.on('chatMessage', (from, msg) => {
      io.emit('chatMessage', from, msg);
    });
    socket.on('notifyUser', (user) => {
      io.emit('notifyUser', user);
    });
    socket.on('saveUser', (user) => {
      fichas = [];
      usuarios[user] = {};
      usuarios[user].fichas = [];
    });
    socket.on('sendDomino', (user) => {
      getDomino(user);
    });
    socket.on('serverDomino', (user, message) => {
      message = serverDomino();
      io.emit('serverDomino', user, "Ficha restante: " + message);
    });
    socket.on('showDomino', (user, message) => {
      message = showDomino(user);
      io.emit('showDomino', user, "Tus fichas son: " + message);
    });
    socket.on('reset', (user) => {
      cont = 0;
      fichasS = [];
      usuarios[user].fichas = [];
      console.log(usuarios)
    });
    socket.on('start', (user, message) => {
      getDomino(user);
    });
    nUser++;
    console.log(nUser);
  }
  socket.on('disconnect', function() {
    nUser--;
    console.log(nUser);
    io.emit('user disconnected');
  });

});

function getDomino(user) {
  while (cont < 9) {
    let a = Math.floor(Math.random() * (28 - 0)) - 0;
    if (((fichas.indexOf(dom[a])) === -1) && ((fichasS.indexOf(dom[a])) === -1)) {
      fichas.push(dom[a]);
      fichasS.push(dom[a]);
      cont++;
    }
  }
  cont = 0;
  usuarios[user].fichas = fichas;
  // console.log("Fichas dadas"+fichasS);
  console.log(usuarios);
}

function serverDomino() {
  cont = 0;
  fichaR = [];
  while (cont < 28) {
    if ((fichasS.indexOf(dom[cont])) === -1) {
      fichaR.push(dom[cont]);
    }
    cont++;
  }
  return fichaR;
}

function showDomino(user) {
  return usuarios[user].fichas;
}
<|endoftext|>


<commit_before>var sweetAlertConfirmConfig = sweetAlertConfirmConfig || {}; // Add default config object

(function( $ ) {
  var sweetAlertConfirm = function(event) {

    swalDefaultOptions = {
      title: sweetAlertConfirmConfig.title || 'Are you sure?',
      type: sweetAlertConfirmConfig.type || 'warning',
      showCancelButton: sweetAlertConfirmConfig.showCancelButton || true,
      //confirmButtonColor: sweetAlertConfirmConfig.confirmButtonColor || null, //"#DD6B55" removed by Noc, do not apply default color as it triggers inline styles on buttons
      //Null causes javascript errors when hover is fired on confirm buttons
      confirmButtonText: sweetAlertConfirmConfig.confirmButtonText || "Ok",
      cancelButtonText: sweetAlertConfirmConfig.cancelButtonText || "Cancel"
    }
    if (sweetAlertConfirmConfig.confirmButtonColor !== null) {
      swalDefaultOptions.confirmButtonColor = sweetAlertConfirmConfig.confirmButtonColor
    }

      $linkToVerify = $(this)
      var swalOptions = swalDefaultOptions;
      var optionKeys = [
                          'confirm',
                          'text',
                          'sweetAlertType',
                          'showCancelButton',
                          'confirmButtonColor',
                          'cancelButtonColor',
                          'confirmButtonText',
                          'cancelButtonText',
                          'closeOnConfirm',
                          'html',
                          'imageUrl',
                          'allowOutsideClick',
                          'remote',
                          'method',
                          'function'
                        ];

      function afterAlertCallback(r){
        if (nameFunction) {
          window[nameFunction]();
        }
        if (swalOptions['remote'] === true) {
          if (r === false) {
            return false;
          } else {
            $.rails.handleRemote($linkToVerify)
          }
        }
        else if(swalOptions[ 'method' ] !== undefined) {
          if (r === false) {
            return false;
          } else {
            $.rails.handleMethod($linkToVerify);
          }
        }
        else {
          if (r === false) {
            return false;
          } else {
            if($linkToVerify.attr('type') == 'submit'){
              var name = $linkToVerify.attr('name'),
              data = name ? {name: name, value:$linkToVerify.val()} : null;
              $linkToVerify.closest('form').data('ujs:submit-button', data);
              $linkToVerify.closest('form').submit();
            }
            else {
              window.location.href = $linkToVerify.attr('href');
            }

          }
        }
      }

      var beforeFunction = null;

      $.each($linkToVerify.data(), function(key, val){
        if ($.inArray(key, optionKeys) >= 0) {
          swalOptions[key] = val
          if (key == 'sweetAlertType') {
            swalOptions['type'] = val;
          }
        }
        // Make a before callback to verify that swal should be shown
        if(key == 'sabeforefunction') {
          beforeFunction = val;
        }
      });

      // Skip alert if false
      if(beforeFunction != null) {
        var beforeRes = window[beforeFunction]($linkToVerify);
        if(beforeRes === true) {
          return afterAlertCallback(true); // Skip alert
        }
      }

      var nameFunction = swalOptions['function'];
      message = $linkToVerify.attr('data-sweet-alert-confirm')
      swalOptions['title'] = message
      swal(swalOptions, afterAlertCallback);

      return false;
  }
  $(document).on('ready page:update ajaxComplete', function() {
    $('[data-sweet-alert-confirm]').on('click', sweetAlertConfirm)
  });

  $(document).on('ready page:load', function() {
    //To avoid "Uncaught TypeError: Cannot read property 'querySelector' of null" on turbolinks
    if (typeof window.sweetAlertInitialize === 'function') {
      window.sweetAlertInitialize();
    }
  });

})( jQuery );
<commit_msg>simply added a customClass key<commit_after>var sweetAlertConfirmConfig = sweetAlertConfirmConfig || {}; // Add default config object

(function( $ ) {
  var sweetAlertConfirm = function(event) {

    swalDefaultOptions = {
      title: sweetAlertConfirmConfig.title || 'Are you sure?',
      type: sweetAlertConfirmConfig.type || 'warning',
      showCancelButton: sweetAlertConfirmConfig.showCancelButton || true,
      //confirmButtonColor: sweetAlertConfirmConfig.confirmButtonColor || null, //"#DD6B55" removed by Noc, do not apply default color as it triggers inline styles on buttons
      //Null causes javascript errors when hover is fired on confirm buttons
      confirmButtonText: sweetAlertConfirmConfig.confirmButtonText || "Ok",
      cancelButtonText: sweetAlertConfirmConfig.cancelButtonText || "Cancel"
    }
    if (sweetAlertConfirmConfig.confirmButtonColor !== null) {
      swalDefaultOptions.confirmButtonColor = sweetAlertConfirmConfig.confirmButtonColor
    }

      $linkToVerify = $(this)
      var swalOptions = swalDefaultOptions;
      var optionKeys = [
                          'confirm',
                          'text',
                          'sweetAlertType',
                          'showCancelButton',
                          'confirmButtonColor',
                          'cancelButtonColor',
                          'confirmButtonText',
                          'cancelButtonText',
                          'closeOnConfirm',
                          'html',
                          'imageUrl',
                          'allowOutsideClick',
                          'customClass',
                          'remote',
                          'method',
                          'function'
                        ];

      function afterAlertCallback(r){
        if (nameFunction) {
          window[nameFunction]();
        }
        if (swalOptions['remote'] === true) {
          if (r === false) {
            return false;
          } else {
            $.rails.handleRemote($linkToVerify)
          }
        }
        else if(swalOptions[ 'method' ] !== undefined) {
          if (r === false) {
            return false;
          } else {
            $.rails.handleMethod($linkToVerify);
          }
        }
        else {
          if (r === false) {
            return false;
          } else {
            if($linkToVerify.attr('type') == 'submit'){
              var name = $linkToVerify.attr('name'),
              data = name ? {name: name, value:$linkToVerify.val()} : null;
              $linkToVerify.closest('form').data('ujs:submit-button', data);
              $linkToVerify.closest('form').submit();
            }
            else {
              window.location.href = $linkToVerify.attr('href');
            }

          }
        }
      }

      var beforeFunction = null;

      $.each($linkToVerify.data(), function(key, val){
        if ($.inArray(key, optionKeys) >= 0) {
          swalOptions[key] = val
          if (key == 'sweetAlertType') {
            swalOptions['type'] = val;
          }
        }
        // Make a before callback to verify that swal should be shown
        if(key == 'sabeforefunction') {
          beforeFunction = val;
        }
      });

      // Skip alert if false
      if(beforeFunction != null) {
        var beforeRes = window[beforeFunction]($linkToVerify);
        if(beforeRes === true) {
          return afterAlertCallback(true); // Skip alert
        }
      }

      var nameFunction = swalOptions['function'];
      message = $linkToVerify.attr('data-sweet-alert-confirm')
      swalOptions['title'] = message
      swal(swalOptions, afterAlertCallback);

      return false;
  }
  $(document).on('ready page:update ajaxComplete', function() {
    $('[data-sweet-alert-confirm]').on('click', sweetAlertConfirm)
  });

  $(document).on('ready page:load', function() {
    //To avoid "Uncaught TypeError: Cannot read property 'querySelector' of null" on turbolinks
    if (typeof window.sweetAlertInitialize === 'function') {
      window.sweetAlertInitialize();
    }
  });

})( jQuery );
<|endoftext|>


<commit_before> // server.js

// set up ======================================================================
// get all the tools we need
var express  = require('express');
var app      = express();
var port     = process.env.PORT || 3000;
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');

var morgan       = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser   = require('body-parser');
var session      = require('express-session');

var configDB = require('./config/database.js');

// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
console.log(configDB.url);

require('./config/passport')(passport); // pass passport for configuration

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true})); // get information from html forms

app.set('view engine', 'ejs'); // set up ejs for templating

// required for passport
app.use(session({
				secret: process.env.SECRET_MODULUS,
				resave: true,
    			saveUninitialized: true })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport

// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);

<commit_msg>changed name variable<commit_after> // server.js

// set up ======================================================================
// get all the tools we need
var express  = require('express');
var app      = express();
var port     = process.env.PORT || 3000;
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');

var morgan       = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser   = require('body-parser');
var session      = require('express-session');

var configDB = require('./config/database.js');

// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
console.log(configDB.url);

require('./config/passport')(passport); // pass passport for configuration

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true})); // get information from html forms

app.set('view engine', 'ejs'); // set up ejs for templating

// required for passport
app.use(session({
				secret: process.env.SECRET_FRONTEND,
				resave: true,
    			saveUninitialized: true })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport

// launch ======================================================================
app.listen(process.env.IP, process.env.PORT);
console.log('The magic happens on port ' + port);

<|endoftext|>


<commit_before>/* globals define, d3 */
define(['d3'], function() {

    var lineFn = d3.svg.line()
        .x(d => d.x)
        .y(d => d.y)
        .interpolate('linear');

    var Connection = function(pEl, desc) {
        this.desc = desc;
        this.id = desc.id;
        this.src = desc.src;
        this.dst = desc.dst;
        this.isConnection = true;
        this.points = [];

        this.x = 10;
        this.y = 10;
        this._width = 0;
        this._height = 0;

        this.$pEl = pEl;
        this.$el = this.$pEl.append('g')
            .attr('id', `conn-${this.id}`);
        this.$path = this.$el.append('path')
            .attr('fill', 'none');

        this.$path
            .on('mouseover', () => this.$path.attr('stroke-width', 3))
            .on('mouseout', () =>  this.$path.attr('stroke-width', 2));
    };

    Connection.prototype.redraw = function() {
        this.$path.attr('d', lineFn(this.points))
            .transition()
            .attr('stroke-width', 2)
            .attr('stroke', 'black')
            .attr('fill', 'none')
            .attr('marker-end', 'url(#arrowhead)');

        // Update the x,y,width, height from the points
        this.updateBounds();
    };

    Connection.prototype.updateBounds = function() {
        var minX = Infinity,
            minY = Infinity,
            maxX = -Infinity,
            maxY = -Infinity;

        for (var i = this.points.length; i--;) {
            minX = Math.min(this.points[i].x, minX);
            minY = Math.min(this.points[i].y, minY);
            maxX = Math.max(this.points[i].x, maxX);
            maxY = Math.max(this.points[i].y, maxY);
        }

        this._width = maxX - minX;
        this._height = maxY - minY;
        this.x = minX + this._width/2;
        this.y = minY + this._height/2;
    };

    Connection.prototype.update = function(desc) {
        this.src = desc.src;
        this.dst = desc.dst;
    };

    Connection.prototype.getWidth = function() {
        return this._width;
    };

    Connection.prototype.getHeight = function() {
        return this._height;
    };

    Connection.prototype.remove = function() {
        this.$el.remove();
    };

    Connection.prototype.onSelect =
    Connection.prototype.onDeselect = function() {
    };

    return Connection;
});
<commit_msg>Updated desc on conn update. Fixes #223 (#224)<commit_after>/* globals define, d3 */
define(['d3'], function() {

    var lineFn = d3.svg.line()
        .x(d => d.x)
        .y(d => d.y)
        .interpolate('linear');

    var Connection = function(pEl, desc) {
        this.desc = desc;
        this.id = desc.id;
        this.src = desc.src;
        this.dst = desc.dst;
        this.isConnection = true;
        this.points = [];

        this.x = 10;
        this.y = 10;
        this._width = 0;
        this._height = 0;

        this.$pEl = pEl;
        this.$el = this.$pEl.append('g')
            .attr('id', `conn-${this.id}`);
        this.$path = this.$el.append('path')
            .attr('fill', 'none');

        this.$path
            .on('mouseover', () => this.$path.attr('stroke-width', 3))
            .on('mouseout', () =>  this.$path.attr('stroke-width', 2));
    };

    Connection.prototype.redraw = function() {
        this.$path.attr('d', lineFn(this.points))
            .transition()
            .attr('stroke-width', 2)
            .attr('stroke', 'black')
            .attr('fill', 'none')
            .attr('marker-end', 'url(#arrowhead)');

        // Update the x,y,width, height from the points
        this.updateBounds();
    };

    Connection.prototype.updateBounds = function() {
        var minX = Infinity,
            minY = Infinity,
            maxX = -Infinity,
            maxY = -Infinity;

        for (var i = this.points.length; i--;) {
            minX = Math.min(this.points[i].x, minX);
            minY = Math.min(this.points[i].y, minY);
            maxX = Math.max(this.points[i].x, maxX);
            maxY = Math.max(this.points[i].y, maxY);
        }

        this._width = maxX - minX;
        this._height = maxY - minY;
        this.x = minX + this._width/2;
        this.y = minY + this._height/2;
    };

    Connection.prototype.update = function(desc) {
        this.src = desc.src;
        this.dst = desc.dst;
        this.desc = desc;
    };

    Connection.prototype.getWidth = function() {
        return this._width;
    };

    Connection.prototype.getHeight = function() {
        return this._height;
    };

    Connection.prototype.remove = function() {
        this.$el.remove();
    };

    Connection.prototype.onSelect =
    Connection.prototype.onDeselect = function() {
    };

    return Connection;
});
<|endoftext|>


<commit_before>var http = require('http');
var path = require('path');
var log = require('./utils/log');
var util = require('util');
var fs = require('fs');

var Init = require('./init');
console.log(Init);
var Index = Init.init_modules();

var server = http.createServer(function(req, res) {
  //log(JSON.stringify(util.inspect(req)), "logs/req_" + Date.now() + ".json");
  var url = req.url;
  var req_url = req.url;
  if(!req_url.startsWith("/index")){
    req_url = "/index" + req_url;
  }
  try {
    var fstats = fs.lstatSync('public'+url);
    if(fstats.isFile()){
      //file exists, serve it
      serve_file(url, res)
    } else {
      Index.route(req, res, req_url);
    }
  } catch (e){
    Index.route(req, res, req_url);
  }

});
server.listen(process.env.PORT || 8250);
console.log("server listening port " + (process.env.PORT || 8250));

function serve_file(url, res){
  var extname = path.extname(url);
  switch (extname) {
    case '.ico':
      contentType = "image/x-icon";
      break;
    case '.js':
      contentType = 'text/javascript';
      break;
    case '.css':
      contentType = 'text/css';
      break;
    case '.json':
      contentType = 'application/json';
      break;
    case '.png':
      contentType = 'image/png';
      break;
    case '.jpg':
      contentType = 'image/jpg';
      break;
    case '.wav':
      contentType = 'audio/wav';
      break;
    default:
      contentType = 'text/html';
  }
  fs.readFile('public'+url, function(error, content) {
    if (error) {
      res.status(500).end();
    }
    else {
        res.writeHead(200, { 'Content-Type': contentType });
        console.log('public file sent: '+url);
        res.end(content, 'utf-8');
    }
  });
}
<commit_msg>port ip setup<commit_after>var http = require('http');
var path = require('path');
var log = require('./utils/log');
var util = require('util');
var fs = require('fs');

var Init = require('./init');
console.log(Init);
var Index = Init.init_modules();

var server = http.createServer(function(req, res) {
  //log(JSON.stringify(util.inspect(req)), "logs/req_" + Date.now() + ".json");
  var url = req.url;
  var req_url = req.url;
  if(!req_url.startsWith("/index")){
    req_url = "/index" + req_url;
  }
  try {
    var fstats = fs.lstatSync('public'+url);
    if(fstats.isFile()){
      //file exists, serve it
      serve_file(url, res)
    } else {
      Index.route(req, res, req_url);
    }
  } catch (e){
    Index.route(req, res, req_url);
  }

});
server.listen(process.env.PORT || 8250, process.env.OPENSHIFT_NODEJS_IP);
console.log("server listening port " + (process.env.OPENSHIFT_NODEJS_PORT || 8250));

function serve_file(url, res){
  var extname = path.extname(url);
  switch (extname) {
    case '.ico':
      contentType = "image/x-icon";
      break;
    case '.js':
      contentType = 'text/javascript';
      break;
    case '.css':
      contentType = 'text/css';
      break;
    case '.json':
      contentType = 'application/json';
      break;
    case '.png':
      contentType = 'image/png';
      break;
    case '.jpg':
      contentType = 'image/jpg';
      break;
    case '.wav':
      contentType = 'audio/wav';
      break;
    default:
      contentType = 'text/html';
  }
  fs.readFile('public'+url, function(error, content) {
    if (error) {
      res.status(500).end();
    }
    else {
        res.writeHead(200, { 'Content-Type': contentType });
        console.log('public file sent: '+url);
        res.end(content, 'utf-8');
    }
  });
}
<|endoftext|>


<commit_before>const express = require('express');
const superagent = require('superagent');
const jsonParser = require('body-parser').json();

const app = express()

app.use('/', express.static(__dirname + '/dist'));

const port = 4000;
app.listen(port);
console.log('Go to http://localhost:' + port);
<commit_msg>Get port from environment.<commit_after>const express = require('express');
const superagent = require('superagent');
const jsonParser = require('body-parser').json();

const app = express()

app.use('/', express.static(__dirname + '/dist'));

const port = process.env.PORT || 8080;
app.listen(port);
console.log('Server listening in port: ' + port);
<|endoftext|>


<commit_before><commit_msg>BNC: Implemented express server<commit_after>var express = require("express"),
    path = require("path"),
    app = express(),
    server = require("http").Server(app),
    port = 54879;

app.use(express.static("src"));
app.use(express.static("node_modules"));
app.use(express.static(__dirname));

server.listen(port, function () {
    console.log("Server is up and running, listening on port: " + port);
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

process.chdir(__dirname + '/../')

var screen = require('../index')

screen().pipe(process.stdout)
<commit_msg>simple server (http endpoint) support<commit_after>#!/usr/bin/env node

process.chdir(__dirname + '/../')

var screen = require('../index')
var http = require('http')

// TODO: minimalist support; usage doc
var doServer = process.argv[2]
if (doServer && doServer === '-s') {
  runServer()
} else {
  screen().pipe(process.stdout)
}

function runServer() {
  var server = http.createServer(function (req, res) {
    if (req.url === '/') {
      screen().pipe(res)
    }
  })
  server.listen(6900)
}
<|endoftext|>


<commit_before>var DeleteRowView = require('../../../../../../javascripts/cartodb/common/dialogs/delete_row/delete_row_view');

describe('common/dialogs/delete_row/delete_row_view', function() {
  beforeEach(function() {

    this.row = new cdb.admin.Row({
      cartodb_id: 100,
      the_geom: JSON.stringify({ type: 'point', coordinates: [2,1] })
    });

    this.table = TestUtil.createTable('test', [['the_geom', 'geometry']]);
    this.table.data().add(this.row);

    spyOn(this.row, 'destroy');

    this.view = new DeleteRowView({
      table: this.table,
      row: this.row
    });

    this.view.render();
  });

  it('should render the view', function() {
    expect(this.innerHTML()).toContain('Ok, delete');
    expect(this.innerHTML()).toContain("You are about to delete one row");
    expect(this.innerHTML()).toContain("Are you sure you want to delete it?");
  });

  describe('when click ok to delete row', function() {
    it('should call to destroy the model', function() {
      var server = sinon.fakeServer.create();
      server.respondWith("DELETE", "/api/v1/tables/" + this.table.get('name') + "/records/100", [ 204, { "Content-Type": "application/json" }, '' ]);

      var succeded = false;

      this.table.bind('removing:row', function() {
        succeded = true;
      });

      this.view.$('.ok').click();

      server.respond();
      expect(succeded).toBeTruthy();
    });
  });

  afterEach(function() {
    this.view.clean();
  });
});
<commit_msg>Adds fail spec<commit_after>var DeleteRowView = require('../../../../../../javascripts/cartodb/common/dialogs/delete_row/delete_row_view');

describe('common/dialogs/delete_row/delete_row_view', function() {
  beforeEach(function() {

    this.row = new cdb.admin.Row({
      cartodb_id: 100,
      the_geom: JSON.stringify({ type: 'point', coordinates: [2,1] })
    });

    this.table = TestUtil.createTable('test', [['the_geom', 'geometry']]);
    this.table.data().add(this.row);

    spyOn(this.row, 'destroy');

    this.view = new DeleteRowView({
      table: this.table,
      row: this.row
    });

    this.view.render();
  });

  it('should render the view', function() {
    expect(this.innerHTML()).toContain('Ok, delete');
    expect(this.innerHTML()).toContain("You are about to delete one row");
    expect(this.innerHTML()).toContain("Are you sure you want to delete it?");
  });

  describe('when click ok to delete row', function() {
    it('should call to destroy the model', function() {
      var server = sinon.fakeServer.create();
      server.respondWith("DELETE", "/api/v1/tables/" + this.table.get('name') + "/records/100", [ 204, { "Content-Type": "application/json" }, '' ]);

      var succeded = false;

      this.table.bind('removing:row', function() {
        succeded = true;
      });

      this.view.$('.ok').click();

      server.respond();
      expect(succeded).toBeTruthy();
    });
  });

  describe('when click ok to delete row and it fails', function() {
    it('should call to destroy the model', function() {
      var server = sinon.fakeServer.create();
      server.respondWith("DELETE", "/api/v1/tables/" + this.table.get('name') + "/records/100", [ 500, { "Content-Type": "application/json" }, '{ "error": "bad request" }' ]);

      var succeded = false;

      this.table.bind('remove:row', function() {
        succeded = true;
      });

      this.view.$('.ok').click();

      server.respond();

      expect(succeded).toBeFalsy();
      expect(this.view._panes.activeTab).toEqual("fail");
    });
  });

  afterEach(function() {
    this.view.clean();
  });
});
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);

app.set('port', process.env.PORT || 3435);
app.use('/controlpanel', express.static(__dirname + '/asteroids-controlpanel'));
app.get('/', function(request, response){
    response.redirect('/controlpanel/');
});

server.listen(app.get('port'));
console.log('Asteroids server started listening on port ' + app.get('port'));

var Game = require('asteroids-game');
var Asteroids = require('asteroids-asteroid');

var options = require('./options');
var game = new Game(options);
for (var index = 0; index < options.asteroidCount; index++) {
    game.addAsteroid();
}

var viewers = {};

io.sockets.on('connection', function(socket){
    console.log('socket %s connected', socket.id);

    socket.on('viewer', function(){
	console.log('socket %s is a viewer', socket.id);
	viewers[socket.id] = socket;
    })

    socket.on('disconnect', function(){
	console.log('socket %s left the game', socket.id);
	delete viewers[socket.id];
    });
});

setInterval(function(){
    console.log('tick');
    game.tick();
    var state = game.state();
    for (var id in viewers) {
	viewers[id].emit('game-state', state)
    }
}, 1000);
<commit_msg>add provisional fighter<commit_after>var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);

app.set('port', process.env.PORT || 3435);
app.use('/controlpanel', express.static(__dirname + '/asteroids-controlpanel'));
app.get('/', function(request, response){
    response.redirect('/controlpanel/');
});

server.listen(app.get('port'));
console.log('Asteroids server started listening on port ' + app.get('port'));

var Game = require('asteroids-game');
var Asteroids = require('asteroids-asteroid');

var options = require('./options');
var game = new Game(options);
game.addFighter(new Asteroids());
for (var index = 0; index < options.asteroidCount; index++) {
    game.addAsteroid();
}

var viewers = {};

io.sockets.on('connection', function(socket){
    console.log('socket %s connected', socket.id);

    socket.on('viewer', function(){
	console.log('socket %s is a viewer', socket.id);
	viewers[socket.id] = socket;
    })

    socket.on('disconnect', function(){
	console.log('socket %s left the game', socket.id);
	delete viewers[socket.id];
    });
});

setInterval(function(){
    console.log('tick');
    game.tick();
    var state = game.state();
    for (var id in viewers) {
	viewers[id].emit('game-state', state)
    }
}, 1000);
<|endoftext|>


<commit_before>var express = require('express'),
    server = express(),
    vhost = require('vhost'),
    config = require('./config.js');

server.use(vhost('mates-checker.'+config.env.dns, require('./mates-checker/index')));

server.get('/', function(req, res) {

    var script = '';

    res.end('
More tools incoming
' + script + '');
});

module.exports = server;<commit_msg>add analytics on default page<commit_after>var express = require('express'),
    server = express(),
    vhost = require('vhost'),
    config = require('./config.js');

server.use(vhost('mates-checker.'+config.env.dns, require('./mates-checker/index')));

server.get('/', function(req, res) {

    var ads = '';

    var analytics = ""

    res.end('
More tools incoming
' + ads + analytics + '');
});

module.exports = server;<|endoftext|>


<commit_before>#!/usr/bin/env node

var _ = require('lodash');
var pkg = require('../package.json');
var cmd = require('commander');
var table = require('text-table');
var emotes = require('../lib/emotes');
var copy = require('copy-paste').silent().copy;

cmd
.version(pkg.version)
.usage('[options] <tag>')
.option('-t, --tags', 'list available tags')
.option('-c, --count <n>', 'specify number to return', parseInt)
.option('-p, --clip', 'copy emoticon(s) to the clipboard')
.option('-v, --verbose', 'get verbose info about the selected emoticon(s)')
.parse(process.argv);

if (cmd.tags) {
  var tags = emotes.getTags();
  var tagList = [];
  var limit = 5;

  for (var i = 0; i < Math.ceil(tags.length / limit); i++) {
    var start = i * limit;
    var end = (i + 1) * limit;

    tagList.push(tags.slice(start, end));
  }
  console.log(table(tagList));
  return;
}

var tag = cmd.args.join(' ');
var count = cmd.count || 1;
var emoticons = [];

for (var i = 0; i < count; i++) {
  emoticons.push(emotes.select(tag));
}

if (!cmd.verbose) {
  emoticons = _.map(emoticons, 'string');
} else {
  emoticons = _.map(emoticons, JSON.stringify);
}

var output = emoticons.join("\n");

if(cmd.clip) {
  copy(output);
}

// output selection
console.log(output);<commit_msg>fix usage pattern, tag is optional<commit_after>#!/usr/bin/env node

var _ = require('lodash');
var pkg = require('../package.json');
var cmd = require('commander');
var table = require('text-table');
var emotes = require('../lib/emotes');
var copy = require('copy-paste').silent().copy;

cmd
.version(pkg.version)
.usage('[options] [tag]')
.option('-t, --tags', 'list available tags')
.option('-c, --count <n>', 'specify number to return', parseInt)
.option('-p, --clip', 'copy emoticon(s) to the clipboard')
.option('-v, --verbose', 'get verbose info about the selected emoticon(s)')
.parse(process.argv);

// show tags it tags flag is set, do nothing else
if (cmd.tags) {
  var tags = emotes.getTags();
  var tagList = [];
  var limit = 5; // number of columns to show

  for (var i = 0; i < Math.ceil(tags.length / limit); i++) {
    var start = i * limit;
    var end = (i + 1) * limit;

    tagList.push(tags.slice(start, end));
  }
  console.log(table(tagList));
  return;
}

var tag = cmd.args.join(' ');
var count = cmd.count || 1;
var emoticons = [];

for (var i = 0; i < count; i++) {
  emoticons.push(emotes.select(tag));
}

if (!cmd.verbose) {
  emoticons = _.map(emoticons, 'string');
} else {
  emoticons = _.map(emoticons, JSON.stringify);
}

var output = emoticons.join("\n");

if(cmd.clip) {
  copy(output);
}

// output selection
console.log(output);<|endoftext|>


<commit_before>module.exports = function (callback) {
  var fs = require('fs')
  var path = require('path')
  var express = require('express')
  var cors = require('cors')
  var compress = require('compression')
  var sharp = require('sharp')
  var config = require('./config')()
  var packageinfo = require('./package.json')
  var imageProcessor = require('./imageProcessor')(sharp, path, config, fs)

  var app = express()

  sharp.cache(0)

  try {
    var images = require(config.image_store_path)
  } catch (e) {
    var images = []
  }

  process.addListener('uncaughtException', function (err) {
    console.log('Uncaught exception: ')
    console.trace(err)
  })

  app.use(compress());

  app.use(cors());

  app.use(express.static(path.join(__dirname, 'public'), {
    extensions: ['html']
  }));

  app.get('/info', function (req, res, next) {
    res.jsonp({ name: packageinfo.name, version: packageinfo.version, author: packageinfo.author })
  })

  app.get('/list', function (req, res, next) {
    var newImages = []

    for (var i in images) {
      var item = images[i]
      var image = {
        format: item.format,
        width: item.width,
        height: item.height,
        filename: path.basename(item.filename),
        id: item.id,
        author: item.author,
        author_url: item.author_url,
        post_url: item.post_url
      }

      newImages.push(image)
    }

    res.jsonp(newImages)
  })

  app.get('/:size', function (req, res, next) {
    serveImage(req, res, true, false)
  })

  app.get('/g/:size', function (req, res, next) {
    serveImage(req, res, true, true)
  })

  app.get('/:width/:height', function (req, res, next) {
    serveImage(req, res, false, false)
  })

  app.get('/g/:width/:height', function (req, res, next) {
    serveImage(req, res, false, true)
  })

  app.all('*', function (req, res, next) {
    res.status(404)
    res.send({ error: 'Resource not found' })
  })

  var serveImage = function(req, res, square, gray) {
    checkParameters(req.params, req.query, square, function (error, code, message) {
      if (error) {
        return displayError(res, code, message)
      }

      imageProcessor.getWidthAndHeight(req.params, square, function (width, height) {
        var filePath
        var blur = false

        if (req.query.image) {
          var matchingImage = findMatchingImage(req.query.image)

          if (matchingImage) {
            filePath = matchingImage.filename

            if (parseInt(width) == 0) {
              width = matchingImage.width
            }

            if (parseInt(height) == 0) {
              height = matchingImage.height
            }
          } else {
            return displayError(res, 404, 'Invalid image id')
          }
        } else {
          filePath = images[Math.floor(Math.random() * images.length)].filename
        }

        imageProcessor.getProcessedImage(parseInt(width), parseInt(height), req.query.gravity, gray, !(!req.query.blur && req.query.blur !== ''), filePath, (!req.query.image && !req.query.random && req.query.random !== ''), function (error, imagePath) {
          if (error) {
            console.log('filePath: ' + filePath)
            console.log('imagePath: ' + imagePath)
            console.log('error: ' + error)
            return displayError(res, 500, 'Something went wrong')
          }

          res.sendFile(imagePath)
          process.send(imagePath)
        })
      })
    })
  }

  var checkParameters = function (params, queryparams, square, callback) {
    if ((square && !params.size) || (square && isNaN(parseInt(params.size))) || (!square && !params.width) || (!square && !params.height) || (!square && isNaN(parseInt(params.width))) || (!square && isNaN(parseInt(params.height))) || (queryparams.gravity && sharp.gravity[queryparams.gravity] != 0 && !sharp.gravity[queryparams.gravity])) {
      return callback(true, 400, 'Invalid arguments')
    }

    if (params.size > config.max_width || params.size > config.max_height || params.height > config.max_height || params.width > config.max_width) {
      if (queryparams.image) {
        var matchingImage = findMatchingImage(queryparams.image)

        if (matchingImage && params.height == matchingImage.height && params.width == matchingImage.width) {
          return callback(false)
        }
      }

      return callback(true, 413, 'Specified dimensions too large')
    }

    callback(false)
  }

  var findMatchingImage = function (id) {
    var matchingImages = images.filter(function (image) {
      return image.id == id
    })

    if (!matchingImages.length) {
      return false
    }

    return matchingImages[0]
  }

  var displayError = function (res, code, message) {
    res.status(code)
    res.send({ error: message })
  }

  callback(app)
}<commit_msg>Cache everything except for ?random images<commit_after>module.exports = function (callback) {
  var fs = require('fs')
  var path = require('path')
  var express = require('express')
  var cors = require('cors')
  var compress = require('compression')
  var sharp = require('sharp')
  var config = require('./config')()
  var packageinfo = require('./package.json')
  var imageProcessor = require('./imageProcessor')(sharp, path, config, fs)

  var app = express()

  sharp.cache(0)

  try {
    var images = require(config.image_store_path)
  } catch (e) {
    var images = []
  }

  process.addListener('uncaughtException', function (err) {
    console.log('Uncaught exception: ')
    console.trace(err)
  })

  app.use(compress());

  app.use(cors());

  app.use(express.static(path.join(__dirname, 'public'), {
    extensions: ['html']
  }));

  app.get('/info', function (req, res, next) {
    res.jsonp({ name: packageinfo.name, version: packageinfo.version, author: packageinfo.author })
  })

  app.get('/list', function (req, res, next) {
    var newImages = []

    for (var i in images) {
      var item = images[i]
      var image = {
        format: item.format,
        width: item.width,
        height: item.height,
        filename: path.basename(item.filename),
        id: item.id,
        author: item.author,
        author_url: item.author_url,
        post_url: item.post_url
      }

      newImages.push(image)
    }

    res.jsonp(newImages)
  })

  app.get('/:size', function (req, res, next) {
    serveImage(req, res, true, false)
  })

  app.get('/g/:size', function (req, res, next) {
    serveImage(req, res, true, true)
  })

  app.get('/:width/:height', function (req, res, next) {
    serveImage(req, res, false, false)
  })

  app.get('/g/:width/:height', function (req, res, next) {
    serveImage(req, res, false, true)
  })

  app.all('*', function (req, res, next) {
    res.status(404)
    res.send({ error: 'Resource not found' })
  })

  var serveImage = function(req, res, square, gray) {
    checkParameters(req.params, req.query, square, function (error, code, message) {
      if (error) {
        return displayError(res, code, message)
      }

      imageProcessor.getWidthAndHeight(req.params, square, function (width, height) {
        var filePath
        var blur = false

        if (req.query.image) {
          var matchingImage = findMatchingImage(req.query.image)

          if (matchingImage) {
            filePath = matchingImage.filename

            if (parseInt(width) == 0) {
              width = matchingImage.width
            }

            if (parseInt(height) == 0) {
              height = matchingImage.height
            }
          } else {
            return displayError(res, 404, 'Invalid image id')
          }
        } else {
          filePath = images[Math.floor(Math.random() * images.length)].filename
        }

        var isRandom = (req.query.random || req.query.random === '')

        imageProcessor.getProcessedImage(parseInt(width), parseInt(height), req.query.gravity, gray, !(!req.query.blur && req.query.blur !== ''), filePath, (!req.query.image && !req.query.random && req.query.random !== ''), function (error, imagePath) {
          if (error) {
            console.log('filePath: ' + filePath)
            console.log('imagePath: ' + imagePath)
            console.log('error: ' + error)
            return displayError(res, 500, 'Something went wrong')
          }

          res.sendFile(imagePath, {
            maxAge: isRandom ? 0 : '24h' // Lets set cache to 24h for now
          })
          process.send(imagePath)
        })
      })
    })
  }

  var checkParameters = function (params, queryparams, square, callback) {
    if ((square && !params.size) || (square && isNaN(parseInt(params.size))) || (!square && !params.width) || (!square && !params.height) || (!square && isNaN(parseInt(params.width))) || (!square && isNaN(parseInt(params.height))) || (queryparams.gravity && sharp.gravity[queryparams.gravity] != 0 && !sharp.gravity[queryparams.gravity])) {
      return callback(true, 400, 'Invalid arguments')
    }

    if (params.size > config.max_width || params.size > config.max_height || params.height > config.max_height || params.width > config.max_width) {
      if (queryparams.image) {
        var matchingImage = findMatchingImage(queryparams.image)

        if (matchingImage && params.height == matchingImage.height && params.width == matchingImage.width) {
          return callback(false)
        }
      }

      return callback(true, 413, 'Specified dimensions too large')
    }

    callback(false)
  }

  var findMatchingImage = function (id) {
    var matchingImages = images.filter(function (image) {
      return image.id == id
    })

    if (!matchingImages.length) {
      return false
    }

    return matchingImages[0]
  }

  var displayError = function (res, code, message) {
    res.status(code)
    res.send({ error: message })
  }

  callback(app)
}<|endoftext|>


<commit_before><commit_msg>Adds base server logic<commit_after>const express = require('express'),
    mongoose = require('mongoose'),
    morgan = require('morgan'),
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    app = express(),
    config = require('./app/config/config');

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());

mongoose.connect(config.db);
mongoose.connection.on('connected', () => { console.log('Mongoose default connection open to ' + config.db); });

app.listen(config.port, (err) => {
    if (err) { throw err; }

    console.log("App listening on port " + config.port);
});<|endoftext|>


<commit_before>var winston = require('winston');
var multer = require('multer');
var bodyParser = require('body-parser');
var express = require("express");
var app = express();
var path = require('path');
var fs = require('fs');
var md5File = require('md5-file');
var moment = require('moment');
var schedule = require('node-schedule');
var yubikey = require('./lib/yubikey.js');
moment().format();

function infoWrapper(message) {
    var timestamp = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
    winston.log('info', "[" + timestamp + "] %s", message);
}

function warningWrapper(message) {
    var timestamp = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
    winston.log('warn', "[" + timestamp + "] %s", message);
}

function errorWrapper(message) {
    var timestamp = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
    winston.log('error', "[" + timestamp + "] %s", message);
}

/* --- Configuration parsing --- */

var config = JSON.parse(fs.readFileSync('lib/config.js'));

if (Object.prototype.toString.call(config.apiId) === '[object Array]') {
    if (Object.prototype.toString.call(config.apiKey) === '[object Array]') {
        if (config.apiId.length !== config.apiKey.length) {
            if (config.apiId.length === 0 || config.apiKey.length === 0) {
                errorWrapper('Configuration missing: have you edited the defaults in "lib/config.js"?');
            } else {
                errorWrapper('Configuration mismatch: not the same number of API IDs and Keys.');
            }
            process.exit(1);
        }
    } else {
        errorWrapper('Configuration mismatch: API Keys field is not an array.');
        process.exit(1);
    }
} else {
    errorWrapper('Configuration mismatch: API IDs field is not an array.');
    process.exit(1);
}

yubikey.apiId = config.apiId;
yubikey.apiKey = config.apiKey;
var uploadPath = config.uploadFolder || "uploads/",
    domainUrl = (config.domainName || "http://localhost:9980/") + uploadPath,
    maxFileSize = config.maxFileSize || 52428800,
    maxFileExpiration = config.maxFileExpiration || 30,
    debug = config.debug || false;
/* --- End configuration parsing --- */

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

var authUpload = function(req, res, next) {
    if (debug) {
        warningWrapper("Bypassing token validation.");
        next();
        return;
    }
    var token = req.query.token;
    yubikey.verify(token, function(isValid, status) {
        if (isValid) {
            infoWrapper("Valid token received.");
            next();
        } else {
            warningWrapper("Invalid token received! Reason: " + status);
            res.status(401).send("AUTH ERROR - " + status + "\n");
        }
    });
}

var dateOk;
var deletionDate;
var validateUpload = function(req, res, next) {
    dateOk = false;
    deletionDate = undefined;
    var deletionQuery = req.query.del,
        deletionDay,
        deletionMonth,
        deletionYear;
    if (deletionQuery) {
        if (/^[0-9]+s$/.test(deletionQuery)) {
            deletionDate = moment().add(deletionQuery.substr(0, deletionQuery.indexOf('s')), 'seconds');
        } else if (/^[0-9]+m$/.test(deletionQuery)) {
            deletionDate = moment().add(deletionQuery.substr(0, deletionQuery.indexOf('m')), 'minutes');
        } else if (/^[0-9]+h$/.test(deletionQuery)) {
            deletionDate = moment().add(deletionQuery.substr(0, deletionQuery.indexOf('h')), 'hours');
        } else if (/^[0-9]+d$/.test(deletionQuery)) {
            deletionDate = moment().add(deletionQuery.substr(0, deletionQuery.indexOf('d')), 'days');
        } else if (/^[0-9]{2}D[0-9]{2}M[0-9]{4}Y$/.test(deletionQuery)) {
            deletionDay = deletionQuery.substr(0, deletionQuery.indexOf('D'));
            deletionMonth = deletionQuery.substr(deletionQuery.indexOf('D') + 1, deletionQuery.indexOf('M'));
            deletionYear = deletionQuery.substr(deletionQuery.indexOf('M') + 1, deletionQuery.indexOf('Y'));
            deletionDate = moment(deletionDay + "-" + deletionMonth + "-" + deletionYear, "DD-MM-YYYY");
        } else if (/^[0-9]{2}D[0-9]{2}M[0-9]{4}Y[0-9]{2}h[0-9]{2}m$/.test(deletionQuery)) {
            deletionDay = deletionQuery.substr(0, deletionQuery.indexOf('D'));
            deletionMonth = deletionQuery.substr(deletionQuery.indexOf('D') + 1, deletionQuery.indexOf('M'));
            deletionYear = deletionQuery.substr(deletionQuery.indexOf('M') + 1, deletionQuery.indexOf('Y'));
            deletionHour = deletionQuery.substr(deletionQuery.indexOf('Y') + 1, deletionQuery.indexOf('h'));
            deletionMinute = deletionQuery.substr(deletionQuery.indexOf('h') + 1, deletionQuery.indexOf('m'));
            deletionDate = moment(deletionDay + "-" + deletionMonth + "-" + deletionYear + " " + deletionHour + ":" + deletionMinute, "DD-MM-YYYY HH:mm");
        } else {
            deletionDate = moment.invalid();
        }
        if (deletionDate.isValid()) {  // TODO: return codes (http://momentjs.com/docs/#/parsing/is-valid/)
            if (deletionDate.isAfter(moment().add(maxFileExpiration, 'days'))) {
                if (debug) {
                    warningWrapper("Too big deletion date received: " + deletionDate.toString() + " - setting to maximum value.");
                } else {
                    warningWrapper("Too big deletion date received, setting to maximum value.");
                }
                deletionDate = moment().add(maxFileExpiration, 'days');
                res.header('Dumpster-Deletion-Date', 'MAX');
            } else {
                if (debug) {
                    infoWrapper("Valid deletion date received: " + deletionDate.toString());
                } else {
                    infoWrapper("Valid deletion date received.");
                }
                res.header('Dumpster-Deletion-Date', 'OK');
            }
            dateOk = true;
            next();
        } else {
            if (debug) {
                warningWrapper("Invalid deletion date received: " + deletionDate.toString());
            } else {
                warningWrapper("Invalid deletion date received!");
            }
            res.status(400).send("BAD DELETION DATE\n");
        }
    } else {
        res.header('Dumpster-Deletion-Date', 'NONE');
        next();
    }
}

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname.replace(/[^0-9A-Za-z\.]+/g, "_").replace(/\.\.+/g, "_"));
  }
})

var upload = multer({ storage: storage,
    limits: {
        fields: 0, // No extra POST fields
        fileSize: maxFileSize
    }
}).single('file');

var postUpload = function(req, res) {
    if (dateOk) {
        schedule.scheduleJob(deletionDate.toDate(), function(file){
            fs.unlinkSync(file.path);
            infoWrapper("Deleted file: " + file.filename);
        }.bind(null, req.file));
        if (debug) {
            infoWrapper("Deletion job scheduled for: " + deletionDate.toString());
        } else {
            infoWrapper("Deletion job scheduled.");
        }
    }
    var md5query = req.query.md5;
    var md5uploaded;
    if (md5query) {
        if (md5query.indexOf(' ') !== -1) {
            md5query = md5query.substr(0, md5query.indexOf(' '));  // allows piping from md5sum
        }
        md5uploaded = md5File(req.file.path).toString();
        if (md5uploaded === md5query) {
            infoWrapper("File '" + req.file.originalname + "' uploaded to '" + req.file.path + "', MD5 OK");
            res.header('Dumpster-Checksum', 'OK');
        } else {
            if (debug) {
                infoWrapper("File '" + req.file.originalname + "' uploaded to '" + req.file.path + "', MD5 BAD (" + md5uploaded + " vs " + md5query + ")");
            } else {
                infoWrapper("File '" + req.file.originalname + "' uploaded to '" + req.file.path + "', MD5 BAD");
            }
            res.header('Dumpster-Checksum', 'BAD');
        }
    } else {
        res.header('Dumpster-Checksum', 'NONE');
    }
    res.end(domainUrl + path.basename(req.file.path) + "\n");
}

app.all('/*', function(req, res, next) {
    res.header('X-Powered-By', 'Dumpster');
    next();
});

app.post('/api/upload', authUpload, validateUpload, function(req, res, next){
    upload(req, res, function(err) {
        if (err) {
            res.status(400).send("UPLOAD FAILED - FILE TOO BIG?\n");
        } else {
            next();
        }
    });
}, postUpload);

app.get('/uploads/*', function(req, res) {
    res.sendFile(__dirname + req.url);
});

app.listen(9980, function() {
    infoWrapper("Starting Dumpster on port 9980");
    if (debug) {
        warningWrapper("Debug mode is enabled!");
    }
});

<commit_msg>Codacy review<commit_after>var winston = require('winston');
var multer = require('multer');
var bodyParser = require('body-parser');
var express = require("express");
var app = express();
var path = require('path');
var fs = require('fs');
var md5File = require('md5-file');
var moment = require('moment');
var schedule = require('node-schedule');
var yubikey = require('./lib/yubikey.js');
moment().format();

function infoWrapper(message) {
    var timestamp = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
    winston.log('info', "[" + timestamp + "] %s", message);
}

function warningWrapper(message) {
    var timestamp = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
    winston.log('warn', "[" + timestamp + "] %s", message);
}

function errorWrapper(message) {
    var timestamp = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
    winston.log('error', "[" + timestamp + "] %s", message);
}

/* --- Configuration parsing --- */

var config = JSON.parse(fs.readFileSync('lib/config.js'));

if (Object.prototype.toString.call(config.apiId) === '[object Array]') {
    if (Object.prototype.toString.call(config.apiKey) === '[object Array]') {
        if (config.apiId.length !== config.apiKey.length) {
            if (config.apiId.length === 0 || config.apiKey.length === 0) {
                errorWrapper('Configuration missing: have you edited the defaults in "lib/config.js"?');
            } else {
                errorWrapper('Configuration mismatch: not the same number of API IDs and Keys.');
            }
            process.exit(1);
        }
    } else {
        errorWrapper('Configuration mismatch: API Keys field is not an array.');
        process.exit(1);
    }
} else {
    errorWrapper('Configuration mismatch: API IDs field is not an array.');
    process.exit(1);
}

yubikey.apiId = config.apiId;
yubikey.apiKey = config.apiKey;
var uploadPath = config.uploadFolder || "uploads/",
    domainUrl = (config.domainName || "http://localhost:9980/") + uploadPath,
    maxFileSize = config.maxFileSize || 52428800,
    maxFileExpiration = config.maxFileExpiration || 30,
    debug = config.debug || false;
/* --- End configuration parsing --- */

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

var authUpload = function(req, res, next) {
    if (debug) {
        warningWrapper("Bypassing token validation.");
        next();
        return;
    }
    var token = req.query.token;
    yubikey.verify(token, function(isValid, status) {
        if (isValid) {
            infoWrapper("Valid token received.");
            next();
        } else {
            warningWrapper("Invalid token received! Reason: " + status);
            res.status(401).send("AUTH ERROR - " + status + "\n");
        }
    });
}

var dateOk;
var deletionDate;
var validateUpload = function(req, res, next) {
    dateOk = false;
    deletionDate = undefined;
    var deletionQuery = req.query.del,
        deletionDay,
        deletionMonth,
        deletionYear,
        deletionHour,
        deletionMinute;
    if (deletionQuery) {
        if (/^[0-9]+s$/.test(deletionQuery)) {
            deletionDate = moment().add(deletionQuery.substr(0, deletionQuery.indexOf('s')), 'seconds');
        } else if (/^[0-9]+m$/.test(deletionQuery)) {
            deletionDate = moment().add(deletionQuery.substr(0, deletionQuery.indexOf('m')), 'minutes');
        } else if (/^[0-9]+h$/.test(deletionQuery)) {
            deletionDate = moment().add(deletionQuery.substr(0, deletionQuery.indexOf('h')), 'hours');
        } else if (/^[0-9]+d$/.test(deletionQuery)) {
            deletionDate = moment().add(deletionQuery.substr(0, deletionQuery.indexOf('d')), 'days');
        } else if (/^[0-9]{2}D[0-9]{2}M[0-9]{4}Y$/.test(deletionQuery)) {
            deletionDay = deletionQuery.substr(0, deletionQuery.indexOf('D'));
            deletionMonth = deletionQuery.substr(deletionQuery.indexOf('D') + 1, deletionQuery.indexOf('M'));
            deletionYear = deletionQuery.substr(deletionQuery.indexOf('M') + 1, deletionQuery.indexOf('Y'));
            deletionDate = moment(deletionDay + "-" + deletionMonth + "-" + deletionYear, "DD-MM-YYYY");
        } else if (/^[0-9]{2}D[0-9]{2}M[0-9]{4}Y[0-9]{2}h[0-9]{2}m$/.test(deletionQuery)) {
            deletionDay = deletionQuery.substr(0, deletionQuery.indexOf('D'));
            deletionMonth = deletionQuery.substr(deletionQuery.indexOf('D') + 1, deletionQuery.indexOf('M'));
            deletionYear = deletionQuery.substr(deletionQuery.indexOf('M') + 1, deletionQuery.indexOf('Y'));
            deletionHour = deletionQuery.substr(deletionQuery.indexOf('Y') + 1, deletionQuery.indexOf('h'));
            deletionMinute = deletionQuery.substr(deletionQuery.indexOf('h') + 1, deletionQuery.indexOf('m'));
            deletionDate = moment(deletionDay + "-" + deletionMonth + "-" + deletionYear + " " + deletionHour + ":" + deletionMinute, "DD-MM-YYYY HH:mm");
        } else {
            deletionDate = moment.invalid();
        }
        if (deletionDate.isValid()) {  // TODO: return codes (http://momentjs.com/docs/#/parsing/is-valid/)
            if (deletionDate.isAfter(moment().add(maxFileExpiration, 'days'))) {
                if (debug) {
                    warningWrapper("Too big deletion date received: " + deletionDate.toString() + " - setting to maximum value.");
                } else {
                    warningWrapper("Too big deletion date received, setting to maximum value.");
                }
                deletionDate = moment().add(maxFileExpiration, 'days');
                res.header('Dumpster-Deletion-Date', 'MAX');
            } else {
                if (debug) {
                    infoWrapper("Valid deletion date received: " + deletionDate.toString());
                } else {
                    infoWrapper("Valid deletion date received.");
                }
                res.header('Dumpster-Deletion-Date', 'OK');
            }
            dateOk = true;
            next();
        } else {
            if (debug) {
                warningWrapper("Invalid deletion date received: " + deletionDate.toString());
            } else {
                warningWrapper("Invalid deletion date received!");
            }
            res.status(400).send("BAD DELETION DATE\n");
        }
    } else {
        res.header('Dumpster-Deletion-Date', 'NONE');
        next();
    }
}

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname.replace(/[^0-9A-Za-z\.]+/g, "_").replace(/\.\.+/g, "_"));
  }
})

var upload = multer({ storage: storage,
    limits: {
        fields: 0, // No extra POST fields
        fileSize: maxFileSize
    }
}).single('file');

var postUpload = function(req, res) {
    if (dateOk) {
        schedule.scheduleJob(deletionDate.toDate(), function(file){
            fs.unlinkSync(file.path);
            infoWrapper("Deleted file: " + file.filename);
        }.bind(null, req.file));
        if (debug) {
            infoWrapper("Deletion job scheduled for: " + deletionDate.toString());
        } else {
            infoWrapper("Deletion job scheduled.");
        }
    }
    var md5query = req.query.md5;
    var md5uploaded;
    if (md5query) {
        if (md5query.indexOf(' ') !== -1) {
            md5query = md5query.substr(0, md5query.indexOf(' '));  // allows piping from md5sum
        }
        md5uploaded = md5File(req.file.path).toString();
        if (md5uploaded === md5query) {
            infoWrapper("File '" + req.file.originalname + "' uploaded to '" + req.file.path + "', MD5 OK");
            res.header('Dumpster-Checksum', 'OK');
        } else {
            if (debug) {
                infoWrapper("File '" + req.file.originalname + "' uploaded to '" + req.file.path + "', MD5 BAD (" + md5uploaded + " vs " + md5query + ")");
            } else {
                infoWrapper("File '" + req.file.originalname + "' uploaded to '" + req.file.path + "', MD5 BAD");
            }
            res.header('Dumpster-Checksum', 'BAD');
        }
    } else {
        res.header('Dumpster-Checksum', 'NONE');
    }
    res.end(domainUrl + path.basename(req.file.path) + "\n");
}

app.all('/*', function(req, res, next) {
    res.header('X-Powered-By', 'Dumpster');
    next();
});

app.post('/api/upload', authUpload, validateUpload, function(req, res, next){
    upload(req, res, function(err) {
        if (err) {
            res.status(400).send("UPLOAD FAILED - FILE TOO BIG?\n");
        } else {
            next();
        }
    });
}, postUpload);

app.get('/uploads/*', function(req, res) {
    res.sendFile(__dirname + req.url);
});

app.listen(9980, function() {
    infoWrapper("Starting Dumpster on port 9980");
    if (debug) {
        warningWrapper("Debug mode is enabled!");
    }
});

<|endoftext|>


<commit_before>#!/usr/bin/env node

const jsf = require('../dist/main.umd.js');

// FIXME: load faker/chance on startup?

const sample = process.argv.slice(2)[0];

// FIXME: setup argv....
const argv = require('wargs')(process.argv.slice(2), {
  boolean: 'O',
  alias: {
    'always-fake-optionals': 'O',
  },
});

const { inspect } = require('util');
const { Transform } = require('stream');
const { readFileSync } = require('fs');

const pretty = process.argv.indexOf('--pretty') !== -1;
const noColor = process.argv.indexOf('--no-color') !== -1;

jsf.option({
  alwaysFakeOptionals: true,
});

function generate(schema, callback) {
  jsf.resolve(JSON.parse(schema)).then(result => {
    let sample;

    if (pretty) {
      sample = inspect(result, { colors: !noColor, depth: Infinity });
    } else {
      sample = JSON.stringify(result);
    }

    callback(null, `${sample}\n`);
  });
}

process.stdin.pipe(new Transform({
  transform(entry, enc, callback) {
    generate(Buffer.from(entry, enc).toString(), callback);
  }
})).pipe(process.stdout);
<commit_msg>Setup argv for CLI<commit_after>#!/usr/bin/env node

const jsf = require('../dist/main.umd.js');

// FIXME: load faker/chance on startup?

const sample = process.argv.slice(2)[0];

// FIXME: validate types on given input....
const argv = require('wargs')(process.argv.slice(2), {
  boolean: 'DXMTFOxedrJUSE',
  alias: {
    D: 'defaultInvalidTypeProduct',
    X: 'defaultRandExpMax',

    p: 'ignoreProperties',
    M: 'ignoreMissingRefs',
    T: 'failOnInvalidTypes',
    F: 'failOnInvalidFormat',

    O: 'alwaysFakeOptionals',
    o: 'optionalsProbability',
    x: 'fixedProbabilities',
    e: 'useExamplesValue',
    d: 'useDefaultValue',
    R: 'requiredOnly',
    r: 'random',

    i: 'minItems',
    I: 'maxItems',
    l: 'minLength',
    L: 'maxLength',

    J: 'resolveJsonPath',
    U: 'reuseProperties',
    S: 'fillProperties',
    E: 'replaceEmptyByRandomValue',
  },
});

if (typeof argv.flags.random === 'string') {
  argv.flags.random = () => parseFloat(argv.flags.random);
}

if (typeof argv.flags.ignoreProperties === 'string') {
  argv.flags.ignoreProperties = [argv.flags.ignoreProperties];
}

jsf.option(argv.flags);

const { inspect } = require('util');
const { Transform } = require('stream');
const { readFileSync } = require('fs');

const pretty = process.argv.indexOf('--pretty') !== -1;
const noColor = process.argv.indexOf('--no-color') !== -1;

jsf.option({
  alwaysFakeOptionals: true,
});

function generate(schema, callback) {
  jsf.resolve(JSON.parse(schema)).then(result => {
    let sample;

    if (pretty) {
      sample = inspect(result, { colors: !noColor, depth: Infinity });
    } else {
      sample = JSON.stringify(result);
    }

    callback(null, `${sample}\n`);
  });
}

process.stdin.pipe(new Transform({
  transform(entry, enc, callback) {
    generate(Buffer.from(entry, enc).toString(), callback);
  }
})).pipe(process.stdout);
<|endoftext|>


<commit_before>'use strict';

var express = require( 'express' );
var morgan = require( 'morgan' );
var env = require( 'nconf' ).argv()
                            .env()
                            .file( { file: 'config.json' } );
var sass = require( 'node-sass' );
var fs = require( 'fs' );

// setup server
var app = express();

// health check
var healthcheck = {
  version: require('./package').version,
  http: 'okay'
};

// pending processes
var pending = [];

// get some debug ouptut
if( env.get( 'debug' ) || env.get( 'DEBUG' ) ) {
  app.use( morgan( 'dev' ) );
}

// healthcheck info public
app.get( [ '/', 'healthcheck' ], function( req, res ) {
	res.jsonp( healthcheck );
});

// function to help deal w/ race conditions
function waitOnTemp( hash, done ) {
	if( pending.indexOf( hash ) > -1 ) {
		setTimeout( function(){
			waitOnTemp( hash, done );
		}, 100 );
		return;
	}

	// file written, read it and send it
	var result = fs.readFileSync( hash + '.css', 'utf-8' );
	done( result );
}

// get sass variables from url
app.post( '/compile', function( req, res ) {
	var result = ''; // this will become the compiled css.

	// check that the request came from a trusted source ( not foolproof )
	if( env.get( 'SHARED_SECRET' ) !== req.param( 'secret' ) ) {
		res.status( 400 ).jsonp({
			errors: [{
				message: 'Request requires authentication.',
				code: 400
			}]
		});
	}

	// deal w/ race conditions
	if( pending.indexOf( req.param( 'hash' ) ) > -1 ) {
		// wait for temp file w/ css to exist
		return waitOnTemp( req.param( 'hash' ), function( result ) {
			res.send( result );
		});
	}

	// set hash as pending
	pending.push( req.param( 'hash' ) );

	// magical shite here

	/*
		- get default variables for the theme
		- generate overrides for this hash
		- generate import for rest of theme
		- write a temp-file to compile
		- return the compiled output to user ( hint: use result )
	 */

	// send back the css
	res.send( result );

	// clear hash from pending queue
	var pendingIdx = pending.indexOf( req.param( 'hash' ) );
	pending.splice( pendingIdx, 1 );
});

// spin up the server
var server = app.listen( env.get( 'PORT' ) || 5000, function() {
	console.log( 'Listening on port %d', server.address().port );
});
<commit_msg>tweak<commit_after>'use strict';

var express = require( 'express' );
var morgan = require( 'morgan' );
var env = require( 'nconf' ).argv()
                            .env()
                            .file( { file: 'config.json' } );
var sass = require( 'node-sass' );
var fs = require( 'fs' );

// setup server
var app = express();

// health check
var healthcheck = {
  version: require('./package').version,
  http: 'okay'
};

// pending processes
var pending = [];

// get some debug ouptut
if( env.get( 'debug' ) || env.get( 'DEBUG' ) ) {
  app.use( morgan( 'dev' ) );
}

// healthcheck info public
app.get( [ '/', 'healthcheck' ], function( req, res ) {
	res.jsonp( healthcheck );
});

// function to help deal w/ race conditions
function waitOnTemp( hash, done ) {
	if( pending.indexOf( hash ) > -1 ) {
		setTimeout( function(){
			waitOnTemp( hash, done );
		}, 100 );
		return;
	}

	// file written, read it and send it
	var result = fs.readFileSync( hash + '.css', 'utf-8' );
	done( result );
}

// get sass variables from url
app.post( '/compile', function( req, res ) {
	var result = ''; // this will become the compiled css.

	// check that the request came from a trusted source ( not foolproof )
	if( env.get( 'SHARED_SECRET' ) !== req.param( 'secret' ) ) {
		res.status( 400 ).jsonp({
			errors: [{
				message: 'Request requires authentication.',
				code: 400
			}]
		});
	}

	// deal w/ race conditions
	if( pending.indexOf( req.param( 'hash' ) ) > -1 ) {
		// wait for temp file w/ css to exist
		return waitOnTemp( req.param( 'hash' ), function( result ) {
			res.send( result );
		});
	}

	// set hash as pending
	pending.push( req.param( 'hash' ) );

	// magical shite here

	/*
		- get default variables for the theme
		- generate overrides for this hash
		- generate import for rest of theme
		- write a temp-file to compile ( {hash}.css )
		- return the compiled output to user ( hint: use result )
	 */

	// send back the css
	res.send( result );

	// clear hash from pending queue
	var pendingIdx = pending.indexOf( req.param( 'hash' ) );
	pending.splice( pendingIdx, 1 );
});

// spin up the server
var server = app.listen( env.get( 'PORT' ) || 5000, function() {
	console.log( 'Listening on port %d', server.address().port );
});
<|endoftext|>


<commit_before>var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
var twilio = require('twilio');
const path = require('path');
const express = require('express');
const app = express();

const indexPath = path.join(__dirname, '/index.html');
const publicPath = express.static(path.join(__dirname, '../static'));
const port = (process.env.PORT || 3000);

app.use('/public', publicPath);

app.get('/', function (req, res) {
  res.sendFile(indexPath);
});

require('dotenv').config();

const client = new twilio.RestClient('ACccfad5c5365b389034ce961ec2c3c33b', process.env.TwilioAPIKEY);
// client.sendSms({
//     to:'+18565626606',
//     from:'+17573245262',
//     body:'ahoy hoy! Testing Twilio and node.js'
// }, function(error, message) {
//     if (!error) {
//         console.log('Success! The SID for this SMS message is:');
//         console.log(message.sid);
//         console.log('Message sent on:');
//         console.log(message.dateCreated);
//     } else {
//         console.log('Oops! There was an error.');
//     }
// });
if (process.env.NODE_ENV !== 'production') {
  // const webpack = require('webpack')
  // const webpackDevMiddleware = require('webpack-dev-middleware')
  // const webpackHotMiddleware = require('webpack-hot-middleware')
  // const config = require('../webpack.dev.config.js')
  // const compiler = webpack(config)

  // app.use(webpackHotMiddleware(compiler))
  // app.use(webpackDevMiddleware(compiler, {
  //   noInfo: true,
  //   publicPath: config.output.publicPath
  // }))

  new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    historyApiFallback: true
  }).listen(3000, 'localhost', function (err, result) {
    if (err) {
      return console.log(err);
    }
    console.log('Listening at http://localhost:3000/');
  });
} else {
  app.listen(port);
  console.log(`Listening at http://localhost:${port}`);
}

// new WebpackDevServer(webpack(config), {
//   publicPath: config.output.publicPath,
//   hot: true,
//   historyApiFallback: true
// }).listen(3000, 'localhost', function (err, result) {
//   if (err) {
//     return console.log(err);
//   }
//   console.log('Listening at http://localhost:3000/');
// });
<commit_msg>remove unuse code<commit_after>var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
var twilio = require('twilio');
const path = require('path');
const express = require('express');
const app = express();
require('dotenv').config();

const indexPath = path.join(__dirname, '/index.html');
const publicPath = express.static(path.join(__dirname, '../static'));
const port = (process.env.PORT || 3000);

app.use('/public', publicPath);

app.get('/', function (req, res) {
  res.sendFile(indexPath);
});

const client = new twilio.RestClient('ACccfad5c5365b389034ce961ec2c3c33b', process.env.TwilioAPIKEY);
// client.sendSms({
//     to:'+18565626606',
//     from:'+17573245262',
//     body:'ahoy hoy! Testing Twilio and node.js'
// }, function(error, message) {
//     if (!error) {
//         console.log('Success! The SID for this SMS message is:');
//         console.log(message.sid);
//         console.log('Message sent on:');
//         console.log(message.dateCreated);
//     } else {
//         console.log('Oops! There was an error.');
//     }
// });

if (process.env.NODE_ENV !== 'production') {
  new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    historyApiFallback: true
  }).listen(3000, 'localhost', function (err, result) {
    if (err) {
      return console.log(err);
    }
    console.log('Listening at http://localhost:3000/');
  });
} else {
  app.listen(port);
  console.log(`Listening at http://localhost:${port}`);
}
<|endoftext|>


<commit_before>require('app-module-path').addPath('./shared');

const config = require('browserify-stockpiler')({
	envPrefix: 'APP',
});

const db = require('./server/db');
const app = require('./server/app');

const PORT = config.server.port;
db.ready.then(() => {
	app.listen(PORT, () => {
		console.info(`Listening on ${PORT}.`);
	});
});
<commit_msg>Fixing port specification.<commit_after>require('app-module-path').addPath('./shared');

const config = require('browserify-stockpiler')({
	envPrefix: 'APP',
});

const db = require('./server/db');
const app = require('./server/app');

const PORT = process.env.PORT || config.server.port;
db.ready.then(() => {
	app.listen(PORT, () => {
		console.info(`Listening on ${PORT}.`);
	});
});
<|endoftext|>


<commit_before>'use strict';
/**
 * Module dependencies.
 */
var init = require('./config/init')(),
	config = require('./config/config'),
	mongoose = require('mongoose'),
	chalk = require('chalk');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

// Bootstrap db connection
var db = mongoose.connect(config.db, function(err) {
	if (err) {
		console.error(chalk.red('Could not connect to MongoDB!'));
		console.log(chalk.red(err));
	}
});

// Init the express application
var app = require('./config/express')(db);

// Bootstrap passport config
require('./config/passport')();

// Start the app by listening on <port>
app.listen(config.port);

// Expose app
exports = module.exports = app;

// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);<commit_msg>make it better<commit_after>'use strict';
/**
 * Module dependencies.
 */
var init = require('./config/init')(),
	config = require('./config/config'),
	mongoose = require('mongoose'),
	chalk = require('chalk');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

// Bootstrap db connection
var db = mongoose.connect(config.db, function(err) {
	if (err) {
		console.error(chalk.red('Could not connect to MongoDB!'));
		console.log(chalk.red(err));
	}
});

// Init the express application
var app = require('./config/express')(db);

// Bootstrap passport config
require('./config/passport')();

// Start the app by listening on <port>
app.listen(config.port);

// Expose app
module.exports = app;

// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);
<|endoftext|>