<commit_before>enterSearchMsg = "Search...";
enterUrlMsg = "Paste URL Here...";
enterTimeMsg = "Type length of video... (ex. 2:49 or 2 49)";

pauseImgSrc = "//cdn.rawgit.com/iconic/open-iconic/master/png/media-pause-4x.png";
playImgSrc = "//cdn.rawgit.com/iconic/open-iconic/master/png/media-play-4x.png";

var search;
var url;
var time;

var videos = {};
var videoCounter = 0;
var videoIteration = 0;
var videoPaused;
var timer;

function Timer(callback, delay) {
  var timerId, start, remaining = delay;

  this.pause = function() {
      window.clearTimeout(timerId);
      remaining -= new Date() - start;
  };

  this.resume = function() {
      start = new Date();
      window.clearTimeout(timerId);
      timerId = window.setTimeout(callback, remaining);
  };

  this.resume();
}

function msConversion(millis) {
  var minutes = Math.floor(millis / 60000);
  var seconds = ((millis % 60000) / 1000).toFixed(0);
  return minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}

function highlight(i) {
  $("tr:nth-child(" + i + ")").attr("id", "newSelected");
  $("tr.selected").removeClass("selected");
  $("#newSelected").addClass("selected");
  $("#newSelected").removeAttr("id");
}

function playVideo() {
  highlight(videoIteration);
  var embedUrl = videos[videoIteration]["url"].replace("/watch?v=", "/embed/") + "?autoplay=1";
  $("#youtube").attr("src", embedUrl);
  $("#pauseImg").attr("src", pauseImgSrc);
}

function loopVideo() {
  videoIteration++;
  playVideo();
  timer = new Timer(function() {
    if (videoIteration < videoCounter) {
      loopVideo();
    }
    else {
      timer.pause();
      timer = 0;
      $("#youtube").attr("src", "");
    }
  }, videos[videoIteration]["time"] + 2000);
}

function pauseVideo() {
  if (!videoPaused) {
    timer.pause();
    $("#pauseImg").attr("src", playImgSrc);
    videoPaused = true;
  }
  else {
    timer.resume();
    $("#pauseImg").attr("src", pauseImgSrc);
    videoPaused = false;
  }
}

function backVideo() {
  if (videoIteration - 2 > -1) {
    videoIteration = videoIteration - 2;
    if (timer != 0) {
      timer.pause();
    }
    timer = 0;
    loopVideo();
  }
}

function forwardVideo() {
  if (videoIteration + 1 <= videoCounter) {
    if (timer != 0) {
      timer.pause();
    }
    timer = 0;
    loopVideo();
  }
}

function Base64EncodeUrl(str){
  str = window.btoa(str);
  return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
}

function Base64DecodeUrl(str){
  str = (str + '===').slice(0, str.length + (str.length % 4));
  str = str.replace(/-/g, '+').replace(/_/g, '/');
  alert(str);
  return window.atob(str);
}

function setPlaylist() {
  var playlist = JSON.stringify(videos);
  playlist = Base64EncodeUrl(playlist);
  window.location.hash = playlist;
}

function getPlaylist() {
  if (window.location.hash.substr(1) !== "") {
    var playlist = window.location.hash.substr(1);
    playlist = Base64DecodeUrl(playlist);
    playlist = JSON.parse(playlist);
    videos = playlist;

    videos.forEach(function() {
      videoCounter++;
      var printTime = msConversion(videos[videoCounter]["time"]);
      $("#videosTable").append("
" + videos[videoCounter]["name"] + "	" + printTime + "
");
    });
    loopVideo();
  }
}
getPlaylist();

function input() {
  switch ($("#inputBox").attr("placeholder")) {
    case enterSearchMsg:
      search = $("#inputBox").val();
      if (search.indexOf(";") === -1) {
        var queryUrl = "https://www.youtube.com/results?search_query=" + search.replace(/ /g, "+");
        window.open(queryUrl);
      }
      else {
        search = search.replace(/\;/g, "");
      }
      $("#inputBox").val("").attr("placeholder", enterUrlMsg);
      break;
    case enterUrlMsg:
      url = $("#inputBox").val();
      $("#inputBox").val("").attr("placeholder", enterTimeMsg);
      break;
    case enterTimeMsg:
      time = $("#inputBox").val();
      time = time.replace(/ /g, ":");
      time = time.split(":");
      time = (+time[0]) * 60 + (+time[1]);
      time = time * 1000;

      videoCounter++;
      videos[videoCounter] = {};
      videos[videoCounter]["name"] = search;
      videos[videoCounter]["time"] = time;
      videos[videoCounter]["url"] = url;

      var printTime = msConversion(videos[videoCounter]["time"]);

      $("#videosTable").append("
" + videos[videoCounter]["name"] + "	" + printTime + "
");

      setPlaylist();

      if (videoCounter == 1 || timer == 0) {
        loopVideo();
      }

      $("#inputBox").val("").attr("placeholder", enterSearchMsg);
      break;
  }
}
<commit_msg>for in instead of foreach<commit_after>enterSearchMsg = "Search...";
enterUrlMsg = "Paste URL Here...";
enterTimeMsg = "Type length of video... (ex. 2:49 or 2 49)";

pauseImgSrc = "//cdn.rawgit.com/iconic/open-iconic/master/png/media-pause-4x.png";
playImgSrc = "//cdn.rawgit.com/iconic/open-iconic/master/png/media-play-4x.png";

var search;
var url;
var time;

var videos = {};
var videoCounter = 0;
var videoIteration = 0;
var videoPaused;
var timer;

function Timer(callback, delay) {
  var timerId, start, remaining = delay;

  this.pause = function() {
      window.clearTimeout(timerId);
      remaining -= new Date() - start;
  };

  this.resume = function() {
      start = new Date();
      window.clearTimeout(timerId);
      timerId = window.setTimeout(callback, remaining);
  };

  this.resume();
}

function msConversion(millis) {
  var minutes = Math.floor(millis / 60000);
  var seconds = ((millis % 60000) / 1000).toFixed(0);
  return minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}

function highlight(i) {
  $("tr:nth-child(" + i + ")").attr("id", "newSelected");
  $("tr.selected").removeClass("selected");
  $("#newSelected").addClass("selected");
  $("#newSelected").removeAttr("id");
}

function playVideo() {
  highlight(videoIteration);
  var embedUrl = videos[videoIteration]["url"].replace("/watch?v=", "/embed/") + "?autoplay=1";
  $("#youtube").attr("src", embedUrl);
  $("#pauseImg").attr("src", pauseImgSrc);
}

function loopVideo() {
  videoIteration++;
  playVideo();
  timer = new Timer(function() {
    if (videoIteration < videoCounter) {
      loopVideo();
    }
    else {
      timer.pause();
      timer = 0;
      $("#youtube").attr("src", "");
    }
  }, videos[videoIteration]["time"] + 2000);
}

function pauseVideo() {
  if (!videoPaused) {
    timer.pause();
    $("#pauseImg").attr("src", playImgSrc);
    videoPaused = true;
  }
  else {
    timer.resume();
    $("#pauseImg").attr("src", pauseImgSrc);
    videoPaused = false;
  }
}

function backVideo() {
  if (videoIteration - 2 > -1) {
    videoIteration = videoIteration - 2;
    if (timer != 0) {
      timer.pause();
    }
    timer = 0;
    loopVideo();
  }
}

function forwardVideo() {
  if (videoIteration + 1 <= videoCounter) {
    if (timer != 0) {
      timer.pause();
    }
    timer = 0;
    loopVideo();
  }
}

function Base64EncodeUrl(str){
  str = window.btoa(str);
  return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
}

function Base64DecodeUrl(str){
  str = (str + '===').slice(0, str.length + (str.length % 4));
  str = str.replace(/-/g, '+').replace(/_/g, '/');
  alert(str);
  return window.atob(str);
}

function setPlaylist() {
  var playlist = JSON.stringify(videos);
  playlist = Base64EncodeUrl(playlist);
  window.location.hash = playlist;
}

function getPlaylist() {
  if (window.location.hash.substr(1) !== "") {
    var playlist = window.location.hash.substr(1);
    playlist = Base64DecodeUrl(playlist);
    playlist = JSON.parse(playlist);
    videos = playlist;

    for (var key in videos) {
      videoCounter++;
      var printTime = msConversion(videos[videoCounter]["time"]);
      $("#videosTable").append("
" + videos[videoCounter]["name"] + "	" + printTime + "
");
    }
    loopVideo();
  }
}
getPlaylist();

function input() {
  switch ($("#inputBox").attr("placeholder")) {
    case enterSearchMsg:
      search = $("#inputBox").val();
      if (search.indexOf(";") === -1) {
        var queryUrl = "https://www.youtube.com/results?search_query=" + search.replace(/ /g, "+");
        window.open(queryUrl);
      }
      else {
        search = search.replace(/\;/g, "");
      }
      $("#inputBox").val("").attr("placeholder", enterUrlMsg);
      break;
    case enterUrlMsg:
      url = $("#inputBox").val();
      $("#inputBox").val("").attr("placeholder", enterTimeMsg);
      break;
    case enterTimeMsg:
      time = $("#inputBox").val();
      time = time.replace(/ /g, ":");
      time = time.split(":");
      time = (+time[0]) * 60 + (+time[1]);
      time = time * 1000;

      videoCounter++;
      videos[videoCounter] = {};
      videos[videoCounter]["name"] = search;
      videos[videoCounter]["time"] = time;
      videos[videoCounter]["url"] = url;

      var printTime = msConversion(videos[videoCounter]["time"]);

      $("#videosTable").append("
" + videos[videoCounter]["name"] + "	" + printTime + "
");

      setPlaylist();

      if (videoCounter == 1 || timer == 0) {
        loopVideo();
      }

      $("#inputBox").val("").attr("placeholder", enterSearchMsg);
      break;
  }
}
<|endoftext|>


<commit_before>import './server/config';
import './server/routes';
<commit_msg>rewrite es6 to commonjs<commit_after>require('./server/config');
require('./server/routes');
<|endoftext|>


<commit_before>var Promise = require("bluebird"),
  url = require("url"),
  path = require("path"),
  BlobService = require("./azureStorageService.js"),
  BaseStore = require("ghost-storage-base"),
  options = {},
  mimeTypes = {
    ".jpg": "image/jpeg",
    ".jpe": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".gif": "image/gif",
    ".png": "image/png",
    ".svg": "image/svg+xml",
    ".svgz": "image/svg+xml",
    ".bmp": "image/bmp",
    ".tiff": "image/tiff"
  };

class AzureGhostStorage extends BaseStore {
  constructor(config = {}) {
    super(config);

    options = config || {};
    options.connectionString =
      process.env.storage_connectionString ||
      process.env.AZURE_STORAGE_CONNECTION_STRING ||
      options.connectionString;
    options.container =
      process.env.storage_container || options.container || "ghost";
    options.cdnUrl = process.env.storage_cdnUrl || options.cdnUrl;
  }

  delete(fileName, targetDir) {
    targetDir = targetDir || this.getTargetDir();
    var blobName = path.join(targetDir, fileName);
    var blobService = new BlobService(options);

    return new Promise((resolve, reject) => {
      return blobService
        .delete(blobName)
        .promise()
        .then(() => resolve(true))
        .catch(() => resolve(false));
    });
  }

  exists(fileName) {
    var blobService = new BlobService(options);
    return new Promise((resolve, reject) => {
      return blobService
        .doesBlobExist(fileName)
        .promise()
        .then(() => resolve(true))
        .catch(() => resolve(false));
    });
  }

  save(image, targetDir) {
    targetDir = targetDir || this.getTargetDir();
    var blobService = new BlobService(options);
    var blobName;

    return new Promise((resolve, reject) => {
      Promise.all([this.getUniqueFileName(image, targetDir)])
        .then(function(fileName, file) {
          blobName = filename;
          var blobOptions = {
            contentSettings: {
              cacheControl: "public, max-age=31536000"
            }
          };

          var ext = path.extname(image.name);
          if (ext) {
            var contentType = mimeTypes[ext];
            if (contentType) {
              blobOptions.contentSettings.contentType = contentType;
            }
          }

          blobService
            .createBlockBlobFromLocalFileAsync(
              blobName,
              image.path,
              blobOptions
            )
            .promise()
            .then(function() {
              var blobUrl = blobService.getUrl(blobName);

              if (!options.cdnUrl) {
                resolve(blobUrl);
              }

              var parsedUrl = url.parse(blobUrl, true, true);
              resolve(options.cdnUrl + parsedUrl.path);
            });
        })
        .catch(error => reject(error));
    });
  }

  serve() {
    return (req, res, next) => {
      next();
    };
  }

  read() {
    /*
     * Dummy function as ghost needs it
     */
  }
}

module.exports = AzureGhostStorage;
<commit_msg>fix promise error.<commit_after>var Promise = require("bluebird"),
  url = require("url"),
  path = require("path"),
  BlobService = require("./azureStorageService.js"),
  BaseStore = require("ghost-storage-base"),
  readFile = require("fs"),
  options = {},
  mimeTypes = {
    ".jpg": "image/jpeg",
    ".jpe": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".gif": "image/gif",
    ".png": "image/png",
    ".svg": "image/svg+xml",
    ".svgz": "image/svg+xml",
    ".bmp": "image/bmp",
    ".tiff": "image/tiff"
  };

class AzureGhostStorage extends BaseStore {
  constructor(config = {}) {
    super(config);

    options = config || {};
    options.connectionString =
      process.env.storage_connectionString ||
      process.env.AZURE_STORAGE_CONNECTION_STRING ||
      options.connectionString;
    options.container =
      process.env.storage_container || options.container || "ghost";
    options.cdnUrl = process.env.storage_cdnUrl || options.cdnUrl;
  }

  delete(fileName, targetDir) {
    targetDir = targetDir || this.getTargetDir();
    var blobName = path.join(targetDir, fileName);
    var blobService = new BlobService(options);

    return new Promise((resolve, reject) => {
      return blobService
        .delete(blobName)
        .promise()
        .then(() => resolve(true))
        .catch(() => resolve(false));
    });
  }

  exists(fileName) {
    var blobService = new BlobService(options);
    return blobService.doesBlobExist(fileName);
  }

  save(image, targetDir) {
    targetDir = targetDir || this.getTargetDir();
    var blobService = new BlobService(options);
    var blobName;

    return this.getUniqueFileName(image, targetDir)
      .then(function(filename) {
        blobName = filename;

        var blobOptions = {
          contentSettings: {
            cacheControl: "public, max-age=31536000"
          }
        };

        var ext = path.extname(image.name);
        if (ext) {
          var contentType = mimeTypes[ext];
          if (contentType) {
            blobOptions.contentSettings.contentType = contentType;
          }
        }

        return blobService.createBlockBlobFromLocalFileAsync(
          blobName,
          image.path,
          blobOptions
        );
      })
      .delay(500)
      .then(function() {
        var blobUrl = blobService.getUrl(blobName);
        if (!options.cdnUrl) {
          return blobUrl;
        }

        var parsedUrl = url.parse(blobUrl, true, true);
        return options.cdnUrl + parsedUrl.path;
      });
  }

  serve() {
    return (req, res, next) => {
      next();
    };
  }

  read() {
    /*
     * Dummy function as ghost needs it
     */
  }
}

module.exports = AzureGhostStorage;
<|endoftext|>


<commit_before>/* eslint-env node */
'use strict';

const path = require('path');
const util = require('util');
const extend = util._extend;
const mergeTrees = require('broccoli-merge-trees');
const Funnel = require('broccoli-funnel');
const stew = require('broccoli-stew');
const mv = stew.mv;
// const log = stew.log;
const rm = stew.rm;
const chalk = require('chalk');

const defaultOptions = {
  importBootstrapTheme: false,
  importBootstrapCSS: true,
  importBootstrapFont: true,
  bootstrapVersion: 3
};

const supportedPreprocessors = [
  'less',
  'sass'
];

module.exports = {
  name: 'ember-bootstrap',

  included(app) {
    // workaround for https://github.com/ember-cli/ember-cli/issues/3718
    if (typeof app.import !== 'function' && app.app) {
      app = app.app;
    }
    this.app = app;

    let options = extend({}, defaultOptions, app.options['ember-bootstrap']);
    if (process.env['BOOTSTRAPVERSION']) {
      // override bootstrapVersion config when environment variable is set
      options.bootstrapVersion = parseInt(process.env['BOOTSTRAPVERSION']);
    }
    this.bootstrapOptions = options;

    this.preprocessor = this.findPreprocessor();

    if (!this.hasPreprocessor()) {

      // static Bootstrap CSS is mapped to vendor tree, independent of BS version, so import from there
      let cssPath = path.join('vendor', 'ember-bootstrap');

      // / Import css from bootstrap
      if (options.importBootstrapCSS) {
        app.import(path.join(cssPath, 'bootstrap.css'));
        app.import(path.join(cssPath, 'bootstrap.css.map'), { destDir: 'assets' });
      }

      if (options.importBootstrapTheme) {
        app.import(path.join(cssPath, 'bootstrap-theme.css'));
        app.import(path.join(cssPath, 'bootstrap-theme.css.map'), { destDir: 'assets' });
      }
    }

    if (!process.env.EMBER_CLI_FASTBOOT) {
      app.import('vendor/transition.js');
    }
  },

  findPreprocessor() {
    return supportedPreprocessors.find((name) => !!this.app.project.findAddonByName(`ember-cli-${name}`) && this.validatePreprocessor(name));
  },

  validatePreprocessor(name) {
    let npmDependencies = this.app.project.dependencies();
    let bowerDependencies = this.app.project.bowerDependencies();
    switch (name) {
      case 'sass':
        if (!('bootstrap-sass' in npmDependencies)) {
          this.ui.writeLine(chalk.red('Npm package "bootstrap-sass" is missing, but required for SASS support. Please run `ember generate ember-bootstrap` to install the missing dependencies!'));
          return false;
        }
        break;
      case 'less':
        if (this.getBootstrapVersion() === 4) {
          this.ui.writeLine(chalk.red('There is no Less support for Bootstrap 4! Falling back to importing static CSS. Consider switching to Sass for preprocessor support!'));
          return false;
        }
        if (!('bootstrap' in bowerDependencies)) {
          this.ui.writeLine(chalk.red('Bower package "bootstrap" is missing, but required for Less support. Please run `ember generate ember-bootstrap` to install the missing dependencies!'));
          return false;
        }
        break;
    }
    return true;
  },

  getBootstrapStylesPath() {
    switch (this.preprocessor) {
      case 'sass':
        if (this.getBootstrapVersion() === 4) {
          return path.join(this.app.project.nodeModulesPath, 'bootstrap', 'scss');
        } else {
          return path.join(this.app.project.nodeModulesPath, 'bootstrap-sass', 'assets', 'stylesheets');
        }
      case 'less':
        return path.join(this.app.bowerDirectory, 'bootstrap', 'less');
      default:
        if (this.getBootstrapVersion() === 4) {
          return path.join(this.app.project.nodeModulesPath, 'bootstrap', 'dist', 'css');
        } else {
          return path.join(this.app.bowerDirectory, 'bootstrap', 'dist', 'css');
        }
    }
  },

  getBootstrapFontPath() {
    switch (this.preprocessor) {
      case 'sass':
        return path.join(this.app.project.nodeModulesPath, 'bootstrap-sass', 'assets', 'fonts');
      case 'less':
      default:
        return path.join(this.app.bowerDirectory, 'bootstrap', 'fonts');
    }
  },

  hasPreprocessor() {
    return !!this.preprocessor;
  },

  treeForStyles() {
    if (this.hasPreprocessor()) {
      return new Funnel(this.getBootstrapStylesPath(), {
        destDir: 'ember-bootstrap'
      });
    }
  },

  treeForPublic() {
    if (this.getBootstrapVersion() === 3 && this.bootstrapOptions.importBootstrapFont) {
      return new Funnel(this.getBootstrapFontPath(), {
        destDir: 'fonts'
      });
    }
  },

  treeForVendor(tree) {
    let trees = [tree];
    if (!this.hasPreprocessor()) {
      trees.push(new Funnel(this.getBootstrapStylesPath(), {
        destDir: 'ember-bootstrap'
      }));
    }
    return mergeTrees(trees);
  },

  getBootstrapVersion() {
    return parseInt(this.bootstrapOptions.bootstrapVersion);
  },

  getOtherBootstrapVersion() {
    return this.getBootstrapVersion() === 3 ? 4 : 3;
  },

  treeForAddon() {
    let tree = this._super.treeForAddon.apply(this, arguments);
    let bsVersion = this.getBootstrapVersion();
    let otherBsVersion = this.getOtherBootstrapVersion();
    let componentsPath = 'modules/ember-bootstrap/components/';
    tree = mv(tree, `${componentsPath}bs${bsVersion}/`, componentsPath);
    tree = rm(tree, `${componentsPath}bs${otherBsVersion}/**/*`);
    return tree; // log(tree, {output: 'tree', label: 'moved'});
  },

  treeForAddonTemplates() {
    let tree = this._super.treeForAddonTemplates.apply(this, arguments);
    let bsVersion = this.getBootstrapVersion();
    let otherBsVersion = this.getOtherBootstrapVersion();
    let templatePath = 'components/';
    tree = mv(tree, `${templatePath}common/`, templatePath);
    tree = mv(tree, `${templatePath}bs${bsVersion}/`, templatePath);
    tree = rm(tree, `${templatePath}bs${otherBsVersion}/**/*`);
    return tree; //log(tree, {output: 'tree', label: 'moved'});
  },

  treeForTemplates() {
    let tree = this._super.treeForTemplates.apply(this, arguments);
    let bsVersion = this.getBootstrapVersion();
    let otherBsVersion = this.getOtherBootstrapVersion();
    let templatePath = 'components/';
    tree = mv(tree, `${templatePath}common/`, templatePath);
    tree = mv(tree, `${templatePath}bs${bsVersion}/`, templatePath);
    tree = rm(tree, `${templatePath}bs${otherBsVersion}/**/*`);
    return tree; //log(tree, {output: 'tree', label: 'moved'});
  }
};
<commit_msg>fix how options are merged<commit_after>/* eslint-env node */
'use strict';

const path = require('path');
const util = require('util');
const extend = util._extend;
const mergeTrees = require('broccoli-merge-trees');
const Funnel = require('broccoli-funnel');
const stew = require('broccoli-stew');
const mv = stew.mv;
// const log = stew.log;
const rm = stew.rm;
const chalk = require('chalk');

const defaultOptions = {
  importBootstrapTheme: false,
  importBootstrapCSS: true,
  importBootstrapFont: true,
  bootstrapVersion: 3
};

const supportedPreprocessors = [
  'less',
  'sass'
];

module.exports = {
  name: 'ember-bootstrap',

  included(app) {
    // workaround for https://github.com/ember-cli/ember-cli/issues/3718
    if (typeof app.import !== 'function' && app.app) {
      app = app.app;
    }
    this.app = app;

    let options = extend(extend({}, defaultOptions), app.options['ember-bootstrap']);
    if (process.env['BOOTSTRAPVERSION']) {
      // override bootstrapVersion config when environment variable is set
      options.bootstrapVersion = parseInt(process.env['BOOTSTRAPVERSION']);
    }
    this.bootstrapOptions = options;

    this.preprocessor = this.findPreprocessor();

    if (!this.hasPreprocessor()) {

      // static Bootstrap CSS is mapped to vendor tree, independent of BS version, so import from there
      let cssPath = path.join('vendor', 'ember-bootstrap');

      // / Import css from bootstrap
      if (options.importBootstrapCSS) {
        app.import(path.join(cssPath, 'bootstrap.css'));
        app.import(path.join(cssPath, 'bootstrap.css.map'), { destDir: 'assets' });
      }

      if (options.importBootstrapTheme) {
        app.import(path.join(cssPath, 'bootstrap-theme.css'));
        app.import(path.join(cssPath, 'bootstrap-theme.css.map'), { destDir: 'assets' });
      }
    }

    if (!process.env.EMBER_CLI_FASTBOOT) {
      app.import('vendor/transition.js');
    }
  },

  findPreprocessor() {
    return supportedPreprocessors.find((name) => !!this.app.project.findAddonByName(`ember-cli-${name}`) && this.validatePreprocessor(name));
  },

  validatePreprocessor(name) {
    let npmDependencies = this.app.project.dependencies();
    let bowerDependencies = this.app.project.bowerDependencies();
    switch (name) {
      case 'sass':
        if (!('bootstrap-sass' in npmDependencies)) {
          this.ui.writeLine(chalk.red('Npm package "bootstrap-sass" is missing, but required for SASS support. Please run `ember generate ember-bootstrap` to install the missing dependencies!'));
          return false;
        }
        break;
      case 'less':
        if (this.getBootstrapVersion() === 4) {
          this.ui.writeLine(chalk.red('There is no Less support for Bootstrap 4! Falling back to importing static CSS. Consider switching to Sass for preprocessor support!'));
          return false;
        }
        if (!('bootstrap' in bowerDependencies)) {
          this.ui.writeLine(chalk.red('Bower package "bootstrap" is missing, but required for Less support. Please run `ember generate ember-bootstrap` to install the missing dependencies!'));
          return false;
        }
        break;
    }
    return true;
  },

  getBootstrapStylesPath() {
    switch (this.preprocessor) {
      case 'sass':
        if (this.getBootstrapVersion() === 4) {
          return path.join(this.app.project.nodeModulesPath, 'bootstrap', 'scss');
        } else {
          return path.join(this.app.project.nodeModulesPath, 'bootstrap-sass', 'assets', 'stylesheets');
        }
      case 'less':
        return path.join(this.app.bowerDirectory, 'bootstrap', 'less');
      default:
        if (this.getBootstrapVersion() === 4) {
          return path.join(this.app.project.nodeModulesPath, 'bootstrap', 'dist', 'css');
        } else {
          return path.join(this.app.bowerDirectory, 'bootstrap', 'dist', 'css');
        }
    }
  },

  getBootstrapFontPath() {
    switch (this.preprocessor) {
      case 'sass':
        return path.join(this.app.project.nodeModulesPath, 'bootstrap-sass', 'assets', 'fonts');
      case 'less':
      default:
        return path.join(this.app.bowerDirectory, 'bootstrap', 'fonts');
    }
  },

  hasPreprocessor() {
    return !!this.preprocessor;
  },

  treeForStyles() {
    if (this.hasPreprocessor()) {
      return new Funnel(this.getBootstrapStylesPath(), {
        destDir: 'ember-bootstrap'
      });
    }
  },

  treeForPublic() {
    if (this.getBootstrapVersion() === 3 && this.bootstrapOptions.importBootstrapFont) {
      return new Funnel(this.getBootstrapFontPath(), {
        destDir: 'fonts'
      });
    }
  },

  treeForVendor(tree) {
    let trees = [tree];
    if (!this.hasPreprocessor()) {
      trees.push(new Funnel(this.getBootstrapStylesPath(), {
        destDir: 'ember-bootstrap'
      }));
    }
    return mergeTrees(trees);
  },

  getBootstrapVersion() {
    return parseInt(this.bootstrapOptions.bootstrapVersion);
  },

  getOtherBootstrapVersion() {
    return this.getBootstrapVersion() === 3 ? 4 : 3;
  },

  treeForAddon() {
    let tree = this._super.treeForAddon.apply(this, arguments);
    let bsVersion = this.getBootstrapVersion();
    let otherBsVersion = this.getOtherBootstrapVersion();
    let componentsPath = 'modules/ember-bootstrap/components/';
    tree = mv(tree, `${componentsPath}bs${bsVersion}/`, componentsPath);
    tree = rm(tree, `${componentsPath}bs${otherBsVersion}/**/*`);
    return tree; // log(tree, {output: 'tree', label: 'moved'});
  },

  treeForAddonTemplates() {
    let tree = this._super.treeForAddonTemplates.apply(this, arguments);
    let bsVersion = this.getBootstrapVersion();
    let otherBsVersion = this.getOtherBootstrapVersion();
    let templatePath = 'components/';
    tree = mv(tree, `${templatePath}common/`, templatePath);
    tree = mv(tree, `${templatePath}bs${bsVersion}/`, templatePath);
    tree = rm(tree, `${templatePath}bs${otherBsVersion}/**/*`);
    return tree; //log(tree, {output: 'tree', label: 'moved'});
  },

  treeForTemplates() {
    let tree = this._super.treeForTemplates.apply(this, arguments);
    let bsVersion = this.getBootstrapVersion();
    let otherBsVersion = this.getOtherBootstrapVersion();
    let templatePath = 'components/';
    tree = mv(tree, `${templatePath}common/`, templatePath);
    tree = mv(tree, `${templatePath}bs${bsVersion}/`, templatePath);
    tree = rm(tree, `${templatePath}bs${otherBsVersion}/**/*`);
    return tree; //log(tree, {output: 'tree', label: 'moved'});
  }
};
<|endoftext|>


<commit_before>var color = require("color");

var Radient = function(obj) {
  if (obj instanceof Radient) return obj;

  this.stops = [];

  for (var i = 0; i < arguments.length; i++)
    this.stops.push({ color: new color(arguments[i]), location: null });

  this.distribute();
}

Radient.prototype.distribute = function()
{
  n = 1 / (this.stops.length - 1);

  for (var i = 0; i < this.stops.length; i++)
    this.stops[i].location = i * n;
}

Radient.prototype.stop = function(c, l)
{
  l = parseFloat(l);

  if(isNaN(l)) throw new Error("Invalid stop location: " + l);

  if (stop = this.stopAt(l))
    stop.color = new color(c);
  else
    this.stops.push({ color: new color(c), location: l });

  this.sort();
}

Radient.prototype.stopAt = function(l)
{
  for (var i = 0; i < this.stops.length; i++)
    if (this.stops[i].location == l)
      return this.stops[i];
}

Radient.prototype.sort = function()
{
  this.stops.sort(function (a, b) {
    return a.location - b.location;
  });
}

Radient.prototype.color = function(l)
{
  if (this.stops.length < 2) throw new Error("Gradients must have at least two stops");

  l = parseFloat(l);

  if(isNaN(l) || l < 0 || l > 1)
    throw new Error("Invalid stop location: " + l);

  left = null;
  right = null;

  for (var i = 0; i < this.stops.length; i++)
  {
    if (this.stops[i].location == l)
      return this.stops[i].color;

    if (this.stops[i].location < l)
      left = this.stops[i];

    if (this.stops[i].location > l) {
      right = this.stops[i];
      break;
    }
  }

  if      (! left)  return right.color;
  else if (! right) return left.color;

  ratio = ( l - left.location ) / ( right.location - left.location);

  console.log(ratio);

  return left.color.mix(right.color, ratio);
}

Radient.prototype.angle = function(deg)
{
  l = deg / 360;
  return this.color(l);
}

Radient.prototype.array = function(num)
{
  if (this.stops.length < 2) throw new Error("Gradients must have at least two stops");
}

Radient.prototype.toString = function()
{
  if (this.stops.length == 0) return 'empty gradient';

  r = [];

  this.stops.forEach(function(element) {
    r.push(element.location + ' ' + element.color.hexString());
  });

  return r.join("\n");
}

module.exports = Radient;

g = new Radient();
<commit_msg>Fix color mixing; Implement array getter;<commit_after>var color = require("color");

var Radient = function(obj) {
  if (obj instanceof Radient) return obj;

  this.stops = [];

  for (var i = 0; i < arguments.length; i++)
    this.stops.push({ color: new color(arguments[i]), location: null });

  this.distribute();
}

Radient.prototype.distribute = function()
{
  n = 1 / (this.stops.length - 1);

  for (var i = 0; i < this.stops.length; i++)
    this.stops[i].location = i * n;
}

Radient.prototype.stop = function(c, l)
{
  l = parseFloat(l);

  if(isNaN(l)) throw new Error("Invalid stop location: " + l);

  if (stop = this.stopAt(l))
    stop.color = new color(c);
  else
    this.stops.push({ color: new color(c), location: l });

  this.sort();
}

Radient.prototype.stopAt = function(l)
{
  for (var i = 0; i < this.stops.length; i++)
    if (this.stops[i].location == l)
      return this.stops[i];
}

Radient.prototype.sort = function()
{
  this.stops.sort(function (a, b) {
    return a.location - b.location;
  });
}

Radient.prototype.color = function(l)
{
  if (this.stops.length < 2) throw new Error("Gradients must have at least two stops");

  l = parseFloat(l);

  if(isNaN(l) || l < 0 || l > 1)
    throw new Error("Invalid stop location: " + l);

  left = null;
  right = null;

  for (var i = 0; i < this.stops.length; i++)
  {
    if (this.stops[i].location == l)
      return this.stops[i].color;

    if (this.stops[i].location < l)
      left = this.stops[i];

    if (this.stops[i].location > l) {
      right = this.stops[i];
      break;
    }
  }

  if      (! left)  return right.color;
  else if (! right) return left.color;

  ratio = ( l - left.location ) / ( right.location - left.location);

  return left.color.mix(right.color, ratio);
}

Radient.prototype.mix = function(c1, c2, ratio)
{
  c1 = new color(c1).rgbArray();
  c2 = new color(c2).rgbArray();
  mixed = [];

  for (var i = 0; i < c1.length; i++)
    mixed[i] = ( c1[i] * 1 - ratio ) + ( c2[i] * (ratio));

  return new color().rgb(mixed);
}

Radient.prototype.angle = function(deg)
{
  l = deg / 360;
  return this.color(l);
}

Radient.prototype.array = function(num)
{
  if (this.stops.length < 2) throw new Error("Gradients must have at least two stops");

  a = [];
  num = num || 8;

  for (var i = 0; i < num; i++) {
    a.push(this.color(i / (num - 1)).hexString());
  }

  return a;
}

Radient.prototype.toString = function()
{
  if (this.stops.length == 0) return 'empty gradient';

  r = [];

  this.stops.forEach(function(element) {
    r.push(element.location + ' ' + element.color.hexString());
  });

  return r.join("\n");
}

module.exports = Radient;
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict'

var geopkg = require('./lib/geopkg')
var pkg = require('./package')

var cmd = process.argv[2] || 'update'

switch (cmd) {
  case 'help':
    help()
    break
  case 'update':
    update()
    break
  case 'open':
    open()
    break
  case 'preview':
    preview()
    break
  case 'interactive':
    interactive()
    break
  default:
    _unknown(cmd)
}

function help () {
  console.log(
    pkg.name + ' ' + pkg.version + '\n' +
    pkg.description + '\n\n' +
    'Usage: ' + pkg.name + ' [command]\n\n' +
    'If no commands are given, the default "update" command is run\n\n' +
    'Commands:\n' +
    '  help         Show this help\n' +
    '  update       Updates the current package.json with current coordinates\n' +
    '  open         Opens the coordinates found in package.json in the browser\n' +
    '  preview      Finds your current location and previews it in the browser\n' +
    '  interacive   Choose coordinates interactively by dragging a marker on a map\n'
  )
  process.exit()
}

function update () {
  _getLocation(function (err, loc) {
    if (err) return _done(err)
    console.log('Updating package.json...')
    geopkg.updatePkg(loc, _done)
  })
}

function open () {
  var currentPkg = geopkg.getPackage()
  if (currentPkg && currentPkg.coordinates) {
    return geopkg.openMaps(currentPkg.coordinates, _done)
  }

  if (!currentPkg) {
    console.error('Could not find a package.json in the current working directory!')
  } else {
    console.log('The current package.json doesn\'t contain any coordinates!')
  }

    console.error('To view your current location, type `geopkg preview`')
    process.exit(1)
}

function preview () {
  _getLocation(function (err, loc) {
    if (err) return _done(err)
    console.log('Opening location in browser...')
    geopkg.openMaps(loc, _done)
  })
}

function interactive () {
  var currentCoords = geopkg.getPackageCoords()
  if (currentCoords) {
    currentCoords = { lat: currentCoords[0], lng: currentCoords[1] }
    selectCoordsInteractively(currentCoords)
  } else {
    _getLocation(function (err, loc) {
      if (err) return _done(err)
      selectCoordsInteractively(loc)
    })
  }

  function selectCoordsInteractively (loc) {
    console.log('Opening location in browser...')
    geopkg.openMapWithDraggableMarker(loc, function (err, newLoc) {
      if (err) return _done(err)
      console.log('Updating package.json...')
      geopkg.updatePkg(newLoc, _done)
    })
  }
}

function _unknown (cmd) {
  console.error('Unknown command %s', cmd)
  console.error('Run `geopkg help` for more information')
  process.exit(1)
  return
}

function _getLocation (cb) {
  console.log('Gathering location info...')
  geopkg.locate(function (err, loc) {
    if (err) return cb(err)

    if (!loc) {
      console.error('\nERROR: Could not find your location!')
      console.error('Your wifi needs to be turned on for %s to find your location', pkg.name)
      console.error('If the problem persists, please open an issue at:\n\n  %s\n', pkg.bugs.url)
      console.error('- Remember to specify your OS and hardware')
      process.exit(1)
      return
    }

    console.log('Found location - lat: %d, long: %d, accuracy: %d', loc.lat, loc.lng, loc.accuracy)

    cb(null, loc)
  })
}

function _done (err) {
  if (!err) return
  console.error('ERROR:', err.message)
  process.exit(1)
}
<commit_msg>fixes adherence to standard<commit_after>#!/usr/bin/env node
'use strict'

var geopkg = require('./lib/geopkg')
var pkg = require('./package')

var cmd = process.argv[2] || 'update'

switch (cmd) {
  case 'help':
    help()
    break
  case 'update':
    update()
    break
  case 'open':
    open()
    break
  case 'preview':
    preview()
    break
  case 'interactive':
    interactive()
    break
  default:
    _unknown(cmd)
}

function help () {
  console.log(
    pkg.name + ' ' + pkg.version + '\n' +
    pkg.description + '\n\n' +
    'Usage: ' + pkg.name + ' [command]\n\n' +
    'If no commands are given, the default "update" command is run\n\n' +
    'Commands:\n' +
    '  help         Show this help\n' +
    '  update       Updates the current package.json with current coordinates\n' +
    '  open         Opens the coordinates found in package.json in the browser\n' +
    '  preview      Finds your current location and previews it in the browser\n' +
    '  interacive   Choose coordinates interactively by dragging a marker on a map\n'
  )
  process.exit()
}

function update () {
  _getLocation(function (err, loc) {
    if (err) return _done(err)
    console.log('Updating package.json...')
    geopkg.updatePkg(loc, _done)
  })
}

function open () {
  var currentPkg = geopkg.getPackage()
  if (currentPkg && currentPkg.coordinates) {
    return geopkg.openMaps(currentPkg.coordinates, _done)
  }

  if (!currentPkg) {
    console.error('Could not find a package.json in the current working directory!')
  } else {
    console.log('The current package.json doesn\'t contain any coordinates!')
  }

  console.error('To view your current location, type `geopkg preview`')
  process.exit(1)
}

function preview () {
  _getLocation(function (err, loc) {
    if (err) return _done(err)
    console.log('Opening location in browser...')
    geopkg.openMaps(loc, _done)
  })
}

function interactive () {
  var currentCoords = geopkg.getPackageCoords()
  if (currentCoords) {
    currentCoords = { lat: currentCoords[0], lng: currentCoords[1] }
    selectCoordsInteractively(currentCoords)
  } else {
    _getLocation(function (err, loc) {
      if (err) return _done(err)
      selectCoordsInteractively(loc)
    })
  }

  function selectCoordsInteractively (loc) {
    console.log('Opening location in browser...')
    geopkg.openMapWithDraggableMarker(loc, function (err, newLoc) {
      if (err) return _done(err)
      console.log('Updating package.json...')
      geopkg.updatePkg(newLoc, _done)
    })
  }
}

function _unknown (cmd) {
  console.error('Unknown command %s', cmd)
  console.error('Run `geopkg help` for more information')
  process.exit(1)
  return
}

function _getLocation (cb) {
  console.log('Gathering location info...')
  geopkg.locate(function (err, loc) {
    if (err) return cb(err)

    if (!loc) {
      console.error('\nERROR: Could not find your location!')
      console.error('Your wifi needs to be turned on for %s to find your location', pkg.name)
      console.error('If the problem persists, please open an issue at:\n\n  %s\n', pkg.bugs.url)
      console.error('- Remember to specify your OS and hardware')
      process.exit(1)
      return
    }

    console.log('Found location - lat: %d, long: %d, accuracy: %d', loc.lat, loc.lng, loc.accuracy)

    cb(null, loc)
  })
}

function _done (err) {
  if (!err) return
  console.error('ERROR:', err.message)
  process.exit(1)
}
<|endoftext|>


<commit_before>var midi = require('midi')
var request = require('request')
var Bacon = require('baconjs')

var siteKey = process.env.HORSELIGHTS_SITEKEY
var lightId = process.argv[2]

if(siteKey == null || lightId == null) {
  throw "Please provide site key in environment variable and light id as command line parameter"
}

console.log("Controlling lightId", lightId);

function putLightState(state) {
  console.log("Putting state", state)
  var url = "https://houm.herokuapp.com/api/site/" + siteKey + "/light/state"
  request({ method: 'PUT', url: url, body: state, json: true }, function (error, response, body) {
    if(error) {
      console.log("Failed putting light state to", state)
    }
  })
}

function isControlMessage(message) {
  return (message[0] >> 4) === 0xb
}

var input = new midi.input()

var midiMessages =
  Bacon.fromEventTarget(input, 'message', function(deltaTime, message) { return message })

var controlMessages = midiMessages.filter(isControlMessage)
var houmioLightState = controlMessages.map(function(message) {
  // MIDI gives us 0-127, Houmio expects 0-255
  var midiControllerValue = message[2]
  var brightness = midiControllerValue * 2
  return {
    _id: lightId,
    on: brightness > 0,
    bri: brightness
  }
})

houmioLightState.throttle(500).onValue(putLightState)

input.openPort(0)
<commit_msg>Refactor<commit_after>var midi = require('midi')
var request = require('request')
var Bacon = require('baconjs')

var siteKey = process.env.HORSELIGHTS_SITEKEY
var lightId = process.argv[2]

if(siteKey == null || lightId == null) {
  throw "Please provide site key in environment variable and light id as command line parameter"
}

console.log("Controlling lightId", lightId);

function putLightState(state) {
  console.log("Putting state", state)
  var url = "https://houm.herokuapp.com/api/site/" + siteKey + "/light/state"
  request({ method: 'PUT', url: url, body: state, json: true }, function (error, response, body) {
    if(error) {
      console.log("Failed putting light state to", state)
    }
  })
}

function isControlMessage(midiMessage) {
  return (midiMessage[0] >> 4) === 0xb
}

function toHoumioLightState(midiMessage) {
  // MIDI gives us 0-127, Houmio expects 0-255
  var midiControllerValue = midiMessage[2]
  var brightness = midiControllerValue * 2
  return {
    _id: lightId,
    on: brightness > 0,
    bri: brightness
  }
}

var input = new midi.input()

var midiMessages =
  Bacon.fromEventTarget(input, 'message', function(deltaTime, message) { return message })

midiMessages
  .filter(isControlMessage)
  .map(toHoumioLightState)
  .throttle(500)
  .onValue(putLightState)

input.openPort(0)
<|endoftext|>


<commit_before>const express = require('express'),
      app = express(),
      compression = require('compression'),
      bodyParser = require('body-parser'),
      cookieParser = require('cookie-parser'),
      handlebars = require('express-handlebars'),
      logger = require('morgan'),
      session = require('express-session'),
      MongoStore = require('connect-mongo')(session),
      busboy = require('connect-busboy'),
      rope = require('./lib/db').rope;

process.on('SIGINT', function() {
  rope.close(function() {
    process.exit(0);
  });
});

app.use(cookieParser());
app.use(busboy({
  immediate: true
}));

app.use(session({
  secret: 'foo',
  name: 'muffin.session',
  store: new MongoStore({
    mongooseConnection: rope
  }),
  resave: false,
  saveUninitialized: true
}));

app.engine('hbs', handlebars({
  defaultLayout: 'main',
  extname: '.hbs',
  helpers: require('./lib/helpers')
}));

app.locals.menuItems = [
  {
    url: '.',
    title: 'Dashboard'
  },
  {
    url: 'pages',
    title: 'Pages'
  },
  {
    url: 'media',
    title: 'Media'
  },
  {
    url: 'settings',
    title: 'Settings'
  }
];

app.locals.appVersion = require('./package.json').version;
app.set('view engine', 'hbs');

app.use(compression());
app.use(logger('dev'));

app.use(function(req, res, next) {
  res.header('x-powered-by', 'Muffin CMS');
  next();
});

app.get('/admin*', function(req, res, next) {

  const url = req.url;

  // Check if request wants a file. If so, let it through.
  if (url.match(/[^\\/]+\.[^\\/]+$/)) {
    return next();
  }

  if (req.session.loggedIn) {
    next();
  } else {

    switch (req.originalUrl) {
      case '/admin':
      case '/admin/':
        var to = '';
        break;

      default:
        var to = '/?to=' + encodeURIComponent(req.originalUrl.replace('/admin/', ''))
    }

    res.redirect('/login' + to);

  }

});

app.use('/admin/assets', express.static('./dist'));

app.use(bodyParser.json());

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

app.use('/login', require('./routes/login'));
app.use('/uploads*', require('./routes/uploads'));

app.use('/admin', require('./routes/dashboard'));
app.use('/admin/pages', require('./routes/pages'));
app.use('/admin/media', require('./routes/media'));

app.listen(2000, function() {
  var port = this.address().port;
  console.log('Muffin is running at http://localhost:' + port + '/admin');
});
<commit_msg>Prevent strangers from retrieving data from the backend<commit_after>const express = require('express'),
      app = express(),
      compression = require('compression'),
      bodyParser = require('body-parser'),
      cookieParser = require('cookie-parser'),
      handlebars = require('express-handlebars'),
      logger = require('morgan'),
      session = require('express-session'),
      MongoStore = require('connect-mongo')(session),
      busboy = require('connect-busboy'),
      rope = require('./lib/db').rope;

process.on('SIGINT', function() {
  rope.close(function() {
    process.exit(0);
  });
});

app.use(cookieParser());
app.use(busboy({
  immediate: true
}));

app.use(session({
  secret: 'foo',
  name: 'muffin.session',
  store: new MongoStore({
    mongooseConnection: rope
  }),
  resave: false,
  saveUninitialized: true
}));

app.engine('hbs', handlebars({
  defaultLayout: 'main',
  extname: '.hbs',
  helpers: require('./lib/helpers')
}));

app.locals.menuItems = [
  {
    url: '.',
    title: 'Dashboard'
  },
  {
    url: 'pages',
    title: 'Pages'
  },
  {
    url: 'media',
    title: 'Media'
  },
  {
    url: 'settings',
    title: 'Settings'
  }
];

app.locals.appVersion = require('./package.json').version;
app.set('view engine', 'hbs');

app.use(compression());
app.use(logger('dev'));

app.use(function(req, res, next) {
  res.header('x-powered-by', 'Muffin CMS');
  next();
});

app.get('/admin*', function(req, res, next) {

  const url = req.url;

  // Check if request wants a file. If so, let it through.
  if (url.match(/[^\\/]+\.[^\\/]+$/)) {
    return next();
  }

  if (req.session.loggedIn) {
    next();
  } else {

    switch (req.originalUrl) {
      case '/admin':
      case '/admin/':
        var to = '';
        break;

      default:
        var to = '/?to=' + encodeURIComponent(req.originalUrl.replace('/admin/', ''))
    }

    res.redirect('/login' + to);

  }

});

app.all('/admin*', function(req, res, next) {

  if (req.session.loggedIn || req.method == 'GET') {
    next();
  } else {
    res.send('Sorry, but I can\'t let you in.');
  }

});

app.use('/admin/assets', express.static('./dist'));

app.use(bodyParser.json());

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

app.use('/login', require('./routes/login'));
app.use('/uploads*', require('./routes/uploads'));

app.use('/admin', require('./routes/dashboard'));
app.use('/admin/pages', require('./routes/pages'));
app.use('/admin/media', require('./routes/media'));

app.listen(2000, function() {
  var port = this.address().port;
  console.log('Muffin is running at http://localhost:' + port + '/admin');
});
<|endoftext|>


<commit_before>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')({
    transports: ['websocket'],
});

//app.get('/', function(req, res){
//  res.sendFile(__dirname + '/index.html');
//	res.send(process.env.PORT);
//});
var roomList = [];
var playerList = [];
io.on('connection', function (socket)
{
    //socket.emit('newplayer');
    //socket.broadcast.emit('newplayer');
    var playerId = String(new Date().getTime());
    playerList.push(playerId);
    socket.emit('connected', {playerid: playerId});
    //socket.to('others').emit('newplayer');
//    socket.on('beep', function ()
//    {
//        socket.emit('boopeeeee');
//    });
    socket.on('createroom', function (msg)
    {
        var roomId = String(new Date().getTime());
        roomList.push(new room(roomId, msg.roomname, [msg.playerid]));
        socket.emit('roomid', {roomid: roomId});
    });

    socket.on('addme', function (msg)
    {
        var newPlayerId = String(new Date().getTime());
        socket.emit('playeradded', {playerid: newPlayerId});
        socket.broadcast.emit('newplayer', {playerid: newPlayerId});
        //socket.emit('roomlist', JSON.stringify(roomList));
    });
    socket.on('getrooms', function (msg)
    {
//        socket.emit('roomlist', JSON.stringify(roomList));
        socket.emit('roomlist', {roomlist: roomList});
    });
    socket.on('joinroom', function (msg)
    {
//        var roomId = String(new Date().getTime());
//        roomList.push(roomId);
//        socket.emit('roomid', {roomid: roomId});
        var roomListSize = roomList.length;
        for (var i = 0; i < roomListSize; i++) {
            if (roomList[i].roomId == msg.roomname) {
                if (!roomList[i].isPlayerHere(msg.playerid))
                {
                    roomList[i].userList.push(msg.playerid);
                    socket.broadcast.to(msg.roomid).emit('newplayer', {playerid: msg.playerid});
                    socket.emit('joined', {roomid: msg.roomname, otherplayers: roomList[i].getOtherPlayers(msg.playerid)});
                }
            }
        }
    });

    socket.on('position', function (msg)
    {
        var roomListSize = roomList.length;
        for (var i = 0; i < roomListSize; i++) {
            if (roomList[i].roomId == msg.roomid) {
                //socket.emit('joined');
                socket.broadcast.to(msg.roomid).emit('position', msg);
                //io.emit('position', msg);
            }
        }
    });
});
io.attach(process.env.PORT || 5000);
//http.listen(process.env.PORT || 5000);
class room {
    constructor(roomId, roomName, userList) {
        this.roomId = roomId;
        this.roomName = roomName;
        this.userList = userList;
    }
    isPlayerHere(playerid) {
        var playerListSize = this.userList.length;
        for (var i = 0; i < playerListSize; i++) {
            if (this.userList[i] == playerid) {
                return true;
            }
        }
        return false;
    }
    getOtherPlayers(playerid) {
        var playerListSize = this.userList.length;
        var playerList=[];
        for (var i = 0; i < playerListSize; i++) {
            if (userList[i] != playerid) {
                playerList.push(this.userList[i]);
            }
        }
        return playerList;
    }
}<commit_msg>dont act like i never tellya<commit_after>"use strict";
class room {
    constructor(roomId, roomName, userList) {
        this.roomId = roomId;
        this.roomName = roomName;
        this.userList = userList;
    }
    isPlayerHere(playerid) {
        var playerListSize = this.userList.length;
        for (var i = 0; i < playerListSize; i++) {
            if (this.userList[i] == playerid) {
                return true;
            }
        }
        return false;
    }
    getOtherPlayers(playerid) {
        var playerListSize = this.userList.length;
        var playerList=[];
        for (var i = 0; i < playerListSize; i++) {
            if (this.userList[i] != playerid) {
                playerList.push(this.userList[i]);
            }
        }
        return playerList;
    }
}

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')({
    transports: ['websocket'],
});

//app.get('/', function(req, res){
//  res.sendFile(__dirname + '/index.html');
//	res.send(process.env.PORT);
//});
var roomList = [];
var playerList = [];
io.on('connection', function (socket)
{
    //socket.emit('newplayer');
    //socket.broadcast.emit('newplayer');
    var playerId = String(new Date().getTime());
    playerList.push(playerId);
    socket.emit('connected', {playerid: playerId});
    //socket.to('others').emit('newplayer');
//    socket.on('beep', function ()
//    {
//        socket.emit('boopeeeee');
//    });
    socket.on('createroom', function (msg)
    {
        var roomId = String(new Date().getTime());
        roomList.push(new room(roomId, msg.roomname, [msg.playerid]));
        socket.emit('roomid', {roomid: roomId});
    });

    socket.on('addme', function (msg)
    {
        var newPlayerId = String(new Date().getTime());
        socket.emit('playeradded', {playerid: newPlayerId});
        socket.broadcast.emit('newplayer', {playerid: newPlayerId});
        //socket.emit('roomlist', JSON.stringify(roomList));
    });
    socket.on('getrooms', function (msg)
    {
//        socket.emit('roomlist', JSON.stringify(roomList));
        socket.emit('roomlist', {roomlist: roomList});
    });
    socket.on('joinroom', function (msg)
    {
        var roomListSize = roomList.length;
        for (var i = 0; i < roomListSize; i++) {
            if (roomList[i].roomId == msg.roomname) {
                if (!roomList[i].isPlayerHere(msg.playerid))
                {
                    roomList[i].userList.push(msg.playerid);
                    socket.broadcast.to(msg.roomid).emit('newplayer', {playerid: msg.playerid});
                    socket.emit('joined', {roomid: msg.roomname, otherplayers: roomList[i].getOtherPlayers(msg.playerid)});
                }
            }
        }
    });

    socket.on('position', function (msg)
    {
        var roomListSize = roomList.length;
        for (var i = 0; i < roomListSize; i++) {
            if (roomList[i].roomId == msg.roomid) {
                //socket.emit('joined');
                socket.broadcast.to(msg.roomid).emit('position', msg);
                //io.emit('position', msg);
            }
        }
    });
});
io.attach(process.env.PORT || 5000);
//http.listen(process.env.PORT || 5000);
<|endoftext|>


<commit_before>
/**
 * Slice reference.
 */

var slice = [].slice;

/**
 * Bind `obj` to `fn`.
 *
 * @param {Object} obj
 * @param {Function|String} fn or string
 * @return {Function}
 * @api public
 */

module.exports = function(obj, fn){
  if ('string' == typeof fn) fn = obj[fn];
  if ('function' != typeof fn) throw new Error('bind() requires a function');
  var args = [].slice.call(arguments, 2);
  return function(){
    return fn.apply(obj, args.concat(slice.call(arguments)));
  }
};
<commit_msg>use slice ref<commit_after>/**
 * Slice reference.
 */

var slice = [].slice;

/**
 * Bind `obj` to `fn`.
 *
 * @param {Object} obj
 * @param {Function|String} fn or string
 * @return {Function}
 * @api public
 */

module.exports = function(obj, fn){
  if ('string' == typeof fn) fn = obj[fn];
  if ('function' != typeof fn) throw new Error('bind() requires a function');
  var args = slice.call(arguments, 2);
  return function(){
    return fn.apply(obj, args.concat(slice.call(arguments)));
  }
};
<|endoftext|>


<commit_before>/**
 * Created by andrew.koroluk on 7/1/15.
 */
// Full list of configuration options available at:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
    controls: true,
    progress: true,
    history: true,
    center: true,

    transition: 'slide', // none/fade/slide/convex/concave/zoom

    multiplex: {
        secret: null, // Obtained from the socket.io server. Gives this (the master) control of the presentation
        id: '8b6cf67d22209131', // Obtained from socket.io server
        url: 'andrewkoroluk.com:1948' // Location of socket.io server
    },

    // Optional reveal.js plugins
    dependencies: [{
        src: 'lib/js/classList.js',
        condition: function() {
            return !document.body.classList;
        }
    }, {
        src: 'plugin/markdown/marked.js',
        condition: function() {
            return !!document.querySelector('[data-markdown]');
        }
    }, {
        src: 'plugin/markdown/markdown.js',
        condition: function() {
            return !!document.querySelector('[data-markdown]');
        }
    }, {
        src: 'plugin/highlight/highlight.js',
        async: true,
        condition: function() {
            return !!document.querySelector('pre code');
        },
        callback: function() {
            hljs.initHighlightingOnLoad();
        }
    }, {
        src: 'plugin/zoom-js/zoom.js',
        async: true
    }, {
        src: 'plugin/notes/notes.js',
        async: true
    }, {
        src: 'socket.io/socket.io.js',
        async: true
    }, {
        src: '//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js',
        async: true
    }, {
        src: 'plugin/multiplex/client.js',
        async: true
    }, {
        src: 'plugin/notes-server/client.js',
        async: true
    }]
});
<commit_msg>feat(server): update id<commit_after>/**
 * Created by andrew.koroluk on 7/1/15.
 */
// Full list of configuration options available at:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
    controls: true,
    progress: true,
    history: true,
    center: true,

    transition: 'slide', // none/fade/slide/convex/concave/zoom

    multiplex: {
        secret: null, // Obtained from the socket.io server. Gives this (the master) control of the presentation
        id: '664093dc5d038c07', // Obtained from socket.io server
        url: 'andrewkoroluk.com:1948' // Location of socket.io server
    },

    // Optional reveal.js plugins
    dependencies: [{
        src: 'lib/js/classList.js',
        condition: function() {
            return !document.body.classList;
        }
    }, {
        src: 'plugin/markdown/marked.js',
        condition: function() {
            return !!document.querySelector('[data-markdown]');
        }
    }, {
        src: 'plugin/markdown/markdown.js',
        condition: function() {
            return !!document.querySelector('[data-markdown]');
        }
    }, {
        src: 'plugin/highlight/highlight.js',
        async: true,
        condition: function() {
            return !!document.querySelector('pre code');
        },
        callback: function() {
            hljs.initHighlightingOnLoad();
        }
    }, {
        src: 'plugin/zoom-js/zoom.js',
        async: true
    }, {
        src: 'plugin/notes/notes.js',
        async: true
    }, {
        src: 'socket.io/socket.io.js',
        async: true
    }, {
        src: '//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js',
        async: true
    }, {
        src: 'plugin/multiplex/client.js',
        async: true
    }, {
        src: 'plugin/notes-server/client.js',
        async: true
    }]
});
<|endoftext|>


<commit_before>var EventEmitter = require('emitter');

function inherits(Child, Parent) {
	Child.prototype = Object.create(Parent.prototype, {
		constructor: { value: Child, enumerable: false, writable: true, configurable: true }
	});
}

var defaultTests = {
	bool: {
		test: function (value) { return value.toLowerCase() === 'true' || value.toLowerCase() === 'false'; },
		parse: function (value) { return value.toLowerCase() === 'true'; }
	},
	date: {
		test: function (value) { return !isNaN(new Date(value).getDate()); },
		parse: function (value) { return new Date(value); }
	},
	number: {
		test: function (value) { return !isNaN(value) && parseFloat(value).toString() === value.toString(); },
		parse: function (value) { return parseFloat(value); }
	},
	string: {
		test: function (value) { return typeof value === 'string'; },
		parse: function (value) { return value; }
	}
};

var CSVParser = function (config) {
	this.loadData = config.loadData;
	this.saveData = config.saveData;
	this.csvTarget = config.target;
	this.options = config.options || {};

	this.headers = [];
	this.values = [];
	this.parsed = {};

	this.allowNull = true;
	this.isSafe = true;

	this.tests = defaultTests;

	this.createButtons();
	this.createDropElement();
	this.createResultElement();
	this.createDataDisplay();

	this.rules = {};

	if (config.rules) {
		this.setRules(config.rules);
	}

	if (config.tests) {
		for (var id in config.tests) {
			this.tests[id] = config.tests[id];
		}
	}
};

inherits(CSVParser, EventEmitter);

CSVParser.prototype.getRows = function (file) {
	var universalNewline = /\r\n|\r|\n/g;
	var rows = (file + '\n').split(universalNewline);
	var csvRows = [];
	var sep = ",";

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

		for (var f = rows[i].split(sep), x = f.length - 1, tl; x >= 0; x--) {

			if (f[x].replace(/"\s+$/, '"').charAt(f[x].length - 1) === '"') {

				if ((tl = f[x].replace(/^\s+"/, '"')).length > 1 && tl.charAt(0) === '"') {

					f[x] = f[x].replace(/^\s*"|"\s*$/g, '').replace(/""/g, '"');

				} else if (x) {

					f.splice(x - 1, 2, [f[x - 1], f[x]].join(sep));

				} else {

					f = f.shift().split(sep).concat(f);
				}

			} else {

				f[x].replace(/""/g, '"');

			}

		}

		csvRows.push(f);

	}

	return csvRows;
};

CSVParser.prototype.setRules = function (rules) {
	for (var ruleName in rules) {
		var rule = rules[ruleName];

		if (typeof rule === "string") {
			rule = { type: rule };
		}

		this.rules[ruleName] = rule;
	}
};

CSVParser.prototype.setUniques = function (ids) {
	this.uniques = Array.isArray(ids) ? ids : [ ids ];
};

CSVParser.prototype.parse = function (key, value) {

	//Check to see if rules exists, and that there is a rule for the specified key.
	//If not, there are no (valid) rules and should thus return true.

	if (this.rules[key]) {
		// empty values
		if (!value.trim()) {
			// we use hasOwnProperty so that the user can use "undefined" as an empty value
			if (this.rules[key].hasOwnProperty('empty')) {
				return this.rules[key].empty;
			}

			if (this.options.hasOwnProperty('empty')) {
				return this.options.empty;
			}
		}

		var type = this.rules[key].type;
		value = this.tests[type].parse.call(this, value);

		// apply post parsing transformation
		if (this.rules[key].transform) {
			value = this.rules[key].transform.call(this, key, value);
		} else if (this.options.transform) {
			value = this.options.transform.call(this, key, value);
		}

	} else {
		if (this.options.hasOwnProperty('empty')) {
			return this.options.empty;
		}

		if (this.options.transform) {
			value = this.options.transform.call(this, key, value);
		}
	}

	return value;
};

CSVParser.prototype.test = function (key, value) {

	//Always return true if rules are not defined.
	if (this.rules === null) {
		return value;
	}

	//Return true if null is allowed.
	if (this.allowNull === true && (value === 'null' || value === null)) {
		return true;
	}

	if (this.rules[key] === undefined) {
		return false;
	}

	var type = this.rules[key].type;

	return this.tests[type].test.call(this, value);
};

CSVParser.prototype.parseCSV = function (file) {
	this.isSafe = true;
	this.headers = [];
	this.values = [];
	this.parsed = {};

	var that = this;

	var reader = new FileReader();

	reader.onload = function (file) {
		file = file.target.result;

		var rows = that.getRows(file);
		var row = rows[0];

		for (var j = 0; j < row.length; j += 1) {
			that.headers.push(row[j]);
		}

		var parsedObject = {};

		for (var i = 1; i < rows.length; i += 1) {
			row = rows[i];

			var id = row[0];
			parsedObject[id] = {};

			for (j = 0; j < row.length; j += 1) {
				parsedObject[id][that.headers[j]] = that.parse(that.headers[j], row[j]);
			}

			that.values.push(row);
		}

		that.dataDisplay.hide();
		that.parsed = parsedObject;
		that.emit('parsed', parsedObject);
	};

	reader.readAsText(file);
};

function removeAllChildren(ele) {
	while (ele.childNodes.length) {
		ele.removeChild(ele.childNodes[0]);
	}
}

function renderResults(that) {
	that.saveButton.show();
	that.cancelButton.show();
	that.dropElement.hide();

	removeAllChildren(that.resultElement);

	var header = document.createElement('TR');
	header.className = 'resultHeader';

	for (var i = 0; i < that.headers.length; i += 1) {
		var key = document.createElement('TH');
		key.className = 'resultKey';
		key.textContent = that.headers[i];
		header.appendChild(key);
	}

	that.resultElement.appendChild(header);

	var uniqueIds = {};

	for (var j = 0; j < that.values.length; j += 1) {
		var row = document.createElement('TR');
		row.className = 'resultRow';

		var valueRow = that.values[j];
		var uniqueId = valueRow[0];
		var parsedRow = that.parsed[uniqueId];

		uniqueIds[uniqueId] = uniqueIds.hasOwnProperty(uniqueId) ? uniqueIds[uniqueId] + 1 : 1;

		for (i = 0; i < valueRow.length; i += 1) {
			var value = document.createElement('TD');
			var classes = 'rowValue valid';

			if (!that.test(that.headers[i], parsedRow[that.headers[i]]) || uniqueIds[uniqueId] > 1) {
				classes = 'rowValue invalid';
				that.isSafe = false;
			}

			value.className = classes;
			value.textContent = parsedRow[that.headers[i]];

			row.appendChild(value);
		}

		that.resultElement.appendChild(row);
	}

	that.resultElement.show();
}

CSVParser.prototype.createResultElement = function () {
	var resultElement = this.resultElement = document.createElement('TABLE');
	resultElement.className = 'csvResults';

	resultElement.show = function () {
		resultElement.style.display = '';
	};

	resultElement.hide = function () {
		resultElement.style.display = 'none';
	};

	this.csvTarget.appendChild(resultElement);
};

CSVParser.prototype.createDropElement = function () {
	var that = this;

	var dropElement = this.dropElement = document.createElement('DIV');
	dropElement.className = 'dropElement';
	dropElement.textContent = 'Drop CSV file here';

	dropElement.addEventListener('dragover', function (e) {
		e.stopPropagation();
		e.preventDefault();
	});

	dropElement.addEventListener('drop', function (e) {
		var files = e.dataTransfer.files;

		e.stopPropagation();
		e.preventDefault();

		if (files.length) {
			if (files[0].type !== 'text/csv') {
				return alert('That file is not a csv.');
			}

			that.once('parsed', function () {
				renderResults(that);
			});

			that.parseCSV(files[0]);
		}
	}, false);

	dropElement.hide = function () {
		dropElement.style.display = 'none';
	}

	dropElement.show = function () {
		dropElement.style.display = '';
	}

	this.csvTarget.appendChild(dropElement);
};

function createButton(value) {
	var button = document.createElement('INPUT');
	button.type = 'button';
	button.value = value;

	button.show = function () {
		button.style.display = '';
	};

	button.hide = function () {
		button.style.display = 'none';
	};

	return button;
}

CSVParser.prototype.createButtons = function () {
	var that = this;

	var saveButton = this.saveButton = createButton('Save');
	var cancelButton = this.cancelButton = createButton('Cancel');

	function saveClicked() {
		if (!that.isSafe && !confirm('There were errors with your data, are you sure you want to save?')) {
			return;
		}

		saveButton.hide();
		cancelButton.hide();
		that.resultElement.hide();
		that.dropElement.show();
		that.dataDisplay.show();

		that.saveData(that.parsed, function (error) {
			if (error) {
				console.error(error);
			}

			that.dataDisplay.refresh();
		});
	}

	function cancelClicked() {
		saveButton.hide();
		cancelButton.hide();
		that.resultElement.hide();
		that.dropElement.show();
		that.dataDisplay.show();
	}

	saveButton.addEventListener('click', saveClicked, false);
	cancelButton.addEventListener('click', cancelClicked, false);

	this.csvTarget.appendChild(saveButton);
	this.csvTarget.appendChild(cancelButton);

	saveButton.hide();
	cancelButton.hide();
};

function JSONHTMLify (data, target) {
	if (typeof data !== 'object') {
		var elm = document.createElement('SPAN');
		elm.textContent = data.toString();
		elm.className = 'value';

		target.appendChild(elm);
		return;
	}

	if (data === null) {
		var elm = document.createElement('SPAN');
		elm.textContent = 'null'
		elm.className = 'value null';

		target.appendChild(elm);
		return;
	}

	var keys = Object.keys(data);
	for (var i = 0; i < keys.length; i += 1) {
		var prop = keys[i];

		var div = document.createElement('DIV');

		var elm = document.createElement( target.className === 'key' ? 'SPAN' : 'H3');
		elm.textContent = prop + (target.className === 'key' ? ': ' : '');

		div.appendChild(elm);
		div.className = 'key';

		target.appendChild(div);

		JSONHTMLify(data[prop], div);
	}
}

CSVParser.prototype.createDataDisplay = function () {
	var that = this;

	var dataDisplay = this.dataDisplay = document.createElement('DIV');

	var data = {};

	dataDisplay.hide = function () {
		dataDisplay.style.display = 'none';
	};

	dataDisplay.show = function () {
		dataDisplay.style.display = '';
	};

	dataDisplay.update = function (newData) {
		data = newData;
		removeAllChildren(dataDisplay);
		dataDisplay.render();
	};

	dataDisplay.render = function () {
		JSONHTMLify(data, dataDisplay);
	};

	dataDisplay.refresh = function () {
		that.loadData(function (error, newData) {
			if (error) {
				console.error(error);
			}

			dataDisplay.update(newData);
		});
	}

	dataDisplay.refresh();

	this.csvTarget.appendChild(dataDisplay);
};

module.exports = CSVParser;
<commit_msg>Cleanup.<commit_after>var EventEmitter = require('emitter');

function inherits(Child, Parent) {
	Child.prototype = Object.create(Parent.prototype, {
		constructor: { value: Child, enumerable: false, writable: true, configurable: true }
	});
}

var defaultTests = {
	bool: {
		test: function (value) { return value.toLowerCase() === 'true' || value.toLowerCase() === 'false'; },
		parse: function (value) { return value.toLowerCase() === 'true'; }
	},
	date: {
		test: function (value) { return !isNaN(new Date(value).getDate()); },
		parse: function (value) { return new Date(value); }
	},
	number: {
		test: function (value) { return !isNaN(value) && parseFloat(value).toString() === value.toString(); },
		parse: function (value) { return parseFloat(value); }
	},
	string: {
		test: function (value) { return typeof value === 'string'; },
		parse: function (value) { return value; }
	}
};

var CSVParser = function (config) {
	this.loadData = config.loadData;
	this.saveData = config.saveData;
	this.csvTarget = config.target;
	this.options = config.options || {};

	this.headers = [];
	this.values = [];
	this.parsed = {};

	this.allowNull = true;
	this.isSafe = true;

	this.tests = defaultTests;

	this.createButtons();
	this.createDropElement();
	this.createResultElement();
	this.createDataDisplay();

	this.rules = {};

	if (config.rules) {
		this.setRules(config.rules);
	}

	if (config.tests) {
		for (var id in config.tests) {
			this.tests[id] = config.tests[id];
		}
	}
};

inherits(CSVParser, EventEmitter);

CSVParser.prototype.getRows = function (file) {
	var universalNewline = /\r\n|\r|\n/g;
	var rows = (file + '\n').split(universalNewline);
	var csvRows = [];
	var sep = ",";

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

		for (var f = rows[i].split(sep), x = f.length - 1, tl; x >= 0; x--) {

			if (f[x].replace(/"\s+$/, '"').charAt(f[x].length - 1) === '"') {

				if ((tl = f[x].replace(/^\s+"/, '"')).length > 1 && tl.charAt(0) === '"') {

					f[x] = f[x].replace(/^\s*"|"\s*$/g, '').replace(/""/g, '"');

				} else if (x) {

					f.splice(x - 1, 2, [f[x - 1], f[x]].join(sep));

				} else {

					f = f.shift().split(sep).concat(f);
				}

			} else {

				f[x].replace(/""/g, '"');

			}

		}

		csvRows.push(f);

	}

	return csvRows;
};

CSVParser.prototype.setRules = function (rules) {
	for (var ruleName in rules) {
		var rule = rules[ruleName];

		if (typeof rule === "string") {
			rule = { type: rule };
		}

		this.rules[ruleName] = rule;
	}
};

CSVParser.prototype.setUniques = function (ids) {
	this.uniques = Array.isArray(ids) ? ids : [ ids ];
};

CSVParser.prototype.parse = function (key, value) {

	//Check to see if rules exists, and that there is a rule for the specified key.
	//If not, there are no (valid) rules and should thus return true.

	if (this.rules[key]) {
		// empty values
		if (!value.trim()) {
			// we use hasOwnProperty so that the user can use "undefined" as an empty value
			if (this.rules[key].hasOwnProperty('empty')) {
				return this.rules[key].empty;
			}

			if (this.options.hasOwnProperty('empty')) {
				return this.options.empty;
			}
		}

		var type = this.rules[key].type;
		value = this.tests[type].parse.call(this, value);

		// apply post parsing transformation
		if (this.rules[key].transform) {
			value = this.rules[key].transform.call(this, key, value);
		} else if (this.options.transform) {
			value = this.options.transform.call(this, key, value);
		}

	} else {
		if (this.options.hasOwnProperty('empty')) {
			return this.options.empty;
		}

		if (this.options.transform) {
			value = this.options.transform.call(this, key, value);
		}
	}

	return value;
};

CSVParser.prototype.test = function (key, value) {

	//Always return true if rules are not defined.
	if (this.rules === null) {
		return value;
	}

	//Return true if null is allowed.
	if (this.allowNull === true && (value === 'null' || value === null)) {
		return true;
	}

	if (this.rules[key] === undefined) {
		return false;
	}

	var type = this.rules[key].type;

	return this.tests[type].test.call(this, value);
};

CSVParser.prototype.parseCSV = function (file) {
	this.isSafe = true;
	this.headers = [];
	this.values = [];
	this.parsed = {};

	var that = this;

	var reader = new FileReader();

	reader.onload = function (file) {
		file = file.target.result;

		var rows = that.getRows(file);
		var row = rows[0];

		for (var j = 0; j < row.length; j += 1) {
			that.headers.push(row[j]);
		}

		var parsedObject = {};

		for (var i = 1; i < rows.length; i += 1) {
			row = rows[i];

			var id = row[0];
			parsedObject[id] = {};

			for (j = 0; j < row.length; j += 1) {
				parsedObject[id][that.headers[j]] = that.parse(that.headers[j], row[j]);
			}

			that.values.push(row);
		}

		that.dataDisplay.hide();
		that.parsed = parsedObject;
		that.emit('parsed', parsedObject);
	};

	reader.readAsText(file);
};

function removeAllChildren(ele) {
	while (ele.childNodes.length) {
		ele.removeChild(ele.childNodes[0]);
	}
}

function renderResults(that) {
	that.saveButton.show();
	that.cancelButton.show();
	that.dropElement.hide();

	removeAllChildren(that.resultElement);

	var header = document.createElement('TR');
	header.className = 'resultHeader';

	for (var i = 0; i < that.headers.length; i += 1) {
		var key = document.createElement('TH');
		key.className = 'resultKey';
		key.textContent = that.headers[i];
		header.appendChild(key);
	}

	that.resultElement.appendChild(header);

	var uniqueIds = {};

	for (var j = 0; j < that.values.length; j += 1) {
		var row = document.createElement('TR');
		row.className = 'resultRow';

		var valueRow = that.values[j];
		var uniqueId = valueRow[0];
		var parsedRow = that.parsed[uniqueId];

		uniqueIds[uniqueId] = uniqueIds.hasOwnProperty(uniqueId) ? uniqueIds[uniqueId] + 1 : 1;

		for (i = 0; i < valueRow.length; i += 1) {
			var value = document.createElement('TD');
			var classes = 'rowValue valid';

			if (!that.test(that.headers[i], parsedRow[that.headers[i]]) || uniqueIds[uniqueId] > 1) {
				classes = 'rowValue invalid';
				that.isSafe = false;
			}

			value.className = classes;
			value.textContent = parsedRow[that.headers[i]];

			row.appendChild(value);
		}

		that.resultElement.appendChild(row);
	}

	that.resultElement.show();
}

CSVParser.prototype.createResultElement = function () {
	var resultElement = this.resultElement = document.createElement('TABLE');
	resultElement.className = 'csvResults';

	resultElement.show = function () {
		resultElement.style.display = '';
	};

	resultElement.hide = function () {
		resultElement.style.display = 'none';
	};

	this.csvTarget.appendChild(resultElement);
};

CSVParser.prototype.createDropElement = function () {
	var that = this;

	var dropElement = this.dropElement = document.createElement('DIV');
	dropElement.className = 'dropElement';
	dropElement.textContent = 'Drop CSV file here';

	dropElement.addEventListener('dragover', function (e) {
		e.stopPropagation();
		e.preventDefault();
	});

	dropElement.addEventListener('drop', function (e) {
		var files = e.dataTransfer.files;

		e.stopPropagation();
		e.preventDefault();

		if (files.length) {
			if (files[0].type !== 'text/csv') {
				return alert('That file is not a csv.');
			}

			that.once('parsed', function () {
				renderResults(that);
			});

			that.parseCSV(files[0]);
		}
	}, false);

	dropElement.hide = function () {
		dropElement.style.display = 'none';
	};

	dropElement.show = function () {
		dropElement.style.display = '';
	};

	this.csvTarget.appendChild(dropElement);
};

function createButton(value) {
	var button = document.createElement('INPUT');
	button.type = 'button';
	button.value = value;

	button.show = function () {
		button.style.display = '';
	};

	button.hide = function () {
		button.style.display = 'none';
	};

	return button;
}

CSVParser.prototype.createButtons = function () {
	var that = this;

	var saveButton = this.saveButton = createButton('Save');
	var cancelButton = this.cancelButton = createButton('Cancel');

	function saveClicked() {
		if (!that.isSafe && !confirm('There were errors with your data, are you sure you want to save?')) {
			return;
		}

		saveButton.hide();
		cancelButton.hide();
		that.resultElement.hide();
		that.dropElement.show();
		that.dataDisplay.show();

		that.saveData(that.parsed, function (error) {
			if (error) {
				console.error(error);
			}

			that.dataDisplay.refresh();
		});
	}

	function cancelClicked() {
		saveButton.hide();
		cancelButton.hide();
		that.resultElement.hide();
		that.dropElement.show();
		that.dataDisplay.show();
	}

	saveButton.addEventListener('click', saveClicked, false);
	cancelButton.addEventListener('click', cancelClicked, false);

	this.csvTarget.appendChild(saveButton);
	this.csvTarget.appendChild(cancelButton);

	saveButton.hide();
	cancelButton.hide();
};

function JSONHTMLify (data, target) {
	var elm;

	if (typeof data !== 'object') {
		elm = document.createElement('SPAN');
		elm.textContent = data.toString();
		elm.className = 'value';

		target.appendChild(elm);
		return;
	}

	if (data === null) {
		elm = document.createElement('SPAN');
		elm.textContent = 'null';
		elm.className = 'value null';

		target.appendChild(elm);
		return;
	}

	var keys = Object.keys(data);
	for (var i = 0; i < keys.length; i += 1) {
		var prop = keys[i];

		var div = document.createElement('DIV');

		elm = document.createElement( target.className === 'key' ? 'SPAN' : 'H3');
		elm.textContent = prop + (target.className === 'key' ? ': ' : '');

		div.appendChild(elm);
		div.className = 'key';

		target.appendChild(div);

		JSONHTMLify(data[prop], div);
	}
}

CSVParser.prototype.createDataDisplay = function () {
	var that = this;

	var dataDisplay = this.dataDisplay = document.createElement('DIV');

	var data = {};

	dataDisplay.hide = function () {
		dataDisplay.style.display = 'none';
	};

	dataDisplay.show = function () {
		dataDisplay.style.display = '';
	};

	dataDisplay.update = function (newData) {
		data = newData;
		removeAllChildren(dataDisplay);
		dataDisplay.render();
	};

	dataDisplay.render = function () {
		JSONHTMLify(data, dataDisplay);
	};

	dataDisplay.refresh = function () {
		that.loadData(function (error, newData) {
			if (error) {
				console.error(error);
			}

			dataDisplay.update(newData);
		});
	};

	dataDisplay.refresh();

	this.csvTarget.appendChild(dataDisplay);
};

module.exports = CSVParser;
<|endoftext|>


<commit_before>'use strict';

const path = require('path')
    , fs = require('fs')
    , env = process.env
    , cp = require('child_process')

const HOST_NON_EXISTENT = /host does not exist/i
    , ALREADY_RUNNING = /already running/i

class Machine {
  static options(opts) {
    if (typeof opts === 'string') return { name: opts }
    else return opts || {}
  }

  static command(args, done) {
    cp.execFile('docker-machine', [].concat(args), {
      cwd: env.DOCKER_TOOLBOX_INSTALL_PATH || '.',
      encoding: 'utf8'
    }, done)
  }

  constructor(opts) {
    opts = Machine.options(opts)
    this.name = opts.name || env.DOCKER_MACHINE_NAME || 'default'
  }

  status(done) {
    this.command(['status', this.name], (err, stdout) => {
      if (err) done(err)
      else done(null, stdout.trim().toLowerCase())
    })
  }

  isRunning(done) {
    this.status((err, status) => {
      done(err, status === 'running')
    })
  }

  start(done) {
    this.command(['start', this.name], (err) => {
      if (HOST_NON_EXISTENT.test(err)) {
        done(new Error(`Docker host "${this.name}" does not exist`))
      } else if (ALREADY_RUNNING.test(err)) {
        done()
      } else {
        done(err)
      }
    })
  }

  env(opts, done) {
    if (typeof opts === 'function') done = opts, opts = {}

    const args = ['env']

    if (opts.json) args.push('--shell', 'bash')
    else if (opts.shell) args.push('--shell', opts.shell)

    args.push(this.name)

    this.command(args, function (err, stdout) {
      if (err) return done(err)
      if (!opts.json) return done(null, stdout.trim())

      const res = {}

      stdout.split(/\n+/).forEach(line => {
        const m = /^export (.+)="([^"]+)/i.exec(line)
        if (m) res[m[1]] = m[2]
      })

      done(null, res)
    })
  }

  ssh(cmd, done) {
    if (Array.isArray(cmd)) cmd = cmd.join(' ')
    this.command(['ssh', this.name, cmd], done)
  }
}

module.exports = Machine
<commit_msg>refactor: make all methods static<commit_after>'use strict';

const path = require('path')
    , fs = require('fs')
    , env = process.env
    , cp = require('child_process')

const HOST_NON_EXISTENT = /host does not exist/i
    , ALREADY_RUNNING = /already running/i

class Machine {
  static options(opts) {
    if (typeof opts === 'string') return { name: opts }
    else return opts || {}
  }

  static command(args, done) {
    cp.execFile('docker-machine', [].concat(args), {
      cwd: env.DOCKER_TOOLBOX_INSTALL_PATH || '.',
      encoding: 'utf8'
    }, done)
  }

  constructor(opts) {
    opts = Machine.options(opts)
    this.name = opts.name || env.DOCKER_MACHINE_NAME || 'default'
  }

  static status(name, done) {
    Machine.command(['status', name], (err, stdout) => {
      if (err) done(err)
      else done(null, stdout.trim().toLowerCase())
    })
  }

  static isRunning(name, done) {
    Machine.status(name, (err, status) => {
      done(err, status === 'running')
    })
  }

  static start(name, done) {
    Machine.command(['start', name], (err) => {
      if (HOST_NON_EXISTENT.test(err)) {
        done(new Error(`Docker host "${name}" does not exist`))
      } else if (ALREADY_RUNNING.test(err)) {
        done()
      } else {
        done(err)
      }
    })
  }

  static env(name, opts, done) {
    if (typeof opts === 'function') done = opts, opts = {}

    const args = ['env']

    if (opts.json) args.push('--shell', 'bash')
    else if (opts.shell) args.push('--shell', opts.shell)

    args.push(name)

    Machine.command(args, function (err, stdout) {
      if (err) return done(err)
      if (!opts.json) return done(null, stdout.trim())

      const res = {}

      stdout.split(/\n+/).forEach(line => {
        const m = /^export (.+)="([^"]+)/i.exec(line)
        if (m) res[m[1]] = m[2]
      })

      done(null, res)
    })
  }

  static ssh(name, cmd, done) {
    if (Array.isArray(cmd)) cmd = cmd.join(' ')
    Machine.command(['ssh', name, cmd], done)
  }
}

;['status', 'isRunning', 'start', 'env', 'ssh'].forEach(method => {
  Machine.prototype[method] = function () {
    const args = Array.from(arguments)
    args.unshift(this.name)
    Machine[method].apply(null, args)
  }
})

module.exports = Machine
<|endoftext|>


<commit_before>//
// transloadit-api
// ===============
//
// A Transloadit API.
//
'use strict';

var Signature = require('./lib/signature');
var Assemblies = require('./lib/assemblies');
var Notifications = require('./lib/notifications');
var uri = {
  base: 'http://api2.transloadit.com',
  assemblies: '/assemblies',
  notifications: '/assembly_notifications'
};

module.exports = function (opts) {
  return {
    signature: new Signature(opts),
    assembly: new Assemblies(opts, uri),
    notification: new Notifications(opts, uri)
  };
};

module.exports.signature = module.exports.Signature = function (opts) {
  return new Signature(opts);
};

module.exports.assembly = module.exports.Assembly = function (opts) {
  return new Assemblies(opts, uri);
};

module.exports.notification = module.exports.Notification = function (opts) {
  return new Notifications(opts, uri);
};
<commit_msg>index: loading templates<commit_after>//
// transloadit-api
// ===============
//
// A Transloadit API.
//
'use strict';

var Signature = require('./lib/signature');
var Assemblies = require('./lib/assemblies');
var Notifications = require('./lib/notifications');
var Templates = require('./lib/templates');
var uri = {
  base: 'http://api2.transloadit.com',
  assemblies: '/assemblies',
  notifications: '/assembly_notifications',
  templates: '/templates'
};

module.exports = function (opts) {
  return {
    signature: new Signature(opts),
    assembly: new Assemblies(opts, uri),
    notification: new Notifications(opts, uri),
    template: new Templates(opts, uri);
  };
};

module.exports.signature = module.exports.Signature = function (opts) {
  return new Signature(opts);
};

module.exports.assembly = module.exports.Assembly = function (opts) {
  return new Assemblies(opts, uri);
};

module.exports.notification = module.exports.Notification = function (opts) {
  return new Notifications(opts, uri);
};

module.exports.template = module.exports.Template = function (opts) {
  return new Templates(opts, uri);
};
<|endoftext|>


<commit_before>global.async = require('asyncawait/async');
global.await = require('asyncawait/await');

const express = require('express');

/*
|* dp for Node
|*
|* @param {Object} [options] {
|         app: Object, Express App.
|         apppath: String, Application Absolute Path [Required]
|         controllerPath: String, View Path, Default is 'controller'
|         viewPath: String, View Path, Default is 'view'
|         port: Int, Binding port, If specified, will bind automatically.
|         debug: Boolean, Debug Mode, Default is false.
|         compression: Boolean, Compression, Default is true.
|         enhanceSecurity: Boolean, Security(Helmet), Default is true.
|         minifyRemoveLineBreakWhitespace: Boolean, Whether if remove line break whitespace or not, Default is true.
|         requestSizeLimit: Numeric, Limit size of the request.
|         error: Function, Error Handler.
|         errorLogging: Boolean, Error Logging enabled, Default is true.
|         logging: Boolean, Logging enabled, Default is false.
|         static: [String], Static file paths.
|         redirectNakedToWWW: Boolean, Whether redirect naked domain to www  or not, Default is false.
|         databaseDsn: [Object], Pre-defined database dsn key as `key`, Default is empty.
|         mode: String, Supported values are `web` or `job`, Default is `web`.
|         session: {
|             driver: String, ENUM('redis'), Session Driver, Default is undefined, disabled.
|             secret: String, Session Secret, Default is dp provided value.
|             ttl: Integer, Time to alive for each session key-value, Default is 3600*24*30
|             volatility: Boolean, Whether if use session cookie or not, Default is false.
|             connection: Object, Options for Driver, Default is empty object({}).
|         }
|         cookie: {
|             secret: String, Cookie Secret, Default is dp provided value.
|             ttl: Integer, Time to alive for each cookie key-value, Default is 3600*24*30
|             volatility: Boolean, Whether if use session cookie or not, Default is false.
|         }
|     }
|*
*/
module.exports = (options) => {
  var app = options ? options.app : null;
  var config = {};

  var defaultVal = (val, defaultVal) => {
    if (val === undefined) {
      return defaultVal;
    }

    return val;
  }

  config.mode = (options.mode || 'web').toLowerCase();
  config.debug = defaultVal(options.debug, false);

  config.cfg = {};
  config.cfg.apppath = options.apppath;
  config.cfg.controller = options.apppath + ('/controller' || options.controllerPath);
  config.cfg.view = options.apppath + ('/view' || options.viewPath);
  config.cfg.minifyRemoveLineBreakWhitespace = defaultVal(options.minifyRemoveLineBreakWhitespace, true);
  config.cfg.requestSizeLimit = options.requestSizeLimit || '0.5mb';
  config.cfg.errorLogging = defaultVal(options.errorLogging, true);

  var errorHandler = options.error || undefined;

  config.handler = {};
  config.handler.error = errorHandler;

  if (typeof config.handler.error === 'function') {
    config.handler.error = (controller, error, statusCode) => {
      return async (() => {
        return await (errorHandler(controller, error, statusCode));
      })();
    }
  }

  config.cfg.viewHelpers = options.viewHelpers || {};

  if (!app) {
    app = express();
  }

  config.app = app;

  if (options.logging) {
    app.use(require('morgan')('short', {}));
  }

  if (defaultVal(options.redirectNakedToWWW, false)) {
    app.use(require('express-naked-redirect')());
  }

  if (defaultVal(options.compression, true)) {
    app.use(require('compression')());
  }

  if (defaultVal(options.enhanceSecurity, true)) {
    app.use(require('helmet')());
  }

  if (defaultVal(options.cookieEnabled, true)) {
    app.use(require('cookie-parser')());
  }

  if (defaultVal(options.session, {})) {
    config.cfg.session = options.session || {};
    config.cfg.session.secret = config.cfg.session.secret || 'dR@9oNp0W@r~NoD2';
    config.cfg.session.volatility = defaultVal(config.cfg.session.volatility, false);
    config.cfg.session.ttl = config.cfg.session.ttl || 3600 * 24 * 30;
  }

  if (defaultVal(options.cookie, {})) {
    config.cfg.cookie = options.cookie || {};
    config.cfg.cookie.secret = config.cfg.cookie.secret || 'dR@9oNp0W@r~Co0K2';
    config.cfg.cookie.volatility = defaultVal(config.cfg.cookie.volatility, false);
    config.cfg.cookie.ttl = config.cfg.cookie.ttl || 3600 * 24 * 30;
  }

  if (defaultVal(options.databaseDsn, [])) {
    config.cfg.databaseDsn = options.databaseDsn;
  }

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

  if (options.static) {
    var paths = options.static;

    if (typeof(paths) != 'object') {
      paths = [paths]
    }

    paths.forEach((e) => {
      app.use(express.static(options.apppath + '/' + e))
    })
  }

  const listen = (port) => {
    if (options.logging) {
      console.log('Listening .. ' + port);
    }

    return app.listen(port);
  }

  if (options.port && config.mode !== 'job') {
    listen(options.port);
  }

  config.view = require('./lib/view')(config);
  config.router = require('./lib/router')(config);
  config.helper = require('./lib/helper')(config);
  config.model = require('./lib/model')(config);

  var dp = {
    app: app,
    listen: listen
  };

  // Assign config when test mode enabled.
  if (global.isTest) {
    dp.config = config;
  }

  // for Job mode.
  if (config.mode === 'job') {
    return require('./lib/job')(config);
  }

  return dp;
}

module.exports.Tester = require('./lib/tester');
<commit_msg>write error response when failed execute error handler.<commit_after>global.async = require('asyncawait/async');
global.await = require('asyncawait/await');

const express = require('express');

/*
|* dp for Node
|*
|* @param {Object} [options] {
|         app: Object, Express App.
|         apppath: String, Application Absolute Path [Required]
|         controllerPath: String, View Path, Default is 'controller'
|         viewPath: String, View Path, Default is 'view'
|         port: Int, Binding port, If specified, will bind automatically.
|         debug: Boolean, Debug Mode, Default is false.
|         compression: Boolean, Compression, Default is true.
|         enhanceSecurity: Boolean, Security(Helmet), Default is true.
|         minifyRemoveLineBreakWhitespace: Boolean, Whether if remove line break whitespace or not, Default is true.
|         requestSizeLimit: Numeric, Limit size of the request.
|         error: Function, Error Handler.
|         errorLogging: Boolean, Error Logging enabled, Default is true.
|         logging: Boolean, Logging enabled, Default is false.
|         static: [String], Static file paths.
|         redirectNakedToWWW: Boolean, Whether redirect naked domain to www  or not, Default is false.
|         databaseDsn: [Object], Pre-defined database dsn key as `key`, Default is empty.
|         mode: String, Supported values are `web` or `job`, Default is `web`.
|         session: {
|             driver: String, ENUM('redis'), Session Driver, Default is undefined, disabled.
|             secret: String, Session Secret, Default is dp provided value.
|             ttl: Integer, Time to alive for each session key-value, Default is 3600*24*30
|             volatility: Boolean, Whether if use session cookie or not, Default is false.
|             connection: Object, Options for Driver, Default is empty object({}).
|         }
|         cookie: {
|             secret: String, Cookie Secret, Default is dp provided value.
|             ttl: Integer, Time to alive for each cookie key-value, Default is 3600*24*30
|             volatility: Boolean, Whether if use session cookie or not, Default is false.
|         }
|     }
|*
*/
module.exports = (options) => {
  var app = options ? options.app : null;
  var config = {};

  var defaultVal = (val, defaultVal) => {
    if (val === undefined) {
      return defaultVal;
    }

    return val;
  }

  config.mode = (options.mode || 'web').toLowerCase();
  config.debug = defaultVal(options.debug, false);

  config.cfg = {};
  config.cfg.apppath = options.apppath;
  config.cfg.controller = options.apppath + ('/controller' || options.controllerPath);
  config.cfg.view = options.apppath + ('/view' || options.viewPath);
  config.cfg.minifyRemoveLineBreakWhitespace = defaultVal(options.minifyRemoveLineBreakWhitespace, true);
  config.cfg.requestSizeLimit = options.requestSizeLimit || '0.5mb';
  config.cfg.errorLogging = defaultVal(options.errorLogging, true);

  var errorHandler = options.error || undefined;

  config.handler = {};
  config.handler.error = errorHandler;

  if (typeof config.handler.error === 'function') {
    config.handler.error = (controller, error, statusCode) => {
      return async (() => {
        try {
          return await (errorHandler(controller, error, statusCode));
        }
        catch (e) {
          console.error(e);

          if (controller && controller.finisher) {
            controller.finisher.error('An error has occurred.');
          }

          return false;
        }
      })();
    }
  }

  config.cfg.viewHelpers = options.viewHelpers || {};

  if (!app) {
    app = express();
  }

  config.app = app;

  if (options.logging) {
    app.use(require('morgan')('short', {}));
  }

  if (defaultVal(options.redirectNakedToWWW, false)) {
    app.use(require('express-naked-redirect')());
  }

  if (defaultVal(options.compression, true)) {
    app.use(require('compression')());
  }

  if (defaultVal(options.enhanceSecurity, true)) {
    app.use(require('helmet')());
  }

  if (defaultVal(options.cookieEnabled, true)) {
    app.use(require('cookie-parser')());
  }

  if (defaultVal(options.session, {})) {
    config.cfg.session = options.session || {};
    config.cfg.session.secret = config.cfg.session.secret || 'dR@9oNp0W@r~NoD2';
    config.cfg.session.volatility = defaultVal(config.cfg.session.volatility, false);
    config.cfg.session.ttl = config.cfg.session.ttl || 3600 * 24 * 30;
  }

  if (defaultVal(options.cookie, {})) {
    config.cfg.cookie = options.cookie || {};
    config.cfg.cookie.secret = config.cfg.cookie.secret || 'dR@9oNp0W@r~Co0K2';
    config.cfg.cookie.volatility = defaultVal(config.cfg.cookie.volatility, false);
    config.cfg.cookie.ttl = config.cfg.cookie.ttl || 3600 * 24 * 30;
  }

  if (defaultVal(options.databaseDsn, [])) {
    config.cfg.databaseDsn = options.databaseDsn;
  }

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

  if (options.static) {
    var paths = options.static;

    if (typeof(paths) != 'object') {
      paths = [paths]
    }

    paths.forEach((e) => {
      app.use(express.static(options.apppath + '/' + e))
    })
  }

  const listen = (port) => {
    if (options.logging) {
      console.log('Listening .. ' + port);
    }

    return app.listen(port);
  }

  if (options.port && config.mode !== 'job') {
    listen(options.port);
  }

  config.view = require('./lib/view')(config);
  config.router = require('./lib/router')(config);
  config.helper = require('./lib/helper')(config);
  config.model = require('./lib/model')(config);

  var dp = {
    app: app,
    listen: listen
  };

  // Assign config when test mode enabled.
  if (global.isTest) {
    dp.config = config;
  }

  // for Job mode.
  if (config.mode === 'job') {
    return require('./lib/job')(config);
  }

  return dp;
}

module.exports.Tester = require('./lib/tester');
<|endoftext|>


<commit_before>
exports.name = "Pichaya";<commit_msg>add comment in line 2<commit_after>
exports.name = "Pichaya";	// This is my name.<|endoftext|>