<commit_before>var util = require('util');
var Flowshop = require('./flowshop');
var Helper = require('./helper');

// NEH algorithm by Nawaz, Enscore, Ham
function NEH() {
}
util.inherits(NEH, Flowshop);
exports.rpd = NEH.prototype.rpd;
exports.makespan = NEH.prototype.makespan;

// NEH heuristic
NEH.prototype.apply = function(data) {

    // Variables
    var pi, piB, sequence, value, minSequence, minValue;

    // Initialization
    pi = Helper.sort(data);
    piB = [Helper.get(pi, 1), Helper.get(pi, 2)];
    if(NEH.prototype.makespan(piB) > NEH.prototype.makespan(Helper.toggle(piB, 1, 2))) {
        piB = Helper.toggle(piB, 1, 2);
    }

    // Best insertion
    for(var i = 3; i <= pi.length; i++) {
        sequence = Helper.insertBefore(piB, 1, Helper.get(pi, i));
        value = NEH.prototype.makespan(sequence);
        minSequence = sequence;
        minValue = value;
        for(var j = 1; j <= piB.length; j++) {
            sequence = Helper.toggle(sequence, j, j + 1);
            value = NEH.prototype.makespan(sequence);
            if(value < minValue) {
                minSequence = sequence;
                minValue = value;
            }
        }
        piB = minSequence;
    }
    return piB;
};
exports.apply = NEH.prototype.apply;
<commit_msg>Added refactored NEH<commit_after>var util = require('util');
var Flowshop = require('./flowshop');
var Helper = require('./helper');

// NEH algorithm by Nawaz, Enscore, Ham
function NEH() {
}
util.inherits(NEH, Flowshop);
exports.rpd = NEH.prototype.rpd;
exports.makespan = NEH.prototype.makespan;

// NEH heuristic
NEH.prototype.apply = function(data) {

    // Variables
    var pi, piB, sequence, value, minSequence, minValue;

    // Initialization
    pi = Helper.sort(data);
    piB = [Helper.get(pi, 1), Helper.get(pi, 2)];
    if(NEH.prototype.makespan(piB) > NEH.prototype.makespan(Helper.toggle(piB, 1, 2))) {
        piB = Helper.toggle(piB, 1, 2);
    }

    // Best insertion
    for(var i = 3; i <= pi.length; i++) {
        sequence = Helper.insertBefore(piB, 1, Helper.get(pi, i));
        value = NEH.prototype.makespan(sequence);
        minSequence = sequence;
        minValue = value;
        for(var j = 1; j < sequence.length; j++) {
            sequence = Helper.toggle(sequence, j, j + 1);
            value = NEH.prototype.makespan(sequence);
            if(value < minValue) {
                minSequence = sequence;
                minValue = value;
            }
        }
        piB = minSequence;
    }
    return piB;
};
exports.apply = NEH.prototype.apply;
<|endoftext|>


<commit_before>
module.exports = function (str) {
  return str
  .split('\n')
  .filter(function (p) { return  /[0-9]+ seconds?/.test(p) })
  .map(getObjects);
}

function getObjects(p) {
  var entitiesRegex = /(^|\s|;|\.|,|:)(audio|sound|panorama|image|picture|text|videosphere|video|seconds|second|voiceover|chart|background|model)(\s|$|;|\.|,|:)/gi;
  var objects = [], obj;
  while((obj = entitiesRegex.exec(p)) !== null) {
    objects.push({ type: obj[2].trim(), index: obj.index });
  }

  return objects.map(function(obj, i){
    // for backwards words I'm going back to the previous obj and add the length
    var sp = i !== 0 ?
      p.substring(objects[i - 1].index + objects[i - 1].type.length, objects[i].index + objects[i].type.length + 1) :
      p.substring(0, objects[i].index + objects[i].type.length + 1);

    // special case for duration
    if(obj.type === 'seconds' || obj.type === 'second') {
      var match = sp.match(/[0-9]+ seconds?/)
      if(!match) return false;

      return {
        type: 'duration',
        value: parseInt(match[0].replace(/seconds?/, ''), 10)
      }
    } else if (obj.type === 'background') {
      var match = sp.match(/(#[a-fA-F0-9]{3,6}|\w+) background/i)
      return {
        type: 'background',
        color: match[0].replace(' background', '')
      }
    }

    sp = i === objects.length - 1 ? p.substring(obj.index) : p.substring(obj.index, objects[i+1].index + 1);

    var str = sp
    switch(obj.type) {
      case 'audio':
      case 'sound':
        return {
          type: 'audio',
          src: getUrl(str),
          position: getPosition(str)
        }
      case 'voiceover':
        return {
          type: 'voiceover',
          text: getQuote(str)
        };
      case 'chart':
        return {
          type: 'chart',
          src: getUrl(str),
          position: getPosition(str, 10, 10),
          rotation: getRotation(str),
          scale: getSize(str)
        };
      case 'panorama':
      return {
        type: 'panorama',
        src: getUrl(str)
      }
      case 'video':
      return {
        type: 'video',
        src: getUrl(str),
        position: getPosition(str),
        scale: getSize(str),
        rotation: getRotation(str)
      }
      case 'videosphere':
      return {
        type: 'videosphere',
        src: getUrl(str)
      }
      case 'image':
      case 'picture':
      return {
        type: 'image',
        src: getUrl(str),
        position: getPosition(str),
        scale: getSize(str),
        rotation: getRotation(str)
      }
      case 'text':
      var text = getQuote(str);
      return {
        type: 'text',
        text: text,
        position: getPosition(str, 14, text.length / 30),
        scale: getSize(str).map(function(el){ return el * 5; }),
        rotation: getRotation(str)
      }
      case 'model':
      return {
        type: 'model',
        src: getUrl(str),
        position: getPosition(str),
        scale: getSize(str),
        rotation: getRotation(str)
      }
    }
    return obj
  })
  .filter(function(obj) { return !!obj; });
}

function getUrl(str) {
  var match = str.match(/https?:\/\/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/)
  if(!match.length) return
  return match[0].toLowerCase()
}

function getQuote(str) {
  var match = str.match(/".*"/)
  if(!(match && match.length)) return
  return match[0].replace(/"/g, '')
}

function getPosition(str, width, height) {
  width = width || 0;
  height = height || 0;
  var match = str.match(/right|left|behind|front/i)
  return getAbsPos(match && match.length ? match[0] : 'front', width, height)
}

function getSize(str) {
  var match = str.match(/tiny|small|large|huge/i)
  return getAbsSize(match && match.length ? match[0] : 'normal')
}

function getAbsPos(str, width, height) {
  var xSize = -.5 * width;
  var ySize = -.5 * height;
  switch(str) {
    case 'left':
      return [-5, 1.5 + ySize, 5 - xSize]
    case 'right':
      return [5, 1.5 + ySize, 5 + xSize]
    case 'behind':
      return [-xSize, 1.5 + ySize, 8]
    case 'front':
      return [0 + xSize, 1.5 + ySize, 0]
  }
}

function getRotation(str) {
  var match = str.match(/right|left|behind|front/i);
  var pos = match && match.length ? match[0] : 'front';
  switch(pos) {
    case 'left':
      return [0, 90, 0]
    case 'right':
      return [0, -90, 0]
    case 'behind':
      return [0, 180, 0]
    case 'front':
      return [0, 0, 0]
    default:
      return [0, 0, 0]
  }
}

function getAbsSize(str) {
  switch(str) {
    case 'tiny':
      return [1/3, 1/3, 1/3]
    case 'small':
      return [1/2, 1/2, 1/2]
    case 'large':
      return [2, 2, 2]
    case 'huge':
      return [3, 3, 3]
    default:
      return [1, 1, 1]
  }
}
<commit_msg>Emojiland<commit_after>
/**
 * Module constants
 */

var ENTITIES_REGEX = /(^|\s|;|\.|,|:)(audio|sound|🔊|panorama|🌅|image|picture|text|📝|videosphere|🎥|video|seconds|second|⏲|voiceover|📢|chart|📊|background|model)(\s|$|;|\.|,|:)/gi;
var LOCATION_REGEX = /right|left|behind|front/i;
var SIZE_REGEX = /tiny|small|large|huge/i;

module.exports = function (str) {
  return str
  .split('\n')
  .filter(function (p) { return  /[0-9]+ (⏲|seconds?)/.test(p) })
  .map(getObjects);
}

function getObjects(p) {
  var entities = [], entity;

  // Iterate over the paragraph and extract entities
  while((entity = ENTITIES_REGEX.exec(p)) !== null) {
    entities.push({ type: entity[2].trim(), index: entity.index });
  }

  // Extract attributes for each entity
  return entities.map(function(entity, i){

    // for backwards words I'm going back to the previous entity and add the length
    var sp = i !== 0 ?
      p.substring(entities[i - 1].index + entities[i - 1].type.length, entities[i].index + entities[i].type.length + 1) :
      p.substring(0, entities[i].index + entities[i].type.length + 1);

    // special case for duration
    if(entity.type === 'seconds' || entity.type === 'second' || entity.type === '⏲') {
      var match = sp.match(/[0-9]+ (⏲|seconds?)/)
      if(!match) return false;

      return {
        type: 'duration',
        value: parseInt(match[0].replace(/(⏲|seconds?)/, ''), 10)
      }
    } else if (entity.type === 'background') {
      var match = sp.match(/(#[a-fA-F0-9]{3,6}|\w+) background/i)
      return {
        type: 'background',
        color: match[0].replace(' background', '')
      }
    }

    // Get the portion of the text relative to this entity
    sp = i === entities.length - 1 ? p.substring(entity.index) : p.substring(entity.index, entities[i+1].index + 1);

    var str = sp
    switch(entity.type) {
      case 'audio':
      case 'sound':
      case '🔊':
        return {
          type: 'audio',
          src: getUrl(str),
          position: getPosition(str)
        }
      case 'voiceover':
      case '📢':
        return {
          type: 'voiceover',
          text: getQuote(str)
        };
      case 'chart':
      case '📊':
        return {
          type: 'chart',
          src: getUrl(str),
          position: getPosition(str, 10, 10),
          rotation: getRotation(str),
          scale: getSize(str)
        };
      case 'panorama':
      case '🌅':
      return {
        type: 'panorama',
        src: getUrl(str)
      }
      case 'video':
      return {
        type: 'video',
        src: getUrl(str),
        position: getPosition(str),
        scale: getSize(str),
        rotation: getRotation(str)
      }
      case 'videosphere':
      case '🎥':
      return {
        type: 'videosphere',
        src: getUrl(str)
      }
      case 'image':
      case 'picture':
      return {
        type: 'image',
        src: getUrl(str),
        position: getPosition(str),
        scale: getSize(str),
        rotation: getRotation(str)
      }
      case 'text':
      case '📝':
      var text = getQuote(str);
      return {
        type: 'text',
        text: text,
        position: getPosition(str, 14, text.length / 30),
        scale: getSize(str).map(function(el){ return el * 5; }),
        rotation: getRotation(str)
      }
      case 'model':
      return {
        type: 'model',
        src: getUrl(str),
        position: getPosition(str),
        scale: getSize(str),
        rotation: getRotation(str)
      }
    }

    return entity;
  })
  .filter(function(entity) { return !!entity; });
}

function getUrl(str) {
  var match = str.match(/https?:\/\/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/)
  if(!match.length) return
  return match[0].toLowerCase()
}

function getQuote(str) {
  var match = str.match(/".*"/)
  if(!(match && match.length)) return
  return match[0].replace(/"/g, '')
}

function getPosition(str, width, height) {
  width = width || 0;
  height = height || 0;
  var match = str.match(LOCATION_REGEX)
  return getAbsPos(match && match.length ? match[0] : 'front', width, height)
}

function getSize(str) {
  var match = str.match(SIZE_REGEX)
  return getAbsSize(match && match.length ? match[0] : 'normal')
}

function getAbsPos(str, width, height) {
  var xSize = -.5 * width;
  var ySize = -.5 * height;
  switch(str) {
    case 'left':
      return [-5, 1.5 + ySize, 5 - xSize]
    case 'right':
      return [5, 1.5 + ySize, 5 + xSize]
    case 'behind':
      return [-xSize, 1.5 + ySize, 8]
    case 'front':
      return [0 + xSize, 1.5 + ySize, 0]
  }
}

function getRotation(str) {
  var match = str.match(LOCATION_REGEX);
  var pos = match && match.length ? match[0] : 'front';
  switch(pos) {
    case 'left':
      return [0, 90, 0]
    case 'right':
      return [0, -90, 0]
    case 'behind':
      return [0, 180, 0]
    case 'front':
      return [0, 0, 0]
    default:
      return [0, 0, 0]
  }
}

function getAbsSize(str) {
  switch(str) {
    case 'tiny':
      return [1/3, 1/3, 1/3]
    case 'small':
      return [1/2, 1/2, 1/2]
    case 'large':
      return [2, 2, 2]
    case 'huge':
      return [3, 3, 3]
    default:
      return [1, 1, 1]
  }
}
<|endoftext|>


<commit_before>
process.title = "npm"

if (require.main === module) {
  console.error(["It looks like you're doing 'node npm.js'."
                ,"Don't do that.  Instead, run 'make install'"
                ,"and then use the 'npm' command line utility."
                ].join("\n"))
  process.exit(1)
}

var EventEmitter = require("events").EventEmitter
  , npm = module.exports = new EventEmitter
  , config = require("./lib/config")
  , set = require("./lib/utils/set")
  , get = require("./lib/utils/get")
  , ini = require("./lib/utils/ini")
  , log = require("./lib/utils/log")
  , fs = require("./lib/utils/graceful-fs")
  , path = require("path")
  , abbrev = require("abbrev")
  , which = require("./lib/utils/which")
  , semver = require("semver")
  , findPrefix = require("./lib/utils/find-prefix")

npm.commands = {}
npm.ELIFECYCLE = {}
npm.E404 = {}
npm.EPUBLISHCONFLICT = {}
npm.EJSONPARSE = {}
npm.EISGIT = {}
npm.ECYCLE = {}
npm.EENGINE = {}

try {
  // startup, ok to do this synchronously
  var j = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"))+"")
  npm.version = j.version
  npm.nodeVersionRequired = j.engines.node
  if (!semver.satisfies(process.version, j.engines.node)) {
    log.error([""
              ,"npm requires node version: "+j.engines.node
              ,"And you have: "+process.version
              ,"which is not satisfactory."
              ,""
              ,"Bad things will likely happen.  You have been warned."
              ,""].join("\n"), "unsupported version")
  }
} catch (ex) {
  try {
    log(ex, "error reading version")
  } catch (er) {}
  npm.version = ex
}

var commandCache = {}
  // short names for common things
  , aliases = { "rm" : "uninstall"
              , "r" : "uninstall"
              , "un" : "uninstall"
              , "rb" : "rebuild"
              , "list" : "ls"
              , "la" : "ls"
              , "ll" : "ls"
              , "ln" : "link"
              , "i" : "install"
              , "up" : "update"
              , "c" : "config"
              , "info" : "view"
              , "find" : "search"
              , "s" : "search"
              , "se" : "search"
              , "author" : "owner"
              }

  , aliasNames = Object.keys(aliases)
  // these are filenames in ./lib
  , cmdList = [ "install"
              , "uninstall"
              , "cache"
              , "config"
              , "set"
              , "get"
              , "update"
              , "outdated"
              , "prune"

              , "rebuild"
              , "link"

              , "publish"
              , "tag"
              , "adduser"
              , "unpublish"
              , "owner"
              , "deprecate"

              , "help"
              , "ls"
              , "search"
              , "view"
              , "init"
              , "version"
              , "edit"
              , "explore"
              , "docs"
              , "faq"
              , "xmas"
              , "root"
              , "prefix"
              , "bin"

              , "test"
              , "stop"
              , "start"
              , "restart"
              , "run-script"
              , "completion"
              ]
  , plumbing = [ "build"
               , "unbuild"
               ]
  , fullList = npm.fullList = cmdList.concat(aliasNames).filter(function (c) {
      return plumbing.indexOf(c) === -1
    })
  , abbrevs = abbrev(fullList)

Object.keys(abbrevs).concat(plumbing).forEach(function (c) {
  Object.defineProperty(npm.commands, c, { get : function () {
    if (!loaded) throw new Error(
      "Call npm.load(conf, cb) before using this command.\n"+
      "See the README.md or cli.js for example usage.")
    var a = npm.deref(c)
    if (c === "la" || c === "ll") {
      npm.config.set("long", true)
    }
    if (commandCache[a]) return commandCache[a]
    return commandCache[a] = require(__dirname+"/lib/"+a)
  }, enumerable: fullList.indexOf(c) !== -1 })
})

npm.deref = function (c) {
  if (plumbing.indexOf(c) !== -1) return c
  var a = abbrevs[c]
  if (aliases[a]) a = aliases[a]
  return a
}

var loaded = false
  , loading = false
  , loadListeners = []

npm.load = function (conf, cb_) {
  if (!cb_ && typeof conf === "function") cb_ = conf , conf = {}
  loadListeners.push(cb_)
  if (loaded) return cb()
  if (loading) return
  loading = true
  var onload = true

  function handleError (er) {
    loadListeners.forEach(function (cb) {
      process.nextTick(function () { cb(er, npm) })
    })
  }

  function cb (er) {
    if (er) return handleError(er)
    loaded = true
    loadListeners.forEach(function (cb) {
      process.nextTick(function () { cb(er, npm) })
    })
    loadListeners.length = 0
    if (onload = onload && npm.config.get("onload-script")) {
      require(onload)
      onload = false
    }
  }
  log.waitForConfig()
  which(process.argv[0], function (er, node) {
    if (!er && node !== process.execPath) {
      log.verbose("node symlink", node)
      process.execPath = node
    }
    ini.resolveConfigs(conf, function (er) {
      if (er) return handleError(er)
      var p
      if (!npm.config.get("global")
          && !conf.hasOwnProperty("prefix")) {
        p = process.cwd()
      } else {
        p = npm.config.get("prefix")
      }
      // try to guess at a good node_modules location.
      findPrefix(p, function (er, p) {
        if (er) return handleError(er)
        Object.defineProperty(npm, "prefix",
          { get : function () { return p }
          , set : function (r) { return p = r }
          , enumerable : true
          })
        return cb()
      })
    })
  })
}

var path = require("path")
npm.config =
  { get : function (key) { return ini.get(key) }
  , set : function (key, val) { return ini.set(key, val, "cli") }
  , del : function (key, val) { return ini.del(key, val, "cli") }
  }

Object.defineProperty(npm, "dir",
  { get : function () {
      if (npm.config.get("global")) {
        return path.resolve(npm.prefix, "lib", "node_modules")
      } else {
        return path.resolve(npm.prefix, "node_modules")
      }
    }
  , enumerable : true
  })

Object.defineProperty(npm, "cache",
  { get : function () { return npm.config.get("cache") }
  , set : function (r) { return npm.config.set("cache", r) }
  , enumerable : true
  })
var tmpFolder
Object.defineProperty(npm, "tmp",
  { get : function () {
      if (!tmpFolder) tmpFolder = "npm-"+Date.now()
      return path.resolve(npm.config.get("tmp"), tmpFolder)
    }
  , enumerable : true
  })
<commit_msg>Fake up the installPrefix, too<commit_after>
process.title = "npm"

if (require.main === module) {
  console.error(["It looks like you're doing 'node npm.js'."
                ,"Don't do that.  Instead, run 'make install'"
                ,"and then use the 'npm' command line utility."
                ].join("\n"))
  process.exit(1)
}

var EventEmitter = require("events").EventEmitter
  , npm = module.exports = new EventEmitter
  , config = require("./lib/config")
  , set = require("./lib/utils/set")
  , get = require("./lib/utils/get")
  , ini = require("./lib/utils/ini")
  , log = require("./lib/utils/log")
  , fs = require("./lib/utils/graceful-fs")
  , path = require("path")
  , abbrev = require("abbrev")
  , which = require("./lib/utils/which")
  , semver = require("semver")
  , findPrefix = require("./lib/utils/find-prefix")

npm.commands = {}
npm.ELIFECYCLE = {}
npm.E404 = {}
npm.EPUBLISHCONFLICT = {}
npm.EJSONPARSE = {}
npm.EISGIT = {}
npm.ECYCLE = {}
npm.EENGINE = {}

try {
  // startup, ok to do this synchronously
  var j = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"))+"")
  npm.version = j.version
  npm.nodeVersionRequired = j.engines.node
  if (!semver.satisfies(process.version, j.engines.node)) {
    log.error([""
              ,"npm requires node version: "+j.engines.node
              ,"And you have: "+process.version
              ,"which is not satisfactory."
              ,""
              ,"Bad things will likely happen.  You have been warned."
              ,""].join("\n"), "unsupported version")
  }
} catch (ex) {
  try {
    log(ex, "error reading version")
  } catch (er) {}
  npm.version = ex
}

var commandCache = {}
  // short names for common things
  , aliases = { "rm" : "uninstall"
              , "r" : "uninstall"
              , "un" : "uninstall"
              , "rb" : "rebuild"
              , "list" : "ls"
              , "la" : "ls"
              , "ll" : "ls"
              , "ln" : "link"
              , "i" : "install"
              , "up" : "update"
              , "c" : "config"
              , "info" : "view"
              , "find" : "search"
              , "s" : "search"
              , "se" : "search"
              , "author" : "owner"
              }

  , aliasNames = Object.keys(aliases)
  // these are filenames in ./lib
  , cmdList = [ "install"
              , "uninstall"
              , "cache"
              , "config"
              , "set"
              , "get"
              , "update"
              , "outdated"
              , "prune"

              , "rebuild"
              , "link"

              , "publish"
              , "tag"
              , "adduser"
              , "unpublish"
              , "owner"
              , "deprecate"

              , "help"
              , "ls"
              , "search"
              , "view"
              , "init"
              , "version"
              , "edit"
              , "explore"
              , "docs"
              , "faq"
              , "xmas"
              , "root"
              , "prefix"
              , "bin"

              , "test"
              , "stop"
              , "start"
              , "restart"
              , "run-script"
              , "completion"
              ]
  , plumbing = [ "build"
               , "unbuild"
               ]
  , fullList = npm.fullList = cmdList.concat(aliasNames).filter(function (c) {
      return plumbing.indexOf(c) === -1
    })
  , abbrevs = abbrev(fullList)

Object.keys(abbrevs).concat(plumbing).forEach(function (c) {
  Object.defineProperty(npm.commands, c, { get : function () {
    if (!loaded) throw new Error(
      "Call npm.load(conf, cb) before using this command.\n"+
      "See the README.md or cli.js for example usage.")
    var a = npm.deref(c)
    if (c === "la" || c === "ll") {
      npm.config.set("long", true)
    }
    if (commandCache[a]) return commandCache[a]
    return commandCache[a] = require(__dirname+"/lib/"+a)
  }, enumerable: fullList.indexOf(c) !== -1 })
})

npm.deref = function (c) {
  if (plumbing.indexOf(c) !== -1) return c
  var a = abbrevs[c]
  if (aliases[a]) a = aliases[a]
  return a
}

var loaded = false
  , loading = false
  , loadListeners = []

npm.load = function (conf, cb_) {
  if (!cb_ && typeof conf === "function") cb_ = conf , conf = {}
  loadListeners.push(cb_)
  if (loaded) return cb()
  if (loading) return
  loading = true
  var onload = true

  function handleError (er) {
    loadListeners.forEach(function (cb) {
      process.nextTick(function () { cb(er, npm) })
    })
  }

  function cb (er) {
    if (er) return handleError(er)
    loaded = true
    loadListeners.forEach(function (cb) {
      process.nextTick(function () { cb(er, npm) })
    })
    loadListeners.length = 0
    if (onload = onload && npm.config.get("onload-script")) {
      require(onload)
      onload = false
    }
  }
  log.waitForConfig()
  which(process.argv[0], function (er, node) {
    if (!er && node !== process.execPath) {
      log.verbose("node symlink", node)
      process.execPath = node
      process.installPrefix = path.resolve(node, "..", "..")
    }
    ini.resolveConfigs(conf, function (er) {
      if (er) return handleError(er)
      var p
      if (!npm.config.get("global")
          && !conf.hasOwnProperty("prefix")) {
        p = process.cwd()
      } else {
        p = npm.config.get("prefix")
      }
      // try to guess at a good node_modules location.
      findPrefix(p, function (er, p) {
        if (er) return handleError(er)
        Object.defineProperty(npm, "prefix",
          { get : function () { return p }
          , set : function (r) { return p = r }
          , enumerable : true
          })
        return cb()
      })
    })
  })
}

var path = require("path")
npm.config =
  { get : function (key) { return ini.get(key) }
  , set : function (key, val) { return ini.set(key, val, "cli") }
  , del : function (key, val) { return ini.del(key, val, "cli") }
  }

Object.defineProperty(npm, "dir",
  { get : function () {
      if (npm.config.get("global")) {
        return path.resolve(npm.prefix, "lib", "node_modules")
      } else {
        return path.resolve(npm.prefix, "node_modules")
      }
    }
  , enumerable : true
  })

Object.defineProperty(npm, "cache",
  { get : function () { return npm.config.get("cache") }
  , set : function (r) { return npm.config.set("cache", r) }
  , enumerable : true
  })
var tmpFolder
Object.defineProperty(npm, "tmp",
  { get : function () {
      if (!tmpFolder) tmpFolder = "npm-"+Date.now()
      return path.resolve(npm.config.get("tmp"), tmpFolder)
    }
  , enumerable : true
  })
<|endoftext|>


<commit_before>/**
 *
 * NUT adapter
 *
 * Adapter loading NUT data from an UPS
 *
 */

"use strict";

var utils = require(__dirname + '/lib/utils'); // Get common adapter utils
var Nut   = require('node-nut');

var adapter = utils.adapter({
  name: 'nut',
  ready: function () {
    //oNut = new Nut(3493, 'localhost');
    var oNut = new Nut(adapter.config.host_port, adapter.config.host_ip);

    oNut.on('error', function(err) {
      adapter.log.error('Error happend: ' + err);
    });

    oNut.on('close', function() {
      adapter.log.debug('NUT Connection closed. Done.');
      setTimeout(function () {
        adapter.stop();
      }, 2000);
    });

    oNut.on('ready', function() {
      adapter.log.debug('NUT Connection ready');
      var self = this;
      this.GetUPSVars(adapter.config.ups_name,function(varlist) {
        adapter.log.debug('Got values, start setting them');
        storeNutData(varlist);
        self.close();
      });
    });

    oNut.start();
  }
});

function storeNutData(varlist) {
  var last='';
  var current='';
  var index=0;
  var stateName='';

  for (var key in varlist) {
    index=key.indexOf('.');
    if (index > 0) {
      current=key.substring(0,index);
    }
    else {
      current='';
      last='';
      index=-1;
    }
    if (((last=='') || (last!=current)) && (current!='')) {
      adapter.log.debug('Create Channel '+current);
      adapter.setObjectNotExists(current, {
          type: 'channel',
          role: 'info',
          common: {name: current},
          native: {}
      });
    }
    stateName=current+'.'+key.substring(index+1).replace(/\./g,'-');
    adapter.log.debug('Create State '+stateName);
    adapter.setObjectNotExists(stateName, {
        type: 'state',
        common: {name: stateName, type: 'string', read: true, write: false},
        native: {id: stateName}
    });
    adapter.log.debug('Set State '+stateName+' = '+varlist[key]);
    adapter.setState(stateName, {ack: true, val: varlist[key]});
    last=current;
  }
  if (varlist['ups.status']) {
    adapter.log.debug('Create Channel status');
    adapter.setObjectNotExists(current, {
        type: 'channel',
        role: 'info',
        common: {name: 'status'},
        native: {}
    });
    var statusMap = {
              'OL':{name:'online',severity:'idle'},
              'OB':{name:'onbattery',severity:'operating'},
              'LB':{name:'lowbattery',severity:'operating_critical'},
              'HB':{name:'highbattery',severity:'operating_critical'},
              'RB':{name:'replacebattery',severity:'action_needed'},
              'CHRG':{name:'charging',severity:'operating'},
              'DISCHRG':{name:'discharging',severity:'operating'},
              'BYPASS':{name:'bypass',severity:'action_needed'},
              'CAL':{name:'calibration',severity:'operating'},
              'OFF':{name:'offline',severity:'action_needed'},
              'OVER':{name:'overload',severity:'action_needed'},
              'TRIM':{name:'trimming',severity:'operating'},
              'BOOST':{name:'boosting',severity:'operating'},
              'FSD':{name:'shutdown',severity:'operating_critical'}
            };
    var severity = {
              'idle':false,
              'operating':false,
              'operating_critical':false,
              'action_needed':false
            };
    var checker=' '+varlist['ups.status']+' ';
    for (var idx in statusMap) {
      if (statusMap.hasOwnProperty(idx)) {
        var found=(checker.indexOf(idx)>-1);
        stateName='status.'+statusMap[idx]['name'];
        adapter.log.debug('Create State '+stateName);
        adapter.setObjectNotExists(stateName, {
            type: 'state',
            common: {name: stateName, type: 'boolean', read: true, write: false},
            native: {id: stateName}
        });
        adapter.log.debug('Set State '+stateName+' = '+found);
        adapter.setState(stateName, {ack: true, val: found});
        if (found) {
          severity[statusMap[idx].severity]=true;
          adapter.log.debug('Severity Flag '+statusMap[idx].severity+'=true');
        }
      }
    }
  }

  adapter.log.info('All Nut values set');
}
<commit_msg>fixes<commit_after>/**
 *
 * NUT adapter
 *
 * Adapter loading NUT data from an UPS
 *
 */

"use strict";

var utils = require(__dirname + '/lib/utils'); // Get common adapter utils
var Nut   = require('node-nut');

var adapter = utils.adapter({
  name: 'nut',
  ready: function () {
    //oNut = new Nut(3493, 'localhost');
    var oNut = new Nut(adapter.config.host_port, adapter.config.host_ip);

    oNut.on('error', function(err) {
      adapter.log.error('Error happend: ' + err);
    });

    oNut.on('close', function() {
      adapter.log.debug('NUT Connection closed. Done.');
      setTimeout(function () {
        adapter.stop();
      }, 2000);
    });

    oNut.on('ready', function() {
      adapter.log.debug('NUT Connection ready');
      var self = this;
      this.GetUPSVars(adapter.config.ups_name,function(varlist) {
        adapter.log.debug('Got values, start setting them');
        storeNutData(varlist);
        self.close();
      });
    });

    oNut.start();
  }
});

function storeNutData(varlist) {
  var last='';
  var current='';
  var index=0;
  var stateName='';

  for (var key in varlist) {
    index=key.indexOf('.');
    if (index > 0) {
      current=key.substring(0,index);
    }
    else {
      current='';
      last='';
      index=-1;
    }
    if (((last=='') || (last!=current)) && (current!='')) {
      adapter.log.debug('Create Channel '+current);
      adapter.setObjectNotExists(current, {
          type: 'channel',
          role: 'info',
          common: {name: current},
          native: {}
      });
    }
    stateName=current+'.'+key.substring(index+1).replace(/\./g,'-');
    adapter.log.debug('Create State '+stateName);
    adapter.setObjectNotExists(stateName, {
        type: 'state',
        common: {name: stateName, type: 'string', read: true, write: false},
        native: {id: stateName}
    });
    adapter.log.debug('Set State '+stateName+' = '+varlist[key]);
    adapter.setState(stateName, {ack: true, val: varlist[key]});
    last=current;
  }
  if (varlist['ups.status']) {
    adapter.log.debug('Create Channel status');
    adapter.setObjectNotExists(current, {
        type: 'channel',
        role: 'info',
        common: {name: 'status'},
        native: {}
    });
    var statusMap = {
              'OL':{name:'online',severity:'idle'},
              'OB':{name:'onbattery',severity:'operating'},
              'LB':{name:'lowbattery',severity:'operating_critical'},
              'HB':{name:'highbattery',severity:'operating_critical'},
              'RB':{name:'replacebattery',severity:'action_needed'},
              'CHRG':{name:'charging',severity:'operating'},
              'DISCHRG':{name:'discharging',severity:'operating'},
              'BYPASS':{name:'bypass',severity:'action_needed'},
              'CAL':{name:'calibration',severity:'operating'},
              'OFF':{name:'offline',severity:'action_needed'},
              'OVER':{name:'overload',severity:'action_needed'},
              'TRIM':{name:'trimming',severity:'operating'},
              'BOOST':{name:'boosting',severity:'operating'},
              'FSD':{name:'shutdown',severity:'operating_critical'}
            };
    var severity = {
              'idle':false,
              'operating':false,
              'operating_critical':false,
              'action_needed':false
            };
    var checker=' '+varlist['ups.status']+' ';
    for (var idx in statusMap) {
      if (statusMap.hasOwnProperty(idx)) {
        var found=(checker.indexOf(idx)>-1);
        stateName='status.'+statusMap[idx]['name'];
        adapter.log.debug('Create State '+stateName);
        adapter.setObjectNotExists(stateName, {
            type: 'state',
            common: {name: stateName, type: 'boolean', read: true, write: false},
            native: {id: stateName}
        });
        adapter.log.debug('Set State '+stateName+' = '+found);
        adapter.setState(stateName, {ack: true, val: found});
        if (found) {
          severity[statusMap[idx]['severity']]=true;
          adapter.log.debug('Severity Flag '+statusMap[idx]['severity']+'=true');
        }
      }
    }
  }

  adapter.log.info('All Nut values set');
}
<|endoftext|>


<commit_before>//this is my oop assignment
function NotesApplication(){
	var Notes = new NotesApplication(author, noteslist);
	this.author = author;
	this.noteslist = [];
}

NotesApplication.prototype = {
	constructor: NotesApplication,
	NotesContent:function (note_content){
		this.noteslist.push(note_content)
	},

	listNotes :function(){
		var Note_ID = this.noteslist[j];
		if(this.noteslist.length>0){
			for(j = 0; j<this.noteslist.length; j++){
				console.log("Note_ID: " + Note_ID );
				console.log(note_content);
				console.log("By Author: " + this.author);
			}
		}

	},

	get: function(Note_ID){
		return this.noteslist.join(',');
	}

}

<commit_msg>seventh commit<commit_after>//this is my oop assignment
function NotesApplication(author, noteslist){
	this.author = author;
	this.noteslist = [];
}

NotesApplication.prototype = {
	constructor: NotesApplication,
	NotesContent:function (note_content){
		this.noteslist.push(note_content)
	},

	listNotes :function(){
		var Note_ID = this.noteslist[j];
		if(this.noteslist.length>0){
			for(j = 0; j<this.noteslist.length; j++){
				console.log("Note_ID: " + Note_ID );
				console.log(note_content);
				console.log("By Author: " + this.author);
			}
		}

	},

	get: function(Note_ID){
		return this.noteslist.join(',');
	}

}

<|endoftext|>


<commit_before>var dietary_restriction;

$(".restrictions-menu li > a").click(function(e){
  $('.restrictions-selection').text(this.innerHTML);
  dietary_restriction = this.innerHTML;

});

var cuisine_choice;

$(".cuisine-menu li > a").click(function(e){
	$('.cuisine-selection').text(this.innerHTML);
	cuisine_choice = this.innerHTML;
});

// Closes the sidebar menu
$("#menu-close").click(function(e) {
	e.preventDefault();
	$("#sidebar-wrapper").toggleClass("active");
});
// Opens the sidebar menu
$("#menu-toggle").click(function(e) {
	e.preventDefault();
	$("#sidebar-wrapper").toggleClass("active");
});
// Scrolls to the selected menu item on the page
$(function() {
	$('a[href*=#]:not([href=#],[data-toggle],[data-target],[data-slide])').click(function() {
		if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
			var target = $(this.hash);
			target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
			if (target.length) {
				$('html,body').animate({
					scrollTop: target.offset().top
				}, 1000);
				return false;
			}
		}
	});
});
<commit_msg>update our.js<commit_after>var dietary_restriction;

$(".restrictions-menu li > a").click(function(e){
  $('.restrictions-selection').text(this.innerHTML);
  dietary_restriction = this.innerHTML;

});

var cuisine_choice;

$(".cuisine-menu li > a").click(function(e){
	$('.cuisine-selection').text(this.innerHTML);
	cuisine_choice = this.innerHTML;
});

var occasion_choice;

$(".occasion-menu li > a").click(function(e){
	$('.occasion-selection').text(this.innerHTML);
	occasion_choice = this.innerHTML;
});

// Closes the sidebar menu
$("#menu-close").click(function(e) {
	e.preventDefault();
	$("#sidebar-wrapper").toggleClass("active");
});
// Opens the sidebar menu
$("#menu-toggle").click(function(e) {
	e.preventDefault();
	$("#sidebar-wrapper").toggleClass("active");
});
// Scrolls to the selected menu item on the page
$(function() {
	$('a[href*=#]:not([href=#],[data-toggle],[data-target],[data-slide])').click(function() {
		if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
			var target = $(this.hash);
			target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
			if (target.length) {
				$('html,body').animate({
					scrollTop: target.offset().top
				}, 1000);
				return false;
			}
		}
	});
});
<|endoftext|>


<commit_before>var peerJsApiKey = "gnyz9wskc2chaor";

function getPeerIdFromURL() {
    if (window.location.search) {
        var params = window.location.search.substring(1).split('&');
        for (var i = 0; i < params.length; ++i) {
            if (params[i].match('^peer-id')) {
                return params[i].split('=')[1];
            }
        }
    }
    return null;
}

var peerConnections = [];
var netRole = null;
var clientUpdateCallback = null;
var clientKeysPressed = null;
var id = null;
var ThisPeerID = null;
var clientID = null;
var serverID = null;
var timeOutTable = [];
var timeout = 7; // in seconds

function gotConnection(conn) {
    if (peerConnections.length > 0 && netRole === 'client') {
        console.log("Can't handle several connections in client mode");
	conn.close();
        return;
    }
    peerConnections.push(conn);
    timeOutTable.push(0);
    conn.on('data', function(data) { gotData(conn, data); });

    if (netRole === 'server') {
        // Add player
        var randomColor = getRandomColor();
        var newPeerID = peerConnections[peerConnections.length-1].peer;
        players.push(new player(newPeerID, newPeerID, randomColor));
        console.log("new player, id:" + newPeerID);

        refreshScene();
    }
}

function refreshScene() {
    // Updated scene
    playerAmount = players.length;
    ball.speed = playerAmount * 70;
    generateScene();
}

function Vec3FromArray(a) {
    var v3 = new THREE.Vector3();
    v3.copy(a);
    return v3;
}

function gotData(conn, data) {
    try {
        msg = JSON.parse(data);
    } catch (err) {
        console.log("not JSON: " + data);
        return;
    }
    if (netRole === 'client' && msg.ballpos !== undefined) {
        msg.ballpos = Vec3FromArray(msg.ballpos);
        msg.racketspos = msg.racketspos.map(function(arr) {
            return Vec3FromArray(arr);
        });
        if (clientUpdateCallback) {
            var keys = clientUpdateCallback(msg);
            conn.send(JSON.stringify({
                pressedkeys: keys,
                playerID: ThisPeerID,
            }))
        } else {
            console.log("update msg without handler, in " + netRole + " mod");
        }
    } else if (netRole === 'server' && msg.pressedkeys !== undefined) {
        clientKeysPressed = msg.pressedkeys;
        clientID = msg.playerID;
    } else if (netRole === 'server') {
	console.log("undefined keys in net msg");
    }

    // Sync scene variables
    if (msg.playeramount !== undefined)
        playerAmount = msg.playeramount;
    if (msg.players !== undefined)
        players = msg.players;

}

function removePeerConnection(conn) {
    for (var i = 0; i < peerConnections.length; i++) {
	if (conn === peerConnections[i]) {
	    peerConnections.splice(i, 1);
	}
    }
}

function makePeer() {
    return new Peer({key: peerJsApiKey})
}

function initNet(updateCallback) {
    var peerid = getPeerIdFromURL();

    if (peerid !== null) {
	initClient(updateCallback, peerid);
    } else {
	initServer(updateCallback);
    }
}

var connectionRetries = 0;

function attemptServerConnection(peerid) {
    if ((typeof peerid) !== "string")
	throw("peerid must be string! got this: " + peerid);
    pjs = makePeer();
    pjs.on('open', function(myid) { ThisPeerID = myid; });
    var conn = pjs.connect(peerid);
    conn.on("open", function () {
	console.log("connection estabilished to server");
	showHelp();
    });
    conn.on("error", function () {
	console.log("connection error to server");
    });
    gotConnection(conn);
    console.log("connecting to peer " + peerid);
    connectionTimeout = function() {
	if (conn.open === false && netRole != null) {
	    removePeerConnection(conn);
	    conn.close();
	    pjs.disconnect();
	    console.log("server connection timed out");
	    if (connectionRetries++ < 10) {
		console.log("retrying connetion, attempt #" + connectionRetries);
		attemptServerConnection(peerid);
	    } else {
		console.log("giving up");
		// can put callback here for connection failure?
	    }
	}
    }
    window.setTimeout(connectionTimeout, 15000 /*ms*/);
    return conn;
}

function initClient(updateCallback, peerid) {
    openCallback = function() {
        conn.send('Hello world!');
        console.log("connected to " + peerid + ", hello sent");

    }
    var conn = attemptServerConnection(peerid)
    netRole = 'client';
    clientUpdateCallback = updateCallback;
    // console.log("client update callback registered");
}

function initServer(updateCallback) {
    netRole = 'server';
    pjs = makePeer();
    pjs.on('open', function(myid) { ThisPeerID = myid; });
    pjs.on('open', function(myid) {
        var gamemsg = window.location.href + '?peer-id=' + myid
        // alert(gamemsg);
        $("#playerUrl").html(gamemsg);
        $("#urlBox").dialog("open");

        if (netRole === 'server') {
            // server is always the player 0
            var randomColor = getRandomColor();
            players[0] = new player(myid, "server", randomColor);
            playerAmount = 1;
            serverID = myid;
            console.log("server id:" + myid);
        }

        console.log(gamemsg);
        showHelp();
    });

    pjs.on('connection', function(conn) {
        gotConnection(conn);
    });
}

function serverNetUpdate(racketPositions, ballPos, timedelta, amountPlayers, playerlist) {
    if (netRole === 'server') {
        // console.log("server net update");
        var update_msg = {
            dt: timedelta,
            racketspos: racketPositions,
            ballpos: ballPos,
            playeramount: amountPlayers,
            players: playerlist,
        };

	var json_msg = JSON.stringify(update_msg);
	for (var i = 0; i < peerConnections.length; i++)
            if (peerConnections[i].open == false) {
		timeOutTable[i] += timedelta;

		if (timeOutTable[i] >= timeout) {
                    // peer disconnected
                    console.log("peer disconnected");
                    if (i === 0 ) {
			peerConnections.shift();
			timeOutTable.shift();
                    }
                    else{
			peerConnections.splice(i,i);
			timeOutTable.splice(i,i);
                    }

                    players.splice(i+1,i+1);

                    refreshScene();
		}
            }
        else {
            if (timeOutTable[i] !== 0) {
                timeOutTable[i] = 0;
            }
	    peerConnections[i].send(json_msg);
        }
    }
}
<commit_msg>net code fixes and fake timeout mode for net timeout testing<commit_after>var peerJsApiKey = "gnyz9wskc2chaor";

function getPeerIdFromURL() {
    if (window.location.search) {
        var params = window.location.search.substring(1).split('&');
        for (var i = 0; i < params.length; ++i) {
            if (params[i].match('^peer-id')) {
                return params[i].split('=')[1];
            }
        }
    }
    return null;
}

var peerConnections = [];
var netRole = null;
var clientUpdateCallback = null;
var clientKeysPressed = null;
var id = null;
var ThisPeerID = null;
var clientID = null;
var serverID = null;
var timeOutTable = [];
var timeout = 7; // in seconds
var players = null;
var playerAmount = null;
var timeoutDebug = true; // first connection will fake-timeout to exercise code

function gotConnection(conn) {
    if (peerConnections.length > 0 && netRole === 'client') {
        console.log("Can't handle several connections in client mode");
	conn.close();
        return;
    }
    peerConnections.push(conn);
    timeOutTable.push(0);
    conn.on('data', function(data) { gotData(conn, data); });

    if (netRole === 'server') {
        // Add player
        var randomColor = getRandomColor();
        var newPeerID = peerConnections[peerConnections.length-1].peer;
        players.push(new player(newPeerID, newPeerID, randomColor));
        console.log("new player, id:" + newPeerID);

        refreshScene();
    }
}

function refreshScene() {
    // Updated scene
    playerAmount = players.length;
    ball.speed = playerAmount * 70;
    generateScene();
}

function Vec3FromArray(a) {
    var v3 = new THREE.Vector3();
    v3.copy(a);
    return v3;
}

function gotData(conn, data) {
    try {
        var msg = JSON.parse(data);
    } catch (err) {
        console.log("not JSON: " + data);
        return;
    }
    if (netRole === 'client' && msg.ballpos !== undefined) {
        msg.ballpos = Vec3FromArray(msg.ballpos);
        msg.racketspos = msg.racketspos.map(function(arr) {
            return Vec3FromArray(arr);
        });
        if (clientUpdateCallback) {
            var keys = clientUpdateCallback(msg);
            conn.send(JSON.stringify({
                pressedkeys: keys,
                playerID: ThisPeerID,
            }))
        } else {
            console.log("update msg without handler, in " + netRole + " mod");
        }
    } else if (netRole === 'server' && msg.pressedkeys !== undefined) {
        clientKeysPressed = msg.pressedkeys;
        clientID = msg.playerID;
    } else if (netRole === 'server') {
	console.log("undefined keys in net msg");
    }

    // Sync scene variables
    if (msg.playeramount !== undefined)
        playerAmount = msg.playeramount;
    if (msg.players !== undefined)
        players = msg.players;

}

function removePeerConnection(conn) {
    for (var i = 0; i < peerConnections.length; i++) {
	if (conn === peerConnections[i]) {
	    peerConnections.splice(i, 1);
	    timeOutTable.splice(i, 1);
	}
    }
}

function makePeer() {
    return new Peer({key: peerJsApiKey})
}

function initNet(updateCallback) {
    var peerid = getPeerIdFromURL();

    if (peerid !== null) {
	initClient(updateCallback, peerid);
    } else {
	initServer(updateCallback);
    }
}

var connectionRetries = 0;

function attemptServerConnection(peerid) {
    if ((typeof peerid) !== "string")
	throw("peerid must be string! got this: " + peerid);
    var pjs = makePeer();
    pjs.on('open', function(myid) { ThisPeerID = myid; });
    var conn = pjs.connect(peerid);
    conn.on("open", function () {
	console.log("connection estabilished to server");
	showHelp();
    });
    conn.on("error", function () {
	console.log("connection error to server");
    });
    gotConnection(conn);
    console.log("connecting to peer " + peerid);

    connectionTimeout = function() {
	var connectionOk = undefined;
	var connectionFailureFaked = undefined;
	if (timeoutDebug && conn.open === true && connectionRetries === 0) {
	    // fake timeout on first attempt
	    connectionOk = false;
	    connectionFailureFaked = true;
	} else {
	    connectionOk = conn.open;
	    connectionFailureFaked = false;
	}

	if (connectionOk === false && netRole != null) {
	    removePeerConnection(conn);
	    conn.close();
	    pjs.disconnect();
	    console.log("server connection timed out - faked=" + connectionFailureFaked);
	    if (connectionRetries++ < 10) {
		console.log("retrying connetion, attempt #" + connectionRetries);
		attemptServerConnection(peerid);
	    } else {
		console.log("giving up");
		// can put callback here for connection failure?
	    }
	}
    }
    window.setTimeout(connectionTimeout, 15000 /*ms*/);
    return conn;
}

function initClient(updateCallback, peerid) {
    var conn = attemptServerConnection(peerid)
    netRole = 'client';
    clientUpdateCallback = updateCallback;
    // console.log("client update callback registered");
}

function initServer(updateCallback) {
    netRole = 'server';
    pjs = makePeer();
    pjs.on('open', function(myid) { ThisPeerID = myid; });
    pjs.on('open', function(myid) {
        var gamemsg = window.location.href + '?peer-id=' + myid
        // alert(gamemsg);
        $("#playerUrl").html(gamemsg);
        $("#urlBox").dialog("open");

        if (netRole === 'server') {
            // server is always the player 0
            var randomColor = getRandomColor();
            players[0] = new player(myid, "server", randomColor);
            playerAmount = 1;
            serverID = myid;
            console.log("server id:" + myid);
        }

        console.log(gamemsg);
        showHelp();
    });

    pjs.on('connection', function(conn) {
        gotConnection(conn);
    });
}

function serverNetUpdate(racketPositions, ballPos, timedelta, amountPlayers, playerlist) {
    if (netRole === 'server') {
        // console.log("server net update");
        var update_msg = {
            dt: timedelta,
            racketspos: racketPositions,
            ballpos: ballPos,
            playeramount: amountPlayers,
            players: playerlist,
        };

	var json_msg = JSON.stringify(update_msg);
	for (var i = 0; i < peerConnections.length; i++)
            if (peerConnections[i].open == false) {
		timeOutTable[i] += timedelta;

		if (timeOutTable[i] >= timeout) {
                    // peer disconnected
                    console.log("peer disconnected");
		    peerConnections.splice(i, 1);
		    timeOutTable.splice(i, 1);

                    players.splice(i+1, 1);

                    refreshScene();
		}
            }
        else {
            if (timeOutTable[i] !== 0) {
                timeOutTable[i] = 0;
            }
	    var conn = peerConnections[i];
	    try {
		conn.send(json_msg);
	    } catch (err) {
		console.log("Send to peer connection " + i + " failed: " + err + " - removing that connection");
		removePeerConnection(conn);
		try { conn.close(); } catch (e) { }
	    }
        }
    }
}
<|endoftext|>


<commit_before>// Eheeey! Welcome to POP.js

var POP = function(params) {
    var that = this;
    that.configs = {
        controls   : true,
        editorMode : true
    };
    that.mode = 'desktop'; // or 'vr'
    that.three = {};
    that.container = (params && params.container) || document.body;
    that.elements = [];
    that.worlds = params.worlds || [];
    that.selectedWorld = params.selectedWorld || 0;
    that.cursorCoords = {};

    that.events = {
        resize            : function() {
            that.three.camera.aspect = window.innerWidth / window.innerHeight;
            that.three.camera.updateProjectionMatrix();

            that.three.rendererGL.setSize(window.innerWidth, window.innerHeight);
            that.three.rendererCSS.setSize(window.innerWidth, window.innerHeight);

            if(that.mode == 'vr') {
                that.effect && that.effect.setSize( window.innerWidth, window.innerHeight );
            }
        },
        addMovingClass    : function() {
            document.body.setAttribute('move', 'true');
        },
        removeMovingClass : function() {
            document.body.removeAttribute('move');
        }
    };

    that.saveImage = function(){

        // This is experiment, fuck this shit

        that.elements.forEach(function(element){
            var copy = element.element;
            var style = copy.getAttribute('style');

            var x = copy.getAttribute('x'),
                y = copy.getAttribute('y'),
                z = copy.getAttribute('z'),
                world = copy.getAttribute('world');

            var W = copy.offsetWidth,
                H = copy.offsetHeight;

            if(world != that.selectedWorld()) return;

            copy.removeAttribute('style');
            html2canvas(copy, {
              allowTaint: true,
              logging: true,
              onrendered: function(canvas) {

                    var texture = new THREE.Texture(canvas);
                    texture.needsUpdate = true;

                    var geometry = new THREE.PlaneGeometry( W, H, 10, 10 );
                    var material = new THREE.MeshBasicMaterial( {map: texture, side: THREE.DoubleSide, transparent: true} );
                    var plane = new THREE.Mesh( geometry, material );
                    that.three.sceneGL.add( plane );

                    plane.position.set(x, y, z);
                    plane.lookAt(that.three.camera.position);

              },
              width: W,
              height: H
            });
            copy.setAttribute('style', style);

        })

        that.three.camera.position.z = 0;
        setTimeout(function(){
            that.three.equi.update( that.three.camera, that.three.sceneGL );

            that.three.camera.position.z = 300;
        }, 1000);
    };

    that.init = function() {
        that.three.sceneGL = new THREE.Scene();
        that.three.sceneCSS = new THREE.Scene();

        // -- Setting up the camera -- //
        that.three.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000000);
        that.three.camera.position.z = 300;

        // -- Defining the WebGL and CSS3D Renderers -- //
        var rendererCSS = null;

        rendererCSS = that.mode == 'vr' ? new THREE.CSS3DStereoRenderer() : new THREE.CSS3DRenderer();
        rendererCSS.setSize(window.innerWidth, window.innerHeight);
        rendererCSS.domElement.id = 'renderer-css';

        var rendererGL = new THREE.WebGLRenderer({
            alpha     : true,
            antialias : true,
            preserveDrawingBuffer: true
        });
        rendererGL.setClearColor(0x00ff00, 0.0);
        rendererGL.domElement.id = 'renderer-gl';

        if(that.mode == 'vr') {
            var effect = new THREE.StereoEffect( rendererGL );
            effect.setSize( window.innerWidth, window.innerHeight );

            that.effect = effect;
        }

        that.three.equi = new THREE.CubemapToEquirectangular( rendererGL, true );

        rendererGL.setSize(window.innerWidth, window.innerHeight);
        rendererCSS.domElement.appendChild(rendererGL.domElement);

        that.container.appendChild(rendererCSS.domElement);

        that.three.rendererGL = rendererGL;
        that.three.rendererCSS = rendererCSS;

        that.three.raycaster = new THREE.Raycaster();
        that.three.mouse = new THREE.Vector2();

        // -- Adding the orbit controls -- //
        if(that.configs.controls) {
            that.three.controls = new THREE.OrbitControls(that.three.camera, that.three.rendererGL.domElement);
            that.three.controls.zoomSpeed = 0;
            that.three.controls.enablePan = false;
        }

        that.addPopElements();
        that.attachingTheEvents();
        that.animate();
    };
    that.createWorld = function(options, cb) {
        options.koColor = options.koColor || ko.observable('blue');
        options.color = options.koColor();
        options.depthTest = false;

        var world = new THREE.Mesh(
            new THREE.SphereGeometry(options.size, 100, 50),
            new THREE.MeshBasicMaterial(that.configs.editorMode ? { side: THREE.DoubleSide } : options)
        );
        var sphereFrame;
        world.options = options;
        world.material.side = THREE.DoubleSide;
        that.three.sceneGL.add(world);

        if(that.configs.editorMode) {
            var sphereFrameGeo = new THREE.EdgesGeometry(world.geometry);
            var sphereFrameMat = new THREE.LineBasicMaterial({color : 'rgb(0,0,0)', linewidth : 1, transparent: true, opacity: 0.2});
            sphereFrame = new THREE.LineSegments(sphereFrameGeo, sphereFrameMat);

            var frameHolder = new THREE.Mesh(
                new THREE.SphereGeometry(options.size, 100, 50),
                new THREE.MeshBasicMaterial({side: THREE.DoubleSide, transparent: true, opacity: 0})
            );

            that.three.sceneGL.add(frameHolder);

            frameHolder.scale.set(0.5, 0.5, 0.5);
            sphereFrame.scale.set(0.6, 0.6, 0.6);

            sphereFrame.frameHolder = frameHolder;
            sphereFrame.visible = false;
            sphereFrame.world = world;
            sphereFrame.options = options;
        }
        that.three.sceneGL.add(sphereFrame);
        that.worlds.push(sphereFrame || world);

        that.selectWorld(that.worlds().length - 1);

        cb && cb();
    };
    that.selectWorld = function(index) {
        if(params.selectedWorld)
            params.selectedWorld(index);
        else
            that.selectedWorld = index;

        var helements = document.querySelectorAll('.pop-element:not([world="' + index + '"])'), // Elements I should hide
            selements = document.querySelectorAll('.pop-element[world="' + index + '"]'); // Elements I should show

            helements.forEach(function(element){
                element.style.display = 'none';
            });

            selements.forEach(function(element){
                element.style.display = 'block';
            });

        that.worlds().forEach(function(item, i) {
            if(i == index) {
                if(!item.world) item.world = {};

                item.visible = item.frameHolder.visible = item.world.visible = true;
            } else {
                if(!item.world) item.world = {};

                item.visible = item.frameHolder.visible = item.world.visible = false;
            }
        });
    };
    that.addPopElements = function(cb) {
        var popElements = document.querySelectorAll('.pop-element');
        for(var i = 0; i < popElements.length; i++) {
            if(that.elements.indexOf(popElements[i]) < 0) {
                that.addPopElement(popElements[i], {
                    world : popElements[i].getAttribute('world'),
                    x     : popElements[i].getAttribute('x'),
                    y     : popElements[i].getAttribute('y'),
                    z     : popElements[i].getAttribute('z')
                });
            }
        }
        cb && cb();
    };
    that.addPopElement = function(element, option, cb) {
        if(option.world === false) {
            console.error("The 'world' attribute is required for the element.")
            return;
        }

        that.addHtml({
            world   : option.world,
            x       : option.x || 0,
            y       : option.y || 0,
            z       : option.z || 0,
            content : element
        });
        cb && cb();
    };
    that.attachingTheEvents = function() {
        window.addEventListener('resize', that.events.resize);
        that.three.rendererGL.domElement.addEventListener('mousedown', that.events.addMovingClass);
        that.three.rendererGL.domElement.addEventListener('mousemove', function(e) {
            that.cursorCoords = that.getCoordsFromWorld(e, 1);
        });
        that.three.rendererGL.domElement.addEventListener('dragover', function(e) {
            that.cursorCoords = that.getCoordsFromWorld(e, 1);
        });
        that.three.rendererGL.domElement.addEventListener('mouseup', that.events.removeMovingClass);
    };
    that.getCoordsFromWorld = function(event, index) {
        event.preventDefault();
        var point;

        that.three.mouse.x = ( event.clientX / that.three.rendererGL.domElement.clientWidth ) * 2 - 1;
        that.three.mouse.y = -( event.clientY / that.three.rendererGL.domElement.clientHeight ) * 2 + 1;

        that.three.raycaster.setFromCamera(that.three.mouse, that.three.camera);

        var intersects = that.three.raycaster.intersectObjects(that.three.sceneGL.children);

        if(intersects.length > 0) {
            if(!intersects[0].face) intersects[0] = intersects[1];

            point = intersects[0].point;
            return point;
        }
    };
    that.changeMode = function(mode) {
        var that = this;

        if(mode){
            that.mode = mode;
        } else {
            that.mode = that.mode == 'vr' ? 'desktop' : 'vr';
        }

        if(that.mode == 'vr' && !that.effect) {
            var effect = new THREE.StereoEffect( that.three.rendererGL );
            effect.setSize( window.innerWidth, window.innerHeight );

            that.effect = effect;
        }

        that.rerender();
        that.events.resize();
    };
    that.rerender = function(){

        document.body.removeChild(document.querySelector('#renderer-css'));

        that.three.rendererCSS = that.mode == 'vr' ? new THREE.CSS3DStereoRenderer() : new THREE.CSS3DRenderer();
        that.three.rendererCSS.setSize(window.innerWidth, window.innerHeight);
        that.three.rendererCSS.domElement.id = 'renderer-css';

        that.three.rendererCSS.domElement.appendChild(that.three.rendererGL.domElement);

        that.container.appendChild(that.three.rendererCSS.domElement);

        that.selectWorld(that.selectedWorld());

    };
    that.animate = function() {
        requestAnimationFrame(that.animate);

        that.three.rendererGL.render(that.three.sceneGL, that.three.camera);
        that.three.rendererCSS.render(that.three.sceneCSS, that.three.camera);

        if(that.mode == 'vr')
            that.effect && that.effect.render(that.three.sceneGL, that.three.camera);

        if(that.configs.controls)
            that.three.controls.update();
    };
    that.init();
};

POP.prototype.addHtml = function(params) {
    var that = this,
        htmlObject = new THREE.CSS3DObject(params.content);

    params.content.setAttribute('world', params.world);
    params.content.setAttribute('x', params.x);
    params.content.setAttribute('y', params.y);
    params.content.setAttribute('z', params.z);

    htmlObject.position.z = params.z || 0;
    htmlObject.position.y = params.y || 0;
    htmlObject.position.x = params.x || 0;

    htmlObject.element = params.content;
    htmlObject.index = that.elements.length;
    params.content.object = htmlObject;

    htmlObject.lookAt(that.three.camera.position);

    // -- Adding the HTML Content to scene -- //
    that.three.sceneCSS.add(htmlObject);
    that.elements.push(htmlObject);
};
POP.prototype.add3dObject = function(params) {
    // :TODO -- This function supports .obj, .js, .collada model formats -- //
    var that = this;
};
<commit_msg>Added a function for 360 screenshot<commit_after>// Eheeey! Welcome to POP.js

var POP = function(params) {
    var that = this;
    that.configs = {
        controls   : true,
        editorMode : true
    };
    that.mode = 'desktop'; // or 'vr'
    that.three = {};
    that.container = (params && params.container) || document.body;
    that.elements = [];
    that.worlds = params.worlds || [];
    that.selectedWorld = params.selectedWorld || 0;
    that.cursorCoords = {};

    that.events = {
        resize            : function() {
            that.three.camera.aspect = window.innerWidth / window.innerHeight;
            that.three.camera.updateProjectionMatrix();

            that.three.rendererGL.setSize(window.innerWidth, window.innerHeight);
            that.three.rendererCSS.setSize(window.innerWidth, window.innerHeight);

            if(that.mode == 'vr') {
                that.effect && that.effect.setSize( window.innerWidth, window.innerHeight );
            }
        },
        addMovingClass    : function() {
            document.body.setAttribute('move', 'true');
        },
        removeMovingClass : function() {
            document.body.removeAttribute('move');
        }
    };

    that.saveImage = function(){

        // This is experiment, fuck this shit

        var planes = [];

        var capture = function(index){
            if(index + 1 != that.elements.length) return;

            var position = {
                x: that.three.camera.position.x,
                y: that.three.camera.position.y,
                z: that.three.camera.position.z
            }

            that.three.camera.position.set(0, 0, 0);
            that.three.equi.update( that.three.camera, that.three.sceneGL );

            setTimeout(function(){
                debugger;
                that.three.camera.position.set(position.x, position.y, position.z)
            }, 300);

            planes.forEach(function(item){
                that.three.sceneGL.remove(item);
            });
        }

        that.elements.forEach(function(element, i){
            var copy = element.element.cloneNode(true);;
            var style = copy.getAttribute('style');

            var x = copy.getAttribute('x'),
                y = copy.getAttribute('y'),
                z = copy.getAttribute('z'),
                world = copy.getAttribute('world');

            var W = element.element.offsetWidth,
                H = element.element.offsetHeight;

            if(world != that.selectedWorld()) return;

            copy.removeAttribute('style');
            document.body.appendChild(copy);

            html2canvas(copy, {
              allowTaint: true,
              logging: true,
              width: W,
              height: H
          }).then(function(canvas){
                var texture = new THREE.Texture(canvas);
                texture.needsUpdate = true;

                texture.wrapS = THREE.RepeatWrapping;
                texture.repeat.x = - 1;

                var geometry = new THREE.PlaneGeometry( W, H );
                var material = new THREE.MeshBasicMaterial( { map: texture, side: THREE.DoubleSide, transparent: true, alphaTest: 0.5 } );
                var plane = new THREE.Mesh( geometry, material );
                that.three.sceneGL.add( plane );

                plane.position.set(x, y, z);
                plane.lookAt(that.three.camera.position);

                console.log(plane);

                planes.push(plane);

                document.body.removeChild(copy);

                setTimeout(function(){
                    capture(i);
                }, 100);
          });
        });
    };

    that.init = function() {
        that.three.sceneGL = new THREE.Scene();
        that.three.sceneCSS = new THREE.Scene();

        // -- Setting up the camera -- //
        that.three.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000000);
        that.three.camera.position.z = 1;

        // -- Defining the WebGL and CSS3D Renderers -- //
        var rendererCSS = null;

        rendererCSS = that.mode == 'vr' ? new THREE.CSS3DStereoRenderer() : new THREE.CSS3DRenderer();
        rendererCSS.setSize(window.innerWidth, window.innerHeight);
        rendererCSS.domElement.id = 'renderer-css';

        var rendererGL = new THREE.WebGLRenderer({
            alpha     : true,
            antialias : true,
            preserveDrawingBuffer: true
        });
        rendererGL.setClearColor(0x00ff00, 0.0);
        rendererGL.domElement.id = 'renderer-gl';

        if(that.mode == 'vr') {
            var effect = new THREE.StereoEffect( rendererGL );
            effect.setSize( window.innerWidth, window.innerHeight );

            that.effect = effect;
        }

        that.three.equi = new THREE.CubemapToEquirectangular( rendererGL, true );

        rendererGL.setSize(window.innerWidth, window.innerHeight);
        rendererCSS.domElement.appendChild(rendererGL.domElement);

        that.container.appendChild(rendererCSS.domElement);

        that.three.rendererGL = rendererGL;
        that.three.rendererCSS = rendererCSS;

        that.three.raycaster = new THREE.Raycaster();
        that.three.mouse = new THREE.Vector2();

        // -- Adding the orbit controls -- //
        if(that.configs.controls) {
            that.three.controls = new THREE.OrbitControls(that.three.camera, that.three.rendererGL.domElement);
            that.three.controls.zoomSpeed = 0;
            that.three.controls.enablePan = false;
        }

        that.addPopElements();
        that.attachingTheEvents();
        that.animate();
    };
    that.createWorld = function(options, cb) {
        options.koColor = options.koColor || ko.observable('blue');
        options.color = options.koColor();
        options.depthTest = false;

        var world = new THREE.Mesh(
            new THREE.SphereGeometry(options.size, 100, 50),
            new THREE.MeshBasicMaterial(that.configs.editorMode ? { side: THREE.DoubleSide } : options)
        );
        var sphereFrame;
        world.options = options;
        world.material.side = THREE.DoubleSide;
        that.three.sceneGL.add(world);

        if(that.configs.editorMode) {
            var sphereFrameGeo = new THREE.EdgesGeometry(world.geometry);
            var sphereFrameMat = new THREE.LineBasicMaterial({color : 'rgb(0,0,0)', linewidth : 1, transparent: true, opacity: 0.2});
            sphereFrame = new THREE.LineSegments(sphereFrameGeo, sphereFrameMat);

            var frameHolder = new THREE.Mesh(
                new THREE.SphereGeometry(options.size, 100, 50),
                new THREE.MeshBasicMaterial({side: THREE.DoubleSide, transparent: true, opacity: 0})
            );

            that.three.sceneGL.add(frameHolder);

            frameHolder.scale.set(0.5, 0.5, 0.5);
            sphereFrame.scale.set(0.6, 0.6, 0.6);

            sphereFrame.frameHolder = frameHolder;
            sphereFrame.visible = false;
            sphereFrame.world = world;
            sphereFrame.options = options;
        }
        that.three.sceneGL.add(sphereFrame);
        that.worlds.push(sphereFrame || world);

        that.selectWorld(that.worlds().length - 1);

        cb && cb();
    };
    that.selectWorld = function(index) {
        if(params.selectedWorld)
            params.selectedWorld(index);
        else
            that.selectedWorld = index;

        var helements = document.querySelectorAll('.pop-element:not([world="' + index + '"])'), // Elements I should hide
            selements = document.querySelectorAll('.pop-element[world="' + index + '"]'); // Elements I should show

            helements.forEach(function(element){
                element.style.display = 'none';
            });

            selements.forEach(function(element){
                element.style.display = 'block';
            });

        that.worlds().forEach(function(item, i) {
            if(i == index) {
                if(!item.world) item.world = {};

                item.visible = item.frameHolder.visible = item.world.visible = true;
            } else {
                if(!item.world) item.world = {};

                item.visible = item.frameHolder.visible = item.world.visible = false;
            }
        });
    };
    that.addPopElements = function(cb) {
        var popElements = document.querySelectorAll('.pop-element');
        for(var i = 0; i < popElements.length; i++) {
            if(that.elements.indexOf(popElements[i]) < 0) {
                that.addPopElement(popElements[i], {
                    world : popElements[i].getAttribute('world'),
                    x     : popElements[i].getAttribute('x'),
                    y     : popElements[i].getAttribute('y'),
                    z     : popElements[i].getAttribute('z')
                });
            }
        }
        cb && cb();
    };
    that.addPopElement = function(element, option, cb) {
        if(option.world === false) {
            console.error("The 'world' attribute is required for the element.")
            return;
        }

        that.addHtml({
            world   : option.world,
            x       : option.x || 0,
            y       : option.y || 0,
            z       : option.z || 0,
            content : element
        });
        cb && cb();
    };
    that.attachingTheEvents = function() {
        window.addEventListener('resize', that.events.resize);
        that.three.rendererGL.domElement.addEventListener('mousedown', that.events.addMovingClass);
        that.three.rendererGL.domElement.addEventListener('mousemove', function(e) {
            that.cursorCoords = that.getCoordsFromWorld(e, 1);
        });
        that.three.rendererGL.domElement.addEventListener('dragover', function(e) {
            that.cursorCoords = that.getCoordsFromWorld(e, 1);
        });
        that.three.rendererGL.domElement.addEventListener('mouseup', that.events.removeMovingClass);
    };
    that.getCoordsFromWorld = function(event, index) {
        event.preventDefault();
        var point;

        that.three.mouse.x = ( event.clientX / that.three.rendererGL.domElement.clientWidth ) * 2 - 1;
        that.three.mouse.y = -( event.clientY / that.three.rendererGL.domElement.clientHeight ) * 2 + 1;

        that.three.raycaster.setFromCamera(that.three.mouse, that.three.camera);

        var intersects = that.three.raycaster.intersectObjects(that.three.sceneGL.children);

        if(intersects.length > 0) {
            if(!intersects[0].face) intersects[0] = intersects[1];

            point = intersects[0].point;
            return point;
        }
    };
    that.changeMode = function(mode) {
        var that = this;

        if(mode){
            that.mode = mode;
        } else {
            that.mode = that.mode == 'vr' ? 'desktop' : 'vr';
        }

        if(that.mode == 'vr' && !that.effect) {
            var effect = new THREE.StereoEffect( that.three.rendererGL );
            effect.setSize( window.innerWidth, window.innerHeight );

            that.effect = effect;
        }

        that.rerender();
        that.events.resize();
    };
    that.rerender = function(){

        document.body.removeChild(document.querySelector('#renderer-css'));

        that.three.rendererCSS = that.mode == 'vr' ? new THREE.CSS3DStereoRenderer() : new THREE.CSS3DRenderer();
        that.three.rendererCSS.setSize(window.innerWidth, window.innerHeight);
        that.three.rendererCSS.domElement.id = 'renderer-css';

        that.three.rendererCSS.domElement.appendChild(that.three.rendererGL.domElement);

        that.container.appendChild(that.three.rendererCSS.domElement);

        that.selectWorld(that.selectedWorld());

    };
    that.animate = function() {
        requestAnimationFrame(that.animate);

        that.three.rendererGL.render(that.three.sceneGL, that.three.camera);
        that.three.rendererCSS.render(that.three.sceneCSS, that.three.camera);

        if(that.mode == 'vr')
            that.effect && that.effect.render(that.three.sceneGL, that.three.camera);

        if(that.configs.controls)
            that.three.controls.update();
    };
    that.init();
};

POP.prototype.addHtml = function(params) {
    var that = this,
        htmlObject = new THREE.CSS3DObject(params.content);

    params.content.setAttribute('world', params.world);
    params.content.setAttribute('x', params.x);
    params.content.setAttribute('y', params.y);
    params.content.setAttribute('z', params.z);

    htmlObject.position.z = params.z || 0;
    htmlObject.position.y = params.y || 0;
    htmlObject.position.x = params.x || 0;

    htmlObject.element = params.content;
    htmlObject.index = that.elements.length;
    params.content.object = htmlObject;

    htmlObject.lookAt(that.three.camera.position);

    // -- Adding the HTML Content to scene -- //
    that.three.sceneCSS.add(htmlObject);
    that.elements.push(htmlObject);
};
POP.prototype.add3dObject = function(params) {
    // :TODO -- This function supports .obj, .js, .collada model formats -- //
    var that = this;
};
<|endoftext|>


<commit_before>"use strict";

const fs = require("fs"),
      path = require('path'),
      pug = require('pug'),
      compose_path = (...parts) => path.join(...parts),
      build_path = compose_path(__dirname, "build", "html"),
      pugdir = compose_path(__dirname, 'src', 'pug', 'pages'),
      compile_pug = () => fs.readdir(pugdir, function (error, files) {
        if (error) {
          console.log(error);
        } else {
          files.forEach(function (fname) {
            fs.open(
              compose_path(
                build_path,
                fname.split('.pug')[0] + '.htm'
              ),
              'w',
              function (error, fd) {
                if (error) {
                  console.log(error);
                } else {
                  fs.write(
                    fd,
                    pug.compileFile(compose_path(pugdir, fname), {
                      //"debug": true,
                      "pretty": true,
                    })(),
                    (error) => (error !== null) && console.log(error)
                  );
                }
              }
            );
          });
        }
      }),
      check_or_create = (a, b) => (
        fs.stat(a, function (error) {
          if (error) {
            fs.lstat(a, function (error) {
              if (error) {
                fs.mkdir(a, function (error) {
                  if (error) {
                    console.log(error);
                  } else {
                    console.log(a, "directory created");
                    if (b)
                      check_or_create(compose_path(a, b));
                    else
                      compile_pug();
                  }
                });
              } else {
                console.log(a, "exist");
                if (b)
                  check_or_create(compose_path(a, b));
                else
                  compile_pug();
              }
            });
          } else {
            console.log(a, "exist");
            if (b)
              check_or_create(compose_path(a, b));
            else
              compile_pug();
          }
        }));

check_or_create(compose_path(__dirname, "build"), "html");
<commit_msg>html generation script fix<commit_after>"use strict";

const fs = require("fs"),
      path = require('path'),
      pug = require('pug'),
      compose_path = (...parts) => path.join(...parts),
      build_path = compose_path(__dirname, "build", "html"),
      pugdir = compose_path(__dirname, 'src', 'pug', 'pages'),
      compile_pug = () => fs.readdir(pugdir, function (error, files) {
        if (error) {
          console.log(error);
        } else {
          files.forEach(function (fname) {
            if (fname.length > 4
              && fname.indexOf('.pug', fname.length - 4) !== -1) {
              fs.open(
                compose_path(
                  build_path,
                  fname.split('.pug')[0] + '.htm'
                ),
                'w',
                function (error, fd) {
                  if (error) {
                    console.log(error);
                  } else {
                    fs.write(
                      fd,
                      pug.compileFile(compose_path(pugdir, fname), {
                        //"debug": true,
                        "pretty": true,
                      })(),
                      (error) => (error !== null) && console.log(error)
                    );
                  }
                }
              );
            }
          });
        }
      }),
      check_or_create = (a, b) => (
        fs.stat(a, function (error) {
          if (error) {
            fs.lstat(a, function (error) {
              if (error) {
                fs.mkdir(a, function (error) {
                  if (error) {
                    console.log(error);
                  } else {
                    console.log(a, "directory created");
                    if (b)
                      check_or_create(compose_path(a, b));
                    else
                      compile_pug();
                  }
                });
              } else {
                console.log(a, "exist");
                if (b)
                  check_or_create(compose_path(a, b));
                else
                  compile_pug();
              }
            });
          } else {
            console.log(a, "exist");
            if (b)
              check_or_create(compose_path(a, b));
            else
              compile_pug();
          }
        }));

check_or_create(compose_path(__dirname, "build"), "html");
<|endoftext|>