<commit_before>var express = require('express'),
	fs= require('fs'),
	https =require('spdy'),
	bodyParser = require('body-parser'),
	cookieParser = require('cookie-parser'),
	request= require('request'),
	MongoClient = require('mongodb').MongoClient,
	compression = require('compression'),
	helmet = require('helmet'),
	mongo=require(__dirname+'/myModules/mongoFunctions.js'),
	setTime = require(__dirname+'/myModules/setTime.js'),
	mangeUsers = require(__dirname+'/myModules/manageUsers.js'),
	session = require(__dirname + '/myModules/userSession.js'),
	link = require(__dirname+'/myModules/fbLinks.js'),
	config = require(__dirname+'/myModules/config'),
	messenger = require(__dirname+'/myModules/messengerBot.js'),
	webhook = require(__dirname+'/myModules/webhookEvents.js'),
	myFunc = require(__dirname+'/myModules/zsoServerComunication.js');

var app = express();
var cookie = new session.sessionCreator();
var sessionList = {};

//set up certificates for HTTPS
var opts = {
	// Specify the key file for the server
	key: fs.readFileSync('cert/wsskey.pem'),
	// Specify the certificate file
	cert: fs.readFileSync('cert/wsscert.pem'),
	// Specify the Certificate Authority certificate
	ca: fs.readFileSync('cert/cacert.pem'),
};

//set up express app
var time = new setTime();
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false })); // for parsing
app.use(cookieParser());
app.use(compression()); //use gzip compression
app.use(helmet()); //Set http headers to protect from eg. clickjacking

//setting cookie on first login
app.use(function (req, res, next) {
  // check if client sent cookie
    var cookie = req.cookies.cookieName;
    if (cookie === undefined){
        // no: set a new cookie
        var randomNumber=Math.random().toString();
        randomNumber=randomNumber.substring(2,randomNumber.length);
        res.cookie('cookieName',randomNumber, { maxAge: 1000*60*60*24*30, httpOnly: true });
        console.log('cookie created successfully');
    }
    else{
    // yes, cookie was already present
        console.log('cookie exists', cookie);
    }
    next(); // <-- important!
});

app.get('/login', function (req, res) {
    console.log('Asking for login');
    var login=link.loginAttempt('');
    //check cookie or something
    console.log(login);
    res.redirect(login);
});

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

app.get('/index', function (req, res) {
    res.sendFile( __dirname + '/public/substitutionPage.htm');
});

app.get('/demo/:id', function (req, res) {
    res.setHeader("X-Frame-Options", "ALLOW-FROM https://www.messenger.com/");
    res.setHeader("X-Frame-Options", "ALLOW-FROM https://www.facebook.com/");
    res.sendFile(__dirname + '/demo/' + req.params.id);
});

app.post('/login', function (req, res) {
   console.log('Asking for login');
    var login=link.loginAttempt('');
    //check cookie or something
    console.log(login);
    res.redirect(login);
});

app.get('/webhook', function(req, res) {
	if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === config.webhookToken) {
		console.log("Validating webhook");
		res.status(200).send(req.query['hub.challenge']);
	} else {
		console.error("Failed validation. Make sure the validation tokens match.");
		res.sendStatus(403);
	}
});

app.post('/webhook', function (req, res) {
var data = req.body;
    //console.log('hey');
// Make sure this is a page subscription
if (data.object === 'page') {
	// Iterate over each entry - there may be multiple if batched
	data.entry.forEach(function(entry) {
		var pageID = entry.id;
		var timeOfEvent = entry.time;
		// Iterate over each messaging event
        //console.log('entry',entry)
		entry.messaging.forEach(function(event) {
            //console.log("any event",event);
			if (event.message) {
                if(event.message["is_echo"]==true){
                    webhook.echo(event);
                    //console.log("any event",event);
                }
                else
				webhook.message(event);
			} else if (event.postback) {
				messenger.receivedPostback(event);
			}else if (event.delivery) {
                webhook.delivered(event);
                //console.log('delivery');
				//messenger.receivedPostback(event);
			} else if (event.optin) {
				messenger.sTMB(event);
			} else {
				//console.log("Webhook received unknown event: ", event);
			}
		});
	});
	//send 200 within 20s to inform Facebook that message was received successfully
	res.sendStatus(200);
	}
});

app.post('/postCall',function(req,res){
    var reqCookie=req.cookies.cookieName;
    var userId=cookie.findIfSessionExist(reqCookie);
    console.log('user session: ',userId);
    console.log('Mode: '+req.body['mode']);
    console.log('user session: ',userId);
	mangeUsers.postCall(userId,req.body,function(resText){
		if(userId == '0000' && req.body['mode'] == 'getSettings'){
			res.send(JSON.stringify({err:true,message:"Please log in using your Facebook account",params:resText}));
		}
		else{
			res.send(JSON.stringify({err:false,message:"",params:resText}));
		}
	})
})

app.get('/redirect', function(req, res){
	var reqCookie=req.cookies.cookieName;
	console.log('redirect');
    console.log('if declined',req.query['error']);
	if(req.query['error']){
		console.log('im here');
		res.redirect('/index');
	}
	else{
		mangeUsers.redirect(req,function(id){
			console.log('idd',id);
			if(id == undefined){
				res.send('Problem logging in. Try again.');
			}
			else{
				cookie.addNewSession(id,reqCookie);
				res.redirect('/index');
			}
		});
	}
});

app.get('/deredirect', function(req, res){
	console.log('deredirect');
	console.log('deredirect',req.body);
});

//Dynamically generate iframe with Send To Messenger button
app.get('/STMbtn', function(req, res){ //respond to GET request on /STMbtn
	var reqCookie = req.cookies.cookieName;  //get session cookie (named "cookieName")
	var userId = cookie.findIfSessionExist(reqCookie); //get user id assigned to session cookie
	if(userId == '0000'){ //send "please log in" message if user is not logged in
		res.send(`<!DOCTYPE html>
Please log in to enable Messenger notifications
`);
	} else { //if user is logged in send "Send To Messenger" button with his id as param
		console.log("Loading Send To Messenger button for user with id", userId);
		var ifrTS = `<!DOCTYPE html><html><body><script>window.fbAsyncInit = function() {FB.init({appId: "` + config.clientId + `",xfbml: true,version: "v2.6"});};(function(d, s, id){var js, fjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)){ return; }js = d.createElement(s); js.id = id;js.src = "//connect.facebook.net/en_US/sdk.js";fjs.parentNode.insertBefore(js, fjs);}(document, 'script', 'facebook-jssdk'));</script><div class="fb-send-to-messenger" color="blue" size="xlarge" messenger_app_id="` + config.clientId + `" data-ref="` + userId + `" page_id="` + config.pageId + `">
`;
		res.send(ifrTS);
	}
})

setInterval(function(){
    time.tommorowIs();
    myFunc.subs(time.displayTime(),function(y){
        time.todayIs();
        myFunc.subs(time.displayTime(),function(b){
            time.theDayAfterTomorrowIs();
            myFunc.subs(time.displayTime(),function(x){
                console.log('downloaded changes');
            });
        });
    });
}, 1000*60*10); //now running once per 10 minutes

setTimeout(function () {
	time.tommorowIs();
    myFunc.subs(time.displayTime(),function(y){
        time.todayIs();
        myFunc.subs(time.displayTime(),function(b){
            time.theDayAfterTomorrowIs();
            myFunc.subs(time.displayTime(),function(x){
                console.log('downloaded changes');
            });
        });
    });
}, 1000); //download substitutions 1 second after start

setTimeout(function(){
	cookie.deleteOld();
},1000*60*60*24*30); //remove cookies (session) after 30 days

https.createServer(opts, app).listen(9001);
console.log('Started');

function mongoTest(){
	MongoClient.connect('mongodb://localhost:27017/test2', function(err, db) {
		var collection = db.collection('substitutions');
		collection.find({}).forEach(function(f){console.log("hi",f)});
	});
}
<commit_msg>disable cookies for some https requests<commit_after>var express = require('express'),
	fs= require('fs'),
	https =require('spdy'),
	bodyParser = require('body-parser'),
	cookieParser = require('cookie-parser'),
	request= require('request'),
	MongoClient = require('mongodb').MongoClient,
	compression = require('compression'),
	helmet = require('helmet'),
	mongo=require(__dirname+'/myModules/mongoFunctions.js'),
	setTime = require(__dirname+'/myModules/setTime.js'),
	mangeUsers = require(__dirname+'/myModules/manageUsers.js'),
	session = require(__dirname + '/myModules/userSession.js'),
	link = require(__dirname+'/myModules/fbLinks.js'),
	config = require(__dirname+'/myModules/config'),
	messenger = require(__dirname+'/myModules/messengerBot.js'),
	webhook = require(__dirname+'/myModules/webhookEvents.js'),
	myFunc = require(__dirname+'/myModules/zsoServerComunication.js');

var app = express();
var cookie = new session.sessionCreator();
var sessionList = {};

//set up certificates for HTTPS
var opts = {
	// Specify the key file for the server
	key: fs.readFileSync('cert/wsskey.pem'),
	// Specify the certificate file
	cert: fs.readFileSync('cert/wsscert.pem'),
	// Specify the Certificate Authority certificate
	ca: fs.readFileSync('cert/cacert.pem'),
};

//set up express app
var time = new setTime();
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false })); // for parsing
app.use(cookieParser());
app.use(compression()); //use gzip compression
app.use(helmet()); //Set http headers to protect from eg. clickjacking

//setting cookie on first login
app.use(function (req, res, next) {
    var disabled=['/webhook','/dataflow','/login'];
    if (disabled.indexOf(req.path) != -1)
        return next();
    //check if client sent cookie
    var cookie = req.cookies.cookieName;
    if (cookie === undefined){
        // no: set a new cookie
        var randomNumber=Math.random().toString();
        randomNumber=randomNumber.substring(2,randomNumber.length);
        res.cookie('cookieName',randomNumber, { maxAge: 1000*60*120, httpOnly: false });
        console.log('cookie created successfully');
    }
    else{
    // yes, cookie was already present
        console.log('cookie exists', cookie);
    }
    next(); // <-- important!
});

app.get('/login', function (req, res) {
    console.log('Asking for login');
    var login=link.loginAttempt('');
    //check cookie or something
    console.log(login);
    res.redirect(login);
});

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

app.get('/index', function (req, res) {
    res.sendFile( __dirname + '/public/substitutionPage.htm');
});

app.get('/demo/:id', function (req, res) {
    res.setHeader("X-Frame-Options", "ALLOW-FROM https://www.messenger.com/");
    res.setHeader("X-Frame-Options", "ALLOW-FROM https://www.facebook.com/");
    res.sendFile(__dirname + '/demo/' + req.params.id);
});

app.post('/login', function (req, res) {
   console.log('Asking for login');
    var login=link.loginAttempt('');
    //check cookie or something
    console.log(login);
    res.redirect(login);
});

app.get('/webhook', function(req, res) {
	if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === config.webhookToken) {
		console.log("Validating webhook");
		res.status(200).send(req.query['hub.challenge']);
	} else {
		console.error("Failed validation. Make sure the validation tokens match.");
		res.sendStatus(403);
	}
});

app.post('/webhook', function (req, res) {
var data = req.body;
    //console.log('hey');
// Make sure this is a page subscription
if (data.object === 'page') {
	// Iterate over each entry - there may be multiple if batched
	data.entry.forEach(function(entry) {
		var pageID = entry.id;
		var timeOfEvent = entry.time;
		// Iterate over each messaging event
        //console.log('entry',entry)
		entry.messaging.forEach(function(event) {
            //console.log("any event",event);
			if (event.message) {
                if(event.message["is_echo"]==true){
                    webhook.echo(event);
                    //console.log("any event",event);
                }
                else
				webhook.message(event);
			} else if (event.postback) {
				messenger.receivedPostback(event);
			}else if (event.delivery) {
                webhook.delivered(event);
                //console.log('delivery');
				//messenger.receivedPostback(event);
			} else if (event.optin) {
				messenger.sTMB(event);
			} else {
				//console.log("Webhook received unknown event: ", event);
			}
		});
	});
	//send 200 within 20s to inform Facebook that message was received successfully
	res.sendStatus(200);
	}
});

app.post('/postCall',function(req,res){
    var reqCookie=req.cookies.cookieName;
    var userId=cookie.findIfSessionExist(reqCookie);
    console.log('user session: ',userId);
    console.log('Mode: '+req.body['mode']);
    console.log('user session: ',userId);
	mangeUsers.postCall(userId,req.body,function(resText){
		if(userId == '0000' && req.body['mode'] == 'getSettings'){
			res.send(JSON.stringify({err:true,message:"Please log in using your Facebook account",params:resText}));
		}
		else{
			res.send(JSON.stringify({err:false,message:"",params:resText}));
		}
	})
})

app.get('/redirect', function(req, res){
	var reqCookie=req.cookies.cookieName;
	console.log('redirect');
    console.log('if declined',req.query['error']);
	if(req.query['error']){
		console.log('im here');
		res.redirect('/index');
	}
	else{
		mangeUsers.redirect(req,function(id){
			console.log('idd',id);
			if(id == undefined){
				res.send('Problem logging in. Try again.');
			}
			else{
				cookie.addNewSession(id,reqCookie);
				res.redirect('/index');
			}
		});
	}
});

app.get('/deredirect', function(req, res){
	console.log('deredirect');
	console.log('deredirect',req.body);
});

//Dynamically generate iframe with Send To Messenger button
app.get('/STMbtn', function(req, res){ //respond to GET request on /STMbtn
	var reqCookie = req.cookies.cookieName;  //get session cookie (named "cookieName")
	var userId = cookie.findIfSessionExist(reqCookie); //get user id assigned to session cookie
	if(userId == '0000'){ //send "please log in" message if user is not logged in
		res.send(`<!DOCTYPE html>
Please log in to enable Messenger notifications
`);
	} else { //if user is logged in send "Send To Messenger" button with his id as param
		console.log("Loading Send To Messenger button for user with id", userId);
		var ifrTS = `<!DOCTYPE html><html><body><script>window.fbAsyncInit = function() {FB.init({appId: "` + config.clientId + `",xfbml: true,version: "v2.6"});};(function(d, s, id){var js, fjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)){ return; }js = d.createElement(s); js.id = id;js.src = "//connect.facebook.net/en_US/sdk.js";fjs.parentNode.insertBefore(js, fjs);}(document, 'script', 'facebook-jssdk'));</script><div class="fb-send-to-messenger" color="blue" size="xlarge" messenger_app_id="` + config.clientId + `" data-ref="` + userId + `" page_id="` + config.pageId + `">
`;
		res.send(ifrTS);
	}
})

setInterval(function(){
    time.tommorowIs();
    myFunc.subs(time.displayTime(),function(y){
        time.todayIs();
        myFunc.subs(time.displayTime(),function(b){
            time.theDayAfterTomorrowIs();
            myFunc.subs(time.displayTime(),function(x){
                console.log('downloaded changes');
            });
        });
    });
}, 1000*60*10); //now running once per 10 minutes

setTimeout(function () {
	time.tommorowIs();
    myFunc.subs(time.displayTime(),function(y){
        time.todayIs();
        myFunc.subs(time.displayTime(),function(b){
            time.theDayAfterTomorrowIs();
            myFunc.subs(time.displayTime(),function(x){
                console.log('downloaded changes');
            });
        });
    });
}, 1000); //download substitutions 1 second after start

setTimeout(function(){
	cookie.deleteOld();
},1000*60*60*24*30); //remove cookies (session) after 30 days

https.createServer(opts, app).listen(9001);
console.log('Started');

function mongoTest(){
	MongoClient.connect('mongodb://localhost:27017/test2', function(err, db) {
		var collection = db.collection('substitutions');
		collection.find({}).forEach(function(f){console.log("hi",f)});
	});
}
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash')
const Trailpack = require('trailpack')
const lib = require('./lib')

/**
 * Hapi Trailpack
 *
 * @class Hapi
 * @see {@link http://trailsjs.io/doc/trailpack
 *
 * Bind application routes to Hapi.js (from trailpack-router)
 */
module.exports = class Hapi extends Trailpack {

  /**
   * Ensure that config/web is valid, and that no other competing web
   * server trailpacks are installed (e.g. express)
   */
  validate () {
    if (_.contains(_.keys(this.app.packs), 'express4', 'koa', 'koa2', 'restify')) {
      return Promise.reject(new Error('There is another web services trailpack installed that conflicts with trailpack-hapi!'))
    }

    return Promise.all([
      lib.Validator.validateWebConfig(this.app.config.web)
    ])
  }

  /**
   * Start Hapi Server
   */
  initialize () {
    const server = lib.Server.createServer(this.app.config)

    lib.Server.registerPlugins(this.app, server)
    lib.Server.registerMethods(this.app, server)
    lib.Server.registerRoutes(this.app, server)
    lib.Server.registerViews(this.app, server)

    return lib.Server.start(server)
  }

  constructor (app, config) {
    super(app, {
      config: require('./config'),
      api: require('./api'),
      pkg: require('./package')
    })
  }
}

<commit_msg>[api] expose "server" property on pack<commit_after>'use strict'

const _ = require('lodash')
const Trailpack = require('trailpack')
const lib = require('./lib')

/**
 * Hapi Trailpack
 *
 * @class Hapi
 * @see {@link http://trailsjs.io/doc/trailpack
 *
 * Bind application routes to Hapi.js (from trailpack-router)
 */
module.exports = class Hapi extends Trailpack {

  /**
   * Ensure that config/web is valid, and that no other competing web
   * server trailpacks are installed (e.g. express)
   */
  validate () {
    if (_.contains(_.keys(this.app.packs), 'express4', 'koa', 'koa2', 'restify')) {
      return Promise.reject(new Error('There is another web services trailpack installed that conflicts with trailpack-hapi!'))
    }

    return Promise.all([
      lib.Validator.validateWebConfig(this.app.config.web)
    ])
  }

  /**
   * Start Hapi Server
   */
  initialize () {
    this.server = lib.Server.createServer(this.app.config)

    lib.Server.registerPlugins(this.app, this.server)
    lib.Server.registerMethods(this.app, this.server)
    lib.Server.registerRoutes(this.app, this.server)
    lib.Server.registerViews(this.app, this.server)

    return lib.Server.start(this.server)
  }

  constructor (app, config) {
    super(app, {
      config: require('./config'),
      api: require('./api'),
      pkg: require('./package')
    })
  }
}

<|endoftext|>


<commit_before>var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var port = process.env.PORT || 8080;
var request = ('request');

app.use('/', express.static(__dirname+ '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.get('/censor', function(req, res) {
    console.log(req.query);
    var url = req.query.url;
    var filter = req.query.filter;
    console.log(url);

    res.json({
        success: true
    });

});

var server = app.listen(port, function(cb) {
    var port = server.address().port;
    console.log('Listening on port http://localhost:%s', port);
});

<commit_msg>making love to the world by creating conceptextractor<commit_after>var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var port = process.env.PORT || 8080;
var conceptExtractor = require('./utils/conceptExtractor')

app.use('/', express.static(__dirname+ '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.get('/censor', function(req, res) {
    var url = req.query.url;
    var filter = JSON.parse(req.query.filter);
    console.log(url);
    console.log("filter: ", filter);
    conceptExtractor.extractConcept(url, filter, function(){
        res.json({
            success: true
        });
    });
});

var server = app.listen(port, function(cb) {
    var port = server.address().port;
    console.log('Listening on port http://localhost:%s', port);
});

<|endoftext|>


<commit_before>const express = require("express"),
favicon = require('express-favicon'),
app = express();

NODE_ENV="production";

app.use(favicon(__dirname + '/favicon.png'));

app.engine('ejs', require('ejs').renderFile);
app.set('view engine', 'ejs');

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

app.get('/', function (req, res, next) {
  res.render('home.ejs',{});
  next();
});

app.get('*',function(req,res,next){
  if(!res.headerSent){
    if(res.status(404)){
      res.render('404.ejs',{
        location: "404"
      });
    }
  }
});

app.listen(process.env.PORT || 8003, function () {
  console.log('Example app listening on port 80!', process.env.PORT );
});
<commit_msg>Heroku<commit_after>const express = require("express"),
favicon = require('express-favicon'),
app = express();

NODE_ENV="production";

app.use(favicon(__dirname + '/favicon.png'));

app.engine('ejs', require('ejs').renderFile);
app.set('view engine', 'ejs');

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

app.get('/', function (req, res, next) {
  res.render('home.ejs',{});
  next();
});

app.get('*',function(req,res,next){
  if(!res.headerSent){
    if(res.status(404)){
      res.render('404.ejs',{
        location: "404"
      });
    }
  }
});

app.listen(process.env.PORT || 8003, function () {
  console.log('Example app listening on port 80!', process.env.PORT );
});
<|endoftext|>


<commit_before><commit_msg>11111<commit_after><|endoftext|>


<commit_before>var fs = require('fs'),
    path = require('path'),
    dir = path.dirname(require.main.filename);

var envFile = fs.readFileSync(dir + path.sep + '.env', 'utf8');
var envArray = envFile.split('\n');

envArray.forEach(function(envKeyVal) {
    if(envKeyVal.length == 0) return;
    var key = envKeyVal.split('=')[0].trim(),
        val = envKeyVal.split('=')[1].trim();
    process.env[key] = val;
}, this);<commit_msg>handle invalid rows<commit_after>var fs = require('fs'),
    path = require('path'),
    dir = path.dirname(require.main.filename);

var envFile = fs.readFileSync(dir + path.sep + '.env', 'utf8');
var envArray = envFile.split('\n');

envArray.forEach(function(envKeyVal) {
    if(envKeyVal.length == 0 || envKeyVal.indexOf('=') == -1) return;
    var key = envKeyVal.split('=')[0].trim(),
        val = envKeyVal.split('=')[1].trim();
    process.env[key] = val;
}, this);<|endoftext|>


<commit_before>function start() {
	//load elements
	svg = document.getElementsByTagName("svg")[0];
	sprite = svg.getElementById("sprite");
	highscore = 0;
	jump = false;
	jump_x = 2;
	var x = parseInt(sprite.getAttribute("cx").slice(0,-1));
	var r1 = makeRect(-15, 5);
	var r2 = makeRect(-30, 5);
	var r3 = makeRect(-60,10);
	var r4 = makeRect(-95, 5);
	var r5 = makeRect(-150, 40);
	moveSprite(2, 0.1, x, false, [r1, r2, r3, r4, r5]);
			//velocity, gravity, x, side, rects
}

function resetScore() {
	var score_box = svg.getElementById("score")
	score_box.textContent = 0;
	score_box.style.opacity = 0.7;
	score_box.setAttributeNS(null, "fill", "#FF0000");
	window.setTimeout(function() {
		score_box.style.opacity = 0.3;
		score_box.setAttributeNS(null, "fill", "#FFFFFF");
	}, 500);
}

function getRandom(min, max) {
	return Math.floor(Math.random() * (max + min + 1) + min);
}

function makeRect(y, h) {
	var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
	rect.setAttributeNS(null, "x", "49%");
	rect.setAttributeNS(null, "y", y + "%");
	rect.setAttributeNS(null, "width", "2%");
	rect.setAttributeNS(null, "height", h +"%");
	rect.setAttributeNS(null, "fill", "#FFFFFF");
	svg.appendChild(rect);
	return rect;
}

function moveRects(rects) {
	for (var i = 0; i < rects.length; i++) {
		var cur_y =  parseInt(rects[i].getAttributeNS(null, "y").slice(0, -1));
		if (cur_y > 100){
			//give the rectangle that moved off the board a random height and y value above the screen
			var new_height = getRandom(5, 15);
			rects[i].setAttributeNS(null, "height", new_height + "%");
			rects[i].setAttributeNS(null, "y", 0 - getRandom(0, 100) - new_height + "%");
		} else {
			rects[i].setAttributeNS(null, "y", cur_y + 1 + "%");
		}
	}
	return rects;
}

function isInBounds(x, velocity) {
	//return true if sprite is in bounds
	if (0 < x + velocity && x + velocity < 100) {
		return true;
	} else {
		return false;
	}
}

function didCollide(rects) {
	//checks rects against the sprite's y coordinate (75)
	//returns true if sprite and rects collided
	for (var i = 0; i < rects.length; i++) {
		var ry = parseInt(rects[i].getAttributeNS(null, "y").slice(0, -1));
		var rh = ry + parseInt(rects[i].getAttributeNS(null, "height").slice(0, -1));
		if (ry <= 75 && rh >= 75) {
			return true;
		}
	}
	return false;
}

function setHighscore(score) {
	var highscore_box = svg.getElementById("highscore");
	highscore_box.textContent = "Highscore: " + score;
}

function setScore(rects) {
	//if no collision, score + 1
	if (!didCollide(rects)) {
		var score_box = svg.getElementById("score");
		var score = parseInt(score_box.textContent) + 1;
		score_box.textContent = score;
		if (score > highscore) {
			setHighscore(score);
			highscore = score;
		}
	} else {
		resetScore();
	}
}

function moveSprite(velocity, gravity, x, left_side, rects) {
	//moves sprite, requestAnimationFrame calls this function repetedly
	if (x < 50) {
		//sprite is on left side
		if (left_side !== true) {
			//apply score if not yet applied
			left_side = true;
			setScore(rects);
		}
		//keep in bounds
		if (!isInBounds(x, velocity)) {
			velocity = Math.abs(velocity) + gravity;
		}else {
			velocity += gravity;
		}
		//if jump on left side
		if (velocity > 0 && jump) {
			//if going towards center, move sprite towards bounds
			velocity -= jump_x;
			jump = false;
		}else if (jump) {
			//if going towards bounds, move sprite towards center
			velocity = -jump_x/2;
			jump = false;
		}
	} else {
		//sprite on right side
		if (left_side !== false) {
			//apply score if not yet applied
			left_side = false;
			setScore(rects);
		}
		//keep in bounds
		if (!isInBounds(x, velocity)) {
			velocity = -(velocity) - gravity;
		} else {
			velocity -= gravity;
		}
		//if jump on right side
		if (jump && velocity < 0) {
			//if going towards center, move in opposite direction
			velocity += jump_x;
			jump = false;
		} else if (jump) {
			//if going towards bounds, move in opposite direction
			velocity = jump_x/2;
			jump = false;
		}
	}

	//set new position
	sprite.setAttribute("cx", (x + velocity) + "%");

	window.requestAnimationFrame( function() {
		moveSprite(velocity, gravity, (x + velocity), left_side, moveRects(rects));
	});
}

function entry() {
	jump = true;
}

document.onkeyup = function(e) {
	//jump on spacebar
	if (e.keyCode == 32) {
		entry();
	}
}
<commit_msg>Get rid of unnecessary variable in moveRects<commit_after>function start() {
	//load elements
	svg = document.getElementsByTagName("svg")[0];
	sprite = svg.getElementById("sprite");
	highscore = 0;
	jump = false;
	jump_x = 2;
	var x = parseInt(sprite.getAttribute("cx").slice(0,-1));
	var r1 = makeRect(-15, 5);
	var r2 = makeRect(-30, 5);
	var r3 = makeRect(-60,10);
	var r4 = makeRect(-95, 5);
	var r5 = makeRect(-150, 40);
	moveSprite(2, 0.1, x, false, [r1, r2, r3, r4, r5]);
			//velocity, gravity, x, side, rects
}

function resetScore() {
	var score_box = svg.getElementById("score")
	score_box.textContent = 0;
	score_box.style.opacity = 0.7;
	score_box.setAttributeNS(null, "fill", "#FF0000");
	window.setTimeout(function() {
		score_box.style.opacity = 0.3;
		score_box.setAttributeNS(null, "fill", "#FFFFFF");
	}, 500);
}

function getRandom(min, max) {
	return Math.floor(Math.random() * (max + min + 1) + min);
}

function makeRect(y, h) {
	var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
	rect.setAttributeNS(null, "x", "49%");
	rect.setAttributeNS(null, "y", y + "%");
	rect.setAttributeNS(null, "width", "2%");
	rect.setAttributeNS(null, "height", h +"%");
	rect.setAttributeNS(null, "fill", "#FFFFFF");
	svg.appendChild(rect);
	return rect;
}

function moveRects(rects) {
	for (var i = 0; i < rects.length; i++) {
		var cur_y =  parseInt(rects[i].getAttributeNS(null, "y").slice(0, -1));
		if (cur_y > 100){
			rects[i].setAttributeNS(null, "height", getRandom(5, 20) + "%");
			rects[i].setAttributeNS(null, "y", 0 - getRandom(20, 70) + "%");
		} else {
			rects[i].setAttributeNS(null, "y", cur_y + 1 + "%");
		}
	}
	return rects;
}

function isInBounds(x, velocity) {
	if (0 < x + velocity && x + velocity < 100) {
		return true;
	} else {
		return false;
	}
}

function didCollide(rects) {
	//checks rects against the sprite's y coordinate (75)
	for (var i = 0; i < rects.length; i++) {
		var ry = parseInt(rects[i].getAttributeNS(null, "y").slice(0, -1));
		var rh = ry + parseInt(rects[i].getAttributeNS(null, "height").slice(0, -1));
		if (ry <= 75 && rh >= 75) {
			return true;
		}
	}
	return false;
}

function setHighscore(score) {
	var highscore_box = svg.getElementById("highscore");
	highscore_box.textContent = "Highscore: " + score;
}

function setScore(rects) {
	if (!didCollide(rects)) {
		var score_box = svg.getElementById("score");
		var score = parseInt(score_box.textContent) + 1;
		score_box.textContent = score;
		if (score > highscore) {
			setHighscore(score);
			highscore = score;
		}
	} else {
		resetScore();
	}
}

function moveSprite(velocity, gravity, x, left_side, rects) {
	if (x < 50) {
		//sprite is on left side
		if (left_side !== true) {
			//apply score if not yet applied
			left_side = true;
			setScore(rects);
		}
		//keep in bounds
		if (!isInBounds(x, velocity)) {
			velocity = Math.abs(velocity) + gravity;
		}else {
			velocity += gravity;
		}
		//if jump on left side
		if (velocity > 0 && jump) {
			//if going towards center, move sprite towards bounds
			velocity -= jump_x;
			jump = false;
		}else if (jump) {
			//if going towards bounds, move sprite towards center
			velocity = -jump_x/2;
			jump = false;
		}
	} else {
		//sprite on right side
		if (left_side !== false) {
			//apply score if not yet applied
			left_side = false;
			setScore(rects);
		}
		//keep in bounds
		if (!isInBounds(x, velocity)) {
			velocity = -(velocity) - gravity;
		} else {
			velocity -= gravity;
		}
		//if jump on right side
		if (jump && velocity < 0) {
			//if going towards center, move in opposite direction
			velocity += jump_x;
			jump = false;
		} else if (jump) {
			//if going towards bounds, move in opposite direction
			velocity = jump_x/2;
			jump = false;
		}
	}

	sprite.setAttribute("cx", (x + velocity) + "%");

	window.requestAnimationFrame( function() {
		moveSprite(velocity, gravity, (x + velocity), left_side, moveRects(rects));
	});
}

function entry() {
	jump = true;
	return false;
}

document.onkeyup = function(e) {
	if (e.keyCode == 32) {
		entry();
	}
}
<|endoftext|>


<commit_before>module.exports = (function() {

    function _random(min, max) {
        return Math.round(min + (Math.random() * (max - min)));
    }

    function _createNode(tag, attrs) {
        var node = document.createElement(tag);

        for(var attrName in attrs) {
            if(attrs.hasOwnProperty(attrName)) {
                node.setAttribute(attrName, attrs[attrName]);
            }
        }

        return node;
    }

    function _createArray(len) {
        return ((len * 10) - 1).toString(10).split('');
    }

    function randomDOM(root, amount, maxDepth, maxPerLevel, maxAttrs, tags, attrs) {
        if(amount > Math.pow(maxPerLevel, maxDepth)) {
            throw 'it is not possible to create ' + amount + ' nodes with ' + maxDepth + ' depth and ' + maxPerLevel + ' nodes per level';
        }

        var current = root;
        var currentDepth = 0;
        var goDeeper;
        var tag;
        var currentAttrs;
        var tagsLen = tags.length;
        var attrsNames = Object.keys(attrs);
        var attrsLen = attrsNames.length;

        function _drawAttrs() {
            var attrIndex = _random(0, attrsLen - 1);
            var attrsValues = attrs[attrsNames[attrIndex]];

            currentAttrs[attrsNames[attrIndex]] = attrsValues[_random(0, attrsValues.length - 1)];
        }

        while(amount) {
            tag = tags[_random(0, tagsLen - 1)];
            currentAttrs = { };
            _createArray(Math.ceil(_random(0, maxAttrs))).forEach(_drawAttrs);

            goDeeper = _random(0, maxDepth) > currentDepth;

            if(goDeeper || !currentDepth) {
                currentDepth++;

                if(current.children.length < maxPerLevel) {
                    current.appendChild(current = _createNode(tag, currentAttrs));
                } else {
                    current = current.children[_random(0, current.children.length - 1)];

                    continue;
                }
            } else {
                if(current.parentNode.children.length < maxPerLevel) {
                    current.parentNode.appendChild(current = _createNode(tag, currentAttrs));
                } else if(currentDepth) {
                    current = current.parentNode;

                    currentDepth--;

                    continue;
                } else {
                    current = current.children[_random(0, current.children.length - 1)];

                    currentDepth++;

                    continue;
                }
            }

            amount--;
        }

        return root;
    }

    return randomDOM;

})();
<commit_msg>fix create array function<commit_after>module.exports = (function() {

    function _random(min, max) {
        return Math.round(min + (Math.random() * (max - min)));
    }

    function _createNode(tag, attrs) {
        var node = document.createElement(tag);

        for(var attrName in attrs) {
            if(attrs.hasOwnProperty(attrName)) {
                node.setAttribute(attrName, attrs[attrName]);
            }
        }

        return node;
    }

    function _createArray(length, defaultValue) {
        var arr = [ ];

        while(length) {
            arr[--length] = defaultValue;
        }

        return arr;
    }

    function randomDOM(root, amount, maxDepth, maxPerLevel, maxAttrs, tags, attrs) {
        if(amount > Math.pow(maxPerLevel, maxDepth)) {
            throw 'it is not possible to create ' + amount + ' nodes with ' + maxDepth + ' depth and ' + maxPerLevel + ' nodes per level';
        }

        var current = root;
        var currentDepth = 0;
        var goDeeper;
        var tag;
        var currentAttrs;
        var tagsLen = tags.length;
        var attrsNames = Object.keys(attrs);
        var attrsLen = attrsNames.length;

        function _drawAttrs() {
            var attrIndex = _random(0, attrsLen - 1);
            var attrsValues = attrs[attrsNames[attrIndex]];

            currentAttrs[attrsNames[attrIndex]] = attrsValues[_random(0, attrsValues.length - 1)];
        }

        while(amount) {
            tag = tags[_random(0, tagsLen - 1)];
            currentAttrs = { };
            _createArray(Math.ceil(_random(0, maxAttrs))).forEach(_drawAttrs);

            goDeeper = _random(0, maxDepth) > currentDepth;

            if(goDeeper || !currentDepth) {
                currentDepth++;

                if(current.children.length < maxPerLevel) {
                    current.appendChild(current = _createNode(tag, currentAttrs));
                } else {
                    current = current.children[_random(0, current.children.length - 1)];

                    continue;
                }
            } else {
                if(current.parentNode.children.length < maxPerLevel) {
                    current.parentNode.appendChild(current = _createNode(tag, currentAttrs));
                } else if(currentDepth) {
                    current = current.parentNode;

                    currentDepth--;

                    continue;
                } else {
                    current = current.children[_random(0, current.children.length - 1)];

                    currentDepth++;

                    continue;
                }
            }

            amount--;
        }

        return root;
    }

    return randomDOM;

})();
<|endoftext|>


<commit_before>import mysql from 'mysql'
import path from 'path'
import fs from 'fs'

const getInsertValues = (values) => {
  const valuesArray = []

  for (let key in values) {
    valuesArray.push('`' + key + '` = ' + mysql.escape(values[key]))
  }

  return valuesArray.join()
}

const sqlWhere = (where) => {
  if (!where) return

  const whereArray = []

  for (let key in where) {
    whereArray.push('`' + key + '` = ' + mysql.escape(where[key]))
  }

  return 'WHERE ' + whereArray.join(' AND ')
}

class MySql {
  constructor (options = { host: 'localhost' }) {
    this.connection = mysql.createConnection(options)
    this.sqlPath = options.sqlPath || './sql'
  }

  select (sql, values = {}) {
    const _this = this

    return new Promise((res, rej) => {
      _this.connection.query(sql, values, (err, rows, fields) => {
        if (err) {
          rej(err)
        } else {
          res(rows, fields)
        }
      })
    })
  }

  selectFile (filename, values = {}) {
    const _this = this

    // Get full path
    const filePath = path.resolve(path.join(
      this.sqlPath,
      filename + (path.extname(filename) === '.sql' ? '' : '.sql')
    ))

    return new Promise((res, rej) => {
      // Read file and execute as SQL statement
      fs.readFile(filePath, 'utf8', (err, sql) => {
        if (err) {
          rej('Cannot find: ' + err.path)
        } else {
          sql = sql.replace(/\n*$/m, ' ').replace(/ $/, '')
          _this.select(sql, values).then(res).catch(rej)
        }
      })
    })
  }

  insert (table, values = {}) {
    const _this = this
    const sql = `INSERT INTO \`${table}\` SET ${getInsertValues(values)}`

    return new Promise((res, rej) => {
      _this.connection.query(sql, (err, rows, fields) => {
        if (err) {
          rej(err)
        } else {
          res(rows.insertId)
        }
      })
    })
  }

  update (table, values, where) {
    const _this = this
    const sql = `UPDATE \`${table}\` SET ${getInsertValues(values)} ${sqlWhere(where)}`

    return new Promise((res, rej) => {
      _this.connection.query(sql, (err, rows, fields) => {
        if (err) {
          rej(err)
        } else {
          res(rows.affectedRows)
        }
      })
    })
  }
}

export default MySql
<commit_msg>use result instead of rows for consistency<commit_after>import mysql from 'mysql'
import path from 'path'
import fs from 'fs'

const getInsertValues = (values) => {
  const valuesArray = []

  for (let key in values) {
    valuesArray.push('`' + key + '` = ' + mysql.escape(values[key]))
  }

  return valuesArray.join()
}

const sqlWhere = (where) => {
  if (!where) return

  const whereArray = []

  for (let key in where) {
    whereArray.push('`' + key + '` = ' + mysql.escape(where[key]))
  }

  return 'WHERE ' + whereArray.join(' AND ')
}

class MySql {
  constructor (options = { host: 'localhost' }) {
    this.connection = mysql.createConnection(options)
    this.sqlPath = options.sqlPath || './sql'
  }

  select (sql, values = {}) {
    const _this = this

    return new Promise((res, rej) => {
      _this.connection.query(sql, values, (err, rows, fields) => {
        if (err) {
          rej(err)
        } else {
          res(rows, fields)
        }
      })
    })
  }

  selectFile (filename, values = {}) {
    const _this = this

    // Get full path
    const filePath = path.resolve(path.join(
      this.sqlPath,
      filename + (path.extname(filename) === '.sql' ? '' : '.sql')
    ))

    return new Promise((res, rej) => {
      // Read file and execute as SQL statement
      fs.readFile(filePath, 'utf8', (err, sql) => {
        if (err) {
          rej('Cannot find: ' + err.path)
        } else {
          sql = sql.replace(/\n*$/m, ' ').replace(/ $/, '')
          _this.select(sql, values).then(res).catch(rej)
        }
      })
    })
  }

  insert (table, values = {}) {
    const _this = this
    const sql = `INSERT INTO \`${table}\` SET ${getInsertValues(values)}`

    return new Promise((res, rej) => {
      _this.connection.query(sql, (err, result, fields) => {
        if (err) {
          rej(err)
        } else {
          res(result.insertId)
        }
      })
    })
  }

  update (table, values, where) {
    const _this = this
    const sql = `UPDATE \`${table}\` SET ${getInsertValues(values)} ${sqlWhere(where)}`

    return new Promise((res, rej) => {
      _this.connection.query(sql, (err, result) => {
        if (err) {
          rej(err)
        } else {
          res(result.affectedRows)
        }
      })
    })
  }
}

export default MySql
<|endoftext|>


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

app.get('/', function (req, res)
{
  res.send('hello world')
})

// app.post('/webhook/', funtion(req, res) {
// 	res.send('hello world');
// })

app.listen(process.env.PORT);<commit_msg>Added express and ports<commit_after>var express = require('express');
var app = express();

app.set('port', (process.env.PORT || 5000));

app.get('/', function (req, res)
{
  res.send('hello world')
})

// app.post('/webhook/', funtion(req, res) {
// 	res.send('hello world');
// })

app.listen(app.get('port'), function() {
    console.log("Node app is running at localhost:" + app.get('port'))
});<|endoftext|>


<commit_before>
'use strict';

/**
 * Module dependencies.
 */

const route = require('koa-route');
const compose = require('koa-compose');
const debug = require('debug')('koa-route-dispatcher');

module.exports = function dispatcher(maps, controllerPath) {
  var middleware = [];

  controllerPath = controllerPath.toString() || require('path').dirname(require.main.filename) + '/controllers/';
  maps = (maps instanceof Array) ? maps : [];

  maps.forEach(function (map) {
    debug('Add route map: %j', map);

    let method = (map.method || map.method == '') ? map.method.toLowerCase() : 'all';
    let path = map.path || '';
    let controller = map.controller || '';
    let opts = map.opts;
    let func;
    let module;

    if ('' === path || '' === controller) {
      throw Error('Cannot read \'controller or path\' (map: ' + JSON.stringify(map) + ')');
    }

    if ('string' == typeof controller) {
      controller = controller.split('.');

      try {
        module = require(controllerPath + controller.shift());
      } catch (err) {
        err.message += ' (module path: ' + __dirname + ' )';
        console.error(err.stack);
        return;
      }

      while (func = controller.shift()) {
        if (module[func]) {
          module = module[func];
        } else {
          throw ReferenceError('function is not defined (controller: ' + map.controller + ')');
        }
      }
    } else {
      module = controller;
    }

    if ('GeneratorFunction' !== module.constructor.name) {
      throw TypeError('dispatcher\'s controller requires a generator function (controller: ' + map.controller + ')');
    }

    middleware.push(route[method](path, module, opts));
  });

  return compose(middleware);
};
<commit_msg>controller path : process cwd<commit_after>
'use strict';

/**
 * Module dependencies.
 */

const route = require('koa-route');
const compose = require('koa-compose');
const debug = require('debug')('koa-route-dispatcher');

module.exports = function dispatcher(maps, controllerPath) {
  var middleware = [];

  controllerPath = controllerPath.toString() || process.cwd() + '/controllers/';
  maps = (maps instanceof Array) ? maps : [];

  maps.forEach(function (map) {
    debug('Add route map: %j', map);

    let method = (map.method || map.method == '') ? map.method.toLowerCase() : 'all';
    let path = map.path || '';
    let controller = map.controller || '';
    let opts = map.opts;
    let func;
    let module;

    if ('' === path || '' === controller) {
      throw Error('Cannot read \'controller or path\' (map: ' + JSON.stringify(map) + ')');
    }

    if ('string' == typeof controller) {
      controller = controller.split('.');

      try {
        module = require(controllerPath + controller.shift());
      } catch (err) {
        err.message += ' (module path: ' + __dirname + ' )';
        console.error(err.stack);
        return;
      }

      while (func = controller.shift()) {
        if (module[func]) {
          module = module[func];
        } else {
          throw ReferenceError('function is not defined (controller: ' + map.controller + ')');
        }
      }
    } else {
      module = controller;
    }

    if ('GeneratorFunction' !== module.constructor.name) {
      throw TypeError('dispatcher\'s controller requires a generator function (controller: ' + map.controller + ')');
    }

    middleware.push(route[method](path, module, opts));
  });

  return compose(middleware);
};
<|endoftext|>


<commit_before>var through     = require('through'),
    path        = require('path'),
    fs          = require('fs'),
    exec        = require('child_process').exec,
    PluginError = require('gulp-util').PluginError;

module.exports = function(destination, opts) {

    if (!destination) {
        throw new PluginError('gulp-copy', 'Missing destination option for gulp-copy');
    }

    opts = opts || {};

    function copyFiles(file) {
        if (file.isNull()) return; // ignore
        if (file.isStream()) return this.emit('error', new PluginError('gulp-copy', 'Streaming not supported'));

        var rel = path.relative(file.cwd, file.path).replace(/\\/g, '/'),
            fileDestination = destination + '/' + rel,
            self = this;

        // Strip path prefixes
        if(opts.prefix) {
            var p = opts.prefix;
            while(p-- > 0) {
                rel = rel.substring(rel.indexOf('/') + 1);
            }
        }

        // Make sure destination exists
         if (!fs.existsSync(fileDestination)) {
             createDestination(fileDestination.substr(0, fileDestination.lastIndexOf('/')));
         }

        // Copy the file
        copyFile(file.path, fileDestination, function (error) {
            if (error) {
                throw new PluginError('gulp-copy', 'Could not copy file <' +  file.path + '>: ' + error.message);
            }

            // Update path for file so this path is used later on
            file.path = fileDestination;
            self.emit('data', file);
        });
    }

    function streamEnd()
    {
        this.emit('end');
    }

    function createDestination(destination)
    {
        var folders = destination.split('/'),
            path = [],
            l = folders.length,
            i = 0;

        for (; i < l; i++) {
            path.push(folders[i]);

            if (!fs.existsSync(path.join('/'))) {
                try {
                    fs.mkdirSync(path.join('/'));
                } catch (error) {
                    throw new PluginError('gulp-copy', 'Could not create destination <' +  destination + '>: ' + error.message);
                }
            }
        }
    }

    function copyFile(source, target, cb)
    {
        var cbCalled = false,
            rd = fs.createReadStream(source),
            wr;

            rd.on("error", function(err) {
                done(err);
            });

        wr = fs.createWriteStream(target);

        wr.on("error", function(err) {
            done(err);
        });

        wr.on("close", function(ex) {
            done();
        });

        rd.pipe(wr);

        function done(err)
        {
            if (!cbCalled) {
                cb(err);
                cbCalled = true;
            }
        }
    }

    return through(copyFiles, streamEnd);
};
<commit_msg>Fix prefix<commit_after>var through     = require('through'),
    path        = require('path'),
    fs          = require('fs'),
    exec        = require('child_process').exec,
    PluginError = require('gulp-util').PluginError;

module.exports = function(destination, opts) {

    if (!destination) {
        throw new PluginError('gulp-copy', 'Missing destination option for gulp-copy');
    }

    opts = opts || {};

    function copyFiles(file) {
        if (file.isNull()) return; // ignore
        if (file.isStream()) return this.emit('error', new PluginError('gulp-copy', 'Streaming not supported'));

        var rel = path.relative(file.cwd, file.path).replace(/\\/g, '/'),
            self = this,
            fileDestination;

        // Strip path prefixes
        if(opts.prefix) {
            var p = opts.prefix;
            while(p-- > 0) {
                rel = rel.substring(rel.indexOf('/') + 1);
            }
        }

        fileDestination = destination + '/' + rel;

        // Make sure destination exists
         if (!fs.existsSync(fileDestination)) {
             createDestination(fileDestination.substr(0, fileDestination.lastIndexOf('/')));
         }

        // Copy the file
        copyFile(file.path, fileDestination, function (error) {
            if (error) {
                throw new PluginError('gulp-copy', 'Could not copy file <' +  file.path + '>: ' + error.message);
            }

            // Update path for file so this path is used later on
            file.path = fileDestination;
            self.emit('data', file);
        });
    }

    function streamEnd()
    {
        this.emit('end');
    }

    function createDestination(destination)
    {
        var folders = destination.split('/'),
            path = [],
            l = folders.length,
            i = 0;

        for (; i < l; i++) {
            path.push(folders[i]);

            if (!fs.existsSync(path.join('/'))) {
                try {
                    fs.mkdirSync(path.join('/'));
                } catch (error) {
                    throw new PluginError('gulp-copy', 'Could not create destination <' +  destination + '>: ' + error.message);
                }
            }
        }
    }

    function copyFile(source, target, cb)
    {
        var cbCalled = false,
            rd = fs.createReadStream(source),
            wr;

            rd.on("error", function(err) {
                done(err);
            });

        wr = fs.createWriteStream(target);

        wr.on("error", function(err) {
            done(err);
        });

        wr.on("close", function(ex) {
            done();
        });

        rd.pipe(wr);

        function done(err)
        {
            if (!cbCalled) {
                cb(err);
                cbCalled = true;
            }
        }
    }

    return through(copyFiles, streamEnd);
};
<|endoftext|>


<commit_before>
module.exports = {
    core: {
        Product: require('./src/core/product'),
        Fabric: require('./src/core/fabric'),
        Buyer: require('./src/core/buyer'),
        Supplier: require('./src/core/supplier'),
        Textile: require('./src/core/textile'),
        Accessories: require('./src/core/accessories'),
        Sparepart: require('./src/core/sparepart'),
        UoM: require('./src/core/UoM').UoM,
        UoM_Template: require('./src/core/UoM').UoM_Template,
        GeneralMerchandise: require('./src/core/general-merchandise')
    },
    po: {
        PurchaseOrderItem: require('./src/po/purchase-order-item'),
        PurchaseOrder: require('./src/po/purchase-order'),
        PurchaseOrderGroup: require('./src/po/purchase-order-group'),
        POGarmentGeneral: require('./src/po/purchase-order-garment-general'),
        POGroupGarmentGeneral: require('./src/po/purchase-order-group-garment-general'),
        POGarmentSparepart: require('./src/po/purchase-order-garment-sparepart'),
        POTextileJobOrder: require('./src/po/purchase-order-textile-job-order-external'),
        POGarmentAccessories: require('./src/po/purchase-order-garment-accessories')
    },
    map: require('./src/map'),
    validator: require('./src/validator')
}
<commit_msg>add PO Textile General ATK<commit_after>
module.exports = {
    core: {
        Product: require('./src/core/product'),
        Fabric: require('./src/core/fabric'),
        Buyer: require('./src/core/buyer'),
        Supplier: require('./src/core/supplier'),
        Textile: require('./src/core/textile'),
        Accessories: require('./src/core/accessories'),
        Sparepart: require('./src/core/sparepart'),
        UoM: require('./src/core/UoM').UoM,
        UoM_Template: require('./src/core/UoM').UoM_Template,
        GeneralMerchandise: require('./src/core/general-merchandise')
    },
    po: {
        PurchaseOrderItem: require('./src/po/purchase-order-item'),
        PurchaseOrder: require('./src/po/purchase-order'),
        PurchaseOrderGroup: require('./src/po/purchase-order-group'),
        POGarmentGeneral: require('./src/po/purchase-order-garment-general'),
        POGroupGarmentGeneral: require('./src/po/purchase-order-group-garment-general'),
        POGarmentSparepart: require('./src/po/purchase-order-garment-sparepart'),
        POTextileJobOrder: require('./src/po/purchase-order-textile-job-order-external'),
        POGarmentAccessories: require('./src/po/purchase-order-garment-accessories'),
        POTextileGeneralATK: require('./src/po/purchase-order-textile-general-atk')
    },
    map: require('./src/map'),
    validator: require('./src/validator')
}
<|endoftext|>


<commit_before><commit_msg>vendor prefixes<commit_after><|endoftext|>


<commit_before>var MongoClient = require('mongodb').MongoClient,
    assert = require('assert');
    /*
    Module to comunicate with mongo

    */

function saveToCollection(params,callback){
        //[collection,{data}]
        var collectionName = params[0];
        var data = params[1];
        var url = 'mongodb://localhost:27017/test2';
        MongoClient.connect(url, function(err, db) {
            assert.equal(null,err);
            var collection=db.collection(collectionName);
            collection.insert(data, {w: 1}, function(err1, records){
                assert.equal(null,err1);
                //console.log("Record added as "+records[0]._id);
            });
            setImmediate(function() {
                callback();
            });
        db.close();
        })
    }
    function modifyById(id,collectionName,paramsToModify,callback){
        //[collection,{data}]
        //var collectionName = collection;
        var data = paramsToModify;
        //console.log(data);
        var url = 'mongodb://localhost:27017/test2';
        MongoClient.connect(url, function(err, db) {
            assert.equal(null,err);
            var collection=db.collection(collectionName);
            collection.findAndModify(
              {_id: id}, // query
                [['_id','asc']],  // sort order
              {$set: paramsToModify}, // replacement, replaces only the field "hi"
              {upsert:true}, // options
              function(err, object) {
                  if (err){
                      //console.warn(err.message);  // returns error if no matching object found
                  }else{
                    setImmediate(function() {
                        callback();
                    });
                     // console.log(object);
                  }
              });

        db.close();
        })
    }
    function findById(id,collectionName,callback){
        //[collection,{data}]
        //var collectionName = collection;
        //var data = paramsToModify;
        var url = 'mongodb://localhost:27017/test2';
        MongoClient.connect(url, function(err, db) {
            assert.equal(null,err);
            var collection=db.collection(collectionName);
            collection.findOne({_id:id},function(err1, doc) {
            //assert.equal(null, err1);
            //assert.equal(null, doc);
            //assert.equal(2, doc.b);
                setImmediate(function() {
                callback(err1,doc);
            });
        db.close();
      });

        //db.close();
        })
    }
exports.findById=findById;
exports.modifyById=modifyById;
exports.save=saveToCollection;
<commit_msg>add finfByParam function - returns array of elements containing param and value<commit_after>var MongoClient = require('mongodb').MongoClient,
    assert = require('assert');
    /*
    Module to comunicate with mongo

    */
function findByParam(paramAndValue,collectionName,callback){
    var url = 'mongodb://localhost:27017/test2';
    MongoClient.connect(url, function(err, db) {
        assert.equal(null,err);
        var collection=db.collection(collectionName);
        var arrayOfElements=[];
        collection.find({},{fields:paramAndValue}).each(function(e, doc) {

            if(doc){
                for(k in paramAndValue){
                    //console.log(doc[k]);
                    if(doc[k]==paramAndValue[k]){
                        arrayOfElements[arrayOfElements.length]=doc;
                      //console.log('ho',doc);
                    }
                }
            }
            else{
                setImmediate(function() {
                    callback(arrayOfElements);
                });
            }
        });
        db.close();
        })

}

function saveToCollection(params,callback){
        //[collection,{data}]
        var collectionName = params[0];
        var data = params[1];
        var url = 'mongodb://localhost:27017/test2';
        MongoClient.connect(url, function(err, db) {
            assert.equal(null,err);
            var collection=db.collection(collectionName);
            collection.insert(data, {w: 1}, function(err1, records){
                assert.equal(null,err1);
                //console.log("Record added as "+records[0]._id);
            });
            setImmediate(function() {
                callback();
            });
        db.close();
        })
    }
    function modifyById(id,collectionName,paramsToModify,callback){
        //[collection,{data}]
        //var collectionName = collection;
        var data = paramsToModify;
        //console.log(data);
        var url = 'mongodb://localhost:27017/test2';
        MongoClient.connect(url, function(err, db) {
            assert.equal(null,err);
            var collection=db.collection(collectionName);
            collection.findAndModify(
              {_id: id}, // query
                [['_id','asc']],  // sort order
              {$set: paramsToModify}, // replacement, replaces only the field "hi"
              {upsert:true}, // options
              function(err, object) {
                  if (err){
                      //console.warn(err.message);  // returns error if no matching object found
                  }else{
                    setImmediate(function() {
                        callback();
                    });
                     // console.log(object);
                  }
              });

        db.close();
        })
    }
    function findById(id,collectionName,callback){
        //[collection,{data}]
        //var collectionName = collection;
        //var data = paramsToModify;
        var url = 'mongodb://localhost:27017/test2';
        MongoClient.connect(url, function(err, db) {
            assert.equal(null,err);
            var collection=db.collection(collectionName);
            collection.findOne({_id:id},function(err1, doc) {
            //assert.equal(null, err1);
            //assert.equal(null, doc);
            //assert.equal(2, doc.b);
                setImmediate(function() {
                callback(err1,doc);
            });
        db.close();
      });

        //db.close();
        })
    }
exports.findById=findById;
exports.modifyById=modifyById;
exports.save=saveToCollection;
exports.findByParam=findByParam;
<|endoftext|>


<commit_before>var figc = require('figc')
  , config = figc(process.cwd() + '/fleet-panel.json')
  , http = require('http')
  , shoe = require('shoe')
  , ecstatic = require('ecstatic')(__dirname + '/public')
  , dnode = require('dnode')
  , server = http.createServer(ecstatic)

server.listen(config.port || 3000)

shoe(function (stream) {
  dnode.connect({
      port : config.hub.split(':')[1]
    , host : config.hub.split(':')[0]
  }, function (remote, conn) {
    var d
    remote.auth(config.secret || '', function (err, result) {
      if (err) throw err
      else {
        d = dnode(result)
        d.pipe(stream).pipe(d)
      }
    })
  })
}).install(server, '/dnode')
<commit_msg>add account to remote<commit_after>var figc = require('figc')
  , config = figc(process.cwd() + '/fleet-panel.json')
  , http = require('http')
  , shoe = require('shoe')
  , ecstatic = require('ecstatic')(__dirname + '/public')
  , dnode = require('dnode')
  , server = http.createServer(ecstatic)

server.listen(config.port || 3000)

shoe(function (stream) {
  dnode.connect({
      port : config.hub.split(':')[1]
    , host : config.hub.split(':')[0]
  }, function (remote, conn) {
    var d
    remote.auth(config.secret || '', function (err, result) {
      if (err) throw err
      else {
        result.account = config.account
        d = dnode(result)
        console.log(d, result)
        d.pipe(stream).pipe(d)
      }
    })
  })
}).install(server, '/dnode')
<|endoftext|>


<commit_before>function detectIssueId (ref) {
    const reg = /^(feature|fix|hotfix|improve|solve|update)-(\d+)/i
    const matches = reg.exec(ref) || []
    return matches[2]
}

module.exports = robot => {
    robot.on('pull_request.opened', async context => {
        const repo = context.repo()
        const pr = context.payload.pull_request
        const branchName = pr.head.ref

        // link with issue
        const issueId = detectIssueId(branchName)
        if (issueId) {
            const comment = context.issue({
                body: ` resolve #${issueId} `
            })

            // create comment
            context.github.issues.createComment(comment)
        }

        // check milestone
        const isMilestoneSetted = !!pr.milestone
        if (!isMilestoneSetted) {
            const milestones = context.github.issues.getMilestones(context.repo({
                state: 'open',
                sort: 'due_on',
                direction: 'desc',
                per_page: 1
            }))
            if (milestone && milestone[0]) {
                const curMilestone = milestone[0]

                // set milestone
                const pr = context.issues()
                context.github.issues.edit(context.issue({
                    milestone: curMilestone.number
                }))
            }
        }
    })
}
<commit_msg>fix bug<commit_after>function detectIssueId (ref) {
    const reg = /^(feature|fix|hotfix|improve|solve|update)-(\d+)/i
    const matches = reg.exec(ref) || []
    return matches[2]
}

module.exports = robot => {
    robot.on('pull_request.opened', async context => {
        const repo = context.repo()
        const pr = context.payload.pull_request
        const branchName = pr.head.ref

        // link with issue
        const issueId = detectIssueId(branchName)
        if (issueId) {
            const comment = context.issue({
                body: ` resolve #${issueId} `
            })

            // create comment
            context.github.issues.createComment(comment)
        }

        // check milestone
        const isMilestoneSetted = !!pr.milestone
        if (!isMilestoneSetted) {
            const milestones = context.github.issues.getMilestones(context.repo({
                state: 'open',
                sort: 'due_on',
                direction: 'desc',
                per_page: 1
            }))
            if (milestones && milestones[0]) {
                const curMilestone = milestones[0]

                // set milestone
                const pr = context.issues()
                context.github.issues.edit(context.issue({
                    milestone: curMilestone.number
                }))
            }
        }
    })
}
<|endoftext|>


<commit_before>//https://github.com/jasondavies/conrec.js
//http://stackoverflow.com/questions/263305/drawing-a-topographical-map
var tin = require('turf-tin');
var inside = require('turf-inside');
var grid = require('turf-grid');
var extent = require('turf-extent');
var planepoint = require('turf-planepoint');
var featurecollection = require('turf-featurecollection');
var linestring = require('turf-linestring');
var polygon = require('turf-polygon');
var point = require('turf-point');
var square = require('turf-square');
var size = require('turf-size');
var Conrec = require('./conrec.js');

/**
 * Takes a {@link FeatureCollection} of {@link Point} features with z-values and an array of
 * value breaks and generates filled contour isobands.
 *
 * @module turf/isobands
 * @category interpolation
 * @param {FeatureCollection} points a FeeatureCollection of {@link Point} features
 * @param {string} z the property name in `points` from which z-values will be pulled
 * @param {number} resolution resolution of the underlying grid
 * @param {Array<number>} breaks where to draw contours
 * @returns {FeatureCollection} a FeatureCollection of {@link Polygon} features representing isobands
 * @example
 * // create random points with random
 * // z-values in their properties
 * var points = turf.random('point', 100, {
 *   bbox: [0, 30, 20, 50]
 * });
 * for (var i = 0; i < points.features.length; i++) {
 *   points.features[i].properties.z = Math.random() * 10;
 * }
 * var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 * var isolined = turf.isobands(points, 'z', 15, breaks);
 * //=isolined
 */
module.exports = function(points, z, resolution, breaks){
  var addEdgesResult = addEdges(points, z, resolution);

  var tinResult = tin(points, z);
  var extentBBox = extent(points);
  var squareBBox = square(extentBBox);
  var gridResult = grid(squareBBox, resolution);
  var data = [];

  gridResult.features.forEach(function(pt){
    tinResult.features.forEach(function(triangle){
      if (inside(pt, triangle)) {
        pt.properties = {};
        pt.properties[z] = planepoint(pt, triangle);
      }
    });
    if(!pt.properties){
      pt.properties = {};
      pt.properties[z] = -100;
    }
  });

  var depth = Math.sqrt(gridResult.features.length);
  for (var x=0; x<depth; x++){
    var xGroup = gridResult.features.slice(x * depth, (x + 1) * depth);
    var xFlat = [];
    xGroup.forEach(function(verticalPoint){
      if(verticalPoint.properties){
        xFlat.push(verticalPoint.properties[z]);
      } else{
        xFlat.push(0);
      }
    });
    data.push(xFlat);
  }
  var interval = (squareBBox[2] - squareBBox[0]) / depth;
  var xCoordinates = [];
  var yCoordinates = [];
  for (var x=0; x<depth; x++){
    xCoordinates.push(x * interval + squareBBox[0]);
    yCoordinates.push(x * interval + squareBBox[1]);
  }

  //change zero breaks to .01 to deal with bug in conrec algorithm
  breaks = breaks.map(function(num) {
    if(num === 0){
      return 0.01;
    }
    else{
      return num;
    }
  });
  //deduplicate breaks
  breaks = unique(breaks);

  var c = new Conrec();
  c.contour(data, 0, resolution, 0, resolution, xCoordinates, yCoordinates, breaks.length, breaks);
  var contourList = c.contourList();

  var fc = featurecollection([]);
  contourList.forEach(function(c){
    if(c.length > 2){
      var polyCoordinates = [];
      c.forEach(function(coord){
        polyCoordinates.push([coord.x, coord.y]);
      });
      polyCoordinates.push([c[0].x, c[0].y]);
      var poly = polygon([polyCoordinates]);
      poly.properties = {};
      poly.properties[z] = c.level;
      fc.features.push(poly);
    }
  });

  return fc;
};

function addEdges(points, z, resolution){
  var extentBBox = extent(points),
    sizeResult;

  var squareBBox = square(extentBBox);
  var sizeBBox = size(squareBBox, 0.35);

  var edgeDistance = sizeBBox[2] - sizeBBox[0];
  var extendDistance = edgeDistance / resolution;

  var xmin = sizeBBox[0];
  var ymin = sizeBBox[1];
  var xmax = sizeBBox[2];
  var ymax = sizeBBox[3];

  //left
  var left = [[xmin, ymin],[xmin, ymax]];
  for(var i = 0; i<=resolution; i++){
    var pt = point([xmin, ymin + (extendDistance * i)]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  var i, pt;

  //bottom
  var bottom = [[xmin, ymin],[xmax, ymin]];
  for(i = 0; i<=resolution; i++){
    pt = point([xmin + (extendDistance * i), ymin]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  //right
  var right = [[xmax, ymin],[xmax, ymax]];
  for(i = 0; i<=resolution; i++){
    pt = point([xmax, ymin + (extendDistance * i)]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  //top
  var top = [[xmin, ymax],[xmax, ymax]];
  for(i = 0; i<=resolution; i++){
    pt = point([xmin + (extendDistance * i), ymax]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  return points;
}

function unique(a) {
  return a.reduce(function(p, c) {
      if (p.indexOf(c) < 0) p.push(c);
      return p;
  }, []);
}
<commit_msg>eslint fixes<commit_after>//https://github.com/jasondavies/conrec.js
//http://stackoverflow.com/questions/263305/drawing-a-topographical-map
var tin = require('turf-tin');
var inside = require('turf-inside');
var grid = require('turf-grid');
var extent = require('turf-extent');
var planepoint = require('turf-planepoint');
var featurecollection = require('turf-featurecollection');
var polygon = require('turf-polygon');
var point = require('turf-point');
var square = require('turf-square');
var size = require('turf-size');
var Conrec = require('./conrec.js');

/**
 * Takes a {@link FeatureCollection} of {@link Point} features with z-values and an array of
 * value breaks and generates filled contour isobands.
 *
 * @module turf/isobands
 * @category interpolation
 * @param {FeatureCollection} points a FeeatureCollection of {@link Point} features
 * @param {string} z the property name in `points` from which z-values will be pulled
 * @param {number} resolution resolution of the underlying grid
 * @param {Array<number>} breaks where to draw contours
 * @returns {FeatureCollection} a FeatureCollection of {@link Polygon} features representing isobands
 * @example
 * // create random points with random
 * // z-values in their properties
 * var points = turf.random('point', 100, {
 *   bbox: [0, 30, 20, 50]
 * });
 * for (var i = 0; i < points.features.length; i++) {
 *   points.features[i].properties.z = Math.random() * 10;
 * }
 * var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 * var isolined = turf.isobands(points, 'z', 15, breaks);
 * //=isolined
 */
module.exports = function(points, z, resolution, breaks) {
  var addEdgesResult = addEdges(points, z, resolution);

  var tinResult = tin(points, z);
  var extentBBox = extent(points);
  var squareBBox = square(extentBBox);
  var gridResult = grid(squareBBox, resolution);
  var data = [];

  gridResult.features.forEach(function(pt) {
    tinResult.features.forEach(function(triangle) {
      if (inside(pt, triangle)) {
        pt.properties = {};
        pt.properties[z] = planepoint(pt, triangle);
      }
    });
    if(!pt.properties) {
      pt.properties = {};
      pt.properties[z] = -100;
    }
  });

  var depth = Math.sqrt(gridResult.features.length);
  for (var x=0; x<depth; x++) {
    var xGroup = gridResult.features.slice(x * depth, (x + 1) * depth);
    var xFlat = [];
    xGroup.forEach(function(verticalPoint) {
      if(verticalPoint.properties) {
        xFlat.push(verticalPoint.properties[z]);
      } else {
        xFlat.push(0);
      }
    });
    data.push(xFlat);
  }
  var interval = (squareBBox[2] - squareBBox[0]) / depth;
  var xCoordinates = [];
  var yCoordinates = [];
  for (var x=0; x<depth; x++) {
    xCoordinates.push(x * interval + squareBBox[0]);
    yCoordinates.push(x * interval + squareBBox[1]);
  }

  //change zero breaks to .01 to deal with bug in conrec algorithm
  breaks = breaks.map(function(num) {
    if(num === 0) {
      return 0.01;
    } else {
      return num;
    }
  });
  //deduplicate breaks
  breaks = unique(breaks);

  var c = new Conrec();
  c.contour(data, 0, resolution, 0, resolution, xCoordinates, yCoordinates, breaks.length, breaks);
  var contourList = c.contourList();

  var fc = featurecollection([]);
  contourList.forEach(function(c) {
    if(c.length > 2) {
      var polyCoordinates = [];
      c.forEach(function(coord) {
        polyCoordinates.push([coord.x, coord.y]);
      });
      polyCoordinates.push([c[0].x, c[0].y]);
      var poly = polygon([polyCoordinates]);
      poly.properties = {};
      poly.properties[z] = c.level;
      fc.features.push(poly);
    }
  });

  return fc;
};

function addEdges(points, z, resolution) {
  var extentBBox = extent(points),
    sizeResult;

  var squareBBox = square(extentBBox);
  var sizeBBox = size(squareBBox, 0.35);

  var edgeDistance = sizeBBox[2] - sizeBBox[0];
  var extendDistance = edgeDistance / resolution;

  var xmin = sizeBBox[0];
  var ymin = sizeBBox[1];
  var xmax = sizeBBox[2];
  var ymax = sizeBBox[3];

  //left
  var left = [[xmin, ymin],[xmin, ymax]];
  for(var i = 0; i<=resolution; i++) {
    var pt = point([xmin, ymin + (extendDistance * i)]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  var i, pt;

  //bottom
  var bottom = [[xmin, ymin],[xmax, ymin]];
  for(i = 0; i<=resolution; i++) {
    pt = point([xmin + (extendDistance * i), ymin]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  //right
  var right = [[xmax, ymin],[xmax, ymax]];
  for(i = 0; i<=resolution; i++) {
    pt = point([xmax, ymin + (extendDistance * i)]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  //top
  var top = [[xmin, ymax],[xmax, ymax]];
  for(i = 0; i<=resolution; i++) {
    pt = point([xmin + (extendDistance * i), ymax]);
    pt.properties = {};
    pt.properties[z] = -100;
    points.features.push(pt);
  }

  return points;
}

function unique(a) {
  return a.reduce(function(p, c) {
      if (p.indexOf(c) < 0) p.push(c);
      return p;
  }, []);
}
<|endoftext|>


<commit_before>"use strict";

// @formatter:off
/**
 * Find image data using the deprecated [Google Image Search API]{@link https://developers.google.com/image-search/v1/devguide}
 * @author Matthew Hasbach
 * @copyright Matthew Hasbach 2015
 * @license MIT
 * @module node-google-image
 * @example
new googleImage('car')
    .quantity(5)
    .page(2)
    .search()
    .then(function(images) {
        images[0].save(path.join(__dirname, images[0].fileName)).then(function() {
            console.log('done');
        }).catch(function(err) {
            console.error(err);
        });
    }).catch(function(err) {
        console.error(err);
    });
 */
// @formatter:on

let fs = require('fs'),
    dwn = require('dwn'),
    http = require('axios'),
    steamToArray = require('stream-to-array'),
    isPlainObject = require('lodash.isplainobject'),
    apiURL = 'http://ajax.googleapis.com/ajax/services/search/images',
    defaultOptions = {
        v: '1.0',
        start: 0,
        rsz: 1
    },
    /**
     * Download an image
     * @alias imageData#download
     * @memberof imageData
     * @param {imageData#download~callback} [cb] - A callback to be executed once the download is complete
     * @returns {Promise}
     */
    download = function(cb) {
        /**
         * @callback imageData#download~callback
         * @param {Error|null} err - An error if one was encountered
         * @param {Buffer|undefined} imageData - Image data
         */
        let url = this.url;

        return new Promise(function(resolve, reject) {
            steamToArray(dwn._download(url), function(err, arr) {
                if (err) {
                    return (cb || reject)(err);
                }

                let buffer = Buffer.concat(arr);

                cb ? cb(null, buffer) : resolve(buffer);
            });
        });
    },
    /**
     * Save an image
     * @alias imageData#save
     * @memberof imageData
     * @param {string} path - A callback to be executed once the image has been saved
     * @param {imageData#save~callback} [cb] - A callback to be executed once the image has been saved
     * @returns {Promise}
     */
    save = function(path, cb) {
        /**
         * @callback imageData#save~callback
         * @param {Error|null} err - An error if one was encountered
         */
        let url = this.url;

        return new Promise(function(resolve, _reject) {
            let reject = cb || _reject;

            let readStream = dwn._download(url);

            readStream.on('end', cb || resolve);
            readStream.on('error', reject);
            readStream.pipe(fs.createWriteStream(path));
        });
    },
    googleImage = class {
        /**
         * @param {string} q - A search query. This may be omitted and supplied later using the [options]{@link node-google-image#options} or [search]{@link node-google-image#search} method.
         * @constructs node-google-image
         */
        constructor(q) {
            this._options = Object.assign({q}, defaultOptions);
        }

        /**
         * Set the desired size of the result set
         * @method node-google-image#quantity
         * @param {number} quantity - The result set size
         * @chainable
         */
        quantity(quantity) {
            this._options.rsz = quantity;
            return this;
        }

        /**
         * Set the desired page number
         * @method node-google-image#page
         * @param {number} page - The page number
         * @chainable
         */
        page(page) {
            this._options.start = page;
            return this;
        }

        /**
         * Set Google Image Search API [options]{@link https://developers.google.com/image-search/v1/jsondevguide#json_args}
         * @method node-google-image#options
         * @param {Object} opt - API options
         * @chainable
         */
        options(opt) {
            this._options = Object.assign(this._options, opt);
            return this;
        }

        /**
         * Search for images. The default page and quantity are 0 and 1, respectively.
         * @method node-google-image#search
         * @param {Object} [opt] - API [options]{@link https://developers.google.com/image-search/v1/jsondevguide#json_args}
         * @param {search~callback} [cb] - A callback to be executed once the search is complete
         * @returns {Promise}
         */
        search(opt, cb) {
            /**
             * @callback search~callback
             * @param {Error|null} err - An error if one was encountered
             * @param {responseDataResults|undefined} responseData - [Response data]{@link https://developers.google.com/image-search/v1/jsondevguide#results_guaranteed} results
             */
            isPlainObject(opt) ? this.options(opt) : cb = opt;

            let options = this._options;

            return new Promise(
                function(resolve, _reject) {
                    let reject = cb || _reject;

                    if (!options.q) {
                        return reject(new Error('query must be supplied'));
                    }

                    http.get(apiURL, {params: options}).then(function(res) {
                        if (res.data.responseDetails) {
                            return reject(new Error(res.data.responseDetails));
                        }
                        /**
                         * [Response data]{@link https://developers.google.com/image-search/v1/jsondevguide#results_guaranteed} results
                         * @typedef {Array<imageData>} responseDataResults
                         * @global
                         */
                        /**
                         * [Image data]{@link https://developers.google.com/image-search/v1/jsondevguide#results_guaranteed} extended with convenience methods (described below)
                         * @typedef {Object<string, function>} imageData
                         * @global
                         */
                        for (let image of res.data.responseData.results) {
                            /**
                             * Image filename
                             * @alias imageData#fileName
                             * @type {string}
                             */
                            image.fileName = image.url.substr(image.url.lastIndexOf('/') + 1);
                            image.download = download;
                            image.save = save;
                        }

                        cb ? cb(null, res.data.responseData.results) : resolve(res.data.responseData.results);
                    }).catch(function(res) {
                        reject(new Error(`${res.status} ${res.statusText}`));
                    });
                });
        }
    };

module.exports = googleImage;<commit_msg>Remove redundant var<commit_after>"use strict";

// @formatter:off
/**
 * Find image data using the deprecated [Google Image Search API]{@link https://developers.google.com/image-search/v1/devguide}
 * @author Matthew Hasbach
 * @copyright Matthew Hasbach 2015
 * @license MIT
 * @module node-google-image
 * @example
new googleImage('car')
    .quantity(5)
    .page(2)
    .search()
    .then(function(images) {
        images[0].save(path.join(__dirname, images[0].fileName)).then(function() {
            console.log('done');
        }).catch(function(err) {
            console.error(err);
        });
    }).catch(function(err) {
        console.error(err);
    });
 */
// @formatter:on

let fs = require('fs'),
    dwn = require('dwn'),
    http = require('axios'),
    steamToArray = require('stream-to-array'),
    isPlainObject = require('lodash.isplainobject'),
    apiURL = 'http://ajax.googleapis.com/ajax/services/search/images',
    defaultOptions = {
        v: '1.0',
        start: 0,
        rsz: 1
    },
    /**
     * Download an image
     * @alias imageData#download
     * @memberof imageData
     * @param {imageData#download~callback} [cb] - A callback to be executed once the download is complete
     * @returns {Promise}
     */
    download = function(cb) {
        /**
         * @callback imageData#download~callback
         * @param {Error|null} err - An error if one was encountered
         * @param {Buffer|undefined} imageData - Image data
         */
        let url = this.url;

        return new Promise(function(resolve, reject) {
            steamToArray(dwn._download(url), function(err, arr) {
                if (err) {
                    return (cb || reject)(err);
                }

                let buffer = Buffer.concat(arr);

                cb ? cb(null, buffer) : resolve(buffer);
            });
        });
    },
    /**
     * Save an image
     * @alias imageData#save
     * @memberof imageData
     * @param {string} path - A callback to be executed once the image has been saved
     * @param {imageData#save~callback} [cb] - A callback to be executed once the image has been saved
     * @returns {Promise}
     */
    save = function(path, cb) {
        /**
         * @callback imageData#save~callback
         * @param {Error|null} err - An error if one was encountered
         */
        let url = this.url;

        return new Promise(function(resolve, _reject) {
            let readStream = dwn._download(url);

            readStream.on('end', cb || resolve);
            readStream.on('error', cb || _reject);
            readStream.pipe(fs.createWriteStream(path));
        });
    },
    googleImage = class {
        /**
         * @param {string} q - A search query. This may be omitted and supplied later using the [options]{@link node-google-image#options} or [search]{@link node-google-image#search} method.
         * @constructs node-google-image
         */
        constructor(q) {
            this._options = Object.assign({q}, defaultOptions);
        }

        /**
         * Set the desired size of the result set
         * @method node-google-image#quantity
         * @param {number} quantity - The result set size
         * @chainable
         */
        quantity(quantity) {
            this._options.rsz = quantity;
            return this;
        }

        /**
         * Set the desired page number
         * @method node-google-image#page
         * @param {number} page - The page number
         * @chainable
         */
        page(page) {
            this._options.start = page;
            return this;
        }

        /**
         * Set Google Image Search API [options]{@link https://developers.google.com/image-search/v1/jsondevguide#json_args}
         * @method node-google-image#options
         * @param {Object} opt - API options
         * @chainable
         */
        options(opt) {
            this._options = Object.assign(this._options, opt);
            return this;
        }

        /**
         * Search for images. The default page and quantity are 0 and 1, respectively.
         * @method node-google-image#search
         * @param {Object} [opt] - API [options]{@link https://developers.google.com/image-search/v1/jsondevguide#json_args}
         * @param {search~callback} [cb] - A callback to be executed once the search is complete
         * @returns {Promise}
         */
        search(opt, cb) {
            /**
             * @callback search~callback
             * @param {Error|null} err - An error if one was encountered
             * @param {responseDataResults|undefined} responseData - [Response data]{@link https://developers.google.com/image-search/v1/jsondevguide#results_guaranteed} results
             */
            isPlainObject(opt) ? this.options(opt) : cb = opt;

            let options = this._options;

            return new Promise(
                function(resolve, _reject) {
                    let reject = cb || _reject;

                    if (!options.q) {
                        return reject(new Error('query must be supplied'));
                    }

                    http.get(apiURL, {params: options}).then(function(res) {
                        if (res.data.responseDetails) {
                            return reject(new Error(res.data.responseDetails));
                        }
                        /**
                         * [Response data]{@link https://developers.google.com/image-search/v1/jsondevguide#results_guaranteed} results
                         * @typedef {Array<imageData>} responseDataResults
                         * @global
                         */
                        /**
                         * [Image data]{@link https://developers.google.com/image-search/v1/jsondevguide#results_guaranteed} extended with convenience methods (described below)
                         * @typedef {Object<string, function>} imageData
                         * @global
                         */
                        for (let image of res.data.responseData.results) {
                            /**
                             * Image filename
                             * @alias imageData#fileName
                             * @type {string}
                             */
                            image.fileName = image.url.substr(image.url.lastIndexOf('/') + 1);
                            image.download = download;
                            image.save = save;
                        }

                        cb ? cb(null, res.data.responseData.results) : resolve(res.data.responseData.results);
                    }).catch(function(res) {
                        reject(new Error(`${res.status} ${res.statusText}`));
                    });
                });
        }
    };

module.exports = googleImage;<|endoftext|>


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

var nextId = 0;

app.set('views', './pages');
app.set('view engine', 'jade');

app.get('/', function(req, res){
  var totalCols = 6;
  var totalRows = 4;

  var config = {
    id: nextId,
    totalCols: totalCols,
    totalRows: totalRows,
    col: (nextId % totalCols) + 1,
    row: Math.floor(nextId/totalCols) + 1
  };

  if (!req.query.col || !req.query.row) {
    res.redirect(302, "/?col=" + config.col + "&row=" + config.row);
    console.log("SERVER: Sent redirect to col: " + config.col + " row: " + config.row);
    nextId++;
  } else {
    config.col = parseInt(req.query.col);
    config.row = parseInt(req.query.row);
    res.render('index', { config: JSON.stringify(config) } );
    console.log("SERVER: Sent PULSAR to : " + config.col + " row: " + config.row);
  }
});

app.get('/pulsar.js', function(req, res){
  res.sendFile(__dirname + '/dist/pulsar.js');
});

io.on('connection', function(socket){
  console.log('PULSAR: client connected');
  socket.on('disconnect', function() {
    console.log('PULSAR: client disconnected');
  });
});

http.listen(3000, function(){
  console.log('SERVER: listening on *:3000');
});

var stdin = process.stdin;
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
stdin.on( 'data', function( key ){
  // ctrl-c ( end of text )
  if ( key === '\u0003' ) {
    console.log("PULSAR: Exiting...");
    process.exit();
  } else if ( key === 'c') {
    console.log("PULSAR: Random colour...");
    io.emit('pulse', {
      name: 'flash',
      r: Math.floor(Math.random() * 255),
      g: Math.floor(Math.random() * 255),
      b: Math.floor(Math.random() * 255)
    });
  } else if ( key === 'b') {
    console.log("PULSAR: Sending ball...");
    io.emit('pulse', {
      name: 'ball'
    });
  } else if ( key === 'w') {
    console.log("PULSAR: Sending long ball...");
    io.emit('pulse', {
      name: 'ball',
      totalFrames: 100
    });
  } else if ( key === '\u0012' ) {
    console.log();
    console.log("PULSAR REBOOTING");
    console.log();
    io.emit('pulsar control', {action: "reboot"});
  } else if ( key === '1' ) {
    io.emit('pulse', {
      name: 'flash',
      target: {
        row: 1
      }
    });
  } else if ( key === '4' ) {
    io.emit('pulse', {
      name: 'flash',
      target: {
        row: 2
      }
    });
  } else if ( key === '2' ) {
    io.emit('pulse', {
      name: 'flash',
      target: {
        col: 2
      }
    });
  } else if ( key === 's' ) {
    console.log("PULSAR: Sending starburst ****");
    io.emit('pulse', {
      name: 'starburst',
      framesLeft: 3000
    });
  } else if ( key === '.' ) {
    console.log("PULSAR: Sending starfield *");
    io.emit('pulse', {
      name: 'starfield',
    });
  } else if ( key === ',' ) {
    console.log("PULSAR: UPDATING STARFIELD *");
    io.emit('pulse update', {
      name: 'starfield',
      rotationX: (Math.random() * (500)) - 250 ,
      rotationY: (Math.random() * (500)) - 250,
    });
  } else if ( key === '=' ) {
    console.log("PULSAR: Strobing");
    io.emit('pulse', {
      name: 'strobe'
    });
  } else {
    console.log("PULSAR: Flashing... (pressed " + key + ")");
    io.emit('pulse', {name: 'flash'});
  }
});
<commit_msg>Require combo file<commit_after>var tty = require('tty');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Combos = require('./combos.js');
var combo = new Combos(io);

var nextId = 0;

app.set('views', './pages');
app.set('view engine', 'jade');

app.get('/', function(req, res){
  var totalCols = 6;
  var totalRows = 4;

  var config = {
    id: nextId,
    totalCols: totalCols,
    totalRows: totalRows,
    col: (nextId % totalCols) + 1,
    row: Math.floor(nextId/totalCols) + 1
  };

  if (!req.query.col || !req.query.row) {
    res.redirect(302, "/?col=" + config.col + "&row=" + config.row);
    console.log("SERVER: Sent redirect to col: " + config.col + " row: " + config.row);
    nextId++;
  } else {
    config.col = parseInt(req.query.col);
    config.row = parseInt(req.query.row);
    res.render('index', { config: JSON.stringify(config) } );
    console.log("SERVER: Sent PULSAR to : " + config.col + " row: " + config.row);
  }
});

app.get('/pulsar.js', function(req, res){
  res.sendFile(__dirname + '/dist/pulsar.js');
});

io.on('connection', function(socket){
  console.log('PULSAR: client connected');
  socket.on('disconnect', function() {
    console.log('PULSAR: client disconnected');
  });
});

http.listen(3000, function(){
  console.log('SERVER: listening on *:3000');
});

var stdin = process.stdin;
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
stdin.on( 'data', function( key ){
  // ctrl-c ( end of text )
  if ( key === '\u0003' ) {
    console.log("PULSAR: Exiting...");
    process.exit();
  } else if ( key === 'c') {
    console.log("PULSAR: Random colour...");
    io.emit('pulse', {
      name: 'flash',
      r: Math.floor(Math.random() * 255),
      g: Math.floor(Math.random() * 255),
      b: Math.floor(Math.random() * 255)
    });
  } else if ( key === 'b') {
    console.log("PULSAR: Sending ball...");
    io.emit('pulse', {
      name: 'ball'
    });
  } else if ( key === 'w') {
    console.log("PULSAR: Sending long ball...");
    io.emit('pulse', {
      name: 'ball',
      totalFrames: 100
    });
  } else if ( key === '\u0012' ) {
    console.log();
    console.log("PULSAR REBOOTING");
    console.log();
    io.emit('pulsar control', {action: "reboot"});
  } else if ( key === '1' ) {
    io.emit('pulse', {
      name: 'flash',
      target: {
        row: 1
      }
    });
  } else if ( key === '4' ) {
    io.emit('pulse', {
      name: 'flash',
      target: {
        row: 2
      }
    });
  } else if ( key === '2' ) {
    io.emit('pulse', {
      name: 'flash',
      target: {
        col: 2
      }
    });
  } else if ( key === 's' ) {
    console.log("PULSAR: Sending starburst ****");
    io.emit('pulse', {
      name: 'starburst',
      framesLeft: 3000
    });
  } else if ( key === '.' ) {
    console.log("PULSAR: Sending starfield *");
    io.emit('pulse', {
      name: 'starfield',
    });
  } else if ( key === ',' ) {
    console.log("PULSAR: UPDATING STARFIELD *");
    io.emit('pulse update', {
      name: 'starfield',
      rotationX: (Math.random() * (500)) - 250 ,
      rotationY: (Math.random() * (500)) - 250,
    });
  } else if ( key === '=' ) {
    console.log("PULSAR: Strobing");
    io.emit('pulse', {
      name: 'strobe'
    });
  } else {
    console.log("PULSAR: Flashing... (pressed " + key + ")");
    io.emit('pulse', {name: 'flash'});
  }
});
<|endoftext|>


<commit_before>// Reference : https://github.com/llSourcell/how_to_deploy_a_keras_model_to_production/blob/master/static/index.js
(function()
{
	var canvas = document.querySelector( "#canvas" );
	var context = canvas.getContext( "2d" );
	canvas.width = 280;
	canvas.height = 280;

	var Mouse = { x: 0, y: 0 };
	var lastMouse = { x: 0, y: 0 };
	context.fillStyle="white";
	context.fillRect(0,0,canvas.width,canvas.height);
	context.color = "black";
	context.lineWidth = 10;
    context.lineJoin = context.lineCap = 'round';

	debug();

	canvas.addEventListener( "mousemove", function( e )
	{
		lastMouse.x = Mouse.x;
		lastMouse.y = Mouse.y;

		Mouse.x = e.pageX - this.offsetLeft;
		Mouse.y = e.pageY - this.offsetTop;

	}, false );

	canvas.addEventListener( "mousedown", function( e )
	{
		canvas.addEventListener( "mousemove", onPaint, false );

	}, false );

	canvas.addEventListener( "mouseup", function()
	{
		canvas.removeEventListener( "mousemove", onPaint, false );

	}, false );

	var onPaint = function()
	{
		context.lineWidth = context.lineWidth;
		context.lineJoin = "round";
		context.lineCap = "round";
		context.strokeStyle = context.color;

		context.beginPath();
		context.moveTo( lastMouse.x, lastMouse.y );
		context.lineTo( Mouse.x, Mouse.y );
		context.closePath();
		context.stroke();
	};

	function debug()
	{
		/* CLEAR BUTTON */
		var clearButton = $( "#clearButton" );

		clearButton.on( "click", function()
		{

				context.clearRect( 0, 0, 280, 280 );
				context.fillStyle="white";
				context.fillRect(0,0,canvas.width,canvas.height);

		});

		/* COLOR SELECTOR */

		$( "#colors" ).change(function()
		{
			var color = $( "#colors" ).val();
			context.color = color;
		});

		/* LINE WIDTH */

		$( "#lineWidth" ).change(function()
		{
			context.lineWidth = $( this ).val();
		});
	}
}());<commit_msg>changed linewidth in static/index.js<commit_after>// Reference : https://github.com/llSourcell/how_to_deploy_a_keras_model_to_production/blob/master/static/index.js
(function()
{
	var canvas = document.querySelector( "#canvas" );
	var context = canvas.getContext( "2d" );
	canvas.width = 280;
	canvas.height = 280;

	var Mouse = { x: 0, y: 0 };
	var lastMouse = { x: 0, y: 0 };
	context.fillStyle="white";
	context.fillRect(0,0,canvas.width,canvas.height);
	context.color = "black";
	context.lineWidth = 20;
    context.lineJoin = context.lineCap = 'round';

	debug();

	canvas.addEventListener( "mousemove", function( e )
	{
		lastMouse.x = Mouse.x;
		lastMouse.y = Mouse.y;

		Mouse.x = e.pageX - this.offsetLeft;
		Mouse.y = e.pageY - this.offsetTop;

	}, false );

	canvas.addEventListener( "mousedown", function( e )
	{
		canvas.addEventListener( "mousemove", onPaint, false );

	}, false );

	canvas.addEventListener( "mouseup", function()
	{
		canvas.removeEventListener( "mousemove", onPaint, false );

	}, false );

	var onPaint = function()
	{
		context.lineWidth = context.lineWidth;
		context.lineJoin = "round";
		context.lineCap = "round";
		context.strokeStyle = context.color;

		context.beginPath();
		context.moveTo( lastMouse.x, lastMouse.y );
		context.lineTo( Mouse.x, Mouse.y );
		context.closePath();
		context.stroke();
	};

	function debug()
	{
		/* CLEAR BUTTON */
		var clearButton = $( "#clearButton" );

		clearButton.on( "click", function()
		{

				context.clearRect( 0, 0, 280, 280 );
				context.fillStyle="white";
				context.fillRect(0,0,canvas.width,canvas.height);

		});

		/* COLOR SELECTOR */

		$( "#colors" ).change(function()
		{
			var color = $( "#colors" ).val();
			context.color = color;
		});

		/* LINE WIDTH */

		$( "#lineWidth" ).change(function()
		{
			context.lineWidth = $( this ).val();
		});
	}
}());
<|endoftext|>