<commit_before>$(document).ready(function() {
  var rotator = new ImageRotator();
  rotator.init();
  var rotationTimer = setInterval(rotator.cycleImages, 4000);

  if (window.location.pathname !== '/') {
    $(".blog-hide").hide();
    $('.navbar.navbar-fixed-top').css("background-color", "#76323F")
  }

  // change navbar color based on scroll
  $(window).scroll(function() {
    if (window.location.pathname === '/') {
      if ($(window).scrollTop() > 946) {
        $('.navbar.navbar-fixed-top, .nav-item > a.anchor-tag').css("background-color", "#76323F");
      } else {
        $('.navbar.navbar-fixed-top, .nav-item > a.anchor-tag').css("background-color", "transparent");
      }
    }
  });

  //debug bootsrap nav
  $('.anchor-tag').mouseleave(function() {
    if ($(window).scrollTop() > 946) {
      $($(this)).css("background-color", "#76323F");
    } else {
      $($(this)).css("background-color", "transparent");
    }
  });

  // close mobile dropdown after link click
  $('.anchor-tag').on('click', function(){
    $('.navbar-toggle').click();
  });

  //smooth scroll
  function smoothScroll(target) {
    $('html, body').animate({
        scrollTop: $($(target).attr('href')).offset().top - 100
    }, 500);
  }

  $('.anchor-tag').click(function() {
    smoothScroll(this);
    return false;
  });

  $(".contact-info-btn").click(function() {
    $(this).siblings().removeClass("active");
    $(this).addClass("active");
    $(".info-display").replaceWith("
"+$(this).data().text+"
");
  });

  // $('#about').mouseover(function() {
  //   $(this).addClass('animated bounceOutLeft');
  // })
});

function ImageRotator() {
  var $image = $('.image-rotator');
  var currentUrl = 0;
  var imageUrls = [];

  this.init = function() {
    setInitialImage(window.location.pathname);
    setImageUrls(window.location.pathname);
  }

  this.cycleImages = function () {
    currentUrl++;
    if (currentUrl === imageUrls.length) {
      currentUrl = 0;
    }
    animate(imageUrls[currentUrl]);
  };

  function googleBucketUrlFrom(url) {
    return "https://storage.googleapis.com/john-hess/portfolio/"+url+".png";
  }

  function animate(url) {
    $image.fadeOut(1500, function() {
      $image.attr("src", googleBucketUrlFrom(url));
      $image.fadeIn(1500);
    });
  }

  function setImageUrls(location) {
    if (location === '/portfolio/west-coast-skateparks/') {
      imageUrls = ['wcs', 'wcs2', 'wcs3', 'wcs4'];
    } else if (location === '/portfolio/music-tree/') {
      imageUrls = ['mt', 'mt2', 'mt3', 'mt4'];
    } else if (location === '/portfolio/repo-ranker/') {
      imageUrls = ['rr', 'rr2', 'rr3'];
    }
  }

  function setInitialImage(location) {
    if (location === '/portfolio/west-coast-skateparks/') {
      $image.attr("src", googleBucketUrlFrom('wcs'));
    } else if (location === '/portfolio/music-tree/') {
      $image.attr("src", googleBucketUrlFrom('mt'));
    } else if (location === '/portfolio/repo-ranker/') {
      $image.attr("src", googleBucketUrlFrom('rr'));
    }
  }
}
<commit_msg>add more js to contact info<commit_after>$(document).ready(function() {
  var rotator = new ImageRotator();
  rotator.init();
  var rotationTimer = setInterval(rotator.cycleImages, 4000);

  if (window.location.pathname !== '/') {
    $(".blog-hide").hide();
    $('.navbar.navbar-fixed-top').css("background-color", "#76323F")
  }

  // change navbar color based on scroll
  $(window).scroll(function() {
    if (window.location.pathname === '/') {
      if ($(window).scrollTop() > 946) {
        $('.navbar.navbar-fixed-top, .nav-item > a.anchor-tag').css("background-color", "#76323F");
      } else {
        $('.navbar.navbar-fixed-top, .nav-item > a.anchor-tag').css("background-color", "transparent");
      }
    }
  });

  //debug bootsrap nav
  $('.anchor-tag').mouseleave(function() {
    if ($(window).scrollTop() > 946) {
      $($(this)).css("background-color", "#76323F");
    } else {
      $($(this)).css("background-color", "transparent");
    }
  });

  // close mobile dropdown after link click
  $('.anchor-tag').on('click', function(){
    $('.navbar-toggle').click();
  });

  //smooth scroll
  function smoothScroll(target) {
    $('html, body').animate({
        scrollTop: $($(target).attr('href')).offset().top - 100
    }, 500);
  }

  $('.anchor-tag').click(function() {
    smoothScroll(this);
    return false;
  });

  // contact info
  $(".contact-info-btn").click(function() {
    $(this).siblings().removeClass("active");
    $(this).addClass("active");
    displayContactInfo($(this).data().text);
  });

  $(".contact-info-btn").mouseover(function() {
    displayContactInfo($(this).data().text);
  });

  $(".contact-info-btn").mouseleave(function() {
    displayContactInfo($(".contact-info-btn.active").data().text);
  });

  function displayContactInfo(info) {
    $(".info-display").replaceWith("
"+info+"
");
  }
});

function ImageRotator() {
  var $image = $('.image-rotator');
  var currentUrl = 0;
  var imageUrls = [];

  this.init = function() {
    setInitialImage(window.location.pathname);
    setImageUrls(window.location.pathname);
  }

  this.cycleImages = function () {
    currentUrl++;
    if (currentUrl === imageUrls.length) {
      currentUrl = 0;
    }
    animate(imageUrls[currentUrl]);
  };

  function googleBucketUrlFrom(url) {
    return "https://storage.googleapis.com/john-hess/portfolio/"+url+".png";
  }

  function animate(url) {
    $image.fadeOut(1500, function() {
      $image.attr("src", googleBucketUrlFrom(url));
      $image.fadeIn(1500);
    });
  }

  function setImageUrls(location) {
    if (location === '/portfolio/west-coast-skateparks/') {
      imageUrls = ['wcs', 'wcs2', 'wcs3', 'wcs4'];
    } else if (location === '/portfolio/music-tree/') {
      imageUrls = ['mt', 'mt2', 'mt3', 'mt4'];
    } else if (location === '/portfolio/repo-ranker/') {
      imageUrls = ['rr', 'rr2', 'rr3'];
    }
  }

  function setInitialImage(location) {
    if (location === '/portfolio/west-coast-skateparks/') {
      $image.attr("src", googleBucketUrlFrom('wcs'));
    } else if (location === '/portfolio/music-tree/') {
      $image.attr("src", googleBucketUrlFrom('mt'));
    } else if (location === '/portfolio/repo-ranker/') {
      $image.attr("src", googleBucketUrlFrom('rr'));
    }
  }
}
<|endoftext|>


<commit_before>var iconv = require('iconv-lite');
var net = require('net');
var util = require('./index');
var config = require('../config');

if (!(config.reqCacheSize > 0) || config.reqCacheSize < 512) {
  config.reqCacheSize = 512;
}

if (!(config.frameCacheSize > 0) || config.frameCacheSize < 512) {
  config.frameCacheSize = 512;
}

var TIMEOUT = 36000;
var CLEAR_INTERVAL = 5000;
var CACHE_TIME = CLEAR_INTERVAL * 2;
var MAX_LENGTH = config.reqCacheSize;
var MIN_LENGTH = MAX_LENGTH - 100;
var MAX_FRAMES_LENGTH = config.frameCacheSize;
var COUNT = 100;
var count = 0;
var ids = [];
var reqData = {};
var frames = [];
var proxy, binded, timeout, interval;

function disable() {
  proxy.removeListener('request', handleRequest);
  proxy.removeListener('frame', handleFrame);
  ids = [];
  reqData = {};
  frames = [];
  interval && clearInterval(interval);
  interval = null;
  binded = false;
}

function enable() {
  if (!binded) {
    binded = true;
    proxy.on('request', handleRequest);
    proxy.on('frame', handleFrame);
  }
  clearTimeout(timeout);
  timeout = setTimeout(disable, TIMEOUT);
  if (!interval) {
    interval = setInterval(clearCache, CLEAR_INTERVAL);
  }
}

/**
* 如果超过最大缓存数，清理如下请求数据：
* 1. 已经请求结束且结束时间超过10秒
* 2. 请求#1前面的未结束且未被ui读取过的请求
*/
function clearCache() {
  if (frames.length > MAX_FRAMES_LENGTH) {
    frames.splice(0, 100);
  }
  var len = ids.length;
  if (len <= MAX_LENGTH) {
    return;
  }

  var index = -1; //已经完成，且缓存超过10s的最后一个请求
  var now = Date.now();
  var i, curData;
  for (i = len - 1; i >= 0; i--) {
    curData = reqData[ids[i]];
    if (curData.endTime && now - curData.endTime > TIMEOUT) {
      index = i;
      break;
    }
  }

  if (index < 0) {
    return;
  }

  var _ids = [];
  ++index;
  for (i = 0; i < index; i++) {
    var id = ids[i];
    curData = reqData[id];
    if (curData.read && (!curData.endTime || now - curData.endTime < CACHE_TIME
        || now - curData.startTime < TIMEOUT)) {
      _ids.push(id);
    } else {
      delete reqData[id];
      if (--len <= MIN_LENGTH) {
        _ids.push.apply(_ids, ids.slice(i + 1, index));
        break;
      }
    }
  }
  ids = _ids.concat(ids.slice(index));
}

function getIds(startTime, count, lastRowId) {
  var len = ids.length;
  if (!len) {
    return [];
  }
  startTime = startTime || lastRowId;
  if (!startTime) {
    return ids.slice(-count);
  }
  for (var i = 0; i < len; i++) {
    if (ids[i] === startTime) {
      return ids.slice(i + 1, i + 1 + count);
    }
  }
  return ids.slice(0, count);
}

function getList(ids) {
  if (!Array.isArray(ids)) {
    return [];
  }
  return ids.map(function(id, i) {
    var curData = reqData[id];
    if (curData) {
      curData.read = true;
    }
    return curData;
  });
}

function handleRequest(req) {
  var curData = req.data;
  var id = curData.id = curData.id || (curData.startTime + '-' + ++count);
  reqData[id] = curData;
  ids.indexOf(id) === -1 && ids.push(id);
}

function decodeData(frame) {
  if (frame.text != null) {
    return frame;
  }
  if (frame.bin) {
    var result = [];
    frame.bin.forEach(function(b) {
      b = b.toString(16).toUpperCase();
      result.push(b.length > 1 ? b : '0' + b);
    });
    try {
      frame.text = iconv.decode(frame.bin, frame.charset || 'utf8');
    } catch (e) {
      frame.text = frame.bin + '';
    }
    frame.bin = result.join('');
  } else {
    frame.bin = frame.text = '';
  }

  return frame;
}
function handleFrame(data) {
  frames.push(data);
}

function getFrames(curReqId, lastFrameId) {
  if (!curReqId) {
    return;
  }
  var result = [];
  var count = 10;
  for (var i = frames.length - 1; i >= 0; i--) {
    var frame = frames[i];
    if (frame.reqId === curReqId && (lastFrameId ? frame.frameId > lastFrameId : count > 0)) {
      result.push(decodeData(frame));
      if (--count <= 0) {
        break;
      }
    }
  }
  return result.reverse();
}

module.exports = function init(_proxy) {
  proxy = _proxy;
/**
* options: {
* 		startTime: timestamp || timestamp + '-' + count
* 		count: 获取新数据的数量
* 		ids: 请未结束的id列表
* }
*
* @param options
*/
  function formatFilter(filter, clientIp) {
    if (!filter) {
      return;
    }
    var url = util.trimStr(filter.url).toLowerCase();
    var name = util.trimStr(filter.name).toLowerCase();
    var value = util.trimStr(filter.value).toLowerCase();
    var ip = util.trimStr(filter.ip);
    var list = [];
    if (ip === 'self') {
      ip = clientIp;
    } else if (ip && !net.isIP(ip)) {
      ip.split(',').forEach(function(item) {
        item = item.trim();
        if (item === 'self') {
          item = clientIp;
        }
        if (net.isIP(item) && list.indexOf(item) === -1) {
          list.push(item);
        }
      });
      ip = null;
    }
    var result;
    if (url) {
      result = {};
      result.url = url;
    }
    if (name && value) {
      result = result || {};
      result.name = name;
      result.value = value;
    }
    if (ip) {
      result = result || {};
      result.ip = ip;
    }
    if (list.length) {
      result = result || {};
      result.ipList = list.slice(0, 16);
    }
    return result;
  }
  function checkClientIp(item, filter) {
    var clientIp = item.req.ip;
    if (filter.ip && clientIp !== filter.ip) {
      return false;
    }
    var ipList = filter.ipList;
    if (!ipList) {
      return true;
    }
    var len = ipList.length;
    if (len < 3) {
      if (ipList[0] === clientIp) {
        return true;
      }
      if (ipList[1] && ipList[1] === clientIp) {
        return true;
      }
    } else {
      for (var i = 0; i < len; i++) {
        var ip = ipList[i];
        if (ip === clientIp) {
          return true;
        }
      }
    }
    return false;
  }
  function checkItem(item, filter) {
    if (!item) {
      return false;
    }
    if (!checkClientIp(item, filter)) {
      return false;
    }
    if (filter.url && item.url.toLowerCase().indexOf(filter.url) === -1) {
      return false;
    }
    if (!filter.name) {
      return true;
    }
    var value = item.req.headers[filter.name];
    if (!value || typeof value !== 'string') {
      if (!Array.isArray(value)) {
        return false;
      }
      value = value.join('\n');
    }
    value = value.toLowerCase();
    if (value.indexOf(filter.value) !== -1) {
      return true;
    }
    return value.indexOf(util.encodeURIComponent(filter.value).toLowerCase()) !== -1;
  }
  proxy.getData = function(options, clientIp) {
    enable();
    options = options || {};
    var data = {};
    var newIds = options.startTime == -1 ? [] : getIds(options.startTime, options.count, options.lastRowId);
    var setData = function(item) {
      if (item) {
        if (config.secureFilter) {
          try {
            item = config.secureFilter(item) || item;
          } catch (e) {}
        }
        data[item.id] = item;
      }
    };
    if (newIds.length > 0) {
      var filter = formatFilter(options, clientIp);
      if (filter) {
        var count = options.count > 0 ? options.count : COUNT;
        var id = newIds[0];
        var index = ids.indexOf(newIds[0]);
        newIds = [];
        while(id && count > 0) {
          var item = reqData[id];
          if (checkItem(item, filter)) {
            setData(item);
            newIds.push(id);
            --count;
          }
          id = ids[++index];
        }
      } else if (!filter) {
        getList(newIds).forEach(setData);
      }
    }
    getList(options.ids).forEach(setData);
    return {
      ids: options.ids || [],
      newIds: newIds,
      data: data,
      lastId: newIds[newIds.length - 1] || ids[ids.length - 1],
      frames: getFrames(options.curReqId, options.lastFrameId)
    };
  };
};
<commit_msg>refactor: Add logger<commit_after>var iconv = require('iconv-lite');
var net = require('net');
var util = require('./index');
var logger = require('./logger');
var config = require('../config');

if (!(config.reqCacheSize > 0) || config.reqCacheSize < 512) {
  config.reqCacheSize = 512;
}

if (!(config.frameCacheSize > 0) || config.frameCacheSize < 512) {
  config.frameCacheSize = 512;
}

var TIMEOUT = 36000;
var CLEAR_INTERVAL = 5000;
var CACHE_TIME = CLEAR_INTERVAL * 2;
var MAX_LENGTH = config.reqCacheSize;
var MIN_LENGTH = MAX_LENGTH - 100;
var MAX_FRAMES_LENGTH = config.frameCacheSize;
var COUNT = 100;
var count = 0;
var ids = [];
var reqData = {};
var frames = [];
var proxy, binded, timeout, interval;

function disable() {
  proxy.removeListener('request', handleRequest);
  proxy.removeListener('frame', handleFrame);
  ids = [];
  reqData = {};
  frames = [];
  interval && clearInterval(interval);
  interval = null;
  binded = false;
}

function enable() {
  if (!binded) {
    binded = true;
    proxy.on('request', handleRequest);
    proxy.on('frame', handleFrame);
  }
  clearTimeout(timeout);
  timeout = setTimeout(disable, TIMEOUT);
  if (!interval) {
    interval = setInterval(clearCache, CLEAR_INTERVAL);
  }
}

/**
* 如果超过最大缓存数，清理如下请求数据：
* 1. 已经请求结束且结束时间超过10秒
* 2. 请求#1前面的未结束且未被ui读取过的请求
*/
function clearCache() {
  if (frames.length > MAX_FRAMES_LENGTH) {
    frames.splice(0, 100);
  }
  var len = ids.length;
  if (len <= MAX_LENGTH) {
    return;
  }

  var index = -1; //已经完成，且缓存超过10s的最后一个请求
  var now = Date.now();
  var i, curData;
  for (i = len - 1; i >= 0; i--) {
    curData = reqData[ids[i]];
    if (curData.endTime && now - curData.endTime > TIMEOUT) {
      index = i;
      break;
    }
  }

  if (index < 0) {
    return;
  }

  var _ids = [];
  ++index;
  for (i = 0; i < index; i++) {
    var id = ids[i];
    curData = reqData[id];
    if (curData.read && (!curData.endTime || now - curData.endTime < CACHE_TIME
        || now - curData.startTime < TIMEOUT)) {
      _ids.push(id);
    } else {
      delete reqData[id];
      if (--len <= MIN_LENGTH) {
        _ids.push.apply(_ids, ids.slice(i + 1, index));
        break;
      }
    }
  }
  ids = _ids.concat(ids.slice(index));
}

function getIds(startTime, count, lastRowId) {
  var len = ids.length;
  if (!len) {
    return [];
  }
  startTime = startTime || lastRowId;
  if (!startTime) {
    return ids.slice(-count);
  }
  for (var i = 0; i < len; i++) {
    if (ids[i] === startTime) {
      return ids.slice(i + 1, i + 1 + count);
    }
  }
  return ids.slice(0, count);
}

function getList(ids) {
  if (!Array.isArray(ids)) {
    return [];
  }
  return ids.map(function(id, i) {
    var curData = reqData[id];
    if (curData) {
      curData.read = true;
    }
    return curData;
  });
}

function handleRequest(req) {
  var curData = req.data;
  var id = curData.id = curData.id || (curData.startTime + '-' + ++count);
  reqData[id] = curData;
  ids.indexOf(id) === -1 && ids.push(id);
}

function decodeData(frame) {
  if (frame.text != null) {
    return frame;
  }
  if (frame.bin) {
    var result = [];
    frame.bin.forEach(function(b) {
      b = b.toString(16).toUpperCase();
      result.push(b.length > 1 ? b : '0' + b);
    });
    try {
      frame.text = iconv.decode(frame.bin, frame.charset || 'utf8');
    } catch (e) {
      frame.text = frame.bin + '';
    }
    frame.bin = result.join('');
  } else {
    frame.bin = frame.text = '';
  }

  return frame;
}
function handleFrame(data) {
  frames.push(data);
}

function getFrames(curReqId, lastFrameId) {
  if (!curReqId) {
    return;
  }
  var result = [];
  var count = 10;
  for (var i = frames.length - 1; i >= 0; i--) {
    var frame = frames[i];
    if (frame.reqId === curReqId && (lastFrameId ? frame.frameId > lastFrameId : count > 0)) {
      result.push(decodeData(frame));
      if (--count <= 0) {
        break;
      }
    }
  }
  return result.reverse();
}

module.exports = function init(_proxy) {
  proxy = _proxy;
/**
* options: {
* 		startTime: timestamp || timestamp + '-' + count
* 		count: 获取新数据的数量
* 		ids: 请未结束的id列表
* }
*
* @param options
*/
  function formatFilter(filter, clientIp) {
    if (!filter) {
      return;
    }
    var url = util.trimStr(filter.url).toLowerCase();
    var name = util.trimStr(filter.name).toLowerCase();
    var value = util.trimStr(filter.value).toLowerCase();
    var ip = util.trimStr(filter.ip);
    var list = [];
    if (ip === 'self') {
      ip = clientIp;
    } else if (ip && !net.isIP(ip)) {
      ip.split(',').forEach(function(item) {
        item = item.trim();
        if (item === 'self') {
          item = clientIp;
        }
        if (net.isIP(item) && list.indexOf(item) === -1) {
          list.push(item);
        }
      });
      ip = null;
    }
    var result;
    if (url) {
      result = {};
      result.url = url;
    }
    if (name && value) {
      result = result || {};
      result.name = name;
      result.value = value;
    }
    if (ip) {
      result = result || {};
      result.ip = ip;
    }
    if (list.length) {
      result = result || {};
      result.ipList = list.slice(0, 16);
    }
    return result;
  }
  function checkClientIp(item, filter) {
    var clientIp = item.req.ip;
    if (filter.ip && clientIp !== filter.ip) {
      return false;
    }
    var ipList = filter.ipList;
    if (!ipList) {
      return true;
    }
    var len = ipList.length;
    if (len < 3) {
      if (ipList[0] === clientIp) {
        return true;
      }
      if (ipList[1] && ipList[1] === clientIp) {
        return true;
      }
    } else {
      for (var i = 0; i < len; i++) {
        var ip = ipList[i];
        if (ip === clientIp) {
          return true;
        }
      }
    }
    return false;
  }
  function checkItem(item, filter) {
    if (!item) {
      return false;
    }
    if (!checkClientIp(item, filter)) {
      return false;
    }
    if (filter.url && item.url.toLowerCase().indexOf(filter.url) === -1) {
      return false;
    }
    if (!filter.name) {
      return true;
    }
    var value = item.req.headers[filter.name];
    if (!value || typeof value !== 'string') {
      if (!Array.isArray(value)) {
        return false;
      }
      value = value.join('\n');
    }
    value = value.toLowerCase();
    if (value.indexOf(filter.value) !== -1) {
      return true;
    }
    return value.indexOf(util.encodeURIComponent(filter.value).toLowerCase()) !== -1;
  }
  proxy.getData = function(options, clientIp) {
    enable();
    options = options || {};
    var data = {};
    var newIds = options.startTime == -1 ? [] : getIds(options.startTime, options.count, options.lastRowId);
    var setData = function(item) {
      if (item) {
        if (config.secureFilter) {
          try {
            item = config.secureFilter(item) || item;
          } catch (e) {
            if (config.debugMode) {
              /* eslint-disable no-console */
              console.log(e);
            }
            logger.error(e);
          }
        }
        data[item.id] = item;
      }
    };
    if (newIds.length > 0) {
      var filter = formatFilter(options, clientIp);
      if (filter) {
        var count = options.count > 0 ? options.count : COUNT;
        var id = newIds[0];
        var index = ids.indexOf(newIds[0]);
        newIds = [];
        while(id && count > 0) {
          var item = reqData[id];
          if (checkItem(item, filter)) {
            setData(item);
            newIds.push(id);
            --count;
          }
          id = ids[++index];
        }
      } else if (!filter) {
        getList(newIds).forEach(setData);
      }
    }
    getList(options.ids).forEach(setData);
    return {
      ids: options.ids || [],
      newIds: newIds,
      data: data,
      lastId: newIds[newIds.length - 1] || ids[ids.length - 1],
      frames: getFrames(options.curReqId, options.lastFrameId)
    };
  };
};
<|endoftext|>


<commit_before>/**
 * Created by Awesome on 1/30/2016.
 */

// use strict
'use strict';

// require dependencies
var os       = require ('os');
var parse    = require ('comment-parser');
var safeEval = require ('safe-eval');

/**
 * build config pipe
 */
class configUtil {
    /**
     * construct config pipe
     */
    constructor () {
        // bind methods
        this.pipe   = this.pipe.bind (this);
        this.config = this.config.bind (this);

        // bind tag methods
        this._fn       = this._fn.bind (this);
        this._acl      = this._acl.bind (this);
        this._name     = this._name.bind (this);
        this._class    = this._class.bind (this);
        this._menus    = this._menus.bind (this);
        this._routes   = this._routes.bind (this);
        this._mounts   = this._mounts.bind (this);
        this._parent   = this._parent.bind (this);
        this._sockets  = this._sockets.bind (this);
        this._priority = this._priority.bind (this);

        // bind loop methods
        this._loopRoutes = this._loopRoutes.bind (this);
        this._loopMenus  = this._loopMenus.bind (this);

        // bind private methods
        this._merge      = this._merge.bind (this);
        this._parseRoute = this._parseRoute.bind (this);
    }

    /**
     * pipe function
     *
     * @param chunk
     */
    pipe (chunk) {
        var that     = this;
        let content  = chunk.contents.toString ();
        let parsed   = parse (content);
        let lines    = content.split (os.EOL);

        // complete pipe loop
        return new Promise ((resolve, reject) => {
            // resolve with new config
            resolve (that.config (chunk, parsed, lines));
        });
    }

    /**
     * routes
     *
     * @param chunk
     * @param parsed
     * @param lines
     * @returns {{}}
     */
    config (chunk, parsed, lines) {
        var that      = this;
        var dPriority = 10;
        var priority  = dPriority;
        var acl       = false;
        var mounts    = [];
        var rtn       = {
            'sockets' : {},
            'routes'  : {},
            'menus'   : {},
            'acl'     : {}
        };

        // loop parsed
        for (var i = 0; i < parsed.length; i++) {
            // set scoped variables
            let obj  = parsed[i];
            let tags = parsed[i].tags;

            // check for class
            var isClass = that._class (obj.line, lines);
            if (isClass) {
                acl      = that._acl (tags);
                mounts   = that._mounts (tags);
                priority = that._priority (tags, dPriority);
            }

            // check for route
            var isFn = that._fn (obj.line, lines);

            // if is function
            if (isFn) {
                // get function level priority
                priority   = that._priority (tags, priority);
                var routes = that._routes (tags);

                // check if routes length
                if (routes) {
                    // force mount
                    if (!mounts.length) {
                        mounts = ['/'];
                    }

                    // loop routes
                    var routeLoop = that._loopRoutes (routes, mounts, priority, acl, chunk, isFn);
                    rtn.routes    = that._merge (rtn.routes, routeLoop.routes);
                    rtn.acl       = that._merge (rtn.acl, routeLoop.acl);

                    // get array of menus in tags
                    var isMenu = that._menus (tags);

                    // chekc if menus exist
                    if (isMenu) {
                        rtn.menus = that._merge (rtn.menus, that._loopMenus (isMenu, mounts, priority, routes, rtn.acl));
                    }
                }

                // get array of sockets in tags
                var isSocket = that._sockets (tags);

                // chekc if menus exist
                if (isSocket) {
                    rtn.sockets = that._merge (rtn.sockets, that._loopSockets (isSocket, priority, acl, chunk, isFn));
                }
            }
        }

        // return rtn
        return rtn;
    }

    /**
     * checks if comment attached to function
     *
     * @param line
     * @param lines
     * @returns {boolean}
     * @private
     */
    _fn (line, lines) {
        // set variables
        var isFn = false;

        // loop check if class
        while (!isFn) {
            // add to line
            line++;

            // check next line exists
            if (!lines[line]) {
                break;
            }

            // check if function
            if (lines[line].indexOf ('(') > -1 && lines[line].indexOf (')') > -1) {
                isFn = lines[line].split ('(')[0].trim ();
                if (isFn.indexOf ('*') > -1) {
                    isFn = isFn.split ('*')[1].trim ();
                }
            } else if (lines[line].indexOf ('*') === -1) {
                break;
            }
        }

        // return class
        return isFn;
    }

    /**
     * checks if comment attached to class
     *
     * @param line
     * @param lines
     * @returns {boolean}
     * @private
     */
    _class (line, lines) {
        // set variables
        var isClass = false;

        // loop check if class
        while (!isClass) {
            // add to line
            line++;

            // check next line exists
            if (!lines[line]) {
                break;
            }

            // check if class
            if (lines[line].indexOf('class') > -1 && lines[line].indexOf('*') == -1) {
                isClass = lines[line].split('class')[1].split('extends')[0].trim();
            } else if (lines[line].indexOf('*') === -1) {
                break;
            }
        }

        // return class
        return isClass;
    }

    /**
     * checks for menus
     *
     * @param tags
     * @returns {*}
     * @private
     */
    _menus (tags) {
        // set mounts
        var menus = [];

        // loop tags for mount
        for (var i = 0; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if mount
            if (tag.tag == 'menu') {
                var acl = this._acl (tags);
                menus.push ({
                    'title'    : (tag.name + ' ' + tag.description).trim (),
                    'name'     : this._name (tags, tag.name, i),
                    'menu'     : tag.type,
                    'parent'   : this._parent (tags, false, i),
                    'priority' : this._priority (tags, 10),
                    'acl'      : acl || false
                });
            }
        }

        // return false
        return menus.length ? menus : false;
    }

    /**
     * checks for sockets
     *
     * @param tags
     * @returns {*}
     * @private
     */
    _sockets (tags) {
        // set mounts
        var sockets = [];

        // loop tags for mount
        for (var i = 0; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if mount
            if (tag.tag == 'socket') {
                var acl = this._acl(tags);
                sockets.push({
                    'type'     : tag.type,
                    'priority' : this._priority(tags, 10),
                    'acl'      : (acl ? acl : false)
                });
            }
        }

        // return false
        return sockets.length ? sockets : false;
    }

    /**
     * returns acl array for tag
     *
     * @param tags
     * @returns {*}
     * @private
     */
    _acl (tags) {
        // loop tags for priority
        for (var i = 0; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if priority
            if (tag.tag == 'acl') {
                return safeEval ('({' + tag.type + '})');
            }
        }

        // return default priority
        return false;
    }

    /**
     * check for mounts
     *
     * @param tags
     * @returns {*}
     * @private
     */
    _mounts (tags) {
        // set mounts
        var mounts = [];

        // loop tags for mount
        for (var i = 0; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if mount
            if (tag.tag == 'mount') {
                mounts.push (tag.name);
            }
        }

        // return false
        return mounts.length ? mounts : false;
    }

    /**
     * checks for name
     *
     * @param tags
     * @param def
     * @param after
     * @returns {*}
     * @private
     */
    _name (tags, def, after) {
        // loop tags for priority
        for (var i = after; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if priority
            if (tag.tag == 'name') {
                return tag.name;
            }
        }

        // return default priority
        return def;
    }

    /**
     * checks for parent
     *
     * @param tags
     * @param def
     * @param after
     * @returns {*}
     * @private
     */
    _parent (tags, def, after) {
        // loop tags for priority
        for (var i = after; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if priority
            if (tag.tag == 'parent') {
                return tag.name;
            }
        }

        // return default priority
        return def;
    }

    /**
     * checks for priority
     *
     * @param tags
     * @param def
     * @returns {*}
     * @private
     */
    _priority (tags, def) {
        // loop tags for priority
        for (var i = 0; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if priority
            if (tag.tag == 'priority') {
                return parseInt (tag.name);
            }
        }

        // return default priority
        return def;
    }

    /**
     * checks for routes
     *
     * @param tags
     * @returns {*}
     * @private
     */
    _routes (tags) {
        // set mounts
        var routes = [];

        // loop tags for mount
        for (var i = 0; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if route
            if (tag.tag == 'route') {
                routes.push({
                    'type'  : tag.type,
                    'route' : tag.name,
                    'acl'   : this._acl (tags, i)
                });
            }
        }

        // return false
        return routes.length ? routes : false;
    }

    /**
    * loop routes for menu config object
    *
    * @param routes
    * @param mounts
    * @param priority
    * @param chunk
    * @param fn
    *
    * @returns {*}
    * @private
     */
    _loopRoutes (routes, mounts, priority, scopeAcl, chunk, fn) {
        // create return variable
        var rtn = {};
        var acl = {};

        // loop routes
        for (var i = 0; i < routes.length; i++) {
            /// loop mount points
            for (var y = 0; y < mounts.length; y++) {
                // ensure type object exists
                if (!rtn[priority]) {
                    rtn[priority] = {};
                }

                // ensure priority object exists
                if (!rtn[priority][routes[i].type]) {
                    rtn[priority][routes[i].type] = {};
                }

                // set acl route
                var rt = this._parseRoute (mounts[y] + routes[i].route);

                // ensure flattened acl
                if (!acl[rt]) {
                    acl[rt] = [];
                }
                // add acl to acl array
                if (routes[i].acl) {
                    acl[rt].push (routes[i].acl);
                }
                // check for scope acl
                if (scopeAcl) {
                    acl[rt].push (scopeAcl);
                }

                // remove acl if required
                if (!acl[rt].length) {
                    delete acl[rt];
                }

                // add route to array
                rtn[priority][(routes[i].type ? routes[i].type : 'get')][rt] = {
                    'controller' : '/' + (chunk.path.indexOf ('/app') > -1 ? 'app' : 'lib') + '/bundles' + chunk.path.split ('bundles')[1].replace (/\\/g, '/'),
                    'action'     : fn
                };
            }
        }

        // return object
        return {
            'routes' : rtn,
            'acl'    : acl
        };
    }

    /**
    * loop menus for menu config object
    *
    * @param menus
    * @param mounts
    * @param priority
    * @param routes
    * @param acl
    *
    * @returns {*}
    * @private
     */
    _loopMenus (menus, mounts, priority, routes, acl) {
        var rtn = {};

        // loop menus
        for (var m = 0; m < menus.length; m++) {
            // only use first route
            menus[m].route    = this._parseRoute (mounts[0] + routes[0].route);
            menus[m].priority = menus[m].priority || priority;

            // set acl
            var menuAcl = acl[menus[m].route] || false;
            if (menuAcl && menuAcl.length) {
                for (var a = 0; a < menuAcl.length; a++) {
                    if (! menus[m].acl || ! Array.isArray (menus[m].acl.test)) {
                      menus[m].acl = menuAcl[a];
                    } else if (Array.isArray (menus[m].acl.test)) {
                      menus[m].acl.test.concat (menuAcl[a].test, menus[m].acl.test);
                    }
                }
            }

            // set menu object
            if (!rtn[menus[m].menu]) {
                rtn[menus[m].menu] = {};
            }

            // set menu
            if (menus[m].parent) {
                if (!rtn[menus[m].menu][menus[m].parent]) {
                    rtn[menus[m].menu][menus[m].parent] = {
                        'title'    : menus[m].parent,
                        'children' : []
                    };
                }
                rtn[menus[m].menu][menus[m].parent].children.push (menus[m]);
            } else {
                if (rtn[menus[m].menu][menus[m].name]) {
                    for (var key in menus[m]) {
                        rtn[menus[m].menu][menus[m].name][key] = menus[m][key];
                    }
                } else {
                    rtn[menus[m].menu][menus[m].name] = menus[m];
                    rtn[menus[m].menu][menus[m].name].children = [];
                }
            }
        }

        // return object
        return rtn;
    }

    /**
    * loop sockets for socket config object
    *
    * @param sockets
    * @param priority
    * @param acl
    * @param chunk
    * @param fn
    *
    * @returns {*}
    * @private
     */
    _loopSockets (sockets, priority, acl, chunk, fn) {
        var rtn = {};

        // loop menu
        for (var s = 0; s < sockets.length; s++) {
            sockets[s].priority = sockets[s].priority ? sockets[s].priority : priority;

            // check for scoped acl
            if (acl) {
                if (!sockets[s].acl || !Array.isArray(sockets[s].acl.test)) {
                  sockets[s].acl = acl;
                } else if (Array.isArray(acl.test)) {
                  sockets[s].acl.test.concat(acl.test, sockets[s].acl.test);
                }
            }

            sockets[s].controller = '/' + (chunk.path.indexOf ('/app') > -1 ? 'app' : 'bin') + '/bundles' + chunk.path.split ('bundles')[1].replace (/\\/g, '/');
            sockets[s].socket     = fn;

            // set in return object
            rtn[sockets[s].type] = sockets[s];
        }

        // return sockets
        return rtn;
    }

    /**
    * Returns parsed route string
    *
    * @param route
    *
    * @returns {String}
    * @private
     */
    _parseRoute (route) {
        return '/' + route.split ('//').join ('/').replace (/^\/|\/$/g, '');
    }

    /**
     * merges two objects
     *
     * @param obj1
     * @param obj2
     * @returns {*}
     * @private
     */
    _merge (obj1, obj2) {
        for (var p in obj2) {
            try {
                // Property in destination object set; update its value.
                if (obj2[p].constructor == Object) {
                    obj1[p] = this._merge (obj1[p], obj2[p]);
                } else {
                    obj1[p] = obj2[p];
                }
            } catch (e) {
                // Property in destination object not set; create it and set its value.
                obj1[p] = obj2[p];
            }
        }

        return obj1;
    }
}

/**
 * export config pipe
 *
 * @type {configUtil}
 */
module.exports = new configUtil ();
<commit_msg>amend issues with menu name configuration<commit_after>/**
 * Created by Awesome on 1/30/2016.
 */

// use strict
'use strict';

// require dependencies
var os       = require ('os');
var parse    = require ('comment-parser');
var safeEval = require ('safe-eval');

/**
 * build config pipe
 */
class configUtil {
    /**
     * construct config pipe
     */
    constructor () {
        // bind methods
        this.pipe   = this.pipe.bind (this);
        this.config = this.config.bind (this);

        // bind tag methods
        this._fn       = this._fn.bind (this);
        this._acl      = this._acl.bind (this);
        this._name     = this._name.bind (this);
        this._class    = this._class.bind (this);
        this._menus    = this._menus.bind (this);
        this._routes   = this._routes.bind (this);
        this._mounts   = this._mounts.bind (this);
        this._parent   = this._parent.bind (this);
        this._sockets  = this._sockets.bind (this);
        this._priority = this._priority.bind (this);

        // bind loop methods
        this._loopRoutes = this._loopRoutes.bind (this);
        this._loopMenus  = this._loopMenus.bind (this);

        // bind private methods
        this._merge      = this._merge.bind (this);
        this._parseRoute = this._parseRoute.bind (this);
    }

    /**
     * pipe function
     *
     * @param chunk
     */
    pipe (chunk) {
        var that     = this;
        let content  = chunk.contents.toString ();
        let parsed   = parse (content);
        let lines    = content.split (os.EOL);

        // complete pipe loop
        return new Promise ((resolve, reject) => {
            // resolve with new config
            resolve (that.config (chunk, parsed, lines));
        });
    }

    /**
     * routes
     *
     * @param chunk
     * @param parsed
     * @param lines
     * @returns {{}}
     */
    config (chunk, parsed, lines) {
        var that      = this;
        var dPriority = 10;
        var priority  = dPriority;
        var acl       = false;
        var mounts    = [];
        var rtn       = {
            'sockets' : {},
            'routes'  : {},
            'menus'   : {},
            'acl'     : {}
        };

        // loop parsed
        for (var i = 0; i < parsed.length; i++) {
            // set scoped variables
            let obj  = parsed[i];
            let tags = parsed[i].tags;

            // check for class
            var isClass = that._class (obj.line, lines);
            if (isClass) {
                acl      = that._acl (tags);
                mounts   = that._mounts (tags);
                priority = that._priority (tags, dPriority);
            }

            // check for route
            var isFn = that._fn (obj.line, lines);

            // if is function
            if (isFn) {
                // get function level priority
                priority   = that._priority (tags, priority);
                var routes = that._routes (tags);

                // check if routes length
                if (routes) {
                    // force mount
                    if (!mounts.length) {
                        mounts = ['/'];
                    }

                    // loop routes
                    var routeLoop = that._loopRoutes (routes, mounts, priority, acl, chunk, isFn);
                    rtn.routes    = that._merge (rtn.routes, routeLoop.routes);
                    rtn.acl       = that._merge (rtn.acl, routeLoop.acl);

                    // get array of menus in tags
                    var isMenu = that._menus (tags);

                    // chekc if menus exist
                    if (isMenu) {
                        rtn.menus = that._merge (rtn.menus, that._loopMenus (isMenu, mounts, priority, routes, rtn.acl));
                    }
                }

                // get array of sockets in tags
                var isSocket = that._sockets (tags);

                // chekc if menus exist
                if (isSocket) {
                    rtn.sockets = that._merge (rtn.sockets, that._loopSockets (isSocket, priority, acl, chunk, isFn));
                }
            }
        }

        // return rtn
        return rtn;
    }

    /**
     * checks if comment attached to function
     *
     * @param line
     * @param lines
     * @returns {boolean}
     * @private
     */
    _fn (line, lines) {
        // set variables
        var isFn = false;

        // loop check if class
        while (!isFn) {
            // add to line
            line++;

            // check next line exists
            if (!lines[line]) {
                break;
            }

            // check if function
            if (lines[line].indexOf ('(') > -1 && lines[line].indexOf (')') > -1) {
                isFn = lines[line].split ('(')[0].trim ();
                if (isFn.indexOf ('*') > -1) {
                    isFn = isFn.split ('*')[1].trim ();
                }
            } else if (lines[line].indexOf ('*') === -1) {
                break;
            }
        }

        // return class
        return isFn;
    }

    /**
     * checks if comment attached to class
     *
     * @param line
     * @param lines
     * @returns {boolean}
     * @private
     */
    _class (line, lines) {
        // set variables
        var isClass = false;

        // loop check if class
        while (!isClass) {
            // add to line
            line++;

            // check next line exists
            if (!lines[line]) {
                break;
            }

            // check if class
            if (lines[line].indexOf('class') > -1 && lines[line].indexOf('*') == -1) {
                isClass = lines[line].split('class')[1].split('extends')[0].trim();
            } else if (lines[line].indexOf('*') === -1) {
                break;
            }
        }

        // return class
        return isClass;
    }

    /**
     * checks for menus
     *
     * @param tags
     * @returns {*}
     * @private
     */
    _menus (tags) {
        // set mounts
        var menus = [];

        // loop tags for mount
        for (var i = 0; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if mount
            if (tag.tag == 'menu') {
                var acl = this._acl (tags);
                menus.push ({
                    'title'    : (tag.name + ' ' + tag.description).trim (),
                    'name'     : this._name (tags, tag.name),
                    'menu'     : tag.type,
                    'parent'   : this._parent (tags, false, i),
                    'priority' : this._priority (tags, 10),
                    'acl'      : acl || false
                });
            }
        }

        // return false
        return menus.length ? menus : false;
    }

    /**
     * checks for sockets
     *
     * @param tags
     * @returns {*}
     * @private
     */
    _sockets (tags) {
        // set mounts
        var sockets = [];

        // loop tags for mount
        for (var i = 0; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if mount
            if (tag.tag == 'socket') {
                var acl = this._acl(tags);
                sockets.push({
                    'type'     : tag.type,
                    'priority' : this._priority(tags, 10),
                    'acl'      : (acl ? acl : false)
                });
            }
        }

        // return false
        return sockets.length ? sockets : false;
    }

    /**
     * returns acl array for tag
     *
     * @param tags
     * @returns {*}
     * @private
     */
    _acl (tags) {
        // loop tags for priority
        for (var i = 0; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if priority
            if (tag.tag == 'acl') {
                return safeEval ('({' + tag.type + '})');
            }
        }

        // return default priority
        return false;
    }

    /**
     * check for mounts
     *
     * @param tags
     * @returns {*}
     * @private
     */
    _mounts (tags) {
        // set mounts
        var mounts = [];

        // loop tags for mount
        for (var i = 0; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if mount
            if (tag.tag == 'mount') {
                mounts.push (tag.name);
            }
        }

        // return false
        return mounts.length ? mounts : false;
    }

    /**
     * checks for name
     *
     * @param tags
     * @param def
     * @param after
     * @returns {*}
     * @private
     */
    _name (tags, def) {
        // loop tags for priority
        for (var i = 0; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if priority
            if (tag.tag == 'name') {
                return tag.name;
            }
        }

        // return default priority
        return def;
    }

    /**
     * checks for parent
     *
     * @param tags
     * @param def
     * @param after
     * @returns {*}
     * @private
     */
    _parent (tags, def, after) {
        // loop tags for priority
        for (var i = after; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if priority
            if (tag.tag == 'parent') {
                return tag.name;
            }
        }

        // return default priority
        return def;
    }

    /**
     * checks for priority
     *
     * @param tags
     * @param def
     * @returns {*}
     * @private
     */
    _priority (tags, def) {
        // loop tags for priority
        for (var i = 0; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if priority
            if (tag.tag == 'priority') {
                return parseInt (tag.name);
            }
        }

        // return default priority
        return def;
    }

    /**
     * checks for routes
     *
     * @param tags
     * @returns {*}
     * @private
     */
    _routes (tags) {
        // set mounts
        var routes = [];

        // loop tags for mount
        for (var i = 0; i < tags.length; i++) {
            // let tag object
            let tag = tags[i];

            // check if route
            if (tag.tag == 'route') {
                routes.push({
                    'type'  : tag.type,
                    'route' : tag.name,
                    'acl'   : this._acl (tags, i)
                });
            }
        }

        // return false
        return routes.length ? routes : false;
    }

    /**
    * loop routes for menu config object
    *
    * @param routes
    * @param mounts
    * @param priority
    * @param chunk
    * @param fn
    *
    * @returns {*}
    * @private
     */
    _loopRoutes (routes, mounts, priority, scopeAcl, chunk, fn) {
        // create return variable
        var rtn = {};
        var acl = {};

        // loop routes
        for (var i = 0; i < routes.length; i++) {
            /// loop mount points
            for (var y = 0; y < mounts.length; y++) {
                // ensure type object exists
                if (!rtn[priority]) {
                    rtn[priority] = {};
                }

                // ensure priority object exists
                if (!rtn[priority][routes[i].type]) {
                    rtn[priority][routes[i].type] = {};
                }

                // set acl route
                var rt = this._parseRoute (mounts[y] + routes[i].route);

                // ensure flattened acl
                if (!acl[rt]) {
                    acl[rt] = [];
                }
                // add acl to acl array
                if (routes[i].acl) {
                    acl[rt].push (routes[i].acl);
                }
                // check for scope acl
                if (scopeAcl) {
                    acl[rt].push (scopeAcl);
                }

                // remove acl if required
                if (!acl[rt].length) {
                    delete acl[rt];
                }

                // add route to array
                rtn[priority][(routes[i].type ? routes[i].type : 'get')][rt] = {
                    'controller' : '/' + (chunk.path.indexOf ('/app') > -1 ? 'app' : 'lib') + '/bundles' + chunk.path.split ('bundles')[1].replace (/\\/g, '/'),
                    'action'     : fn
                };
            }
        }

        // return object
        return {
            'routes' : rtn,
            'acl'    : acl
        };
    }

    /**
    * loop menus for menu config object
    *
    * @param menus
    * @param mounts
    * @param priority
    * @param routes
    * @param acl
    *
    * @returns {*}
    * @private
     */
    _loopMenus (menus, mounts, priority, routes, acl) {
        var rtn = {};

        // loop menus
        for (var m = 0; m < menus.length; m++) {
            // only use first route
            menus[m].route    = this._parseRoute (mounts[0] + routes[0].route);
            menus[m].priority = menus[m].priority || priority;

            // set acl
            var menuAcl = acl[menus[m].route] || false;
            if (menuAcl && menuAcl.length) {
                for (var a = 0; a < menuAcl.length; a++) {
                    if (! menus[m].acl || ! Array.isArray (menus[m].acl.test)) {
                        menus[m].acl = menuAcl[a];
                    } else if (Array.isArray (menus[m].acl.test)) {
                        menus[m].acl.test.concat (menuAcl[a].test, menus[m].acl.test);
                    }
                }
            }

            // set menu object
            if (!rtn[menus[m].menu]) {
                rtn[menus[m].menu] = {};
            }

            // set menu
            if (menus[m].parent) {
                if (!rtn[menus[m].menu][menus[m].parent]) {
                    rtn[menus[m].menu][menus[m].parent] = {
                        'title'    : menus[m].parent,
                        'children' : []
                    };
                }
                rtn[menus[m].menu][menus[m].parent].children.push (menus[m]);
            } else {
                if (rtn[menus[m].menu][menus[m].name]) {
                    for (var key in menus[m]) {
                        rtn[menus[m].menu][menus[m].name][key] = menus[m][key];
                    }
                } else {
                    rtn[menus[m].menu][menus[m].name] = menus[m];
                    rtn[menus[m].menu][menus[m].name].children = [];
                }
            }
        }

        // return object
        return rtn;
    }

    /**
    * loop sockets for socket config object
    *
    * @param sockets
    * @param priority
    * @param acl
    * @param chunk
    * @param fn
    *
    * @returns {*}
    * @private
     */
    _loopSockets (sockets, priority, acl, chunk, fn) {
        var rtn = {};

        // loop menu
        for (var s = 0; s < sockets.length; s++) {
            sockets[s].priority = sockets[s].priority ? sockets[s].priority : priority;

            // check for scoped acl
            if (acl) {
                if (!sockets[s].acl || !Array.isArray(sockets[s].acl.test)) {
                  sockets[s].acl = acl;
                } else if (Array.isArray(acl.test)) {
                  sockets[s].acl.test.concat(acl.test, sockets[s].acl.test);
                }
            }

            sockets[s].controller = '/' + (chunk.path.indexOf ('/app') > -1 ? 'app' : 'bin') + '/bundles' + chunk.path.split ('bundles')[1].replace (/\\/g, '/');
            sockets[s].socket     = fn;

            // set in return object
            rtn[sockets[s].type] = sockets[s];
        }

        // return sockets
        return rtn;
    }

    /**
    * Returns parsed route string
    *
    * @param route
    *
    * @returns {String}
    * @private
     */
    _parseRoute (route) {
        return '/' + route.split ('//').join ('/').replace (/^\/|\/$/g, '');
    }

    /**
     * merges two objects
     *
     * @param obj1
     * @param obj2
     * @returns {*}
     * @private
     */
    _merge (obj1, obj2) {
        for (var p in obj2) {
            try {
                // Property in destination object set; update its value.
                if (obj2[p].constructor == Object) {
                    obj1[p] = this._merge (obj1[p], obj2[p]);
                } else {
                    obj1[p] = obj2[p];
                }
            } catch (e) {
                // Property in destination object not set; create it and set its value.
                obj1[p] = obj2[p];
            }
        }

        return obj1;
    }
}

/**
 * export config pipe
 *
 * @type {configUtil}
 */
module.exports = new configUtil ();
<|endoftext|>


<commit_before>var fs = require("fs");
var path = require("path");
var wrench = require("wrench");

/**
 * Search files recursivly and filter by include / exlude filters.
 *
 * @param {Object[]} options                  Options.
 * @param {String}   options.src              Path to source-files.
 * @param {String[]} [options.excludeFilters] Exclude Filters.
 * @param {String[]} options.includeFilters   Include Filters.
 * @returns {String[]}
 */
function findFiles(options)
{
	var files = [];
	try {
		// Find Files
		files = wrench.readdirSyncRecursive(options.src);

		// Create RegExp Include Filter List
		var regExpIncludeFilters = [];
		filters = options.includeFilters;
		if(typeof(filters) === "string") filters = [ filters ];
		filters.forEach(function(filter) {
			if(filter.length > 0) regExpIncludeFilters.push( new RegExp(filter) );
		}); // forEach

		// RegExp Include Filter
		var length = regExpIncludeFilters.length;
		files = files.filter(function(filename) {
			// Not include Directories like "dirname.js"
			var fullFilename = path.join(options.src, filename);
			if(fs.statSync(fullFilename).isDirectory()) return 0;
			// Apply every filter
			for(var i = 0; i < length; i += 1)
			{
				if(regExpIncludeFilters[i].test(filename)) return 1;
			} // for
			return 0;
		}); // files.filter

		// Create RegExp Exclude Filter List
		var regExpExcludeFilters = [];
		filters = options.excludeFilters;
		if(typeof(filters) === "string") filters = [ filters ];
		filters.forEach(function(filter) {
			if(filter.length > 0) regExpExcludeFilters.push( new RegExp(filter) );
		}); // forEach

		// RegExp Exclude Filter
		length = regExpExcludeFilters.length;
		files = files.filter(function(filename) {
		// Apply every filter
			for(var i = 0; i < length; i += 1)
			{
				if(regExpExcludeFilters[i].test(filename)) return 0;
			} // for
			return 1;
		}); // files.filter
	} // try
	finally
	{
		if( ! files || files.length === 0)
		{
			console.log("apidoc: no files found in " + options.src);
			process.exit(0);
		}
	} // finally
	return files;
} // findFiles

/**
 * Exports.
 */
module.exports = findFiles;<commit_msg>Give some indication, in case file listing with fails<commit_after>var fs = require("fs");
var path = require("path");
var wrench = require("wrench");

/**
 * Search files recursivly and filter by include / exlude filters.
 *
 * @param {Object[]} options                  Options.
 * @param {String}   options.src              Path to source-files.
 * @param {String[]} [options.excludeFilters] Exclude Filters.
 * @param {String[]} options.includeFilters   Include Filters.
 * @returns {String[]}
 */
function findFiles(options)
{
	var files = [];
	try {
		// Find Files
		files = wrench.readdirSyncRecursive(options.src);

		// Create RegExp Include Filter List
		var regExpIncludeFilters = [];
		filters = options.includeFilters;
		if(typeof(filters) === "string") filters = [ filters ];
		filters.forEach(function(filter) {
			if(filter.length > 0) regExpIncludeFilters.push( new RegExp(filter) );
		}); // forEach

		// RegExp Include Filter
		var length = regExpIncludeFilters.length;
		files = files.filter(function(filename) {
			// Not include Directories like "dirname.js"
			var fullFilename = path.join(options.src, filename);
			if(fs.statSync(fullFilename).isDirectory()) return 0;
			// Apply every filter
			for(var i = 0; i < length; i += 1)
			{
				if(regExpIncludeFilters[i].test(filename)) return 1;
			} // for
			return 0;
		}); // files.filter

		// Create RegExp Exclude Filter List
		var regExpExcludeFilters = [];
		filters = options.excludeFilters;
		if(typeof(filters) === "string") filters = [ filters ];
		filters.forEach(function(filter) {
			if(filter.length > 0) regExpExcludeFilters.push( new RegExp(filter) );
		}); // forEach

		// RegExp Exclude Filter
		length = regExpExcludeFilters.length;
		files = files.filter(function(filename) {
		// Apply every filter
			for(var i = 0; i < length; i += 1)
			{
				if(regExpExcludeFilters[i].test(filename)) return 0;
			} // for
			return 1;
		}); // files.filter
	} // try
	catch (e) {
		console.warn(e);
	} // catch
	finally
	{
		if( ! files || files.length === 0)
		{
			console.log("apidoc: no files found in " + options.src);
			process.exit(0);
		}
	} // finally
	return files;
} // findFiles

/**
 * Exports.
 */
module.exports = findFiles;<|endoftext|>


<commit_before>function populateMarkers(mapData) {
	var geocoder = new google.maps.Geocoder();
	for (i = 1; i < mapData.length; i++) {
		console.log(mapData[i][1]);

		geocoder.geocode({'address': mapData[i][4]}, function(results, status)
		{
			if (status === google.maps.GeocoderStatus.OK)
			{
				marker = new google.maps.Marker({
				map: map,
				position: results[0].geometry.location,
				animation: google.maps.Animation.DROP
				});
			}
			else
			{
			  alert('Geocode was not successful for the following reason: ' + status);
			}
		});
	}
}

function initMap() {
	var element = document.createElement('div');
	var mapDiv = document.getElementById('map-hider').appendChild(element);
	mapDiv.id = 'map';
	mapDiv.style.cssText = 'width:100%; height:750px; margin: auto';
	var map = new google.maps.Map(mapDiv, {
		center: {lat: 54.2774, lng: -1.7126},
		zoom: 7
	});

	var mapdata = Papa.parse("https://rawcdn.githack.com/WearyWanderer/wearywanderer.github.io/master/assets/csv/wanderlustvids.csv", {
		download: true,
		complete: function(results) {
			console.log(results);
			populateMarkers(results.data);
		}
	});
}

window.onload = initMap;

<commit_msg>FIxed missing map parameter passed in func<commit_after>function populateMarkers(mapData, map) {
	var geocoder = new google.maps.Geocoder();
	for (i = 1; i < mapData.length; i++) {
		console.log(mapData[i][1]);

		geocoder.geocode({'address': mapData[i][4]}, function(results, status)
		{
			if (status === google.maps.GeocoderStatus.OK)
			{
				marker = new google.maps.Marker({
				map: map,
				position: results[0].geometry.location,
				animation: google.maps.Animation.DROP
				});
			}
			else
			{
			  alert('Geocode was not successful for the following reason: ' + status);
			}
		});
	}
}

function initMap() {
	var element = document.createElement('div');
	var mapDiv = document.getElementById('map-hider').appendChild(element);
	mapDiv.id = 'map';
	mapDiv.style.cssText = 'width:100%; height:750px; margin: auto';
	var map = new google.maps.Map(mapDiv, {
		center: {lat: 54.2774, lng: -1.7126},
		zoom: 7
	});

	var mapdata = Papa.parse("https://rawcdn.githack.com/WearyWanderer/wearywanderer.github.io/master/assets/csv/wanderlustvids.csv", {
		download: true,
		complete: function(results) {
			console.log(results);
			populateMarkers(results.data, map);
		}
	});
}

window.onload = initMap;

<|endoftext|>


<commit_before>// font size
var FONT = 32;

// map dimensions
var ROWS = 10;
var COLS = 15;

// number of actors per level, including player
var ACTORS = 10;

// the structure of the map
var map;

// the ascii display, as a 2d array of characters
var screen;

// a list of all actors, 0 is the player
var player;
var actorList;
var livingEnemies;

// points to each actor in its position, for quick searching
var actorMap;

// initialize phaser, call create() once done
var game = new Phaser.Game(COLS * FONT * 0.6, ROWS * FONT, Phaser.AUTO, null, {
	create: create
});

function create() {
	// init keyboard commands
	game.input.keyboard.addCallbacks(null, null, onKeyUp);

	// initialize map
	initMap();

	// initialize screen
	screen = [];
	for (var y = 0; y < ROWS; y++) {
		var newRow = [];
		screen.push(newRow);
		for (var x = 0; x < COLS; x++)
			newRow.push(initCell('', x, y));
	}

	// initialize actors
	initActors();

	// draw level
	drawMap();
	drawActors();
}

function initCell(chr, x, y) {
	// add a single cell in a given position to the ascii display
	var style = {
		font: FONT + "px monospace",
		fill: "#fff"
	};
	return game.add.text(FONT * 0.6 * x, FONT * y, chr, style);
}

function initMap() {
	// create a new random map
	map = [];
	for (var y = 0; y < ROWS; y++) {
		var newRow = [];
		for (var x = 0; x < COLS; x++) {
			if (Math.random() > 0.8)
				newRow.push('#');
			else
				newRow.push('.');
		}
		map.push(newRow);
	}
}

function drawMap() {
	for (var y = 0; y < ROWS; y++)
		for (var x = 0; x < COLS; x++)
			screen[y][x].content = map[y][x];
}

function randomInt(max) {
	return Math.floor(Math.random() * max);
}

function initActors() {
	// create actors at random locations
	actorList = [];
	actorMap = {};
	for (var e = 0; e < ACTORS; e++) {
		// create new actor
		var actor = {
			x: 0,
			y: 0,
			hp: e == 0 ? 3 : 1
		};
		do {
			// pick a random position that is both a floor and not occupied
			actor.y = randomInt(ROWS);
			actor.x = randomInt(COLS);
		} while (map[actor.y][actor.x] == '#' || actorMap[actor.y + "_" + actor.x] != null);

		// add references to the actor to the actors list & map
		actorMap[actor.y + "_" + actor.x] = actor;
		actorList.push(actor);
	}

	// the player is the first actor in the list
	player = actorList[0];
	livingEnemies = ACTORS - 1;
}

function drawActors() {
	for (var a in actorList) {
		if (actorList[a] != null && actorList[a].hp > 0)
			screen[actorList[a].y][actorList[a].x].content = a == 0 ? '' + player.hp : 'e';
	}
}

function canGo(actor,dir) {
	return 	actor.x+dir.x >= 0 &&
			actor.x+dir.x <= COLS - 1 &&
			actor.y+dir.y >= 0 &&
			actor.y+dir.y <= ROWS - 1 &&
			map[actor.y+dir.y][actor.x +dir.x] == '.';
}

function moveTo(actor, dir) {
	// check if actor can move in the given direction
	if (!canGo(actor,dir))
		return false;

	// moves actor to the new location
	var newKey = (actor.y + dir.y) +'_' + (actor.x + dir.x);
	// if the destination tile has an actor in it
	if (actorMap[newKey] != null) {
		//decrement hitpoints of the actor at the destination tile
		var victim = actorMap[newKey];
		victim.hp--;

		// if it's dead remove its reference
		if (victim.hp == 0) {
			actorMap[newKey]= null;
			actorList[actorList.indexOf(victim)]=null;
			if(victim!=player) {
				livingEnemies--;
				if (livingEnemies == 0) {
					// victory message
					var victory = game.add.text(game.world.centerX, game.world.centerY, 'Victory!\nCtrl+r to restart', { fill : '#2e2', align: "center" } );
					victory.anchor.setTo(0.5,0.5);
				}
			}
		}
	} else {
		// remove reference to the actor's old position
		actorMap[actor.y + '_' + actor.x]= null;

		// update position
		actor.y+=dir.y;
		actor.x+=dir.x;

		// add reference to the actor's new position
		actorMap[actor.y + '_' + actor.x]=actor;
	}
	return true;
}

function onKeyUp(event) {
	// draw map to overwrite previous actors positions
	drawMap();

	// act on player input
	var acted = false;
	switch (event.keyCode) {
		case Phaser.Keyboard.LEFT:
			acted = moveTo(player, {x:-1, y:0});
			break;

		case Phaser.Keyboard.RIGHT:
			acted = moveTo(player,{x:1, y:0});
			break;

		case Phaser.Keyboard.UP:
			acted = moveTo(player, {x:0, y:-1});
			break;

		case Phaser.Keyboard.DOWN:
			acted = moveTo(player, {x:0, y:1});
			break;
	}

	// enemies act every time the player does
	if (acted)
		for (var enemy in actorList) {
			// skip the player
			if(enemy==0)
				continue;

			var e = actorList[enemy];
			if (e != null)
				aiAct(e);
		}

	// draw actors in new positions
	drawActors();
}

function aiAct(actor) {
	var directions = [ { x: -1, y:0 }, { x:1, y:0 }, { x:0, y: -1 }, { x:0, y:1 } ];
	var dx = player.x - actor.x;
	var dy = player.y - actor.y;

	// if player is far away, walk randomly
	if (Math.abs(dx) + Math.abs(dy) > 6)
		// try to walk in random directions until you succeed once
		while (!moveTo(actor, directions[randomInt(directions.length)])) { };

	// otherwise walk towards player
	if (Math.abs(dx) > Math.abs(dy)) {
		if (dx < 0) {
			// left
			moveTo(actor, directions[0]);
		} else {
			// right
			moveTo(actor, directions[1]);
		}
	} else {
		if (dy < 0) {
			// up
			moveTo(actor, directions[2]);
		} else {
			// down
			moveTo(actor, directions[3]);
		}
	}
	if (player.hp < 1) {
		// game over message
		var gameOver = game.add.text(game.world.centerX, game.world.centerY, 'Game Over\nCtrl+r to restart', { fill : '#e22', align: "center" } );
		gameOver.anchor.setTo(0.5,0.5);
	}
}<commit_msg>Update rl.js<commit_after>// font size
var FONT = 32;

// map dimensions
var ROWS = 10;
var COLS = 15;

// number of actors per level, including player
var ACTORS = 10;

// the structure of the map
var map;

// the ascii display, as a 2d array of characters
var asciidisplay;

// a list of all actors, 0 is the player
var player;
var actorList;
var livingEnemies;

// points to each actor in its position, for quick searching
var actorMap;

// initialize phaser, call create() once done
var game = new Phaser.Game(COLS * FONT * 0.6, ROWS * FONT, Phaser.AUTO, null, {
	create: create
});

function create() {
	// init keyboard commands
	game.input.keyboard.addCallbacks(null, null, onKeyUp);

	// initialize map
	initMap();

	// initialize ascii display
	asciidisplay = [];
	for (var y = 0; y < ROWS; y++) {
		var newRow = [];
		asciidisplay.push(newRow);
		for (var x = 0; x < COLS; x++)
			newRow.push(initCell('', x, y));
	}

	// initialize actors
	initActors();

	// draw level
	drawMap();
	drawActors();
}

function initCell(chr, x, y) {
	// add a single cell in a given position to the ascii display
	var style = {
		font: FONT + "px monospace",
		fill: "#fff"
	};
	return game.add.text(FONT * 0.6 * x, FONT * y, chr, style);
}

function initMap() {
	// create a new random map
	map = [];
	for (var y = 0; y < ROWS; y++) {
		var newRow = [];
		for (var x = 0; x < COLS; x++) {
			if (Math.random() > 0.8)
				newRow.push('#');
			else
				newRow.push('.');
		}
		map.push(newRow);
	}
}

function drawMap() {
	for (var y = 0; y < ROWS; y++)
		for (var x = 0; x < COLS; x++)
			asciidisplay[y][x].content = map[y][x];
}

function randomInt(max) {
	return Math.floor(Math.random() * max);
}

function initActors() {
	// create actors at random locations
	actorList = [];
	actorMap = {};
	for (var e = 0; e < ACTORS; e++) {
		// create new actor
		var actor = {
			x: 0,
			y: 0,
			hp: e == 0 ? 3 : 1
		};
		do {
			// pick a random position that is both a floor and not occupied
			actor.y = randomInt(ROWS);
			actor.x = randomInt(COLS);
		} while (map[actor.y][actor.x] == '#' || actorMap[actor.y + "_" + actor.x] != null);

		// add references to the actor to the actors list & map
		actorMap[actor.y + "_" + actor.x] = actor;
		actorList.push(actor);
	}

	// the player is the first actor in the list
	player = actorList[0];
	livingEnemies = ACTORS - 1;
}

function drawActors() {
	for (var a in actorList) {
		if (actorList[a] != null && actorList[a].hp > 0)
			asciidisplay[actorList[a].y][actorList[a].x].content = a == 0 ? '' + player.hp : 'e';
	}
}

function canGo(actor,dir) {
	return 	actor.x+dir.x >= 0 &&
			actor.x+dir.x <= COLS - 1 &&
			actor.y+dir.y >= 0 &&
			actor.y+dir.y <= ROWS - 1 &&
			map[actor.y+dir.y][actor.x +dir.x] == '.';
}

function moveTo(actor, dir) {
	// check if actor can move in the given direction
	if (!canGo(actor,dir))
		return false;

	// moves actor to the new location
	var newKey = (actor.y + dir.y) +'_' + (actor.x + dir.x);
	// if the destination tile has an actor in it
	if (actorMap[newKey] != null) {
		//decrement hitpoints of the actor at the destination tile
		var victim = actorMap[newKey];
		victim.hp--;

		// if it's dead remove its reference
		if (victim.hp == 0) {
			actorMap[newKey]= null;
			actorList[actorList.indexOf(victim)]=null;
			if(victim!=player) {
				livingEnemies--;
				if (livingEnemies == 0) {
					// victory message
					var victory = game.add.text(game.world.centerX, game.world.centerY, 'Victory!\nCtrl+r to restart', { fill : '#2e2', align: "center" } );
					victory.anchor.setTo(0.5,0.5);
				}
			}
		}
	} else {
		// remove reference to the actor's old position
		actorMap[actor.y + '_' + actor.x]= null;

		// update position
		actor.y+=dir.y;
		actor.x+=dir.x;

		// add reference to the actor's new position
		actorMap[actor.y + '_' + actor.x]=actor;
	}
	return true;
}

function onKeyUp(event) {
	// draw map to overwrite previous actors positions
	drawMap();

	// act on player input
	var acted = false;
	switch (event.keyCode) {
		case Phaser.Keyboard.LEFT:
			acted = moveTo(player, {x:-1, y:0});
			break;

		case Phaser.Keyboard.RIGHT:
			acted = moveTo(player,{x:1, y:0});
			break;

		case Phaser.Keyboard.UP:
			acted = moveTo(player, {x:0, y:-1});
			break;

		case Phaser.Keyboard.DOWN:
			acted = moveTo(player, {x:0, y:1});
			break;
	}

	// enemies act every time the player does
	if (acted)
		for (var enemy in actorList) {
			// skip the player
			if(enemy==0)
				continue;

			var e = actorList[enemy];
			if (e != null)
				aiAct(e);
		}

	// draw actors in new positions
	drawActors();
}

function aiAct(actor) {
	var directions = [ { x: -1, y:0 }, { x:1, y:0 }, { x:0, y: -1 }, { x:0, y:1 } ];
	var dx = player.x - actor.x;
	var dy = player.y - actor.y;

	// if player is far away, walk randomly
	if (Math.abs(dx) + Math.abs(dy) > 6)
		// try to walk in random directions until you succeed once
		while (!moveTo(actor, directions[randomInt(directions.length)])) { };

	// otherwise walk towards player
	if (Math.abs(dx) > Math.abs(dy)) {
		if (dx < 0) {
			// left
			moveTo(actor, directions[0]);
		} else {
			// right
			moveTo(actor, directions[1]);
		}
	} else {
		if (dy < 0) {
			// up
			moveTo(actor, directions[2]);
		} else {
			// down
			moveTo(actor, directions[3]);
		}
	}
	if (player.hp < 1) {
		// game over message
		var gameOver = game.add.text(game.world.centerX, game.world.centerY, 'Game Over\nCtrl+r to restart', { fill : '#e22', align: "center" } );
		gameOver.anchor.setTo(0.5,0.5);
	}
}
<|endoftext|>


<commit_before>const pool = require('./api/db');
const SQL = require('sql-template-strings')

//     //to run a query we just pass it to the pool
//     //after we're done nothing has to be taken care of
//     //we don't have to return any client to the pool or close a connection

const get_num_couples_per_event_for_competition = cid => {
    return pool.query(SQL`SELECT COUNT(p.number), e.id
        FROM partnership p
        LEFT JOIN event e ON (e.id = p.eventid)
        WHERE p.competitionid = ${cid}
        GROUP BY e.id`);
}

const create_rounds_for_events_for_competition = cid => {
    return new Promise(function(resolve, reject) {
       get_num_couples_per_event_for_competition(cid).then(value => {
          pool.connect(function(err, client, done) {
              if (err) {
                  console.error('error running query', err);
                  reject(err);
              } else {
                  let ordernumber = 1;
                  for (let row of value) {
                      let couples = parseInt(row.count);
                      let eventid = row.id;
                      let numRounds = Math.ceil(couples / 7.0);
                      for (let i = 1; i <= numRounds; i++) {
                          let size = Math.min(couples, (numRounds - i + 1) * 7);
                          if (i == numRounds) {
                              client.query(SQL`INSERT INTO round (eventid, name, ordernumber, size) VALUES (${eventid}, 'Final', ${ordernumber}, ${size})`, (err, result) => {
                                  if (err) {
                                      done(err);
                                      reject(err);
                                  }
                              });
                          } else if (i == numRounds - 1) {
                              client.query(SQL`INSERT INTO round (eventid, name, ordernumber, size) VALUES (${eventid}, 'Semifinal', ${ordernumber}, ${size})`, (err, result) => {
                                  if (err) {
                                      done(err);
                                      reject(err);
                                  }
                              });
                          } else if (i == numRounds - 2) {
                              client.query(SQL`INSERT INTO round (eventid, name, ordernumber, size) VALUES (${eventid}, 'Quarter', ${ordernumber}, ${size})`, (err, result) => {
                                  if (err) {
                                      done(err);
                                      reject(err);
                                  }
                              });
                          } else {
                              const name = 'Round ' + i;
                              client.query(SQL`INSERT INTO round (eventid, name, ordernumber, size) VALUES (${eventid}, ${name}, ${ordernumber}, ${size})`, (err, result) => {
                                  if (err) {
                                      done(err);
                                      reject(err);
                                  }
                              });
                          }
                          ordernumber++;
                      }
                  }
                  done(null);
                  resolve("{finished: true}");
              }
          })
       });
    });
}

const get_all_admins = () => {
    return pool.query('SELECT * FROM admin', []);
}

const get_judges_for_competition = (comp_id) => {
    return pool.query(SQL`SELECT * FROM judge WHERE competitionid = ${comp_id}`);
}

const get_judge = id => {
    return pool.query(SQL`SELECT * FROM judge WHERE id = ${id}`);
}

const get_affiliations = () => {
    return pool.query('SELECT * FROM affiliation', []);
}

const get_levels_for_competition = cid => {
    return pool.query(SQL`SELECT id, name, ordernumber FROM level WHERE competitionid = ${cid}`);
}

const get_styles_for_competition = cid => {
    return pool.query(SQL`SELECT id, name, ordernumber FROM style WHERE competitionid = ${cid}`);
}

const get_competition_info = cid => {
    return pool.query(SQL`SELECT * FROM competition WHERE id = ${cid}`);
}

const get_events_for_competition = cid => {
    return pool.query(SQL`SELECT * FROM event where competitionid = ${cid} ORDER BY ordernumber`);
}

const get_rounds_for_competition = cid => {
    return pool.query(SQL`SELECT r.id, e.level, e.style, e.dance, r.name, r.ordernumber, r.size, r.nextround,
        r.judgeid1, r.judgeid2, r.judgeid3, r.judgeid4, r.judgeid5, r.judgeid6 FROM event e
        LEFT JOIN round r ON (e.id = r.eventid) WHERE e.competitionid = ${cid} ORDER BY r.ordernumber`);
}

const get_competitors_for_competition = cid => {
    return pool.query(SQL`SELECT DISTINCT ON (id) c.id, firstname || ' ' || lastname as name, email,
        CASE WHEN c.id = p.leadcompetitorid THEN p.number ELSE NULL END as number, a.name as affiliationname,
        pr.paidwithaffiliation, pr.amount FROM competitor c
        LEFT JOIN partnership p ON (c.id = p.leadcompetitorid OR c.id = p.followcompetitorid)
        LEFT JOIN paymentrecord pr ON (c.id = pr.competitorid)
        LEFT JOIN  affiliation a ON (c.affiliationid = a.id)
        WHERE p.competitionid = ${cid}`);
}

const get_affiliations_for_competition = cid => {
    return pool.query(SQL`SELECT DISTINCT ON (affiliationname) a.name as affiliationname
        FROM competitor c
        LEFT JOIN partnership p ON (c.id = p.leadcompetitorid OR c.id = p.followcompetitorid)
        LEFT JOIN  affiliation a ON (c.affiliationid = a.id)
        WHERE p.competitionid = ${cid}`);
}

const get_num_competitors_per_style_for_competition = cid => {
    return pool.query(SQL`SELECT COUNT(c.id), s.name
        FROM competitor c
        LEFT JOIN partnership p ON (c.id = p.leadcompetitorid OR c.id = p.followcompetitorid)
        LEFT JOIN event e ON (e.id = p.eventid)
        LEFT JOIN style s ON (e.styleid = s.id)
        WHERE p.competitionid = ${cid}
        GROUP BY s.name`)
}

const add_new_judge = (judge) => {
    return pool.query(SQL`INSERT INTO judge (email, token, firstname, lastname, phonenumber, competitionid)
        VALUES (${judge.email}, ${judge.token}, ${judge.firstName}, ${judge.lastName}, ${judge.phoneNumber}, ${judge.competitionId})`);
}

// INSERT

// DELETE

module.exports = {
    get_all_admins,
    get_judges_for_competition,
    get_judge,
    get_affiliations,
    get_levels_for_competition,
    get_styles_for_competition,
    get_competition_info,
    get_events_for_competition,
    get_rounds_for_competition,
    get_competitors_for_competition,
    get_affiliations_for_competition,
    get_num_competitors_per_style_for_competition,
    add_new_judge,
    create_rounds_for_events_for_competition
}
<commit_msg>Fixed bug in getting event.levelid and styleid<commit_after>const pool = require('./api/db');
const SQL = require('sql-template-strings')

//     //to run a query we just pass it to the pool
//     //after we're done nothing has to be taken care of
//     //we don't have to return any client to the pool or close a connection

const get_num_couples_per_event_for_competition = cid => {
    return pool.query(SQL`SELECT COUNT(p.number), e.id
        FROM partnership p
        LEFT JOIN event e ON (e.id = p.eventid)
        WHERE p.competitionid = ${cid}
        GROUP BY e.id`);
}

const create_rounds_for_events_for_competition = cid => {
    return new Promise(function(resolve, reject) {
       get_num_couples_per_event_for_competition(cid).then(value => {
          pool.connect(function(err, client, done) {
              if (err) {
                  console.error('error running query', err);
                  reject(err);
              } else {
                  let ordernumber = 1;
                  for (let row of value) {
                      let couples = parseInt(row.count);
                      let eventid = row.id;
                      let numRounds = Math.ceil(couples / 7.0);
                      for (let i = 1; i <= numRounds; i++) {
                          let size = Math.min(couples, (numRounds - i + 1) * 7);
                          if (i == numRounds) {
                              client.query(SQL`INSERT INTO round (eventid, name, ordernumber, size) VALUES (${eventid}, 'Final', ${ordernumber}, ${size})`, (err, result) => {
                                  if (err) {
                                      done(err);
                                      reject(err);
                                  }
                              });
                          } else if (i == numRounds - 1) {
                              client.query(SQL`INSERT INTO round (eventid, name, ordernumber, size) VALUES (${eventid}, 'Semifinal', ${ordernumber}, ${size})`, (err, result) => {
                                  if (err) {
                                      done(err);
                                      reject(err);
                                  }
                              });
                          } else if (i == numRounds - 2) {
                              client.query(SQL`INSERT INTO round (eventid, name, ordernumber, size) VALUES (${eventid}, 'Quarter', ${ordernumber}, ${size})`, (err, result) => {
                                  if (err) {
                                      done(err);
                                      reject(err);
                                  }
                              });
                          } else {
                              const name = 'Round ' + i;
                              client.query(SQL`INSERT INTO round (eventid, name, ordernumber, size) VALUES (${eventid}, ${name}, ${ordernumber}, ${size})`, (err, result) => {
                                  if (err) {
                                      done(err);
                                      reject(err);
                                  }
                              });
                          }
                          ordernumber++;
                      }
                  }
                  done(null);
                  resolve("{finished: true}");
              }
          })
       });
    });
}

const get_all_admins = () => {
    return pool.query('SELECT * FROM admin', []);
}

const get_judges_for_competition = (comp_id) => {
    return pool.query(SQL`SELECT * FROM judge WHERE competitionid = ${comp_id}`);
}

const get_judge = id => {
    return pool.query(SQL`SELECT * FROM judge WHERE id = ${id}`);
}

const get_affiliations = () => {
    return pool.query('SELECT * FROM affiliation', []);
}

const get_levels_for_competition = cid => {
    return pool.query(SQL`SELECT id, name, ordernumber FROM level WHERE competitionid = ${cid}`);
}

const get_styles_for_competition = cid => {
    return pool.query(SQL`SELECT id, name, ordernumber FROM style WHERE competitionid = ${cid}`);
}

const get_competition_info = cid => {
    return pool.query(SQL`SELECT * FROM competition WHERE id = ${cid}`);
}

const get_events_for_competition = cid => {
    return pool.query(SQL`SELECT * FROM event where competitionid = ${cid} ORDER BY ordernumber`);
}

const get_rounds_for_competition = cid => {
    return pool.query(SQL`SELECT r.id, e.levelid, e.styleid, e.dance, r.name, r.ordernumber, r.size, r.nextround,
        r.judgeid1, r.judgeid2, r.judgeid3, r.judgeid4, r.judgeid5, r.judgeid6 FROM event e
        LEFT JOIN round r ON (e.id = r.eventid) WHERE e.competitionid = ${cid} ORDER BY r.ordernumber`);
}

const get_competitors_for_competition = cid => {
    return pool.query(SQL`SELECT DISTINCT ON (id) c.id, firstname || ' ' || lastname as name, email,
        CASE WHEN c.id = p.leadcompetitorid THEN p.number ELSE NULL END as number, a.name as affiliationname,
        pr.paidwithaffiliation, pr.amount FROM competitor c
        LEFT JOIN partnership p ON (c.id = p.leadcompetitorid OR c.id = p.followcompetitorid)
        LEFT JOIN paymentrecord pr ON (c.id = pr.competitorid)
        LEFT JOIN  affiliation a ON (c.affiliationid = a.id)
        WHERE p.competitionid = ${cid}`);
}

const get_affiliations_for_competition = cid => {
    return pool.query(SQL`SELECT DISTINCT ON (affiliationname) a.name as affiliationname
        FROM competitor c
        LEFT JOIN partnership p ON (c.id = p.leadcompetitorid OR c.id = p.followcompetitorid)
        LEFT JOIN  affiliation a ON (c.affiliationid = a.id)
        WHERE p.competitionid = ${cid}`);
}

const get_num_competitors_per_style_for_competition = cid => {
    return pool.query(SQL`SELECT COUNT(c.id), s.name
        FROM competitor c
        LEFT JOIN partnership p ON (c.id = p.leadcompetitorid OR c.id = p.followcompetitorid)
        LEFT JOIN event e ON (e.id = p.eventid)
        LEFT JOIN style s ON (e.styleid = s.id)
        WHERE p.competitionid = ${cid}
        GROUP BY s.name`)
}

const add_new_judge = (judge) => {
    return pool.query(SQL`INSERT INTO judge (email, token, firstname, lastname, phonenumber, competitionid)
        VALUES (${judge.email}, ${judge.token}, ${judge.firstName}, ${judge.lastName}, ${judge.phoneNumber}, ${judge.competitionId})`);
}

// INSERT

// DELETE

module.exports = {
    get_all_admins,
    get_judges_for_competition,
    get_judge,
    get_affiliations,
    get_levels_for_competition,
    get_styles_for_competition,
    get_competition_info,
    get_events_for_competition,
    get_rounds_for_competition,
    get_competitors_for_competition,
    get_affiliations_for_competition,
    get_num_competitors_per_style_for_competition,
    add_new_judge,
    create_rounds_for_events_for_competition
}
<|endoftext|>