<commit_before>var base64 = require('base64-stream');
var express = require('express');
var fs = require('fs');
var gm = require('gm');
var passport = require('passport');
var request = require('request');
var rollbar = require('rollbar');
var tmp = require('tmp');
var validator = require('validator');
var InstagramStrategy = require('passport-instagram').Strategy;

var config = require('./config');

var INSTAGRAM_CLIENT_ID = config.instagram.clientID;
var INSTAGRAM_CLIENT_SECRET = config.instagram.clientSecret;
const GEOMETRY_FORMAT = '1000x1000+0+0';

const Cache = require('./cache');
const Timer = require('./timer');
const cache = new Cache(new Timer(100000));

if (!INSTAGRAM_CLIENT_ID || !INSTAGRAM_CLIENT_SECRET) {
  console.log('Instagram client ID and secret must be specified in config');
  process.exit(1);
}

// rollbar.init(config.rollbar.serversideToken);

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});

passport.use(new InstagramStrategy({
    clientID: INSTAGRAM_CLIENT_ID,
    clientSecret: INSTAGRAM_CLIENT_SECRET,
    callbackURL: config.instagram.callbackUrl
  },
  function(accessToken, refreshToken, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      // To keep the example simple, the user's Instagram profile is returned to
      // represent the logged-in user.  In a typical application, you would want
      // to associate the Instagram account with a user record in your database,
      // and return that user instead.
      return done(null, {profile: profile, accessToken: accessToken});
    });
  }
));

var app = express();
app.use(require('cookie-parser')());
app.use(require('body-parser').json());

/* TODO:
* See the express-session docs and further research proper settings
* for resave and saveUninitialized
*/
app.use(require('express-session')({
  cookie: {
    httpOnly: false
  },
  resave: false,                        // Set to squelch noise
  saveUninitialized: false,             // Set to squelch noise
  secret: config.express.sessionSecret
}));
// Initialize Passport!  Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());

app.get('/api', function(req, res){
  console.log('User is', req.user);
  res.send(`Hello ${req.user.profile.displayName}`);
});

app.get('/api/account', ensureAuthenticated, function(req, res){
  request(req.user._json.data.profile_picture).pipe(res);
});

app.get('/api/posts', ensureAuthenticated, function(req, res) {
  res.setHeader('Content-Type', 'application/json');
  request.get(`https://api.instagram.com/v1/users/self/media/recent/?access_token=${req.user.accessToken}`).pipe(res);
});

app.get('/login', function(req, res){
  res.render('login', { user: req.user });
});

app.post('/api/montage', function(req, res, next) {
  if (Array.isArray(req.body) &&
        req.body.every(i => validator.isURL(i)) &&
        req.body.length >= 2) {
    return next();
  } else {
    res.sendStatus(400);
  }
}, function(req, res) {
  const photos = req.body;
  const photoStreams = photos.map((item) => {
    const cacheItem = cache.get(item);
    if (cacheItem) {
      return Promise.resolve(cacheItem);
    } else {
      return new Promise((resolve, reject) => {
        const tmpName = tmp.tmpNameSync();
        request(item).on('end', (response) => {
            cache.set(item, tmpName);
            return resolve(tmpName);
          })
          .pipe(fs.createWriteStream(tmpName));
      });
    }
  });

  Promise.all(photoStreams).then(photoStreams => {
    var tmpMontageName = `${tmp.tmpNameSync()}.png`;
    photoStreams.reverse();
    var callChain = gm(photoStreams[0])
    for (var i = 1; i < photoStreams.length; i++) {
      callChain = callChain.montage(photoStreams[i]);
    }
    callChain.geometry(GEOMETRY_FORMAT)
    .tile('10x10')
    .write(tmpMontageName, (err) => {
      if (err) {
        console.log(`Error generating image: ${err}`);
        return res.status(500).send(err);
      }
      res.setHeader('Content-Type', 'image/png');
      fs.createReadStream(tmpMontageName).pipe(base64.encode()).pipe(res);
    });
  });
});

// GET /api/auth/instagram
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in Instagram authentication will involve
//   redirecting the user to instagram.com.  After authorization, Instagram
//   will redirect the user back to this application at /api/auth/instagram/callback
app.get('/api/auth/instagram',
  passport.authenticate('instagram'),
  function(req, res){
    // The request will be redirected to Instagram for authentication, so this
    // function will not be called.
  });

// GET /api/auth/instagram/callback
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
app.get('/api/auth/instagram/callback',
  passport.authenticate('instagram', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

app.get('/api/logout', function(req, res){
  req.logout();
    cookie = req.cookies;
    for (var prop in cookie) {
        if (!cookie.hasOwnProperty(prop)) {
            continue;
        }
        res.cookie(prop, '', {expires: new Date(0)});
    }
    res.redirect('/');
});

// Simple route middleware to ensure user is authenticated.
//   Use this route middleware on any resource that needs to be protected.  If
//   the request is authenticated (typically via a persistent login session),
//   the request will proceed.  Otherwise, the user will be redirected to the
//   login page.
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login')
}

// Rollbar error handler: should occur after other handlers
function errorHandler (err, req, res, next) {
  console.log('Reporting error', err);
  console.log(err.stack);
  // rollbar.reportMessage(JSON.stringify(err));
  next();
}
app.use(errorHandler);

app.listen(8000, function () {
  console.log('Example app listening on port 8000!')
});
<commit_msg>Adding very minimal request logging<commit_after>var base64 = require('base64-stream');
var express = require('express');
var fs = require('fs');
var gm = require('gm');
var passport = require('passport');
var request = require('request');
var rollbar = require('rollbar');
var tmp = require('tmp');
var validator = require('validator');
var InstagramStrategy = require('passport-instagram').Strategy;

var config = require('./config');

var INSTAGRAM_CLIENT_ID = config.instagram.clientID;
var INSTAGRAM_CLIENT_SECRET = config.instagram.clientSecret;
const GEOMETRY_FORMAT = '1000x1000+0+0';

const Cache = require('./cache');
const Timer = require('./timer');
const cache = new Cache(new Timer(100000));

if (!INSTAGRAM_CLIENT_ID || !INSTAGRAM_CLIENT_SECRET) {
  console.log('Instagram client ID and secret must be specified in config');
  process.exit(1);
}

// rollbar.init(config.rollbar.serversideToken);

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});

passport.use(new InstagramStrategy({
    clientID: INSTAGRAM_CLIENT_ID,
    clientSecret: INSTAGRAM_CLIENT_SECRET,
    callbackURL: config.instagram.callbackUrl
  },
  function(accessToken, refreshToken, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      // To keep the example simple, the user's Instagram profile is returned to
      // represent the logged-in user.  In a typical application, you would want
      // to associate the Instagram account with a user record in your database,
      // and return that user instead.
      return done(null, {profile: profile, accessToken: accessToken});
    });
  }
));

var app = express();
app.use(require('cookie-parser')());
app.use(require('body-parser').json());

/* TODO:
* See the express-session docs and further research proper settings
* for resave and saveUninitialized
*/
app.use(require('express-session')({
  cookie: {
    httpOnly: false
  },
  resave: false,                        // Set to squelch noise
  saveUninitialized: false,             // Set to squelch noise
  secret: config.express.sessionSecret
}));
// Initialize Passport!  Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
  console.log(`${req.method} - ${req.url}`);
  next();
});

app.get('/api', function(req, res){
  console.log('User is', req.user);
  res.send(`Hello ${req.user.profile.displayName}`);
});

app.get('/api/account', ensureAuthenticated, function(req, res){
  request(req.user._json.data.profile_picture).pipe(res);
});

app.get('/api/posts', ensureAuthenticated, function(req, res) {
  res.setHeader('Content-Type', 'application/json');
  request.get(`https://api.instagram.com/v1/users/self/media/recent/?access_token=${req.user.accessToken}`).pipe(res);
});

app.get('/login', function(req, res){
  res.render('login', { user: req.user });
});

app.post('/api/montage', function(req, res, next) {
  if (Array.isArray(req.body) &&
        req.body.every(i => validator.isURL(i)) &&
        req.body.length >= 2) {
    return next();
  } else {
    res.sendStatus(400);
  }
}, function(req, res) {
  const photos = req.body;
  const photoStreams = photos.map((item) => {
    const cacheItem = cache.get(item);
    if (cacheItem) {
      return Promise.resolve(cacheItem);
    } else {
      return new Promise((resolve, reject) => {
        const tmpName = tmp.tmpNameSync();
        request(item).on('end', (response) => {
            cache.set(item, tmpName);
            return resolve(tmpName);
          })
          .pipe(fs.createWriteStream(tmpName));
      });
    }
  });

  Promise.all(photoStreams).then(photoStreams => {
    var tmpMontageName = `${tmp.tmpNameSync()}.png`;
    photoStreams.reverse();
    var callChain = gm(photoStreams[0])
    for (var i = 1; i < photoStreams.length; i++) {
      callChain = callChain.montage(photoStreams[i]);
    }
    callChain.geometry(GEOMETRY_FORMAT)
    .tile('10x10')
    .write(tmpMontageName, (err) => {
      if (err) {
        console.log(`Error generating image: ${err}`);
        return res.status(500).send(err);
      }
      res.setHeader('Content-Type', 'image/png');
      fs.createReadStream(tmpMontageName).pipe(base64.encode()).pipe(res);
    });
  });
});

// GET /api/auth/instagram
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in Instagram authentication will involve
//   redirecting the user to instagram.com.  After authorization, Instagram
//   will redirect the user back to this application at /api/auth/instagram/callback
app.get('/api/auth/instagram',
  passport.authenticate('instagram'),
  function(req, res){
    // The request will be redirected to Instagram for authentication, so this
    // function will not be called.
  });

// GET /api/auth/instagram/callback
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
app.get('/api/auth/instagram/callback',
  passport.authenticate('instagram', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

app.get('/api/logout', function(req, res){
  req.logout();
    cookie = req.cookies;
    for (var prop in cookie) {
        if (!cookie.hasOwnProperty(prop)) {
            continue;
        }
        res.cookie(prop, '', {expires: new Date(0)});
    }
    res.redirect('/');
});

// Simple route middleware to ensure user is authenticated.
//   Use this route middleware on any resource that needs to be protected.  If
//   the request is authenticated (typically via a persistent login session),
//   the request will proceed.  Otherwise, the user will be redirected to the
//   login page.
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login')
}

// Rollbar error handler: should occur after other handlers
function errorHandler (err, req, res, next) {
  console.log('Reporting error', err);
  console.log(err.stack);
  // rollbar.reportMessage(JSON.stringify(err));
  next();
}
app.use(errorHandler);

app.listen(8000, function () {
  console.log('Example app listening on port 8000!')
});
<|endoftext|>


<commit_before>var http = require('http');
var fs = require('fs');
var socketio = require('socket.io');

var port = process.env.PORT || process.env.NODE_PORT || 3000;

// Read the client html file into memory
// __dirname in node is the current directory
// in this case the same folder as the server js file
var index = fs.readFileSync(__dirname + '/../client/client.html');

function onRequest(request, response){
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write(index);
  response.end();
}

var app = http.createServer(onRequest).listen(port);

console.log("Listening on 127.0.0.1:" + port);

//pass in the http server into socketio and grab the websocket server as io
var io = socketio(app);
//object to hold all of our connected users
var users = { };

// Delegate functions
var onJoined = function(socket) {
  socket.on("join", function(data){

    var joinMsg = {
      name:'server',
      msg: 'There are ' + Object.keys(users).length + ' users online.'
    };

    socket.emit('msg', joinMsg);
    socket.name = data.name;

    socket.join('room1');
    // updates the count of active users
    users[data.name] = true;

    socket.broadcast.to('room1').emit('msg',{
      name:'server',
      msg: data.name + ' has joined the room.'
    });
    socket.emit('msg', {name:'server',msg:'You have joined the room'});
    console.log(users);
  });

};

var onMsg = function(socket) {
  socket.on('msgToServer',function(data){
    console.log(data);
    console.log(data.msg[0]);
    if(data.msg[0] === '/'){
      var command = data.msg.split(" ");
      console.log(command);
      var message = "";
      var err = false;

      switch(command[0]){
        case '/r':
        case '/R':
        case '/roll':
        case '/Roll':
          message = "You rolled " + command[1] + " " + command[2] + "-sided dice.";
          for(var i = 0; i< parseInt(command[1]); i++){
            var result = (1 + Math.floor(Math.random()*parseInt(command[2])));
            message += result + " ";
          }
          break;
        case '/n':
        case '/N':
        case '/name':
        case '/Name':
            var newName = command [1];
            var oldName = socket.name;
            message = oldName + " changes their name to " + newName + ".";
            socket.name = newName;
          break;
        case '/m':
        case '/M':
        case '/me':
        case '/Me':
          message += socket.name;
          for(var i =1;i<command.length;i++){
            message += command[i];
          }
          break;
        default:
          message = "That is an invalid command";
          err = true;
      }
      if(err){
        socket.emit('msg', {name: 'server', msg: message});
      }else{
        console.log(message);
        io.sockets.in('room1').emit('msg',{
          name:socket.name,
          msg:message
        });
      }

    }else{
      io.sockets.in('room1').emit('msg',{
        name:socket.name,
        msg:socket.name + ":" +data.msg
      });
    }
  });
};

var onDisconnect = function(socket) {
  socket.on("disconnect", function(data){
    console.log("disconnected\n",socket.name);
    delete users[socket.name];
  });
};

io.sockets.on("connection", function(socket) {

 onJoined(socket);
 onMsg(socket);
 onDisconnect(socket);

});

console.log("Websocket server started.");
<commit_msg>Appeased jshint.<commit_after>var http = require('http');
var fs = require('fs');
var socketio = require('socket.io');

var port = process.env.PORT || process.env.NODE_PORT || 3000;

// Read the client html file into memory
// __dirname in node is the current directory
// in this case the same folder as the server js file
var index = fs.readFileSync(__dirname + '/../client/client.html');

function onRequest(request, response){
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write(index);
  response.end();
}

var app = http.createServer(onRequest).listen(port);

console.log("Listening on 127.0.0.1:" + port);

//pass in the http server into socketio and grab the websocket server as io
var io = socketio(app);
//object to hold all of our connected users
var users = { };

// Delegate functions
var onJoined = function(socket) {
  socket.on("join", function(data){

    var joinMsg = {
      name:'server',
      msg: 'There are ' + Object.keys(users).length + ' users online.'
    };

    socket.emit('msg', joinMsg);
    socket.name = data.name;

    socket.join('room1');
    // updates the count of active users
    users[data.name] = true;

    socket.broadcast.to('room1').emit('msg',{
      name:'server',
      msg: data.name + ' has joined the room.'
    });
    socket.emit('msg', {name:'server',msg:'You have joined the room'});
    console.log(users);
  });

};

var onMsg = function(socket) {
  socket.on('msgToServer',function(data){
    console.log(data);
    console.log(data.msg[0]);
    if(data.msg[0] === '/'){
      var command = data.msg.split(" ");
      console.log(command);
      var message = "";
      var err = false;

      switch(command[0]){
        case '/r':
        case '/R':
        case '/roll':
        case '/Roll':
          message = "You rolled " + command[1] + " " + command[2] + "-sided dice.";
          for(var i = 0; i< parseInt(command[1]); i++){
            var result = (1 + Math.floor(Math.random()*parseInt(command[2])));
            message += result + " ";
          }
          break;
        case '/n':
        case '/N':
        case '/name':
        case '/Name':
            var newName = command [1];
            var oldName = socket.name;
            message = oldName + " changes their name to " + newName + ".";
            socket.name = newName;
          break;
        case '/m':
        case '/M':
        case '/me':
        case '/Me':
          message += socket.name;
          for(var j =1;j<command.length;j++){
            message += command[j];
          }
          break;
        default:
          message = "That is an invalid command";
          err = true;
      }
      if(err){
        socket.emit('msg', {name: 'server', msg: message});
      }else{
        console.log(message);
        io.sockets.in('room1').emit('msg',{
          name:socket.name,
          msg:message
        });
      }

    }else{
      io.sockets.in('room1').emit('msg',{
        name:socket.name,
        msg:socket.name + ":" +data.msg
      });
    }
  });
};

var onDisconnect = function(socket) {
  socket.on("disconnect", function(data){
    console.log("disconnected\n",socket.name);
    delete users[socket.name];
  });
};

io.sockets.on("connection", function(socket) {

 onJoined(socket);
 onMsg(socket);
 onDisconnect(socket);

});

console.log("Websocket server started.");
<|endoftext|>


<commit_before>/* eslint consistent-return: 0 */
const express = require('express')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const storage = require('node-persist')
const { getFileContents } = require('./utils')
const { HELP_MESSAGE, EMPTY_REQUEST, ERROR_MESSAGE, BS_URL_MATCH, UNRECOGNIZED_REQUEST } = require('./constants')

const { SLACK_VERIFY_TOKEN, PORT } = process.env
if (!SLACK_VERIFY_TOKEN) {
    console.error('SLACK_VERIFY_TOKEN is required')
    process.exit(1)
}
if (!PORT) {
    console.error('PORT is required')
    process.exit(1)
}

const app = express()
app.use(morgan('dev'))

app.route('/code')
    .get((req, res) => {
        res.sendStatus(200)
    })
    .post(bodyParser.urlencoded({ extended: true }), (req, res) => {
        if (req.body.token !== SLACK_VERIFY_TOKEN) {
            return res.sendStatus(401)
        }

        const { text, response_url, team_id } = req.body

        // Handle empty request
        if (!text) {
            return res.json({
                response_type: 'ephemeral',
                text: EMPTY_REQUEST
            })
        }

        // Handle any help requests
        if (text === 'help') {
            return res.json({
                response_type: 'ephemeral',
                text: HELP_MESSAGE
            })
        }

        if (text.indexOf(BS_URL_MATCH) > -1) {
            // Iterate through storage data
            storage.forEach((key, value) => {

                // Match team ID in storage from request
                if (value.slackTeamID === team_id) {

                    // Get file contents from Beanstalk
                    getFileContents(text, {
                        username: value.bsUsername,
                        token: value.bsAuthToken
                    }, (err, content) => {
                        if (err) {
                            return res.json({
                                response_type: 'ephemeral',
                                text: ERROR_MESSAGE
                            })
                        }

                        // TODO: If this request takes more than 3000ms slack will not post our response. Instead we should probably return an initial message to the user("Looking up your file"). Then after send the file as an incoming webhook using response_url.
                        return res.json(
                            Object.assign({
                                response_type: 'in_channel'
                            }, content)
                        )
                    })
                }
            })
        } else {
            return res.json({
                response_type: 'ephemeral',
                text: UNRECOGNIZED_REQUEST
            })
        }

    })

app.listen(PORT, (err) => {
    if (err) {
        return console.error('Error starting server: ', err)
    }

    return console.log('Server successfully started on port %s', PORT)
})
<commit_msg>More eslint fixes<commit_after>/* eslint consistent-return: 0 */
const express = require('express')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const storage = require('node-persist')
const { getFileContents } = require('./utils')
const {
    HELP_MESSAGE,
    EMPTY_REQUEST,
    ERROR_MESSAGE,
    BS_URL_MATCH,
    UNRECOGNIZED_REQUEST
} = require('./constants')

const { SLACK_VERIFY_TOKEN, PORT } = process.env
if (!SLACK_VERIFY_TOKEN) {
    console.error('SLACK_VERIFY_TOKEN is required')
    process.exit(1)
}
if (!PORT) {
    console.error('PORT is required')
    process.exit(1)
}

const app = express()
app.use(morgan('dev'))

app.route('/code')
    .get((req, res) => {
        res.sendStatus(200)
    })
    .post(bodyParser.urlencoded({ extended: true }), (req, res) => {
        if (req.body.token !== SLACK_VERIFY_TOKEN) {
            return res.sendStatus(401)
        }

        const { text, team_id } = req.body

        // Handle empty request
        if (!text) {
            return res.json({
                response_type: 'ephemeral',
                text: EMPTY_REQUEST
            })
        }

        // Handle any help requests
        if (text === 'help') {
            return res.json({
                response_type: 'ephemeral',
                text: HELP_MESSAGE
            })
        }

        if (text.indexOf(BS_URL_MATCH) > -1) {
            // Iterate through storage data
            storage.forEach((key, value) => {

                // Match team ID in storage from request
                if (value.slackTeamID === team_id) { // eslint-disable-line

                    // Get file contents from Beanstalk
                    getFileContents(text, {
                        username: value.bsUsername,
                        token: value.bsAuthToken
                    }, (err, content) => {
                        if (err) {
                            return res.json({
                                response_type: 'ephemeral',
                                text: ERROR_MESSAGE
                            })
                        }

                        /*
                        * TODO: If this request takes more than 3000ms slack will not post our
                        * response. Instead we should probably return an initial message to the
                        * user("Looking up your file"). Then after send the file as an incoming
                        * webhook using response_url.
                        * */
                        return res.json(
                            Object.assign({
                                response_type: 'in_channel'
                            }, content)
                        )
                    })
                }
            })
        } else {
            return res.json({
                response_type: 'ephemeral',
                text: UNRECOGNIZED_REQUEST
            })
        }

    })

app.listen(PORT, (err) => {
    if (err) {
        return console.error('Error starting server: ', err)
    }

    return console.log('Server successfully started on port %s', PORT)
})
<|endoftext|>


<commit_before>/*
 * grunt-includes
 * https://github.com/vanetix/grunt-includes
 *
 * Copyright (c) 2013 Matt McFarland
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {

  /**
   * Dependencies
   */

  var path = require('path');

  /**
   * Regex for parsing includes
   */

  var defaultRegexp = /^(\s*)include\s+"(\S+)"\s*$/;

  /**
   * Format of comments per file extension
   */

  var commentStyle = {
    js: "/* %s */",
    css: "/* %s */",
    html: "<!-- %s -->",
    generic: "/* %s */"
  };

  /**
   * Core `grunt-includes` task
   * Iterates over all source files and calls `recurse(path)` on each
   */

  grunt.registerMultiTask('includes', 'Include other files within files.', function() {
    var opts = this.options({
      debug: false,
      duplicates: true,
      includeRegexp: defaultRegexp
    });

    this.files.forEach(function(f) {
      var cwd = f.cwd;
      var src = f.src.filter(function(p) {
        p = cwd ? path.join(cwd, p) : p;
        if(grunt.file.exists(p)) {
          return true;
        } else {
          grunt.log.warn('Source file "' + p + '" not found.');
          return false;
        }
      });

      if(src.length > 1 && grunt.file.isFile(f.dest)) {
        grunt.log.warn('Source file cannot be more than one when dest is a file.');
      }

      var flatten = f.flatten;

      src.forEach(function(p) {
        var save_name = flatten ? path.basename(p) : p;
        var dest_file = isfile ? f.dest : path.join(f.dest, save_name);

        p = cwd ? path.join(cwd, p) : p;

        if (opts.comment) {
          opts.comment = commentStyle[fileType(p)] || commentStyle['generic'];
        }
        grunt.file.write(dest_file, recurse(p, opts));
        grunt.log.oklns('Saved ' + dest_file);
      });

    });
  });

  /**
   * Is file with path `p` an html file?
   *
   * @param {String} p
   * @return {Boolean}
   */

  function fileType(p) {
    return path.extname(p).slice(1);
  }

  /**
   * Helper for `includes` builds all includes for `p`
   *
   * @param {String} p
   * @return {String}
   */

  function recurse(p, opts, included) {
    if(!grunt.file.isFile(p)) {
      grunt.log.warn('Included file "' + p + '" not found.');
      return 'Error including "' + p + '".';
    }

    included = included || {};

    var comment = opts.comment;

    if(opts.duplicates && (p in included)) {
      var msg = 'File ' + p + ' included before, skip';
      grunt.log.debug(msg);
      return opts.debug && comment.replace('%s', msg) || '';
    }

    included[p] = 1;

    var src = grunt.file.read(p).split(grunt.util.linefeed);
    var compiled = src.map(function(line) {
      var match = line.match(opts.includeRegexp);

      if(match) {
        var f = path.join(path.dirname(p), match[opts.pos]);
        line = recurse(f, opts, included);
        if (opts.debug) {
          var msg_begin = 'File: ' + f;
          var msg_end = 'EOF: ' + f;
          line = comment.replace('%s', msg_begin) + '\n' + line + '\n';
          line = line + comment.replace('%s', msg_end);
        }
      }
      return line;
    });

    return  compiled.join(grunt.util.linefeed);
  }

};
<commit_msg>fix variable names, use camelcase. condense some options<commit_after>/*
 * grunt-includes
 * https://github.com/vanetix/grunt-includes
 *
 * Copyright (c) 2013 Matt McFarland
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {

  /**
   * Dependencies
   */

  var path = require('path');

  /**
   * Regex for parsing includes
   */

  var defaultRegexp = /^(\s*)include\s+"(\S+)"\s*$/;

  /**
   * Format of comments per file extension
   */

  var commentStyle = {
    js: "/* %s */",
    css: "/* %s */",
    html: "<!-- %s -->",
    generic: "/* %s */"
  };

  /**
   * Core `grunt-includes` task
   * Iterates over all source files and calls `recurse(path)` on each
   */

  grunt.registerMultiTask('includes', 'Include other files within files.', function() {
    var opts = this.options({
      debug: false,
      duplicates: true,
      includeRegexp: defaultRegexp
    });

    this.files.forEach(function(f) {
      var cwd = f.cwd;
      var src = f.src.filter(function(p) {
        p = cwd ? path.join(cwd, p) : p;
        if(grunt.file.exists(p)) {
          return true;
        } else {
          grunt.log.warn('Source file "' + p + '" not found.');
          return false;
        }
      });

      if(src.length > 1 && grunt.file.isFile(f.dest)) {
        grunt.log.warn('Source file cannot be more than one when dest is a file.');
      }

      src.forEach(function(p) {
        var fileName = f.flatten ? path.basename(p) : p;
        var outFile = grunt.file.isFile(f.dest) ? f.dest : path.join(f.dest, fileName);

        p = cwd ? path.join(cwd, p) : p;

        grunt.file.write(outFile, recurse(p, opts));
        grunt.log.oklns('Saved ' + outFile);
      });

    });
  });

  /**
   * Is file with path `p` an html file?
   *
   * @param {String} p
   * @return {Boolean}
   */

  function fileType(p) {
    return path.extname(p).slice(1);
  }

  /**
   * Helper for `includes` builds all includes for `p`
   *
   * @param {String} p
   * @return {String}
   */

  function recurse(p, opts, included) {
    if(!grunt.file.isFile(p)) {
      grunt.log.warn('Included file "' + p + '" not found.');
      return 'Error including "' + p + '".';
    }

    included = included || {};

    var comment = opts.comment;

    if(opts.duplicates && (p in included)) {
      var msg = 'File ' + p + ' included before, skip';
      grunt.log.debug(msg);
      return opts.debug && comment.replace('%s', msg) || '';
    }

    included[p] = 1;

    var src = grunt.file.read(p).split(grunt.util.linefeed);
    var compiled = src.map(function(line) {
      var match = line.match(opts.includeRegexp);

      if(match) {
        var f = path.join(path.dirname(p), match[opts.pos]);
        line = recurse(f, opts, included);
        if (opts.debug) {
          var msg_begin = 'File: ' + f;
          var msg_end = 'EOF: ' + f;
          line = comment.replace('%s', msg_begin) + '\n' + line + '\n';
          line = line + comment.replace('%s', msg_end);
        }
      }
      return line;
    });

    return  compiled.join(grunt.util.linefeed);
  }

};
<|endoftext|>


<commit_before>// Import node libs
import express from 'express'
import bodyParser from 'body-parser'
import path from 'path'
import chalk from 'chalk'
import fs from 'fs'
// Import local libs
import mkdir from './library/mkdir'
import options from './library/options'

const app = express()
const log = console.log
const dateTime = new Date().toISOString()

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

app.post('/', (req, res) => {
  if (req.body.Action === 'SendEmail') {
    log(`
    ${chalk.green('Email Recieved')}
      ${chalk.blue('From:')} ${req.body.Source}
      ${chalk.blue('To:')} ${req.body['Destination.ToAddresses.member.1']}
      ${chalk.blue('Subject:')} ${req.body['Message.Subject.Data']}
    `)
    let dir = `${options.outputDir}/${dateTime.slice(0, 10)}/${dateTime.slice(11, 22)}`
    let headers = `Subject: ${req.body['Message.Subject.Data']}\nDestination: ${req.body['Destination.ToAddresses.member.1']}\nSource: ${req.body.Source}`
    mkdir(path.join(dir))
    fs.writeFileSync(`${dir}/body.html`, req.body['Message.Body.Html.Data']);
    fs.writeFileSync(`${dir}/body.txt`, req.body['Message.Body.Text.Data']);
    fs.writeFileSync(`${dir}/headers.txt`, headers);
  }
  res.status(200).send('Were up\n')
})

app.listen(options.port)

log(`
${chalk.inverse('  AWS Simple Email Service Local 📬  ')}
  ${chalk.green('Listening on port:')} ${options.port}
  ${chalk.green('Output directory:')} ${options.outputDir}
`)<commit_msg>fixed linting problems<commit_after>// Import node libs
import express from 'express'
import bodyParser from 'body-parser'
import path from 'path'
import chalk from 'chalk'
import fs from 'fs'
// Import local libs
import mkdir from './library/mkdir'
import options from './library/options'

const app = express()
const log = console.log
const dateTime = new Date().toISOString()

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

app.post('/', (req, res) => {
  if (req.body.Action === 'SendEmail') {
    log(`
    ${chalk.green('Email Recieved')}
      ${chalk.blue('From:')} ${req.body.Source}
      ${chalk.blue('To:')} ${req.body['Destination.ToAddresses.member.1']}
      ${chalk.blue('Subject:')} ${req.body['Message.Subject.Data']}
    `)
    const dir = `${options.outputDir}/${dateTime.slice(0, 10)}/${dateTime.slice(11, 22)}`
    const headers = `Subject: ${req.body['Message.Subject.Data']}\nDestination: ${req.body['Destination.ToAddresses.member.1']}\nSource: ${req.body.Source}`
    mkdir(path.join(dir))
    fs.writeFileSync(`${dir}/body.html`, req.body['Message.Body.Html.Data'])
    fs.writeFileSync(`${dir}/body.txt`, req.body['Message.Body.Text.Data'])
    fs.writeFileSync(`${dir}/headers.txt`, headers)
  }
  res.status(200).send('Were up\n')
})

app.listen(options.port)

log(`
${chalk.inverse('  AWS Simple Email Service Local 📬  ')}
  ${chalk.green('Listening on port:')} ${options.port}
  ${chalk.green('Output directory:')} ${options.outputDir}
`)<|endoftext|>


<commit_before>var Promise = require('promise');
var Config = require('./config.json');
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var io = require('socket.io');
var proxy = require('http-proxy-middleware');

var app = express();

exports.proxyContainer = function (name, port) {
    return new Promise( (resolve, reject) =>  {

        var onProxyRes = function(proxyRes, req, res) {
            console.log(proxyRes, req, res);
            proxyRes.headers['Access-Control-Allow-Origin'] = '*';
            proxyRes.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, Content-Length, X-Requested-With';
            proxyRes.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS';
        };

        var p = proxy("/"+name, {logLevel: 'debug', target: "http://localhost:" + port, ws: true, pathRewrite:{ ["^/"+name]: '/'}, proxyRes: onProxyRes });

        app.use(p);
        resolve();
    });
}

exports.launch = function (port, conman) {
    server = http.createServer(app);
    installingApps = [];
    io = io(server);

    app.enable('trust proxy');
    app.set('views', 'src/www');
    app.set('view engine','pug');
    app.use(express.static('src/www'));

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

    app.get('/',(req,res) => { res.render('index') });
    app.get('/slayer',(req,res) => { res.render('slayer') });
    app.get('/close',(req,res) => { res.render('close') });

    app.get('/list-containers',(req,res) => {
        conman.listContainers()
        .then( (containers) => {
            for(appName of installingApps) {
              found = false;
              for(app of containers) {
                if(app.Names.indexOf(appName) != -1){
                  found = true;
                }
              }
              if(!found){
                containers.push({Names:[appName], Status: "Installing"});
              }
            }
            res.end(JSON.stringify(containers));
        })
        //.catch()
    });

    app.get('/list-images',(req,res) => {
        conman.listImages()
        .then( (images) => {
            res.end(JSON.stringify(images));
        })
        //.catch()
    });

    app.get('/list-store',(req,res) => {

        console.log('list-store');

        request('https://' + Config.registryUrl + '/v2/_catalog', (error,response,body) => {
           if(error) {
                res.end(JSON.stringify(error));
                return
            }
            var repositories = JSON.parse(body).repositories;
            var repocount = repositories.length;
            var manifests = [];

            repositories.map((repo) => {
                request.post( {'url':Config.storeUrl+'/app/get/', 'form':{'name':repo}}, (err,data) => {

                    if(err) {
                        //do nothing
                        return ;
                    }

                    body = JSON.parse(data.body);
                    if( typeof body.error == 'undefined' || body.error != 23) {
                        manifests.push(body);
                    }
                    repocount--;
                    if(repocount <= 0) {
                        res.end(JSON.stringify(manifests));
                    }
                });
            });

        });
    });

    app.post('/pull-app', (req,res) => {
        name = req.body.name
        tag  = req.body.tag
        conman.pullImage(Config.registryUrl +  name + ':' + tag)
        .then((err, data) => {
            if(err) {
                return;
            }
            stream.pipe(data)
        })
    });

    app.post('/install', (req,res) => {
        var sla = JSON.parse(req.body.sla);
        var name = sla.name;
        console.log(JSON.stringify(installingApps));
        repoTag =  '/' + name;
        installingApps.push("/"+name);

        io.emit('docker-create',repoTag);
        conman.launchContainer(repoTag)
          .then((info) => {
            var index = installingApps.indexOf('/'+name)
            if(index != -1) {
              installingApps.splice(index, 1)
            }
            proxyContainer(info.name, info.port);
            res.send(JSON.stringify(info));
          });
    });

    app.post('/restart', (req,res) => {
        name = req.body.name || req.body.id
        console.log("Restarting " + req.body.id);
        conman.getContainer(req.body.id)
        .then( (container) => {
            console.log("Restarting " + container.id);
            container.stop((err,data) => {

                if(err && err['statusCode'] != 304) {
                    res.send(JSON.stringify(err))
                    return
                }
                console.log("Stoped " + container.id);

                container.start((err,data) => {
                    if(err) {
                        res.send(JSON.stringify(err))
                        return
                    }
                    console.log("Restarted " + container.id);
                    res.send(JSON.stringify(data))
                })
            })
        })
    });

    app.post('/uninstall', (req,res) => {
        name = req.body.name || req.body.id
        conman.getContainer(req.body.id)
        .then( (container) => {
            console.log("Uninstalling " + container.id);
            container.stop((err,data) => {

                if(err && err['statusCode'] != 304) {
                    res.send(JSON.stringify(err))
                    return
                }
                console.log("Stoped " + container.id);

                container.remove((err,data) => {
                    if(err) {
                        res.send(JSON.stringify(err))
                        return
                    }
                    console.log("Removed " + container.id);
                    res.send(JSON.stringify(data))
                })
            })
        })
    });

    io.on('connection',(socket)=>{

        var emitter = conman.getDockerEmitter();

        emitter.on("connect", function() {
          socket.emit('docker-connect');
        });
        emitter.on("disconnect", function() {
          socket.emit('docker-disconnect');
        });
        emitter.on("_message", function(message) {
          socket.emit('docker-_message',message);
        });
        emitter.on("create", function(message) {
          socket.emit('docker-create',message);
        });
        emitter.on("start", function(message) {
          socket.emit('docker-star',message);
        });
        emitter.on("start", function(message) {
          socket.emit('docker-stop',message);
        });
        emitter.on("die", function(message) {
          socket.emit('docker-die',message);
        });
        emitter.on("destroy", function(message) {
          socket.emit('docker-destroy',message);
        });
        emitter.start();

    })

    server.listen(port);
}

<commit_msg>Switch to state rather than status<commit_after>var Promise = require('promise');
var Config = require('./config.json');
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var io = require('socket.io');
var proxy = require('http-proxy-middleware');

var app = express();

exports.proxyContainer = function (name, port) {
    return new Promise( (resolve, reject) =>  {

        var onProxyRes = function(proxyRes, req, res) {
            console.log(proxyRes, req, res);
            proxyRes.headers['Access-Control-Allow-Origin'] = '*';
            proxyRes.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, Content-Length, X-Requested-With';
            proxyRes.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS';
        };

        var p = proxy("/"+name, {logLevel: 'debug', target: "http://localhost:" + port, ws: true, pathRewrite:{ ["^/"+name]: '/'}, proxyRes: onProxyRes });

        app.use(p);
        resolve();
    });
}

exports.launch = function (port, conman) {
    server = http.createServer(app);
    installingApps = [];
    io = io(server);

    app.enable('trust proxy');
    app.set('views', 'src/www');
    app.set('view engine','pug');
    app.use(express.static('src/www'));

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

    app.get('/',(req,res) => { res.render('index') });
    app.get('/slayer',(req,res) => { res.render('slayer') });
    app.get('/close',(req,res) => { res.render('close') });

    app.get('/list-containers',(req,res) => {
        conman.listContainers()
        .then( (containers) => {
            for(appName of installingApps) {
              found = false;
              for(app of containers) {
                if(app.Names.indexOf(appName) != -1){
                  found = true;
                }
              }
              if(!found){
                containers.push({Names:[appName], State: "installing"});
              }
            }
            res.end(JSON.stringify(containers));
        });
        //.catch()
    });

    app.get('/list-images',(req,res) => {
        conman.listImages()
        .then( (images) => {
            res.end(JSON.stringify(images));
        })
        //.catch()
    });

    app.get('/list-store',(req,res) => {

        console.log('list-store');

        request('https://' + Config.registryUrl + '/v2/_catalog', (error,response,body) => {
           if(error) {
                res.end(JSON.stringify(error));
                return
            }
            var repositories = JSON.parse(body).repositories;
            var repocount = repositories.length;
            var manifests = [];

            repositories.map((repo) => {
                request.post( {'url':Config.storeUrl+'/app/get/', 'form':{'name':repo}}, (err,data) => {

                    if(err) {
                        //do nothing
                        return ;
                    }

                    body = JSON.parse(data.body);
                    if( typeof body.error == 'undefined' || body.error != 23) {
                        manifests.push(body);
                    }
                    repocount--;
                    if(repocount <= 0) {
                        res.end(JSON.stringify(manifests));
                    }
                });
            });

        });
    });

    app.post('/pull-app', (req,res) => {
        name = req.body.name
        tag  = req.body.tag
        conman.pullImage(Config.registryUrl +  name + ':' + tag)
        .then((err, data) => {
            if(err) {
                return;
            }
            stream.pipe(data)
        })
    });

    app.post('/install', (req,res) => {
        var sla = JSON.parse(req.body.sla);
        var name = sla.name;
        console.log(JSON.stringify(installingApps));
        repoTag =  '/' + name;
        installingApps.push("/"+name);

        io.emit('docker-create',repoTag);
        conman.launchContainer(repoTag)
          .then((info) => {
            var index = installingApps.indexOf('/'+name)
            if(index != -1) {
              installingApps.splice(index, 1)
            }
            proxyContainer(info.name, info.port);
            res.send(JSON.stringify(info));
          });
    });

    app.post('/restart', (req,res) => {
        name = req.body.name || req.body.id
        console.log("Restarting " + req.body.id);
        conman.getContainer(req.body.id)
        .then( (container) => {
            console.log("Restarting " + container.id);
            container.stop((err,data) => {

                if(err && err['statusCode'] != 304) {
                    res.send(JSON.stringify(err))
                    return
                }
                console.log("Stoped " + container.id);

                container.start((err,data) => {
                    if(err) {
                        res.send(JSON.stringify(err))
                        return
                    }
                    console.log("Restarted " + container.id);
                    res.send(JSON.stringify(data))
                })
            })
        })
    });

    app.post('/uninstall', (req,res) => {
        name = req.body.name || req.body.id
        conman.getContainer(req.body.id)
        .then( (container) => {
            console.log("Uninstalling " + container.id);
            container.stop((err,data) => {

                if(err && err['statusCode'] != 304) {
                    res.send(JSON.stringify(err))
                    return
                }
                console.log("Stoped " + container.id);

                container.remove((err,data) => {
                    if(err) {
                        res.send(JSON.stringify(err))
                        return
                    }
                    console.log("Removed " + container.id);
                    res.send(JSON.stringify(data))
                })
            })
        })
    });

    io.on('connection',(socket)=>{

        var emitter = conman.getDockerEmitter();

        emitter.on("connect", function() {
          socket.emit('docker-connect');
        });
        emitter.on("disconnect", function() {
          socket.emit('docker-disconnect');
        });
        emitter.on("_message", function(message) {
          socket.emit('docker-_message',message);
        });
        emitter.on("create", function(message) {
          socket.emit('docker-create',message);
        });
        emitter.on("start", function(message) {
          socket.emit('docker-star',message);
        });
        emitter.on("start", function(message) {
          socket.emit('docker-stop',message);
        });
        emitter.on("die", function(message) {
          socket.emit('docker-die',message);
        });
        emitter.on("destroy", function(message) {
          socket.emit('docker-destroy',message);
        });
        emitter.start();

    })

    server.listen(port);
}

<|endoftext|>


<commit_before>'use strict';

var check = require('check-types'),
	path = require('path'),
	fs = require('fs'),
	cp = require('child_process'),
	events = require('events');

module.exports = function (options) {
	options = options || {};

	// defaults
	options.port = options.port || 9700;
	options.ssl = options.ssl || false;
	options.cors = options.cors || false;
	// options.spec = options.spec || 1;
	options.dir = options.dir || process.cwd();
	// options.log = options.log || process.cwd();
	options.host = options.host || 'localhost';
	// options.consumer = options.consumer || 'consumer name';
	// options.provider = options.provider || 'provider name';

	// port checking
	check.assert.number(options.port);
	check.assert.integer(options.port);
	check.assert.positive(options.port);
	check.assert.inRange(options.port, 0, 65535);

	if (check.not.inRange(options.port, 1024, 49151)) {
		console.warn("Like a Boss, you used a port range outside of the registered range (1024 to 49151); I too like to live dangerously.");
	}

	// ssl check
	check.assert.boolean(options.ssl);

	// cors check
	check.assert.boolean(options.cors);

	// spec checking
	if (options.spec) {
		check.assert.number(options.spec);
		check.assert.integer(options.spec);
		check.assert.positive(options.spec);
	}

	// dir check
	check.assert(fs.statSync(path.normalize(options.dir)).isDirectory(), "Error on directory, not a valid directory");

	// log check
	if (options.log) {
		check.assert(fs.statSync(path.normalize(options.log)).isFile(), "Error on log file, not a valid file");
	}

	return new Server(options.port, options.host, options.dir, options.ssl, options.cors, options.log, options.spec, options.consumer, options.provider);
};

function Server(port, host, dir, ssl, cors, log, spec, consumer, provider) {
	this.port = port;
	this.host = host;
	this.dir = dir;
	this.ssl = ssl;
	this.cors = cors;
	this.log = log;
	this.spec = spec;
	this.consumer = consumer;
	this.provider = provider;
}

Server.prototype = new events.EventEmitter;

Server.prototype.start = function () {
	if (this.instance && this.instance.connected) {
		console.warn('You already have a process running with PID: ' + this.instance.pid);
		return;
	}
	var file,
		args = [],
		opts = {
			cwd: path.join(__dirname, '..', 'node_modules/.bin/'),
			detached: (process.platform !== 'win32')
		},
		mapping = {
			'port': '--port',
			'host': '--host',
			'log': '--log',
			'ssl': '--ssl',
			'cors': '--cors',
			'dir': '--pact_dir',
			'spec': '--pact_specification_version',
			'consumer': '--consumer',
			'provider': '--provider'
		};

	for (var key in mapping) {
		if (this[key]) {
			args.push(mapping[key] + ' ' + this[key]);
		}
	}

	var cmd = (process.platform !== 'win32' ? "./" : "") + "pact-mock-service " + args.join(' ');

	if (process.platform === 'win32') {
		file = 'cmd.exe';
		args = ['/s', '/c', cmd];
		opts.windowsVerbatimArguments = true;
	} else {
		file = '/bin/sh';
		args = ['-c', cmd];
	}

	this.instance = cp.spawn(file, args, opts);

	this.instance.stdout.setEncoding('utf8');
	this.instance.stdout.on('data', console.log);
	this.instance.stderr.setEncoding('utf8');
	this.instance.stderr.on('data', console.error);
	this.instance.on('error', console.error);

	console.info('Creating Pact with PID: ' + this.instance.pid);

	this.instance.on('close', function (code) {
		if (code !== 0) {
			console.warn('Pact exited with code ' + code + '.');
		}
		this.stop();
	}.bind(this));

	var onExit = function () {
		console.info('exiting node');
		this.delete();
	}.bind(this);

	// Kill process on node exit
	process.once('exit', onExit);
	process.once('SIGINT', function(){
		process.exit();
	});

	return this;
};

Server.prototype.stop = function () {
	if (this.instance) {
		console.info('Killing Pact');
		this.instance.removeAllListeners();
		if (process.platform === 'win32') {
			cp.execSync('taskkill /f /t /pid ' + this.instance.pid);
		} else {
			process.kill(-this.instance.pid, 'SIGKILL');
		}
		this.instance = undefined;
	}
	return this;
};

Server.prototype.delete = function () {
	this.stop();
	this.emit('delete', this);
	return this;
};
<commit_msg>adding callback to server functions, still need to add checks<commit_after>'use strict';

var check = require('check-types'),
	path = require('path'),
	fs = require('fs'),
	cp = require('child_process'),
	events = require('events'),
	noop = function(){};

module.exports = function (options) {
	options = options || {};

	// defaults
	options.port = options.port || 9700;
	options.ssl = options.ssl || false;
	options.cors = options.cors || false;
	// options.spec = options.spec || 1;
	options.dir = options.dir || process.cwd();
	// options.log = options.log || process.cwd();
	options.host = options.host || 'localhost';
	// options.consumer = options.consumer || 'consumer name';
	// options.provider = options.provider || 'provider name';

	// port checking
	check.assert.number(options.port);
	check.assert.integer(options.port);
	check.assert.positive(options.port);
	check.assert.inRange(options.port, 0, 65535);

	if (check.not.inRange(options.port, 1024, 49151)) {
		console.warn("Like a Boss, you used a port range outside of the registered range (1024 to 49151); I too like to live dangerously.");
	}

	// ssl check
	check.assert.boolean(options.ssl);

	// cors check
	check.assert.boolean(options.cors);

	// spec checking
	if (options.spec) {
		check.assert.number(options.spec);
		check.assert.integer(options.spec);
		check.assert.positive(options.spec);
	}

	// dir check
	check.assert(fs.statSync(path.normalize(options.dir)).isDirectory(), "Error on directory, not a valid directory");

	// log check
	if (options.log) {
		check.assert(fs.statSync(path.normalize(options.log)).isFile(), "Error on log file, not a valid file");
	}

	return new Server(options.port, options.host, options.dir, options.ssl, options.cors, options.log, options.spec, options.consumer, options.provider);
};

function Server(port, host, dir, ssl, cors, log, spec, consumer, provider) {
	this.port = port;
	this.host = host;
	this.dir = dir;
	this.ssl = ssl;
	this.cors = cors;
	this.log = log;
	this.spec = spec;
	this.consumer = consumer;
	this.provider = provider;
}

Server.prototype = new events.EventEmitter;

Server.prototype.start = function (callback) {
	callback = callback || noop;
	if (this.instance && this.instance.connected) {
		console.warn('You already have a process running with PID: ' + this.instance.pid);
		callback(this);
		return;
	}
	var file,
		args = [],
		opts = {
			cwd: path.join(__dirname, '..', 'node_modules/.bin/'),
			detached: (process.platform !== 'win32')
		},
		mapping = {
			'port': '--port',
			'host': '--host',
			'log': '--log',
			'ssl': '--ssl',
			'cors': '--cors',
			'dir': '--pact_dir',
			'spec': '--pact_specification_version',
			'consumer': '--consumer',
			'provider': '--provider'
		};

	for (var key in mapping) {
		if (this[key]) {
			args.push(mapping[key] + ' ' + this[key]);
		}
	}

	var cmd = (process.platform !== 'win32' ? "./" : "") + "pact-mock-service " + args.join(' ');

	if (process.platform === 'win32') {
		file = 'cmd.exe';
		args = ['/s', '/c', cmd];
		opts.windowsVerbatimArguments = true;
	} else {
		file = '/bin/sh';
		args = ['-c', cmd];
	}

	this.instance = cp.spawn(file, args, opts);

	this.instance.stdout.setEncoding('utf8');
	this.instance.stdout.on('data', console.log);
	this.instance.stderr.setEncoding('utf8');
	this.instance.stderr.on('data', console.error);
	this.instance.on('error', console.error);

	console.info('Creating Pact with PID: ' + this.instance.pid);

	this.instance.on('close', function (code) {
		if (code !== 0) {
			console.warn('Pact exited with code ' + code + '.');
		}
		this.stop();
	}.bind(this));

	var onExit = function () {
		console.info('exiting node');
		this.delete();
	}.bind(this);

	// Kill process on node exit
	process.once('exit', onExit);
	process.once('SIGINT', function(){
		process.exit();
	});

	// TODO: add check here to make sure service is up before calling callback
	callback(this);
};

Server.prototype.stop = function (callback) {
	callback = callback || noop;
	if (this.instance) {
		console.info('Killing Pact');
		this.instance.removeAllListeners();
		if (process.platform === 'win32') {
			cp.execSync('taskkill /f /t /pid ' + this.instance.pid);
		} else {
			process.kill(-this.instance.pid, 'SIGKILL');
		}
		this.instance = undefined;
	}
	// TODO: add check here to make sure service is down before calling callback
	callback(this);
};

Server.prototype.delete = function (callback) {
	callback = callback || noop;
	this.stop(function(){
		this.emit('delete', this);
		callback(this);
	}.bind(this));
};
<|endoftext|>


<commit_before>/**
 * Write a function that outputs a multiplication table for numbers up to 5.
 * The table should be a two-dimensional array.
 */
var MultiplicationTable = function() {
  'use strict';

  function generate5(n) {
  	var arr = [[], [], [], [], [], []];
    (function() {
      for(var i = 0; i <= 5; i++){
        arr[0].push(i)
      }
    })();
    for(var z = 1; z <= 5; z++){
      arr[z].push(z);
    }
    for (var j=1; j<=5; j++) {
      for (var i=1; i<=5; i++) {
        arr[i].push(i * j)
      }
    }
    return arr;
  }

  return {
    generate5: generate5
  };
};
<commit_msg>Updated<commit_after>/**
 * Write a function that outputs a multiplication table for numbers up to 5.
 * The table should be a two-dimensional array.
 */
var MultiplicationTable = function () {
    'use strict';

    function generate5(n) {
        var arr = [[], [], [], [], [], []];

        (function () {
            for (var i = 0; i <= 5; i++) {
                arr[0].push(i)
            }
        })();

        for (var z = 1; z <= 5; z++) {
            arr[z].push(z);
        }

        for (var j = 1; j <= 5; j++) {
            for (var i = 1; i <= 5; i++) {
                arr[i].push(i * j)
            }
        }

        return arr;
    }

    return {
        generate5: generate5
    };
};
<|endoftext|>


<commit_before>var lblStatus;
var longitude, latitude;

function PoloWindow() {

	var self = Ti.UI.createWindow({
		title: 'Polo',
		backgroundColor: '#fff'
	});

	self.add(Ti.UI.createLabel({
		top: 27,
		width: '80%',
		height: Ti.UI.SIZE,
		color: '#000',
		text: 'Enter your name'
	}));

	var txtPlayerName = Ti.UI.createTextField({
		top: 50,
		width: '80%',
		borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
		value: 'Joe Jambon'
	});

	self.add(txtPlayerName);

	var btnCheckin = Ti.UI.createImageView({
		width: 150,
		height: 150,
		backgroundColor: 'red'
	});

	self.add(btnCheckin);

	lblStatus = Ti.UI.createLabel({
		bottom: 1,
		width: Ti.UI.FILL,
		backgroundColor: '#000',
		color: '#fff',
		opacity: 0.7,
		textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER
	});

	self.add(lblStatus);

	btnCheckin.addEventListener('click', function(evt) {
		lblStatus.text = 'Checking in, please wait...';
		var placeId = Ti.App.Properties.getString('PLACE_ID', '');

		if (!placeId) {	 // No pace for this user yet
			Cloud.Places.create({
				name: txtPlayerName.text,
				latitude: latitude,
				longitude: longitude
			}, function(e) {
				var place = e.places[0];

				Ti.App.Properties.setString('PLACE_ID', place.id);
				if (e.success) {
					lblStatus.text = 'Position registered successfully!';
				} else {
					error(e);
				}
			});
		} else {  // A place already exists, se we update it
			Cloud.Places.update({
				place_id: placeId,
				name: txtPlayerName.text,
				latitude: latitude,
				longitude: longitude
			}, function(e) {
				if (e.success) {
					lblStatus.text = 'Position updated successfully!';
				} else {
					error(e);
				}
			});
		}

	});

	self.addEventListener('open', findMe);

	return self;
}

function findMe(statusLabel) {

	lblStatus.text = 'Geolocating...';

	if (Ti.Geolocation) {
		Ti.Geolocation.purpose = 'To find current location.';
		Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_BEST;
		Ti.Geolocation.distanceFilter = 0;

		Ti.Geolocation.getCurrentPosition(function (e) {
			if (!e.success || e.error) {
				lblStatus.text = 'GPS lost';
			}
			else {
				lblStatus.text = 'Location determined...';

				latitude = e.coords.latitude;
				longitude = e.coords.longitude;
			}
		});
	}
	else {
		Cloud.Clients.geolocate(function (e) {
			if (e.success) {
				lblStatus.text = 'Location determined...';

				latitude = e.location.latitude;
				longitude = e.location.longitude;
			}
			else {
				lblStatus.text = 'GPS lost';
			}
		});
	}
}

function error(e) {
	var msg = (e.error && e.message) || JSON.stringify(e);
	if (e.code) {
		alert(msg);
	} else {
		Ti.API.error(msg);
	}
}

module.exports = PoloWindow;<commit_msg>Better look and feel<commit_after>var lblStatus;
var longitude, latitude;

function PoloWindow() {

	var self = Ti.UI.createWindow({
		title: 'Polo',
		backgroundColor: '#cccc99',
		barColor: '#003366'
	});

	self.add(Ti.UI.createLabel({
		top: 17,
		width: '80%',
		height: Ti.UI.SIZE,
		color: '#000',
		text: 'Enter your name'
	}));

	var txtPlayerName = Ti.UI.createTextField({
		top: 40,
		width: '80%',
		borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
		value: 'Joe Jambon'
	});

	self.add(txtPlayerName);

	var btnCheckin = Ti.UI.createImageView({
		width: 200,
		height: 200,
		backgroundColor: '#666699',
		borderColor: '#fff',
		borderWidth: 4,
		borderRadius: '100%'
	});

	btnCheckin.add(Ti.UI.createLabel({
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
		color: '#fff',
		text: 'Polo',
		textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
		font: {
			fontSize: '45sp',
			fontWeight: 'bold'
		}
	}));

	self.add(btnCheckin);

	lblStatus = Ti.UI.createLabel({
		bottom: 1,
		width: Ti.UI.FILL,
		backgroundColor: '#003333',
		color: '#fff',
		opacity: 0.7,
		textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER
	});

	self.add(lblStatus);

	btnCheckin.addEventListener('click', function(evt) {
		lblStatus.text = 'Checking in, please wait...';
		var placeId = Ti.App.Properties.getString('PLACE_ID', '');

		if (!placeId) {	 // No pace for this user yet
			Cloud.Places.create({
				name: txtPlayerName.text,
				latitude: latitude,
				longitude: longitude
			}, function(e) {
				var place = e.places[0];

				Ti.App.Properties.setString('PLACE_ID', place.id);
				if (e.success) {
					lblStatus.text = 'Position registered successfully!';
				} else {
					error(e);
				}
			});
		} else {  // A place already exists, se we update it
			Cloud.Places.update({
				place_id: placeId,
				name: txtPlayerName.text,
				latitude: latitude,
				longitude: longitude
			}, function(e) {
				if (e.success) {
					lblStatus.text = 'Position updated successfully!';
				} else {
					error(e);
				}
			});
		}

	});

	self.addEventListener('open', findMe);

	return self;
}

function findMe(statusLabel) {
	lblStatus.text = 'Geolocating...';

	if (Ti.Geolocation) {
		Ti.Geolocation.purpose = 'To find current location.';
		Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_BEST;
		Ti.Geolocation.distanceFilter = 0;

		Ti.Geolocation.getCurrentPosition(function (e) {
			if (!e.success || e.error) {
				lblStatus.text = 'GPS lost';
			}
			else {
				lblStatus.text = 'Location determined...';

				latitude = e.coords.latitude;
				longitude = e.coords.longitude;
			}
		});
	}
	else {
		Cloud.Clients.geolocate(function (e) {
			if (e.success) {
				lblStatus.text = 'Location determined...';

				latitude = e.location.latitude;
				longitude = e.location.longitude;
			}
			else {
				lblStatus.text = 'GPS lost';
			}
		});
	}
}

function error(e) {
	var msg = (e.error && e.message) || JSON.stringify(e);
	if (e.code) {
		alert(msg);
	} else {
		Ti.API.error(msg);
	}
}

module.exports = PoloWindow;<|endoftext|>


<commit_before>var superagent = require('superagent')
var server = process.env.COUCHDB_HOST || 'localhost'
var port = process.env.COUCHDB_PORT || 5984
var couchdb = 'http://'+server+':'+port
//console.log(couchdb)
/**
 * couchdb_check_state(opts,cb)
 * opts = {'db': the couchdb holding the document,
 *         'doc': the document holding the state,
 *         'year': the year to check (any sub key in the doc, really),
 *         'state': the state to get from the doc under the 'year' key,
 * }
 * cb = a callback
 *
 * cb will be called as cb(error,value)
 *
 * The error will contain any error passed from accessing couchdb
 *
 * The value can be null if there is nothing in the document, or will
 * equal the value of doc[year][state]
 *
 * in a special case, if there is doc[state], but nothing at doc[year]
 * and/or if opts.year is not defined, then I will return doc[state]
 *
 * So for example, if you want to check 'rawimpute' in the year 2008
 * for detector 1212432, in a couchdb called 'tracking', you would
 * call with
 *
 * {'db':'tracking',doc':'1212432','year':2008,'state':'rawimpute'}
 *
 * If you want to check 'rawimpute' in the year 2008 for detector
 * 1212432, in a couchdb database named vds_detector/tracking/D12, you
 * could call with
 *
 * {'db':'vds_detector%2ftracking%2f/D12','doc':'1212432',
 *  'year':2008,'state':'rawimpute'}
 *
 *
 *
 * note that I don't make any assumptions about the db or year, aside
 * from the fact that I expect that there will be a couchdb document
 * with that name.  Typically this means the detector id should
 * resolve to some string.  If you have a couchdb with slashes, you
 * should remember to escape those properly, etc
 *
 * If you pass dbroot, it is presumed that the separator is a slash,
 * and if you don't want that, then do not use dbroot, use a full
 * couchdb name passed as detector_id
 *
 */
function couchdb_check_state(opts,cb){
    var db = opts.db
    var id = opts.doc
    var year = opts.year
    var state = opts.state

    var query = couchdb+'/'+db+'/'+id
    //console.log(query)
    superagent
    .get(query)
    .set('accept','application/json')
    .set('followRedirect',true)
    .end(function(err,res){
        if(err) return cb(err)
        var doc = res.body
        if(doc[year] === undefined){
            if(doc[state] === undefined){
                return cb(null,null)
            }else{
                return cb(null,doc[state])
            }
        }
        // if still here, have doc year, but maybe not doc state
        return cb(null, doc[year][state])
    })
}
module.exports=couchdb_check_state
<commit_msg>modified to allow checking multiple states at once<commit_after>var superagent = require('superagent')
var server = process.env.COUCHDB_HOST || 'localhost'
var port = process.env.COUCHDB_PORT || 5984
var couchdb = 'http://'+server+':'+port
//console.log(couchdb)
/**
 * couchdb_check_state(opts,cb)
 * opts = {'db': the couchdb holding the document,
 *         'doc': the document holding the state,
 *         'year': the year to check (any sub key in the doc, really),
 *         'state': the state to get from the doc under the 'year' key,
 * }
 * cb = a callback
 *
 * cb will be called as cb(error,value)
 *
 * The error will contain any error passed from accessing couchdb
 *
 * The value can be null if there is nothing in the document, or will
 * equal the value of doc[year][state]
 *
 * in a special case, if there is doc[state], but nothing at doc[year]
 * and/or if opts.year is not defined, then I will return doc[state]
 *
 * So for example, if you want to check 'rawimpute' in the year 2008
 * for detector 1212432, in a couchdb called 'tracking', you would
 * call with
 *
 * {'db':'tracking',doc':'1212432','year':2008,'state':'rawimpute'}
 *
 * If you want to check 'rawimpute' in the year 2008 for detector
 * 1212432, in a couchdb database named vds_detector/tracking/D12, you
 * could call with
 *
 * {'db':'vds_detector%2ftracking%2f/D12','doc':'1212432',
 *  'year':2008,'state':'rawimpute'}
 *
 *
 *
 * note that I don't make any assumptions about the db or year, aside
 * from the fact that I expect that there will be a couchdb document
 * with that name.  Typically this means the detector id should
 * resolve to some string.  If you have a couchdb with slashes, you
 * should remember to escape those properly, etc
 *
 * If you pass dbroot, it is presumed that the separator is a slash,
 * and if you don't want that, then do not use dbroot, use a full
 * couchdb name passed as detector_id
 *
 */
function couchdb_check_state(opts,cb){
    var db = opts.db
    var id = opts.doc
    var year = opts.year
    var state = opts.state

    var query = couchdb+'/'+db+'/'+id
    //console.log(query)
    superagent
    .get(query)
    .set('accept','application/json')
    .set('followRedirect',true)
    .end(function(err,res){
        if(err) return cb(err)
        var doc = res.body
        // let state be an array
        var result = []
        var _state = state
        if(! _.isArray(state)){
            _state = [state]
        }
        if(doc[year] === undefined){
            _.each(_state,function(s){
                if(doc[state] === undefined){
                    result.push(null)
                }else{
                    result.push(doc[state])
                }
            })
        }else{
            _.each(_state,function(s){
                if(doc[year][state] === undefined){
                    result.push(null)
                }else{
                    result.push(doc[year][state])
                }
            })
        }
        // if still here, have doc year, but maybe not doc state
        if(result.length === 1) result = result[0]
        return cb(null, result)
    })
}
module.exports=couchdb_check_state
<|endoftext|>


<commit_before>/*jslint node:true*/

(function prep() {
    "use strict";
    var node  = {
            child: require("child_process").exec,
            path : require("path")
        },
        msg   = "",
        delay = function prep_delay() {
            setTimeout(function prep_delay_timeout() {
                if (msg === "") {
                    console.log("Waiting...");
                    prep_delay();
                } else {
                    console.log(msg);
                }
            }, 1000);
        };
    node.child("git clone https://github.com/prettydiff/biddle.git", function prep_clone(cer, stdcout, stdcer) {
        if (cer !== null && cer.toString().indexOf("Cloning into 'biddle'...") < 0) {
            msg = cer;
            console.log("cer");
            return console.log(cer);
        }
        if (stdcer !== null && stdcer !== "" && stdcer.indexOf("Cloning into 'biddle'...") < 0) {
            msg = stdcer;
            console.log("stdcer");
            return console.log(stdcer);
        }
        console.log("biddle clone complete!");
        node.child("node biddle global", {cwd:"biddle"}, function prep_clone_global(ger, stdgout, stdger) {
            if (ger !== null) {
                msg = ger;
                console.log("ger");
                return console.log(ger);
            }
            if (stdger !== null && stdger !== "") {
                msg = stdger;
                console.log("stdger");
                return console.log(stdger);
            }
            console.log("biddle global complete!");
            node.child("biddle install http://prettydiff.com/downloads/jslint/jslint_latest.zip", function prep_clone_global_install(ier, stdiout, stdier) {
                if (ier !== null) {
                    msg = ier;
                    console.log("ier");
                    return console.log(ier);
                }
                if (stdier !== null && stdier !== "") {
                    msg = stdier;
                    console.log("stdier");
                    return console.log(stdier);
                }
                msg = "jslint installed by biddle";
                console.log("Pretty Diff test execute!");
                require("./lint.js");
                return [stdcout, stdgout, stdiout];
            });
        });
    });
    delay();
}());<commit_msg>debugging travis build<commit_after>/*jslint node:true*/

(function prep() {console.log(process.cwd());
    "use strict";
    var node  = {
            child: require("child_process").exec,
            path : require("path")
        },
        msg   = "",
        delay = function prep_delay() {
            setTimeout(function prep_delay_timeout() {
                if (msg === "") {
                    console.log("Waiting...");
                    prep_delay();
                } else {
                    console.log(msg);
                }
            }, 1000);
        };
    node.child("git clone https://github.com/prettydiff/biddle.git", function prep_clone(cer, stdcout, stdcer) {
        if (cer !== null && cer.toString().indexOf("Cloning into 'biddle'...") < 0) {
            msg = cer;
            console.log("cer");
            return console.log(cer);
        }
        if (stdcer !== null && stdcer !== "" && stdcer.indexOf("Cloning into 'biddle'...") < 0) {
            msg = stdcer;
            console.log("stdcer");
            return console.log(stdcer);
        }
        console.log("biddle clone complete!");
        node.child("node biddle global", {cwd:"biddle"}, function prep_clone_global(ger, stdgout, stdger) {
            if (ger !== null) {
                msg = ger;
                console.log("ger");
                return console.log(ger);
            }
            if (stdger !== null && stdger !== "") {
                msg = stdger;
                console.log("stdger");
                return console.log(stdger);
            }
            console.log("biddle global complete!");
            node.child("biddle install http://prettydiff.com/downloads/jslint/jslint_latest.zip", function prep_clone_global_install(ier, stdiout, stdier) {
                if (ier !== null) {
                    msg = ier;
                    console.log("ier");
                    return console.log(ier);
                }
                if (stdier !== null && stdier !== "") {
                    msg = stdier;
                    console.log("stdier");
                    return console.log(stdier);
                }
                msg = "jslint installed by biddle";
                console.log("Pretty Diff test execute!");
                require("./lint.js");
                return [stdcout, stdgout, stdiout];
            });
        });
    });
    delay();
}());<|endoftext|>


<commit_before>function esShader(gl) {
	this.gl = gl;
	this.program = gl.createProgram();
}

<commit_msg>Add: Shader base.<commit_after>var ES_VERTEX = 1;
var ES_FRAGMENT = 2;

function esShader(gl) {
	this.gl = gl;
	this.program = gl.createProgram();
}

esShader.prototype.addShaderId = function(shader, idName, type) {
	this.gl.createShader(type);
}

<|endoftext|>


<commit_before>Date.prototype.toDateInputValue = (function() {
    var local = new Date(this);
    local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
    return local.toJSON().slice(0,10);
});

var admonitus = {};
admonitus.transFreqNoToName = function(num)
{
	switch (num)
	{
	case 0:
		return "One-time";
	case 1:
		return "Daily";
	case 2:
		return "Weekly";
	case 3:
		return "Monthly";
	default:
		return "Invalid";
	}
}

var reminderTable = {};
reminderTable.addRow = function (rowNr, data, highlight)
{
	newrow = $("#template").clone();

	this.updateRow(newrow, rowNr, data);

	newrow.insertAfter("#template");

	newrow.show();

	if(highlight)
	{
		newrow.effect("highlight", { color: "AACCE8"}, 1500);
	}
}

reminderTable.updateRow = function (tr, id, data)
{
	tr.find("td.number").text(id + 1);
	tr.find("span.text").text(data['text']);
	tr.find("input.text").val(data['text']);
	tr.find("button[name=deleteButton]").attr('data-id', data['id']);
	tr.attr("id", data['id']);
	tr.find("span.startingat").text(new Date(data['datestart']).format('d-M-Y'))
	tr.find(".startingat").val(new Date(data['datestart']).toDateInputValue())

	tr.find("span.frequency").text(
		admonitus.transFreqNoToName(data['frequency'])
	);
	tr.find(".frequency").val(data['frequency']);
}

var mainObj = function() {
	var self = this;

	this.refreshRemindersList = function()
	{
		$.ajax({
			type : "GET",
			dataType : "json",
			url : "/Admonitus/ctl/Reminder/get",
			success : function(response) {

				$("#remindersList > tbody").find("tr:gt(1)").remove();

				$.each(response.data, function(index, entry) {
					reminderTable.addRow(index, entry);
				});
			}

		});
	}

	this.switchToLoggedIn = function(response)
	{
		$("#emailAddress").text(response.data.email);
		$(".loggedOut").hide();
		$(".loggedIn").show();
		self.refreshRemindersList();
	}

	this.switchToLoggedOut = function()
	{
		$(".loggedOut").show();
		$(".loggedIn").hide();
	}

	$(document).on("click", "button[name=editButton]",
		function (e)
		{
			e.preventDefault();
			id = $(this).parent().parent().attr("id");
			$("#remindersList > tbody > tr[id=" + id + "]").find(".reminderView").hide();
			$("#remindersList > tbody > tr[id=" + id + "]").find(".reminderEdit").show();
		}
	);

	$(document).on("click", "button[name=saveButton]",
		function(e)
		{
			e.preventDefault();
			id = $(this).parent().parent().attr("id");
			var tr = $("#remindersList > tbody > tr[id=" + id + "]");

			var request = {
				"frequency": tr.find("select[name=frequency] option:selected").val(),
				"text": tr.find("input[name=text]").val(),
				"startingat": tr.find("input[name=startingat]").val()
			}

			$.ajax({
				type: "POST",
				dataType: "json",
				url: "/Admonitus/ctl/Reminder/edit/" + id,
				data: request,
				context: self,
				success: function(response)
				{
					if(response.success)
					{
						reminderTable.updateRow($("#" + id), id, response.data)
						tr.find(".reminderView").show();
						tr.find(".reminderEdit").hide();
						tr.effect("highlight", { color: "A8D9A8"}, 1000);
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});
		}
	);

	$("input[name=startingat]").val((new Date()).toDateInputValue());

	$(document).on("click", "#registerButton",
		function(e)
		{
			e.preventDefault();
			var request = {
					"email": $("input[id=registerEmail]").val(),
					"password1": $("input[id=registerPassword1]").val(),
					"password2": $("input[id=registerPassword2]").val()
				}
				$.ajax({
					type: "POST",
					dataType: "json",
					url: "/Admonitus/ctl/User/register",
					data: request,
					context: self,
					success: function(response)
					{
						if(response.success)
						{
							$("#registerForm").hide();
							$("#registerCompleted").show();
						}
						else
						{
							$("#jsonErrorText").text(response.error);
							$('#jsonErrorModal').modal('show');
						}
					}
				});
		}

	);

	$(document).on("click", "#logoutButton",
		function(e)
		{
			e.preventDefault();
			$.ajax({
				type: "GET",
				dataType: "json",
				url: "/Admonitus/ctl/User/logout",
				context: self,
				success: function(response)
				{
					if(response.success)
					{
						self.switchToLoggedOut();
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});
		}
	);

	$(document).on("click", "#loginButton",
		function(e)
		{
			e.preventDefault();
			var request = {
				"email": $("input[id=loginEmail]").val(),
				"password": $("input[id=loginPassword]").val()
			}
			$.ajax({
				type: "POST",
				dataType: "json",
				url: "/Admonitus/ctl/User/login",
				data: request,
				context: self,
				success: function(response)
				{
					if(response.success)
					{
						self.switchToLoggedIn(response);
						$("#loginForm")[0].reset();
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});
		}
	);

	$("#deleteModal").on('show.bs.modal',
		function(e)
		{
	    	$("button[name=deleteConfirm]").attr("data-id", $(e.relatedTarget).data('id'));
		}
	);

	$("#jsonEditModal").on('show.bs.modal'),
		function(e)
		{

		}

	$(document).on('click', "button[name=deleteConfirm]",
		function(e)
		{
			var id = $(this).attr("data-id");
			console.log("Delete id " + id);

			$.ajax({
				type: "GET",
				dataType: "json",
				url: "/Admonitus/ctl/Reminder/delete/" + id
			});

			$("#remindersList").find("tr[id=" + id + "]").remove();
		}
	);

	$("#reminderForm").submit(function(e) {
		e.preventDefault();

		var request = {
			"frequency": $("#new select[name=frequency] option:selected").val(),
			"text": $("#new input[name=text]").val(),
			"startingat": $("#new input[name=startingat]").val()
		}

		$.ajax({
			type : "POST",
			dataType : "json",
			url : "/Admonitus/ctl/Reminder/add",
			data : request,
			context: self,
			success: function(response)
			{
				if(response.success)
				{
					reminderTable.addRow(0, response.data, true)
					$("#new input[name=text]").val("");
					$("#new select[name=frequency]").val(2);
					$("#new input[name=startingat]").val((new Date()).toDateInputValue());
				}
				else
				{
					$("#jsonErrorText").text(response.error);
					$('#jsonErrorModal').modal('show');
				}
			}
		});
	});

	$.ajax({
		type: "GET",
		dataType: "json",
		url: "/Admonitus/ctl/User/isLoggedIn",
		context: self,
		success: function(response)
		{
			if(response.data)
			{
				self.switchToLoggedIn(response);
			}
		}
	});

}

$("document").ready(mainObj);
<commit_msg>Friend implementation<commit_after>Date.prototype.toDateInputValue = (function() {
    var local = new Date(this);
    local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
    return local.toJSON().slice(0,10);
});

var admonitus = {};
admonitus.transFreqNoToName = function(num)
{
	switch (num)
	{
	case 0:
		return "One-time";
	case 1:
		return "Daily";
	case 2:
		return "Weekly";
	case 3:
		return "Monthly";
	default:
		return "Invalid";
	}
}

var reminderTable = {};
reminderTable.addRow = function (rowNr, data, highlight)
{
	newrow = $("#template").clone();

	this.updateRow(newrow, rowNr, data);

	newrow.insertAfter("#template");

	newrow.show();

	if(highlight)
	{
		newrow.effect("highlight", { color: "AACCE8"}, 1500);
	}
}

reminderTable.updateRow = function (tr, id, data)
{
	tr.find("td.number").text(id + 1);
	tr.find("span.text").text(data['text']);
	tr.find("input.text").val(data['text']);
	tr.find("button[name=deleteButton]").attr('data-id', data['id']);
	tr.attr("id", data['id']);
	tr.find("span.startingat").text(new Date(data['datestart']).format('d-M-Y'))
	tr.find(".startingat").val(new Date(data['datestart']).toDateInputValue())

	tr.find("span.frequency").text(
		admonitus.transFreqNoToName(data['frequency'])
	);
	tr.find(".frequency").val(data['frequency']);
}

var friendsTable = {};
friendsTable.addRow = function(data, highlight)
{
	newrow = $("#friendTemplate").clone();

	newrow.attr("id", "");
	newrow.attr("data-id", data['id']);

	newrow.find("span.email").text(data['email']);
	newrow.find("button[name=deleteFriendButton]").attr('data-id', data['id']);

	newrow.show();
	newrow.insertAfter("#friendTemplate");
	if(highlight)
	{
		newrow.effect("highlight", { color: "AACCE8"}, 1500);
	}
}

var mainObj = function() {
	var self = this;

	this.refreshRemindersList = function()
	{
		$.ajax({
			type : "GET",
			dataType : "json",
			url : "/Admonitus/ctl/Reminder/get",
			success : function(response) {

				$("#remindersList > tbody").find("tr:gt(1)").remove();

				$.each(response.data, function(index, entry) {
					reminderTable.addRow(index, entry);
				});
			}

		});
	}

	this.switchToLoggedIn = function(response)
	{
		$("#emailAddress").text(response.data.email);
		$(".loggedOut").hide();
		$(".loggedIn").show();
		self.refreshRemindersList();
		$('#reminderForm input[name=text]').focus();
	}

	this.switchToLoggedOut = function()
	{
		$(".loggedOut").show();
		$(".loggedIn").hide();
	}

	$(document).on("click", "button[name=editButton]",
		function (e)
		{
			e.preventDefault();
			id = $(this).parent().parent().attr("id");
			$("#remindersList > tbody > tr[id=" + id + "]").find(".reminderView").hide();
			$("#remindersList > tbody > tr[id=" + id + "]").find(".reminderEdit").show();
		}
	);

	$(document).on("click", "button[name=saveButton]",
		function(e)
		{
			e.preventDefault();
			id = $(this).parent().parent().attr("id");
			var tr = $("#remindersList > tbody > tr[id=" + id + "]");

			var request = {
				"frequency": tr.find("select[name=frequency] option:selected").val(),
				"text": tr.find("input[name=text]").val(),
				"startingat": tr.find("input[name=startingat]").val()
			}

			$.ajax({
				type: "POST",
				dataType: "json",
				url: "/Admonitus/ctl/Reminder/edit/" + id,
				data: request,
				context: self,
				success: function(response)
				{
					if(response.success)
					{
						reminderTable.updateRow($("#" + id), id, response.data)
						tr.find(".reminderView").show();
						tr.find(".reminderEdit").hide();
						tr.effect("highlight", { color: "A8D9A8"}, 1000);
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});
		}
	);

	$("input[name=startingat]").val((new Date()).toDateInputValue());

	$(document).on("click", "#registerButton",
		function(e)
		{
			e.preventDefault();
			var request = {
					"email": $("input[id=registerEmail]").val(),
					"password1": $("input[id=registerPassword1]").val(),
					"password2": $("input[id=registerPassword2]").val()
				}
				$.ajax({
					type: "POST",
					dataType: "json",
					url: "/Admonitus/ctl/User/register",
					data: request,
					context: self,
					success: function(response)
					{
						if(response.success)
						{
							$("#registerForm").hide();
							$("#registerCompleted").show();
						}
						else
						{
							$("#jsonErrorText").text(response.error);
							$('#jsonErrorModal').modal('show');
						}
					}
				});
		}

	);

	$(document).on("click", "#logoutButton",
		function(e)
		{
			e.preventDefault();
			$.ajax({
				type: "GET",
				dataType: "json",
				url: "/Admonitus/ctl/User/logout",
				context: self,
				success: function(response)
				{
					if(response.success)
					{
						self.switchToLoggedOut();
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});
		}
	);

	$(document).on("click", "#loginButton",
		function(e)
		{
			e.preventDefault();
			var request = {
				"email": $("input[id=loginEmail]").val(),
				"password": $("input[id=loginPassword]").val()
			}
			$.ajax({
				type: "POST",
				dataType: "json",
				url: "/Admonitus/ctl/User/login",
				data: request,
				context: self,
				success: function(response)
				{
					if(response.success)
					{
						self.switchToLoggedIn(response);
						$("#loginForm")[0].reset();
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});
		}
	);

	$("#deleteModal").on('show.bs.modal',
		function(e)
		{
	    	$("button[name=deleteConfirm]").attr("data-id", $(e.relatedTarget).data('id'));
		}
	);

	$("#friendModal").on('show.bs.modal',
		function(e)
		{
			var id = $(e.relatedTarget).parent().parent().attr('id');
			$("#friendModal button[id=addFriend]").attr('data-id', id);

			$("#friendsTable > tbody").find("tr:gt(1)").remove();

			$.ajax(
				{
					type: "GET",
					dataType: "json",
					url: "/Admonitus/ctl/Reminder/getFriends/" + id,
					success: function(response)
					{
						if(response.success)
						{
							$.each(response.data, function(index, entry) {
								friendsTable.addRow(entry);
							});
						}
					}
				}
			);
		}
	);

	$('#friendModal').on('shown.bs.modal',
		function () {
	    	$('#friendEmail').focus();
		}
	);

	$(document).on('click', "#friendModal button[id=addFriend]",
		function(e)
		{
			e.preventDefault();

			var id = $(this).attr("data-id");

			var request =
			{
				email: $("#friendModal input[id=friendEmail]").val()
			}

			$.ajax(
				{
					type: "POST",
					dataType: "json",
					data: request,
					url: "/Admonitus/ctl/Reminder/addFriend/" + id,
					success: function(response)
					{
						if(response.success)
						{
							$("#friendModal form")[0].reset();
							friendsTable.addRow(response.data, true);
						}
						else
						{
							$("#jsonErrorText").text(response.error);
							$('#jsonErrorModal').modal('show');
						}
					}
				}
			)
		}
	);

	$(document).on('click', "button[name=deleteConfirm]",
		function(e)
		{
			var id = $(this).attr("data-id");
			console.log("Delete id " + id);

			$.ajax({
				type: "GET",
				dataType: "json",
				url: "/Admonitus/ctl/Reminder/delete/" + id
			});

			$("#remindersList").find("tr[id=" + id + "]").remove();
		}
	);

	$(document).on('click', "button[name='friendButton']",
		function (e)
		{
			e.preventDefault();
		}
	);

	$(document).on('click', "button[name=deleteFriendButton]",
		function(e)
		{
			var id = $(this).attr("data-id");

			$.ajax({
				type: "POST",
				dataType: "json",
				url: "/Admonitus/ctl/Reminder/deleteFriend/" + id,
				success: function(response)
				{
					if(response.success)
					{
						$("#friendsTable tr[data-id=" + id + "]").remove();
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});

		}
	);

	$(document).on('click', "button[name='addReminder']", function(e) {
		e.preventDefault();

		var request = {
			"frequency": $("#new select[name=frequency] option:selected").val(),
			"text": $("#new input[name=text]").val(),
			"startingat": $("#new input[name=startingat]").val()
		}

		$.ajax({
			type : "POST",
			dataType : "json",
			url : "/Admonitus/ctl/Reminder/add",
			data : request,
			context: self,
			success: function(response)
			{
				if(response.success)
				{
					reminderTable.addRow(0, response.data, true)
					$("#new input[name=text]").val("");
					$("#new select[name=frequency]").val(2);
					$("#new input[name=startingat]").val((new Date()).toDateInputValue());
				}
				else
				{
					$("#jsonErrorText").text(response.error);
					$('#jsonErrorModal').modal('show');
				}
			}
		});
	});

	/* Initialization */
	$.ajax({
		type: "GET",
		dataType: "json",
		url: "/Admonitus/ctl/User/isLoggedIn",
		context: self,
		success: function(response)
		{
			if(response.data)
			{
				self.switchToLoggedIn(response);
			}
		}
	});

	$('#loginEmail').focus();

}

$("document").ready(mainObj);
<|endoftext|>


<commit_before>var assert = require( 'assert' ),
    request = require( 'supertest' ),
    generator = require( '../lib/generator' );

describe( 'Generator', function() {
    describe( 'getRandomInt', function() {
        it( 'should return an integer in [0..1000000000]', function() {
            var randomInt = generator.getRandomInt();

            assert.equal( typeof randomInt, 'number' );
            assert.equal( Math.floor( randomInt ), randomInt );
            assert( randomInt < 1000000000 );
            assert( randomInt >= 0 );
        });
    });

    describe( 'getQuery', function() {
        it( 'should return a string of the form "A+B=" where A and B are integers', function() {
            var query = generator.getQuery();

            assert( /^\d+\+\d+\=?$/.test( query ) );
        });
    });

    describe( 'sendRequest', function() {
        it( 'should send an HTTP get request' );

        it( 'should log the response body' );

        it( 'should log errors if received', function(done) {
            assert.throws( function() {
                generator.sendRequest( function(data) {
                    done();
                });
            });
        });
    });
});<commit_msg>added tests for sendRequest<commit_after>var assert = require( 'assert' ),
    sinon = require( 'sinon' ),
    PassThrough = require( 'stream' ).PassThrough,
    http = require( 'http' ),
    generator = require( '../lib/generator' );

describe( 'Generator', function() {
    describe( 'getRandomInt', function() {
        it( 'should return an integer in [0..1000000000]', function() {
            var randomInt = generator.getRandomInt();

            assert.equal( typeof randomInt, 'number' );
            assert.equal( Math.floor( randomInt ), randomInt );
            assert( randomInt < 1000000000 );
            assert( randomInt >= 0 );
        });
    });

    describe( 'getQuery', function() {
        it( 'should return a string of the form "A+B=" where A and B are integers', function() {
            var query = generator.getQuery();

            assert( /^\d+\+\d+\=?$/.test( query ) );
        });
    });

    describe( 'sendRequest', function() {
        beforeEach(function() {
            this.get = sinon.stub(http, 'get');
        });

        afterEach(function() {
            http.get.restore();
        });

        describe( 'request is successful', function() {
            it( 'should execute a callback on response data', function() {
                var expected = 'hello';
                var response = new PassThrough();

                response.write( expected );
                response.end();

                response.on( 'data', function( chunk ) {
                    // console.log(chunk);
                });

                var get = new PassThrough();

                this.get.callsArgWith( 1, response )
                            .returns( get );

                generator.sendRequest(function( err, data ) {
                    assert.equals( data, expected );
                });
            });
        });
        describe( 'request errors', function() {
            it( 'should call callback with error as first arg', function() {
                var expected = new Error( 'test' );

                var get = new PassThrough();

                this.get.returns( get );

                generator.sendRequest( function( err, data ) {
                    assert.equal( err, expected );
                });

                get.emit( 'error', expected );
            });
        });
    });
});<|endoftext|>