<commit_before>'use strict';

var React = require('react');
var Router = require('react-router');

function hapiReactRouter(server, options, done){

  var routes = options.routes;

  server.decorate('reply', 'router', function(data){
    var response = this.response().hold();

    Router.run(routes, this.request.path, function(Handler){
      var component = React.createElement(Handler, data);
      var html = React.renderToString(component);
      response.source = html;
      response.send();
    });

    return response;
  });

  done();
}

hapiReactRouter.attributes = {
  pkg: require('./package.json')
};

module.exports = {
  register: hapiReactRouter
};
<commit_msg>use request.url.path instead of request.path<commit_after>'use strict';

var React = require('react');
var Router = require('react-router');

function hapiReactRouter(server, options, done){

  var routes = options.routes;

  server.decorate('reply', 'router', function(data){
    var response = this.response().hold();

    Router.run(routes, this.request.url.path, function(Handler){
      var component = React.createElement(Handler, data);
      var html = React.renderToString(component);
      response.source = html;
      response.send();
    });

    return response;
  });

  done();
}

hapiReactRouter.attributes = {
  pkg: require('./package.json')
};

module.exports = {
  register: hapiReactRouter
};
<|endoftext|>


<commit_before>var binarymax = window.binarymax = {};
binarymax.circus=(function(){
	"use strict";

	var head = document.getElementById("head");
	var logo = document.getElementById("logo");
	var anim = document.getElementById("anim");
	var year = document.getElementById("year");
	var cont = anim.getContext('2d');
	var back = "";

	var dim = 75;
	anim.width = dim;
	anim.height = dim;

	var imgd = cont.createImageData(dim,dim);

	var memo = [dim*dim];
	var frms = [];

	year.innerText = (new Date()).getFullYear();

	var load = function() {
		logo.onclick = S;
		for(var x=0;x<dim;x++){
			for(var y=0;y<dim;y++){
				var offset=(x+y*dim)*4;
				memo[offset] = {
					r:parseInt((x^y)),
					g:parseInt((x|y)),
					b:parseInt((x&y))
				};
			}
		}

		for(var z=0;z<dim;z++) {
			drawImage(z);
		}

		setInterval(animate,120);

	};

	var drawImage = function (z) {
		var pix = imgd.data;
		for(var x=0;x<dim;x++) {
			for(var y=0;y<dim;y++) {
				var offset=(x+y*dim)*4;
				pix[offset+0]=(memo[offset].r * z)%255;
				pix[offset+1]=(memo[offset].g * z)%255;
				pix[offset+2]=(memo[offset].b * z)%255;
				pix[offset+3]=255;
			}
		}
		cont.putImageData(imgd, 0,0);
		back = anim.toDataURL();
		frms.push('url('+back+')');
	};

	var frm = 0, dir = 1;
	var animate = function(){
		logo.style.backgroundImage=frms[frm];
		frm += dir;
		if(frm === dim) dir = -1;
		if(frm === 0)   dir = 1;
	};

	var B = 1;
	var S = function(){
		B = B^1;
		logo.src='http://binarymax.com/images/binarymax_orange'+B+'.png';
	}

	load();

})();<commit_msg>requestAnimationFrame instead of setInterval<commit_after>var binarymax = window.binarymax = {};
binarymax.circus=(function(){
	"use strict";

	var head = document.getElementById("head");
	var logo = document.getElementById("logo");
	var anim = document.getElementById("anim");
	var year = document.getElementById("year");
	var cont = anim.getContext('2d');
	var back = "";

	var dim = 75;
	anim.width = dim;
	anim.height = dim;

	var imgd = cont.createImageData(dim,dim);

	var memo = [dim*dim];
	var frms = [];

	year.innerText = (new Date()).getFullYear();

	var load = function() {
		logo.onclick = S;
		for(var x=0;x<dim;x++){
			for(var y=0;y<dim;y++){
				var offset=(x+y*dim)*4;
				memo[offset] = {
					r:parseInt((x^y)),
					g:parseInt((x|y)),
					b:parseInt((x&y))
				};
			}
		}

		for(var z=0;z<dim;z++) {
			drawImage(z);
		}

		requestAnimationFrame(animate);
	};

	var drawImage = function (z) {
		var pix = imgd.data;
		for(var x=0;x<dim;x++) {
			for(var y=0;y<dim;y++) {
				var offset=(x+y*dim)*4;
				pix[offset+0]=(memo[offset].r * z)%255;
				pix[offset+1]=(memo[offset].g * z)%255;
				pix[offset+2]=(memo[offset].b * z)%255;
				pix[offset+3]=255;
			}
		}
		cont.putImageData(imgd, 0,0);
		back = anim.toDataURL();
		frms.push('url('+back+')');
	};

	var frm = 0, dir = 1, wait = 0;
	var animate = function(){
		if(wait==5) {
			logo.style.backgroundImage=frms[frm];
			frm += dir;
			wait=0;
		}
		wait++;
		if(frm === dim) dir = -1;
		if(frm === 0)   dir = 1;
		requestAnimationFrame(animate);
	};

	var B = 1;
	var S = function(){
		B = B^1;
		logo.src='http://binarymax.com/images/binarymax_orange'+B+'.png';
	}

	load();

})();<|endoftext|>


<commit_before>var request = require('request');
var Vow = require('vow');
var extend = require('extend');
var WebSocket = require('ws');
var util = require('util');
var utils = require('./libs/utils.js');
var find = utils.find;
var assert = utils.assert;
var EventEmitter = require('events').EventEmitter;

/**
 * @param {object} params
 * @constructor
 */
function Bot(params) {
    this.token = params.token;
    this.name = params.name;

    assert(params.token, 'token must be defined');
    this.login();
}

util.inherits(Bot, EventEmitter);

/**
 * Starts a Real Time Messaging API session
 */
Bot.prototype.login = function() {
    this._api('rtm.start').then(function(data) {
        this.wsUrl = data.url;
        this.self = data.self;
        this.channels = data.channels;
        this.users = data.users;
        this.ims = data.ims;
        this.groups = data.groups;

        this.emit('start');

        this.connect();
    }.bind(this)).fail(function(data) {
        assert(false, data.error);
    }).done();
};

/**
 * Establish a WebSocket connection
 */
Bot.prototype.connect = function() {
    this.ws = new WebSocket(this.wsUrl);

    this.ws.on('open', function(data) {
        this.emit('open', data);
    }.bind(this));

    this.ws.on('close', function(data) {
        this.emit('close', data);
    }.bind(this));

    this.ws.on('message', function(data) {
        try {
            this.emit('message', JSON.parse(data));
        } catch (e) {
            console.log(e);
        }
    }.bind(this));
};

/**
 * Get channels
 * @returns {vow.Promise}
 */
Bot.prototype.getChannels = function() {
    if (this.channels) {
        return Vow.fulfill({ channels: this.channels });
    }
    return this._api('channels.list');
};

/**
 * Get users
 * @returns {vow.Promise}
 */
Bot.prototype.getUsers = function() {
    if (this.users) {
        return Vow.fulfill({ members: this.users });
    }

    return this._api('users.list');
};

/**
 * Get groups
 * @returns {vow.Promise}
 */
Bot.prototype.getGroups = function() {
    if (this.groups) {
        return Vow.fulfill({ groups: this.groups });
    }

    return this._api('groups.list');
};

/**
 * Get user by name
 * @param {string} name
 * @returns {object}
 */
Bot.prototype.getUser = function(name) {
    return this.getUsers().then(function(data) {
        return find(data.members, { name: name });
    });
};

/**
 * Get channel by name
 * @param {string} name
 * @returns {object}
 */
Bot.prototype.getChannel = function(name) {
    return this.getChannels().then(function(data) {
        return find(data.channels, { name: name });
    });
};

/**
 * Get group by name
 * @param {string} name
 * @returns {object}
 */
Bot.prototype.getGroup = function(name) {
    return this.getGroups().then(function(data) {
        return find(data.groups, { name: name });
    });
};

/**
 * Get channel ID
 * @param {string} name
 * @returns {string}
 */
Bot.prototype.getChannelId = function(name) {
    return this.getChannel(name).then(function(channel) {
        return channel.id;
    });
};

/**
 * Get group ID
 * @param {string} name
 * @returns {string}
 */
Bot.prototype.getGroupId = function(name) {
    return this.getGroup(name).then(function(group) {
        return group.id;
    });
};

/**
 * Get "direct message" channel ID
 * @param {string} name
 * @returns {vow.Promise}
 */
Bot.prototype.getChatId = function(name) {
    return this.getUser(name).then(function(data) {

        var chatId = find(this.ims, { user: data.id }).id;

        return chatId || this.openIm(data.id);
    }.bind(this)).then(function(data) {
        return typeof data === 'string' ? data : data.channel.id;
    });
};

/**
 * Opens a "direct message" channel with another member of your Slack team
 * @param {string} userId
 * @returns {vow.Promise}
 */
Bot.prototype.openIm = function(userId) {
    return this._api('im.open', {user: userId});
};

/**
 * Posts a message to a channel by ID
 * @param {string} id - channel ID
 * @param {string} text
 * @param {object} params
 * @returns {vow.Promise}
 */
Bot.prototype.postMessage = function(id, text, params) {
    params = extend({
        text: text,
        channel: id,
        username: this.name
    }, params || {});

    return this._api('chat.postMessage', params);
};

/**
 * Posts a message to user by name
 * @param {string} name
 * @param {string} text
 * @param {object} params
 * @param {function} cb
 * @returns {vow.Promise}
 */
Bot.prototype.postMessageToUser = function(name, text, params, cb) {
    return this._post('user', name, text, params, cb);
};

/**
 * Posts a message to channel by name
 * @param {string} name
 * @param {string} text
 * @param {object} params
 * @param {function} cb
 * @returns {vow.Promise}
 */
Bot.prototype.postMessageToChannel = function(name, text, params, cb) {
    return this._post('channel', name, text, params, cb);
};

/**
 * Posts a message to group by name
 * @param {string} name
 * @param {string} text
 * @param {object} params
 * @param {function} cb
 * @returns {vow.Promise}
 */
Bot.prototype.postMessageToGroup = function(name, text, params, cb) {
    return this._post('group', name, text, params, cb);
};

/**
 * Common method for posting messages
 * @param {string} type
 * @param {string} name
 * @param {string} text
 * @param {object} params
 * @param {function} cb
 * @returns {vow.Promise}
 * @private
 */
Bot.prototype._post = function(type, name, text, params, cb) {
    var method = ({
        'group': 'getGroupId',
        'channel': 'getChannelId',
        'user': 'getChatId'
    })[type];

    if (typeof params === 'function') {
        cb = params;
        params = null;
    }

    return this[method](name).then(function(itemId) {
        return this.postMessage(itemId, text, params);
    }.bind(this)).always(function(data) {
        if (cb) {
            cb(data._value);
        }
    });
};

/**
 * Posts a message to group | channel | user
 * @param {string} name
 * @param {string} text
 * @param {object} params
 * @param {function} cb
 * @returns {vow.Promise}
 */
Bot.prototype.postTo = function(name, text, params, cb) {
    return Vow.all([this.getChannels(), this.getUsers(), this.getGroups()]).then(function(data) {

        var all = [].concat(data[0].channels, data[1].members, data[2].groups);
        var result = find(all, {name: name});

        assert(Object.keys(result).length, 'wrong name');

        if (result['is_channel']) {
            return this.postMessageToChannel(name, text, params, cb);
        } else if (result['is_group']) {
            return this.postMessageToGroup(name, text, params, cb);
        } else {
            return this.postMessageToUser(name, text, params, cb);
        }
    }.bind(this));
};

/**
 * Send request to API method
 * @param {string} methodName
 * @param {object} params
 * @returns {vow.Promise}
 * @private
 */
Bot.prototype._api = function(methodName, params) {
    params = extend(params || {}, {token: this.token});

    var data = {
        url: 'https://slack.com/api/' + methodName,
        form: params
    };

    return new Vow.Promise(function(resolve, reject) {

        request.post(data, function(err, request, body) {
            if (err) {
                reject(err);

                return false;
            }

            try {
                body = JSON.parse(body);

                // Response always contain a top-level boolean property ok,
                // indicating success or failure
                if (body.ok) {
                    resolve(body);
                } else {
                    reject(body);
                }

            } catch (e) {
                reject(e);
            }
        });
    });
};

module.exports = Bot;
<commit_msg>capture team info from start event<commit_after>var request = require('request');
var Vow = require('vow');
var extend = require('extend');
var WebSocket = require('ws');
var util = require('util');
var utils = require('./libs/utils.js');
var find = utils.find;
var assert = utils.assert;
var EventEmitter = require('events').EventEmitter;

/**
 * @param {object} params
 * @constructor
 */
function Bot(params) {
    this.token = params.token;
    this.name = params.name;

    assert(params.token, 'token must be defined');
    this.login();
}

util.inherits(Bot, EventEmitter);

/**
 * Starts a Real Time Messaging API session
 */
Bot.prototype.login = function() {
    this._api('rtm.start').then(function(data) {
        this.wsUrl = data.url;
        this.self = data.self;
        this.team = data.team;
        this.channels = data.channels;
        this.users = data.users;
        this.ims = data.ims;
        this.groups = data.groups;

        this.emit('start');

        this.connect();
    }.bind(this)).fail(function(data) {
        assert(false, data.error);
    }).done();
};

/**
 * Establish a WebSocket connection
 */
Bot.prototype.connect = function() {
    this.ws = new WebSocket(this.wsUrl);

    this.ws.on('open', function(data) {
        this.emit('open', data);
    }.bind(this));

    this.ws.on('close', function(data) {
        this.emit('close', data);
    }.bind(this));

    this.ws.on('message', function(data) {
        try {
            this.emit('message', JSON.parse(data));
        } catch (e) {
            console.log(e);
        }
    }.bind(this));
};

/**
 * Get channels
 * @returns {vow.Promise}
 */
Bot.prototype.getChannels = function() {
    if (this.channels) {
        return Vow.fulfill({ channels: this.channels });
    }
    return this._api('channels.list');
};

/**
 * Get users
 * @returns {vow.Promise}
 */
Bot.prototype.getUsers = function() {
    if (this.users) {
        return Vow.fulfill({ members: this.users });
    }

    return this._api('users.list');
};

/**
 * Get groups
 * @returns {vow.Promise}
 */
Bot.prototype.getGroups = function() {
    if (this.groups) {
        return Vow.fulfill({ groups: this.groups });
    }

    return this._api('groups.list');
};

/**
 * Get user by name
 * @param {string} name
 * @returns {object}
 */
Bot.prototype.getUser = function(name) {
    return this.getUsers().then(function(data) {
        return find(data.members, { name: name });
    });
};

/**
 * Get channel by name
 * @param {string} name
 * @returns {object}
 */
Bot.prototype.getChannel = function(name) {
    return this.getChannels().then(function(data) {
        return find(data.channels, { name: name });
    });
};

/**
 * Get group by name
 * @param {string} name
 * @returns {object}
 */
Bot.prototype.getGroup = function(name) {
    return this.getGroups().then(function(data) {
        return find(data.groups, { name: name });
    });
};

/**
 * Get channel ID
 * @param {string} name
 * @returns {string}
 */
Bot.prototype.getChannelId = function(name) {
    return this.getChannel(name).then(function(channel) {
        return channel.id;
    });
};

/**
 * Get group ID
 * @param {string} name
 * @returns {string}
 */
Bot.prototype.getGroupId = function(name) {
    return this.getGroup(name).then(function(group) {
        return group.id;
    });
};

/**
 * Get "direct message" channel ID
 * @param {string} name
 * @returns {vow.Promise}
 */
Bot.prototype.getChatId = function(name) {
    return this.getUser(name).then(function(data) {

        var chatId = find(this.ims, { user: data.id }).id;

        return chatId || this.openIm(data.id);
    }.bind(this)).then(function(data) {
        return typeof data === 'string' ? data : data.channel.id;
    });
};

/**
 * Opens a "direct message" channel with another member of your Slack team
 * @param {string} userId
 * @returns {vow.Promise}
 */
Bot.prototype.openIm = function(userId) {
    return this._api('im.open', {user: userId});
};

/**
 * Posts a message to a channel by ID
 * @param {string} id - channel ID
 * @param {string} text
 * @param {object} params
 * @returns {vow.Promise}
 */
Bot.prototype.postMessage = function(id, text, params) {
    params = extend({
        text: text,
        channel: id,
        username: this.name
    }, params || {});

    return this._api('chat.postMessage', params);
};

/**
 * Posts a message to user by name
 * @param {string} name
 * @param {string} text
 * @param {object} params
 * @param {function} cb
 * @returns {vow.Promise}
 */
Bot.prototype.postMessageToUser = function(name, text, params, cb) {
    return this._post('user', name, text, params, cb);
};

/**
 * Posts a message to channel by name
 * @param {string} name
 * @param {string} text
 * @param {object} params
 * @param {function} cb
 * @returns {vow.Promise}
 */
Bot.prototype.postMessageToChannel = function(name, text, params, cb) {
    return this._post('channel', name, text, params, cb);
};

/**
 * Posts a message to group by name
 * @param {string} name
 * @param {string} text
 * @param {object} params
 * @param {function} cb
 * @returns {vow.Promise}
 */
Bot.prototype.postMessageToGroup = function(name, text, params, cb) {
    return this._post('group', name, text, params, cb);
};

/**
 * Common method for posting messages
 * @param {string} type
 * @param {string} name
 * @param {string} text
 * @param {object} params
 * @param {function} cb
 * @returns {vow.Promise}
 * @private
 */
Bot.prototype._post = function(type, name, text, params, cb) {
    var method = ({
        'group': 'getGroupId',
        'channel': 'getChannelId',
        'user': 'getChatId'
    })[type];

    if (typeof params === 'function') {
        cb = params;
        params = null;
    }

    return this[method](name).then(function(itemId) {
        return this.postMessage(itemId, text, params);
    }.bind(this)).always(function(data) {
        if (cb) {
            cb(data._value);
        }
    });
};

/**
 * Posts a message to group | channel | user
 * @param {string} name
 * @param {string} text
 * @param {object} params
 * @param {function} cb
 * @returns {vow.Promise}
 */
Bot.prototype.postTo = function(name, text, params, cb) {
    return Vow.all([this.getChannels(), this.getUsers(), this.getGroups()]).then(function(data) {

        var all = [].concat(data[0].channels, data[1].members, data[2].groups);
        var result = find(all, {name: name});

        assert(Object.keys(result).length, 'wrong name');

        if (result['is_channel']) {
            return this.postMessageToChannel(name, text, params, cb);
        } else if (result['is_group']) {
            return this.postMessageToGroup(name, text, params, cb);
        } else {
            return this.postMessageToUser(name, text, params, cb);
        }
    }.bind(this));
};

/**
 * Send request to API method
 * @param {string} methodName
 * @param {object} params
 * @returns {vow.Promise}
 * @private
 */
Bot.prototype._api = function(methodName, params) {
    params = extend(params || {}, {token: this.token});

    var data = {
        url: 'https://slack.com/api/' + methodName,
        form: params
    };

    return new Vow.Promise(function(resolve, reject) {

        request.post(data, function(err, request, body) {
            if (err) {
                reject(err);

                return false;
            }

            try {
                body = JSON.parse(body);

                // Response always contain a top-level boolean property ok,
                // indicating success or failure
                if (body.ok) {
                    resolve(body);
                } else {
                    reject(body);
                }

            } catch (e) {
                reject(e);
            }
        });
    });
};

module.exports = Bot;
<|endoftext|>


<commit_before>'use strict';

const spawn = (command, args, cwd) => {
    return new Promise((resolve, reject) => {
        try {
            if (!args) args = [];

            conosole.log(`$ ${command} ${args.join(' ')}`);

            const child = require('child_process').spawn(command, args, {
                cwd,
                stdio: 'pipe',
            });

            child.on('exit', (code) => {
                if (code) {
                    console.error(`${command}:${child.pid} exitied with ${code}`);
                    return reject(code);
                }
                console.log(`${command}:${child.pid} exitied with ${code}`);
                return resolve();
            });

            child.stdin.end();

            child.stdout.pipe(process.stdout);
            child.stderr.pipe(process.stderr);
        } catch (e) {
            reject(e);
        }
    });
};

const chunks = [];
process.stdin
    .on('data', (d) => chunks.push(d))
    .on('end', () => {
        const json = Buffer.concat(chunks).toString();
        const {
            build,
            repository,
        } = JSON.parse(json);

        const ref = build.ref;
        const id = build.commit_id;

        const clone_url = repository.clone_url;
        const full_name = repository.full_name;

        const image_name = full_name.toLowerCase();
        const tag = ref.split('/')[2];

        const ref_type = ref.split('/')[1];
        const latest = ref_type === 'heads' && (
            tag === 'master' ? 'latest' : `${tag}-latest`
        );

        console.log('Build started');

        spawn('git', ['init', 'build'])
            .then(() => spawn('git', ['fetch', clone_url, tag], 'build'))
            .then(() => spawn('git', ['checkout', '--force', id], 'build'))
            .then(() => spawn('git', ['submodule', 'update', '--init', '--recursive'], 'build'))
            .then(() => spawn('docker', ['build', '-t', `${image_name}:${tag}`, 'build']))
            .then(() => latest &&
                spawn('docker', ['tag', '-f', `${image_name}:${tag}`, `${image_name}:${latest}`])
            )
            .then(() => {
                console.log('Bulid done');
                process.exit();
            })
            .catch((e) => {
                consoler.error(e);
                process.exit(1)
            });
    });
<commit_msg>Fix console<commit_after>'use strict';

const spawn = (command, args, cwd) => {
    return new Promise((resolve, reject) => {
        try {
            if (!args) args = [];

            console.log(`$ ${command} ${args.join(' ')}`);

            const child = require('child_process').spawn(command, args, {
                cwd,
                stdio: 'pipe',
            });

            child.on('exit', (code) => {
                if (code) {
                    console.error(`${command}:${child.pid} exitied with ${code}`);
                    return reject(code);
                }
                console.log(`${command}:${child.pid} exitied with ${code}`);
                return resolve();
            });

            child.stdin.end();

            child.stdout.pipe(process.stdout);
            child.stderr.pipe(process.stderr);
        } catch (e) {
            reject(e);
        }
    });
};

const chunks = [];
process.stdin
    .on('data', (d) => chunks.push(d))
    .on('end', () => {
        try {
            const json = Buffer.concat(chunks).toString();
            const data = JSON.parse(json);
            const build = data.build;
            const repository = data.repository;

            console.log(build);
            console.log(repository);

            const ref = build.ref;
            const id = build.commit_id;

            const clone_url = repository.clone_url;
            const full_name = repository.full_name;

            const image_name = full_name.toLowerCase();
            const tag = ref.split('/')[2];

            const ref_type = ref.split('/')[1];
            const latest = ref_type === 'heads' && (
                tag === 'master' ? 'latest' : `${tag}-latest`
            );

            console.log('Build started');

            spawn('git', ['init', 'build'])
                .then(() => spawn('git', ['fetch', clone_url, tag], 'build'))
                .then(() => spawn('git', ['checkout', '--force', id], 'build'))
                .then(() => spawn('git', ['submodule', 'update', '--init', '--recursive'], 'build'))
                .then(() => spawn('docker', ['build', '-t', `${image_name}:${tag}`, 'build']))
                .then(() => latest &&
                    spawn('docker', ['tag', '-f', `${image_name}:${tag}`, `${image_name}:${latest}`])
                )
                .then(() => {
                    console.log('Bulid done');
                    process.exit();
                })
                .catch((e) => {
                    consoler.error(e);
                    process.exit(1)
                });
        } catch (e) {
            console.error(e);
            process.exit(2);
        }
    });
<|endoftext|>


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

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

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

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, response) {
  response.render('pages/index');
});

app.get('/db', function (request, response) {
  pg.connect(process.env.DATABASE_URL, function(err, client, done) {
    client.query('SELECT * FROM test_table ', function(err, result) {
      done();
      if (err)
       { console.error(err); response.send("Error " + err); }
      else
       { response.send(result); }
    });
  });
});

app.get('/userdata',function(request,response){

	var query1 = url.parse(request.url, true);
	var name = query1.query.uname;
	var pass = query1.query.pass;

	pg.connect(process.env.DATABASE_URL, function(err, client, done) {

  	  client.query('SELECT * FROM userdata WHERE name = 'shubham' ', function(err, result) {
      if (err)
       { console.error(err); response.send("Error " + err); }
      else
       { response.send(result); }
    });
  });
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

<commit_msg>make-it-better<commit_after>var express = require('express');
var app = express();
var pg = require('pg');
var url = require('url');

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

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

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, response) {
  response.render('pages/index');
});

app.get('/db', function (request, response) {
  pg.connect(process.env.DATABASE_URL, function(err, client, done) {
    client.query('SELECT * FROM test_table ', function(err, result) {
      done();
      if (err)
       { console.error(err); response.send("Error " + err); }
      else
       { response.send(result); }
    });
  });
});

app.get('/userdata',function(request,response){

	var query1 = url.parse(request.url, true);
	var name = query1.query.uname;
	var pass = query1.query.pass;

	pg.connect(process.env.DATABASE_URL, function(err, client, done) {

  	  client.query('SELECT * FROM userdata WHERE name = /'shubham'/ ', function(err, result) {
      if (err)
       { console.error(err); response.send("Error " + err); }
      else
       { response.send(result); }
    });
  });
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

<|endoftext|>


<commit_before>'use strict';

/**
 * Require 'em all!
 */
var glob    = require('glob');
var map     = require('vinyl-map');
var colors  = require('colors');

var path    = require('path');
var fs      = require('fs');

/**
 * Output a message, e.g. errors, warnings,...
 * @param  {Object} options Title, message
 */
var message = function (options) {
  options = options || {};
  options.title = options.title || 'Error!';
  options.message = options.message || '';

  console.log('gulp-jade-globbing'.bold.red + ': '.red + options.title);
  console.log(options.message);
};

/**
 * Remove new lines (you never know!)
 * @param  {String} string Input string
 * @return {String}        Output string without new lines
 */
var removeNewLines = function (string) {
  return string.replace(/(\r\n|\n|\r)/gm, '');
};

/**
 * Check if given string has indentation or not
 * @param  {String} string Input string
 * @return {Boolean}
 */
var hasIndent = function (string) {
  return /[\s](\binclude\b|\bextends\b)/g.test(removeNewLines(string));
};

/**
 * Return indentation of a string
 * @param  {String} string Input string
 * @return {String}        Indentation
 */
var getIndentation = function (string) {
  return /(\s*)?(?:\binclude\b|\bextends\b)/g.exec(removeNewLines(string))[1] || '';
};

/**
 * Return if string is an "include" or "extends"
 * @param  {String} string Input string
 * @return {String}        "include" or "extends"
 */
var getType = function (string) {
  return /[\s]?extends\s/g.test(removeNewLines(string)) ? 'extends' : 'include';
};

/**
 * Check if given object is empty or not.
 * @param  {Object}  obj The object to check
 * @return {Boolean}
 */
var isEmptyObject = function (obj) {
  return Object.keys(obj).length === 0;
};

/**
 * Regex tests to check which type of globbing is used
 * @return {Object} Tests
 */
var regexTests = {
  folder: /\/\*\*\/\*.jade/,
  direct: /[^*]\.jade/,
  file: /[^*]\/\*\.jade/,
  all: /\*\/\*[^\.]?/,
};

/**
 * Get type of globbing used via path string
 * @param  {String} path Path which includes globbing stuff
 * @return {String}      Globbing type used
 */
var getGlobType = function (path) {
  var globType;

  Object.keys(regexTests).forEach(function (type) {
    if (regexTests[type].test(path)) {
      globType = type;
      return false;
    }
  });

  return globType;
};

/**
 * Parse the files that will be extended
 * @param  {String} path     Path of the requested file
 * @param  {String} filename Name of the file
 * @return {String}          File content
 */
var parseExtends = function(path, fileName) {
  var data = fs.readFileSync(path + fileName).toString();
  return data;
}

module.exports = function (options) {
  /**
   * Default options object
   * @type {Object}
   */
  var opt = options || {};

  /**
   * Ignore specific paths which shouldn't be included
   * @type {Array}
   */
  opt.ignore = opt.ignore || [];
  if (typeof opt.ignore == 'string') opt.ignore = [opt.ignore];

  /**
   * Check if given path should be ignored or not
   * @param  {String} path Path to check
   * @return {Boolean}     Yep/Nope
   */
  var ignorePath = function (path) {
    var ignore = false;

    if (opt.ignore.length > 0) {
      opt.ignore.forEach(function (ignoreFolder) {
        if ((new RegExp(ignoreFolder)).test(path)) {
          ignore = true;
        }
      });
    }

    return ignore;
  };

  /**
   * Turn on/off placeholder replacement
   * @type {Object}
   */
  opt.placeholder = opt.placeholder || {};

  return map(function (buffer, filepath) {
    var content             = buffer.toString();
    var contentRegex        = /^((?:\s+)?(?:\binclude\b|\bextends\b)\s.+)$/gm;
    var globRegEx           = /\/\*/;
    var placeholderRegEx    = /\{/;
    var dirName             = path.dirname(filepath);

    /**
     * Parse all extended files
     */
    content = parseExtends(
      filepath.replace(/\/$/, '').match(/.*\//g)[0],
      content.match(/extends.*/g)[0].replace(/.*\s+/g, '')
    );

    /**
     * Check file for "include"'s and "extends" and replace
     * those with relative paths to given files.
     */
    content = content.replace(contentRegex, function (result, includeGlob) {
      /**
       * This holds all paths found by one glob pattern
       * @type {Array}
       */
      var files = [];

      /**
       * "include" or "extends"?
       * @type {String}
       */
      var lineType = getType(result);

      /**
       * Check if it's a placeholder...
       */
      var isPlaceholder = !isEmptyObject(opt.placeholder) && placeholderRegEx.exec(includeGlob) ? true : false;

      if (isPlaceholder) {
        /**
         * Plain placeholder name
         */
        var placeholder = /\{(.+)\}/.exec(includeGlob)[1];

        /**
         * Iterate over all placeholders defined...
         */
        Object.keys(opt.placeholder).forEach(function (name) {
          /**
           * ... and if we have a match...
           */
          if (placeholder === name) {
            var placeholderPath = includeGlob.replace(
              /^(?:\s+)?(?:\binclude\b|\bextends\b)\s({.+})$/,
              opt.placeholder[name]
            );

            var placeholderPathArr = placeholderPath.split(path.sep);
            var rootDir = placeholderPathArr[0] === '.' ? placeholderPathArr[1] : placeholderPathArr[0];
            var relativeFilepath = rootDir + dirName.split(rootDir)[1];
            var relativePath = path.relative(relativeFilepath, placeholderPath);

            includeGlob = includeGlob.replace(
              '{' + name + '}',
              relativePath
            );
          }
        });
      }

      /**
       * Check if we have a glob pattern...
       */
      var hasGlobPattern = includeGlob.match(globRegEx);

      /**
       * Include Path containing the glob
       */
      var includeGlobPath = includeGlob.replace(/^\s\s*/, '');
          includeGlobPath = includeGlobPath.replace(/^(\binclude\b|\bextends\b)\s+/, '');

      /**
       * If we have a glob pattern in the current line...
       */
      if (hasGlobPattern || isPlaceholder) {
        glob.sync(includeGlobPath, { cwd: dirName }).forEach(function (includePath) {
          /**
           * ... push only ".jade" filepaths into the files array...
           */
          if (path.extname(includePath) === '.jade') {
            /**
             * ... if they are not set to be ignored.
             */
            if (!ignorePath(path.resolve(dirName, includePath))) {
              files.push(includePath);
            } else if (isPlaceholder && !hasGlobPattern) {
              files.push(includePath);
            }
          }
        });

        /**
         * If we managed to push filepaths into the files array...
         */
        if (files.length > 0) {
          /**
           * ... and, if it's an "extends" statement, contains
           * no globs or placeholders...
           */
          if (lineType === 'extends' && /\s?(?:\bextends\b)\s(?:[^*{]+)$/.test(includeGlob) === false) {
            var errorMessage = '  statement:    ' + includeGlobPath.cyan + '\n';

            if (isPlaceholder) {
              errorMessage  += '  placeholder:  {' + placeholder + '}\n';
            }

            message({
              title: 'Error!\n  glob patterns are not allowed on extend statements.'.red,
              message: errorMessage
            });
          } else {
            /**
             * ... we can now replace the line containing the glob...
             */
            result = '';

            /**
             * ... with the found file paths.
             */
            files.forEach(function (includePath) {
              result += getIndentation(includeGlob) + lineType + ' ' + includePath + '\n';
            });
          }
        /**
         * Otherwise show a warning about the glob pattern not matching.
         */
        } else {
          var warningMessage = '  pattern:      ' + includeGlobPath.cyan + '\n';

          if (isPlaceholder) {
            warningMessage  += '  placeholder:  {' + placeholder + '}\n';
          }

          message({
            title: 'Warning!\n  glob pattern did not match any files.'.red,
            message: warningMessage
          });

          result = '//- No file(s) found in ' + includeGlobPath + '\n';
        }
      }

      return result;
    });

    return content;
  });
};
<commit_msg>Revert "Parsing extended files to avoid forget some "hidden" globbing"<commit_after>'use strict';

/**
 * Require 'em all!
 */
var glob    = require('glob');
var map     = require('vinyl-map');
var colors  = require('colors');

var path    = require('path');

/**
 * Output a message, e.g. errors, warnings,...
 * @param  {Object} options Title, message
 */
var message = function (options) {
  options = options || {};
  options.title = options.title || 'Error!';
  options.message = options.message || '';

  console.log('gulp-jade-globbing'.bold.red + ': '.red + options.title);
  console.log(options.message);
};

/**
 * Remove new lines (you never know!)
 * @param  {String} string Input string
 * @return {String}        Output string without new lines
 */
var removeNewLines = function (string) {
  return string.replace(/(\r\n|\n|\r)/gm, '');
};

/**
 * Check if given string has indentation or not
 * @param  {String} string Input string
 * @return {Boolean}
 */
var hasIndent = function (string) {
  return /[\s](\binclude\b|\bextends\b)/g.test(removeNewLines(string));
};

/**
 * Return indentation of a string
 * @param  {String} string Input string
 * @return {String}        Indentation
 */
var getIndentation = function (string) {
  return /(\s*)?(?:\binclude\b|\bextends\b)/g.exec(removeNewLines(string))[1] || '';
};

/**
 * Return if string is an "include" or "extends"
 * @param  {String} string Input string
 * @return {String}        "include" or "extends"
 */
var getType = function (string) {
  return /[\s]?extends\s/g.test(removeNewLines(string)) ? 'extends' : 'include';
};

/**
 * Check if given object is empty or not.
 * @param  {Object}  obj The object to check
 * @return {Boolean}
 */
var isEmptyObject = function (obj) {
  return Object.keys(obj).length === 0;
};

/**
 * Regex tests to check which type of globbing is used
 * @return {Object} Tests
 */
var regexTests = {
  folder: /\/\*\*\/\*.jade/,
  direct: /[^*]\.jade/,
  file: /[^*]\/\*\.jade/,
  all: /\*\/\*[^\.]?/,
};

/**
 * Get type of globbing used via path string
 * @param  {String} path Path which includes globbing stuff
 * @return {String}      Globbing type used
 */
var getGlobType = function (path) {
  var globType;

  Object.keys(regexTests).forEach(function (type) {
    if (regexTests[type].test(path)) {
      globType = type;
      return false;
    }
  });

  return globType;
};

module.exports = function (options) {
  /**
   * Default options object
   * @type {Object}
   */
  var opt = options || {};

  /**
   * Ignore specific paths which shouldn't be included
   * @type {Array}
   */
  opt.ignore = opt.ignore || [];
  if (typeof opt.ignore == 'string') opt.ignore = [opt.ignore];

  /**
   * Check if given path should be ignored or not
   * @param  {String} path Path to check
   * @return {Boolean}     Yep/Nope
   */
  var ignorePath = function (path) {
    var ignore = false;

    if (opt.ignore.length > 0) {
      opt.ignore.forEach(function (ignoreFolder) {
        if ((new RegExp(ignoreFolder)).test(path)) {
          ignore = true;
        }
      });
    }

    return ignore;
  };

  /**
   * Turn on/off placeholder replacement
   * @type {Object}
   */
  opt.placeholder = opt.placeholder || {};

  return map(function (buffer, filepath) {
    var content             = buffer.toString();
    var contentRegex        = /^((?:\s+)?(?:\binclude\b|\bextends\b)\s.+)$/gm;
    var globRegEx           = /\/\*/;
    var placeholderRegEx    = /\{/;
    var dirName             = path.dirname(filepath);

    /**
     * Check file for "include"'s and "extends" and replace
     * those with relative paths to given files.
     */
    content = content.replace(contentRegex, function (result, includeGlob) {
      /**
       * This holds all paths found by one glob pattern
       * @type {Array}
       */
      var files = [];

      /**
       * "include" or "extends"?
       * @type {String}
       */
      var lineType = getType(result);

      /**
       * Check if it's a placeholder...
       */
      var isPlaceholder = !isEmptyObject(opt.placeholder) && placeholderRegEx.exec(includeGlob) ? true : false;

      if (isPlaceholder) {
        /**
         * Plain placeholder name
         */
        var placeholder = /\{(.+)\}/.exec(includeGlob)[1];

        /**
         * Iterate over all placeholders defined...
         */
        Object.keys(opt.placeholder).forEach(function (name) {
          /**
           * ... and if we have a match...
           */
          if (placeholder === name) {
            var placeholderPath = includeGlob.replace(
              /^(?:\s+)?(?:\binclude\b|\bextends\b)\s({.+})$/,
              opt.placeholder[name]
            );

            var placeholderPathArr = placeholderPath.split(path.sep);
            var rootDir = placeholderPathArr[0] === '.' ? placeholderPathArr[1] : placeholderPathArr[0];
            var relativeFilepath = rootDir + dirName.split(rootDir)[1];
            var relativePath = path.relative(relativeFilepath, placeholderPath);

            includeGlob = includeGlob.replace(
              '{' + name + '}',
              relativePath
            );
          }
        });
      }

      /**
       * Check if we have a glob pattern...
       */
      var hasGlobPattern = includeGlob.match(globRegEx);

      /**
       * Include Path containing the glob
       */
      var includeGlobPath = includeGlob.replace(/^\s\s*/, '');
          includeGlobPath = includeGlobPath.replace(/^(\binclude\b|\bextends\b)\s+/, '');

      /**
       * If we have a glob pattern in the current line...
       */
      if (hasGlobPattern || isPlaceholder) {
        glob.sync(includeGlobPath, { cwd: dirName }).forEach(function (includePath) {
          /**
           * ... push only ".jade" filepaths into the files array...
           */
          if (path.extname(includePath) === '.jade') {
            /**
             * ... if they are not set to be ignored.
             */
            if (!ignorePath(path.resolve(dirName, includePath))) {
              files.push(includePath);
            } else if (isPlaceholder && !hasGlobPattern) {
              files.push(includePath);
            }
          }
        });

        /**
         * If we managed to push filepaths into the files array...
         */
        if (files.length > 0) {
          /**
           * ... and, if it's an "extends" statement, contains
           * no globs or placeholders...
           */
          if (lineType === 'extends' && /\s?(?:\bextends\b)\s(?:[^*{]+)$/.test(includeGlob) === false) {
            var errorMessage = '  statement:    ' + includeGlobPath.cyan + '\n';

            if (isPlaceholder) {
              errorMessage  += '  placeholder:  {' + placeholder + '}\n';
            }

            message({
              title: 'Error!\n  glob patterns are not allowed on extend statements.'.red,
              message: errorMessage
            });
          } else {
            /**
             * ... we can now replace the line containing the glob...
             */
            result = '';

            /**
             * ... with the found file paths.
             */
            files.forEach(function (includePath) {
              result += getIndentation(includeGlob) + lineType + ' ' + includePath + '\n';
            });
          }
        /**
         * Otherwise show a warning about the glob pattern not matching.
         */
        } else {
          var warningMessage = '  pattern:      ' + includeGlobPath.cyan + '\n';

          if (isPlaceholder) {
            warningMessage  += '  placeholder:  {' + placeholder + '}\n';
          }

          message({
            title: 'Warning!\n  glob pattern did not match any files.'.red,
            message: warningMessage
          });

          result = '//- No file(s) found in ' + includeGlobPath + '\n';
        }
      }

      return result;
    });

    return content;
  });
};
<|endoftext|>


<commit_before>var fs = require('fs');
var _ = require('lodash')
var Mustache = require('mustache');

var d = new Date();
var curyear = d.getFullYear();

function getMonth(startDateStr) {
    switch (startDateStr.substr(5,2)) {
    case '01':
        return "January ";
    case '02':
        return "February ";
    case '03':
        return "March ";
    case '04':
        return "April ";
    case '05':
        return "May ";
    case '06':
        return "June ";
    case '07':
        return "July ";
    case '08':
        return "August ";
    case '09':
        return "September ";
    case '10':
        return "October ";
    case '11':
        return "November ";
    case '12':
        return "December ";
    }
}

function render(resumeObject) {

    resumeObject.basics.capitalName = resumeObject.basics.name.toUpperCase();

    _.each(resumeObject.basics.profiles, function(p){
        switch(p.network.toLowerCase()) {
            case "Facebook":
            case "facebook":
                p.iconClass = "fa fa-facebook-square";
                break;
            case "Github":
            case "github":
                p.iconClass = "fa fa-github-square";
                break;
            case "Twitter":
            case "twitter":
                p.iconClass = "fa fa-twitter-square";
                break;
            case "googlePlus":
            case "GooglePlus":
            case: "google-plus":
            case "googleplus":
                p.iconClass = "fa fa-google-plus-square";
                break;
            case "youtube":
            case "Youtube":
            case "YouTube":
                p.iconClass = "fa fa-youtube-square";
                break;
            case "vimeo":
            case: "Vimeo":
                p.iconClass = "fa fa-vimeo-square";
                break;
            case "linkedin":
            case "Linkedin":
                p.iconClass = "fa fa-linkedin-square";
                break;
            case "pinterest":
            case "Pinterest":
                p.iconClass = "fa fa-pinterest-square";
                break;
            case "flickr":
            case "flicker":
            case: "Flickr":
                p.iconClass = "fa fa-flickr";
                break;
            case "behance":
            case "Behance":
                p.iconClass = "fa fa-behance-square";
                break;
            case "dribbble":
            case "Dribbble":
            case "dribble":
                p.iconClass = "fa fa-dribbble";
                break;
            case "codepen":
            case "Codepen":
            case "codePen":
                p.iconClass = "fa fa-codepen";
                break;
            case "soundcloud":
            case "Soundcloud":
            case "soundCloud":
                p.iconClass = "fa fa-soundcloud";
                break;
            case "steam":
            case "Steam":
                p.iconClass = "fa fa-steam";
                break;
            case "reddit":
            case "Reddit":
                p.iconClass = "fa fa-reddit";
                break;
            case "tumblr":
            case "Tumblr":
            case "tumbler":
                p.iconClass = "fa fa-tumblr-square";
                break;
            case "stack-overflow":
            case "stackOverflow":
            case "StackOverflow":
                p.iconClass = "fa fa-stack-overflow";
                break;
            case "blog":
            case "Blog":
            case "rss":
                p.iconClass = "fa fa-rss-square";
                break;
        }

        if (p.url) {
            p.text = p.url;
        } else {
            p.text = p.network + ": " + p.username;
        }
    });

    if (resumeObject.work && resumeObject.work.length) {
        resumeObject.workBool = true;
        _.each(resumeObject.work, function(w){
            if (w.startDate) {
                w.startDateYear = (w.startDate || "").substr(0,4);
                w.startDateMonth = getMonth(w.startDate || "");

            }
            if(w.endDate) {
                w.endDateYear = (w.endDate || "").substr(0,4);
                w.endDateMonth = getMonth(w.endDate || "");
            } else {
                w.endDateYear = 'Present'
            }
            if (w.highlights) {
                if (w.highlights[0]) {
                    if (w.highlights[0] != "") {
                        w.boolHighlights = true;
                    }
                }
            }
        });
    }

    if (resumeObject.volunteer && resumeObject.volunteer.length) {
        resumeObject.volunteerBool = true;
        _.each(resumeObject.volunteer, function(w){
            if (w.startDate) {
                w.startDateYear = (w.startDate || "").substr(0,4);
                w.startDateMonth = getMonth(w.startDate || "");

            }
            if(w.endDate) {
                w.endDateYear = (w.endDate || "").substr(0,4);
                w.endDateMonth = getMonth(w.endDate || "");
            } else {
                w.endDateYear = 'Present'
            }
            if (w.highlights) {
                if (w.highlights[0]) {
                    if (w.highlights[0] != "") {
                        w.boolHighlights = true;
                    }
                }
            }
        });
    }

    if (resumeObject.education && resumeObject.education.length) {
        if (resumeObject.education[0].institution) {
            resumeObject.educationBool = true;
            _.each(resumeObject.education, function(e){
                if( !e.area || !e.studyType ){
                  e.educationDetail = (e.area == null ? '' : e.area) + (e.studyType == null ? '' : e.studyType);
                } else {
                  e.educationDetail = e.area + ", "+ e.studyType;
                }
                if (e.startDate) {
                    e.startDateYear = e.startDate.substr(0,4);
                    e.startDateMonth = getMonth(e.startDate || "");
                } else {
                    e.endDateMonth = "";
                }
                if (e.endDate) {
                    e.endDateYear = e.endDate.substr(0,4);
                    e.endDateMonth = getMonth(e.endDate || "")

                    if (e.endDateYear > curyear) {
                        e.endDateYear += " (expected)";
                    }
                } else {
                    e.endDateYear = 'Present'
                    e.endDateMonth = '';
                }
                if (e.courses) {
                    if (e.courses[0]) {
                        if (e.courses[0] != "") {
                            e.educationCourses = true;
                        }
                    }
                }
            });
        }
    }

    if (resumeObject.awards && resumeObject.awards.length) {
        if (resumeObject.awards[0].title) {
            resumeObject.awardsBool = true;
            _.each(resumeObject.awards, function(a){
                a.year = (a.date || "").substr(0,4);
                a.day = (a.date || "").substr(8,2);
                a.month = getMonth(a.date || "");
            });
        }
    }

    if (resumeObject.publications && resumeObject.publications.length) {
        if (resumeObject.publications[0].name) {
            resumeObject.publicationsBool = true;
            _.each(resumeObject.publications, function(a){
                a.year = (a.releaseDate || "").substr(0,4);
                a.day = (a.releaseDate || "").substr(8,2);
                a.month = getMonth(a.releaseDate || "");
            });
        }
    }

    if (resumeObject.skills && resumeObject.skills.length) {
        if (resumeObject.skills[0].name) {
            resumeObject.skillsBool = true;
        }
    }

    if (resumeObject.interests && resumeObject.interests.length) {
        if (resumeObject.interests[0].name) {
            resumeObject.interestsBool = true;
        }
    }

    if (resumeObject.languages && resumeObject.languages.length) {
        if (resumeObject.languages[0].language) {
            resumeObject.languagesBool = true;
        }
    }

    if (resumeObject.references && resumeObject.references.length) {
        if (resumeObject.references[0].name) {
            resumeObject.referencesBool = true;
        }
    }

    resumeObject.css = fs.readFileSync(__dirname + "/style.css", "utf-8");
    resumeObject.printcss = fs.readFileSync(__dirname + "/print.css", "utf-8");
    var theme = fs.readFileSync(__dirname + '/resume.template', 'utf8');
    var resumeHTML = Mustache.render(theme, resumeObject);

    return resumeHTML;
};
module.exports = {
    render: render
}
<commit_msg>Removed capitalization<commit_after>var fs = require('fs');
var _ = require('lodash')
var Mustache = require('mustache');

var d = new Date();
var curyear = d.getFullYear();

function getMonth(startDateStr) {
    switch (startDateStr.substr(5,2)) {
    case '01':
        return "January ";
    case '02':
        return "February ";
    case '03':
        return "March ";
    case '04':
        return "April ";
    case '05':
        return "May ";
    case '06':
        return "June ";
    case '07':
        return "July ";
    case '08':
        return "August ";
    case '09':
        return "September ";
    case '10':
        return "October ";
    case '11':
        return "November ";
    case '12':
        return "December ";
    }
}

function render(resumeObject) {

    resumeObject.basics.capitalName = resumeObject.basics.name.toUpperCase();

    _.each(resumeObject.basics.profiles, function(p){
        switch(p.network.toLowerCase()) {
            case "facebook":
                p.iconClass = "fa fa-facebook-square";
                break;
            case "github":
                p.iconClass = "fa fa-github-square";
                break;
            case "twitter":
                p.iconClass = "fa fa-twitter-square";
                break;
            case "googlePlus":
            case: "google-plus":
            case "googleplus":
                p.iconClass = "fa fa-google-plus-square";
                break;
            case "youtube":
            case "YouTube":
                p.iconClass = "fa fa-youtube-square";
                break;
            case "vimeo":
                p.iconClass = "fa fa-vimeo-square";
                break;
            case "linkedin":
                p.iconClass = "fa fa-linkedin-square";
                break;
            case "pinterest":
                p.iconClass = "fa fa-pinterest-square";
                break;
            case "flickr":
            case "flicker":
                p.iconClass = "fa fa-flickr";
                break;
            case "behance":
                p.iconClass = "fa fa-behance-square";
                break;
            case "dribbble":
            case "dribble":
                p.iconClass = "fa fa-dribbble";
                break;
            case "codepen":
            case "codePen":
                p.iconClass = "fa fa-codepen";
                break;
            case "soundcloud":
            case "soundCloud":
                p.iconClass = "fa fa-soundcloud";
                break;
            case "steam":
                p.iconClass = "fa fa-steam";
                break;
            case "reddit":
                p.iconClass = "fa fa-reddit";
                break;
            case "tumblr":
            case "tumbler":
                p.iconClass = "fa fa-tumblr-square";
                break;
            case "stack-overflow":
            case "stackOverflow":
                p.iconClass = "fa fa-stack-overflow";
                break;
            case "blog":
            case "rss":
                p.iconClass = "fa fa-rss-square";
                break;
        }

        if (p.url) {
            p.text = p.url;
        } else {
            p.text = p.network + ": " + p.username;
        }
    });

    if (resumeObject.work && resumeObject.work.length) {
        resumeObject.workBool = true;
        _.each(resumeObject.work, function(w){
            if (w.startDate) {
                w.startDateYear = (w.startDate || "").substr(0,4);
                w.startDateMonth = getMonth(w.startDate || "");

            }
            if(w.endDate) {
                w.endDateYear = (w.endDate || "").substr(0,4);
                w.endDateMonth = getMonth(w.endDate || "");
            } else {
                w.endDateYear = 'Present'
            }
            if (w.highlights) {
                if (w.highlights[0]) {
                    if (w.highlights[0] != "") {
                        w.boolHighlights = true;
                    }
                }
            }
        });
    }

    if (resumeObject.volunteer && resumeObject.volunteer.length) {
        resumeObject.volunteerBool = true;
        _.each(resumeObject.volunteer, function(w){
            if (w.startDate) {
                w.startDateYear = (w.startDate || "").substr(0,4);
                w.startDateMonth = getMonth(w.startDate || "");

            }
            if(w.endDate) {
                w.endDateYear = (w.endDate || "").substr(0,4);
                w.endDateMonth = getMonth(w.endDate || "");
            } else {
                w.endDateYear = 'Present'
            }
            if (w.highlights) {
                if (w.highlights[0]) {
                    if (w.highlights[0] != "") {
                        w.boolHighlights = true;
                    }
                }
            }
        });
    }

    if (resumeObject.education && resumeObject.education.length) {
        if (resumeObject.education[0].institution) {
            resumeObject.educationBool = true;
            _.each(resumeObject.education, function(e){
                if( !e.area || !e.studyType ){
                  e.educationDetail = (e.area == null ? '' : e.area) + (e.studyType == null ? '' : e.studyType);
                } else {
                  e.educationDetail = e.area + ", "+ e.studyType;
                }
                if (e.startDate) {
                    e.startDateYear = e.startDate.substr(0,4);
                    e.startDateMonth = getMonth(e.startDate || "");
                } else {
                    e.endDateMonth = "";
                }
                if (e.endDate) {
                    e.endDateYear = e.endDate.substr(0,4);
                    e.endDateMonth = getMonth(e.endDate || "")

                    if (e.endDateYear > curyear) {
                        e.endDateYear += " (expected)";
                    }
                } else {
                    e.endDateYear = 'Present'
                    e.endDateMonth = '';
                }
                if (e.courses) {
                    if (e.courses[0]) {
                        if (e.courses[0] != "") {
                            e.educationCourses = true;
                        }
                    }
                }
            });
        }
    }

    if (resumeObject.awards && resumeObject.awards.length) {
        if (resumeObject.awards[0].title) {
            resumeObject.awardsBool = true;
            _.each(resumeObject.awards, function(a){
                a.year = (a.date || "").substr(0,4);
                a.day = (a.date || "").substr(8,2);
                a.month = getMonth(a.date || "");
            });
        }
    }

    if (resumeObject.publications && resumeObject.publications.length) {
        if (resumeObject.publications[0].name) {
            resumeObject.publicationsBool = true;
            _.each(resumeObject.publications, function(a){
                a.year = (a.releaseDate || "").substr(0,4);
                a.day = (a.releaseDate || "").substr(8,2);
                a.month = getMonth(a.releaseDate || "");
            });
        }
    }

    if (resumeObject.skills && resumeObject.skills.length) {
        if (resumeObject.skills[0].name) {
            resumeObject.skillsBool = true;
        }
    }

    if (resumeObject.interests && resumeObject.interests.length) {
        if (resumeObject.interests[0].name) {
            resumeObject.interestsBool = true;
        }
    }

    if (resumeObject.languages && resumeObject.languages.length) {
        if (resumeObject.languages[0].language) {
            resumeObject.languagesBool = true;
        }
    }

    if (resumeObject.references && resumeObject.references.length) {
        if (resumeObject.references[0].name) {
            resumeObject.referencesBool = true;
        }
    }

    resumeObject.css = fs.readFileSync(__dirname + "/style.css", "utf-8");
    resumeObject.printcss = fs.readFileSync(__dirname + "/print.css", "utf-8");
    var theme = fs.readFileSync(__dirname + '/resume.template', 'utf8');
    var resumeHTML = Mustache.render(theme, resumeObject);

    return resumeHTML;
};
module.exports = {
    render: render
}
<|endoftext|>


<commit_before>module.exports = Swarm

var addrToIPPort = require('addr-to-ip-port') // browser exclude
var debug = require('debug')('bittorrent-swarm')
var dezalgo = require('dezalgo')
var EventEmitter = require('events').EventEmitter
var inherits = require('inherits')
var net = require('net') // browser exclude
var Peer = require('./lib/peer')
var speedometer = require('speedometer')
var TCPPool = require('./lib/tcp-pool')

var MAX_CONNS = 55
var RECONNECT_WAIT = [ 1000, 5000, 15000 ]

inherits(Swarm, EventEmitter)

/**
 * BitTorrent Swarm
 *
 * Abstraction of a BitTorrent "swarm", which is handy for managing all peer
 * connections for a given torrent download. This handles connecting to peers,
 * listening for incoming connections, and doing the initial peer wire protocol
 * handshake with peers. It also tracks total data uploaded/downloaded to/from
 * the swarm.
 *
 * @param {Buffer|string} infoHash
 * @param {Buffer|string} peerId
 * @param {Object} opts
 * @param {Object} opts.handshake handshake options (passed to bittorrent-protocol)
 * @param {number} opts.maxConns maximum number of connections in swarm
 */
function Swarm (infoHash, peerId, opts) {
  var self = this
  if (!(self instanceof Swarm)) return new Swarm(infoHash, peerId, opts)
  EventEmitter.call(self)

  self.infoHash = typeof infoHash === 'string'
    ? new Buffer(infoHash, 'hex')
    : infoHash
  self.infoHashHex = self.infoHash.toString('hex')

  self.peerId = typeof peerId === 'string'
    ? new Buffer(peerId, 'hex')
    : peerId
  self.peerIdHex = self.peerId.toString('hex')

  if (!opts) opts = {}

  debug('new swarm (i %s p %s)', self.infoHashHex, self.peerIdHex)

  self.handshakeOpts = opts.handshake // handshake extensions (optional)
  self.maxConns = opts.maxConns !== undefined ? opts.maxConns : MAX_CONNS

  self.destroyed = false
  self.listening = false
  self.paused = false

  self.server = null // tcp listening socket
  self.wires = [] // open wires (added *after* handshake)

  self._queue = [] // queue of outgoing tcp peers to connect to
  self._peers = {} // connected peers (addr/peerId -> Peer)
  self._peersLength = 0 // number of elements in `self._peers` (cache, for perf)
  self._port = 0 // tcp listening port (cache, for perf)

  // track stats
  self.downloaded = 0
  self.uploaded = 0
  self.downloadSpeed = speedometer()
  self.uploadSpeed = speedometer()
}

Object.defineProperty(Swarm.prototype, 'ratio', {
  get: function () {
    var self = this
    return (self.uploaded / self.downloaded) || 0
  }
})

Object.defineProperty(Swarm.prototype, 'numQueued', {
  get: function () {
    var self = this
    return self._queue.length + (self._peersLength - self.numConns)
  }
})

Object.defineProperty(Swarm.prototype, 'numConns', {
  get: function () {
    var self = this
    var numConns = 0
    for (var id in self._peers) {
      var peer = self._peers[id]
      if (peer && peer.conn) numConns += 1
    }
    return numConns
  }
})

Object.defineProperty(Swarm.prototype, 'numPeers', {
  get: function () {
    var self = this
    return self.wires.length
  }
})

/**
 * Add a peer to the swarm.
 * @param {string|simple-peer} peer    "ip:port" string or simple-peer instance
 * @param {string}             peer.id bittorrent peer id (when `peer` is simple-peer)
 */
Swarm.prototype.addPeer = function (peer) {
  var self = this
  if (self.destroyed) {
    if (peer && peer.destroy) peer.destroy(new Error('swarm already destroyed'))
    return
  }
  if (typeof peer === 'string' && !self._validAddr(peer)) {
    debug('ignoring invalid peer %s (from swarm.addPeer)', peer)
    return
  }

  var id = (peer && peer.id) || peer
  if (self._peers[id]) return

  debug('addPeer %s', id)

  var newPeer
  if (typeof peer === 'string') {
    // `peer` in an addr ("ip:port" string)
    newPeer = Peer.createOutgoingTCPPeer(peer, self)
    self._queue.push(newPeer)
    self._drain()
  } else {
    // `peer` is a WebRTC connection (simple-peer)
    newPeer = Peer.createWebRTCPeer(peer, self)
  }
  self._peers[newPeer.id] = newPeer
  self._peersLength += 1
}

/**
 * Add a web seed to the swarm.
 * @param {string} url web seed url
 * @param {Object} parsedTorrent
 */
Swarm.prototype.addWebSeed = function (url, parsedTorrent) {
  var self = this
  if (self.destroyed) return

  if (!/^https?:\/\/.+/.test(url)) {
    debug('ignoring invalid web seed %s (from swarm.addWebSeed)', url)
    return
  }

  if (self._peers[url]) return

  debug('addWebSeed %s', url)

  self._peers[url] = Peer.createWebPeer(url, parsedTorrent, self)
  self._peersLength += 1
}

/**
 * Called whenever a new incoming TCP peer connects to this swarm. Called with a peer
 * that has already sent a handshake.
 * @param {Peer} peer
 */
Swarm.prototype._addIncomingPeer = function (peer) {
  var self = this
  if (self.destroyed) return peer.destroy(new Error('swarm already destroyed'))
  if (self.paused) return peer.destroy(new Error('swarm paused'))

  if (!self._validAddr(peer.addr)) {
    return peer.destroy(new Error('invalid addr ' + peer.addr + ' (from incoming)'))
  }
  debug('_addIncomingPeer %s', peer.id)

  self._peers[peer.id] = peer
  self._peersLength += 1
}

/**
 * Remove a peer from the swarm.
 * @param  {string} id for tcp peers, "ip:port" string; for webrtc peers, peerId
 */
Swarm.prototype.removePeer = function (id) {
  var self = this
  var peer = self._peers[id]
  if (!peer) return

  debug('removePeer %s', id)

  self._peers[id] = null
  self._peersLength -= 1

  peer.destroy()
}

/**
 * Temporarily stop connecting to new peers. Note that this does not pause new
 * incoming connections, nor does it pause the streams of existing connections
 * or their wires.
 */
Swarm.prototype.pause = function () {
  var self = this
  if (self.destroyed) return
  debug('pause')
  self.paused = true
}

/**
 * Resume connecting to new peers.
 */
Swarm.prototype.resume = function () {
  var self = this
  if (self.destroyed) return
  debug('resume')
  self.paused = false
  self._drain()
}

/**
 * Listen on the given port for peer connections.
 * @param {number} port
 * @param {string=} hostname
 * @param {function=} onlistening
 */
Swarm.prototype.listen = function (port, hostname, onlistening) {
  var self = this
  if (typeof hostname === 'function') {
    onlistening = hostname
    hostname = undefined
  }
  if (onlistening) onlistening = dezalgo(onlistening)

  if (self.listening) throw new Error('swarm already listening')

  if (process.browser) {
    onlistening()
  } else {
    self._port = port || TCPPool.getDefaultListenPort(self.infoHashHex)
    self._hostname = hostname
    if (onlistening) self.once('listening', onlistening)

    debug('listen %s', port)

    var pool = TCPPool.addSwarm(self)
    self.server = pool.server
  }
}

Swarm.prototype._onListening = function (port) {
  var self = this
  self._port = port
  self.listening = true
  self.emit('listening')
}

Swarm.prototype.address = function () {
  var self = this
  return self.server.address()
}

/**
 * Destroy the swarm, close all open peer connections, and do cleanup.
 * @param {function} onclose
 */
Swarm.prototype.destroy = function (onclose) {
  var self = this
  if (self.destroyed) return

  self.destroyed = true
  self.listening = false
  self.paused = false

  if (onclose) self.once('close', onclose)

  debug('destroy')

  for (var id in self._peers) {
    self.removePeer(id)
  }

  TCPPool.removeSwarm(self, function () {
    // TODO: only emit when all peers are destroyed
    self.emit('close')
  })
}

/**
 * Pop a peer off the FIFO queue and connect to it. When _drain() gets called,
 * the queue will usually have only one peer in it, except when there are too
 * many peers (over `this.maxConns`) in which case they will just sit in the
 * queue until another connection closes.
 */
Swarm.prototype._drain = function () {
  var self = this
  debug('_drain numConns %s maxConns %s', self.numConns, self.maxConns)
  if (typeof net.connect !== 'function' || self.destroyed || self.paused ||
      self.numConns >= self.maxConns) {
    return
  }
  debug('drain (%s queued, %s/%s peers)', self.numQueued, self.numPeers, self.maxConns)

  var peer = self._queue.shift()
  if (!peer) return // queue could be empty

  debug('tcp connect attempt to %s', peer.addr)
  var parts = addrToIPPort(peer.addr)
  var host = parts[0]
  var port = parts[1]
  var conn = peer.conn = net.connect({
    host: host,
    port: port,
    localAddress: self._hostname
  })

  conn.once('connect', function () { peer.onConnect() })
  conn.once('error', function (err) { peer.destroy(err) })
  peer.setConnectTimeout()

  // When connection closes, attempt reconnect after timeout (with exponential backoff)
  conn.on('close', function () {
    if (self.destroyed) return

    if (peer.retries >= RECONNECT_WAIT.length) {
      debug(
        'conn %s closed: will not re-add (max %s attempts)',
        peer.addr, RECONNECT_WAIT.length
      )
      return
    }

    function readd () {
      var newPeer = Peer.createOutgoingTCPPeer(peer.addr, self)
      newPeer.retries = peer.retries + 1
      self._queue.push(newPeer)
      self._drain()
    }

    var ms = RECONNECT_WAIT[peer.retries]
    debug(
      'conn %s closed: will re-add to queue in %sms (attempt %s)',
      peer.addr, ms, peer.retries + 1
    )

    var readdTimeout = setTimeout(readd, ms)
    if (readdTimeout.unref) readdTimeout.unref()
  })
}

Swarm.prototype._onError = function (err) {
  var self = this
  self.emit('error', err)
  self.destroy()
}

/**
 * Returns `true` if string is valid IPv4/6 address, and is not the address of this swarm.
 * @param {string} addr
 * @return {boolean}
 */
Swarm.prototype._validAddr = function (addr) {
  var self = this
  var parts = addrToIPPort(addr)
  var host = parts[0]
  var port = parts[1]
  return port > 0 && port < 65535 && !(host === '127.0.0.1' && port === self._port)
}
<commit_msg>try to open new conn after removePeer is called<commit_after>module.exports = Swarm

var addrToIPPort = require('addr-to-ip-port') // browser exclude
var debug = require('debug')('bittorrent-swarm')
var dezalgo = require('dezalgo')
var EventEmitter = require('events').EventEmitter
var inherits = require('inherits')
var net = require('net') // browser exclude
var Peer = require('./lib/peer')
var speedometer = require('speedometer')
var TCPPool = require('./lib/tcp-pool')

var MAX_CONNS = 55
var RECONNECT_WAIT = [ 1000, 5000, 15000 ]

inherits(Swarm, EventEmitter)

/**
 * BitTorrent Swarm
 *
 * Abstraction of a BitTorrent "swarm", which is handy for managing all peer
 * connections for a given torrent download. This handles connecting to peers,
 * listening for incoming connections, and doing the initial peer wire protocol
 * handshake with peers. It also tracks total data uploaded/downloaded to/from
 * the swarm.
 *
 * @param {Buffer|string} infoHash
 * @param {Buffer|string} peerId
 * @param {Object} opts
 * @param {Object} opts.handshake handshake options (passed to bittorrent-protocol)
 * @param {number} opts.maxConns maximum number of connections in swarm
 */
function Swarm (infoHash, peerId, opts) {
  var self = this
  if (!(self instanceof Swarm)) return new Swarm(infoHash, peerId, opts)
  EventEmitter.call(self)

  self.infoHash = typeof infoHash === 'string'
    ? new Buffer(infoHash, 'hex')
    : infoHash
  self.infoHashHex = self.infoHash.toString('hex')

  self.peerId = typeof peerId === 'string'
    ? new Buffer(peerId, 'hex')
    : peerId
  self.peerIdHex = self.peerId.toString('hex')

  if (!opts) opts = {}

  debug('new swarm (i %s p %s)', self.infoHashHex, self.peerIdHex)

  self.handshakeOpts = opts.handshake // handshake extensions (optional)
  self.maxConns = opts.maxConns !== undefined ? opts.maxConns : MAX_CONNS

  self.destroyed = false
  self.listening = false
  self.paused = false

  self.server = null // tcp listening socket
  self.wires = [] // open wires (added *after* handshake)

  self._queue = [] // queue of outgoing tcp peers to connect to
  self._peers = {} // connected peers (addr/peerId -> Peer)
  self._peersLength = 0 // number of elements in `self._peers` (cache, for perf)
  self._port = 0 // tcp listening port (cache, for perf)

  // track stats
  self.downloaded = 0
  self.uploaded = 0
  self.downloadSpeed = speedometer()
  self.uploadSpeed = speedometer()
}

Object.defineProperty(Swarm.prototype, 'ratio', {
  get: function () {
    var self = this
    return (self.uploaded / self.downloaded) || 0
  }
})

Object.defineProperty(Swarm.prototype, 'numQueued', {
  get: function () {
    var self = this
    return self._queue.length + (self._peersLength - self.numConns)
  }
})

Object.defineProperty(Swarm.prototype, 'numConns', {
  get: function () {
    var self = this
    var numConns = 0
    for (var id in self._peers) {
      var peer = self._peers[id]
      if (peer && peer.conn) numConns += 1
    }
    return numConns
  }
})

Object.defineProperty(Swarm.prototype, 'numPeers', {
  get: function () {
    var self = this
    return self.wires.length
  }
})

/**
 * Add a peer to the swarm.
 * @param {string|simple-peer} peer    "ip:port" string or simple-peer instance
 * @param {string}             peer.id bittorrent peer id (when `peer` is simple-peer)
 */
Swarm.prototype.addPeer = function (peer) {
  var self = this
  if (self.destroyed) {
    if (peer && peer.destroy) peer.destroy(new Error('swarm already destroyed'))
    return
  }
  if (typeof peer === 'string' && !self._validAddr(peer)) {
    debug('ignoring invalid peer %s (from swarm.addPeer)', peer)
    return
  }

  var id = (peer && peer.id) || peer
  if (self._peers[id]) return

  debug('addPeer %s', id)

  var newPeer
  if (typeof peer === 'string') {
    // `peer` in an addr ("ip:port" string)
    newPeer = Peer.createOutgoingTCPPeer(peer, self)
    self._queue.push(newPeer)
    self._drain()
  } else {
    // `peer` is a WebRTC connection (simple-peer)
    newPeer = Peer.createWebRTCPeer(peer, self)
  }
  self._peers[newPeer.id] = newPeer
  self._peersLength += 1
}

/**
 * Add a web seed to the swarm.
 * @param {string} url web seed url
 * @param {Object} parsedTorrent
 */
Swarm.prototype.addWebSeed = function (url, parsedTorrent) {
  var self = this
  if (self.destroyed) return

  if (!/^https?:\/\/.+/.test(url)) {
    debug('ignoring invalid web seed %s (from swarm.addWebSeed)', url)
    return
  }

  if (self._peers[url]) return

  debug('addWebSeed %s', url)

  self._peers[url] = Peer.createWebPeer(url, parsedTorrent, self)
  self._peersLength += 1
}

/**
 * Called whenever a new incoming TCP peer connects to this swarm. Called with a peer
 * that has already sent a handshake.
 * @param {Peer} peer
 */
Swarm.prototype._addIncomingPeer = function (peer) {
  var self = this
  if (self.destroyed) return peer.destroy(new Error('swarm already destroyed'))
  if (self.paused) return peer.destroy(new Error('swarm paused'))

  if (!self._validAddr(peer.addr)) {
    return peer.destroy(new Error('invalid addr ' + peer.addr + ' (from incoming)'))
  }
  debug('_addIncomingPeer %s', peer.id)

  self._peers[peer.id] = peer
  self._peersLength += 1
}

/**
 * Remove a peer from the swarm.
 * @param  {string} id for tcp peers, "ip:port" string; for webrtc peers, peerId
 */
Swarm.prototype.removePeer = function (id) {
  var self = this
  var peer = self._peers[id]
  if (!peer) return

  debug('removePeer %s', id)

  self._peers[id] = null
  self._peersLength -= 1

  peer.destroy()

  // If swarm was at capacity before, try to open a new connection now
  self._drain()
}

/**
 * Temporarily stop connecting to new peers. Note that this does not pause new
 * incoming connections, nor does it pause the streams of existing connections
 * or their wires.
 */
Swarm.prototype.pause = function () {
  var self = this
  if (self.destroyed) return
  debug('pause')
  self.paused = true
}

/**
 * Resume connecting to new peers.
 */
Swarm.prototype.resume = function () {
  var self = this
  if (self.destroyed) return
  debug('resume')
  self.paused = false
  self._drain()
}

/**
 * Listen on the given port for peer connections.
 * @param {number} port
 * @param {string=} hostname
 * @param {function=} onlistening
 */
Swarm.prototype.listen = function (port, hostname, onlistening) {
  var self = this
  if (typeof hostname === 'function') {
    onlistening = hostname
    hostname = undefined
  }
  if (onlistening) onlistening = dezalgo(onlistening)

  if (self.listening) throw new Error('swarm already listening')

  if (process.browser) {
    onlistening()
  } else {
    self._port = port || TCPPool.getDefaultListenPort(self.infoHashHex)
    self._hostname = hostname
    if (onlistening) self.once('listening', onlistening)

    debug('listen %s', port)

    var pool = TCPPool.addSwarm(self)
    self.server = pool.server
  }
}

Swarm.prototype._onListening = function (port) {
  var self = this
  self._port = port
  self.listening = true
  self.emit('listening')
}

Swarm.prototype.address = function () {
  var self = this
  return self.server.address()
}

/**
 * Destroy the swarm, close all open peer connections, and do cleanup.
 * @param {function} onclose
 */
Swarm.prototype.destroy = function (onclose) {
  var self = this
  if (self.destroyed) return

  self.destroyed = true
  self.listening = false
  self.paused = false

  if (onclose) self.once('close', onclose)

  debug('destroy')

  for (var id in self._peers) {
    self.removePeer(id)
  }

  TCPPool.removeSwarm(self, function () {
    // TODO: only emit when all peers are destroyed
    self.emit('close')
  })
}

/**
 * Pop a peer off the FIFO queue and connect to it. When _drain() gets called,
 * the queue will usually have only one peer in it, except when there are too
 * many peers (over `this.maxConns`) in which case they will just sit in the
 * queue until another connection closes.
 */
Swarm.prototype._drain = function () {
  var self = this
  debug('_drain numConns %s maxConns %s', self.numConns, self.maxConns)
  if (typeof net.connect !== 'function' || self.destroyed || self.paused ||
      self.numConns >= self.maxConns) {
    return
  }
  debug('drain (%s queued, %s/%s peers)', self.numQueued, self.numPeers, self.maxConns)

  var peer = self._queue.shift()
  if (!peer) return // queue could be empty

  debug('tcp connect attempt to %s', peer.addr)
  var parts = addrToIPPort(peer.addr)
  var host = parts[0]
  var port = parts[1]
  var conn = peer.conn = net.connect({
    host: host,
    port: port,
    localAddress: self._hostname
  })

  conn.once('connect', function () { peer.onConnect() })
  conn.once('error', function (err) { peer.destroy(err) })
  peer.setConnectTimeout()

  // When connection closes, attempt reconnect after timeout (with exponential backoff)
  conn.on('close', function () {
    if (self.destroyed) return

    if (peer.retries >= RECONNECT_WAIT.length) {
      debug(
        'conn %s closed: will not re-add (max %s attempts)',
        peer.addr, RECONNECT_WAIT.length
      )
      return
    }

    function readd () {
      var newPeer = Peer.createOutgoingTCPPeer(peer.addr, self)
      newPeer.retries = peer.retries + 1
      self._queue.push(newPeer)
      self._drain()
    }

    var ms = RECONNECT_WAIT[peer.retries]
    debug(
      'conn %s closed: will re-add to queue in %sms (attempt %s)',
      peer.addr, ms, peer.retries + 1
    )

    var readdTimeout = setTimeout(readd, ms)
    if (readdTimeout.unref) readdTimeout.unref()
  })
}

Swarm.prototype._onError = function (err) {
  var self = this
  self.emit('error', err)
  self.destroy()
}

/**
 * Returns `true` if string is valid IPv4/6 address, and is not the address of this swarm.
 * @param {string} addr
 * @return {boolean}
 */
Swarm.prototype._validAddr = function (addr) {
  var self = this
  var parts = addrToIPPort(addr)
  var host = parts[0]
  var port = parts[1]
  return port > 0 && port < 65535 && !(host === '127.0.0.1' && port === self._port)
}
<|endoftext|>


<commit_before>'use strict';

import React, { Component, PropTypes } from 'react';
import {
  StyleSheet,
  Dimensions,
  Vibration,
  Animated,
  Easing,
  View
} from 'react-native';

import Camera from 'react-native-camera'

export default class QRCodeScanner extends Component {
  static propTypes = {
    onRead: PropTypes.func.isRequired,
    reactivate: PropTypes.bool,
    reactivateTimeout: PropTypes.number,
    fadeIn: PropTypes.bool,
    showMarker: PropTypes.bool,
    customMarker: PropTypes.element,
    cameraStyle: PropTypes.any,
    topViewStyle: PropTypes.any,
    bottomViewStyle: PropTypes.any,
    topContent: PropTypes.oneOfType([
      PropTypes.element,
      PropTypes.string,
    ]),
    bottomContent: PropTypes.oneOfType([
      PropTypes.element,
      PropTypes.string,
    ]),
  }

  static defaultProps = {
    onRead: () => (console.log('QR code scanned!')),
    reactivate: false,
    reactivateTimeout: 0,
    fadeIn: true,
    showMarker: false,
  }

  constructor(props) {
    super(props);
    this.state = {
      scanning: false,
      fadeInOpacity: new Animated.Value(0)
    }

    this._handleBarCodeRead = this._handleBarCodeRead.bind(this);
  }

  componentDidMount() {
    if (this.props.fadeIn) {
      Animated.sequence([
        Animated.delay(1000),
        Animated.timing(
         this.state.fadeInOpacity,
         {
           toValue: 1,
           easing: Easing.inOut(Easing.quad),
         },
        )
      ]).start();
    }
   }

  _setScanning(value) {
    this.setState({ scanning: value });
  }

  _handleBarCodeRead(e) {
    if (!this.state.scanning) {
      Vibration.vibrate();
      this._setScanning(true);
      this.props.onRead(e)
      if (this.props.reactivate) {
        setTimeout(() => (this._setScanning(false)), this.props.reactivateTimeout);
      }
    }
  }

  _renderTopContent() {
    if (this.props.topContent) {
      return this.props.topContent;
    }
    return null;
  }

  _renderBottomContent() {
    if (this.props.bottomContent) {
      return this.props.bottomContent;
    }
    return null;
  }

  _renderCameraMarker() {
    if (this.props.showMarker) {
      return (
      <View style={styles.rectangleContainer}>
        <View style={styles.rectangle}/>
      </View>
      )
    }
    return null;
  }

  _renderCamera() {
    if (this.props.fadeIn) {
      return (
        <Animated.View
          style={{
            opacity: this.state.fadeInOpacity,
            backgroundColor: 'transparent'
        }}>
          <Camera style={[styles.camera, this.props.cameraStyle]} onBarCodeRead={this._handleBarCodeRead.bind(this)}>
            {this._renderCameraMarker()}
          </Camera>
        </Animated.View>
      )
    }
    return (
      <Camera style={[styles.camera, this.props.cameraStyle]} onBarCodeRead={this._handleBarCodeRead.bind(this)}>
        {this._renderCameraMarker()}
      </Camera>
    )
  }

  render() {
    return (
      <View style={styles.mainContainer}>
        <View style={[styles.infoView, this.props.topViewStyle]}>
          {this._renderTopContent()}
        </View>
        {this._renderCamera()}
        <View style={[styles.infoView, this.props.bottomViewStyle]}>
          {this._renderBottomContent()}
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  mainContainer: {
    flex: 1
  },
  infoView: {
    flex: 2,
    justifyContent: 'center',
    alignItems: 'center',
    width: Dimensions.get('window').width,
  },

  camera: {
    flex: 0,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
    height: Dimensions.get('window').width,
    width: Dimensions.get('window').width,
  },

  rectangleContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
  },

  rectangle: {
    height: 250,
    width: 250,
    borderWidth: 2,
    borderColor: '#00FF00',
    backgroundColor: 'transparent',
  },
})
<commit_msg>Added custom marker<commit_after>'use strict';

import React, { Component, PropTypes } from 'react';
import {
  StyleSheet,
  Dimensions,
  Vibration,
  Animated,
  Easing,
  View
} from 'react-native';

import Camera from 'react-native-camera'

export default class QRCodeScanner extends Component {
  static propTypes = {
    onRead: PropTypes.func.isRequired,
    reactivate: PropTypes.bool,
    reactivateTimeout: PropTypes.number,
    fadeIn: PropTypes.bool,
    showMarker: PropTypes.bool,
    customMarker: PropTypes.element,
    cameraStyle: PropTypes.any,
    topViewStyle: PropTypes.any,
    bottomViewStyle: PropTypes.any,
    topContent: PropTypes.oneOfType([
      PropTypes.element,
      PropTypes.string,
    ]),
    bottomContent: PropTypes.oneOfType([
      PropTypes.element,
      PropTypes.string,
    ]),
  }

  static defaultProps = {
    onRead: () => (console.log('QR code scanned!')),
    reactivate: false,
    reactivateTimeout: 0,
    fadeIn: true,
    showMarker: false,
  }

  constructor(props) {
    super(props);
    this.state = {
      scanning: false,
      fadeInOpacity: new Animated.Value(0)
    }

    this._handleBarCodeRead = this._handleBarCodeRead.bind(this);
  }

  componentDidMount() {
    if (this.props.fadeIn) {
      Animated.sequence([
        Animated.delay(1000),
        Animated.timing(
         this.state.fadeInOpacity,
         {
           toValue: 1,
           easing: Easing.inOut(Easing.quad),
         },
        )
      ]).start();
    }
   }

  _setScanning(value) {
    this.setState({ scanning: value });
  }

  _handleBarCodeRead(e) {
    if (!this.state.scanning) {
      Vibration.vibrate();
      this._setScanning(true);
      this.props.onRead(e)
      if (this.props.reactivate) {
        setTimeout(() => (this._setScanning(false)), this.props.reactivateTimeout);
      }
    }
  }

  _renderTopContent() {
    if (this.props.topContent) {
      return this.props.topContent;
    }
    return null;
  }

  _renderBottomContent() {
    if (this.props.bottomContent) {
      return this.props.bottomContent;
    }
    return null;
  }

  _renderCameraMarker() {
    if (this.props.showMarker) {
      if (this.props.customMarker) {
        return this.props.customMarker;
      } else {
        return (
        <View style={styles.rectangleContainer}>
          <View style={styles.rectangle} />
        </View>
        );
      }
    }
    return null;
  }

  _renderCamera() {
    if (this.props.fadeIn) {
      return (
        <Animated.View
          style={{
            opacity: this.state.fadeInOpacity,
            backgroundColor: 'transparent'
        }}>
          <Camera style={[styles.camera, this.props.cameraStyle]} onBarCodeRead={this._handleBarCodeRead.bind(this)}>
            {this._renderCameraMarker()}
          </Camera>
        </Animated.View>
      )
    }
    return (
      <Camera style={[styles.camera, this.props.cameraStyle]} onBarCodeRead={this._handleBarCodeRead.bind(this)}>
        {this._renderCameraMarker()}
      </Camera>
    )
  }

  render() {
    return (
      <View style={styles.mainContainer}>
        <View style={[styles.infoView, this.props.topViewStyle]}>
          {this._renderTopContent()}
        </View>
        {this._renderCamera()}
        <View style={[styles.infoView, this.props.bottomViewStyle]}>
          {this._renderBottomContent()}
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  mainContainer: {
    flex: 1
  },
  infoView: {
    flex: 2,
    justifyContent: 'center',
    alignItems: 'center',
    width: Dimensions.get('window').width,
  },

  camera: {
    flex: 0,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
    height: Dimensions.get('window').width,
    width: Dimensions.get('window').width,
  },

  rectangleContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
  },

  rectangle: {
    height: 250,
    width: 250,
    borderWidth: 2,
    borderColor: '#00FF00',
    backgroundColor: 'transparent',
  },
})
<|endoftext|>


<commit_before>var mosca = require('mosca')

var moscaSettings = function() {
  // for heroku
  if (process.env.NODE_ENV == 'production') {
    console.log('hello production');
    var config = {};
    config.port = process.env.PORT || 1883;
    return config;
  } else {
    return { port: 1883, host: '0.0.0.0' }
  }
}

var server = new mosca.Server(moscaSettings());
server.on('ready', setup);

server.on('clientConnected', function(client) {
  console.log('client connected', client.id);
});

// fired when a message is received
server.on('published', function(packet, client) {
  console.log('Published', packet.payload);
});

server.on('error', function(client) {
  console.log('some errors');
});

// fired when the mqtt server is ready
function setup() {
  console.log('Mosca server is up and running')
}
<commit_msg>attempt to fix heroku setup<commit_after>var mosca = require('mosca')

var moscaSettings = function() {
  // for heroku
  if (process.env.NODE_ENV == 'production') {
    console.log('hello production');
    var config = {};
    config.port = process.env.PORT || 1883;
    console.log(JSON.stringify(config));
    return config;
  } else {
    return { port: 1883, host: '0.0.0.0' }
  }
}

var server = new mosca.Server(moscaSettings());
server.on('ready', setup);

server.on('clientConnected', function(client) {
  console.log('client connected', client.id);
});

// fired when a message is received
server.on('published', function(packet, client) {
  console.log('Published', packet.payload);
});

server.on('error', function(client) {
  console.log('some errors');
});

// fired when the mqtt server is ready
function setup() {
  console.log('Mosca server is up and running')
}
<|endoftext|>