<commit_before>/**
 * Created by guy on 08/08/15.
 */
var net = require('net'),
    readline = require('readline');

var map = {};

var server = net.createServer(function(socket) { //'connection' listener
    console.log('client connected');
    socket.on('end', function() {
        console.log('client disconnected');
    });

    var totalParts = -1,
        parts = 0,
        next = -1,
        command = [],
        reset = function(socket){
            if(socket)
                socket.write('+ERROR\r\n');
            totalParts = -1;
            parts = 0;
            next = -1;
        },
        i = readline.createInterface(socket, socket);

    i.on('line', function (line) {
        console.log(line);
        var prefix = line[0];
        switch(prefix){
            case '*':
                if(totalParts >= 0){
                    return reset(socket);
                }
                totalParts = parseInt(line.substring(1));
                parts = 0;
                next = -1;
                break;
            case '$':
                if(totalParts < 0 || parts >= totalParts || next>=0 ){
                    return reset(socket);
                }
                next = parseInt(line.substring(1));
                break;
            default:
                if(line.length != next){
                    return reset(socket);
                }
                command[parts++] = line;
                next = -1;
                if(parts < totalParts)
                    return;

                switch(command[0].toLowerCase()){
                    case 'ping':
                        socket.write('+PONG\r\n');
                        break;
                    case 'set':
                        map[command[1]] = command[2];
                        socket.write('+OK\r\n');
                        break;
                    case 'get':
                        var value = map[command[1]];
                        if(value) {
                            socket.write('+');
                            socket.write(map[command[1]]);
                            socket.write('\r\n');
                        } else {
                            socket.write('$-1\r\n');
                        }
                        break;
                }
                reset();
                break;
        }

    });
    //socket.write('hello\r\n');
    //socket.pipe(socket);
});

server.on('error', function (e) {
    if (e.code == 'EADDRINUSE') {
        console.log('Address in use, retrying...');
        setTimeout(function () {
            server.close();
            server.listen(PORT, HOST);
        }, 1000);
    }
});

server.listen(6379, function() { //'listening' listener
    var address = server.address();
    console.log("opened server on %j", address);
});<commit_msg>add DEL<commit_after>/**
 * Created by guy on 08/08/15.
 */
var net = require('net'),
    readline = require('readline');

var map = {};

var server = net.createServer(function(socket) { //'connection' listener
    console.log('client connected');
    socket.on('end', function() {
        console.log('client disconnected');
    });

    var totalParts = -1,
        parts = 0,
        next = -1,
        command = [],
        reset = function(socket){
            if(socket)
                socket.write('-ERR wrong command\r\n');
            totalParts = -1;
            parts = 0;
            next = -1;
        },
        i = readline.createInterface(socket, socket);

    i.on('line', function (line) {
        console.log(line);
        var prefix = line[0];
        switch(prefix){
            case '*':
                if(totalParts >= 0){
                    return reset(socket);
                }
                totalParts = parseInt(line.substring(1));
                parts = 0;
                next = -1;
                break;
            case '$':
                if(totalParts < 0 || parts >= totalParts || next>=0 ){
                    return reset(socket);
                }
                next = parseInt(line.substring(1));
                break;
            default:
                if(line.length != next){
                    return reset(socket);
                }
                command[parts++] = line;
                next = -1;
                if(parts < totalParts)
                    return;

                switch(command[0].toLowerCase()){
                    case 'ping':
                        socket.write('+PONG\r\n');
                        break;
                    case 'exists':
                        var value = map[command[1]];
                        if(value) {
                            socket.write(':1\r\n');
                        } else {
                            socket.write(':0\r\n');
                        }
                        break;
                    case 'set':
                        map[command[1]] = command[2];
                        socket.write('+OK\r\n');
                        break;
                    case 'del':
                        var count = 0;
                        for( var i=1; i<parts ; ++i){
                            var key = command[i],
                                value = map[key];
                            if(value) {
                                delete map[key];
                                ++count;
                            }
                        }
                        socket.write(':' + count + '\r\n');
                        break;
                    case 'get':
                        var value = map[command[1]];
                        if(value) {
                            socket.write('$' + value.length.toString() + '\r\n' + value + '\r\n');
                        } else {
                            socket.write('$-1\r\n');
                        }
                        break;
                    case 'mget': // TODO finish it
                        var result = new Array();
                        for( var i=1; i<parts ; ++i){
                            var key = command[i],
                                value = map[key];
                            if(value) {
                                result[i] = value;
                            } else {
                                result[i] = '$-1\r\n';
                            }
                        }
                        socket.write(':' + count + '\r\n');

                        var value = map[command[1]];
                        if(value) {
                            socket.write('$' + value.length.toString() + '\r\n' + value + '\r\n');
                        } else {
                            socket.write('$-1\r\n');
                        }
                        break;
                    default:
                        return reset(socket);
                }
                reset();
                break;
        }

    });
    //socket.write('hello\r\n');
    //socket.pipe(socket);
});

server.on('error', function (e) {
    if (e.code == 'EADDRINUSE') {
        console.log('Address in use, retrying...');
        setTimeout(function () {
            server.close();
            server.listen(PORT, HOST);
        }, 1000);
    }
});

server.listen(6379, function() { //'listening' listener
    var address = server.address();
    console.log("opened server on %j", address);
});<|endoftext|>


<commit_before>'use strict';

const postcss = require('postcss');

module.exports = postcss.plugin('postcss-hexrgba', () => {

  /**
   * Hex to RGB converter
   * @param  {string} hex hexidecimal string without #
   * @return {array} RGB values
   */
  function hexRgb(hex){
    let shorthandCheck = /^([a-f\d])([a-f\d])([a-f\d])$/i,
        rgbRegex = /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i,
        rgb;

    hex = hex.replace(shorthandCheck, function(m, r, g, b) {
      return r + r + g + g + b + b;
    });

    rgb = hex.replace(/^\s+|\s+$/g, '').match(rgbRegex);

    // Convert it
    return rgb ? [
      parseInt(rgb[1], 16),
      parseInt(rgb[2], 16),
      parseInt(rgb[3], 16)
    ] : false;
  }

  /**
   * CSS rule handler
   * @param  {string} decl CSS delcaration
   */
  function ruleHandler(decl, result) {
    let input = decl.value,
        output = input,
        hexes = [];

    // Get the raw hex values out of the decl value and put them in an array
    input.replace(/rgba\(#(.*?),/g, (a, b) => hexes.push(b));

    // If there are no hexes in the value, exit
    if (!hexes.length) {
      return;
    }

    // Convert each hex to RGB
    hexes.forEach(hex => {
      let rgb = hexRgb(hex),
          matchHex = new RegExp('#' + hex);

      // If conversion fails, warn and exit
      if (!rgb) {
        result.warn('not a valid hex', { node: decl });
        return;
      }

      rgb = rgb.toString();

      // Replace hex values in output string
      output = output.replace(matchHex, rgb);
    });

    decl.replaceWith({ prop: decl.prop, value: output });
  }

  return function(css, result) {
    css.walkDecls(decl => {
      if (typeof decl.value === 'undefined' || decl.value.indexOf('rgba') === -1) {
        return;
      }

      ruleHandler(decl, result);
    });
  };
});
<commit_msg>do not omit !important<commit_after>'use strict';

const postcss = require('postcss');

module.exports = postcss.plugin('postcss-hexrgba', () => {

  /**
   * Hex to RGB converter
   * @param  {string} hex hexidecimal string without #
   * @return {array} RGB values
   */
  function hexRgb(hex){
    let shorthandCheck = /^([a-f\d])([a-f\d])([a-f\d])$/i,
        rgbRegex = /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i,
        rgb;

    hex = hex.replace(shorthandCheck, function(m, r, g, b) {
      return r + r + g + g + b + b;
    });

    rgb = hex.replace(/^\s+|\s+$/g, '').match(rgbRegex);

    // Convert it
    return rgb ? [
      parseInt(rgb[1], 16),
      parseInt(rgb[2], 16),
      parseInt(rgb[3], 16)
    ] : false;
  }

  /**
   * CSS rule handler
   * @param  {string} decl CSS delcaration
   */
  function ruleHandler(decl, result) {
    let input = decl.value,
        output = input,
        hexes = [];

    // Get the raw hex values out of the decl value and put them in an array
    input.replace(/rgba\(#(.*?),/g, (a, b) => hexes.push(b));

    // If there are no hexes in the value, exit
    if (!hexes.length) {
      return;
    }

    // Convert each hex to RGB
    hexes.forEach(hex => {
      let rgb = hexRgb(hex),
          matchHex = new RegExp('#' + hex);

      // If conversion fails, warn and exit
      if (!rgb) {
        result.warn('not a valid hex', { node: decl });
        return;
      }

      rgb = rgb.toString();

      // Replace hex values in output string
      output = output.replace(matchHex, rgb);
    });

    decl.replaceWith({
      prop: decl.prop,
      value: output,
      important: decl.important
    });
  }

  return function(css, result) {
    css.walkDecls(decl => {
      if (typeof decl.value === 'undefined' || decl.value.indexOf('rgba') === -1) {
        return;
      }

      ruleHandler(decl, result);
    });
  };
});
<|endoftext|>


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

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});<commit_msg>Making app listen on localhost<commit_after>var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

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


<commit_before>var irc = require("irc");
var fs = require("fs");
var config = require("./config.js");
var jsonfile = require("jsonfile");
var format = require("util").format;
var inspect = require("util").inspect;
var google = require('google');
var fetch = require("node-fetch");
fetch.Promise = require("bluebird");
google.resultsPerPage = 1;
require('es6-shim');

var users;

//For logging, not really currently useful.
var actions = {
    JOIN: "join",
    PART: "part",
    MSG: "msg",
    ERROR: "error",
    INFO: "info"
};

//see: config.js
var bot = new irc.Client(config.server, config.botName, {
    channels: config.channels
});

//The 'names' event is sent whenever a user connects, disconnects, or renames themselves. Used for Karma mainly, which isn't currently implemented, but a helpful thing to have
bot.addListener("names" + config.channels[0], function(nicks) {
    //Object.keys because node-irc returns nicks as a large object with empty keys...
    users = Object.keys(nicks);

});
//Whenver a user joins, let's check their user name. Once TheLounge supports in-line notices, this should probably be changed to bot.notice()
bot.addListener("join", function(channel, who) {
    log(actions.JOIN, who + " joined " + channel);
    //TheLounge's default username
    if (who.indexOf("lounge-user") > -1) {
        bot.say(who, "Hey, " + who + ", now that you've figured out how to use The Lounge, feel free to change your nickname to something more personal using the /nick <new_nickname> command so we know who you are :)");
    }
});

bot.addListener("message", function(from, to, text) {
    //Let's turn the message into an array, easier to work with its arguments.
    var splitMessage = text.split(" ");
    var message = "";
    log(actions.MSG, "(" + to + ") " + from + ": " + text);

    //It's a command! startsWith() is provided by es6-shim.
    if (splitMessage[0].startsWith(config.commandPrefix)) {
        if (splitMessage[0] === "!gh" || splitMessage[0] === "!github") {
            var arg = splitMessage[1];
            //just !gh
            if (splitMessage.length === 1) {
                message = format("https://github.com/%s/%s", config.githubUser, config.githubRepo);
                //<number> or repo info
            } else if (splitMessage.length === 2 && splitMessage[1] !== "search") {
                //It's a number, so it's an issue or a commit
                if (stringIsPositiveInteger(arg)) {
                    log(actions.INFO, config.githubUser);
                    message = getIssueInformation({
                        user: config.githubUser,
                        repo: config.githubRepo,
                        issue: arg
                    });
                    //It's a commit!
                } else if (arg.length === 7 && splitMessage.length === 2 && arg !== "search") {
                    log(actions.INFO, "Commit recognized");
                    message = getIssueInformation({
                        user: config.githubUser,
                        repo: config.githubRepo,
                        issue: arg
                    });
                } else {
                    //!gh user/repo
                    var userRepo = parseUserRepoString(arg);
                    mesage = format("https://www.github.com/%s/%s", userRepo.user, userRepo.repo);
                }
                //!gh search
            } else if (splitMessage.length === 3 && splitMessage[1] !== "search") {
                //search is either an issue or PR
                if (stringIsPositiveInteger(splitMessage[2])) {
                    message = getIssueInformation(withIssue(parseUserRepoString(splitMessage[1]), splitMessage[2]));
                } else if (splitMessage[2].length === 7) {
                    //Temporary hack to see if it's a commit
                    message = getIssueInformation(withIssue(parseUserRepoString(splitMessage[1]), splitMessage[2]));
                } else {
                    message = format("https://github.com/%s/%s", splitMessage[1], splitMessage[2]);
                }
            } else if (splitMessage.length === 4 && splitMessage[1] !== "search") {
                message = getIssueInformation({
                    user: splitMessage[1],
                    repo: splitMessage[2],
                    issue: splitMessage[3]
                });
            } else if (splitMessage.length > 2 && splitMessage[1] === "search") {
                //remove '!gh search'
                for(var i = 0; i < 2; i++) {
                    splitMessage.shift();
                }
                //The third string is a repo
                if(splitMessage[0].includes("/")) {
                    var userRepo = parseUserRepoString(splitMessage[0]);
                    //remove the user/repo
                    splitMessage.shift();
                    message = searchGithub({
                        repo: userRepo.repo,
                        user: userRepo.user,
                        terms: splitMessage
                    });
                } else {
                    message = searchGithub({
                        repo: config.githubRepo,
                        user: config.githubUser,
                        terms: splitMessage
                    });
                }
            }

            //Google command
        } else if ((splitMessage[0] === "!g" || splitMessage[0] === "!google") && splitMessage.length > 1) {
            //Remove the command from the message array
            var query = splitMessage.slice(1).join(' ');
            log(actions.INFO, query);
            google(query, function(err, next, links) {
                if (err) {
                    log(actions.ERROR, err);
                }
                bot.say(to, links[0].title + ' - ' + links[0].link);
            });
        }
        //Just a message
    } else {
        if (text.indexOf("#") > -1 && from.toLowerCase().indexOf(config.ignore) === -1) {
            var issues = text.match(/#([0-9]*)/g);
            if(issues) {
                issues.forEach(function (issue) {
                    console.log(issue);
                    var issueNumber = issue.substr(1);
                    message = getIssueInformation({
                        user: config.githubUser,
                        repo: config.githubRepo,
                        issue: issueNumber
                    });
                    message.then(function(m) {
                        return bot.say(to, m);
                    });
                });
                return;
            }
        }
    }
    log(actions.INFO, message);
    if (message !== "") {
        //If it's returned as a Promise
        if (message.then) {
            message.then(function(m) {
                return bot.say(to, m);
            });
        } else {
            bot.say(to, message);
        }
    }
});

/** Utils **/
var log = function(action, message) {
    var message = "[" + action.toUpperCase() + "]" + " " + message;
    console.log(message);
    fs.open('log.txt', 'a', 666, function(e, id) {
        fs.write(id, message + "\n", null, 'utf8', function() {
            fs.close(id);
        });
    });
}

var userInChannel = function(user) {
    if (users.indexOf(user.toString().toLowerCase()) > -1) {
        return true;
    } else {
        return false;
    }
}

var arrayObjectIndexOf = function(array, searchTerm, property) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (array[i][property] === searchTerm) {
            return i;
        }
    }
    return -1;
}

/** Github **/
//Credits to tennu-github for parts of the following.
var getIssueInformation = function(options) {
    var user = options.user;
    var repo = options.repo;
    var issueNumber = options.issue;
    console.log(issueNumber);
    if (stringIsPositiveInteger(issueNumber.toString())) {
        var result = format("https://api.github.com/repos/%s/%s/issues/%s", user, repo, issueNumber);
        return fetch(result).then(function(res) {
            log(actions.INFO, result);
            return res.json();
        }).then(function(res) {
            if (res.message === "Not Found") {
                return "";
            }

            var type = res.pull_request === undefined ? "Issue" : "PR";
            var status = res.state;
            var title = res.title;
            var link = res.html_url;

            if (type === "PR" && status === "closed") {
                return fetch(res.pull_request.url).then(function(res) {
                    return res.json();
                }).then(function(res) {
                    if (res.message === "Not Found") {
                        return "";
                    }

                    var type = "PR";
                    var status = res.merged_at === null ? "closed" : "merged";
                    var title = res.title;
                    var link = res.html_url;

                    return format("[%s %s] (%s) %s (%s)", type, issueNumber, status, title, link);
                });
            } else {
                return format("[%s %s] (%s) %s (%s)", type, issueNumber, status, title, link);
            }
        });
} else {
    var result = format("https://api.github.com/repos/%s/%s/commits/%s", user, repo, issueNumber);
    return fetch(result).then(function(res) {
        log(actions.INFO, result);
        return res.json();
    }).then(function(res) {
        if (res.message === "Not Found") {
            return "";
        }

        var type = "Commit";
        var author = res.commit.author.name;
        var message = res.commit.message;
        var link = res.html_url;
        var add = res.stats.additions;
        var del = res.stats.deletions;

        return format("[%s %s] - %s (add: %s, del: %s) - %s", type, author, message, add, del, link);
    });
}
}

var searchGithub = function(options) {
    var repo = options.repo;
    var user = options.user;
    var search = options.terms;
    var result = format("https://api.github.com/search/issues?q=repo:%s/%s+%s", user, repo, search.join("+"));
    return fetch(result).then(function(res) {
        log(actions.INFO, result);
        return res.json();
    }).then(function(res) {
        if(res.items[0].state) {
            var status = res.items[0].state;
        } else {
            return "No issue found";
        }
        var title = res.items[0].title;
        var link = res.items[0].html_url;
        var issueNumber = res.items[0].number;
        return format("[%s %s] (%s) %s (%s)", "Issue", issueNumber, status, title, link);
    });
}

var withIssue = function(obj, issueNumber) {
    obj.issue = issueNumber;
    return obj;
}

var stringIsPositiveInteger = function(string) {
    var number = Number(string);

    if (isNaN(number)) {
        return false;
    }

    if (number === Infinity) {
        return false;
    }

    if (number < 1) {
        return false;
    }

    if (Math.floor(number) !== number) {
        return false;
    }

    return true;
}

var parseUserRepoString = function(userRepoString) {
    if (userRepoString.length === 0) {
        return {
            user: config.githubUser,
            repo: config.githubRepo
        };
    }

    if (userRepoString.indexOf("/") === -1) {
        return {
            user: config.githubUser,
            repo: config.userRepoString
        };
    }

    var split = userRepoString.split("/");
    var user = split[0].length !== 0 ? split[0] : config.githubUser;
    var repo = split[1].length !== 0 ? split[1] : config.githubRepo;

    return {
        user: user,
        repo: repo
    };
}
<commit_msg>!gh search returns proper type, no longer hardcoded to issue<commit_after>var irc = require("irc");
var fs = require("fs");
var config = require("./config.js");
var jsonfile = require("jsonfile");
var format = require("util").format;
var inspect = require("util").inspect;
var google = require('google');
var fetch = require("node-fetch");
fetch.Promise = require("bluebird");
google.resultsPerPage = 1;
require('es6-shim');

var users;

//For logging, not really currently useful.
var actions = {
    JOIN: "join",
    PART: "part",
    MSG: "msg",
    ERROR: "error",
    INFO: "info"
};

//see: config.js
var bot = new irc.Client(config.server, config.botName, {
    channels: config.channels
});

//The 'names' event is sent whenever a user connects, disconnects, or renames themselves. Used for Karma mainly, which isn't currently implemented, but a helpful thing to have
bot.addListener("names" + config.channels[0], function(nicks) {
    //Object.keys because node-irc returns nicks as a large object with empty keys...
    users = Object.keys(nicks);

});
//Whenver a user joins, let's check their user name. Once TheLounge supports in-line notices, this should probably be changed to bot.notice()
bot.addListener("join", function(channel, who) {
    log(actions.JOIN, who + " joined " + channel);
    //TheLounge's default username
    if (who.indexOf("lounge-user") > -1) {
        bot.say(who, "Hey, " + who + ", now that you've figured out how to use The Lounge, feel free to change your nickname to something more personal using the /nick <new_nickname> command so we know who you are :)");
    }
});

bot.addListener("message", function(from, to, text) {
    //Let's turn the message into an array, easier to work with its arguments.
    var splitMessage = text.split(" ");
    var message = "";
    log(actions.MSG, "(" + to + ") " + from + ": " + text);

    //It's a command! startsWith() is provided by es6-shim.
    if (splitMessage[0].startsWith(config.commandPrefix)) {
        if (splitMessage[0] === "!gh" || splitMessage[0] === "!github") {
            var arg = splitMessage[1];
            //just !gh
            if (splitMessage.length === 1) {
                message = format("https://github.com/%s/%s", config.githubUser, config.githubRepo);
                //<number> or repo info
            } else if (splitMessage.length === 2 && splitMessage[1] !== "search") {
                //It's a number, so it's an issue or a commit
                if (stringIsPositiveInteger(arg)) {
                    log(actions.INFO, config.githubUser);
                    message = getIssueInformation({
                        user: config.githubUser,
                        repo: config.githubRepo,
                        issue: arg
                    });
                    //It's a commit!
                } else if (arg.length === 7 && splitMessage.length === 2 && arg !== "search") {
                    log(actions.INFO, "Commit recognized");
                    message = getIssueInformation({
                        user: config.githubUser,
                        repo: config.githubRepo,
                        issue: arg
                    });
                } else {
                    //!gh user/repo
                    var userRepo = parseUserRepoString(arg);
                    mesage = format("https://www.github.com/%s/%s", userRepo.user, userRepo.repo);
                }
                //!gh search
            } else if (splitMessage.length === 3 && splitMessage[1] !== "search") {
                //search is either an issue or PR
                if (stringIsPositiveInteger(splitMessage[2])) {
                    message = getIssueInformation(withIssue(parseUserRepoString(splitMessage[1]), splitMessage[2]));
                } else if (splitMessage[2].length === 7) {
                    //Temporary hack to see if it's a commit
                    message = getIssueInformation(withIssue(parseUserRepoString(splitMessage[1]), splitMessage[2]));
                } else {
                    message = format("https://github.com/%s/%s", splitMessage[1], splitMessage[2]);
                }
            } else if (splitMessage.length === 4 && splitMessage[1] !== "search") {
                message = getIssueInformation({
                    user: splitMessage[1],
                    repo: splitMessage[2],
                    issue: splitMessage[3]
                });
            } else if (splitMessage.length > 2 && splitMessage[1] === "search") {
                //remove '!gh search'
                for(var i = 0; i < 2; i++) {
                    splitMessage.shift();
                }
                //The third string is a repo
                if(splitMessage[0].includes("/")) {
                    var userRepo = parseUserRepoString(splitMessage[0]);
                    //remove the user/repo
                    splitMessage.shift();
                    message = searchGithub({
                        repo: userRepo.repo,
                        user: userRepo.user,
                        terms: splitMessage
                    });
                } else {
                    message = searchGithub({
                        repo: config.githubRepo,
                        user: config.githubUser,
                        terms: splitMessage
                    });
                }
            }

            //Google command
        } else if ((splitMessage[0] === "!g" || splitMessage[0] === "!google") && splitMessage.length > 1) {
            //Remove the command from the message array
            var query = splitMessage.slice(1).join(' ');
            log(actions.INFO, query);
            google(query, function(err, next, links) {
                if (err) {
                    log(actions.ERROR, err);
                }
                bot.say(to, links[0].title + ' - ' + links[0].link);
            });
        }
        //Just a message
    } else {
        if (text.indexOf("#") > -1 && from.toLowerCase().indexOf(config.ignore) === -1) {
            var issues = text.match(/#([0-9]*)/g);
            if(issues) {
                issues.forEach(function (issue) {
                    console.log(issue);
                    var issueNumber = issue.substr(1);
                    message = getIssueInformation({
                        user: config.githubUser,
                        repo: config.githubRepo,
                        issue: issueNumber
                    });
                    message.then(function(m) {
                        return bot.say(to, m);
                    });
                });
                return;
            }
        }
    }
    log(actions.INFO, message);
    if (message !== "") {
        //If it's returned as a Promise
        if (message.then) {
            message.then(function(m) {
                return bot.say(to, m);
            });
        } else {
            bot.say(to, message);
        }
    }
});

/** Utils **/
var log = function(action, message) {
    var message = "[" + action.toUpperCase() + "]" + " " + message;
    console.log(message);
    fs.open('log.txt', 'a', 666, function(e, id) {
        fs.write(id, message + "\n", null, 'utf8', function() {
            fs.close(id);
        });
    });
}

var userInChannel = function(user) {
    if (users.indexOf(user.toString().toLowerCase()) > -1) {
        return true;
    } else {
        return false;
    }
}

var arrayObjectIndexOf = function(array, searchTerm, property) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (array[i][property] === searchTerm) {
            return i;
        }
    }
    return -1;
}

/** Github **/
//Credits to tennu-github for parts of the following.
var getIssueInformation = function(options) {
    var user = options.user;
    var repo = options.repo;
    var issueNumber = options.issue;
    console.log(issueNumber);
    if (stringIsPositiveInteger(issueNumber.toString())) {
        var result = format("https://api.github.com/repos/%s/%s/issues/%s", user, repo, issueNumber);
        return fetch(result).then(function(res) {
            log(actions.INFO, result);
            return res.json();
        }).then(function(res) {
            if (res.message === "Not Found") {
                return "";
            }

            var type = res.pull_request === undefined ? "Issue" : "PR";
            var status = res.state;
            var title = res.title;
            var link = res.html_url;

            if (type === "PR" && status === "closed") {
                return fetch(res.pull_request.url).then(function(res) {
                    return res.json();
                }).then(function(res) {
                    if (res.message === "Not Found") {
                        return "";
                    }

                    var type = "PR";
                    var status = res.merged_at === null ? "closed" : "merged";
                    var title = res.title;
                    var link = res.html_url;

                    return format("[%s %s] (%s) %s (%s)", type, issueNumber, status, title, link);
                });
            } else {
                return format("[%s %s] (%s) %s (%s)", type, issueNumber, status, title, link);
            }
        });
} else {
    var result = format("https://api.github.com/repos/%s/%s/commits/%s", user, repo, issueNumber);
    return fetch(result).then(function(res) {
        log(actions.INFO, result);
        return res.json();
    }).then(function(res) {
        if (res.message === "Not Found") {
            return "";
        }

        var type = "Commit";
        var author = res.commit.author.name;
        var message = res.commit.message;
        var link = res.html_url;
        var add = res.stats.additions;
        var del = res.stats.deletions;

        return format("[%s %s] - %s (add: %s, del: %s) - %s", type, author, message, add, del, link);
    });
}
}

var searchGithub = function(options) {
    var repo = options.repo;
    var user = options.user;
    var search = options.terms;
    var result = format("https://api.github.com/search/issues?q=repo:%s/%s+%s", user, repo, search.join("+"));
    return fetch(result).then(function(res) {
        log(actions.INFO, result);
        return res.json();
    }).then(function(res) {
        if(res.items[0].state) {
            var status = res.items[0].state;
        } else {
            return "No issue found";
        }
        var title = res.items[0].title;
        var link = res.items[0].html_url;
        var issueNumber = res.items[0].number;
        var type = "";
        if(link.indexOf("issues") > -1) {
            type = "Issue";
        } else {
            type = "PR";
        }
        return format("[%s %s] (%s) %s (%s)", type, issueNumber, status, title, link);
    });
}

var withIssue = function(obj, issueNumber) {
    obj.issue = issueNumber;
    return obj;
}

var stringIsPositiveInteger = function(string) {
    var number = Number(string);

    if (isNaN(number)) {
        return false;
    }

    if (number === Infinity) {
        return false;
    }

    if (number < 1) {
        return false;
    }

    if (Math.floor(number) !== number) {
        return false;
    }

    return true;
}

var parseUserRepoString = function(userRepoString) {
    if (userRepoString.length === 0) {
        return {
            user: config.githubUser,
            repo: config.githubRepo
        };
    }

    if (userRepoString.indexOf("/") === -1) {
        return {
            user: config.githubUser,
            repo: config.userRepoString
        };
    }

    var split = userRepoString.split("/");
    var user = split[0].length !== 0 ? split[0] : config.githubUser;
    var repo = split[1].length !== 0 ? split[1] : config.githubRepo;

    return {
        user: user,
        repo: repo
    };
}
<|endoftext|>


<commit_before>var isProperty = require('is-property')

var gen = function(obj, prop) {
  return isProperty(prop) ? obj+'.'+prop : obj+'['+JSON.stringify(prop)+']'
}

gen.valid = isProperty
gen.property = function (prop) {
 return isProperty(prop) ? prop : JSON.stringify(prop)
}

module.exports = gen
<commit_msg>Fix indentation<commit_after>var isProperty = require('is-property')

var gen = function(obj, prop) {
  return isProperty(prop) ? obj+'.'+prop : obj+'['+JSON.stringify(prop)+']'
}

gen.valid = isProperty
gen.property = function (prop) {
  return isProperty(prop) ? prop : JSON.stringify(prop)
}

module.exports = gen
<|endoftext|>


<commit_before>var request = require('request'),
  fs = require('fs'),
  SimpleTokenClient = require('simple-token-client');

function StorageApi (config) {
  this.config = config;
  this.tokenClient = new SimpleTokenClient(config);
}

function jsonResponseHandler (done) {
  return function (err, res, body) {
    if(err) {
      return done(err);
    }

    try {
      body = JSON.parse(body) || body;
    }
    catch (ex) {
      return done(new Error('response is not json'));
    }
    if(res.statusCode !== 200) {
      err = new Error(body.errmsg);
      err.code = body.errcode;
      return done(err);
    }
    done(null, body);
  };
}

function requestForm (method, url, options, formData, done) {
  var opts = {
    url: url,
    proxy: false
  };
  opts = _.merge(opts, options);
  method = method.toLowerCase();

  var req = request[method](opts, jsonResponseHandler(done));
  var form = req.form();
  _.each(formData, function (val, key) {
    form.append(key, val);
  });
}

function request (url, method, options, done) {
  var opts = {
      url: url,
      method: method,
      proxy: false,
      followRedirect: false
    };
  opts = _.merge(opts, options);

  request(opts, jsonResponseHandler(done));
}

function postFile (url, options, formData, files, done) {
  _.each(files, function (val, key) {
    formData[key] = fs.createReadStream(val);
  });
  requestForm('post', url, options, formData, done);
}

StorageApi.prototype.createFile = function (bucket, path, file, done) {
  var self = this;
  self.tokenClient.getToken(function (err, token) {
    if(err) {
      return done(new Error('failed to get access token:' + err.message));
    }
    postFile(self.config.endpoint + '/api/v1/file',
      {
        headers : {
          Authorization: 'Bearer ' + token
        }
      },
      {
        bucket: bucket,
        path: path
      },
      {
        file: file.path
      },
      done);
  });
};

module.exports = StorageApi;
<commit_msg>add get file api<commit_after>var request = require('request'),
  fs = require('fs'),
  SimpleTokenClient = require('simple-token-client');

function StorageApi (config) {
  this.config = config;
  this.tokenClient = new SimpleTokenClient(config);
}

function jsonResponseHandler (done) {
  return function (err, res, body) {
    if(err) {
      return done(err);
    }

    try {
      body = JSON.parse(body) || body;
    }
    catch (ex) {
      return done(new Error('response is not json'));
    }
    if(res.statusCode !== 200) {
      err = new Error(body.errmsg);
      err.code = body.errcode;
      return done(err);
    }
    done(null, body);
  };
}

function requestForm (method, url, options, formData, done) {
  var opts = {
    url: url,
    proxy: false
  };
  opts = _.merge(opts, options);
  method = method.toLowerCase();

  var req = request[method](opts, jsonResponseHandler(done));
  var form = req.form();
  _.each(formData, function (val, key) {
    form.append(key, val);
  });
}

function postFile (url, options, formData, files, done) {
  _.each(files, function (val, key) {
    formData[key] = fs.createReadStream(val);
  });
  requestForm('post', url, options, formData, done);
}

StorageApi.prototype.createFile = function (bucket, path, file, done) {
  var self = this;
  self.tokenClient.getToken(function (err, token) {
    if(err) {
      return done(new Error('failed to get access token:' + err.message));
    }
    postFile(self.config.endpoint + '/api/v1/file',
      {
        headers : {
          Authorization: 'Bearer ' + token
        }
      },
      {
        bucket: bucket,
        path: path
      },
      {
        file: file.path
      },
      done);
  });
};

StorageApi.prototype.getFile = function (url, done) {
  var self = this;
  self.tokenClient.getToken(function (err, token) {
    if(err) {
      return done(new Error('failed to get access token:' + err.message));
    }
    done(null, request({
      url: url,
      headers: {
        Authorization: 'Bearer ' + token
      }
    }));
  });
};

module.exports = StorageApi;
<|endoftext|>


<commit_before>var through2 = require("through2");
var css = require("css");
var _ = require("underscore");
var fs = require("fs");
var path = require("path");
var source = require("vinyl-source-stream");
var dest = require("vinyl-fs").dest;
var mkdirp = require("mkdirp");

var INITIALIZED = false;
var outputCssFile = path.resolve("./out/css/main.css");

function deepCopy(obj) {
	return JSON.parse(JSON.stringify(obj));
}

function adler32(a) {for(var b=65521,c=1,d=0,e=0,f;f=a.charCodeAt(e++);d=(d+c)%b)c=(c+f)%b;return c|d<<16}

function camelCase(str) {
	return str.replace(/-([a-z])/g, function(match) {
		return match[1].toUpperCase();
	});
}

/**
 * b - Browserify instance
 */
var Sportsokken = function(b, opts) {
	_(this).bindAll(
		"transform"
	);
	var self = this;

	this.cssStream = null;

	this.b = b;

	this.cache = {};

	b.transform(this.transform);

	b.on("bundle", function(pipeline) {
		self.cssStream = through2();

		pipeline.push(through2.obj(
			{objectMode: true},
			null,
			function(end) {
				// TODO Clean up cache
				self.cssStream
					.pipe(source("main.css"))
					.pipe(dest("./out/css"));
				end();
			}
		));

		console.log("onbuncdle");
	});

	b.on("dep", function(dep) {

		// TODO Add to css stream
		if(/\.css$/.test(dep.file)) {
			console.log(dep.file);
			if(self.cache[dep.file]) {
				self.cssStream.write(self.cache[dep.file]);
			}
		}
	});

	b.on("update", function(changingDeps) {

	});

};

_.extend(Sportsokken.prototype, {

	transform: function(file, opts) {
		if(!/\.css$/.test(file)) {
			return through2();
		}

		var self = this;
		var buffer = "";

		return through2(
			function(data, enc, next) {
				buffer += data.toString();
				next();
			},
			function(end) {
				var tree = css.parse(buffer);
				var newTree = {};
				var map = {};
				var prefix = "r" + adler32(buffer).toString(36);
				var counter = 0;
				var stream = this;

				_(tree).each(function(value, key, list) {
					if(key == "stylesheet") {
						newTree[key] = _(value).reduce(function(memo, value, key, list) {
							memo = Object.create(memo);

							if(key == "rules") {
								memo[key] = _(value).map(function(rule) {
									return _(rule).reduce(function(memo, value, key, list) {
										memo = Object.create(memo);

										if(key == "selectors") {
											memo[key] = _(value).map(function(selector) {
												// Search selector for class names and replace them
												// TODO Make sure this sures catches all situations (maybe use tokenizer?)
												return selector.replace(/\.([_a-z][_a-z0-9-]*)/gi, function(match, cssClassName) {
													cssClassName = camelCase(cssClassName);
													if(!map[cssClassName]) {
														map[cssClassName] = prefix + counter.toString(36);
														counter++;
													}
													return "." + map[cssClassName];
												});
											});
										}
										else {
											memo[key] = deepCopy(value);
										}

										return memo;
									}, {});
								});

								return memo;
							}
							else {
								memo[key] = deepCopy(value);
							}
						}, {});
					}
					else {
						newTree[key] = deepCopy(value);
					}
				});

				self.cache[file] = css.stringify(newTree);

				this.push("module.exports = " + JSON.stringify(map));
				console.log("Finished parsing css file: " + file);
				end();
			}
		);
	}

});

module.exports = Sportsokken;<commit_msg>More clean up<commit_after>var through2 = require("through2");
var css = require("css");
var _ = require("underscore");
var fs = require("fs");
var path = require("path");
var source = require("vinyl-source-stream");
var dest = require("vinyl-fs").dest;
var mkdirp = require("mkdirp");

var INITIALIZED = false;
var outputCssFile = path.resolve("./out/css/main.css");

function deepCopy(obj) {
	return JSON.parse(JSON.stringify(obj));
}

function adler32(a) {for(var b=65521,c=1,d=0,e=0,f;f=a.charCodeAt(e++);d=(d+c)%b)c=(c+f)%b;return c|d<<16}

function camelCase(str) {
	return str.replace(/-([a-z])/g, function(match) {
		return match[1].toUpperCase();
	});
}

/**
 * b - Browserify instance
 */
var Sportsokken = function(b, opts) {
	_(this).bindAll(
		"transform"
	);
	var self = this;

	this.cssStream = null;

	this.b = b;

	this.cache = {};

	b.transform(this.transform);

	b.on("bundle", function(pipeline) {
		self.cssStream = through2();

		pipeline.push(through2.obj(
			{objectMode: true},
			null,
			function(end) {
				// TODO Clean up cache
				self.cssStream
					.pipe(source("main.css"))
					.pipe(dest("./out/css"));
				end();
			}
		));
	});

	b.on("dep", function(dep) {

		// TODO Add to css stream
		if(/\.css$/.test(dep.file)) {
			console.log(dep.file);
			if(self.cache[dep.file]) {
				self.cssStream.write(self.cache[dep.file]);
			}
		}
	});

	b.on("update", function(changingDeps) {

	});

};

_.extend(Sportsokken.prototype, {

	transform: function(file, opts) {
		if(!/\.css$/.test(file)) {
			return through2();
		}

		var self = this;
		var buffer = "";

		return through2(
			function(data, enc, next) {
				buffer += data.toString();
				next();
			},
			function(end) {
				var tree = css.parse(buffer);
				var newTree = {};
				var map = {};
				var prefix = "r" + adler32(buffer).toString(36);
				var counter = 0;
				var stream = this;

				_(tree).each(function(value, key, list) {
					if(key == "stylesheet") {
						newTree[key] = _(value).reduce(function(memo, value, key, list) {
							memo = Object.create(memo);

							if(key == "rules") {
								memo[key] = _(value).map(function(rule) {
									return _(rule).reduce(function(memo, value, key, list) {
										memo = Object.create(memo);

										if(key == "selectors") {
											memo[key] = _(value).map(function(selector) {
												// Search selector for class names and replace them
												// TODO Make sure this sures catches all situations (maybe use tokenizer?)
												return selector.replace(/\.([_a-z][_a-z0-9-]*)/gi, function(match, cssClassName) {
													cssClassName = camelCase(cssClassName);
													if(!map[cssClassName]) {
														map[cssClassName] = prefix + counter.toString(36);
														counter++;
													}
													return "." + map[cssClassName];
												});
											});
										}
										else {
											memo[key] = deepCopy(value);
										}

										return memo;
									}, {});
								});

								return memo;
							}
							else {
								memo[key] = deepCopy(value);
							}
						}, {});
					}
					else {
						newTree[key] = deepCopy(value);
					}
				});

				self.cache[file] = css.stringify(newTree);

				this.push("module.exports = " + JSON.stringify(map));
				console.log("Finished parsing css file: " + file);
				end();
			}
		);
	}

});

module.exports = Sportsokken;<|endoftext|>


<commit_before>'use strict';

var enforce = require('express-sslify');
var helmet = require('helmet');
var csp = require('helmet-csp');
var uuid = require('node-uuid');
var parseDomain = require("parse-domain");

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

	return function reallySecure(req, res, next) {

		var makeSecure = function() {
			res.locals.nonce = uuid.v4();
			var nonceArray = [res.locals.nonce];
			// Sets "X-DNS-Prefetch-Control: on".
			helmet.dnsPrefetchControl({
				allow: true
			})(req, res, function() {
				// Don't allow me to be in ANY frames.
				// Sets "X-Frame-Options: DENY".
				helmet.frameguard({
					action: 'deny'
				})(req, res, function() {
					// Set X-Powered-By to Aicial Engine
					helmet.hidePoweredBy({
						setTo: options.poweredBy || 'The Internet'
					})(req, res, function() {
						// Sets "X-Download-Options: noopen".
						helmet.ieNoOpen()(req, res, function() {
							// Sets "X-Content-Type-Options: nosniff".
							helmet.noSniff()(req, res, function() {
								// Sets "Referrer-Policy: same-origin".
								helmet.referrerPolicy({
									policy: 'origin-when-cross-origin'
								})(req, res, function() {
									// Sets "X-XSS-Protection: 1; mode=block".
									helmet.xssFilter()(req, res, function() {
										if (options.csp === undefined) options.csp = {};

										var defaultSrc = options.csp.defaultSrc || ["'self'"];
										var scriptSrc = options.csp.scriptSrc || ["'self'"];
										var styleSrc = options.csp.styleSrc || ["'self'"];
										var fontSrc = options.csp.fontSrc || ["'self'"];
										var imgSrc = options.csp.imgSrc || ["'self'"];

										var upgradeInsecureRequests = options.csp.upgradeInsecureRequests || true;

										var hostnameParts = parseDomain(req.hostname);
										if (hostnameParts) {
											var hostname = hostnameParts.domain + '.' + hostnameParts.tld;
										} else {
											var hostname = req.hostname;
										}

										var noSubs = ['localhost', 'appspot.com'];

										if (!noSubs.includes(hostname)) {
											if (defaultSrc.indexOf("api." + hostname) === -1) defaultSrc.push("api." + hostname);
											if (scriptSrc.indexOf("script." + hostname) === -1) scriptSrc.push("script." + hostname);
											if (styleSrc.indexOf("sytle." + hostname) === -1) styleSrc.push("sytle." + hostname);
											if (fontSrc.indexOf("font." + hostname) === -1) fontSrc.push("font." + hostname);
											if (imgSrc.indexOf("img." + hostname) === -1) imgSrc.push("img." + hostname);
										}

										if (hostname === 'localhost') {
											upgradeInsecureRequests = false;
										}

										var cspConfig = {
											// Specify directives as normal.
											directives: {
												defaultSrc: defaultSrc.concat(nonceArray),
												scriptSrc: scriptSrc.concat(nonceArray),
												styleSrc: styleSrc.concat(nonceArray),
												fontSrc: fontSrc.concat(nonceArray),
												imgSrc: imgSrc.concat(nonceArray),
												objectSrc: options.csp.objectSrc || ["'none'"]
											},

											sandbox: options.csp.sandbox || ['allow-forms', 'allow-scripts'],
											reportUri: options.csp.reportUri || '/report-violation',

											// This module will detect common mistakes in your directives and throw errors
											// if it finds any. To disable this, enable "loose mode".
											loose: false,

											// Set to true if you only want browsers to report errors, not block them.
											// You may also set this to a function(req, res) in order to decide dynamically
											// whether to use reportOnly mode, e.g., to allow for a dynamic kill switch.
											reportOnly: false,

											// Set to true if you want to blindly set all headers: Content-Security-Policy,
											// X-WebKit-CSP, and X-Content-Security-Policy.
											setAllHeaders: false,

											// Set to true if you want to disable CSP on Android where it can be buggy.
											disableAndroid: false,

											// Set to false if you want to completely disable any user-agent sniffing.
											// This may make the headers less compatible but it will be much faster.
											// This defaults to `true`.
											browserSniff: true
										};

										if (upgradeInsecureRequests) {
											cspConfig.directives.upgradeInsecureRequests = true
										}

										csp(cspConfig)(req, res, next);
									});
								});
							});
						});
					});
				});
			});
		}

		//When in production make sure we force SSL and send HSTS headers
		if (process.env.NODE_ENV === 'production') {
			var enforceHTTPS = function() {
				enforce.HTTPS({
					trustProtoHeader: true
				})(req, res, makeSecure);
			}
			if (options.hsts !== undefined) {
				// Add HSTS Strict-Transport-Security headers
				helmet.hsts({
					maxAge: options.hsts.maxAge || 10886400, // Must be at least 18 weeks to be approved by Google
					includeSubDomains: options.hsts.includeSubDomains || true, // Must be enabled to be approved by Google
					preload: options.hsts.preload || true,
					force: options.hsts.force || true
				})(req, res, function() {
					enforceHTTPS();
				});
			} else {
				enforceHTTPS();
			}
		} else {
			makeSecure();
		}

	}

}
<commit_msg>Added correct formatting<commit_after>'use strict';

var enforce = require('express-sslify');
var helmet = require('helmet');
var csp = require('helmet-csp');
var uuid = require('node-uuid');
var parseDomain = require("parse-domain");

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

	return function reallySecure(req, res, next) {

		var makeSecure = function() {
			res.locals.nonce = uuid.v4();
			var nonceArray = ["'nonce-"+res.locals.nonce+"'"];
			// Sets "X-DNS-Prefetch-Control: on".
			helmet.dnsPrefetchControl({
				allow: true
			})(req, res, function() {
				// Don't allow me to be in ANY frames.
				// Sets "X-Frame-Options: DENY".
				helmet.frameguard({
					action: 'deny'
				})(req, res, function() {
					// Set X-Powered-By to Aicial Engine
					helmet.hidePoweredBy({
						setTo: options.poweredBy || 'The Internet'
					})(req, res, function() {
						// Sets "X-Download-Options: noopen".
						helmet.ieNoOpen()(req, res, function() {
							// Sets "X-Content-Type-Options: nosniff".
							helmet.noSniff()(req, res, function() {
								// Sets "Referrer-Policy: same-origin".
								helmet.referrerPolicy({
									policy: 'origin-when-cross-origin'
								})(req, res, function() {
									// Sets "X-XSS-Protection: 1; mode=block".
									helmet.xssFilter()(req, res, function() {
										if (options.csp === undefined) options.csp = {};

										var defaultSrc = options.csp.defaultSrc || ["'self'"];
										var scriptSrc = options.csp.scriptSrc || ["'self'"];
										var styleSrc = options.csp.styleSrc || ["'self'"];
										var fontSrc = options.csp.fontSrc || ["'self'"];
										var imgSrc = options.csp.imgSrc || ["'self'"];

										var upgradeInsecureRequests = options.csp.upgradeInsecureRequests || true;

										var hostnameParts = parseDomain(req.hostname);
										if (hostnameParts) {
											var hostname = hostnameParts.domain + '.' + hostnameParts.tld;
										} else {
											var hostname = req.hostname;
										}

										var noSubs = ['localhost', 'appspot.com'];

										if (!noSubs.includes(hostname)) {
											if (defaultSrc.indexOf("api." + hostname) === -1) defaultSrc.push("api." + hostname);
											if (scriptSrc.indexOf("script." + hostname) === -1) scriptSrc.push("script." + hostname);
											if (styleSrc.indexOf("sytle." + hostname) === -1) styleSrc.push("sytle." + hostname);
											if (fontSrc.indexOf("font." + hostname) === -1) fontSrc.push("font." + hostname);
											if (imgSrc.indexOf("img." + hostname) === -1) imgSrc.push("img." + hostname);
										}

										if (hostname === 'localhost') {
											upgradeInsecureRequests = false;
										}

										var cspConfig = {
											// Specify directives as normal.
											directives: {
												defaultSrc: defaultSrc.concat(nonceArray),
												scriptSrc: scriptSrc.concat(nonceArray),
												styleSrc: styleSrc.concat(nonceArray),
												fontSrc: fontSrc.concat(nonceArray),
												imgSrc: imgSrc.concat(nonceArray),
												objectSrc: options.csp.objectSrc || ["'none'"]
											},

											sandbox: options.csp.sandbox || ['allow-forms', 'allow-scripts'],
											reportUri: options.csp.reportUri || '/report-violation',

											// This module will detect common mistakes in your directives and throw errors
											// if it finds any. To disable this, enable "loose mode".
											loose: false,

											// Set to true if you only want browsers to report errors, not block them.
											// You may also set this to a function(req, res) in order to decide dynamically
											// whether to use reportOnly mode, e.g., to allow for a dynamic kill switch.
											reportOnly: false,

											// Set to true if you want to blindly set all headers: Content-Security-Policy,
											// X-WebKit-CSP, and X-Content-Security-Policy.
											setAllHeaders: false,

											// Set to true if you want to disable CSP on Android where it can be buggy.
											disableAndroid: false,

											// Set to false if you want to completely disable any user-agent sniffing.
											// This may make the headers less compatible but it will be much faster.
											// This defaults to `true`.
											browserSniff: true
										};

										if (upgradeInsecureRequests) {
											cspConfig.directives.upgradeInsecureRequests = true
										}

										csp(cspConfig)(req, res, next);
									});
								});
							});
						});
					});
				});
			});
		}

		//When in production make sure we force SSL and send HSTS headers
		if (process.env.NODE_ENV === 'production') {
			var enforceHTTPS = function() {
				enforce.HTTPS({
					trustProtoHeader: true
				})(req, res, makeSecure);
			}
			if (options.hsts !== undefined) {
				// Add HSTS Strict-Transport-Security headers
				helmet.hsts({
					maxAge: options.hsts.maxAge || 10886400, // Must be at least 18 weeks to be approved by Google
					includeSubDomains: options.hsts.includeSubDomains || true, // Must be enabled to be approved by Google
					preload: options.hsts.preload || true,
					force: options.hsts.force || true
				})(req, res, function() {
					enforceHTTPS();
				});
			} else {
				enforceHTTPS();
			}
		} else {
			makeSecure();
		}

	}

}
<|endoftext|>


<commit_before>'use strict';

const raml2obj = require('raml2obj');
const pjson = require('./package.json');

/**
 * Render the source RAML object using the config's processOutput function
 *
 * The config object should contain at least the following property:
 * processRamlObj: function that takes the raw RAML object and returns a promise with the rendered HTML
 *
 * @param {(String|Object)} source - The source RAML file. Can be a filename, url, contents of the RAML file,
 * or an already-parsed RAML object.
 * @param {Object} config
 * @param {Function} config.processRamlObj
 * @returns a promise
 */
function render(source, config) {
  config = config || {};
  config.raml2HtmlVersion = pjson.version;

  return raml2obj.parse(source).then((ramlObj) => {
    ramlObj.config = config;

    if (config.processRamlObj) {
      return config.processRamlObj(ramlObj).then((html) => {
        if (config.postProcessHtml) {
          return config.postProcessHtml(html);
        }
        return html;
      });
    }

    return ramlObj;
  });
}

/**
 * @param {String} [mainTemplate] - The filename of the main template, leave empty to use default templates
 * @param {String} [templatesPath] - Optional, by default it uses the current working directory
 * @returns {{processRamlObj: Function, postProcessHtml: Function}}
 */
function getDefaultConfig(mainTemplate, templatesPath) {
  if (!mainTemplate) {
    mainTemplate = './lib/template.nunjucks';

    // When using the default template, make sure that Nunjucks isn't
    // using the working directory since that might be anything
    templatesPath = __dirname;
  }

  return {
    processRamlObj(ramlObj) {
      const nunjucks = require('nunjucks');
      const markdown = require('nunjucks-markdown');
      const marked = require('marked');
      const ramljsonexpander = require('raml-jsonschema-expander');
      const renderer = new marked.Renderer();
      renderer.table = function (thead, tbody) {
        // Render Bootstrap style tables
        return `<table class="table"><thead>${thead}</thead><tbody>${tbody}</tbody></table>`;
      };

      // Setup the Nunjucks environment with the markdown parser
      const env = nunjucks.configure(templatesPath, { watch: false });
      markdown.register(env, (md) => marked(md, { renderer }));

      // Add extra function for finding a security scheme by name
      ramlObj.securitySchemeWithName = function (name) {
        return ramlObj.securitySchemes.find((scheme) => scheme[name]);
      };

      // Parse securedBy and use scopes if they are defined
      ramlObj.renderSecuredBy = function (securedBy) {
        let out = '';
        if (typeof securedBy === 'object') {
          Object.keys(securedBy).forEach((key) => {
            out += `<b>${key}</b>`;

            if (securedBy[key].scopes.length) {
              out += ' with scopes:
';

              securedBy[key].scopes.forEach((scope) => {
                out += `<li>${scope}</li>`;
              });

              out += '
';
            }
          });
        } else {
          out = `<b>${securedBy}</b>`;
        }
        return out;
      };

      // Find and replace the $ref parameters.
      ramlObj = ramljsonexpander.expandJsonSchemas(ramlObj);

      // Render the main template using the raml object and fix the double quotes
      let html = env.render(mainTemplate, ramlObj);
      html = html.replace(/"/g, '"');

      // Return the promise with the html
      return new Promise((resolve) => {
        resolve(html);
      });
    },

    postProcessHtml(html) {
      // Minimize the generated html and return the promise with the result
      const Minimize = require('minimize');
      const minimize = new Minimize({ quotes: true });

      return new Promise((resolve, reject) => {
        minimize.parse(html, (error, result) => {
          if (error) {
            reject(new Error(error));
          } else {
            resolve(result);
          }
        });
      });
    },
  };
}

module.exports = {
  getDefaultConfig,
  render,
};

if (require.main === module) {
  console.log('This script is meant to be used as a library. You probably want to run bin/raml2html if you\'re looking for a CLI.');
  process.exit(1);
}
<commit_msg>Fix securitySchemeWithName - needed to return the object value instead of the whole object<commit_after>'use strict';

const raml2obj = require('raml2obj');
const pjson = require('./package.json');

/**
 * Render the source RAML object using the config's processOutput function
 *
 * The config object should contain at least the following property:
 * processRamlObj: function that takes the raw RAML object and returns a promise with the rendered HTML
 *
 * @param {(String|Object)} source - The source RAML file. Can be a filename, url, contents of the RAML file,
 * or an already-parsed RAML object.
 * @param {Object} config
 * @param {Function} config.processRamlObj
 * @returns a promise
 */
function render(source, config) {
  config = config || {};
  config.raml2HtmlVersion = pjson.version;

  return raml2obj.parse(source).then((ramlObj) => {
    ramlObj.config = config;

    if (config.processRamlObj) {
      return config.processRamlObj(ramlObj).then((html) => {
        if (config.postProcessHtml) {
          return config.postProcessHtml(html);
        }
        return html;
      });
    }

    return ramlObj;
  });
}

/**
 * @param {String} [mainTemplate] - The filename of the main template, leave empty to use default templates
 * @param {String} [templatesPath] - Optional, by default it uses the current working directory
 * @returns {{processRamlObj: Function, postProcessHtml: Function}}
 */
function getDefaultConfig(mainTemplate, templatesPath) {
  if (!mainTemplate) {
    mainTemplate = './lib/template.nunjucks';

    // When using the default template, make sure that Nunjucks isn't
    // using the working directory since that might be anything
    templatesPath = __dirname;
  }

  return {
    processRamlObj(ramlObj) {
      const nunjucks = require('nunjucks');
      const markdown = require('nunjucks-markdown');
      const marked = require('marked');
      const ramljsonexpander = require('raml-jsonschema-expander');
      const renderer = new marked.Renderer();
      renderer.table = function (thead, tbody) {
        // Render Bootstrap style tables
        return `<table class="table"><thead>${thead}</thead><tbody>${tbody}</tbody></table>`;
      };

      // Setup the Nunjucks environment with the markdown parser
      const env = nunjucks.configure(templatesPath, { watch: false });
      markdown.register(env, (md) => marked(md, { renderer }));

      // Add extra function for finding a security scheme by name
      ramlObj.securitySchemeWithName = function (name) {
        const result = ramlObj.securitySchemes.find(s => s[name]);
        if (result) {
          return result[name];
        }
        return {};
      };

      // Parse securedBy and use scopes if they are defined
      ramlObj.renderSecuredBy = function (securedBy) {
        let out = '';
        if (typeof securedBy === 'object') {
          Object.keys(securedBy).forEach((key) => {
            out += `<b>${key}</b>`;

            if (securedBy[key].scopes.length) {
              out += ' with scopes:
';

              securedBy[key].scopes.forEach((scope) => {
                out += `<li>${scope}</li>`;
              });

              out += '
';
            }
          });
        } else {
          out = `<b>${securedBy}</b>`;
        }
        return out;
      };

      // Find and replace the $ref parameters.
      ramlObj = ramljsonexpander.expandJsonSchemas(ramlObj);

      // Render the main template using the raml object and fix the double quotes
      let html = env.render(mainTemplate, ramlObj);
      html = html.replace(/"/g, '"');

      // Return the promise with the html
      return new Promise((resolve) => {
        resolve(html);
      });
    },

    postProcessHtml(html) {
      // Minimize the generated html and return the promise with the result
      const Minimize = require('minimize');
      const minimize = new Minimize({ quotes: true });

      return new Promise((resolve, reject) => {
        minimize.parse(html, (error, result) => {
          if (error) {
            reject(new Error(error));
          } else {
            resolve(result);
          }
        });
      });
    },
  };
}

module.exports = {
  getDefaultConfig,
  render,
};

if (require.main === module) {
  console.log('This script is meant to be used as a library. You probably want to run bin/raml2html if you\'re looking for a CLI.');
  process.exit(1);
}
<|endoftext|>


<commit_before>// index constants for properties
var MEDITERRANEAN_AVE = 0;
var BALTIC_AVE = 1;
var ORIENTAL_AVE = 2;
var VERMONT_AVE = 3;
var CONNECTICUT_AVE = 4;
var ST_CHARLES_PLACE = 5;
var STATES_AVE = 6;
var VIRGINIA_AVE = 7;
var ST_JAMES_PLACE = 8;
var TENNESSEE_AVE = 9;
var NEW_YORK_AVE = 10;
var KENTUCKY_AVE = 11;
var INDIANA_AVE = 12;
var ILLINOIS_AVE = 13;
var ATLANTIC_AVE = 14;
var VENTNOR_AVE = 15;
var MARVIN_GARDENS = 16;
var PACIFIC_AVE = 17;
var NORTH_CAROLINA_AVE = 18;
var PENNSYLVANIA_AVE = 19;
var PARK_PLACE = 20;
var BOARDWALK = 21;
var READING_RR = 22;
var PENN_RR = 23;
var BO_RR = 24;
var SHORTLINE_RR = 25;
var ELECTRIC_CO = 26;
var WATERWORKS = 27;

// property groups
var PG_BROWN = 0;
var PG_LIGHT_BLUE = 1;
var PG_PINK = 2;
var PG_ORANGE = 3;
var PG_RED = 4;
var PG_YELLOW = 5;
var PG_GREEN = 6;
var PG_BLUE = 7;
var PG_RR = 8;
var PG_UTIL = 9;

// placeholder for now - should talk when merged to properly integrate this with
// existing "board" and "players" implementations
function Board(players) {
  this.players = players; // just a placeholder for now - on merge should combine
  this.spaces = [];
}

// class definitions for any space on the board -
// properties, utilities, free parking, go, etc.
function Space(name) {
  this.name = name;
  this.occupier = null;
}
// every space needs a landing action
Space.prototype.perform_landing_action = function(){
  console.log("You landed on " + this.name);
};

function Property(name, cost, property_group) {
  Space.call(this, name);
  this.cost = cost;
  this.mortage = .5*cost;
  this.property_group = property_group; // "red", "blue", "railroad", etc.
  this.owner = null;
}
Property.prototype = Object.create(Space.prototype); // subclassing space

// rent should be array with following format:
// [1 owned, 2 owned ... (3 owned, 4 owned)]
function UtilityProperty(name, cost, property_group, rent) {
  this.rent = rent;
  Property.call(this, this.name, this.cost, this.property_group);
}
UtilityProperty.prototype = Object.create(Property.prototype);
UtilityProperty.prototype.perform_landing_action = function(player) {
};

// rent should be array with following format:
// [rent, 1 house, 2 houses, 3 houses, 4 houses, hotel]
function HousingProperty(name, cost, property_group, rent) {
  this.rent = rent;
  Property.call(this, this.name, this.cost, this.property_group);
}
HousingProperty.prototype = Object.create(Property.prototype);
HousingProperty.prototype.perform_landing_action = function(player) {
};

function Chance() {}
Chance.prototype = Object.create(Space.prototype);
Chance.prototype.perform_landing_action = function(player) {
};

function CommunityChest() {}
CommunityChest.prototype = Object.create(Space.prototype);
Chance.prototype.perform_landing_action = function(player) {
};

function FreeParking() {}
FreeParking.prototype = Object.create(Space.prototype);
FreeParking.prototype.perform_landing_action = function(player) {
};

function Jail() {}
GoToJail.prototype = Object.create(Space.prototype);
GoToJail.prototype.perform_landing_action = function(player) {
};

function GoToJail() {}
GoToJail.prototype = Object.create(Space.prototype);
GoToJail.prototype.perform_landing_action = function(player) {
};

function Tax() {
  this.tax_amount = 0; // give default value of 0, should be overridden
}
Tax.prototype = Object.create(Space.prototype);
Tax.prototype.perform_landing_action = function(player) {
  this.player.money -= this.tax_amount;
};

function IncomeTax() {
  this.tax_amount = 200; // flat tax - will give user option later
}
IncomeTax.prototype = Object.create(Tax.prototype);
IncomeTax.prototype.perform_landing_action = function(player) {
  // todo: prompt user for choice here
  // if (userWantsFlatTax) this.tax_amount = 200;
  // else this.tax_amount = playerAssetValue(player)*.10;
};

function LuxuryTax() {
  this.tax_amount = 75;
}
LuxuryTax.prototype = Object.create(Tax.prototype);

function Go() {}
Go.prototype = Object.create(Space.prototype);

// end of space class definitions

// now let's build the board
var board;
function build_board() {
  board = new Board();
  build_spaces(board);
}

function build_spaces(board) {
  var props = properties_list();
  board.spaces = [

    // first row
    new Go(),
    property_for_index(MEDITERRANEAN_AVE, props),
    new CommunityChest(),
    property_for_index(BALTIC_AVE, props),
    new IncomeTax(),
    property_for_index(READING_RR, props),
    property_for_index(ORIENTAL_AVE, props),
    new Chance(),
    property_for_index(VERMONT_AVE, props),
    property_for_index(CONNECTICUT_AVE, props),
    new Jail(),

    // second row
    property_for_index(ST_CHARLES_PLACE, props),
    property_for_index(ELECTRIC_CO, props),
    property_for_index(STATES_AVE, props),
    property_for_index(VIRGINIA_AVE, props),
    property_for_index(PENN_RR, props),
    property_for_index(ST_JAMES_PLACE, props),
    new CommunityChest(),
    property_for_index(TENNESSEE_AVE, props),
    property_for_index(NEW_YORK_AVE, props),
    new FreeParking(),

    // third
    property_for_index(KENTUCKY_AVE, props),
    new Chance(),
    property_for_index(INDIANA_AVE, props),
    property_for_index(ILLINOIS_AVE, props),
    property_for_index(BO_RR, props),
    property_for_index(ATLANTIC_AVE, props),
    property_for_index(VENTNOR_AVE, props),
    property_for_index(WATERWORKS, props),
    property_for_index(MARVIN_GARDENS, props),
    new GoToJail(),

    // fourth
    property_for_index(PACIFIC_AVE, props),
    property_for_index(NORTH_CAROLINA_AVE, props),
    new CommunityChest(),
    property_for_index(PENNSYLVANIA_AVE, props),
    property_for_index(SHORTLINE_RR, props),
    new Chance(),
    property_for_index(PARK_PLACE, props),
    new LuxuryTax(),
    property_for_index(BOARDWALK, props),

  ];
}

// indices correlate to order in below function properties_list()
function property_for_index(index, props) {
  if (index <= 21) {
    return new HousingProperty(props[index][0], props[index][2], props[index][1], props[index][4]);
  } else if (index <= 25) {
    return new UtilityProperty(props[index][0], props[index][2], props[index][3]);
  } else {
    return new UtilityProperty(props[index][0], props[index][2], NULL);
  }
}

/* housing properties: [name, color, cost, house cost, [rent, 1, 2, 3, 4, hotel]]
 railroads: [name, "Railroad", cost, [1, 2, 3, 4]]
 utilities: [name, "Utility", cost]
*/
function properties_list() {
  return [
    ["Mediterranean Ave", PG_BROWN, 60, 50, [2, 10, 30, 90, 160, 250]],
    ["Baltic Ave", PG_BROWN, 60, 50, [4, 20, 60, 180, 320, 450]],

    ["Oriental Ave", PG_LIGHT_BLUE, 100, 50, [6, 30, 90, 270, 400, 550]],
    ["Vermont Ave", PG_LIGHT_BLUE, 100, 50, [6, 30, 90, 270, 400, 550]],
    ["Connecticut Ave", PG_LIGHT_BLUE, 120, 50, [8, 40, 100, 300, 450, 600]],

    ["St. Charles Place", PG_PINK, 140, 100, [10, 50, 150, 450, 625, 750]], // 5
    ["States Ave", PG_PINK, 140, 100, [10, 50, 150, 450, 625, 750]],
    ["Virginia Ave", PG_PINK, 160, 100 [12, 60, 180, 500, 700, 900]],

    ["St. James Place", PG_ORANGE, 180, 100, [14, 70, 200, 550, 750, 950]],
    ["Tennessee Ave", PG_ORANGE, 180, 100, [14, 70, 200, 550, 750, 950]],
    ["New York Ave", PG_ORANGE, 200, 100, [16, 80, 220, 600, 800, 1000]], // 10

    ["Kentucky Ave", PG_RED, 220, 150, [18, 90, 250, 700, 875, 1050]],
    ["Indiana Ave", PG_RED, 220, 150, [18, 90, 250, 700, 875, 1050]],
    ["Illinois Ave", PG_RED, 240, 150, [20, 100, 300, 750, 925, 1100]],

    ["Atlantic Ave", PG_YELLOW, 260, 150, [22, 110, 330, 800, 975, 1150]],
    ["Ventnor Ave", PG_YELLOW, 260, 150, [22, 110, 330, 800, 975, 1150]], // 15
    ["Marvin Gardens", PG_YELLOW, 280, 150, [24, 120, 360, 850, 1025, 1200]],

    ["Pacific Ave", PG_GREEN, 300, 200, [26, 130, 390, 900, 1100, 1275]],
    ["North Carolina Ave", PG_GREEN, 300, 200, [26, 130, 390, 900, 1100, 1275]],
    ["Pennsylvaniva Ave", PG_GREEN, 320, 200, [28, 150, 450, 1000, 1200, 1400]],

    ["Park Place", PG_BLUE, 350, 200, [35, 175, 500, 1100, 1300, 1500]], // 20
    ["Boardwalk", PG_BLUE, 400, 200, [50, 200, 600, 1400, 1700, 2000]],

    ["Reading Railroad", PG_RR, 200, [25, 50, 100, 200]],
    ["Pennsylvania Railroad", PG_RR, 200, [25, 50, 100, 200]],
    ["B. & O. Railroad", PG_RR, 200, [25, 50, 100, 200]],
    ["Shortline Railroad", PG_RR, 200, [25, 50, 100, 200]], // 25

    ["Electric Company", PG_UTIL, 150],
    ["WaterWorks", PG_UTIL, 150]
  ];

}

window.onload = function() {
  build_board();
};
<commit_msg>separating utility/railroad classes<commit_after>// index constants for properties
var MEDITERRANEAN_AVE = 0;
var BALTIC_AVE = 1;
var ORIENTAL_AVE = 2;
var VERMONT_AVE = 3;
var CONNECTICUT_AVE = 4;
var ST_CHARLES_PLACE = 5;
var STATES_AVE = 6;
var VIRGINIA_AVE = 7;
var ST_JAMES_PLACE = 8;
var TENNESSEE_AVE = 9;
var NEW_YORK_AVE = 10;
var KENTUCKY_AVE = 11;
var INDIANA_AVE = 12;
var ILLINOIS_AVE = 13;
var ATLANTIC_AVE = 14;
var VENTNOR_AVE = 15;
var MARVIN_GARDENS = 16;
var PACIFIC_AVE = 17;
var NORTH_CAROLINA_AVE = 18;
var PENNSYLVANIA_AVE = 19;
var PARK_PLACE = 20;
var BOARDWALK = 21;
var READING_RR = 22;
var PENN_RR = 23;
var BO_RR = 24;
var SHORTLINE_RR = 25;
var ELECTRIC_CO = 26;
var WATERWORKS = 27;

// property groups
var PG_BROWN = 0;
var PG_LIGHT_BLUE = 1;
var PG_PINK = 2;
var PG_ORANGE = 3;
var PG_RED = 4;
var PG_YELLOW = 5;
var PG_GREEN = 6;
var PG_BLUE = 7;
var PG_RR = 8;
var PG_UTIL = 9;

// placeholder for now - should talk when merged to properly integrate this with
// existing "board" and "players" implementations
function Board(players) {
  this.players = players; // just a placeholder for now - on merge should combine
  this.spaces = [];
}

// class definitions for any space on the board -
// properties, utilities, free parking, go, etc.
function Space(name) {
  this.name = name;
  this.occupier = null;
}
// every space needs a landing action
Space.prototype.perform_landing_action = function(){
  console.log("You landed on " + this.name);
};

function Property(name, cost, property_group) {
  Space.call(this, name);
  this.cost = cost;
  this.mortage = .5*cost;
  this.property_group = property_group; // "red", "blue", "railroad", etc.
  this.owner = null;
}
Property.prototype = Object.create(Space.prototype); // subclassing space

// rent should be array with following format:
// [1 owned, 2 owned, 3 owned, 4 owned]
function RailroadProperty(name, cost, property_group, rent) {
  this.rent = rent;
  Property.call(this, this.name, this.cost, this.property_group);
}
RailroadProperty.prototype = Object.create(Property.prototype);
RailroadProperty.prototype.perform_landing_action = function(player) {
};

function UtilityProperty(name, cost, property_group) {
  Property.call(this, this.name, this.cost, this.property_group);
}
UtilityProperty.prototype = Object.create(Property.prototype);
UtilityProperty.prototype.perform_landing_action = function(player) {
};

// rent should be array with following format:
// [rent, 1 house, 2 houses, 3 houses, 4 houses, hotel]
function HousingProperty(name, cost, property_group, rent) {
  this.rent = rent;
  Property.call(this, this.name, this.cost, this.property_group);
}
HousingProperty.prototype = Object.create(Property.prototype);
HousingProperty.prototype.perform_landing_action = function(player) {
};

function Chance() {}
Chance.prototype = Object.create(Space.prototype);
Chance.prototype.perform_landing_action = function(player) {
};

function CommunityChest() {}
CommunityChest.prototype = Object.create(Space.prototype);
Chance.prototype.perform_landing_action = function(player) {
};

function FreeParking() {}
FreeParking.prototype = Object.create(Space.prototype);
FreeParking.prototype.perform_landing_action = function(player) {
};

function Jail() {}
GoToJail.prototype = Object.create(Space.prototype);
GoToJail.prototype.perform_landing_action = function(player) {
};

function GoToJail() {}
GoToJail.prototype = Object.create(Space.prototype);
GoToJail.prototype.perform_landing_action = function(player) {
};

function Tax() {
  this.tax_amount = 0; // give default value of 0, should be overridden
}
Tax.prototype = Object.create(Space.prototype);
Tax.prototype.perform_landing_action = function(player) {
  this.player.money -= this.tax_amount;
};

function IncomeTax() {
  this.tax_amount = 200; // flat tax - will give user option later
}
IncomeTax.prototype = Object.create(Tax.prototype);
IncomeTax.prototype.perform_landing_action = function(player) {
  // todo: prompt user for choice here
  // if (userWantsFlatTax) this.tax_amount = 200;
  // else this.tax_amount = playerAssetValue(player)*.10;
};

function LuxuryTax() {
  this.tax_amount = 75;
}
LuxuryTax.prototype = Object.create(Tax.prototype);

function Go() {}
Go.prototype = Object.create(Space.prototype);

// end of space class definitions

// now let's build the board
var board;
function build_board() {
  board = new Board();
  build_spaces(board);
}

function build_spaces(board) {
  var props = properties_list();
  board.spaces = [

    // first row
    new Go(),
    property_for_index(MEDITERRANEAN_AVE, props),
    new CommunityChest(),
    property_for_index(BALTIC_AVE, props),
    new IncomeTax(),
    property_for_index(READING_RR, props),
    property_for_index(ORIENTAL_AVE, props),
    new Chance(),
    property_for_index(VERMONT_AVE, props),
    property_for_index(CONNECTICUT_AVE, props),
    new Jail(),

    // second row
    property_for_index(ST_CHARLES_PLACE, props),
    property_for_index(ELECTRIC_CO, props),
    property_for_index(STATES_AVE, props),
    property_for_index(VIRGINIA_AVE, props),
    property_for_index(PENN_RR, props),
    property_for_index(ST_JAMES_PLACE, props),
    new CommunityChest(),
    property_for_index(TENNESSEE_AVE, props),
    property_for_index(NEW_YORK_AVE, props),
    new FreeParking(),

    // third
    property_for_index(KENTUCKY_AVE, props),
    new Chance(),
    property_for_index(INDIANA_AVE, props),
    property_for_index(ILLINOIS_AVE, props),
    property_for_index(BO_RR, props),
    property_for_index(ATLANTIC_AVE, props),
    property_for_index(VENTNOR_AVE, props),
    property_for_index(WATERWORKS, props),
    property_for_index(MARVIN_GARDENS, props),
    new GoToJail(),

    // fourth
    property_for_index(PACIFIC_AVE, props),
    property_for_index(NORTH_CAROLINA_AVE, props),
    new CommunityChest(),
    property_for_index(PENNSYLVANIA_AVE, props),
    property_for_index(SHORTLINE_RR, props),
    new Chance(),
    property_for_index(PARK_PLACE, props),
    new LuxuryTax(),
    property_for_index(BOARDWALK, props),

  ];
}

// indices correlate to order in below function properties_list()
function property_for_index(index, props) {
  if (index <= 21) {
    return new HousingProperty(props[index][0], props[index][2], props[index][1], props[index][4]);
  } else if (index <= 25) {
    return new RailroadProperty(props[index][0], props[index][2], props[index][3]);
  } else {
    return new UtilityProperty(props[index][0], props[index][2]);
  }
}

/* housing properties: [name, color, cost, house cost, [rent, 1, 2, 3, 4, hotel]]
 railroads: [name, "Railroad", cost, [1, 2, 3, 4]]
 utilities: [name, "Utility", cost]
*/
function properties_list() {
  return [
    ["Mediterranean Ave", PG_BROWN, 60, 50, [2, 10, 30, 90, 160, 250]],
    ["Baltic Ave", PG_BROWN, 60, 50, [4, 20, 60, 180, 320, 450]],

    ["Oriental Ave", PG_LIGHT_BLUE, 100, 50, [6, 30, 90, 270, 400, 550]],
    ["Vermont Ave", PG_LIGHT_BLUE, 100, 50, [6, 30, 90, 270, 400, 550]],
    ["Connecticut Ave", PG_LIGHT_BLUE, 120, 50, [8, 40, 100, 300, 450, 600]],

    ["St. Charles Place", PG_PINK, 140, 100, [10, 50, 150, 450, 625, 750]], // 5
    ["States Ave", PG_PINK, 140, 100, [10, 50, 150, 450, 625, 750]],
    ["Virginia Ave", PG_PINK, 160, 100 [12, 60, 180, 500, 700, 900]],

    ["St. James Place", PG_ORANGE, 180, 100, [14, 70, 200, 550, 750, 950]],
    ["Tennessee Ave", PG_ORANGE, 180, 100, [14, 70, 200, 550, 750, 950]],
    ["New York Ave", PG_ORANGE, 200, 100, [16, 80, 220, 600, 800, 1000]], // 10

    ["Kentucky Ave", PG_RED, 220, 150, [18, 90, 250, 700, 875, 1050]],
    ["Indiana Ave", PG_RED, 220, 150, [18, 90, 250, 700, 875, 1050]],
    ["Illinois Ave", PG_RED, 240, 150, [20, 100, 300, 750, 925, 1100]],

    ["Atlantic Ave", PG_YELLOW, 260, 150, [22, 110, 330, 800, 975, 1150]],
    ["Ventnor Ave", PG_YELLOW, 260, 150, [22, 110, 330, 800, 975, 1150]], // 15
    ["Marvin Gardens", PG_YELLOW, 280, 150, [24, 120, 360, 850, 1025, 1200]],

    ["Pacific Ave", PG_GREEN, 300, 200, [26, 130, 390, 900, 1100, 1275]],
    ["North Carolina Ave", PG_GREEN, 300, 200, [26, 130, 390, 900, 1100, 1275]],
    ["Pennsylvaniva Ave", PG_GREEN, 320, 200, [28, 150, 450, 1000, 1200, 1400]],

    ["Park Place", PG_BLUE, 350, 200, [35, 175, 500, 1100, 1300, 1500]], // 20
    ["Boardwalk", PG_BLUE, 400, 200, [50, 200, 600, 1400, 1700, 2000]],

    ["Reading Railroad", PG_RR, 200, [25, 50, 100, 200]],
    ["Pennsylvania Railroad", PG_RR, 200, [25, 50, 100, 200]],
    ["B. & O. Railroad", PG_RR, 200, [25, 50, 100, 200]],
    ["Shortline Railroad", PG_RR, 200, [25, 50, 100, 200]], // 25

    ["Electric Company", PG_UTIL, 150],
    ["WaterWorks", PG_UTIL, 150]
  ];

}

window.onload = function() {
  build_board();
};
<|endoftext|>


<commit_before>function classNames() {
	var classes = '';
	var arg;

	for (var i = 0; i < arguments.length; i++) {
		arg = arguments[i];
		if (!arg) {
			continue;
		}

		if ('string' === typeof arg || 'number' === typeof arg) {
			classes += ' ' + arg;
		} else if (Object.prototype.toString.call(arg) === '[object Array]') {
			classes += ' ' + classNames.apply(null, arg);
		} else if ('object' === typeof arg) {
			for (var key in arg) {
				if (!arg.hasOwnProperty(key) || !arg[key]) {
					continue;
				}
				classes += ' ' + key;
			}
		}
	}
	return classes.substr(1);
}

// safely export classNames in case the script is included directly on a page
if (typeof module !== 'undefined' && module.exports) {
	module.exports = classNames;
}
<commit_msg>index: clarify intention behind special-cased export<commit_after>function classNames() {
	var classes = '';
	var arg;

	for (var i = 0; i < arguments.length; i++) {
		arg = arguments[i];
		if (!arg) {
			continue;
		}

		if ('string' === typeof arg || 'number' === typeof arg) {
			classes += ' ' + arg;
		} else if (Object.prototype.toString.call(arg) === '[object Array]') {
			classes += ' ' + classNames.apply(null, arg);
		} else if ('object' === typeof arg) {
			for (var key in arg) {
				if (!arg.hasOwnProperty(key) || !arg[key]) {
					continue;
				}
				classes += ' ' + key;
			}
		}
	}
	return classes.substr(1);
}

// safely export classNames for bower
if (typeof module !== 'undefined' && module.exports) {
	module.exports = classNames;
}
<|endoftext|>


<commit_before>const {Transform} = require("../transform")
const RopeSequence = require("rope-sequence")
const {historyPlugin} = require("../history")

const {rebaseSteps} = require("./rebase")
exports.rebaseSteps = rebaseSteps

// !! This module implements an API into which a communication channel
// for collaborative editing can be hooked. See [this
// guide](guide/collab.html) for more details and an example.

function randomID() { return Math.floor(Math.random() * 0xFFFFFFFF) }

// ;; This state field accumulates changes that have to be sent to the
// central authority in the collaborating group and makes it possible
// to integrate changes made by peers into our local document. It is
// created and attached to the editor when the
// [plugin](#collabEditing) is enabled, and will be available as the
// `collab` field in the resulting editor state.
class CollabState {
  constructor(version, clientID, unconfirmed) {
    // : number
    // The version number of the last update received from the central
    // authority. Starts at 0 or the value of the `version` property
    // in the option object, for the editor's value when the option
    // was enabled.
    this.version = version

    // : number
    // This client's random ID. Used to identify the origin of
    // changes.
    this.clientID = clientID

    // : RopeSequence<{step: Step, inverted: Step}>
    // The local steps that havent been successfully sent to the
    // server yet.
    this.unconfirmed = unconfirmed
  }

  applyTransform(transform, options) {
    return options.newCollabState ||
      new CollabState(this.version, this.clientID, this.unconfirmed.append(unconfirmedFrom(transform)))
  }
}

function unconfirmedFrom(transform, start = 0) {
  let add = []
  for (let i = start; i < transform.steps.length; i++)
    add.push({step: transform.steps[i],
              inverted: transform.steps[i].invert(transform.docs[i])})
  return add
}

// :: (EditorState, [Step], [number]) → EditorState
// Pushes a set of steps (received from the central authority) into
// the editor state (which should have the collab plugin enabled).
// Will recognize its own changes, and confirm unconfirmed steps as
// appropriate. Remaining unconfirmed steps will be rebased over
// remote steps.
function receiveSteps(state, steps, clientIDs) {
  let collab = state.collab
  let version = collab.version + steps.length

  // Find out which prefix of the steps originated with us
  let ours = 0
  while (ours < clientIDs.length && clientIDs[ours] == collab.clientID) ++ours
  let unconfirmed = collab.unconfirmed.slice(ours)
  steps = ours ? steps.slice(ours) : steps

  // If all steps originated with us, we're done.
  if (!steps.length)
    return state.update({collab: new CollabState(version, collab.clientID, unconfirmed)})

  let nUnconfirmed = unconfirmed.length
  let transform = new Transform(state.doc)
  if (nUnconfirmed) {
    rebaseSteps(transform, unconfirmed.map(s => s.step), unconfirmed.map(s => s.inverted), steps)
  } else {
    for (let i = 0; i < steps.length; i++) transform.step(steps[i])
  }

  unconfirmed = RopeSequence.from(unconfirmedFrom(transform, nUnconfirmed + steps.length))
  let newCollabState = new CollabState(version, collab.clientID, unconfirmed)
  return state.applyTransform(transform, {rebased: nUnconfirmed, addToHistory: false, newCollabState})
}
exports.receiveSteps = receiveSteps

// :: (EditorState) → ?{version: number, steps: [Step], clientID: number}
// Provides the data describing the editor's unconfirmed steps. The
// version and array of steps are the things you'd send to the
// central authority. Returns null when there is nothing to send.
function sendableSteps(state) {
  let collab = state.collab
  if (collab.unconfirmed.length == 0) return null
  return {
    version: collab.version,
    steps: collab.unconfirmed.map(s => s.step),
    clientID: collab.clientID
  }
}
exports.sendableSteps = sendableSteps

const pluginID = {plugin: "collab"}

// :: (?Object) → Object
//
// Creates a plugin that enables the collaborative editing framework
// for the editor.
//
// You can pass a `version` option, which determines the starting
// version number of the collaborative editing, and defaults to 0.
function collabEditing(options) {
  return {
    identity: pluginID,

    dependencies: [
      historyPlugin({preserveItems: true})
    ],

    stateFields: {collab: () => new CollabState(options && options.version || 0, randomID(), RopeSequence.empty)}
  }
}
exports.collabEditing = collabEditing
<commit_msg>Simplify plugin management, allow plugins to add state methods<commit_after>const {Transform} = require("../transform")
const RopeSequence = require("rope-sequence")

const {rebaseSteps} = require("./rebase")
exports.rebaseSteps = rebaseSteps

// !! This module implements an API into which a communication channel
// for collaborative editing can be hooked. See [this
// guide](guide/collab.html) for more details and an example.

function randomID() { return Math.floor(Math.random() * 0xFFFFFFFF) }

// ;; This state field accumulates changes that have to be sent to the
// central authority in the collaborating group and makes it possible
// to integrate changes made by peers into our local document. It is
// created and attached to the editor when the
// [plugin](#collabEditing) is enabled, and will be available as the
// `collab` field in the resulting editor state.
class CollabState {
  constructor(version, clientID, unconfirmed) {
    // : number
    // The version number of the last update received from the central
    // authority. Starts at 0 or the value of the `version` property
    // in the option object, for the editor's value when the option
    // was enabled.
    this.version = version

    // : number
    // This client's random ID. Used to identify the origin of
    // changes.
    this.clientID = clientID

    // : RopeSequence<{step: Step, inverted: Step}>
    // The local steps that havent been successfully sent to the
    // server yet.
    this.unconfirmed = unconfirmed
  }

  // :: () → ?{version: number, steps: [Step], clientID: number}
  // Provides the data describing the editor's unconfirmed steps. The
  // version and array of steps are the things you'd send to the
  // central authority. Returns null when there is nothing to send.
  sendableSteps() {
    if (this.unconfirmed.length == 0) return null
    return {
      version: this.version,
      steps: this.unconfirmed.map(s => s.step),
      clientID: this.clientID
    }
  }
}

function unconfirmedFrom(transform, start = 0) {
  let add = []
  for (let i = start; i < transform.steps.length; i++)
    add.push({step: transform.steps[i],
              inverted: transform.steps[i].invert(transform.docs[i])})
  return add
}

// :: (EditorState, [Step], [number]) → EditorState
// Pushes a set of steps (received from the central authority) into
// the editor state (which should have the collab plugin enabled).
// Will recognize its own changes, and confirm unconfirmed steps as
// appropriate. Remaining unconfirmed steps will be rebased over
// remote steps.
function receiveSteps(state, steps, clientIDs) {
  let collab = state.collab
  let version = collab.version + steps.length

  // Find out which prefix of the steps originated with us
  let ours = 0
  while (ours < clientIDs.length && clientIDs[ours] == collab.clientID) ++ours
  let unconfirmed = collab.unconfirmed.slice(ours)
  steps = ours ? steps.slice(ours) : steps

  // If all steps originated with us, we're done.
  if (!steps.length)
    return state.update({collab: new CollabState(version, collab.clientID, unconfirmed)})

  let nUnconfirmed = unconfirmed.length
  let transform = new Transform(state.doc)
  if (nUnconfirmed) {
    rebaseSteps(transform, unconfirmed.map(s => s.step), unconfirmed.map(s => s.inverted), steps)
  } else {
    for (let i = 0; i < steps.length; i++) transform.step(steps[i])
  }

  unconfirmed = RopeSequence.from(unconfirmedFrom(transform, nUnconfirmed + steps.length))
  let newCollabState = new CollabState(version, collab.clientID, unconfirmed)
  return state.applyTransform(transform, {rebased: nUnconfirmed, addToHistory: false, newCollabState})
}

// :: (?Object) → Object
//
// Creates a plugin that enables the collaborative editing framework
// for the editor.
//
// You can pass a `version` option, which determines the starting
// version number of the collaborative editing, and defaults to 0.
exports.collab = function(options) {
  return {
    stateFields: {
      collab: {
        init: () => new CollabState(options && options.version || 0, randomID(), RopeSequence.empty),
        applyTransform({collab}, transform, options) {
          return options.newCollabState ||
            new CollabState(collab.version, collab.clientID, collab.unconfirmed.append(unconfirmedFrom(transform)))
        }
      }
    },

    stateMethods: {
      collabReceive(steps, clientIDs) {
        return receiveSteps(this, steps, clientIDs)
      }
    }
  }
}
<|endoftext|>


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

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

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

var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

// 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.post('/', function(request, response) {
  if(request.body['command'] == "/onenoteurl"){
      var url = request.body['text'];

var decodedUrl = decodeURI(url);
var first = decodedUrl.indexOf(".one|");
var second = decodedUrl.indexOf("/", first + 4);
var third = decodedUrl.indexOf("|", second + 1);
var actualName = decodedUrl.substr(second, 5);

var name = actualName+" (Webview)";
      var responseUrl = request.body['response_url'];
      var returnVal = {
    "response_type": "in_channel",
    "text": "A OneNote link to page was pasted",
    "attachments": [
        {
                       "title": name,
            "title_link": url
        }
    ]
};
      response.send(returnVal);
  }
  else {
      response.send("fail");
  }
});

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

<commit_msg>attempting to get page name<commit_after>var express = require('express');
var app = express();

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

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

var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

// 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.post('/', function(request, response) {
  if(request.body['command'] == "/onenoteurl"){
      var url = request.body['text'];

var decodedUrl = decodeURI(url);
var first = decodedUrl.indexOf(".one|");
var second = decodedUrl.indexOf("/", first + 4);
var third = decodedUrl.indexOf("|", second + 1);
var actualName = decodedUrl.substr(first, 25);

var name = actualName+" (Webview)";
      var responseUrl = request.body['response_url'];
      var returnVal = {
    "response_type": "in_channel",
    "text": "A OneNote link to page was pasted",
    "attachments": [
        {
                       "title": name,
            "title_link": url
        }
    ]
};
      response.send(returnVal);
  }
  else {
      response.send("fail");
  }
});

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

<|endoftext|>


<commit_before>var solarflare = function (rays) {
	var $element = document.createElement('div');

	if (Array.isArray(rays)) {
		rays.forEach(function (e, i) {
			if (i === 0 && typeof e === 'string') {
				if (e.length > 0) {
					$element = document.createElement(e);
				}

				return;
			}

			if (typeof e === 'string') {
				$element.innerHTML += e;
			}

			if (e.nodeType) {
				$element.appendChild(e);
			}

			if (typeof e === 'object') {
				if (Array.isArray(e)) {
					$element.appendChild(solarflare(e));
				} else if (e.view  && typeof e.view === 'function') {
					$element.appendChild(e.view());
				} else {
					Object.keys(e).filter(function (key) {
						$element.setAttribute(key, e[key]);
					});
				}
			}
		});
	}

	return $element;
};

module.exports = solarflare;

<commit_msg>element.view() can now be an array or node.<commit_after>var solarflare = function (rays) {
	var $element = document.createElement('div');
	var v;

	if (Array.isArray(rays)) {
		rays.forEach(function (e, i) {
			if (i === 0 && typeof e === 'string') {
				if (e.length > 0) {
					$element = document.createElement(e);
				}

				return;
			}

			if (typeof e === 'string') {
				$element.innerHTML += e;
			}

			if (e.nodeType) {
				$element.appendChild(e);
			}

			if (typeof e === 'object') {
				if (e.view  && typeof e.view === 'function') {
					v = e.view();

					if (Array.isArray(v)) {
						$element.appendChild(solarflare(v));
					} else {
						$element.appendChild(v);
					}
				} else if (Array.isArray(e)) {
					$element.appendChild(solarflare(e));
				} else {
					Object.keys(e).filter(function (key) {
						$element.setAttribute(key, e[key]);
					});
				}
			}
		});
	}

	return $element;
};

module.exports = solarflare;

<|endoftext|>