<commit_before>(function (window) {
  'use strict';

  var KEY_MAP = {},
    CTRL_KEY_LISTENERS = {},
    LIST_ELEMENT_DELIMITER = ':',
    document = window.document,
    addToAll = window.attachAll || false,
    whitelist = window.bedit_allow || [],
    blacklist = window.bedit_deny || [],
    inputMode = {}; // 0: Uyghur, 1: Latin

  function getCharCode(ch) {
    return ch.charCodeAt(0);
  }

  function getChar(ascii) {
    return String.fromCharCode(ascii);
  }

  function initialize() {
    // ASCII -> Unicode of Uyghur characters
    KEY_MAP[getCharCode('a')] = 0x06BE;
    KEY_MAP[getCharCode('b')] = 0x0628;
    KEY_MAP[getCharCode('c')] = 0x063A;
    KEY_MAP[getCharCode('D')] = 0x0698;
    KEY_MAP[getCharCode('d')] = 0x062F;
    KEY_MAP[getCharCode('e')] = 0x06D0;
    KEY_MAP[getCharCode('F')] = 0x0641;
    KEY_MAP[getCharCode('f')] = 0x0627;
    KEY_MAP[getCharCode('G')] = 0x06AF;
    KEY_MAP[getCharCode('g')] = 0x06D5;
    KEY_MAP[getCharCode('H')] = 0x062E;
    KEY_MAP[getCharCode('h')] = 0x0649;
    KEY_MAP[getCharCode('i')] = 0x06AD;
    KEY_MAP[getCharCode('J')] = 0x062C;
    KEY_MAP[getCharCode('j')] = 0x0642;
    KEY_MAP[getCharCode('K')] = 0x06C6;
    KEY_MAP[getCharCode('k')] = 0x0643;
    KEY_MAP[getCharCode('l')] = 0x0644;
    KEY_MAP[getCharCode('m')] = 0x0645;
    KEY_MAP[getCharCode('n')] = 0x0646;
    KEY_MAP[getCharCode('o')] = 0x0648;
    KEY_MAP[getCharCode('p')] = 0x067E;
    KEY_MAP[getCharCode('q')] = 0x0686;
    KEY_MAP[getCharCode('r')] = 0x0631;
    KEY_MAP[getCharCode('s')] = 0x0633;
    KEY_MAP[getCharCode('t')] = 0x062A;
    KEY_MAP[getCharCode('u')] = 0x06C7;
    KEY_MAP[getCharCode('v')] = 0x06C8;
    KEY_MAP[getCharCode('w')] = 0x06CB;
    KEY_MAP[getCharCode('x')] = 0x0634;
    KEY_MAP[getCharCode('y')] = 0x064A;
    KEY_MAP[getCharCode('z')] = 0x0632;
    KEY_MAP[getCharCode('/')] = 0x0626;

    // Uyghur punctuation marks
    KEY_MAP[getCharCode(';')] = 0x061B;
    KEY_MAP[getCharCode('?')] = 0x061F;
    KEY_MAP[getCharCode(',')] = 0x060C;

    // Invert parentheses, brackets, and braces for RTL layout.
    KEY_MAP[getCharCode('(')] = getCharCode(')');
    KEY_MAP[getCharCode(')')] = getCharCode('(');
    KEY_MAP[getCharCode('[')] = getCharCode(']');
    KEY_MAP[getCharCode(']')] = getCharCode('[');
    KEY_MAP[getCharCode('}')] = 0x00AB;
    KEY_MAP[getCharCode('{')] = 0x00BB;
    KEY_MAP[getCharCode('<')] = getCharCode('>'); // Sticking to the standard.
    KEY_MAP[getCharCode('>')] = getCharCode('<'); // Sticking to the standard.

    CTRL_KEY_LISTENERS.K = toggleInputMode;
    // [Ctrl-T] can no longer be used for inverting the input direction in WebKit (Blink), see:
    //   https://code.google.com/p/chromium/issues/detail?id=33056
    // Therefore, use 'Y' ('Y' as in the Uyghur word 'Yönilish')
    CTRL_KEY_LISTENERS.Y = toggleInputDirection;
  }

  function toggleInputMode(event) {
    var element = event.srcElement || event.target;

    inputMode[element.name] = 1 - inputMode[element.name];
  }

  function toggleInputDirection(event) {
    var element = event.srcElement || event.target;

    element.style.direction = (element.style.direction === 'ltr' ? 'rtl' : 'ltr');
  }

  function insert(element, text) {
    var previousSelectionStart,
      currentSelectionStart,
      previousScrollTop,
      previousScrollLeft;

    if (document.selection && document.selection.createRange) { // Trident 5.0+
      document.selection.createRange().text = text;
    } else { // W3C
      previousSelectionStart = element.selectionStart;

      // Gecko scrolls to top in textarea after input, fix this.
      if (element.type === 'textarea' && element.scrollTop) {
        previousScrollTop = element.scrollTop;
        previousScrollLeft = element.scrollLeft;
      }

      element.value = element.value.substring(0, element.selectionStart) +
        text + element.value.substring(element.selectionEnd);

      if (previousScrollTop) {
        element.scrollTop = previousScrollTop;
        element.scrollLeft = previousScrollLeft;
      }

      currentSelectionStart = previousSelectionStart + text.length;
      element.setSelectionRange(currentSelectionStart, currentSelectionStart);
    }
  }

  function keydownListener(e) {
    var event = e || window.event,
      isMetaKey = event.ctrlKey || event.metaKey,
      keyCode = event.keyCode || event.which,
      c = getChar(keyCode).toUpperCase();

    if (isMetaKey && CTRL_KEY_LISTENERS[c]) {
      CTRL_KEY_LISTENERS[c](event);

      if (event.preventDefault) {
        event.preventDefault();
        event.stopPropagation();
      } else {
        event.returnValue = false;
        event.cancelBubble = true;
      }
    }
  }

  function keypressListener(e) {
    var event = e || window.event,
      target = event.srcElement || event.target,
      isMetaKey = event.ctrlKey || event.metaKey,
      keyCode = event.keyCode || event.which,
      c = getChar(keyCode).toUpperCase(),
      isAlphabetic = /^[A-Z]{1}$/.test(c),
      preventDefaultAndStopPropagation = false;

    // The extra check for the meta key ([Ctrl]) is because:
    //   https://bugzilla.mozilla.org/show_bug.cgi?id=501496
    if (!isMetaKey && inputMode[target.name] === 0) {
      if (KEY_MAP[keyCode]) {
        if (event.keyCode && !event.which) { // Trident 4.0-
          event.keyCode = KEY_MAP[keyCode];
        } else {                             // W3C event is read-only.
          insert(target, getChar(KEY_MAP[keyCode]));
        }
        preventDefaultAndStopPropagation = true;
      } else if (isAlphabetic) {
        event.returnValue = false;
        preventDefaultAndStopPropagation = true;
      }
    }

    if (preventDefaultAndStopPropagation) {
      if (event.preventDefault) {
        event.preventDefault();
        event.stopPropagation();
      } else {
        event.cancelBubble = true;
      }
    }
  }

  function indexOf(array, element) {
    var i;

    if (array && array.length) {
      for (i = 0; i < array.length; i++) {
        if (array[i] === element) {
          return i;
        }
      }
    }

    return -1;
  }

  function getAllEditBoxes() {
    var inputs,
      textAreas,
      all = [],
      i;

    inputs = document.getElementsByTagName('input');
    textAreas = document.getElementsByTagName('textarea');

    for (i = 0; i < inputs.length; i++) {
      if (inputs[i].type.toLowerCase() === 'text') {
        all.push(inputs[i]);
      }
    }

    for (i = 0; i < textAreas.length; i++) {
      all.push(textAreas[i]);
    }

    return all;
  }

  function addEventListener(element, event, listener) {
    if (element.addEventListener) { // W3C
      element.removeEventListener(event, listener, false);
      element.addEventListener(event, listener, false);
    } else if (element.attachEvent) { // Trident 4.0-
      element.detachEvent('on' + event, listener);
      element.attachEvent('on' + event, listener);
    }
  }

  function addKeyboardEventListeners() {
    var all,
      element,
      cancel = true,
      i;

    if (!addToAll) {
      if (whitelist.length) {
        cancel = false;
        whitelist = whitelist.split(LIST_ELEMENT_DELIMITER);
      }

      if (blacklist.length) {
        cancel = false;
        addToAll = true; // A blacklist by itself implies 'addToAll'.
        blacklist = blacklist.split(LIST_ELEMENT_DELIMITER);
      }
    } else {
      if (blacklist.length) {
        cancel = false;
        blacklist = blacklist.split(LIST_ELEMENT_DELIMITER);
      }
    }

    if (cancel) {
      return;
    }

    all = getAllEditBoxes();

    if (addToAll) {
      for (i = 0; i < all.length; i++) {
        element = all[i];

        if (indexOf(blacklist, element.name) < 0) {
          addEventListener(element, 'keydown', keydownListener);
          addEventListener(element, 'keypress', keypressListener);

          // Initialize the input mode for this element.
          inputMode[element.name] = 0;
        }
      }
    } else {
      for (i = 0; i < all.length; i++) {
        element = all[i];

        if (indexOf(whitelist, element.name) >= 0) {
          addEventListener(element, 'keydown', keydownListener);
          addEventListener(element, 'keypress', keypressListener);

          // Initialize the input mode for this element.
          inputMode[element.name] = 0;
        }
      }
    }
  }

  function load() {
    initialize();
    addKeyboardEventListeners();
  }

  function onDomReady() {
    var isDomReadyCallbackCalled = false,
      isDomReadyListenerAdded = false;

    function callDomReadyCallback() {
      if (!isDomReadyCallbackCalled) {
        if (!document.body) { // In case IE gets a little overzealous.
          return setTimeout(callDomReadyCallback, 1);
        }

        isDomReadyCallbackCalled = true;
        load();
      }
    }

    function domReadyListener() {
      if (document.addEventListener) {
        document.removeEventListener('DOMContentLoaded', domReadyListener);
      } else if (document.attachEvent) {
        // Execution gets here only when document.readyState !== 'loading'
        document.detachEvent('onreadystatechange', domReadyListener);
      } else {
        return;
      }

      callDomReadyCallback();
    }

    function ieScrollCheck() {
      if (isDomReadyCallbackCalled) {
        return;
      }

      try {
        document.documentElement.doScroll('left');
      } catch (e) {
        setTimeout(ieScrollCheck, 1);
        return;
      }

      callDomReadyCallback();
    }

    function addDomReadyListener() {
      var isTopLevel = false;

      if (isDomReadyListenerAdded) {
        return;
      }
      isDomReadyListenerAdded = true;

      // In case DOM has already been loaded, call the function right away.
      if (document.readyState !== 'loading') {
        callDomReadyCallback();
        return;
      }

      if (document.addEventListener) {
        document.addEventListener('DOMContentLoaded', domReadyListener, false);
        window.addEventListener('load', domReadyListener, false); // Fallback.
      } else if (document.attachEvent) {
        document.attachEvent('onreadystatechange', domReadyListener);
        document.attachEvent('onload', domReadyListener); // Fallback.

        // http://javascript.nwbox.com/IEContentLoaded/
        try {
          isTopLevel = !window.frameElement;
        } catch (e) {}

        if (document.documentElement.doScroll && isTopLevel) {
          ieScrollCheck();
        }
      }
    }

    addDomReadyListener();
  }

  onDomReady();
}) (window);

<commit_msg>got rid of getCharCode()<commit_after>(function (window) {
  'use strict';

  var document = window.document,
    KEY_CHAR_MAP = {},
    CTRL_KEY_LISTENERS = {},
    DELIMITER = ':',
    inputMode = {}, // 0: Uyghur, 1: Latin
    addToAll = window.attachAll || false,
    whitelist = window.bedit_allow || [],
    blacklist = window.bedit_deny || [];

  function getChar(code) {
    return String.fromCharCode(code);
  }

  function initialize() {
    // ASCII -> Unicode of Uyghur characters
    KEY_CHAR_MAP.a = getChar(0x06BE);
    KEY_CHAR_MAP.b = getChar(0x0628);
    KEY_CHAR_MAP.c = getChar(0x063A);
    KEY_CHAR_MAP.D = getChar(0x0698);
    KEY_CHAR_MAP.d = getChar(0x062F);
    KEY_CHAR_MAP.e = getChar(0x06D0);
    KEY_CHAR_MAP.F = getChar(0x0641);
    KEY_CHAR_MAP.f = getChar(0x0627);
    KEY_CHAR_MAP.G = getChar(0x06AF);
    KEY_CHAR_MAP.g = getChar(0x06D5);
    KEY_CHAR_MAP.H = getChar(0x062E);
    KEY_CHAR_MAP.h = getChar(0x0649);
    KEY_CHAR_MAP.i = getChar(0x06AD);
    KEY_CHAR_MAP.J = getChar(0x062C);
    KEY_CHAR_MAP.j = getChar(0x0642);
    KEY_CHAR_MAP.K = getChar(0x06C6);
    KEY_CHAR_MAP.k = getChar(0x0643);
    KEY_CHAR_MAP.l = getChar(0x0644);
    KEY_CHAR_MAP.m = getChar(0x0645);
    KEY_CHAR_MAP.n = getChar(0x0646);
    KEY_CHAR_MAP.o = getChar(0x0648);
    KEY_CHAR_MAP.p = getChar(0x067E);
    KEY_CHAR_MAP.q = getChar(0x0686);
    KEY_CHAR_MAP.r = getChar(0x0631);
    KEY_CHAR_MAP.s = getChar(0x0633);
    KEY_CHAR_MAP.t = getChar(0x062A);
    KEY_CHAR_MAP.u = getChar(0x06C7);
    KEY_CHAR_MAP.v = getChar(0x06C8);
    KEY_CHAR_MAP.w = getChar(0x06CB);
    KEY_CHAR_MAP.x = getChar(0x0634);
    KEY_CHAR_MAP.y = getChar(0x064A);
    KEY_CHAR_MAP.z = getChar(0x0632);

    // Uyghur punctuation marks
    KEY_CHAR_MAP['/'] = getChar(0x0626);
    KEY_CHAR_MAP[';'] = getChar(0x061B);
    KEY_CHAR_MAP['?'] = getChar(0x061F);
    KEY_CHAR_MAP[','] = getChar(0x060C);

    // Invert parentheses, brackets, and braces for RTL layout.
    KEY_CHAR_MAP['('] = ')';
    KEY_CHAR_MAP[')'] = '(';
    KEY_CHAR_MAP['['] = ']';
    KEY_CHAR_MAP[']'] = '[';
    KEY_CHAR_MAP['}'] = getChar(0x00AB);
    KEY_CHAR_MAP['{'] = getChar(0x00BB);
    KEY_CHAR_MAP['<'] = '>'; // Sticking to the standard.
    KEY_CHAR_MAP['>'] = '<'; // Sticking to the standard.

    CTRL_KEY_LISTENERS.K = toggleInputMode;
    // [Ctrl-T] can no longer be used for inverting the input direction in WebKit (Blink), see:
    //   https://code.google.com/p/chromium/issues/detail?id=33056
    // Therefore, use 'Y' ('Y' as in the Uyghur word 'Yönilish')
    CTRL_KEY_LISTENERS.Y = toggleInputDirection;
  }

  function toggleInputMode(event) {
    var element = event.srcElement || event.target;

    inputMode[element.name] = 1 - inputMode[element.name];
  }

  function toggleInputDirection(event) {
    var element = event.srcElement || event.target;

    element.style.direction = (element.style.direction === 'ltr' ? 'rtl' : 'ltr');
  }

  function insert(element, ch) {
    var previousSelectionStart,
      currentSelectionStart,
      previousScrollTop,
      previousScrollLeft;

    if (document.selection && document.selection.createRange) { // Trident 5.0+
      document.selection.createRange().text = ch;
    } else { // W3C
      previousSelectionStart = element.selectionStart;

      // Gecko scrolls to top in textarea after input, fix this.
      if (element.type === 'textarea' && element.scrollTop) {
        previousScrollTop = element.scrollTop;
        previousScrollLeft = element.scrollLeft;
      }

      element.value = element.value.substring(0, element.selectionStart) +
        ch + element.value.substring(element.selectionEnd);

      if (previousScrollTop) {
        element.scrollTop = previousScrollTop;
        element.scrollLeft = previousScrollLeft;
      }

      currentSelectionStart = previousSelectionStart + ch.length;
      element.setSelectionRange(currentSelectionStart, currentSelectionStart);
    }
  }

  function keydownListener(e) {
    var event = e || window.event,
      isMetaKey = event.ctrlKey || event.metaKey,
      keyCode = event.keyCode || event.which,
      c = getChar(keyCode).toUpperCase();

    if (isMetaKey && CTRL_KEY_LISTENERS[c]) {
      CTRL_KEY_LISTENERS[c](event);

      if (event.preventDefault) {
        event.preventDefault();
        event.stopPropagation();
      } else {
        event.returnValue = false;
        event.cancelBubble = true;
      }
    }
  }

  function keypressListener(e) {
    var event = e || window.event,
      target = event.srcElement || event.target,
      isMetaKey = event.ctrlKey || event.metaKey,
      keyCode = event.keyCode || event.which,
      c = getChar(keyCode),
      isAlphabetic = /^[A-Z]{1}$/.test(c.toUpperCase()),
      preventDefaultAndStopPropagation = false;

    // The extra check for the meta key ([Ctrl]) is because:
    //   https://bugzilla.mozilla.org/show_bug.cgi?id=501496
    if (!isMetaKey && inputMode[target.name] === 0) {
      if (KEY_CHAR_MAP[c]) {
        if (event.keyCode && !event.which) { // Trident 4.0-
          event.keyCode = KEY_CHAR_MAP[c].charCodeAt(0);
        } else {                             // W3C event is read-only.
          insert(target, KEY_CHAR_MAP[c]);
        }
        preventDefaultAndStopPropagation = true;
      } else if (isAlphabetic) {
        event.returnValue = false;
        preventDefaultAndStopPropagation = true;
      }
    }

    if (preventDefaultAndStopPropagation) {
      if (event.preventDefault) {
        event.preventDefault();
        event.stopPropagation();
      } else {
        event.cancelBubble = true;
      }
    }
  }

  function indexOf(array, element) {
    var i;

    if (array && array.length) {
      for (i = 0; i < array.length; i++) {
        if (array[i] === element) {
          return i;
        }
      }
    }

    return -1;
  }

  function getAllEditBoxes() {
    var inputs,
      textAreas,
      all = [],
      i;

    inputs = document.getElementsByTagName('input');
    textAreas = document.getElementsByTagName('textarea');

    for (i = 0; i < inputs.length; i++) {
      if (inputs[i].type.toLowerCase() === 'text') {
        all.push(inputs[i]);
      }
    }

    for (i = 0; i < textAreas.length; i++) {
      all.push(textAreas[i]);
    }

    return all;
  }

  function addEventListener(element, event, listener) {
    if (element.addEventListener) { // W3C
      element.removeEventListener(event, listener, false);
      element.addEventListener(event, listener, false);
    } else if (element.attachEvent) { // Trident 4.0-
      element.detachEvent('on' + event, listener);
      element.attachEvent('on' + event, listener);
    }
  }

  function addKeyboardEventListeners() {
    var all,
      element,
      cancel = true,
      i;

    if (!addToAll) {
      if (whitelist.length) {
        cancel = false;
        whitelist = whitelist.split(DELIMITER);
      }

      if (blacklist.length) {
        cancel = false;
        addToAll = true; // A blacklist by itself implies 'addToAll'.
        blacklist = blacklist.split(DELIMITER);
      }
    } else {
      if (blacklist.length) {
        cancel = false;
        blacklist = blacklist.split(DELIMITER);
      }
    }

    if (cancel) {
      return;
    }

    all = getAllEditBoxes();

    if (addToAll) {
      for (i = 0; i < all.length; i++) {
        element = all[i];

        if (indexOf(blacklist, element.name) < 0) {
          addEventListener(element, 'keydown', keydownListener);
          addEventListener(element, 'keypress', keypressListener);

          // Initialize the input mode for this element.
          inputMode[element.name] = 0;
        }
      }
    } else {
      for (i = 0; i < all.length; i++) {
        element = all[i];

        if (indexOf(whitelist, element.name) >= 0) {
          addEventListener(element, 'keydown', keydownListener);
          addEventListener(element, 'keypress', keypressListener);

          // Initialize the input mode for this element.
          inputMode[element.name] = 0;
        }
      }
    }
  }

  function load() {
    initialize();
    addKeyboardEventListeners();
  }

  function onDomReady() {
    var isDomReadyCallbackCalled = false,
      isDomReadyListenerAdded = false;

    function callDomReadyCallback() {
      if (!isDomReadyCallbackCalled) {
        if (!document.body) { // In case IE gets a little overzealous.
          return setTimeout(callDomReadyCallback, 1);
        }

        isDomReadyCallbackCalled = true;
        load();
      }
    }

    function domReadyListener() {
      if (document.addEventListener) {
        document.removeEventListener('DOMContentLoaded', domReadyListener);
      } else if (document.attachEvent) {
        // Execution gets here only when document.readyState !== 'loading'
        document.detachEvent('onreadystatechange', domReadyListener);
      } else {
        return;
      }

      callDomReadyCallback();
    }

    function ieScrollCheck() {
      if (isDomReadyCallbackCalled) {
        return;
      }

      try {
        document.documentElement.doScroll('left');
      } catch (e) {
        setTimeout(ieScrollCheck, 1);
        return;
      }

      callDomReadyCallback();
    }

    function addDomReadyListener() {
      var isTopLevel = false;

      if (isDomReadyListenerAdded) {
        return;
      }
      isDomReadyListenerAdded = true;

      // In case DOM has already been loaded, call the function right away.
      if (document.readyState !== 'loading') {
        callDomReadyCallback();
        return;
      }

      if (document.addEventListener) {
        document.addEventListener('DOMContentLoaded', domReadyListener, false);
        window.addEventListener('load', domReadyListener, false); // Fallback.
      } else if (document.attachEvent) {
        document.attachEvent('onreadystatechange', domReadyListener);
        document.attachEvent('onload', domReadyListener); // Fallback.

        // http://javascript.nwbox.com/IEContentLoaded/
        try {
          isTopLevel = !window.frameElement;
        } catch (e) {}

        if (document.documentElement.doScroll && isTopLevel) {
          ieScrollCheck();
        }
      }
    }

    addDomReadyListener();
  }

  onDomReady();
}) (window);

<|endoftext|>


<commit_before>"use strict";
var etg = require("./etg");
var gfx = require("./gfx");
function fakepoint(x,y){
	this.x = x;
	this.y = y;
}
var Point;
if (typeof PIXI === "undefined"){
	Point = fakepoint;
	Point.prototype.set = Point;
}else Point = PIXI.Point;
function mkFont(font, color){
	if (typeof font == "number"){
		font += "px Dosis";
	}
	return {font: font, fill: color || "black"};
}
function reflectPos(obj) {
	var pos = obj instanceof Point ? obj : obj.position;
	pos.set(900 - pos.x, 600 - pos.y);
}
function creaturePos(j, i) {
	var row = i < 8 ? 0 : i < 15 ? 1 : 2;
	var column = row == 2 ? (i+1) % 8 : i % 8;
	var p = new Point(151 + column * 79 + (row == 1 ? 79/2 : 0), 344 + row * 33);
	if (j) {
		reflectPos(p);
	}
	return p;
}
function permanentPos(j, i) {
	var p = new Point(140 + (i % 8) * 64  , 504 + Math.floor(i / 8) * 40);
	if (j) {
		reflectPos(p);
	}
	return p;
}
function tgtToPos(t) {
	if (t instanceof etg.Creature) {
		return creaturePos(t.owner == t.owner.game.player2, t.getIndex());
	} else if (t instanceof etg.Weapon) {
		var p = new Point(666, 512);
		if (t.owner == t.owner.game.player2) reflectPos(p);
		return p;
	} else if (t instanceof etg.Shield) {
		var p = new Point(710, 532);
		if (t.owner == t.owner.game.player2) reflectPos(p);
		return p;
	} else if (t instanceof etg.Permanent) {
		return permanentPos(t.owner == t.owner.game.player2, t.getIndex());
	} else if (t instanceof etg.Player) {
		var p = new Point(50, 560);
		if (t == t.owner.game.player2) reflectPos(p);
		return p;
	} else if (t instanceof etg.CardInstance) {
		return new Point(t.owner == t.owner.game.player2 ? 20 : 780, (t.owner == t.owner.game.player2 ? 140 : 300) + 20 * t.owner.hand.indexOf(t));
	} else console.log("Unknown target");
}
var tximgcache = {};
function getTextImage(text, font, bgcolor, width) {
	if (!gfx.loaded || !text) return gfx.nopic;
	if (bgcolor === undefined) bgcolor = "";
	var size;
	if (typeof font == "number"){
		size = font;
		font = mkFont(font);
	}else size = parseInt(font.font);
	var fontkey = JSON.stringify(font) + bgcolor + "w" + width;
	if (!(fontkey in tximgcache)) {
		tximgcache[fontkey] = {};
	}
	if (text in tximgcache[fontkey]) {
		return tximgcache[fontkey][text];
	}
	var doc = new PIXI.DisplayObjectContainer();
	if (bgcolor !== ""){
		var bg = new PIXI.Graphics();
		doc.addChild(bg);
	}
	var pieces = text.replace(/\|/g, " | ").split(/(\d\d?:\d\d?|\$|\n)/);
	var x = 0, y = 0, h = Math.max(size, new PIXI.Text("j", font).height), w = 0;
	function pushChild(){
		var w = 0;
		if (x > 0){
			for (var i = 0; i<arguments.length; i++){
				w += arguments[i].width;
			}
		}
		if (width && x + w > width){
			x = 0;
			y += h;
		}
		for (var i = 0; i<arguments.length; i++){
			var c = arguments[i];
			c.position.set(x, y);
			x += c.width;
			doc.addChild(c);
		}
	}
	pieces.forEach(function(piece){
		if (piece == "\n"){
			w = Math.max(w, x);
			x = 0;
			y += h;
		}else if (piece == "$"){
			var spr = new PIXI.Sprite(gfx.gold);
			spr.scale.set(size/16, size/16);
			pushChild(spr);
		}else if (/^\d\d?:\d\d?$/.test(piece)) {
			var parse = piece.split(":");
			var num = parseInt(parse[0]);
			var icon = gfx.eicons[parseInt(parse[1])];
			if (num < 4) {
				var icons = [];
				for (var j = 0;j < num;j++) {
					var spr = new PIXI.Sprite(icon);
					spr.scale.set(size/32, size/32);
					icons.push(spr);
				}
				pushChild.apply(null, icons);
			}else{
				var spr = new PIXI.Sprite(icon);
				spr.scale.set(size/32, size/32);
				pushChild(new PIXI.Text(num, font), spr);
			}
		} else if (piece) {
			var txt = new PIXI.Text(piece, font);
			if (!width || x + txt.width < width){
				pushChild(txt);
			}else{
				piece.split(" ").forEach(function(word){
					if (word){
						pushChild(new PIXI.Text(word, font));
						if (x){
							x += 3;
						}
					}
				});
			}
		}
	});
	var rtex = new PIXI.RenderTexture(width || Math.max(w, x), y+h);
	if (bg){
		bg.beginFill(bgcolor);
		bg.drawRect(0, 0, rtex.width, rtex.height);
		bg.endFill();
	}
	rtex.render(doc);
	return tximgcache[fontkey][text] = rtex;
}
var sounds = {}, musics = {};
var soundEnabled = false, musicEnabled = false;
function loadSounds() {
	if (soundEnabled){
		for (var i = 0;i < arguments.length;i++) {
			sounds[arguments[i]] = new Audio("sound/" + arguments[i] + ".ogg");
		}
	}
}
function loadMusics() {
	if (musicEnabled){
		for (var i = 0;i < arguments.length;i++) {
			musics[arguments[i]] = new Audio("sound/" + arguments[i] + ".ogg");
		}
	}
}
function playSound(name, dontreset) {
	var sound = sounds[name];
	if (soundEnabled) {
		if (!sound){
			sound = sounds[name] = new Audio("sound/" + name + ".ogg");
		}
		if (!dontreset && sound.duration) sound.currentTime = 0;
		sound.play();
	}
}
function playMusic(name) {
	var music = musics[name];
	if (musicEnabled){
		if (!music){
			music = musics[name] = new Audio("sound/" + name + ".ogg");
		}
		if (music.duration) music.currentTime = 0;
		music.play();
	}
}
function changeSound(enabled) {
	soundEnabled = enabled;
	if (!soundEnabled) {
		for (var sound in sounds) {
			sounds[sound].pause();
		}
	}
}
function changeMusic(enabled) {
	musicEnabled = enabled;
	if (!musicEnabled) {
		for (var music in musics) {
			musics[music].pause();
		}
	}
}
exports.mkFont = mkFont;
exports.reflectPos = reflectPos;
exports.creaturePos = creaturePos;
exports.permanentPos = permanentPos;
exports.tgtToPos = tgtToPos;
if (typeof PIXI !== "undefined") exports.getTextImage = getTextImage;
exports.loadSounds = loadSounds;
exports.loadMusics = loadMusics;
exports.playSound = playSound;
exports.playMusic = playMusic;
exports.changeSound = changeSound;
exports.changeMusic = changeMusic;<commit_msg>Simplify tximgcache<commit_after>"use strict";
var etg = require("./etg");
var gfx = require("./gfx");
function fakepoint(x,y){
	this.x = x;
	this.y = y;
}
var Point;
if (typeof PIXI === "undefined"){
	Point = fakepoint;
	Point.prototype.set = Point;
}else Point = PIXI.Point;
function mkFont(font, color){
	if (typeof font == "number"){
		font += "px Dosis";
	}
	return {font: font, fill: color || "black"};
}
function reflectPos(obj) {
	var pos = obj instanceof Point ? obj : obj.position;
	pos.set(900 - pos.x, 600 - pos.y);
}
function creaturePos(j, i) {
	var row = i < 8 ? 0 : i < 15 ? 1 : 2;
	var column = row == 2 ? (i+1) % 8 : i % 8;
	var p = new Point(151 + column * 79 + (row == 1 ? 79/2 : 0), 344 + row * 33);
	if (j) {
		reflectPos(p);
	}
	return p;
}
function permanentPos(j, i) {
	var p = new Point(140 + (i % 8) * 64  , 504 + Math.floor(i / 8) * 40);
	if (j) {
		reflectPos(p);
	}
	return p;
}
function tgtToPos(t) {
	if (t instanceof etg.Creature) {
		return creaturePos(t.owner == t.owner.game.player2, t.getIndex());
	} else if (t instanceof etg.Weapon) {
		var p = new Point(666, 512);
		if (t.owner == t.owner.game.player2) reflectPos(p);
		return p;
	} else if (t instanceof etg.Shield) {
		var p = new Point(710, 532);
		if (t.owner == t.owner.game.player2) reflectPos(p);
		return p;
	} else if (t instanceof etg.Permanent) {
		return permanentPos(t.owner == t.owner.game.player2, t.getIndex());
	} else if (t instanceof etg.Player) {
		var p = new Point(50, 560);
		if (t == t.owner.game.player2) reflectPos(p);
		return p;
	} else if (t instanceof etg.CardInstance) {
		return new Point(t.owner == t.owner.game.player2 ? 20 : 780, (t.owner == t.owner.game.player2 ? 140 : 300) + 20 * t.owner.hand.indexOf(t));
	} else console.log("Unknown target");
}
var tximgcache = {};
function getTextImage(text, font, bgcolor, width) {
	if (!gfx.loaded || !text) return gfx.nopic;
	if (bgcolor === undefined) bgcolor = "";
	var size;
	if (typeof font == "number"){
		size = font;
		font = mkFont(font);
	}else size = parseInt(font.font);
	var key = JSON.stringify(arguments);
	if (key in tximgcache) {
		return tximgcache[key];
	}
	var doc = new PIXI.DisplayObjectContainer();
	if (bgcolor !== ""){
		var bg = new PIXI.Graphics();
		doc.addChild(bg);
	}
	var pieces = text.replace(/\|/g, " | ").split(/(\d\d?:\d\d?|\$|\n)/);
	var x = 0, y = 0, h = Math.max(size, new PIXI.Text("j", font).height), w = 0;
	function pushChild(){
		var w = 0;
		if (x > 0){
			for (var i = 0; i<arguments.length; i++){
				w += arguments[i].width;
			}
		}
		if (width && x + w > width){
			x = 0;
			y += h;
		}
		for (var i = 0; i<arguments.length; i++){
			var c = arguments[i];
			c.position.set(x, y);
			x += c.width;
			doc.addChild(c);
		}
	}
	pieces.forEach(function(piece){
		if (piece == "\n"){
			w = Math.max(w, x);
			x = 0;
			y += h;
		}else if (piece == "$"){
			var spr = new PIXI.Sprite(gfx.gold);
			spr.scale.set(size/16, size/16);
			pushChild(spr);
		}else if (/^\d\d?:\d\d?$/.test(piece)) {
			var parse = piece.split(":");
			var num = parseInt(parse[0]);
			var icon = gfx.eicons[parseInt(parse[1])];
			if (num < 4) {
				var icons = [];
				for (var j = 0;j < num;j++) {
					var spr = new PIXI.Sprite(icon);
					spr.scale.set(size/32, size/32);
					icons.push(spr);
				}
				pushChild.apply(null, icons);
			}else{
				var spr = new PIXI.Sprite(icon);
				spr.scale.set(size/32, size/32);
				pushChild(new PIXI.Text(num, font), spr);
			}
		} else if (piece) {
			var txt = new PIXI.Text(piece, font);
			if (!width || x + txt.width < width){
				pushChild(txt);
			}else{
				piece.split(" ").forEach(function(word){
					if (word){
						pushChild(new PIXI.Text(word, font));
						if (x){
							x += 3;
						}
					}
				});
			}
		}
	});
	var rtex = new PIXI.RenderTexture(width || Math.max(w, x), y+h);
	if (bg){
		bg.beginFill(bgcolor);
		bg.drawRect(0, 0, rtex.width, rtex.height);
		bg.endFill();
	}
	rtex.render(doc);
	return tximgcache[key] = rtex;
}
var sounds = {}, musics = {};
var soundEnabled = false, musicEnabled = false;
function loadSounds() {
	if (soundEnabled){
		for (var i = 0;i < arguments.length;i++) {
			sounds[arguments[i]] = new Audio("sound/" + arguments[i] + ".ogg");
		}
	}
}
function loadMusics() {
	if (musicEnabled){
		for (var i = 0;i < arguments.length;i++) {
			musics[arguments[i]] = new Audio("sound/" + arguments[i] + ".ogg");
		}
	}
}
function playSound(name, dontreset) {
	var sound = sounds[name];
	if (soundEnabled) {
		if (!sound){
			sound = sounds[name] = new Audio("sound/" + name + ".ogg");
		}
		if (!dontreset && sound.duration) sound.currentTime = 0;
		sound.play();
	}
}
function playMusic(name) {
	var music = musics[name];
	if (musicEnabled){
		if (!music){
			music = musics[name] = new Audio("sound/" + name + ".ogg");
		}
		if (music.duration) music.currentTime = 0;
		music.play();
	}
}
function changeSound(enabled) {
	soundEnabled = enabled;
	if (!soundEnabled) {
		for (var sound in sounds) {
			sounds[sound].pause();
		}
	}
}
function changeMusic(enabled) {
	musicEnabled = enabled;
	if (!musicEnabled) {
		for (var music in musics) {
			musics[music].pause();
		}
	}
}
exports.mkFont = mkFont;
exports.reflectPos = reflectPos;
exports.creaturePos = creaturePos;
exports.permanentPos = permanentPos;
exports.tgtToPos = tgtToPos;
if (typeof PIXI !== "undefined") exports.getTextImage = getTextImage;
exports.loadSounds = loadSounds;
exports.loadMusics = loadMusics;
exports.playSound = playSound;
exports.playMusic = playMusic;
exports.changeSound = changeSound;
exports.changeMusic = changeMusic;<|endoftext|>


<commit_before>var expand = require("reducers/expand")
var map = require("reducers/map")
var filter = require("reducers/filter")
var merge = require("reducers/merge")
var concat = require("reducers/concat")

var introspect = require("introspect-reduce")

module.exports = unpackSnapshot

function unpackSnapshot(snapshot) {
    return expand(snapshot, function (snapshot) {
        var allValues = flattenValue(snapshot)
        var ts = snapshot.__lastTimestamp__ || 0

        var actualValues = filter(allValues, isEvent)
        var cleansedValues = cleanse(concat(snapshot, actualValues))

        return map(cleansedValues, function (value) {
            return { eventType: "add", timestamp: ts, value: value }
        })
    })
}

function isEvent(value) {
    return value && value.type && Array.isArray(value.parentId)
}

function cleanse(list) {
    return map(list, function (item) {
        return Object.keys(item).reduce(function (acc, key) {
            var value = item[key]

            if (!Array.isArray(value)) {
                acc[key] = value
            } else if (!value.some(isEvent)) {
                acc[key] = value
            }

            return acc
        }, {})
    })
}

function flattenValue(value) {
    var keys = Object.keys(value)
    var values = map(keys, function (key) { return value[key] })
    return concat(value, flattenArrays(values))
}

function isObject(x) {
    return typeof x === "object" && x !== null
}

function flattenArrays(arr) {
    return expand(arr, function (value) {
        if (Array.isArray(value)) {
            return flattenArrays(value)
        } else if (isObject(value)) {
            return flattenValue(value)
        } else {
            return value
        }
    })
}
<commit_msg>do not require(introspect)"<commit_after>var expand = require("reducers/expand")
var map = require("reducers/map")
var filter = require("reducers/filter")
var merge = require("reducers/merge")
var concat = require("reducers/concat")

module.exports = unpackSnapshot

function unpackSnapshot(snapshot) {
    return expand(snapshot, function (snapshot) {
        var allValues = flattenValue(snapshot)
        var ts = snapshot.__lastTimestamp__ || 0

        var actualValues = filter(allValues, isEvent)
        var cleansedValues = cleanse(concat(snapshot, actualValues))

        return map(cleansedValues, function (value) {
            return { eventType: "add", timestamp: ts, value: value }
        })
    })
}

function isEvent(value) {
    return value && value.type && Array.isArray(value.parentId)
}

function cleanse(list) {
    return map(list, function (item) {
        return Object.keys(item).reduce(function (acc, key) {
            var value = item[key]

            if (!Array.isArray(value)) {
                acc[key] = value
            } else if (!value.some(isEvent)) {
                acc[key] = value
            }

            return acc
        }, {})
    })
}

function flattenValue(value) {
    var keys = Object.keys(value)
    var values = map(keys, function (key) { return value[key] })
    return concat(value, flattenArrays(values))
}

function isObject(x) {
    return typeof x === "object" && x !== null
}

function flattenArrays(arr) {
    return expand(arr, function (value) {
        if (Array.isArray(value)) {
            return flattenArrays(value)
        } else if (isObject(value)) {
            return flattenValue(value)
        } else {
            return value
        }
    })
}
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const http = require('http');
const he = require('he');
const db = require('sqlite');

const tablesToColumns = require('./dbinfo');

db.open('./vexdb.sqlite')
		.then(() => Object.entries(tablesToColumns).forEach(([table, columns]) => {
			var columnDefinitions = [];
			Object.entries(columns).forEach(([column, type]) => {
				columnDefinitions.push(`${column} ${type}`);
			});
			db.run(`DROP TABLE ${table}`);
			//db.run(`CREATE TABLE IF NOT EXISTS ${table} (${columnDefinitions.join(', ')})`)
			//		.catch(console.error);
		})).catch(console.error);
<commit_msg>Debugging.<commit_after>const Discord = require('discord.js');
const http = require('http');
const he = require('he');
const db = require('sqlite');

const tablesToColumns = require('./dbinfo');

db.open('./vexdb.sqlite')
		.then(() => Object.entries(tablesToColumns).forEach(([table, columns]) => {
			var columnDefinitions = [];
			Object.entries(columns).forEach(([column, type]) => {
				columnDefinitions.push(`${column} ${type}`);
			});
			//db.run(`DROP TABLE ${table}`);
			db.run(`CREATE TABLE IF NOT EXISTS ${table} (${columnDefinitions.join(', ')})`)
					.catch(console.error);
		})).catch(console.error);
<|endoftext|>


<commit_before>var fs = require('fs')
var version = require('../vue/package.json').version
var themeconfPath = 'themes/vue/_config.yml'
var installPath = 'src/v2/guide/installation.md'
var themeconfig = fs.readFileSync(themeconfPath, 'utf-8')
var installation = fs.readFileSync(installPath, 'utf-8')

fs.writeFileSync(
  themeconfPath,
  themeconfig.replace(/vue_version: .*/, 'vue_version: ' + version)
)

var sizes = {
  dev: 'vue.js',
  min: 'vue.min.js',
  gz: 'vue.min.js.gz',
  ro_gz: 'vue.common.min.js.gz'
}

for (var file in sizes) {
  var filesize = fs.statSync('../vue/dist/' + sizes[file], 'utf-8').size
  sizes[file] = (filesize / 1024).toFixed(2)
}

fs.writeFileSync(
  installPath,
  installation
    .replace(/vue_version: .*/, 'vue_version: ' + version)
    .replace(/(\w+)_size:.*/g, function (m, p1) {
      return p1 + '_size: "' + sizes[p1] + '"'
    })
)
<commit_msg>revert update.js file path for now<commit_after>var fs = require('fs')
var version = require('../vue/package.json').version
var themeconfPath = 'themes/vue/_config.yml'
var installPath = 'src/guide/installation.md'
var themeconfig = fs.readFileSync(themeconfPath, 'utf-8')
var installation = fs.readFileSync(installPath, 'utf-8')

fs.writeFileSync(
  themeconfPath,
  themeconfig.replace(/vue_version: .*/, 'vue_version: ' + version)
)

var sizes = {
  dev: 'vue.js',
  min: 'vue.min.js',
  gz: 'vue.min.js.gz',
  ro_gz: 'vue.common.min.js.gz'
}

for (var file in sizes) {
  var filesize = fs.statSync('../vue/dist/' + sizes[file], 'utf-8').size
  sizes[file] = (filesize / 1024).toFixed(2)
}

fs.writeFileSync(
  installPath,
  installation
    .replace(/vue_version: .*/, 'vue_version: ' + version)
    .replace(/(\w+)_size:.*/g, function (m, p1) {
      return p1 + '_size: "' + sizes[p1] + '"'
    })
)
<|endoftext|>


<commit_before>/**
 * Usage:
 *
 * node ./upload.js sources sourceZip dataSet1 solutionFileForDataSet1 dataSet2 solutionFileForDataSet2 ...
 *
 * sources is required. At least one data set is required. Valid data set names can be found in the dataSet const.
 */

const _ = require('lodash')
const debug = require('debug')('upload')
const fs = require('fs')
const joi = require('joi')
const request = require('request-promise')

const {HASH_CODE_JUDGE_AUTH_TOKEN: authToken} = process.env
if (authToken) {
  debug('token', shorten(authToken))
} else {
  console.error('HASH_CODE_JUDGE_AUTH_TOKEN not defined. Set it with your auth token to the Judge system.')
  process.exit()
}

const createUrlUri = 'https://hashcode-judge.appspot.com/_ah/api/judge/v1/upload/createUrl'
const submitUri = 'https://hashcode-judge.appspot.com/_ah/api/judge/v1/submissions'
const authorizationHeader = {'Authorization': `Bearer ${authToken}`}
const dataSets = {
  example: 5708411572322304,
  small: 6050554908246016,
  medium: 5184724934852608,
  big: 6310624841695232
}

const solutionSchema = joi.object().min(2)
    .keys(_.mapValues(dataSets, () => joi.string()))
    .keys({sources: joi.string().required()})

function* submitSolution (solution) {
  solution = joi.attempt(solution, solutionSchema, 'invalid solution parameters')

  const blobKeys = yield _.mapValues(solution, upload)
  const solutionBlobKeys = _.omit(blobKeys, 'sources')
  return yield _.mapValues(solutionBlobKeys, function (blobKey, dataSetName) {
    debug(`submitting data set ${dataSetName} (key: ${shorten(blobKey)}`)
    return submit(dataSets[dataSetName], blobKey, blobKeys.sources)
  })
}

function* upload (filePath) {
  const uploadUri = yield createUploadUri()
  debug(`uploading ${filePath} to ${shorten(uploadUri)}`)
  const formData = {file: fs.createReadStream(filePath)}
  const responseBody = yield request({
    method: 'POST',
    uri: uploadUri,
    formData,
    json: true})
  const blobKey = responseBody.file[0]
  debug(`uploaded ${filePath} (key: ${shorten(blobKey)})`)
  return blobKey
}

function* createUploadUri () {
  const response = yield request({
    method: 'GET',
    uri: createUrlUri,
    headers: authorizationHeader,
    json: true})
  return response.value
}

function* submit (dataSet, submissionBlobKey, sourcesBlobKey) {
  const queryParameters = {dataSet, submissionBlobKey, sourcesBlobKey}
  return yield request({
    method: 'POST',
    uri: submitUri,
    headers: authorizationHeader,
    qs: queryParameters
  })
}

function shorten (str) {
  return _(str).slice(0, 20).join('') + '...'
}

if (module === require.main) {
  const co = require('co')
  const explode = err => process.nextTick(() => { throw err })
  const solution = _(process.argv).drop(2).chunk(2).fromPairs().value()
  debug('solution', solution)
  co(submitSolution(solution)).catch(explode)
}
<commit_msg>feat: better upload script<commit_after>/**
 * Usage:
 *
 * node ./upload.js sources sourceZip dataSet1 solutionFileForDataSet1 dataSet2 solutionFileForDataSet2 ...
 *
 * sources is required. At least one data set is required. Valid data set names can be found in the dataSet const.
 */

const path = require('path')
const _ = require('lodash')
const debug = require('debug')('upload')
const fs = require('fs')
const joi = require('joi')
const request = require('request-promise')

const {HASH_CODE_JUDGE_AUTH_TOKEN: authToken} = process.env
if (authToken) {
  debug('token', shorten(authToken))
} else {
  console.error('HASH_CODE_JUDGE_AUTH_TOKEN not defined. Set it with your auth token to the Judge system.')
  process.exit()
}

const createUrlUri = 'https://hashcode-judge.appspot.com/_ah/api/judge/v1/upload/createUrl'
const submitUri = 'https://hashcode-judge.appspot.com/_ah/api/judge/v1/submissions'
const authorizationHeader = {'Authorization': `Bearer ${authToken}`}
const dataSets = {
  example: 5708411572322304,
  small: 6050554908246016,
  medium: 5184724934852608,
  big: 6310624841695232
}

const solutionSchema = joi.object().min(2)
    .keys(_.mapValues(dataSets, () => joi.string()))
    .keys({sources: joi.string().required()})

function* submitSolution (solution) {
  solution = joi.attempt(solution, solutionSchema, 'invalid solution parameters')

  const blobKeys = yield _.mapValues(solution, upload)
  const solutionBlobKeys = _.omit(blobKeys, 'sources')
  return yield _.mapValues(solutionBlobKeys, function (blobKey, dataSetName) {
    debug(`submitting data set ${dataSetName} (key: ${shorten(blobKey)}`)
    return submit(dataSets[dataSetName], blobKey, blobKeys.sources)
  })
}

function* upload (filePath) {
  const uploadUri = yield createUploadUri()
  debug(`uploading ${filePath} to ${shorten(uploadUri)}`)
  const formData = {file: fs.createReadStream(filePath)}
  const responseBody = yield request({
    method: 'POST',
    uri: uploadUri,
    formData,
    json: true})
  const blobKey = responseBody.file[0]
  debug(`uploaded ${filePath} (key: ${shorten(blobKey)})`)
  return blobKey
}

function* createUploadUri () {
  const response = yield request({
    method: 'GET',
    uri: createUrlUri,
    headers: authorizationHeader,
    json: true})
  return response.value
}

function* submit (dataSet, submissionBlobKey, sourcesBlobKey) {
  const queryParameters = {dataSet, submissionBlobKey, sourcesBlobKey}
  return yield request({
    method: 'POST',
    uri: submitUri,
    headers: authorizationHeader,
    qs: queryParameters
  })
}

function shorten (str) {
  return _(str).slice(0, 20).join('') + '...'
}

if (module === require.main) {
  const co = require('co')
  const explode = err => process.nextTick(() => { throw err })
  let solution = _(process.argv).drop(2).chunk(2).fromPairs().value()
  if (_.isEmpty(solution)) {
    solution = _.mapValues(dataSets, (id, name) => `${name}.in.out.txt`)
    solution.sources = path.join(__dirname, '.builds', _.last(fs.readdirSync(path.join(__dirname, '.builds')).sort()))
  }
  debug('solution', solution)
  co(submitSolution(solution)).catch(explode)
}
<|endoftext|>


<commit_before>var fs = require('fs'),
    MapboxClient = require('mapbox'),
    AWS = require('aws-sdk');

var districtsFile = process.argv[2],
    labelsFile = process.argv[3],
    user = process.env.MAPBOX_USERNAME,
    accessToken = process.env.MAPBOX_WRITE_SCOPE_ACCESS_TOKEN;

var client = new MapboxClient(accessToken);

// Upload district boundaries data to Mapbox.com
client.createUploadCredentials(function(err, credentials) {
  console.log('staging districts...');

  // Use aws-sdk to stage the file on Amazon S3
  var s3 = new AWS.S3({
       accessKeyId: credentials.accessKeyId,
       secretAccessKey: credentials.secretAccessKey,
       sessionToken: credentials.sessionToken,
       region: 'us-east-1'
  });
  s3.putObject({
    Bucket: credentials.bucket,
    Key: credentials.key,
    Body: fs.createReadStream(districtsFile)
  }, function(err, resp) {
    if (err) throw err;

    // Create a Mapbox upload
    client.createUpload({
       tileset: [user, 'congress'].join('.'),
       url: credentials.url,
       name: 'US_Congressional_Districts'
    }, function(err, upload) {
      if (err) throw err;
      console.log('districts uploaded, check mapbox.com/studio for updates.');
    });

  });
});

// Upload district labels data to Mapbox.com
client.createUploadCredentials(function(err, credentials) {
  console.log('staging district labels...');

  // Use aws-sdk to stage the file on Amazon S3
  var s3 = new AWS.S3({
       accessKeyId: credentials.accessKeyId,
       secretAccessKey: credentials.secretAccessKey,
       sessionToken: credentials.sessionToken,
       region: 'us-east-1'
  });
  s3.putObject({
    Bucket: credentials.bucket,
    Key: credentials.key,
    Body: fs.createReadStream(labelsFile)
  }, function(err, resp) {
    if (err) throw err;

    // Create a Mapbox upload
    client.createUpload({
       tileset: [user, 'congress-labels'].join('.'),
       url: credentials.url,
       name: 'US_Congressional_Districts_Labels'
    }, function(err, upload) {
      if (err) throw err;
      console.log('labels uploaded, check mapbox.com/studio for updates.');
    });

  });
});
<commit_msg>reduce repeated code in upload.js<commit_after>var fs = require('fs'),
    MapboxClient = require('mapbox'),
    AWS = require('aws-sdk');

var districtsFile = process.argv[2],
    labelsFile = process.argv[3],
    user = process.env.MAPBOX_USERNAME,
    accessToken = process.env.MAPBOX_WRITE_SCOPE_ACCESS_TOKEN;

var tileset_id = user + ".congress";
var tielset_name = "US_Congressional_Districts"

var client = new MapboxClient(accessToken);

// here's how to upload a file to Mapbox

function upload_tileset(file, id, name) {
  client.createUploadCredentials(function(err, credentials) {
    console.log('staging', file, '>', id, '...');

    // Use aws-sdk to stage the file on Amazon S3
    var s3 = new AWS.S3({
         accessKeyId: credentials.accessKeyId,
         secretAccessKey: credentials.secretAccessKey,
         sessionToken: credentials.sessionToken,
         region: 'us-east-1'
    });
    s3.putObject({
      Bucket: credentials.bucket,
      Key: credentials.key,
      Body: fs.createReadStream(file)
    }, function(err, resp) {
      if (err) throw err;

      // Create a Mapbox upload
      client.createUpload({
         tileset: id,
         url: credentials.url,
         name: name
      }, function(err, upload) {
        if (err) throw err;
        console.log(file, id, name, 'uploaded, check mapbox.com/studio for updates.');
      });

    });
  });
}

// do the upload

upload_tileset(labelsFile, tileset_id + '-labels', tielset_name + '_Labels')
upload_tileset(districtsFile, tileset_id, tielset_name)

<|endoftext|>


<commit_before>// Code and design by Felix Bade

var canvas = document.getElementById("graafi");
var context = canvas.getContext("2d");
var vertexInfo = document.getElementById("vertex-info");
var dataInputElement = document.getElementById("data");

context.lineWidth = 1.5;
var maxAllowedForce = 10;
var continueForceThreshold = 0.03;

var radius, vertexXs, vertexYs, vertexNames, vertexNeighbours, vertexConnectsOthers, edges, numberOfVertices, graphCenterX, graphCenterY, delta_t, pull, push, dx, dy, stopped, vertexVXs, vertexVYs;

function initialize() {
    clearCanvas();
    parseInput();
    stopped = false;
    tick();
}

function tick() {
    simulateGraphForces();
    reDraw();
    if (!stopped) {
        requestAnimationFrame(tick);
    }
}

// Initialization stuff

function parseInput() {
    var edgeNames = GraphParser.parseString(dataInputElement.value).compatibilityForm();
    findUniqueVertices(edgeNames);
    parseEdges(edgeNames);
    checkVerticesThatConnectOtherVertices();
    randomCoordinates();
}

function findUniqueVertices(edgeNames) {
    vertexNames = new Array();
    for (var i = 0; i < edgeNames.length; i++) {
        var firstVertexName = edgeNames[i][0];
        var secondVertexName = edgeNames[i][1];
        pushIfNotPresent(vertexNames, firstVertexName);
        pushIfNotPresent(vertexNames, secondVertexName);
    }
    numberOfVertices = vertexNames.length;
}

function parseEdges(edgeNames) {
    edges = new Array();
    vertexNeighbours = new Array(numberOfVertices);
    for (var i = 0; i < edgeNames.length; i++) {
        var firstVertex = vertexNames.indexOf(edgeNames[i][0]);
        var secondVertex = vertexNames.indexOf(edgeNames[i][1]);
        edges.push([firstVertex, secondVertex]);
        addNeighbour(firstVertex, secondVertex);
        addNeighbour(secondVertex, firstVertex);
    }
}

function addNeighbour(vertex, neighbour) {
    if (vertexNeighbours[vertex] == undefined) {
        vertexNeighbours[vertex] = new Array();
    }
    pushIfNotPresent(vertexNeighbours[vertex], neighbour);
}

function pushIfNotPresent(array, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] == value) {
            return;
        }
    }
    array.push(value);
}

function checkVerticesThatConnectOtherVertices() {
    vertexConnectsOthers = new Array(numberOfVertices);
    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        vertexConnectsOthers[vertex] = doesVertexConnectOtherVertices(vertex);
    }
}

function doesVertexConnectOtherVertices(vertex) {
    var neighbours = vertexNeighbours[vertex];
    if (neighbours.length < 2) {
        return false;
    }
    for (var a = 0; a < neighbours.length-1; a++) {
        for (var b = a+1; b < neighbours.length; b++) {
            if (!areNeighbours(neighbours[a], neighbours[b])) {
                return true;
            }
        }
    }
    return false;
}

function areNeighbours(x, y) {
    var xsNeighbours = vertexNeighbours[x];
    for (var i = 0; i < xsNeighbours.length; i++) {
        if (xsNeighbours[i] == y) {
            return true;
        }
    }
    return false;
}

function randomCoordinates() {
    vertexXs = new Array(numberOfVertices);
    vertexYs = new Array(numberOfVertices);
    vertexVXs = new Array(numberOfVertices);
    vertexVYs = new Array(numberOfVertices);
    for (var i = 0; i < numberOfVertices; i++) {
        vertexXs[i] = Math.random() * canvas.width;
        vertexYs[i] = Math.random() * canvas.height;
        vertexVXs[i] = 0;
        vertexVYs[i] = 0;
    }
}

// Simulation stuff

function simulateGraphForces() {
    var vertexForcesSumXs = new Array(numberOfVertices);
    var vertexForcesSumYs = new Array(numberOfVertices);
    var vertexForcesSumRs = new Array(numberOfVertices);
    var vertexNearestNeighbourDistance = new Array(numberOfVertices);

    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        var forcesSumX = 0;
        var forcesSumY = 0;

        // calculate pull
        var neighbours = vertexNeighbours[vertex];
        for (var i = 0; i < neighbours.length; i++) {
            var other = neighbours[i];
            dx = vertexXs[other] - vertexXs[vertex];
            dy = vertexYs[other] - vertexYs[vertex];
            // F ~ 1
            var dr = Math.sqrt(dx*dx + dy*dy);
            forcesSumX += dx / dr;
            forcesSumY += dy / dr;
        }

        // calculate push
        for (var other = 0; other < numberOfVertices; other++) {
            if (other == vertex) {
                continue;
            }
            dx = vertexXs[other] - vertexXs[vertex];
            dy = vertexYs[other] - vertexYs[vertex];
            // F ~ -1/(r^3)
            var drSquared = dx*dx + dy*dy;
            forcesSumX -= 100000 * dx / drSquared / drSquared;
            forcesSumY -= 100000 * dy / drSquared / drSquared;

            var dr = Math.sqrt(drSquared);
            if (vertexNearestNeighbourDistance[vertex] == undefined || dr < vertexNearestNeighbourDistance[vertex]) {
                vertexNearestNeighbourDistance[vertex] = dr;
            }
        }

        // Make sure that forcesSum is not arbitrarily big. If it is, two nodes are probably
        // just on top of each other
        forcesSumR = Math.sqrt(forcesSumX*forcesSumX + forcesSumY*forcesSumY);
        if (forcesSumR > maxAllowedForce) {
            vertexForcesSumXs[vertex] = forcesSumX * maxAllowedForce / forcesSumR;
            vertexForcesSumYs[vertex] = forcesSumY * maxAllowedForce / forcesSumR;
            vertexForcesSumRs[vertex] = maxAllowedForce;
        } else {
            vertexForcesSumXs[vertex] = forcesSumX;
            vertexForcesSumYs[vertex] = forcesSumY;
            vertexForcesSumRs[vertex] = forcesSumR;
        }
    }

    var minDistancePerForce;
    var maxForce = 0;
    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        maxForce = Math.max(maxForce, vertexForcesSumRs[vertex]);
        var distancePerForce = vertexNearestNeighbourDistance[vertex] / vertexForcesSumRs[vertex];
        if (vertex == 0 || distancePerForce < minDistancePerForce) {
            minDistancePerForce = distancePerForce;
        }
    }
    //console.log(vertexForcesSumRs);

    var delta_t = minDistancePerForce / 30; // Prevent bad shaking
    if (maxForce < 1) {
        delta_t *= maxForce;
    }
    //console.log(minDistancePerForce);
    if (maxForce < 0.01) {
        stopped = true;
    }
    //console.log(maxForce, delta_t, minDistancePerForce);
    //console.log(minDistancePerForce);

    //delta_t = Math.min(10000, delta_t);
    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        // Just keep the vertex being dragged under the cursor
        if (vertex == selectedVertex) {
            continue;
        }
        vertexVXs[vertex] += vertexForcesSumXs[vertex] * delta_t;
        vertexVYs[vertex] += vertexForcesSumYs[vertex] * delta_t;
        vertexVXs[vertex] *= 0.9;
        vertexVYs[vertex] *= 0.9;
    }

    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        vertexXs[vertex] += vertexVXs[vertex];
        vertexYs[vertex] += vertexVYs[vertex];
    }
}

// Rendering stuff

function reDraw() {
    clearCanvas();
    if (!isMouseDown) {
        moveGraphTowardsCenter();
    }
    drawEdgesAndVertices();
}

function moveGraphTowardsCenter() {
    var imageCenterX = canvas.width / 2;
    var imageCenterY = canvas.height / 2;
    calculateGraphCenter();
    for (var i = 0; i < numberOfVertices; i++) {
        vertexXs[i] += (imageCenterX - graphCenterX) / 30;
        vertexYs[i] += (imageCenterY - graphCenterY) / 30;
    }
}

function calculateGraphCenter() {
    var xSum = 0;
    var ySum = 0;
    for (var i = 0; i < numberOfVertices; i++) {
        xSum += vertexXs[i];
        ySum += vertexYs[i];
    }
    graphCenterX = xSum / numberOfVertices;
    graphCenterY = ySum / numberOfVertices;
}

function drawEdgesAndVertices() {
    drawNonImportantEdges();
    drawNonImportantVertices();
    drawImportantEdges();
    drawImportantVertices();
}

function drawNonImportantEdges() {
    setNonImportantStyle();
    for (var edge = 0; edge < edges.length; edge++) {
        if (!isEdgeImportant(edge)) {
            drawEdge(edge);
        }
    }
}

function drawImportantEdges() {
    setImportantStyle();
    for (var edge = 0; edge < edges.length; edge++) {
        if (isEdgeImportant(edge)) {
            drawEdge(edge);
        }
    }
}

function drawNonImportantVertices() {
    setNonImportantStyle();
    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        if (!isVertexImportant(vertex)) {
            drawVertex(vertex);
        }
    }
}

function drawImportantVertices() {
    setImportantStyle();
    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        if (isVertexImportant(vertex)) {
            drawVertex(vertex);
        }
    }
}

function setNonImportantStyle() {
    context.strokeStyle = "#ccc";
    context.fillStyle = "#ccc";
    radius = 4;
}

function setImportantStyle() {
    context.strokeStyle = "#444";
    context.fillStyle = "#444";
    radius = 6;
}

function isEdgeImportant(edge) {
    var vertex1 = edges[edge][0];
    var vertex2 = edges[edge][1];
    return isVertexImportant(vertex1) && isVertexImportant(vertex2);
}

function isVertexImportant(vertex) {
    if (!document.getElementById("emphasize-important-vertices").checked) {
        return true;
    }
    return vertexConnectsOthers[vertex];
}

function drawEdge(edge) {
    var vertex1 = edges[edge][0];
    var vertex2 = edges[edge][1];
    var x1 = vertexXs[vertex1];
    var y1 = vertexYs[vertex1];
    var x2 = vertexXs[vertex2];
    var y2 = vertexYs[vertex2];
    context.beginPath();
    context.moveTo(x1, y1);
    context.lineTo(x2, y2);
    context.stroke();
}

function drawVertex(vertex) {
    var x = vertexXs[vertex];
    var y = vertexYs[vertex];
    context.beginPath();
    context.arc(x, y, radius, 0, 2 * Math.PI, false);
    context.fill();
    context.stroke();
}

function clearCanvas() {
    context.fillStyle = "white";
    context.fillRect(0, 0, canvas.width, canvas.height);
}

// Mouse stuff

var isMouseDown = false;
var mouseX, mouseY;
var selectedVertex = -1;

function onMouseDown(event) {
    isMouseDown = true;
    updateMouseCoordinates(event);
    selectedVertex = getVertexByMouseCoordinates();
}

function onMouseMove(event) {
    updateMouseCoordinates(event);
    if (isMouseDown) {
        run();
        moveSelectedVertexToMouse();
    }
    updateLabel();
}

function onMouseUp(event) {
    isMouseDown = false;
    selectedVertex = -1;
}

function updateMouseCoordinates(event) {
    mouseX = event.offsetX;
    mouseY = event.offsetY;
}

function getVertexByMouseCoordinates() {
    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        var dx = vertexXs[vertex] - mouseX;
        var dy = vertexYs[vertex] - mouseY;
        var distance = Math.sqrt(dx*dx + dy*dy);
        if (distance < 8) {
            return vertex;
        }
    }
    return -1;
}

function moveSelectedVertexToMouse() {
    if (selectedVertex != -1) {
        vertexXs[selectedVertex] = mouseX;
        vertexYs[selectedVertex] = mouseY;
        reDraw();
    }
}

function updateLabel() {
    if (isMouseDown) {
        hideLabel();
    } else {
        vertex = getVertexByMouseCoordinates();
        if (vertex != -1) {
            var name = vertexNames[vertex];
            showLabel(name, mouseX, mouseY);
        } else {
            hideLabel();
        }
    }
}

function hideLabel() {
    showLabel('', -1000, -1000);
}

function showLabel(text, x, y) {
    vertexInfo.innerHTML = text;
    vertexInfo.style.left = x + 'px';
    vertexInfo.style.top = y + 'px';
}

function run() {
    if (stopped) {
        stopped = false;
        tick();
    }
}

// These must be in the end :(

document.getElementById("updatebutton").onclick = initialize;
document.getElementById("emphasize-important-vertices").onclick = reDraw;

canvas.addEventListener("mousedown", onMouseDown, true);
canvas.addEventListener("mouseup", onMouseUp, true);
canvas.addEventListener("mousemove", onMouseMove, true);
<commit_msg>update verkko.js<commit_after>// Code and design by Felix Bade

var canvas = document.getElementById("graafi");
var context = canvas.getContext("2d");
var vertexInfo = document.getElementById("vertex-info");
var dataInputElement = document.getElementById("data");

context.lineWidth = 1.5;
var maxAllowedForce = 10;

var radius, vertexXs, vertexYs, vertexNames, vertexNeighbours, vertexConnectsOthers, edges, numberOfVertices, graphCenterX, graphCenterY, delta_t, pull, push, dx, dy, stopped, vertexVXs, vertexVYs;

function initialize() {
    resizeCanvas();
    clearCanvas();
    parseInput();
    stopped = false;
    tick();
}

function tick() {
    simulateGraphForces();
    reDraw();
    if (!stopped) {
        requestAnimationFrame(tick);
    }
}

// Initialization stuff

function parseInput() {
    var edgeNames = GraphParser.parseString(dataInputElement.value).compatibilityForm();
    findUniqueVertices(edgeNames);
    parseEdges(edgeNames);
    checkVerticesThatConnectOtherVertices();
    randomCoordinates();
}

function findUniqueVertices(edgeNames) {
    vertexNames = new Array();
    for (var i = 0; i < edgeNames.length; i++) {
        var firstVertexName = edgeNames[i][0];
        var secondVertexName = edgeNames[i][1];
        pushIfNotPresent(vertexNames, firstVertexName);
        pushIfNotPresent(vertexNames, secondVertexName);
    }
    numberOfVertices = vertexNames.length;
}

function parseEdges(edgeNames) {
    edges = new Array();
    vertexNeighbours = new Array(numberOfVertices);
    for (var i = 0; i < edgeNames.length; i++) {
        var firstVertex = vertexNames.indexOf(edgeNames[i][0]);
        var secondVertex = vertexNames.indexOf(edgeNames[i][1]);
        edges.push([firstVertex, secondVertex]);
        addNeighbour(firstVertex, secondVertex);
        addNeighbour(secondVertex, firstVertex);
    }
}

function addNeighbour(vertex, neighbour) {
    if (vertexNeighbours[vertex] == undefined) {
        vertexNeighbours[vertex] = new Array();
    }
    pushIfNotPresent(vertexNeighbours[vertex], neighbour);
}

function pushIfNotPresent(array, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] == value) {
            return;
        }
    }
    array.push(value);
}

function checkVerticesThatConnectOtherVertices() {
    vertexConnectsOthers = new Array(numberOfVertices);
    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        vertexConnectsOthers[vertex] = doesVertexConnectOtherVertices(vertex);
    }
}

function doesVertexConnectOtherVertices(vertex) {
    var neighbours = vertexNeighbours[vertex];
    if (neighbours.length < 2) {
        return false;
    }
    for (var a = 0; a < neighbours.length-1; a++) {
        for (var b = a+1; b < neighbours.length; b++) {
            if (!areNeighbours(neighbours[a], neighbours[b])) {
                return true;
            }
        }
    }
    return false;
}

function areNeighbours(x, y) {
    var xsNeighbours = vertexNeighbours[x];
    for (var i = 0; i < xsNeighbours.length; i++) {
        if (xsNeighbours[i] == y) {
            return true;
        }
    }
    return false;
}

function randomCoordinates() {
    vertexXs = new Array(numberOfVertices);
    vertexYs = new Array(numberOfVertices);
    vertexVXs = new Array(numberOfVertices);
    vertexVYs = new Array(numberOfVertices);
    for (var i = 0; i < numberOfVertices; i++) {
        vertexXs[i] = Math.random() * canvas.width;
        vertexYs[i] = Math.random() * canvas.height;
        vertexVXs[i] = 0;
        vertexVYs[i] = 0;
    }
}

// Simulation stuff

function simulateGraphForces() {
    var vertexForcesSumXs = new Array(numberOfVertices);
    var vertexForcesSumYs = new Array(numberOfVertices);
    var vertexForcesSumRs = new Array(numberOfVertices);
    var vertexNearestNeighbourDistance = new Array(numberOfVertices);

    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        var forcesSumX = 0;
        var forcesSumY = 0;

        // calculate pull
        var neighbours = vertexNeighbours[vertex];
        for (var i = 0; i < neighbours.length; i++) {
            var other = neighbours[i];
            dx = vertexXs[other] - vertexXs[vertex];
            dy = vertexYs[other] - vertexYs[vertex];
            // F ~ 1
            var dr = Math.sqrt(dx*dx + dy*dy);
            forcesSumX += dx / dr;
            forcesSumY += dy / dr;
        }

        // calculate push
        for (var other = 0; other < numberOfVertices; other++) {
            if (other == vertex) {
                continue;
            }
            dx = vertexXs[other] - vertexXs[vertex];
            dy = vertexYs[other] - vertexYs[vertex];
            // F ~ -1/(r^3)
            var drSquared = dx*dx + dy*dy;
            forcesSumX -= 100000 * dx / drSquared / drSquared;
            forcesSumY -= 100000 * dy / drSquared / drSquared;

            var dr = Math.sqrt(drSquared);
            if (vertexNearestNeighbourDistance[vertex] == undefined || dr < vertexNearestNeighbourDistance[vertex]) {
                vertexNearestNeighbourDistance[vertex] = dr;
            }
        }

        // Make sure that forcesSum is not arbitrarily big. If it is, two nodes are probably
        // just on top of each other
        forcesSumR = Math.sqrt(forcesSumX*forcesSumX + forcesSumY*forcesSumY);
        if (forcesSumR > maxAllowedForce) {
            vertexForcesSumXs[vertex] = forcesSumX * maxAllowedForce / forcesSumR;
            vertexForcesSumYs[vertex] = forcesSumY * maxAllowedForce / forcesSumR;
            vertexForcesSumRs[vertex] = maxAllowedForce;
        } else {
            vertexForcesSumXs[vertex] = forcesSumX;
            vertexForcesSumYs[vertex] = forcesSumY;
            vertexForcesSumRs[vertex] = forcesSumR;
        }
    }

    var minDistancePerForce;
    var maxForce = 0;
    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        maxForce = Math.max(maxForce, vertexForcesSumRs[vertex]);
        var distancePerForce = vertexNearestNeighbourDistance[vertex] / vertexForcesSumRs[vertex];
        if (vertex == 0 || distancePerForce < minDistancePerForce) {
            minDistancePerForce = distancePerForce;
        }
    }
    //console.log(vertexForcesSumRs);

    var delta_t = minDistancePerForce / 30; // Prevent bad shaking
    if (maxForce < 1) {
        delta_t *= maxForce;
    }
    //console.log(minDistancePerForce);
    if (maxForce < 0.01) {
        stopped = true;
    }
    //console.log(maxForce, delta_t, minDistancePerForce);
    //console.log(minDistancePerForce);

    //delta_t = Math.min(10000, delta_t);
    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        // Just keep the vertex being dragged under the cursor
        if (vertex == selectedVertex) {
            continue;
        }
        vertexVXs[vertex] += vertexForcesSumXs[vertex] * delta_t;
        vertexVYs[vertex] += vertexForcesSumYs[vertex] * delta_t;
        vertexVXs[vertex] *= 0.9;
        vertexVYs[vertex] *= 0.9;
    }

    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        vertexXs[vertex] += vertexVXs[vertex];
        vertexYs[vertex] += vertexVYs[vertex];
    }
}

// Rendering stuff

function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
}

function reDraw() {
    clearCanvas();
    if (!isMouseDown) {
        moveGraphTowardsCenter();
    }
    drawEdgesAndVertices();
}

function moveGraphTowardsCenter() {
    var imageCenterX = canvas.width / 2;
    var imageCenterY = canvas.height / 2;
    calculateGraphCenter();
    for (var i = 0; i < numberOfVertices; i++) {
        vertexXs[i] += (imageCenterX - graphCenterX) / 30;
        vertexYs[i] += (imageCenterY - graphCenterY) / 30;
    }
}

function calculateGraphCenter() {
    var xSum = 0;
    var ySum = 0;
    for (var i = 0; i < numberOfVertices; i++) {
        xSum += vertexXs[i];
        ySum += vertexYs[i];
    }
    graphCenterX = xSum / numberOfVertices;
    graphCenterY = ySum / numberOfVertices;
}

function drawEdgesAndVertices() {
    drawNonImportantEdges();
    drawNonImportantVertices();
    drawImportantEdges();
    drawImportantVertices();
}

function drawNonImportantEdges() {
    setNonImportantStyle();
    for (var edge = 0; edge < edges.length; edge++) {
        if (!isEdgeImportant(edge)) {
            drawEdge(edge);
        }
    }
}

function drawImportantEdges() {
    setImportantStyle();
    for (var edge = 0; edge < edges.length; edge++) {
        if (isEdgeImportant(edge)) {
            drawEdge(edge);
        }
    }
}

function drawNonImportantVertices() {
    setNonImportantStyle();
    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        if (!isVertexImportant(vertex)) {
            drawVertex(vertex);
        }
    }
}

function drawImportantVertices() {
    setImportantStyle();
    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        if (isVertexImportant(vertex)) {
            drawVertex(vertex);
        }
    }
}

function setNonImportantStyle() {
    context.strokeStyle = "#ccc";
    context.fillStyle = "#ccc";
    radius = 4;
}

function setImportantStyle() {
    context.strokeStyle = "#444";
    context.fillStyle = "#444";
    radius = 6;
}

function isEdgeImportant(edge) {
    var vertex1 = edges[edge][0];
    var vertex2 = edges[edge][1];
    return isVertexImportant(vertex1) && isVertexImportant(vertex2);
}

function isVertexImportant(vertex) {
    if (!document.getElementById("emphasize-important-vertices").checked) {
        return true;
    }
    return vertexConnectsOthers[vertex];
}

function drawEdge(edge) {
    var vertex1 = edges[edge][0];
    var vertex2 = edges[edge][1];
    var x1 = vertexXs[vertex1];
    var y1 = vertexYs[vertex1];
    var x2 = vertexXs[vertex2];
    var y2 = vertexYs[vertex2];
    context.beginPath();
    context.moveTo(x1, y1);
    context.lineTo(x2, y2);
    context.stroke();
}

function drawVertex(vertex) {
    var x = vertexXs[vertex];
    var y = vertexYs[vertex];
    context.beginPath();
    context.arc(x, y, radius, 0, 2 * Math.PI, false);
    context.fill();
    context.stroke();
}

function clearCanvas() {
    context.fillStyle = "white";
    context.fillRect(0, 0, canvas.width, canvas.height);
}

// Mouse stuff

var isMouseDown = false;
var mouseX, mouseY;
var selectedVertex = -1;

function onMouseDown(event) {
    isMouseDown = true;
    updateMouseCoordinates(event);
    selectedVertex = getVertexByMouseCoordinates();
}

function onMouseMove(event) {
    updateMouseCoordinates(event);
    if (isMouseDown) {
        run();
        moveSelectedVertexToMouse();
    }
    updateLabel();
}

function onMouseUp(event) {
    isMouseDown = false;
    selectedVertex = -1;
}

function updateMouseCoordinates(event) {
    mouseX = event.offsetX;
    mouseY = event.offsetY;
}

function getVertexByMouseCoordinates() {
    for (var vertex = 0; vertex < numberOfVertices; vertex++) {
        var dx = vertexXs[vertex] - mouseX;
        var dy = vertexYs[vertex] - mouseY;
        var distance = Math.sqrt(dx*dx + dy*dy);
        if (distance < 8) {
            return vertex;
        }
    }
    return -1;
}

function moveSelectedVertexToMouse() {
    if (selectedVertex != -1) {
        vertexXs[selectedVertex] = mouseX;
        vertexYs[selectedVertex] = mouseY;
        reDraw();
    }
}

function updateLabel() {
    if (isMouseDown) {
        hideLabel();
    } else {
        vertex = getVertexByMouseCoordinates();
        if (vertex != -1) {
            var name = vertexNames[vertex];
            showLabel(name, mouseX, mouseY);
        } else {
            hideLabel();
        }
    }
}

function hideLabel() {
    showLabel('', -1000, -1000);
}

function showLabel(text, x, y) {
    vertexInfo.innerHTML = text;
    vertexInfo.style.left = x + 'px';
    vertexInfo.style.top = y + 'px';
}

function run() {
    if (stopped) {
        stopped = false;
        tick();
    }
}

// These must be in the end :(

document.getElementById("emphasize-important-vertices").onclick = reDraw;
dataInputElement.oninput = initialize;
initialize();

document.body.onresize = resizeCanvas;

canvas.addEventListener("mousedown", onMouseDown, true);
canvas.addEventListener("mouseup", onMouseUp, true);
canvas.addEventListener("mousemove", onMouseMove, true);
<|endoftext|>


<commit_before>#!/usr/bin/env node

var program = require('./node_modules/commander');
var gpio = require('./node_modules/pi-gpio');

var PIN_LED = 7;

function sanitizeInterval(val) {
    var interval = parseInt(val, 10);
    if (isNaN(val)) {
        console.log("***Invalid interval passed. Setting to the default.***");
        return 5;
    } else {
        return interval;
    }
}

function sanitizeEmail(val) {
    var emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
    if (!emailRegex.test(val)) {
        console.log("***Invalid email passed. Setting to the default.***");
        return "me@example.com";
    } else {
        return val;
    }
}

program
  .version('0.0.1')
  .usage('./vermin.js')
  .option('-i, --interval [number]', 'Polling interval, in seconds', sanitizeInterval, 5)
  .option('-e, --email [email]', 'Notification email address', sanitizeEmail, 'me@example.com')
  .parse(process.argv);

console.log('interval: %j', program.interval);
console.log('email: %j', program.email);
console.log("Running...");

function reset() {
    gpio.open(PIN_LED, "output", function(err) {
        gpio.write(PIN_LED, 0, function() {
            gpio.close(PIN_LED);
        });
    });
}

function exec() {

    var ledPinState = gpio.read(PIN_LED);

    console.log("pin state", ledPinState);

    gpio.open(PIN_LED, "output", function(err) {
        gpio.write(PIN_LED, 1, function() {
            gpio.close(PIN_LED);
        });
    });

    setInterval(exec, program.interval * 1000);
}

//reset();
exec();
<commit_msg>Output error.<commit_after>#!/usr/bin/env node

var program = require('./node_modules/commander');
var gpio = require('./node_modules/pi-gpio');

var PIN_LED = 7;

function sanitizeInterval(val) {
    var interval = parseInt(val, 10);
    if (isNaN(val)) {
        console.log("***Invalid interval passed. Setting to the default.***");
        return 5;
    } else {
        return interval;
    }
}

function sanitizeEmail(val) {
    var emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
    if (!emailRegex.test(val)) {
        console.log("***Invalid email passed. Setting to the default.***");
        return "me@example.com";
    } else {
        return val;
    }
}

program
  .version('0.0.1')
  .usage('./vermin.js')
  .option('-i, --interval [number]', 'Polling interval, in seconds', sanitizeInterval, 5)
  .option('-e, --email [email]', 'Notification email address', sanitizeEmail, 'me@example.com')
  .parse(process.argv);

console.log('interval: %j', program.interval);
console.log('email: %j', program.email);
console.log("Running...");

function reset() {
    gpio.open(PIN_LED, "output", function(err) {
        gpio.write(PIN_LED, 0, function() {
            gpio.close(PIN_LED);
        });
    });
}

function exec() {

    var ledPinState = gpio.read(PIN_LED);

    console.log("pin state", ledPinState);

    gpio.open(PIN_LED, "output", function(err) {
        if (err) {
            console.log(err);
        } else {
            gpio.write(PIN_LED, 1, function() {
                gpio.close(PIN_LED);
            });
            setInterval(exec, program.interval * 1000);
        }
    });
}

reset();
exec();
<|endoftext|>


<commit_before>#!/usr/bin/env node

var program = require('./node_modules/commander');
var gpio = require('./node_modules/pi-gpio');

var PIN_LED = 7;

function sanitizeInterval(val) {
    var interval = parseInt(val, 10);
    if (isNaN(val)) {
        console.log("***Invalid interval passed. Setting to the default.***");
        return 5;
    } else {
        return interval;
    }
}

function sanitizeEmail(val) {
    var emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
    if (!emailRegex.test(val)) {
        console.log("***Invalid email passed. Setting to the default.***");
        return "me@example.com";
    } else {
        return val;
    }
}

program
  .version('0.0.1')
  .usage('./vermin.js')
  .option('-i, --interval [number]', 'Polling interval, in seconds', sanitizeInterval, 5)
  .option('-e, --email [email]', 'Notification email address', sanitizeEmail, 'me@example.com')
  .parse(process.argv);

console.log('interval: %j', program.interval);
console.log('email: %j', program.email);
console.log("Running...");

function reset() {
    gpio.open(PIN_LED, "output", function(err) { });
    gpio.write(PIN_LED, 1, function() { });
    setTimeout(function () {
        gpio.write(PIN_LED, 0);
        gpio.close(PIN_LED);
    }, 2000);
}

function exec() {

    var ledPinState = gpio.read(PIN_LED);

    console.log("pin state", ledPinState);

    gpio.open(PIN_LED, "output", function(err) {
        if (err) {
            console.log(err);
        } else {
            gpio.write(PIN_LED, 1, function() {
                gpio.close(PIN_LED);
            });
            setInterval(exec, program.interval * 1000);
        }
    });
}

reset();
// exec();
<commit_msg>Mental reset.<commit_after>#!/usr/bin/env node

var program = require('./node_modules/commander');
var gpio = require('./node_modules/pi-gpio');

var PIN_LED = 7;

function sanitizeInterval(val) {
    var interval = parseInt(val, 10);
    if (isNaN(val)) {
        console.log("***Invalid interval passed. Setting to the default.***");
        return 5;
    } else {
        return interval;
    }
}

function sanitizeEmail(val) {
    var emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
    if (!emailRegex.test(val)) {
        console.log("***Invalid email passed. Setting to the default.***");
        return "me@example.com";
    } else {
        return val;
    }
}

program
  .version('0.0.1')
  .usage('./vermin.js')
  .option('-i, --interval [number]', 'Polling interval, in seconds', sanitizeInterval, 5)
  .option('-e, --email [email]', 'Notification email address', sanitizeEmail, 'me@example.com')
  .parse(process.argv);

console.log('interval: %j', program.interval);
console.log('email: %j', program.email);
console.log("Running...");

function exec() {
    gpio.open(PIN_LED, "output", function(err) {
        gpio.write(PIN_LED, 1, function() {
            gpio.close(PIN_LED);
        });
    });
}

exec();
<|endoftext|>


<commit_before>/*jslint browser:true*/

var vlille = (function () {
    'use strict';

    var API_PROXY_BASE = 'http://localhost:8001/';

    /**
     *
     * @param  {String} xml [description]
     * @return {Object}     [description]
     */
    function xmlToJson(xml) {
        //TODO
        return xml;
    }

    /**
     * Format params object to url query args string.
     * @param  {Object} params [description]
     * @return {String}        [description]
     */
    function formatParams(params) {
        var key,
            query = [];

        for (key in params) {
            if (params.hasOwnProperty(key)) {
                query.push(key + '=' + params[key]);
            }
        }

        return query.join('&');
    }

    /**
     * Basic XHR request implementation.
     * @param  {String}   url     [description]
     * @param  {Object}   params  [description]
     * @param  {Function} resolve [description]
     * @param  {Function} reject  [description]
     */
    function request(url, params, resolve, reject) {
        var requestObj = new XMLHttpRequest(),
            urlWithParams = url;

        if (params) {
            urlWithParams += '?' + formatParams(params);
        }

        requestObj.open('GET', urlWithParams);

        requestObj.addEventListener('load', function (event) {
            var target = event.target;

            if (target.status === 200) {
                resolve(xmlToJson(target.response));
            } else {
                reject(target);
            }
        });

        requestObj.addEventListener('error', function (event) {
            reject(new Error(event));
        });

        requestObj.send();
    }

    /**
     * Publics
     */

    function getStation(id) {
        var params = {
            borne: id
        };

        return {
            then: function (resolve, reject) {
                request(API_PROXY_BASE + 'xml-stations.aspx', params, resolve, reject);
            }
        };
    }

    function getStations() {
        return {
            then: function (resolve, reject) {
                request(API_PROXY_BASE + 'xml-stations.aspx', null, resolve, reject);
            }
        };
    }

    return {
        stations: getStations,
        station: getStation
    };
}());<commit_msg>Implements xmlToJson to get json from vlille API<commit_after>/*jslint browser:true*/

var vlille = (function () {
    'use strict';

    var API_PROXY_BASE = 'http://localhost:8001/';

    /**
     *
     * @param  {String} xml [description]
     * @return {Object}     [description]
     */
    function xmlToJson(xmlNode) {
        var i,
            j,
            len,
            len2,
            markers = xmlNode.childNodes[0].children || [],
            attributes,
            jsonMarker,
            jsonArray = [];

        // imperative way
        for (i = 0, len = markers.length; i < len; i += 1) {
            jsonMarker = {};
            attributes = markers[i].attributes;

            for (j = 0, len2 = attributes.length; j < len2; j += 1) {
                jsonMarker[attributes[j].name] = attributes[j].value;
            }

            jsonArray.push(jsonMarker);
        }

        // functionnal way
        // markers = [].slice.call(markers);
        // jsonArray = markers.map(function (marker) {
        //     var attributes = [].slice.call(marker.attributes);

        //     return attributes.reduce(function (prevAttr, currentAttr) {
        //         prevAttr[currentAttr.name] = currentAttr.value;

        //         return prevAttr;
        //     }, {});
        // });

        return jsonArray;
    }

    /**
     * Format params object to url query args string.
     * @param  {Object} params [description]
     * @return {String}        [description]
     */
    function formatParams(params) {
        var key,
            query = [];

        for (key in params) {
            if (params.hasOwnProperty(key)) {
                query.push(key + '=' + params[key]);
            }
        }

        return query.join('&');
    }

    /**
     * Basic XHR request implementation.
     * @param  {String}   url     [description]
     * @param  {Object}   params  [description]
     * @param  {Function} resolve [description]
     * @param  {Function} reject  [description]
     */
    function request(url, params, resolve, reject) {
        var requestObj = new XMLHttpRequest(),
            urlWithParams = url;

        if (params) {
            urlWithParams += '?' + formatParams(params);
        }

        requestObj.open('GET', urlWithParams);

        requestObj.addEventListener('load', function (event) {
            var target = event.target;

            if (target.status === 200) {
                resolve(xmlToJson(target.responseXML));
            } else {
                reject(target);
            }
        });

        requestObj.addEventListener('error', function (event) {
            reject(new Error(event));
        });

        requestObj.send();
    }

    /**
     * Publics
     */

    function getStation(id) {
        var params = {
            borne: id
        };

        return {
            then: function (resolve, reject) {
                request(API_PROXY_BASE + 'xml-stations.aspx', params, resolve, reject);
            }
        };
    }

    function getStations() {
        return {
            then: function (resolve, reject) {
                request(API_PROXY_BASE + 'xml-stations.aspx', null, resolve, reject);
            }
        };
    }

    return {
        stations: getStations,
        station: getStation
    };
}());<|endoftext|>