<commit_before>'use strict'

const pg = require('pg') // postgres database
const request = require('superagent') // AJAX api
const express = require('express') // middleware connector
const app = express()
const PORT = 3000

const conString = process.env.DATABASE || 'postgres://@localhost:5432/dyes'
const client = new pg.Client(conString)

client.connect() // Connects to postgres database

// PSQL database Event Listeners
client.on('connect', function(){
  console.log('Connected to the psql database successfully!')
})

client.on('error', function(err){
  console.error('Something went wrong involving the database' , err);
})

// If there's no Leaderboard Table then make one.
function createLeaderboardTable(){
  client.query(`
    CREATE TABLE IF NOT EXISTS leaderboard (
      leaderboard_id SERIAL PRIMARY KEY,
      name VARCHAR(255),
      time VARCHAR(255)
    )`)
    .catch(function(err){
      console.log('Something went wrong with checking/creating the leaderboard tables.',err);
    });
}
createLeaderboardTable()

// Routing for server

app.use(express.static('./public'))
app.listen(PORT,function(){
  console.log('Server started on: ', PORT);

})

app.get('/getSteamID', (req,res) => {
  req.headers.vanityUrl = 'killertreat'
  if(req.headers.vanityUrl){
    request.get(`https://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=${process.env.KEYs}&vanityurl=${req.headers.vanityUrl}`)
    .end( function(err, response){
      if(err) {
        console.log('There was an error while trying to get the SteamID.\n\nerr.message:\n    ', err.status, err.message)
        res.send(err.status, err.message)
      }else{
        console.log(`This is the response.body: ${response.body}`)
        res.steamid = response.body.response.steamid
        res.send(res.status, res.steamid)
      }
    })
  }else{
    res.status('400').send('400 Bad Request - The vanityUrl was not attached to the headers on your request.')
    console.log('400 bad request- There is noting assigned to req.headers.vanityUrl.')
  }
})
// Route to get a user's SteamData.

app.get('/checkLeaderboard', (req, res) => {
  // Route to check if someone is already on the leaderboard.
})

app.post('/addToLeaderboard', (req, res) => {
  // Route to add someone to the leaderboard for the first time.
})

app.put('/updateLeaderboard', (req, res) => {
  // Route to update a score for a user currently on the leaderboard.
})

app.delete('/removeFromLeaderboard', (req, res) => {
  // Removes a user from the leaderboard.
})

app.delete('/delete', (req, res) => {
  request.delete().then( () => {

  }).catch()
})

app.get('/*', (request, response) => response.sendFile('./public/index.html', {root: '.'}));
<commit_msg>Added route to get the user's game data. Also removed the testing req.headers. The routes will now give valid responses when used with proper headers.<commit_after>'use strict'

const pg = require('pg') // postgres database
const request = require('superagent') // AJAX api
const express = require('express') // middleware connector
const app = express()
const PORT = 3000

const conString = process.env.DATABASE || 'postgres://@localhost:5432/dyes'
const client = new pg.Client(conString)

client.connect() // Connects to postgres database

// PSQL database Event Listeners
client.on('connect', function(){
  console.log('Connected to the psql database successfully!')
})

client.on('error', function(err){
  console.error('Something went wrong involving the database!' , err);
})

// If there's no Leaderboard Table then make one.
function createLeaderboardTable(){
  client.query(`
    CREATE TABLE IF NOT EXISTS leaderboard (
      leaderboard_id SERIAL PRIMARY KEY,
      name VARCHAR(255),
      time VARCHAR(255)
    )`)
    .catch(function(err){
      console.log('Something went wrong with checking/creating the leaderboard tables.',err);
    });
}
createLeaderboardTable()

// Routing for server
app.use(express.static('./public'))
app.listen(PORT,function(){
  console.log('Server started on: ', PORT);

})

app.get('/getSteamID', (req,res) => {

  if(req.headers.vanityUrl){
    request.get(`https://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=${process.env.KEY}&vanityurl=${req.headers.vanityUrl}`)
      .end( function(err, response){
        if(err) {
          console.log('There was an error while trying to get the SteamID.\n\nerr.message:\n    ', err.status, err.message)
          res.status(`${response.status}`).send(err.status, err.message)
        }else{
          console.log(`This is the response.body: ${response.body.response.steamid}`)
          res.steamid = response.body.response.steamid
          res.status(`${response.status}`).send(res.steamid)
        }
      })
  }else{
    res.status('400').send('400 Bad Request - The vanityUrl was not attached to the headers on your request.')
    console.log('400 bad request- There is noting assigned to req.headers.vanityUrl.')
  }
})

// Route to get a user's SteamData.
app.get('/getSteamData', (req,res) => {
  if(req.headers.steamID){

    request.get(`https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=${process.env.KEY}&steamid=${req.headers.steamID}&format=json&include_appinfo=1`)

    .end( function(err, response){
      if(err){
        console.log('There was an error trying to get the user\'s game data.\n\n err:\n    ', err.status, err.message)
        res.status(`${response.status}`).send(err.status, err.message)
      }else{
        console.log('This is the response for /getSteamData:\n\nresponse.body:\n    ', response.body.response)
        res.steamData = response.body
        res.status(`${response.status}`).send(response.status, res.steamData)
      }
    })

  }else{
    res.status('400').send('400 Bad Request - The steamID was not attached to the headers on the request.')
    console.log('400 Bad Request - There is nothing assigned to req.headers.steamID');
  }
})

app.get('/checkLeaderboard', (req, res) => {
  // Route to check if someone is already on the leaderboard.
})

app.post('/addToLeaderboard', (req, res) => {
  // Route to add someone to the leaderboard for the first time.
})

app.put('/updateLeaderboard', (req, res) => {
  // Route to update a score for a user currently on the leaderboard.
})

app.delete('/removeFromLeaderboard', (req, res) => {
  // Removes a user from the leaderboard.
})

app.get('/*', (req, res) => res.sendFile('./public/index.html', {root: '.'}));
<|endoftext|>


<commit_before>var express = require('express')
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var config = require('./config/main');
var app = express();
var port = 3000;
require('dotenv').config();

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

//current homepage
app.get('/', function(req, res) {
	res.send('root of Purdue Men\'s Rugby Servers.');
});

//log request to console
app.use(morgan('dev'));
console.log(process.env.DB);
//connect to db
var db = mongoose.connect(process.env.DB);
//bring in api router
require('./app/routes/roster')(app);
require('./app/routes/calendar')(app);

app.listen(port);
console.log('Your server is running on port ' + port + '.');

<commit_msg>I may have it<commit_after>var express = require('express')
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var config = require('./config/main');
var app = express();
var port = 3000;
require('dotenv').config();

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

//current homepage
app.get('/', function(req, res) {
	res.send('root of Purdue Men\'s Rugby Servers.');
});

//log request to console
app.use(morgan('dev'));
//connect to db
var db = mongoose.connect(MONGODB_URI);
//bring in api router
require('./app/routes/roster')(app);
require('./app/routes/calendar')(app);

app.listen(port);
console.log('Your server is running on port ' + port + '.');

<|endoftext|>


<commit_before>// 'use strict'

const five = require("johnny-five");
const board = new five.Board();
let led;
const express = require('express');
const app = express();
const path = require('path');
const logger = require('morgan');
const PORT = process.env[2] || process.env.PORT || 3000 ;
const homeRoute = require("./routes/home");
const onOffRoute = require("./routes/onoff");
const $ = require('jquerygo');
const request = require('request');
const http = require("http");
let io = require('socket.io')
let fs = require('fs')

app.listen(PORT,()=>{
  console.log('sup from '+PORT);
})
// to-do: add views
app.set('view engine','ejs');
app.use(express.static(path.join(__dirname,'public')));
app.use(logger('dev'));

let state = false
// SEtting homeRoute
app.use('/', homeRoute);
app.get('/on', function(req,res) {
  console.log("Current state is " + state)
  res.send(state = true)

} );
app.get('/off', function(req,res) {
  state = false
} );

// Do we want the sequence to loop?
let loop = true;

// Create a simple demo sequece that calls various
// five.Led methods with specified arguments and
// let it run for the given duration (defaults to 3 seconds).
let demoSequence = [{
  method: "pulse",
  args: [1000],
  duration: 5000
}, {
  method: "strobe",
  args: [500],
  duration: 3000
}, {
  method: "fadeIn",
  args: [
    2000,
    function() {
      console.log("fadeIn complete!");
    }
  ],
  duration: 2500
}, {
  method: "fadeOut",
  args: [
    5000,
    function() {
      console.log("fadeOut complete!");
    }
  ],
  duration: 5500
}, {
  method: "brightness",
  args: [10],
  duration: 3000
}, {
  method: "off"
}];

// $(".on").on("click",
// if (state === true) {
  console.log("will turn on")
// Execute a method in the demo sequence
function execute(step) {
    console.log("clicked on")

  // Grab everything we need for this step
  let method = demoSequence[step].method;
  let args = demoSequence[step].args;
  let duration = demoSequence[step].duration || 3000;

  // Just print out what we're executing
  console.log("led." + method + "(" + (args ? args.join() : "") + ")");

  // Make the actual call to the LED
  five.Led.prototype[method].apply(led, args);

  // Increment the step
  step++;

  // If we're at the end, start over (loop==true) or exit
  if (step === demoSequence.length) {
    if (loop) {
      step = 0;
    } else {
      // We're done!
      process.exit(0);
    }
  }

  // Recursively call the next step after specified duration
  board.wait(duration, function() {
    execute(step);
  });
}
// )
// ENd of click function

board.on("ready", function() {
  // Defaults to pin 11 (must be PWM)
  led = new five.Led(process.argv[2] || 11);

  // Kick off the first step
  execute(0);
});

// } else {
//   console.log(false)
//   state = false
// }

// http.createServer(function (req, resp) {
//   if (req.url === '/') {
//     if (req.method === 'PUT') {
//       req.pipe(request.put('http://mysite.com/doodle.png'))
//     } else if (req.method === 'GET' || req.method === 'HEAD') {
//       request.get('http://mysite.com/doodle.png').pipe(resp)
//     }
//   }
// }).listen(3000)
// console.log("server started rewuest")

// let five = require("johnny-five");
// let =board = new five.Board();
// let led  ;
// let toggleState = false;

// board.on("ready", function() {
//   console.log("The board is blinking!");
//   let led = new five.Led(13);
//   led.blink(500);
// });

<commit_msg>removed jquery package.json<commit_after>// 'use strict'

const five = require("johnny-five");
const board = new five.Board();
let led;
const express = require('express');
const app = express();
const path = require('path');
const logger = require('morgan');
const PORT = process.env[2] || process.env.PORT || 3000 ;
const homeRoute = require("./routes/home");
const onOffRoute = require("./routes/onoff");
const $ = require('jquerygo');
const request = require('request');
const http = require("http");
let io = require('socket.io');
let fs = require('fs');
let gpio = require("rpi-gpio")

app.listen(PORT,()=>{
  console.log('sup from '+PORT);
})
// to-do: add views
app.set('view engine','ejs');
app.use(express.static(path.join(__dirname,'public')));
app.use(logger('dev'));

let state = false
// SEtting homeRoute
app.use('/', homeRoute);
app.get('/on', function(req,res) {
  console.log("Current state is " + state)
  res.send(state = true)

} );
app.get('/off', function(req,res) {
  state = false
} );

// Do we want the sequence to loop?
let loop = true;

// Create a simple demo sequece that calls various
// five.Led methods with specified arguments and
// let it run for the given duration (defaults to 3 seconds).
let demoSequence = [{
  method: "pulse",
  args: [1000],
  duration: 5000
}, {
  method: "strobe",
  args: [500],
  duration: 3000
}, {
  method: "fadeIn",
  args: [
    2000,
    function() {
      console.log("fadeIn complete!");
    }
  ],
  duration: 2500
}, {
  method: "fadeOut",
  args: [
    5000,
    function() {
      console.log("fadeOut complete!");
    }
  ],
  duration: 5500
}, {
  method: "brightness",
  args: [10],
  duration: 3000
}, {
  method: "off"
}];

// $(".on").on("click",
// if (state === true) {
  console.log("will turn on")
// Execute a method in the demo sequence
function execute(step) {
    console.log("clicked on")

  // Grab everything we need for this step
  let method = demoSequence[step].method;
  let args = demoSequence[step].args;
  let duration = demoSequence[step].duration || 3000;

  // Just print out what we're executing
  console.log("led." + method + "(" + (args ? args.join() : "") + ")");

  // Make the actual call to the LED
  five.Led.prototype[method].apply(led, args);

  // Increment the step
  step++;

  // If we're at the end, start over (loop==true) or exit
  if (step === demoSequence.length) {
    if (loop) {
      step = 0;
    } else {
      // We're done!
      process.exit(0);
    }
  }

  // Recursively call the next step after specified duration
  board.wait(duration, function() {
    execute(step);
  });
}
// )
// ENd of click function

board.on("ready", function() {
  // Defaults to pin 11 (must be PWM)
  led = new five.Led(process.argv[2] || 11);

  // Kick off the first step
  execute(0);
});

// } else {
//   console.log(false)
//   state = false
// }

// http.createServer(function (req, resp) {
//   if (req.url === '/') {
//     if (req.method === 'PUT') {
//       req.pipe(request.put('http://mysite.com/doodle.png'))
//     } else if (req.method === 'GET' || req.method === 'HEAD') {
//       request.get('http://mysite.com/doodle.png').pipe(resp)
//     }
//   }
// }).listen(3000)
// console.log("server started rewuest")

// let five = require("johnny-five");
// let =board = new five.Board();
// let led  ;
// let toggleState = false;

// board.on("ready", function() {
//   console.log("The board is blinking!");
//   let led = new five.Led(13);
//   led.blink(500);
// });

<|endoftext|>


<commit_before>require('dotenv').config();

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import morgan from 'morgan';
import mongoose from 'mongoose';
import fetch from 'node-fetch';
const app = express()

const PORT               = process.env.PORT || 3001;
const DB_URL             = process.env.DB_URL;
const MOVIE_DB_URL       = process.env.MOVIE_DB_URL;
const MOVIE_DB_KEY       = process.env.MOVIE_DB_KEY;
const FACEBOOK_APP_TOKEN = process.env.FACEBOOK_APP_TOKEN;

app.use(cors());

//Connect to database
mongoose.connect(DB_URL);

//Use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//Use morgan to log
app.use(morgan('dev'));

//API Routes
app.get('/', function(req, res) {
  res.send('MovieCircle API');
});

app.get('/api/verifyFacebook', function(req, res) {
  const accessToken = req.get('Authorization');

  fetch('https://graph.facebook.com/debug_token?input_token=' + accessToken +'&access_token=' + FACEBOOK_APP_TOKEN,
    {
      method: 'GET',
      timeout: 3000,
    }
  )
  .then((response) => {
    if (response.status == 200) {
      return response.json()
    } else {
      res.sendStatus(reponse.status);
    }
  })
  .then((response) => {
    console.log('Facebook Debug', response, response.status);
    res.json({
      status: 200,
      is_valid: true,
    });
  })
  .catch((error) => {
    res.json({
      status: 503,
      error: 'Cannot reach Facebook API.',
    });
  });
});

//Redirect Movie API calls to TheMovieDB.org and return response
app.get('/movieapi', function(req, res) {
  var path  = req.get('path');

  //If no path is defined, request is malformed
  if(!path) {
    res.json({
      error: true,
      status: 400,
    })
  }

  function callback(error, response, body) {
    if(!error && response.statusCode == 200) {
      res.json(body);
    } else {
      res.json({
        error: true,
        status: response.statusCode,
      });
    }
  }

  function correctSymbol(path) { return (path.includes('?')) ? '&' : '?'; }

  fetch(
    {
      url: MOVIE_DB_URL + path + correctSymbol(path) + 'api_key=' + MOVIE_DB_KEY,
      method: 'GET',
    },
    callback
  );
});

//Start server
app.listen(PORT);
console.log('Listening >> http://localhost:' + PORT);
<commit_msg>Few fixes.<commit_after>require('dotenv').config();

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import morgan from 'morgan';
import mongoose from 'mongoose';
import fetch from 'node-fetch';
const app = express()

const PORT               = process.env.PORT || 3001;
const TIMEOUT            = process.env.TIMEOUT || 3000;
const DB_URL             = process.env.DB_URL;
const MOVIE_DB_URL       = process.env.MOVIE_DB_URL;
const MOVIE_DB_KEY       = process.env.MOVIE_DB_KEY;
const FACEBOOK_APP_TOKEN = process.env.FACEBOOK_APP_TOKEN;

let moviedbImageURL = 'http://image.tmdb.org/t/p/'; //Should be getting this on start every few days

app.use(cors());

//Connect to database
mongoose.connect(DB_URL);

//Use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//Use morgan to log
app.use(morgan('dev'));

//API Routes
app.get('/', function(req, res) {
  res.send('MovieCircle API');
});

app.get('/api/verifyFacebook', function(req, res) {
  const accessToken = req.get('Authorization');

  fetch('https://graph.facebook.com/debug_token?input_token=' + accessToken +'&access_token=' + FACEBOOK_APP_TOKEN,
    {
      method: 'GET',
      timeout: TIMEOUT,
    }
  )
  .then((response) => {
    if (response.status == 200) {
      return response.json()
    } else {
      res.sendStatus(reponse.status);
    }
  })
  .then((response) => {
    console.log('Facebook Debug', response, response.status);
    res.json({
      status: 200,
      is_valid: true,
    });
  })
  .catch((error) => {
    res.json({
      status: 503,
      error: 'Cannot reach Facebook API.',
    });
  });
});

//Redirect Movie API calls to TheMovieDB.org and return response
app.get('/movieapi', function(req, res) {
  var path  = req.get('path');

  //If no path is defined, request is malformed
  if(!path) {
    res.json({
      status: 400,
      error: 'Bad Request.',
    });
  }

  function correctSymbol(path) { return (path.includes('?')) ? '&' : '?'; }

  fetch(MOVIE_DB_URL + path + correctSymbol(path) + 'api_key=' + MOVIE_DB_KEY,
  {
    method: 'GET',
    timeout: TIMEOUT,
  })
  .then((response) => {
    if(response.status == 200) {
      return response.json();
    } else {
      res.json({
        status: 503,
        error: 'Cannot reach MovieDB API.'
      });
    }
  })
  .then((response) => {
    res.json(response);
  })
  .catch((error) => {
    res.json({
      status: 503,
      error: 'Cannot reach MovieDB API.',
    });
  });
});

app.get('/configuration', function(req, res) {
  res.json({
    base_url: moviedbImageURL,
  });
});

//Start server
app.listen(PORT);
console.log('Listening >> http://localhost:' + PORT);
<|endoftext|>


<commit_before>var express = require('express'),
    stylus = require('stylus'),
    logger = require('morgan'),
    bodyParser = require('body-parser'),
    mongoose = require('mongoose');

var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var app = express();

// Setup view templates and jade as view engine

app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');

// MIDDLEWARE

// middleware function for stylus
function compileStylus(str, path) {
  return stylus(str).set('filename', path);
}

app.use(logger('dev'));
app.use(bodyParser.urlencoded({extended: true}));
// app.use(bodyParser.json());
app.use(stylus.middleware(
  {
    src: __dirname + '/public',
    compile: compileStylus
  }
));

// Setup static file location for express will serve the file when requested.
app.use(express.static(__dirname + '/public'));

// Mongo setup

if(env === 'development') {
  mongoose.connect('mongodb://localhost/jobs');
} else {

}

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error...'));
db.once('open', function() {
  console.log('jobs db opened');
});

var messageSchema = mongoose.Schema({
  message: String
});

var Message = mongoose.model('Message', messageSchema);

var mongoMessage;

Message.findOne().exec(function(err, messageDoc){
  mongoMessage = messageDoc.message;
});

app.get('/partials/:partialPath', function(req, res) {
  res.render('partials/' + req.params.partialPath);
});

// ROUTES

app.get('*', function(req, res) {
  res.render('index', {
    mongoMessage: mongoMessage
  });
});

// Start server
var port = process.env.PORT || 3030;
app.listen(port);
console.log('Listening on port ' + port + '...');
<commit_msg>added mongo live server connection<commit_after>var express = require('express'),
    stylus = require('stylus'),
    logger = require('morgan'),
    bodyParser = require('body-parser'),
    mongoose = require('mongoose');

var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var app = express();

// Setup view templates and jade as view engine

app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');

// MIDDLEWARE

// middleware function for stylus
function compileStylus(str, path) {
  return stylus(str).set('filename', path);
}

app.use(logger('dev'));
app.use(bodyParser.urlencoded({extended: true}));
// app.use(bodyParser.json());
app.use(stylus.middleware(
  {
    src: __dirname + '/public',
    compile: compileStylus
  }
));

// Setup static file location for express will serve the file when requested.
app.use(express.static(__dirname + '/public'));

// Mongo setup

if(env === 'development') {
  mongoose.connect('mongodb://localhost/jobs');
} else {
  mongoose.connect('mongodb://' + process.env.MONGOLABS_USER + ':' + process.env.MONGOLABS_USER_PASS + '.mongolab.com:35240/jobs');
}

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error...'));
db.once('open', function() {
  console.log('jobs db opened');
});

var messageSchema = mongoose.Schema({
  message: String
});

var Message = mongoose.model('Message', messageSchema);

var mongoMessage;

Message.findOne().exec(function(err, messageDoc){
  mongoMessage = messageDoc.message;
});

app.get('/partials/:partialPath', function(req, res) {
  res.render('partials/' + req.params.partialPath);
});

// ROUTES

app.get('*', function(req, res) {
  res.render('index', {
    mongoMessage: mongoMessage
  });
});

// Start server
var port = process.env.PORT || 3030;
app.listen(port);
console.log('Listening on port ' + port + '...');
<|endoftext|>


<commit_before>const express = require('express');
const path = require('path');
const fs = require('fs');
const pug = require('pug');
const request = require('request');
const cheerio = require('cheerio');

const app = express();

app.set('views', './views')
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, '/')));

//
// API: /
// --------------------------------------------------------------------------
app.get('/', function(req, res) {

	// Scrape GO Transit main page
  const url = 'http://www.gotransit.com/publicroot/en/default.aspx';
  var timestamp;
  var trainsArr = [];

  // Supply formatted, scraped data to render of pug
  request(url, function(error, response, html) {
		if (!error) {
			var name, status, smallDelay, bigDelay;
			var names = [];
	    var $ = cheerio.load(html);
	    timestamp = $('.timestamp div span').html();
	    // Returns all train lines
	    var trains = $('#rtab1 .gridStatusTrain tbody tr');
	    // If empty, no trains are delayed
	    var trainsDelayed = trains.has('.delayLink');

	    for (var i = 0; i < trains.length; i++) {
	    	name = $(trains[i.toString()]).find('.gridStatusWidthOne').text();
	    	// console.log(name);

	    	// Set default status to On time
	    	status = "On time";
	    	// Check if
 contains info within one of its children
	    	smallDelay = $(trains[i.toString()]).has('.delayLink');
	    	// Check if
 has link to URL with additional info
	    	bigDelay = $(trains[i.toString()]).has('.moreInfoLink');

	    	// If
 contains an element
	    	// with either .delayLink or
	    	// .moreInfoLink, it's delayed
	    	if (smallDelay.length > 0) {
	    		status = "Delayed";

	    		// If the current retrieved train line is delayed,
	    		// find info about it
	    		var statusText, direction, details;
	    		var statusArr = [];
	    		var statusPopovers = $(trains[i.toString()]).find('.messageDisrp');

		    	for (var j = 0; j < statusPopovers.length; j++) {
		    		if ($(statusPopovers[j.toString()]).find('h3').text() === name) {
		    			direction = $(statusPopovers[j.toString()]).find('.subtitle h4').text();
		    			details = $(statusPopovers[j.toString()]).find('li > span');

		    			for (var k = 0; k < details.length; k++) {
		    				// Iterate through known delays,
		    				// save their data to statusArr[]
		    				var detail = details[k.toString()];
		    				// Data within the . Contains up to 7 children. (As of 12/01/2016)
			    			// Counts text as an Object?
			    			// [0] = Which train time is delayed (e.x., Union Station 22:13 - Aldershot GO 23:31)
			    			// [1] =

			    			// [2] = Length of delay (e.x., Delay of 7m:53s)
			    			// [3] =

			    			// [4] = State of train (e.x., Moving)
			    			// [5] =

			    			// [6] = Additional state of train (e.x., Waiting on a train ahead)
		    				statusArr.push({
		    					"delayDirection": direction,
		    					"delayedTrain": detail.children[0].data,
		    					"delayLength": detail.children[2].data,
		    					"delayStatus": detail.children[4].data
		    				});
		    			}

		    			// Data within the . Contains up to 7 children. (As of 12/01/2016)
		    			// Counts text as an Object?
		    			// [0] = Which train time is delayed (e.x., Union Station 22:13 - Aldershot GO 23:31)
		    			// [1] =

		    			// [2] = Length of delay (e.x., Delay of 7m:53s)
		    			// [3] =

		    			// [4] = State of train (e.x., Moving)
		    			// [5] =

		    			// [6] = Additional state of train (e.x., Waiting on a train ahead)
		    		}
		    	}
	    	}
	    	else if (bigDelay.length > 0) {
	    		names.push(name);
	    		status = "Delayed";

	    		// If the current retrieved train line is delayed,
	    		// find info about it
	    		var statusText, details;
	    		var statusArr = [];
	    		var moreInfoURL = $(trains[i.toString()]).find('.moreInfoLink').attr('href');

	    		request(moreInfoURL, function(error, response, html) {
	    			if (!error) {
					    var $ = cheerio.load(html);
					    var content = $('.tabs_tab').prop('style');
					    console.log(content);
					    statusArr.push({
					    	"delayMsg": "Errro retrieving message"
					    })
					  }
	    		});
	    	}

	    	// Push retrieved train line info
	    	// to trains array
	    	trainsArr.push({
	    		"name": name,
	    		"status": status,
	    		"direction": direction,
	    		"details": statusArr
	    	})
	    }
    }
    res.render('index', { "retrieveTime": timestamp, "trains": trainsArr });
	});
});

//
// API: /fetch
// --------------------------------------------------------------------------
app.get('/fetch', (req, res) => {
	var url = 'http://www.gotransit.com/publicroot/en/default.aspx';
	var trainsArr = [];
	var timestamp;

	request(url, function(error, response, html) {
		if (!error) {
      var $ = cheerio.load(html);
	    timestamp = $('.timestamp div span').html();
	    // Returns all train lines
	    var trains = $('#rtab1 .gridStatusTrain tbody tr');
	    // If empty, no trains are delayed
	    var trainsDelayed = trains.has('.delayLink');

	    for (var i = 0; i < trains.length; i++) {
	    	var name = $(trains[i.toString()]).find('.gridStatusWidthOne').text();
	    	var status = $(trains[i.toString()]).has('.delayLink').length === 0 ? "On time" : "Delayed";

	    	// Push retrieved train line info
	    	// to trains array
	    	trainsArr.push({
	    		"name": name,
	    		"status": status
	    	})
	    }
    }
    res.json({"timestamp": timestamp, "trains": trainsArr});
	});
});

app.trainsAreDelayed = function() {
	var url = 'http://www.gotransit.com/publicroot/en/default.aspx';

  request(url, function(error, response, html) {
      if (!error) {
          // Next, we'll utilize the cheerio library on the returned html which will essentially give us jQuery functionality
          var $ = cheerio.load(html);
          var trains = $('.gridStatusTrain tbody tr');
          var trainsDelayed = trains.has('.delayLink');

          // If trainsDelayed.length is 0, none are delayed
          if (trainsDelayed.length === 0) {
          	return false;
          }
          else {
          	return true;
          }
      }
  });
}

app.listen(process.env.PORT || 5000);

exports = module.exports = app;<commit_msg>Push delay information to data array if current tab title is same as delayed train with more info<commit_after>const express = require('express');
const path = require('path');
const fs = require('fs');
const pug = require('pug');
const request = require('request');
const cheerio = require('cheerio');

const app = express();

app.set('views', './views')
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, '/')));

//
// API: /
// --------------------------------------------------------------------------
app.get('/', function(req, res) {

	// Scrape GO Transit main page
  const url = 'http://www.gotransit.com/publicroot/en/default.aspx';
  var timestamp;
  var trainsArr = [];

  // Supply formatted, scraped data to render of pug
  request(url, function(error, response, html) {
		if (!error) {
			var name, status, smallDelay, bigDelay;
			var names = [];
	    var $ = cheerio.load(html);
	    timestamp = $('.timestamp div span').html();
	    // Returns all train lines
	    var trains = $('#rtab1 .gridStatusTrain tbody tr');
	    // If empty, no trains are delayed
	    var trainsDelayed = trains.has('.delayLink');

	    for (var i = 0; i < trains.length; i++) {
	    	name = $(trains[i.toString()]).find('.gridStatusWidthOne').text();
	    	// console.log(name);

	    	// Set default status to On time
	    	status = "On time";
	    	// Check if
 contains info within one of its children
	    	smallDelay = $(trains[i.toString()]).has('.delayLink');
	    	// Check if
 has link to URL with additional info
	    	bigDelay = $(trains[i.toString()]).has('.moreInfoLink');

	    	// If
 contains an element
	    	// with either .delayLink or
	    	// .moreInfoLink, it's delayed
	    	if (smallDelay.length > 0) {
	    		status = "Delayed";

	    		// If the current retrieved train line is delayed,
	    		// find info about it
	    		var statusText, direction, details;
	    		var statusArr = [];
	    		var statusPopovers = $(trains[i.toString()]).find('.messageDisrp');

		    	for (var j = 0; j < statusPopovers.length; j++) {
		    		if ($(statusPopovers[j.toString()]).find('h3').text() === name) {
		    			direction = $(statusPopovers[j.toString()]).find('.subtitle h4').text();
		    			details = $(statusPopovers[j.toString()]).find('li > span');

		    			for (var k = 0; k < details.length; k++) {
		    				// Iterate through known delays,
		    				// save their data to statusArr[]
		    				var detail = details[k.toString()];
		    				// Data within the . Contains up to 7 children. (As of 12/01/2016)
			    			// Counts text as an Object?
			    			// [0] = Which train time is delayed (e.x., Union Station 22:13 - Aldershot GO 23:31)
			    			// [1] =

			    			// [2] = Length of delay (e.x., Delay of 7m:53s)
			    			// [3] =

			    			// [4] = State of train (e.x., Moving)
			    			// [5] =

			    			// [6] = Additional state of train (e.x., Waiting on a train ahead)
		    				statusArr.push({
		    					"delayDirection": direction,
		    					"delayedTrain": detail.children[0].data,
		    					"delayLength": detail.children[2].data,
		    					"delayStatus": detail.children[4].data
		    				});
		    			}
		    		}
		    	}
	    	}
	    	else if (bigDelay.length > 0) {
	    		names.push(name);
	    		status = "Delayed";

	    		// If the current retrieved train line is delayed,
	    		// find info about it
	    		var statusText, details;
	    		var statusArr = [];
	    		var moreInfoURL = $(trains[i.toString()]).find('.moreInfoLink').attr('href');

	    		request(moreInfoURL, function(error, response, html) {
	    			if (!error) {
					    var $ = cheerio.load(html);
					    var content = $('#divupdates_train .MsgGroup');
					    var msgTitles = $(content).find('h2');

					    for (var l = 0; l < names.length; l++) {
					    	// If name of train with "more information" matches
					    	// name of retrieved
, we're on the right info page
					    	if (names[l] === $(msgTitles[l.toString()]).text()) {
						    	statusArr.push({
							    	"delayMsg": $(content).find('li').text()
							    });
						    }
						    else {
						    	statusArr.push({
							    	"delayMsg": ""
							    });
						    }
					    }
					  }
	    		});
	    	}

	    	// Push retrieved train line info
	    	// to trains array
	    	trainsArr.push({
	    		"name": name,
	    		"status": status,
	    		"direction": direction,
	    		"details": statusArr
	    	});
	    }
    }
    res.render('index', { "retrieveTime": timestamp, "trains": trainsArr });
	});
});

//
// API: /fetch
// --------------------------------------------------------------------------
app.get('/fetch', (req, res) => {
	var url = 'http://www.gotransit.com/publicroot/en/default.aspx';
	var trainsArr = [];
	var timestamp;

	request(url, function(error, response, html) {
		if (!error) {
      var $ = cheerio.load(html);
	    timestamp = $('.timestamp div span').html();
	    // Returns all train lines
	    var trains = $('#rtab1 .gridStatusTrain tbody tr');
	    // If empty, no trains are delayed
	    var trainsDelayed = trains.has('.delayLink');

	    for (var i = 0; i < trains.length; i++) {
	    	var name = $(trains[i.toString()]).find('.gridStatusWidthOne').text();
	    	var status = $(trains[i.toString()]).has('.delayLink').length === 0 ? "On time" : "Delayed";

	    	// Push retrieved train line info
	    	// to trains array
	    	trainsArr.push({
	    		"name": name,
	    		"status": status
	    	})
	    }
    }
    res.json({"timestamp": timestamp, "trains": trainsArr});
	});
});

app.trainsAreDelayed = function() {
	var url = 'http://www.gotransit.com/publicroot/en/default.aspx';

  request(url, function(error, response, html) {
      if (!error) {
          // Next, we'll utilize the cheerio library on the returned html which will essentially give us jQuery functionality
          var $ = cheerio.load(html);
          var trains = $('.gridStatusTrain tbody tr');
          var trainsDelayed = trains.has('.delayLink');

          // If trainsDelayed.length is 0, none are delayed
          if (trainsDelayed.length === 0) {
          	return false;
          }
          else {
          	return true;
          }
      }
  });
}

app.listen(process.env.PORT || 5000);

exports = module.exports = app;<|endoftext|>


<commit_before>var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.prod');

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

app.use(require('webpack-hot-middleware')(compiler));
*/
app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(3000, 'localhost', function(err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:3000');
});
<commit_msg>Server<commit_after>var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config');

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

app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(3000, 'localhost', function(err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:3000');
});
<|endoftext|>


<commit_before>jQuery(function() { $(document).ready(function(){

	function setExtent(){
		this.name = "Map Extent Plug-in";
	}
	//This will be called immediatly after the addPlugin function
	setExtent.prototype.init = function(){
		addButton("Set Map Extent", "#editor-toolbar",{
			onclick: this.open,
			buttonid: 'setMapExtent'
		});
		$('#setMapExtent').button('disable');
	}

	setExtent.prototype.open = function(){
		//Find the extent in the mapEditor
		line = -1;
		for(var i=0; i<mapEditor.lineCount(); i++){
			if(mapEditor.getLine(i).indexOf("EXTENT:") !== -1){
				//Hightlight line in codemirror
				 mapEditor.setLineClass(i, 'background', 'setextent-highlighted-line');
				line = i;
				break;
			}
		}
		if(line === -1) return "Couldn't find map extent.";

		//We need a vector layer to draw the box
		var boxLayer = new OpenLayers.Layer.Vector("Box layer");
		_workspace.openedMap.OLMap.addLayer(boxLayer);

		//Add drawing control to map
		var boxControl = new OpenLayers.Control.DrawFeature(boxLayer,
			OpenLayers.Handler.RegularPolygon, {
				handlerOptions: {
					sides: 4,
					irregular: true
				}
			}
		);
		boxLayer.events.register('beforefeatureadded',this, function(e){
			boxLayer.removeAllFeatures();
		});
		boxLayer.events.register('featureadded',this, function(e){
			$(".ui-dialog-buttonpane button:contains('SetExtent')").button("enable");
		});
		_workspace.openedMap.OLMap.addControl(boxControl);
		boxControl.activate();

		//Create the dialog
		var dialogDiv = $('

Draw a rectangle on the map to choose the map extent.

')
		dialogDiv.hide();
		$('.main').append(dialogDiv);
		dialogDiv.dialog({
			autoOpen: false,
			resizable: false,
			height: "130",
			width: "180",
   		    modal: false,
   		    buttons: {
				"SetExtent": function(){
					//Get extent string
					var ext = boxLayer.features[0].geometry.bounds.toString();
					ext = ext.replace(/,/g,' ');
					var lineContent = mapEditor.getLine(line);
					var newLineContent = lineContent.substr(0, lineContent.indexOf("EXTENT:")+7);
					newLineContent += ext;
					mapEditor.setLine(line, newLineContent);

				 	mapEditor.setLineClass(i, 'background', '');
					_workspace.openedMap.OLMap.removeControl(boxControl);
					boxControl.destroy();
					_workspace.openedMap.OLMap.removeLayer(boxLayer);
					boxLayer.destroy();
					$(this).dialog("close");
				},
				"Cancel": function(){
				 	mapEditor.setLineClass(i, 'background', '');
					_workspace.openedMap.OLMap.removeControl(boxControl);
					boxControl.destroy();
					_workspace.openedMap.OLMap.removeLayer(boxLayer);
					boxLayer.destroy();
					$(this).dialog("close");
				}
			}
		 }).dialog("open");
		//We keep the button disabled until the user draws a box
		$(".ui-dialog-buttonpane button:contains('SetExtent')").button("disable");

		//Open the map tab if it isn't opened already
		openSecondaryPanel("maps", mapEditor);

	}
        //This will be called by functions.js once the map is opened.
        //There exists also a onWorkspaceOpened function
	setExtent.prototype.onMapOpened = function(){
		$('#setMapExtent').button('enable');
	}
	//Call this to add your plugin to the application.
	addPlugin(new setExtent())
})})
<commit_msg>Fixes last issues with the setExtent plugins. Close button work properly, and it works with standard mapfile.<commit_after>jQuery(function() { $(document).ready(function(){

	function setExtent(){
		this.name = "Map Extent Plug-in";
		this.boxControl = null;
		this.boxLayer = null;
		this.dialogDiv = null;
		this.extentLineNumer = null;
	}
	//This will be called immediatly after the addPlugin function
	setExtent.prototype.init = function(){
		addButton("Set Map Extent", "#editor-toolbar",{
			onclick: $.proxy(this.open,this),
			buttonid: 'setMapExtent'
		});
		$('#setMapExtent').button('disable');
	}

	setExtent.prototype.open = function(){
		//Find the extent in the mapEditor
		var extentStr = "EXTENT ";
		if(_workspace.openedMap.type == "Scribe")
			extentStr = "EXTENT:";
		for(var i=0; i<mapEditor.lineCount(); i++){
			if(mapEditor.getLine(i).indexOf(extentStr) !== -1){
				//Hightlight line in codemirror
				 mapEditor.setLineClass(i, 'background', 'setextent-highlighted-line');
				this.extentLineNumer = i;
				break;
			}
		}
		if(this.extentLineNumer === -1) return "Couldn't find map extent.";
		var extProxyLineNumber = this.extentLineNumer;

		//We need a vector layer to draw the box
		boxLayer = new OpenLayers.Layer.Vector("Box layer");
		_workspace.openedMap.OLMap.addLayer(boxLayer);

		//Add drawing control to map
		boxControl = new OpenLayers.Control.DrawFeature(boxLayer,
			OpenLayers.Handler.RegularPolygon, {
				handlerOptions: {
					sides: 4,
					irregular: true
				}
			}
		);
		boxLayer.events.register('beforefeatureadded',this, function(e){
			boxLayer.removeAllFeatures();
		});
		boxLayer.events.register('featureadded',this, function(e){
			$(".ui-dialog-buttonpane button:contains('SetExtent')").button("enable");
		});
		_workspace.openedMap.OLMap.addControl(boxControl);
		boxControl.activate();

		//Create the dialog
		dialogDiv = $('

Draw a rectangle on the map to choose the map extent.

')
		dialogDiv.hide();
		$('.main').append(dialogDiv);
		dialogDiv.dialog({
			autoOpen: false,
			resizable: false,
			height: "130",
			width: "180",
   		    modal: false,
			beforeClose: $.proxy(this.closeDialog, this),
   		    buttons: {
				"SetExtent": function(){
					//Get extent string
					var ext = boxLayer.features[0].geometry.bounds.toString();
					ext = ext.replace(/,/g,' ');
					var lineContent = mapEditor.getLine(extProxyLineNumber);
					var newLineContent = lineContent.substr(0, lineContent.indexOf(extentStr)+extentStr.length);
					newLineContent += ext;
					mapEditor.setLine(extProxyLineNumber, newLineContent);

					$(this).dialog("close");
				},
				"Cancel": function(){
					$(this).dialog("close");
				}
			}
		 }).dialog("open");
		//We keep the button disabled until the user draws a box
		$(".ui-dialog-buttonpane button:contains('SetExtent')").button("disable");

		//Open the map tab if it isn't opened already
		openSecondaryPanel("maps", mapEditor);

	}
        //This will be called by functions.js once the map is opened.
        //There exists also a onWorkspaceOpened function
	setExtent.prototype.onMapOpened = function(){
		$('#setMapExtent').button('enable');
	}
	setExtent.prototype.closeDialog = function(e, ui){
		mapEditor.setLineClass(this.extentLineNumer, 'background', '');
		_workspace.openedMap.OLMap.removeControl(boxControl);
		boxControl.destroy();
		_workspace.openedMap.OLMap.removeLayer(boxLayer);
		boxLayer.destroy();
	}

	//Call this to add your plugin to the application.
	addPlugin(new setExtent())
})})
<|endoftext|>


<commit_before>module.exports = {
  description: 'Performs post-installation tasks for ember-sinon',

  normalizeEntityName: function() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall: function() {
    return this.addBowerPackageToProject('sinon=http://sinonjs.org/releases/sinon-1.12.2.js');
  }
};
<commit_msg>remove redundant directory<commit_after><|endoftext|>


<commit_before>
module.exports = {
   components: {
      rquery: {
         redisUrl: 'redis://localhost:6379/14',
         redisKeyspace: 'test:rquery',
         hostname: 'test.redishub.com',
         hostUrl: 'https://test.redishub.com',
         serviceName: 'redishub-test',
         serviceLabel: 'RH Test',
         port: 4567,
         location: '',
         assetsUrl: '/assets',
         aboutUrl: 'https://github.com/evanx/redishub/blob/master/README.md',
         helpUrl: 'https://github.com/evanx/redishub/blob/master/README.md',
         indexCommand: 'show-keyspace-config',
         //keyExpire: 2764800, // 31 days
         keyExpire: 604800, // 7 days
         ephemeralKeyExpire: 600,
         ephemeralAccountExpire: 1200,
         certLimit: 4,
         secureDomain: true,
         cliDomain: false,
         htmlDomain: true,
         registerLimit: 10,
         importLimit: 5,
         adminLimit: 1,
         defaultFormat: 'html',
         addClientIp: false
      }
   }
};
<commit_msg>register-cert<commit_after>
module.exports = {
   components: {
      rquery: {
         redisUrl: 'redis://localhost:6379/14',
         redisKeyspace: 'test:rquery',
         hostname: 'test.redishub.com',
         hostUrl: 'https://test.redishub.com',
         serviceName: 'redishub-test',
         serviceLabel: 'RH Test',
         port: 4567,
         location: '',
         assetsUrl: '/assets',
         aboutUrl: 'https://github.com/evanx/redishub/blob/master/README.md',
         helpUrl: 'https://github.com/evanx/redishub/blob/master/README.md',
         indexCommand: 'show-keyspace-config',
         //keyExpire: 2764800, // 31 days
         enrollExpire: 300,
         keyExpire: 604800, // 7 days
         ephemeralKeyExpire: 600,
         ephemeralAccountExpire: 1200,
         certLimit: 4,
         secureDomain: true,
         cliDomain: false,
         htmlDomain: true,
         registerLimit: 10,
         importLimit: 5,
         adminLimit: 1,
         defaultFormat: 'html',
         addClientIp: false
      }
   }
};
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var unirest = require('unirest');
var ExpressPeerServer = require('peer').ExpressPeerServer;

var options = {
    debug: true
}

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
  next();
});

var rooms=[];

app.use('/api', ExpressPeerServer(http, options));

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

app.get('/', function(req, res){
  res.sendFile(__dirname +'/public/landing_page.html');
});

app.get('/:roomName', function(req, res){
  activeChat=req.params.roomName;
  res.sendFile(__dirname +'/public/index.html');
});

io.on('connection', function(socket){
    //console.log(' user connected %s',socket.id);
    if(socket.user === undefined || socket.room === undefined){
      io.to(socket.id).emit("giveuser");
      //console.log("reconnect sent");
    }
    socket.on('disconnect', function(){
      socket.leave(socket.room);
       var user_idx = -1;
      if(rooms[socket.room] != undefined){
      for(var i=0;i<rooms[socket.room].user_array.length;i++){

        if(rooms[socket.room].user_array[i][0] === socket.user){
            user_idx = i;
            break;
          }
      }

      rooms[socket.room].user_array.splice(user_idx,1);
      //console.log(rooms[socket.room].user_array);

      if(rooms[socket.room].user_array.length === 0){
        delete rooms[socket.room];
      }
      io.sockets.in(socket.room).emit('usr_disconnect', socket.user);
      console.log(socket.user+" Disconnected.");
    }
    else console.log("Probable Server Restart. Disconnecting user to reconnect. user: %s room: %s",socket.user,socket.room);

    });

    socket.on('addToRoom', function (roomName){
      socket.room = roomName.room;
      socket.user = roomName.user;
      if(socket.room == ""){
        socket.room = "defaultroom";
        //console.log("added to dafultroom");
      }
      var flag=0; //NOTE: No raising race condition now
      for( var key in rooms ) {
        if( key === socket.room ){
            //console.log("Room Exists: ");
            //console.log(rooms[key]);
            flag=1;
            break;
        }
      }

      if(flag === 0){
        rooms[socket.room] = {
              name:socket.room,
              user_array:[]
        }
        rooms[socket.room].user_array.push([socket.user,socket.id]);
      }
      else{
        rooms[socket.room].user_array.push([socket.user,socket.id]);
      }
        socket.join(socket.room);
        io.sockets.in(socket.room).emit('usr_connect', rooms[socket.room].user_array);
        io.to(socket.id).emit('socket_id',{"myid":socket.id, "port":process.env.PORT});
       // console.log(socket.user+" connected.");
      });

    socket.on('chatmsg', function(msg){
      socket.broadcast.to(socket.room).emit('chatmsg',{"user":socket.user,"msg":msg});
      //console.log('%s: user %s says, %s', socket.room,socket.user, msg);
   });
/*
    socket.on('getPeerId', function(parameter){

      socket.broadcast.to(socket.room).emit('peer_id_requested',{"user":parameter.user,"from":socket.id});
      //console.log('%s: user %s says, %s', socket.room,socket.user, msg);
   });

  socket.on('TakePeerId', function(parameter){

      io.to(parameter.to).emit('id_received',parameter.id);
      console.log('id received emmited');
   });*/

     socket.on('Edit_Request', function(msg){
      socket.broadcast.to(socket.room).emit('Edit_Response', msg);
    });

    socket.on('test_code', function(msg){
           unirest.post("https://api.hackerrank.com/checker/submission.json")
          .strictSSL(false)
          .header("Content-Type", "application/x-www-form-urlencoded")
          .header("Accept", "application/json")
          .send("format=json")
          .send("lang="+ msg.lang)
          .send("source=" + encodeURIComponent(msg.src))
          .send('testcases=["'+ msg.inp +'"]')
          .send("wait=true")
          .send("api_key=")
          .end(function (result) {
            console.log(result.body);
            io.sockets.in(socket.room).emit("result",result.body);
          });

      });

});

http.listen( (process.env.PORT || 5000), function(){
  console.log('listening on port: %s',5000 );
});
<commit_msg>Refactored code.<commit_after>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

//For creating Post requests
var unirest = require('unirest');

//Peer Server Object
var ExpressPeerServer = require('peer').ExpressPeerServer;

var options = {
    debug: true
}

//Enable CORS
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
  next();
});

//Store user data in variable room
var rooms = [];

//Initialise peer server
app.use('/api', ExpressPeerServer(http, options));

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

//Get Room id from url
app.get('/:roomName', function(req, res){

  activeChat = req.params.roomName;
  res.sendFile(__dirname +'/public/chat.html');

});

//Socket.io on connection event

io.on('connection', function(socket){
    /*Check if the socket was already connected previously
      .user .room custom properties are added to the on connection.
      In cases when server fails and restarts
    */

  if(socket.user === undefined || socket.room === undefined)
    io.to(socket.id).emit("giveuser");

  //User disconnect event listener.
  socket.on('disconnect', function(){
    /*  Code:
            Remove user from socket.
            Search user in it's room and remove it from user array of the room.
            If room is empty, remove the room.
    */
    socket.leave(socket.room);
    var user_idx = -1;

    //Check if user room is lost. Common cause: Server restart.
    if(rooms[socket.room] != undefined){
      for(var i=0;i<rooms[socket.room].user_array.length;i++){
        if(rooms[socket.room].user_array[i][0] === socket.user){
          //Find user in user array. O(length)
          user_idx = i;
          break;
        }
      }

      //Remove user from user_array.
      rooms[socket.room].user_array.splice(user_idx,1);

      if(rooms[socket.room].user_array.length === 0){
        delete rooms[socket.room];
      }

      //Update people online for other users.
      io.sockets.in(socket.room).emit('user_disconnect', socket.user);

      console.log(socket.user+" disconnected.");
    }
    else
      console.log("Probable Server Restart. Disconnecting user to reconnect. user: %s room: %s",socket.user,socket.room);

  });

  socket.on('addToRoom', function (roomName){
    /*  Code:
            Add user to room.
            Add custom property .user .room to socket for later identification.
            Search if room exists. Add user.
    */

    socket.room = roomName.room;
    socket.user = roomName.user;

    var flag = 0; //NOTE: No race conditions observed now

    for( var key in rooms ) {
      if( key === socket.room ){
          flag=1;
          break;
      }
    }

    if(flag === 0){
      rooms[socket.room] = {
        name:socket.room,
        user_array:[]
      }
      rooms[socket.room].user_array.push([socket.user,socket.id]);
    }
    else{
      rooms[socket.room].user_array.push([socket.user,socket.id]);
    }

    //Add socket to provided room
    socket.join(socket.room);

    //Send user_connect msg to other users in room.
    io.sockets.in(socket.room).emit('user_connect', rooms[socket.room].user_array);

    //Send the current user it's server socket.id to use as peerjs id. Ensures uniqueness on custom server.
    io.to(socket.id).emit('socket_id',socket.id);

    console.log(socket.user+" connected.");
    });

  //Broadcast users chat message to its room.
  socket.on('chatmsg', function(msg){
    socket.broadcast.to(socket.room).emit('chatmsg',{"user":socket.user,"msg":msg});
  });

  //Recieve text user is writing in editor broadcast to other users.
  socket.on('Edit_Request', function(msg){
    socket.broadcast.to(socket.room).emit('Edit_Response', msg);
  });

  /*
      Receive code running request.
      Send data to hackerrank api using unirest.
      Send result to all users.
  */
  socket.on('test_code', function(msg){
    unirest.post("https://api.hackerrank.com/checker/submission.json")
          .strictSSL(false)
          .header("Content-Type", "application/x-www-form-urlencoded")
          .header("Accept", "application/json")
          .send("format=json")
          .send("lang="+ msg.lang)
          .send("source=" + encodeURIComponent(msg.src))
          .send('testcases=["'+ msg.inp +'"]')
          .send("wait=true")

          //Get your own api_key registering at hackerrank.com
          .send("api_key=")
          .end(function (result) {
            io.sockets.in(socket.room).emit("result",result.body);
          });

    });
});

http.listen( (process.env.PORT || 5000), function(){
  console.log('Server running');
});<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.dev.config');
var express = require('express');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// var index = require('./app/index.tdx');
var authenticate = require('./routes/authenticate');
var vsts = require('./routes/vsts');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Routes

var authRouter = express.Router({mergeParams: true});
var vstsRouter = express.Router({mergeParams: true});

// [START]
// app.get('/', index);
app.use('/authenticate', authRouter);
authRouter.use('/callback', authenticate.callback);
authRouter.use('/', authenticate.authorize);
app.use('/VSTS', vstsRouter);
// vstsRouter.use('/', vsts.listItems);
// [END]

// [START server]
var server = app.listen(process.env.PORT || '8080', '0.0.0.0', function () {
  console.log('App listening at http://%s', server);
  console.log("Press Ctrl+C to quit.");
});
// [END server]

// [START Webpack]
// var compiler = webpack(config);

// var server = new WebpackDevServer(compiler, {
//     hot: true,
//     // display no info to console (only warnings and errors)
//     noInfo: false,
//     publicPath: config.output.publicPath,
//     stats: {
//       // With console colors
//       colors: true,
//       // add the hash of the compilation
//       hash: true,
//       // add webpack version information
//       version: false,
//       // add timing information
//       timings: true,
//       // add assets information
//       assets: false,
//       // add chunk information
//       chunks: false,
//       // add built modules information to chunk information
//       chunkModules: false,
//       // add built modules information
//       modules: false,
//       // add also information about cached (not built) modules
//       cached: false,
//       // add information about the reasons why modules are included
//       reasons: false,
//       // add the source code of modules
//       source: false,
//       // add details to errors (like resolving log)
//       errorDetails: true,
//       // add the origins of chunks and chunk merging info
//       chunkOrigins: false,
//       // Add messages from child loaders
//       children: false
//     }
// });

// server.listen(3333, 'localhost', function (err) {
//   if (err) {
//     console.log(err);
//     return;
//   }

//   console.log("Listening at http://localhost:3333. Please wait, I'm building things for you...");
// });
// [END Webpack]<commit_msg>adding index<commit_after>var path = require('path');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.dev.config');
var express = require('express');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./index');
var authenticate = require('./routes/authenticate');
var vsts = require('./routes/vsts');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Routes

var authRouter = express.Router({mergeParams: true});
var vstsRouter = express.Router({mergeParams: true});

// [START]
app.get('/', index);
app.use('/authenticate', authRouter);
authRouter.use('/callback', authenticate.callback);
authRouter.use('/', authenticate.authorize);
app.use('/VSTS', vstsRouter);
// vstsRouter.use('/', vsts.listItems);
// [END]

// [START server]
var server = app.listen(process.env.PORT || '8080', '0.0.0.0', function () {
  console.log('App listening at http://%s', server);
  console.log("Press Ctrl+C to quit.");
});
// [END server]

// [START Webpack]
// var compiler = webpack(config);

// var server = new WebpackDevServer(compiler, {
//     hot: true,
//     // display no info to console (only warnings and errors)
//     noInfo: false,
//     publicPath: config.output.publicPath,
//     stats: {
//       // With console colors
//       colors: true,
//       // add the hash of the compilation
//       hash: true,
//       // add webpack version information
//       version: false,
//       // add timing information
//       timings: true,
//       // add assets information
//       assets: false,
//       // add chunk information
//       chunks: false,
//       // add built modules information to chunk information
//       chunkModules: false,
//       // add built modules information
//       modules: false,
//       // add also information about cached (not built) modules
//       cached: false,
//       // add information about the reasons why modules are included
//       reasons: false,
//       // add the source code of modules
//       source: false,
//       // add details to errors (like resolving log)
//       errorDetails: true,
//       // add the origins of chunks and chunk merging info
//       chunkOrigins: false,
//       // Add messages from child loaders
//       children: false
//     }
// });

// server.listen(3333, 'localhost', function (err) {
//   if (err) {
//     console.log(err);
//     return;
//   }

//   console.log("Listening at http://localhost:3333. Please wait, I'm building things for you...");
// });
// [END Webpack]<|endoftext|>


<commit_before>$(function() {
  var dt = {sPaginationType: 'full_numbers',
            bAutoWidth:false ,
            aaSorting: [[ 0, 'desc' ]],
            fnDrawCallback: _iconify,
  }

  if ($(window).width() <= 600) dt = $.extend({
        'bScrollCollapse': true,
        'sScrollX': '100%',
  }, dt)

  $('.robot_actions').dataTable(dt)

  $('a.add').button({ icons: { primary: 'ui-icon-plus' } })

  function _iconify() {
    $('a.view').button({ icons: { primary: 'ui-icon-search' }, text: false })
    $('a.label').button({ icons: { primary: 'ui-icon-print' }, text: false })
  }
})<commit_msg>Add responsive behaviour to table, add search box<commit_after>$(function() {
  var dt = {sPaginationType: 'full_numbers',
            bAutoWidth: false,
            aaSorting: [[ 0, 'desc' ]],
            fnDrawCallback: _iconify,
  }

  /*if ($(window).width() <= 600) dt = $.extend({
        'bScrollCollapse': true,
        'sScrollX': '100%',
  }, dt)*/

  var dt = $('.robot_actions').dataTable(dt)
  $('.table input').focus()

  $('input.search-mobile').keyup(function() {
    $('.dataTables_filter input').val($(this).val()).trigger('keyup')
  }).parent('span').addClass('enable')
  $('#sidebar,.cont_wrap').addClass('searchbox')

  $('a.add').button({ icons: { primary: 'ui-icon-plus' } })

  $(window).resize(function() { _resize() })

  function _resize() {
    $.each([2,3,5,6],function(i,n) {
      dt.fnSetColumnVis(n, !($(window).width() <= 600))
    })
  }

  _resize()

  function _iconify() {
    $('a.view').button({ icons: { primary: 'ui-icon-search' }, text: false })
    $('a.label').button({ icons: { primary: 'ui-icon-print' }, text: false })
  }
})<|endoftext|>


<commit_before>// A safer console object - see github.com/nathanl/consolation
safe_console = {
  enabled: false,
  original_console: (function(){
    // If the browser has no usable one, define a no-op
    return (typeof(window.console === 'object') && typeof(window.console.log) === 'function') ? window.console : {log: function(){}};
  })(),
  __args_to_array: function(args) { return Array.prototype.slice.call(args); },
  __caller_location: function() {
    var caller  = (new Error).stack.split("\n")[3];
    // The strings! Oh, the horrifying strings!
    var cleaned = caller.split('/').pop().split(':').slice(0,2).join(':').replace(/\s+/gi, ' ').replace(' at ', '');
    return cleaned;
  }
};

(function(){
  // Metaprogramming in JS! Wooooooooooooooo
  logging_methods = ['log', 'debug', 'info', 'error', 'warn'];
  methods         = ['dir', 'group', 'groupCollapsed', 'groupEnd', 'time', 'timeEnd', 'trace'].concat(logging_methods);
  for (i = 0; i < methods.length; i++) {
    method_name = methods[i];
    (function(method_name){
      safe_console[method_name] = function() {
        if (!this.enabled) { return; }
        var args = arguments;
        // Tack on the caller location if this is a logging method
        if (logging_methods.indexOf(method_name) !== -1) {
          var called_from = this.__caller_location();
          args            = this.__args_to_array(arguments).concat("(" + called_from + ")");
        }
        this.original_console[method_name].apply(this.original_console, args);
      };
    }
    )(method_name);
  }
})();

// In case we missed any methods: inherit, regardless of `enabled` switch
safe_console.__proto__ = safe_console.original_console;

// Recklessly cautious!
window.console = safe_console;
<commit_msg>Improved browser compatibility Show call location in Chrome and Firefox Fail gracefully at showing call location in Safari<commit_after>// A safer console object - see github.com/nathanl/consolation
safe_console = {
  enabled: false,
  original_console: (function(){
    // If the browser has no usable one, define a no-op
    return (typeof(window.console === 'object') && typeof(window.console.log) === 'function') ? window.console : {log: function(){}};
  })(),
  __args_to_array: function(args) { return Array.prototype.slice.call(args); },
  __caller_location: function() {
    var call_locations, current_position, caller, file_and_line;
    try {
    call_locations   = (new Error).stack.split("\n");
    current_position = call_locations[0].match(/Error/) ? 3 : 2;
    caller           = call_locations[current_position];
    file_and_line    = caller.match(/\/([^\/]*$)/)[1];
    } catch (err) {
      file_and_line = 'location not supported by browser';
    }
    return file_and_line;
  }
};

(function(){
  // Metaprogramming in JS! Wooooooooooooooo
  logging_methods = ['log', 'debug', 'info', 'error', 'warn'];
  methods         = ['dir', 'group', 'groupCollapsed', 'groupEnd', 'time', 'timeEnd', 'trace'].concat(logging_methods);
  for (i = 0; i < methods.length; i++) {
    method_name = methods[i];
    (function(method_name){
      safe_console[method_name] = function() {
        if (!this.enabled) { return; }
        var args = arguments;
        // Tack on the caller location if this is a logging method
        if (logging_methods.indexOf(method_name) !== -1) {
          var called_from = this.__caller_location();
          args            = this.__args_to_array(arguments).concat("(" + called_from + ")");
        }
        this.original_console[method_name].apply(this.original_console, args);
      };
    }
    )(method_name);
  }
})();

// In case we missed any methods: inherit, regardless of `enabled` switch
safe_console.__proto__ = safe_console.original_console;

// Recklessly cautious!
window.console = safe_console;
<|endoftext|>


<commit_before>define([
    'underscore',
    'leaflet',
    'knockout',
    'knockout-mapping',
    'viewmodels/widget',
    'views/components/iiif-annotation',
    'geojson-extent',
    'leaflet-fullscreen'
], function(_, L, ko, koMapping, WidgetViewModel, IIIFAnnotationViewmodel, geojsonExtent) {
    return ko.components.register('iiif-widget', {
        viewModel: function(params) {
            var self = this;

            params.configKeys = ['defaultManifest'];
            WidgetViewModel.apply(this, [params]);

            if (params.widget) params.widgets = [params.widget];
            if (!params.manifest) params.manifest = this.defaultManifest();

            IIIFAnnotationViewmodel.apply(this, [params]);

            if (params.state === 'report') {
                this.canvasConfigs = [];
                var canvases = {};
                var value = koMapping.toJS(params.value);
                if (value && value.features) {
                    value.features.forEach(function(feature) {
                        if (!canvases[feature.properties.canvas]) canvases[feature.properties.canvas] = [];
                        canvases[feature.properties.canvas].push(feature);
                    });
                }
                _.forEach(canvases, function(features, canvas) {
                    self.canvasConfigs.push({
                        center: [0, 0],
                        crs: L.CRS.Simple,
                        zoom:  0,
                        afterRender: function(map) {
                            L.tileLayer.iiif(canvas + '/info.json').addTo(map);
                            var featureCollection = {
                                type: 'FeatureCollection',
                                features: features
                            };
                            var extent = geojsonExtent(featureCollection);
                            map.addLayer(L.geoJson(featureCollection, {
                                pointToLayer: function(feature, latlng) {
                                    return L.circleMarker(latlng, {
                                        color: feature.properties.color,
                                        fillColor: feature.properties.fillColor,
                                        weight: feature.properties.weight,
                                        radius: feature.properties.radius,
                                        opacity: feature.properties.opacity,
                                        fillOpacity: feature.properties.fillOpacity
                                    });
                                },
                                style: function(feature) {
                                    return {
                                        color: feature.properties.color,
                                        fillColor: feature.properties.fillColor,
                                        weight: feature.properties.weight,
                                        radius: feature.properties.radius,
                                        opacity: feature.properties.opacity,
                                        fillOpacity: feature.properties.fillOpacity
                                    };
                                }
                            }));
                            L.control.fullscreen().addTo(map);
                            setTimeout(function() {
                                if (features.length === 1 && features[0].geometry.type === 'Point') {
                                    var coords = features[0].geometry.coordinates;
                                    map.panTo([coords[1], coords[0]]);
                                } else {
                                    map.fitBounds([
                                        [extent[1], extent[0]],
                                        [extent[3], extent[2]]
                                    ]);
                                }
                            }, 250);
                        }
                    });
                });
            }

            this.manifest.subscribe(function(manifest) {
                if (manifest !== self.defaultManifest())
                    self.defaultManifest(manifest);
            });

            this.defaultManifest.subscribe(function(manifest) {
                if (manifest !== self.manifest())
                    self.manifest(manifest);
            });
        },
        template: { require: 'text!templates/views/components/widgets/iiif.htm' }
    });
});
<commit_msg>refactors and improves iiif report display<commit_after>define([
    'underscore',
    'leaflet',
    'knockout',
    'knockout-mapping',
    'viewmodels/widget',
    'views/components/iiif-annotation',
    'geojson-extent',
    'leaflet-fullscreen'
], function(_, L, ko, koMapping, WidgetViewModel, IIIFAnnotationViewmodel, geojsonExtent) {
    return ko.components.register('iiif-widget', {
        viewModel: function(params) {
            var self = this;

            params.configKeys = ['defaultManifest'];
            WidgetViewModel.apply(this, [params]);

            if (params.widget) params.widgets = [params.widget];
            if (!params.manifest) params.manifest = this.defaultManifest();

            IIIFAnnotationViewmodel.apply(this, [params]);

            if (params.state === 'report') {
                this.canvasConfigs = [];
                var canvases = {};
                var value = koMapping.toJS(params.value);
                if (value && value.features) {
                    value.features.forEach(function(feature) {
                        if (!canvases[feature.properties.canvas]) canvases[feature.properties.canvas] = [];
                        canvases[feature.properties.canvas].push(feature);
                    });
                }
                _.forEach(canvases, function(features, canvas) {
                    self.canvasConfigs.push({
                        center: [0, 0],
                        crs: L.CRS.Simple,
                        zoom:  0,
                        afterRender: function(map) {
                            L.tileLayer.iiif(canvas + '/info.json').addTo(map);
                            var featureCollection = {
                                type: 'FeatureCollection',
                                features: features
                            };
                            var extent = geojsonExtent(featureCollection);
                            map.addLayer(L.geoJson(featureCollection, {
                                pointToLayer: function(feature, latlng) {
                                    return L.circleMarker(latlng, feature.properties);
                                },
                                style: function(feature) {
                                    return feature.properties;
                                }
                            }));
                            L.control.fullscreen().addTo(map);
                            setTimeout(function() {
                                map.fitBounds([
                                    [extent[1]-1, extent[0]-1],
                                    [extent[3]+1, extent[2]+1]
                                ]);
                            }, 250);
                        }
                    });
                });
            }

            this.manifest.subscribe(function(manifest) {
                if (manifest !== self.defaultManifest())
                    self.defaultManifest(manifest);
            });

            this.defaultManifest.subscribe(function(manifest) {
                if (manifest !== self.manifest())
                    self.manifest(manifest);
            });
        },
        template: { require: 'text!templates/views/components/widgets/iiif.htm' }
    });
});
<|endoftext|>


<commit_before>'use strict';
const DEBUG = !!process.env.PORTAL_DEBUG,
	PORTAL_DEBUG_CONTROLLERS = !!process.env.PORTAL_DEBUG_CONTROLLERS,
	fiber = require('carbonfibers'),
	ObjectId = fiber.mongo.ObjectID,
	fs = fiber.fs,
	slice = Array.prototype.slice,
	hasOwn = Object.prototype.hasOwnProperty,
	toString = Object.prototype.toString,
	ServerError = require('./errors').ServerError,
	colorBold = '\x1B[1m',
	colorGrey = '\x1B[90m',
	colorRed = '\x1B[31m',
	colorYellow = '\x1B[33m',
	colorWhite = '\x1B[37m',
	colorGreen = '\x1B[32m',
	colorCyan = '\x1B[1m\x1B[36m',
	colorReset = '\x1B[0m';
function Name(string) {
	return (('' + (string || '')).toLowerCase().replace(/[^a-z0-9]/g, ''));
}
function PathName(string) {
	return (('' + (string || '')).toLowerCase().replace(/[^a-z0-9\/]/g, '').replace(/\/+/g, '/'));
}
function allKeys(object) {
	const keys = [];
	for (let key in object) {
		// get all keys, not just top level prototype with hasOwnProperty
		keys.push(key);
	}
	return keys;
}
function sequence(next, fn) {
	function sequence() {
		return fn.apply(this,
			(next ?
				slice.call(next.apply(this, arguments)) :
				arguments));
	}
	return sequence;
}
function ModelApplier(functions) {
	function applier() {
		const args = slice.call(arguments),
			length = functions.length;
		let index = 0; while (index < length) {
			args[index] = functions[index].call(this, args[index]);
			index += 1;
		}
		return args;
	}
	return applier;
}
function Model(name, models, functions) {
	let signature = [];
	function lookupModel(model) {
		if (model instanceof Function) {
			signature.push('fn');
			return model;
		}
		signature.push('"' + colorCyan + model + colorReset + '"');
		if (typeof model === 'string') {
			if (!models[Name(model)]) {
				throw new Error(name + ' -> ' + signature.join(' -> ') + 'not found in\n{ ' + allKeys(models).join(', ') + ' }');
			}
			let modelSequence = Model(name + ' -> ' + signature.join(' -> '), models, models[Name(model)]);
			signature.push(modelSequence.signature);
			return modelSequence;
		}
		console.log(model)
		throw new Error(name + ' -> ' + signature.join(' -> ') + 'not a function, or model name string');
	}
	const sequenceFn = ((Array.isArray(functions) ? functions : [functions])
		.map(lookupModel)
		.reduce(sequence));
	sequenceFn.signature = '(' + signature.join(' -> ') + ')';
	return sequenceFn;
}
function Method(name, methods, models, functions) {
	let signature = [];
	function lookupMethod(method) {
		if (method instanceof Function) {
			signature.push('fn');
			return method;
		}
		if (Array.isArray(method)) {
			const modelFunctions = method.map(Model.bind(this, name + ' -> ' + signature.join(' -> '), models)),
				modelApplier = ModelApplier(modelFunctions);
			modelApplier.signature = '[ ' + modelFunctions.map(function (fn) { return fn.signature; }).join(', ') + ' ]';
			signature.push(modelApplier.signature);
			return modelApplier;
		}
		signature.push('"' + colorCyan + method + colorReset + '"');
		if (typeof method === 'string') {
			if (!methods[Name(method)]) {
				throw new Error(name + ' -> ' + signature.join(' -> ') + 'not found in\n{ ' + allKeys(methods).join(', ') + ' }');
			}
			let methodSequence = Method(name + ' -> ' + signature.join(' -> '), methods, models, methods[Name(method)]);
			signature.push(methodSequence.signature);
			return methodSequence;
		}
		throw new Error(name + ' -> ' + signature.join(' -> ') + 'not a function, models array, or method name string');
	}
	const sequenceFn = ((Array.isArray(functions) ? functions : [functions])
		.map(lookupMethod)
		.reduce(sequence));
	sequenceFn.signature = '(' + signature.join(' -> ') + ')';
	return sequenceFn;
}
function dummy(object) {
	const dummy = Object.create(object);
	let method = '';
	for (method in object) {
		const meth = method;
		if ('function' === typeof object[meth]) {
			dummy[meth] = function () {
				var promise = fiber();
				setTimeout(function () {
					if (meth === 'find') {
						promise.fulfill(null, []);
					} else if (meth === 'mget') {
						promise.fulfill(null, []);
					} else {
						promise.fulfill(null);
					}
				});
				return promise;
			};
		}
	}
	return dummy;
}
function isModuleNotFound(error) {
	if (!error || error.code !== 'MODULE_NOT_FOUND') { throw error; }
}
module.exports = function(pkg) {
	var baseController = {
		mixins: ['base'],
		models: {
			Object: Object,
			Array: Function.prototype.call.bind(Array.prototype.slice),
			String: String,
			Boolean: Boolean
		}
	};
	function lookupController(directory, name) {
		try {
			return require(directory + name.replace(/\./g, '/') + '.controller');
		} catch (error) {
			isModuleNotFound(error);
		}
	}
	Controller.prototype.__proto__ = pkg;
	function Controller(options) {
		if (!(this instanceof Controller)) { return new Controller(options); }
		const mixins = [],
			self = this;
		function findMixins(options) {
			if ('string' === typeof options) {
				options = lookupController(pkg.dirname + '/controllers/', options)
					|| lookupController(pkg.server.dirname + '/controllers/', options)
					|| lookupController(__dirname + '/controllers/', options);
				if (!options) { throw new Error('Mixin Not Found: ' + pkg.name + '/' + options); }
			}
			if (Array.isArray(options.mixins)) {
				options.mixins.forEach(function (mixin) {
					findMixins(mixin);
				});
			} else if (options.mixins) {
				findMixins(options.mixins);
			}
			mixins.push(options);
		}
		findMixins(options);
		mixins.forEach(function (options) {
			Object.keys(options).forEach(function (propertyName) {
				self[propertyName] = options[propertyName];
			}.bind(self));
		}.bind(self));
		self.collection = self.collection || self.namespace.replace(/^\/|\/$/g, '').replace(/\//g, '_');
		self.server = pkg.server;
		self.package = pkg;
		self.models = Object.create(null);
		self.methods = Object.create(null);
		self.api = Object.create(null);
		if (options === baseController) {
			self.__proto__ = pkg;
		} else {
			if ('string' === typeof options.inherits) {
				const controllerOptions = lookupController(pkg.dirname + '/controllers/', options.inherits)
					|| lookupController(pkg.server.dirname + '/controllers/', options.inherits)
					|| lookupController(__dirname + '/controllers/', options.inherits);
				if (!controllerOptions) { throw new Error('Mixin Not Found: ' + pkg.name + '/' + options.inherits); }
				self.__proto__ = new Controller(controllerOptions);
			} else {
				self.__proto__ = new Controller(options.inherits || baseController);
			}
			self.models.__proto__ = self.__proto__.models;
			self.methods.__proto__ = self.__proto__.methods;
			self.api.__proto__ = self.__proto__.api;
		}
		mixins.forEach(function (options) {
			Object.keys(options.models || {}).forEach(function (modelName) {
				self.models[Name(modelName)] = self.models[modelName] = options.models[modelName];
			});
			Object.keys(options.methods || {}).forEach(function (methodName) {
				self.methods[Name(methodName)] = self.methods[methodName] = options.methods[methodName];
			});
			Object.keys(options.api || {}).forEach(function (apiName) {
				self.api[PathName(apiName)] = options.api[apiName];
			});
		});
		Object.keys(self.models).forEach(function (modelName) {
			self.models[modelName] = Model(self.package.name + ' ' + self.namespace + ' models{} -> ' + modelName + ' -> ', self.models, self.models[modelName]);
		});
		Object.keys(self.methods).forEach(function (methodName) {
			self.methods[methodName] = Method(self.package.name + ' ' + self.namespace + ' methods{} -> ' + methodName + ' -> ', self.methods, self.models, self.methods[methodName]);
		});
		Object.keys(self.api).forEach(function (apiName) {
			self.api[apiName] = Method(self.package.name + ' ' + self.namespace + ' api{} -> ' + apiName + ' -> ', self.methods, self.models, self.api[apiName]);
		});
		mixins.forEach(function (options) {
			if (hasOwn.call(options, 'constructor') && options.constructor instanceof Function && options.constructor !== Object) {
				options.constructor.call(self, options);
			}
		});
		if (this.initialization) {
			this.initialization();
		}
		this.server.tests.push(fiber(function(callback) {
			let method = '',
				testInstance = Object.create(this);
			testInstance.session = { user: {}, permissions: {}, };
			testInstance.permits = function () { return true; };
			if (this.package.mongo) {
				testInstance.mongo = {
					get: function (collectionName) {
						return dummy(this.package.mongo.get(collectionName));
					}.bind(this),
					oid: this.package.mongo.oid,
				};
			}
			testInstance.redis = dummy(testInstance.redis);
			for (method in this.api) {
				try {
					output.apply(testInstance, (this.api[method].apply(testInstance, input([]))));
				} catch(error) {
					if (!(error instanceof ServerError)) {
						/*useful*/ console.log('TEST FAIL:', pkg.name, this.namespace, method, ' -> ', (this.api[method]||{}).signature, '\n' + colorRed, error, error.stack, colorReset);
						// console.log('TEST FAIL:', pkg.name, this.namespace, method, error, error.stack);
						throw error;
					}
				}
			}
		}.bind(this)).fork());
	}
	Controller.prototype.get = get;
	function get(name) {
		const
			path = PathName(name);
		name = Name(name);
		return (
			this.api[path] ||
			this.methods[name] ||
			this.models[name] ||
			this[name] ||
			function () {}).bind(this);
	}
	function input(object) {
		var i, key, copy, array;
		if (object && ('object' === typeof object)) {
			if (object instanceof ObjectId) {
				return '' + object;
			}
			if (Array.isArray(object)) {
				array = [];
				i = 0;
				while (i < object.length) {
					array[i] = input(object[i]);
					i += 1;
				}
				return array;
			}
			copy = {};
			key = '';
			for (key in object) {
				if (hasOwn.call(object, key) && !/^_/.test(key)) {
					copy[key] = input(object[key]);
				}
			}
			return copy;
		}
		return object;
	}
	baseController.models.input = input;
	function output(object) {
		var i, key, copy, array;
		if (object && ('object' === typeof object)) {
			if (object instanceof ObjectId) {
				return '' + object;
			}
			if (Array.isArray(object)) {
				array = [];
				i = 0;
				while (i < object.length) {
					array[i] = output(object[i]);
					i += 1;
				}
				return array;
			}
			copy = {};
			key = '';
			for (key in object) {
				if ((hasOwn.call(object, key) && !/^__|\./.test(key))) {
					copy[key] = output(object[key]);
				}
			}
			return copy;
		}
		return object;
	}
	baseController.models.output = output;
	fs.readdirc(pkg.paths.controllers).wait()
		.filter(function (filename) {
			return /\.controller\.\w+$/.test(filename);
		})
		.forEach(function (fileName) {
			const controllerName = fileName.substring(pkg.paths.controllers.length).replace(/\.controller\.\w+$/, ''),
				options = require(fileName);
			if(!options.namespace) { options.namespace = ('/' + controllerName + '/').replace(/^\/*|\/+$/g, '/'); }
			this.controllers[options.namespace] = Controller(options);
			if (PORTAL_DEBUG_CONTROLLERS) {
				/*useful*/ console.log(pkg.name + ':' + controllerName + ' loaded for namespace ' + options.namespace + '\n\t(' + colorYellow + Object.keys(this.controllers[options.namespace].api).join(colorReset + ', ' + colorYellow) + colorReset + ')');
			}
		}.bind(pkg));
}
module.exports.Name = Name;
module.exports.PathName = PathName;
<commit_msg>moved the this.get function<commit_after>'use strict';
const DEBUG = !!process.env.PORTAL_DEBUG,
	PORTAL_DEBUG_CONTROLLERS = !!process.env.PORTAL_DEBUG_CONTROLLERS,
	fiber = require('carbonfibers'),
	ObjectId = fiber.mongo.ObjectID,
	fs = fiber.fs,
	slice = Array.prototype.slice,
	hasOwn = Object.prototype.hasOwnProperty,
	toString = Object.prototype.toString,
	ServerError = require('./errors').ServerError,
	colorBold = '\x1B[1m',
	colorGrey = '\x1B[90m',
	colorRed = '\x1B[31m',
	colorYellow = '\x1B[33m',
	colorWhite = '\x1B[37m',
	colorGreen = '\x1B[32m',
	colorCyan = '\x1B[1m\x1B[36m',
	colorReset = '\x1B[0m';
function Name(string) {
	return (('' + (string || '')).toLowerCase().replace(/[^a-z0-9]/g, ''));
}
function PathName(string) {
	return (('' + (string || '')).toLowerCase().replace(/[^a-z0-9\/]/g, '').replace(/\/+/g, '/'));
}
function allKeys(object) {
	const keys = [];
	for (let key in object) {
		// get all keys, not just top level prototype with hasOwnProperty
		keys.push(key);
	}
	return keys;
}
function sequence(next, fn) {
	function sequence() {
		return fn.apply(this,
			(next ?
				slice.call(next.apply(this, arguments)) :
				arguments));
	}
	return sequence;
}
function ModelApplier(functions) {
	function applier() {
		const args = slice.call(arguments),
			length = functions.length;
		let index = 0; while (index < length) {
			args[index] = functions[index].call(this, args[index]);
			index += 1;
		}
		return args;
	}
	return applier;
}
function Model(name, models, functions) {
	let signature = [];
	function lookupModel(model) {
		if (model instanceof Function) {
			signature.push('fn');
			return model;
		}
		signature.push('"' + colorCyan + model + colorReset + '"');
		if (typeof model === 'string') {
			if (!models[Name(model)]) {
				throw new Error(name + ' -> ' + signature.join(' -> ') + 'not found in\n{ ' + allKeys(models).join(', ') + ' }');
			}
			let modelSequence = Model(name + ' -> ' + signature.join(' -> '), models, models[Name(model)]);
			signature.push(modelSequence.signature);
			return modelSequence;
		}
		console.log(model)
		throw new Error(name + ' -> ' + signature.join(' -> ') + 'not a function, or model name string');
	}
	const sequenceFn = ((Array.isArray(functions) ? functions : [functions])
		.map(lookupModel)
		.reduce(sequence));
	sequenceFn.signature = '(' + signature.join(' -> ') + ')';
	return sequenceFn;
}
function Method(name, methods, models, functions) {
	let signature = [];
	function lookupMethod(method) {
		if (method instanceof Function) {
			signature.push('fn');
			return method;
		}
		if (Array.isArray(method)) {
			const modelFunctions = method.map(Model.bind(this, name + ' -> ' + signature.join(' -> '), models)),
				modelApplier = ModelApplier(modelFunctions);
			modelApplier.signature = '[ ' + modelFunctions.map(function (fn) { return fn.signature; }).join(', ') + ' ]';
			signature.push(modelApplier.signature);
			return modelApplier;
		}
		signature.push('"' + colorCyan + method + colorReset + '"');
		if (typeof method === 'string') {
			if (!methods[Name(method)]) {
				throw new Error(name + ' -> ' + signature.join(' -> ') + 'not found in\n{ ' + allKeys(methods).join(', ') + ' }');
			}
			let methodSequence = Method(name + ' -> ' + signature.join(' -> '), methods, models, methods[Name(method)]);
			signature.push(methodSequence.signature);
			return methodSequence;
		}
		throw new Error(name + ' -> ' + signature.join(' -> ') + 'not a function, models array, or method name string');
	}
	const sequenceFn = ((Array.isArray(functions) ? functions : [functions])
		.map(lookupMethod)
		.reduce(sequence));
	sequenceFn.signature = '(' + signature.join(' -> ') + ')';
	return sequenceFn;
}
function dummy(object) {
	const dummy = Object.create(object);
	let method = '';
	for (method in object) {
		const meth = method;
		if ('function' === typeof object[meth]) {
			dummy[meth] = function () {
				var promise = fiber();
				setTimeout(function () {
					if (meth === 'find') {
						promise.fulfill(null, []);
					} else if (meth === 'mget') {
						promise.fulfill(null, []);
					} else {
						promise.fulfill(null);
					}
				});
				return promise;
			};
		}
	}
	return dummy;
}
function isModuleNotFound(error) {
	if (!error || error.code !== 'MODULE_NOT_FOUND') { throw error; }
}
module.exports = function(pkg) {
	var baseController = {
		mixins: ['base'],
		models: {
			Object: Object,
			Array: Function.prototype.call.bind(Array.prototype.slice),
			String: String,
			Boolean: Boolean
		}
	};
	function lookupController(directory, name) {
		try {
			return require(directory + name.replace(/\./g, '/') + '.controller');
		} catch (error) {
			isModuleNotFound(error);
		}
	}
	Controller.prototype.__proto__ = pkg;
	function Controller(options) {
		if (!(this instanceof Controller)) { return new Controller(options); }
		const mixins = [],
			self = this;
		function findMixins(options) {
			if ('string' === typeof options) {
				options = lookupController(pkg.dirname + '/controllers/', options)
					|| lookupController(pkg.server.dirname + '/controllers/', options)
					|| lookupController(__dirname + '/controllers/', options);
				if (!options) { throw new Error('Mixin Not Found: ' + pkg.name + '/' + options); }
			}
			if (Array.isArray(options.mixins)) {
				options.mixins.forEach(function (mixin) {
					findMixins(mixin);
				});
			} else if (options.mixins) {
				findMixins(options.mixins);
			}
			mixins.push(options);
		}
		findMixins(options);
		mixins.forEach(function (options) {
			Object.keys(options).forEach(function (propertyName) {
				self[propertyName] = options[propertyName];
			}.bind(self));
		}.bind(self));
		self.collection = self.collection || self.namespace.replace(/^\/|\/$/g, '').replace(/\//g, '_');
		self.server = pkg.server;
		self.package = pkg;
		self.models = Object.create(null);
		self.methods = Object.create(null);
		self.api = Object.create(null);
		if (options === baseController) {
			self.__proto__ = pkg;
		} else {
			if ('string' === typeof options.inherits) {
				const controllerOptions = lookupController(pkg.dirname + '/controllers/', options.inherits)
					|| lookupController(pkg.server.dirname + '/controllers/', options.inherits)
					|| lookupController(__dirname + '/controllers/', options.inherits);
				if (!controllerOptions) { throw new Error('Mixin Not Found: ' + pkg.name + '/' + options.inherits); }
				self.__proto__ = new Controller(controllerOptions);
			} else {
				self.__proto__ = new Controller(options.inherits || baseController);
			}
			self.models.__proto__ = self.__proto__.models;
			self.methods.__proto__ = self.__proto__.methods;
			self.api.__proto__ = self.__proto__.api;
		}
		mixins.forEach(function (options) {
			Object.keys(options.models || {}).forEach(function (modelName) {
				self.models[Name(modelName)] = self.models[modelName] = options.models[modelName];
			});
			Object.keys(options.methods || {}).forEach(function (methodName) {
				self.methods[Name(methodName)] = self.methods[methodName] = options.methods[methodName];
			});
			Object.keys(options.api || {}).forEach(function (apiName) {
				self.api[PathName(apiName)] = options.api[apiName];
			});
		});
		Object.keys(self.models).forEach(function (modelName) {
			self.models[modelName] = Model(self.package.name + ' ' + self.namespace + ' models{} -> ' + modelName + ' -> ', self.models, self.models[modelName]);
		});
		Object.keys(self.methods).forEach(function (methodName) {
			self.methods[methodName] = Method(self.package.name + ' ' + self.namespace + ' methods{} -> ' + methodName + ' -> ', self.methods, self.models, self.methods[methodName]);
		});
		Object.keys(self.api).forEach(function (apiName) {
			self.api[apiName] = Method(self.package.name + ' ' + self.namespace + ' api{} -> ' + apiName + ' -> ', self.methods, self.models, self.api[apiName]);
		});
		mixins.forEach(function (options) {
			if (hasOwn.call(options, 'constructor') && options.constructor instanceof Function && options.constructor !== Object) {
				options.constructor.call(self, options);
			}
		});
		this.get = function (name) {
			const
				path = PathName(name);
			name = Name(name);
			return (
				this.api[path] ||
				this.methods[name] ||
				this.models[name] ||
				this[name] ||
				function () {}).bind(this);
		}
		if (this.initialization) {
			this.initialization();
		}
		this.server.tests.push(fiber(function(callback) {
			let method = '',
				testInstance = Object.create(this);
			testInstance.session = { user: {}, permissions: {}, };
			testInstance.permits = function () { return true; };
			if (this.package.mongo) {
				testInstance.mongo = {
					get: function (collectionName) {
						return dummy(this.package.mongo.get(collectionName));
					}.bind(this),
					oid: this.package.mongo.oid,
				};
			}
			testInstance.redis = dummy(testInstance.redis);
			for (method in this.api) {
				try {
					output.apply(testInstance, (this.api[method].apply(testInstance, input([]))));
				} catch(error) {
					if (!(error instanceof ServerError)) {
						/*useful*/ console.log('TEST FAIL:', pkg.name, this.namespace, method, ' -> ', (this.api[method]||{}).signature, '\n' + colorRed, error, error.stack, colorReset);
						// console.log('TEST FAIL:', pkg.name, this.namespace, method, error, error.stack);
						throw error;
					}
				}
			}
		}.bind(this)).fork());
	}
	function input(object) {
		var i, key, copy, array;
		if (object && ('object' === typeof object)) {
			if (object instanceof ObjectId) {
				return '' + object;
			}
			if (Array.isArray(object)) {
				array = [];
				i = 0;
				while (i < object.length) {
					array[i] = input(object[i]);
					i += 1;
				}
				return array;
			}
			copy = {};
			key = '';
			for (key in object) {
				if (hasOwn.call(object, key) && !/^_/.test(key)) {
					copy[key] = input(object[key]);
				}
			}
			return copy;
		}
		return object;
	}
	baseController.models.input = input;
	function output(object) {
		var i, key, copy, array;
		if (object && ('object' === typeof object)) {
			if (object instanceof ObjectId) {
				return '' + object;
			}
			if (Array.isArray(object)) {
				array = [];
				i = 0;
				while (i < object.length) {
					array[i] = output(object[i]);
					i += 1;
				}
				return array;
			}
			copy = {};
			key = '';
			for (key in object) {
				if ((hasOwn.call(object, key) && !/^__|\./.test(key))) {
					copy[key] = output(object[key]);
				}
			}
			return copy;
		}
		return object;
	}
	baseController.models.output = output;
	fs.readdirc(pkg.paths.controllers).wait()
		.filter(function (filename) {
			return /\.controller\.\w+$/.test(filename);
		})
		.forEach(function (fileName) {
			const controllerName = fileName.substring(pkg.paths.controllers.length).replace(/\.controller\.\w+$/, ''),
				options = require(fileName);
			if(!options.namespace) { options.namespace = ('/' + controllerName + '/').replace(/^\/*|\/+$/g, '/'); }
			this.controllers[options.namespace] = Controller(options);
			if (PORTAL_DEBUG_CONTROLLERS) {
				/*useful*/ console.log(pkg.name + ':' + controllerName + ' loaded for namespace ' + options.namespace + '\n\t(' + colorYellow + Object.keys(this.controllers[options.namespace].api).join(colorReset + ', ' + colorYellow) + colorReset + ')');
			}
		}.bind(pkg));
}
module.exports.Name = Name;
module.exports.PathName = PathName;
<|endoftext|>