<commit_before>// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

define(['jquery', 'api', 'util', 'input', 'cterm', 'hterm'],
function($, api, util, input, cterm){
  'use strict';

  var LINES_IN_TINY = 3;
  var LINES_IN_PAGE = 24;

  var SCROLL_PAGE = {};
  var SCROLL_FULL = {};

  var scrollback = $('#scrollback');
  var jobProto = scrollback.children('.job.proto').detach();
  jobProto.removeClass('proto');

  function jobFromElement(elem) {
    return $(elem).closest('.job').data('jobPrivate');
  }

  var currentTopic = null;

  function focusTopic(nextTopic) {
    if (currentTopic) currentTopic.removeClass('topic')
    currentTopic = nextTopic;
    if (currentTopic) {
      currentTopic.addClass('topic');
      util.scrollIntoView(scrollback, currentTopic);
      currentTopic.focus();
    }
  }

  function nextTopic(n) {
    var next = currentTopic;
    if (!currentTopic) {
      next = scrollback.children('.job').last();
    } else if (!(currentTopic.hasClass('focus'))) {
      // ignore motion if topic wasn't focused, and just refocus
    } else {
      switch (n) {
        case -1:
          next = currentTopic.next('.job');
          break;
        case 1:
          next = currentTopic.prev('.job');
          break;
      }
    }
    if (next && next.length) {
      focusTopic(next);
    }
  }

  function atLastTopic() {
    return currentTopic && currentTopic.next('.job').length === 0;
  }
  function topicCommand() {
    return currentTopic ? currentTopic.data('jobPrivate').cmd : '';
  }

  scrollback.on('scroll', '.output-container', function() {
    // TODO(jasvir): Do the same for scrollBottom
    if ($(this).scrollTop() === 0) {
      $(this).css('-webkit-mask-image', 'none');
    } else {
      $(this).css('-webkit-mask-image',
        '-webkit-gradient(linear, left top, 0 10,'
        + ' from(rgba(0,0,0,0)), to(rgba(0,0,0,1)))');
    }
  });

  scrollback.on('click', '.send-eof',
    function(e) { jobFromElement(this).sender('\x04'); });
  scrollback.on('click', '.send-sigint',
    function(e) { jobFromElement(this).signaler('int'); });
  scrollback.on('click', '.send-sigquit',
    function(e) { jobFromElement(this).signaler('quit'); });
  scrollback.on('click', '.send-sigkill',
    function(e) { jobFromElement(this).signaler('kill'); });

  scrollback.on('click', '.view-hide',
    function(e) { jobFromElement(this).sizeOutput('hide'); });
  scrollback.on('click', '.view-tiny',
    function(e) { jobFromElement(this).sizeOutput('tiny'); });
  scrollback.on('click', '.view-page',
    function(e) { jobFromElement(this).sizeOutput('page'); });
  scrollback.on('click', '.view-full',
    function(e) { jobFromElement(this).sizeOutput('full'); });
  scrollback.on('click', '.view-deferred',
    function(e) { jobFromElement(this).loadDeferredOutput(); });

  scrollback.on('click', '.job',
    function(e) { jobFromElement(this).takeTopic(); });

  scrollback.on('focusin', '.job',
    function(e) { $(this).addClass('focus'); });
  scrollback.on('focusout', '.job',
    function(e) { $(this).removeClass('focus'); });

  // keydown handler for jobs, even when running
  var jobKeydown = input.keyHandler({
    functions: {
      pageDown:           function(j) { j.scroller(1, SCROLL_PAGE); },
      pageUp:             function(j) { j.scroller(-1, SCROLL_PAGE); },
    },
    bindings: {
      'PAGE_DOWN,   ALT+PAGE_DOWN':   'pageDown',
      'PAGE_UP,     ALT+PAGE_UP':     'pageUp',
      '             ALT+SPACE':       'pageDown',
      '             ALT+SHIFT+SPACE': 'pageUp',

      'END,  ALT+END':    function(j) { j.scroller(1, SCROLL_FULL); },
      'HOME, ALT+HOME':   function(j) { j.scroller(-1, SCROLL_FULL); },

      'ALT+0':            function(j) { j.sizeOutput('hide'); },
      'ALT+1':            function(j) { j.sizeOutput('tiny'); },
      'ALT+2':            function(j) { j.sizeOutput('page'); },
      'ALT+3':            function(j) { j.sizeOutput('full'); },
    }
  });

  function keydown(e) {
    if (!currentTopic) return;
    var j = currentTopic.data('jobPrivate');
    return jobKeydown(e, j);
  }

  var forwardingKeys = input.keyHandler({
    functions: {
      forward: function() { }
    },
    bindings: {
      'ALT+SPACE,   ALT+SHIFT+SPACE':           'forward',
      '    PAGE_UP,     PAGE_DOWN':             'forward',
      'ALT+PAGE_UP, ALT+PAGE_DOWN':             'forward',
      '    HOME,        END':                   'forward',
      'ALT+HOME,    ALT+END':                   'forward',
      'ALT+0, ALT+1, ALT+2, ALT+3':             'forward',
      'ALT+UP, ALT+DOWN, ALT+LEFT, ALT+RIGHT':  'forward',
      'ALT+RETURN':                             'forward',
    }
  });

  function forwardingKeydown(e) {
    var r = forwardingKeys(e);
    if (r !== undefined) {
      $(window).triggerHandler(e);
      e.stopImmediatePropagation();
      e.originalEvent.stopImmediatePropagation();
        // needed due to bug in jQuery: stop DOM added handlers, too
      e.preventDefault();
      return r;
    }
  }

  var jobCount = 0;

  function newJob(cmd, job, historical) {
    if (!job) {
      job = "job" + (++jobCount);
    }

    var node = jobProto.clone();
    node.attr('data-job', job);
    node.find('.command').text(cmd);
    if (historical) {
      node.prependTo(scrollback);
    } else {
      node.appendTo(scrollback);
      util.scrollIntoView(scrollback, node);
    }

    var output = node.find('.output-container');
    var outputArea = output.find('.output');
    var deferredOutputLoader = null;
    var terminal = null;
    var terminalOutput = function() { };
    var terminalIsFullScreen = false;
    var takingInput = false;

    function sender(s) {
      api.api('input', {job: job, input: s}, function() {});
    };

    function signaler(s) {
      s = 'kill'; // TODO: remove this when int and quit work
      api.api('input', {job: job, signal: s}, function() {});
    };

    function sizeOutput(m) {
      if (deferredOutputLoader) {
        loadDeferredOutput();
      } else {
        node.removeClass('output-hide output-tiny output-page output-full');
        node.addClass('output-' + m);
        setTimeout(function() { util.scrollIntoView(scrollback, node); }, 100);
          // have to wait until layout has been recomputed for new size
      }
    };

    function setDeferredOutput(f) {
      deferredOutputLoader = f;
      node.removeClass('output-hide output-tiny output-page output-full');
      node.addClass('output-hide max-deferred');
    }

    function loadDeferredOutput() {
      if (deferredOutputLoader) {
        deferredOutputLoader(job);
        deferredOutputLoader = null;
        node.removeClass('max-deferred');
        adjustOutput();
      }
    }

    function scroller(dir, amt) {
      var line = 10; // TODO: Should be determined dynamically

      var scroll = 0;
      if      (amt === SCROLL_FULL)  scroll = outputArea.height();
      else if (amt === SCROLL_PAGE)  scroll = output.height() - 2 * line;

      output.scrollTop(output.scrollTop() + scroll * dir);
    }

    function takeTopic() {
      focusTopic(node);
    }

    var jobPrivate = {
      cmd: cmd,
      sender: sender,
      signaler: signaler,
      sizeOutput: sizeOutput,
      loadDeferredOutput: loadDeferredOutput,
      scroller: scroller,
      takeTopic: takeTopic
    };
    node.data('jobPrivate', jobPrivate);

    function adjustOutput() {
      var m, s;

      if (terminalIsFullScreen) {
        m =  s = 'full';
      } else if (terminal) {
        var n = terminal.getLineCount();
        var lh = outputArea.css('lineHeight').replace(/px$/,'');
        var oh = outputArea.height();
        if (lh >= 1 && oh > 0) {
          n = Math.max(n, Math.floor(oh / lh));
        }

        if (n < 1 && takingInput) n = 1;

        if (n == 0)                   m = s = 'hide';
        else if (n <= LINES_IN_TINY)  m = s = 'tiny';
        else if (n <= LINES_IN_PAGE)  m = s = 'page';
        else                          { m = 'full'; s = 'page'; }
      } else {
        m = s = 'hide';
      }

      if (!deferredOutputLoader) {
        node.removeClass('max-hide max-tiny max-page max-full');
        node.addClass('max-' + m);
        sizeOutput(s);
      }
    };

    function setClass(cls) {
      if (!node.hasClass(cls)) {
        node.removeClass('running complete').addClass(cls);
      }
    };

    function goCTerm() {
      removeOutput();

      var pleaseGoFullScreen = false;
      var fullScreenReplayBuffer = '';
      var FULL_SCREEN_REPLAY_MAX_LENGTH = 4096;
      var SCROLL_END_TOLERANCE = 6;

      terminal = new cterm.Terminal(outputArea,
            function() { pleaseGoFullScreen = true; }
      );

      terminal.io.onVTKeystroke = sender;
      terminal.io.sendString = sender;
      if (takingInput) {
        node.on('keydown', forwardingKeydown);
        terminal.installKeyboard(node);
        terminal.setCursorVisible(true);
      }

      terminalOutput = function(cls, txt) {
        if (fullScreenReplayBuffer !== null) {
          if (fullScreenReplayBuffer.length + txt.length
              < FULL_SCREEN_REPLAY_MAX_LENGTH) {
            fullScreenReplayBuffer += txt;
          } else {
            fullScreenReplayBuffer = null;
          }
        }

        var oldEnd = outputArea.outerHeight();
        var wasAtEnd = (
              output.scrollTop() + output.height() + SCROLL_END_TOLERANCE
              >= oldEnd);

        terminal.setSpanClass(cls);
        terminal.interpret(txt);

        if (wasAtEnd) {
          util.scrollIntoView(output, outputArea, oldEnd);
        }

        if (pleaseGoFullScreen) {
          pleaseGoFullScreen = false;
          outputArea.empty();
          goHTerm(fullScreenReplayBuffer || '');
        } else {
          adjustOutput();
        }
      };
    }

    function goHTerm(txt) {
      removeOutput();

      outputArea.addClass('vtoutput');
      var node = $('

', { 'class': 'terminal' })
      node.appendTo(outputArea);
      terminal = new hterm.Terminal();
      terminal.decorate(node.get(0));
      terminal.io.onVTKeystroke = sender;
      terminal.io.sendString = sender;
      terminal.onTerminalReady = function() {
        var style = getComputedStyle(outputArea.get(0));
        terminal.setFontSize(style.fontSize.replace(/px$/,''));
        terminal.setBackgroundColor(style.backgroundColor);
        terminal.setForegroundColor(style.color);
        terminal.setWidth(80);
        terminal.setHeight(24);
        terminal.setAutoCarriageReturn(true);
        if (takingInput) {
          terminal.installKeyboard();
        }
        terminalIsFullScreen = true;
        adjustOutput();
        node.get(0).scrollIntoView(true);

        if (txt) {
          terminal.interpret(txt);
        }
      };

      terminalOutput = function(cls, txt) {
        terminal.interpret(txt);
      };
    }

    function removeOutput() {
      if (terminal !== null) {
        terminal.uninstallKeyboard();
        terminal.setCursorVisible(false);
        adjustOutput();
        terminal = null;
      }
      terminalOutput = function() { };
    };

    function removeInput() {
      node.find('.input-controls').remove();
      takingInput = false;
    }

    function addOutput(cls, txt) {
      if (terminal === null) {
        goCTerm();
      }
      terminalOutput(cls, txt);
    }

    function setRunning() {
      setClass('running');
    }

    function setComplete(exitcode) {
      setClass(exitcode === 0 ? 'complete' : 'failed');
      removeInput();
      removeOutput();
    }

    if (!historical) {
      takingInput = true;
      addOutput('stdout', '');
      takeTopic();
    } else {
      removeInput();
    }

    var jobPublic = {
      job: job,
      user: true,
      addOutput: addOutput,
      setRunning: setRunning,
      setComplete: setComplete,
      setDeferredOutput: setDeferredOutput
    };

    node.data('jobPublic', jobPublic);
    return jobPublic;
  }

  var unknownJob = {
    user: false,
    addOutput: function(cls, txt) {
      var node = $('', { 'class': cls }).text(txt);
      node.appendTo(scrollback);
      node[0].scrollIntoView(true);
    },
    setRunning: function() { },
    setComplete: function(e) { },
    setDeferredOutput: function(f) { }
  };

  function fromJob(job) {
    return $('.job[data-job="' + job + '"]').data('jobPublic') || unknownJob;
  }

  function toDiv(j) {
    return $('.job[data-job="' + j.job + '"]');
  }

  return {
    newJob:           function(cmd, job) { return newJob(cmd, job, false); },
    addHistoricalJob: function(cmd, job) { return newJob(cmd, job, true); },
    fromJob: fromJob,
    unknownJob: unknownJob,

    nextTopic: nextTopic,
    atLastTopic: atLastTopic,
    topicCommand: topicCommand,
    keydown: keydown
  };
});
<commit_msg>'freeze' output from hterm<commit_after>// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

define(['jquery', 'api', 'util', 'input', 'cterm', 'hterm'],
function($, api, util, input, cterm){
  'use strict';

  var LINES_IN_TINY = 3;
  var LINES_IN_PAGE = 24;

  var SCROLL_PAGE = {};
  var SCROLL_FULL = {};

  var scrollback = $('#scrollback');
  var jobProto = scrollback.children('.job.proto').detach();
  jobProto.removeClass('proto');

  function jobFromElement(elem) {
    return $(elem).closest('.job').data('jobPrivate');
  }

  var currentTopic = null;

  function focusTopic(nextTopic) {
    if (currentTopic) currentTopic.removeClass('topic')
    currentTopic = nextTopic;
    if (currentTopic) {
      currentTopic.addClass('topic');
      util.scrollIntoView(scrollback, currentTopic);
      currentTopic.focus();
    }
  }

  function nextTopic(n) {
    var next = currentTopic;
    if (!currentTopic) {
      next = scrollback.children('.job').last();
    } else if (!(currentTopic.hasClass('focus'))) {
      // ignore motion if topic wasn't focused, and just refocus
    } else {
      switch (n) {
        case -1:
          next = currentTopic.next('.job');
          break;
        case 1:
          next = currentTopic.prev('.job');
          break;
      }
    }
    if (next && next.length) {
      focusTopic(next);
    }
  }

  function atLastTopic() {
    return currentTopic && currentTopic.next('.job').length === 0;
  }
  function topicCommand() {
    return currentTopic ? currentTopic.data('jobPrivate').cmd : '';
  }

  scrollback.on('scroll', '.output-container', function() {
    // TODO(jasvir): Do the same for scrollBottom
    if ($(this).scrollTop() === 0) {
      $(this).css('-webkit-mask-image', 'none');
    } else {
      $(this).css('-webkit-mask-image',
        '-webkit-gradient(linear, left top, 0 10,'
        + ' from(rgba(0,0,0,0)), to(rgba(0,0,0,1)))');
    }
  });

  scrollback.on('click', '.send-eof',
    function(e) { jobFromElement(this).sender('\x04'); });
  scrollback.on('click', '.send-sigint',
    function(e) { jobFromElement(this).signaler('int'); });
  scrollback.on('click', '.send-sigquit',
    function(e) { jobFromElement(this).signaler('quit'); });
  scrollback.on('click', '.send-sigkill',
    function(e) { jobFromElement(this).signaler('kill'); });

  scrollback.on('click', '.view-hide',
    function(e) { jobFromElement(this).sizeOutput('hide'); });
  scrollback.on('click', '.view-tiny',
    function(e) { jobFromElement(this).sizeOutput('tiny'); });
  scrollback.on('click', '.view-page',
    function(e) { jobFromElement(this).sizeOutput('page'); });
  scrollback.on('click', '.view-full',
    function(e) { jobFromElement(this).sizeOutput('full'); });
  scrollback.on('click', '.view-deferred',
    function(e) { jobFromElement(this).loadDeferredOutput(); });

  scrollback.on('click', '.job',
    function(e) { jobFromElement(this).takeTopic(); });

  scrollback.on('focusin', '.job',
    function(e) { $(this).addClass('focus'); });
  scrollback.on('focusout', '.job',
    function(e) { $(this).removeClass('focus'); });

  // keydown handler for jobs, even when running
  var jobKeydown = input.keyHandler({
    functions: {
      pageDown:           function(j) { j.scroller(1, SCROLL_PAGE); },
      pageUp:             function(j) { j.scroller(-1, SCROLL_PAGE); },
    },
    bindings: {
      'PAGE_DOWN,   ALT+PAGE_DOWN':   'pageDown',
      'PAGE_UP,     ALT+PAGE_UP':     'pageUp',
      '             ALT+SPACE':       'pageDown',
      '             ALT+SHIFT+SPACE': 'pageUp',

      'END,  ALT+END':    function(j) { j.scroller(1, SCROLL_FULL); },
      'HOME, ALT+HOME':   function(j) { j.scroller(-1, SCROLL_FULL); },

      'ALT+0':            function(j) { j.sizeOutput('hide'); },
      'ALT+1':            function(j) { j.sizeOutput('tiny'); },
      'ALT+2':            function(j) { j.sizeOutput('page'); },
      'ALT+3':            function(j) { j.sizeOutput('full'); },
    }
  });

  function keydown(e) {
    if (!currentTopic) return;
    var j = currentTopic.data('jobPrivate');
    return jobKeydown(e, j);
  }

  var forwardingKeys = input.keyHandler({
    functions: {
      forward: function() { }
    },
    bindings: {
      'ALT+SPACE,   ALT+SHIFT+SPACE':           'forward',
      '    PAGE_UP,     PAGE_DOWN':             'forward',
      'ALT+PAGE_UP, ALT+PAGE_DOWN':             'forward',
      '    HOME,        END':                   'forward',
      'ALT+HOME,    ALT+END':                   'forward',
      'ALT+0, ALT+1, ALT+2, ALT+3':             'forward',
      'ALT+UP, ALT+DOWN, ALT+LEFT, ALT+RIGHT':  'forward',
      'ALT+RETURN':                             'forward',
    }
  });

  function forwardingKeydown(e) {
    var r = forwardingKeys(e);
    if (r !== undefined) {
      $(window).triggerHandler(e);
      e.stopImmediatePropagation();
      e.originalEvent.stopImmediatePropagation();
        // needed due to bug in jQuery: stop DOM added handlers, too
      e.preventDefault();
      return r;
    }
  }

  var jobCount = 0;

  function newJob(cmd, job, historical) {
    if (!job) {
      job = "job" + (++jobCount);
    }

    var node = jobProto.clone();
    node.attr('data-job', job);
    node.find('.command').text(cmd);
    if (historical) {
      node.prependTo(scrollback);
    } else {
      node.appendTo(scrollback);
      util.scrollIntoView(scrollback, node);
    }

    var output = node.find('.output-container');
    var outputArea = output.find('.output');
    var deferredOutputLoader = null;
    var terminal = null;
    var terminalOutput = function() { };
    var terminalIsFullScreen = false;
    var takingInput = false;

    function sender(s) {
      api.api('input', {job: job, input: s}, function() {});
    };

    function signaler(s) {
      s = 'kill'; // TODO: remove this when int and quit work
      api.api('input', {job: job, signal: s}, function() {});
    };

    function sizeOutput(m) {
      if (deferredOutputLoader) {
        loadDeferredOutput();
      } else {
        node.removeClass('output-hide output-tiny output-page output-full');
        node.addClass('output-' + m);
        setTimeout(function() { util.scrollIntoView(scrollback, node); }, 100);
          // have to wait until layout has been recomputed for new size
      }
    };

    function setDeferredOutput(f) {
      deferredOutputLoader = f;
      node.removeClass('output-hide output-tiny output-page output-full');
      node.addClass('output-hide max-deferred');
    }

    function loadDeferredOutput() {
      if (deferredOutputLoader) {
        deferredOutputLoader(job);
        deferredOutputLoader = null;
        node.removeClass('max-deferred');
        adjustOutput();
      }
    }

    function scroller(dir, amt) {
      var line = 10; // TODO: Should be determined dynamically

      var scroll = 0;
      if      (amt === SCROLL_FULL)  scroll = outputArea.height();
      else if (amt === SCROLL_PAGE)  scroll = output.height() - 2 * line;

      output.scrollTop(output.scrollTop() + scroll * dir);
    }

    function takeTopic() {
      focusTopic(node);
    }

    var jobPrivate = {
      cmd: cmd,
      sender: sender,
      signaler: signaler,
      sizeOutput: sizeOutput,
      loadDeferredOutput: loadDeferredOutput,
      scroller: scroller,
      takeTopic: takeTopic
    };
    node.data('jobPrivate', jobPrivate);

    function adjustOutput() {
      var m, s;

      if (terminalIsFullScreen) {
        m =  s = 'full';
      } else {
        var n = 0;
        if (terminal) {
          n = terminal.getLineCount();
        }
        var lh = outputArea.css('lineHeight').replace(/px$/,'');
        var oh = outputArea.height();
        if (lh >= 1 && oh > 0) {
          n = Math.max(n, Math.floor(oh / lh));
        }

        if (n < 1 && takingInput) n = 1;

        if (n == 0)                   m = s = 'hide';
        else if (n <= LINES_IN_TINY)  m = s = 'tiny';
        else if (n <= LINES_IN_PAGE)  m = s = 'page';
        else                          { m = 'full'; s = 'page'; }
      }

      if (!deferredOutputLoader) {
        node.removeClass('max-hide max-tiny max-page max-full');
        node.addClass('max-' + m);
        sizeOutput(s);
      }
    };

    function setClass(cls) {
      if (!node.hasClass(cls)) {
        node.removeClass('running complete').addClass(cls);
      }
    };

    function goCTerm() {
      removeOutput();

      var pleaseGoFullScreen = false;
      var fullScreenReplayBuffer = '';
      var FULL_SCREEN_REPLAY_MAX_LENGTH = 4096;
      var SCROLL_END_TOLERANCE = 6;

      terminal = new cterm.Terminal(outputArea,
            function() { pleaseGoFullScreen = true; }
      );

      terminal.io.onVTKeystroke = sender;
      terminal.io.sendString = sender;
      if (takingInput) {
        node.on('keydown', forwardingKeydown);
        terminal.installKeyboard(node);
        terminal.setCursorVisible(true);
      }

      terminalOutput = function(cls, txt) {
        if (fullScreenReplayBuffer !== null) {
          if (fullScreenReplayBuffer.length + txt.length
              < FULL_SCREEN_REPLAY_MAX_LENGTH) {
            fullScreenReplayBuffer += txt;
          } else {
            fullScreenReplayBuffer = null;
          }
        }

        var oldEnd = outputArea.outerHeight();
        var wasAtEnd = (
              output.scrollTop() + output.height() + SCROLL_END_TOLERANCE
              >= oldEnd);

        terminal.setSpanClass(cls);
        terminal.interpret(txt);

        if (wasAtEnd) {
          util.scrollIntoView(output, outputArea, oldEnd);
        }

        if (pleaseGoFullScreen) {
          pleaseGoFullScreen = false;
          outputArea.empty();
          goHTerm(fullScreenReplayBuffer || '');
        } else {
          adjustOutput();
        }
      };
    }

    function goHTerm(txt) {
      removeOutput();

      outputArea.addClass('vtoutput');
      var node = $('

', { 'class': 'terminal' })
      node.appendTo(outputArea);
      terminal = new hterm.Terminal();
      terminal.decorate(node.get(0));
      terminal.io.onVTKeystroke = sender;
      terminal.io.sendString = sender;
      terminal.onTerminalReady = function() {
        var style = getComputedStyle(outputArea.get(0));
        terminal.setFontSize(style.fontSize.replace(/px$/,''));
        terminal.setBackgroundColor(style.backgroundColor);
        terminal.setForegroundColor(style.color);
        terminal.setWidth(80);
        terminal.setHeight(24);
        terminal.setAutoCarriageReturn(true);
        if (takingInput) {
          terminal.installKeyboard();
        }
        terminalIsFullScreen = true;
        adjustOutput();
        node.get(0).scrollIntoView(true);

        if (txt) {
          terminal.interpret(txt);
        }
      };

      terminalOutput = function(cls, txt) {
        terminal.interpret(txt);
      };
    }

    function freezeHTerm() {
      var rows = terminal.screen_.rowsArray;
      var newSpans = [];
      for (var i = rows.length - 1; i >= 0; i -= 1) {
        var parts = rows[i].childNodes;
        if (newSpans.length === 0) {
          if (parts.length == 0) continue;
          if (parts.length == 1
              && parts[0].nodeType == 3
              && parts[0].textContent.length == 0) continue;
        }

        var eol = '\n';
        for (var j = parts.length - 1; j >= 0; j -= 1) {
          var elem = parts[j];
          var newNode = null;
          if (elem.nodeType == 1) {
            newNode = $('

', { style: elem.style.cssText });
            newNode.text(elem.innerText + eol);
          } else if (elem.nodeType == 3) {
            newNode = $('

');
            newNode.text(elem.textContent + eol);
          }
          if (newNode) {
            newSpans.unshift(newNode);
            eol = '';
          }
        }
      }
      outputArea.empty();
      outputArea.removeClass('vtoutput');
      newSpans.forEach(function(sp) { outputArea.append(sp); });
    }

    function removeOutput() {
      if (terminal !== null) {
        terminal.uninstallKeyboard();
        terminal.setCursorVisible(false);
        if (terminalIsFullScreen) {
          freezeHTerm();
        }
        terminal = null;
        terminalIsFullScreen = false;
        adjustOutput();
      }
      terminalOutput = function() { };
    };

    function removeInput() {
      node.find('.input-controls').remove();
      takingInput = false;
    }

    function addOutput(cls, txt) {
      if (terminal === null) {
        goCTerm();
      }
      terminalOutput(cls, txt);
    }

    function setRunning() {
      setClass('running');
    }

    function setComplete(exitcode) {
      setClass(exitcode === 0 ? 'complete' : 'failed');
      removeInput();
      removeOutput();
    }

    if (!historical) {
      takingInput = true;
      addOutput('stdout', '');
      takeTopic();
    } else {
      removeInput();
    }

    var jobPublic = {
      job: job,
      user: true,
      addOutput: addOutput,
      setRunning: setRunning,
      setComplete: setComplete,
      setDeferredOutput: setDeferredOutput
    };

    node.data('jobPublic', jobPublic);
    return jobPublic;
  }

  var unknownJob = {
    user: false,
    addOutput: function(cls, txt) {
      var node = $('', { 'class': cls }).text(txt);
      node.appendTo(scrollback);
      node[0].scrollIntoView(true);
    },
    setRunning: function() { },
    setComplete: function(e) { },
    setDeferredOutput: function(f) { }
  };

  function fromJob(job) {
    return $('.job[data-job="' + job + '"]').data('jobPublic') || unknownJob;
  }

  function toDiv(j) {
    return $('.job[data-job="' + j.job + '"]');
  }

  return {
    newJob:           function(cmd, job) { return newJob(cmd, job, false); },
    addHistoricalJob: function(cmd, job) { return newJob(cmd, job, true); },
    fromJob: fromJob,
    unknownJob: unknownJob,

    nextTopic: nextTopic,
    atLastTopic: atLastTopic,
    topicCommand: topicCommand,
    keydown: keydown
  };
});
<|endoftext|>


<commit_before>'use strict';

var videoElement = document.querySelector('video');
var audioSelect = document.querySelector('select#audioSource');
var videoSelect = document.querySelector('select#videoSource');

navigator.getUserMedia = navigator.getUserMedia ||
  navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

function gotSources(sourceInfos) {
  for (var i = 0; i !== sourceInfos.length; ++i) {
    var sourceInfo = sourceInfos[i];
    var option = document.createElement('option');
    option.value = sourceInfo.id;
    if (sourceInfo.kind === 'audio') {
      option.text = sourceInfo.label || 'microphone ' +
        (audioSelect.length + 1);
      audioSelect.appendChild(option);
    } else if (sourceInfo.kind === 'video') {
      option.text = sourceInfo.label || 'camera ' + (videoSelect.length + 1);
      videoSelect.appendChild(option);
    } else {
      console.log('Some other kind of source: ', sourceInfo);
    }
  }
}

if (typeof MediaStreamTrack === 'undefined' ||
    typeof MediaStreamTrack.getSources === 'undefined') {
  alert('This browser does not support MediaStreamTrack.\n\nTry Chrome.');
} else {
  MediaStreamTrack.getSources(gotSources);
}

function successCallback(stream) {
  window.stream = stream; // make stream available to console
  videoElement.src = window.URL.createObjectURL(stream);
  videoElement.play();
  alert("success");
}

function errorCallback(error) {
  alert('navigator.getUserMedia error: ', error);
}

function start() {
  alert("window stream = "+ window.stream);
  if (window.stream) {
    videoElement.src = null;
    window.stream.stop();
    alert("window stream stoped");
  }
  var audioSource = audioSelect.value;

  var videoSource = videoSelect.value;
  alert("videoSource now is = "+ videoSource);
  var constraints = {
    audio: {
      optional: [{
        sourceId: audioSource
      }]
    },
    video: {
      optional: [{
        sourceId: videoSource
      }]
    }
  };
  navigator.getUserMedia(constraints, successCallback, errorCallback);
}

audioSelect.onchange = start;
videoSelect.onchange = start;

start();
<commit_msg>just for update<commit_after>'use strict';

var videoElement = document.querySelector('video');
var audioSelect = document.querySelector('select#audioSource');
var videoSelect = document.querySelector('select#videoSource');

navigator.getUserMedia = navigator.getUserMedia ||
  navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

function gotSources(sourceInfos) {
  for (var i = 0; i !== sourceInfos.length; ++i) {
    var sourceInfo = sourceInfos[i];
    var option = document.createElement('option');
    option.value = sourceInfo.id;
    if (sourceInfo.kind === 'audio') {
      option.text = sourceInfo.label || 'microphone ' +
        (audioSelect.length + 1);
      audioSelect.appendChild(option);
    } else if (sourceInfo.kind === 'video') {
      option.text = sourceInfo.label || 'camera ' + (videoSelect.length + 1);
      videoSelect.appendChild(option);
    } else {
      console.log('Some other kind of source: ', sourceInfo);
    }
  }
}

if (typeof MediaStreamTrack === 'undefined' ||
    typeof MediaStreamTrack.getSources === 'undefined') {
  alert('This browser does not support MediaStreamTrack.\n\nTry Chrome.');
} else {
  MediaStreamTrack.getSources(gotSources);
}

function successCallback(stream) {
  window.stream = stream; // make stream available to console
  videoElement.src = window.URL.createObjectURL(stream);
  videoElement.play();
  alert("success");
}

function errorCallback(error) {
  alert('navigator.getUserMedia error: ', error);
}

function start() {
  alert("window stream = "+ window.stream);
  if (window.stream) {
    videoElement.src = null;
    alert("window stream is going to stop");
    window.stream.stop();
    alert("window stream stoped");
  }
  var audioSource = audioSelect.value;

  var videoSource = videoSelect.value;
  alert("videoSource now is = "+ videoSource);
  var constraints = {
    audio: {
      optional: [{
        sourceId: audioSource
      }]
    },
    video: {
      optional: [{
        sourceId: videoSource
      }]
    }
  };
  navigator.getUserMedia(constraints, successCallback, errorCallback);
}

audioSelect.onchange = start;
videoSelect.onchange = start;

start();
<|endoftext|>


<commit_before>function modProd(a,b,n){
    if(b==0) return 0;
    if(b==1) return a%n;
    return (modProd(a,(b-b%10)/10,n)*10+(b%10)*a)%n;
}

function modPow(a,b,n){
    if(b==0) return 1;
    if(b==1) return a%n;
    if(b%2==0){
        var c=modPow(a,b/2,n);
        return modProd(c,c,n);
    }
    return modProd(a,modPow(a,b-1,n),n);
}

function isPrime(n){
    // Miller-Rabin primality test taken from
    // O(k*log(n)^3) worst case, given k-accuracy
    // http://rosettacode.org/wiki/Miller-Rabin_primality_test#JavaScript
    if(n==2||n==3||n==5) return true;
    if(n%2==0||n%3==0||n%5==0) return false;
    if(n<25) return true;
    for(var a=[2,3,5,7,11,13,17,19],b=n-1,d,t,i,x;b%2==0;b/=2);
    for(i=0;i<a.length;i++) {
        x=modPow(a[i],b,n);
        if(x==1||x==n-1) continue;
        for(t=true,d=b;t&&d<n-1;d*=2){
              x=modProd(x,x,n); if(x==n-1) t=false;
        }
        if(t) return false;
    }
    return true;
}

function random_prime(n) {
    while(!isPrime(n)) n -= 2;
    return n;
}

function gcd(x, y) {
    if(!y) return x;
    return gcd(y, x%y);
}

function totient(n) {
    // compute Euler's totient function
    // O(sqrt(n)/3) worst case
    // Taken from:
    // https://en.wikipedia.org/wiki/Talk:Euler%27s_totient_function#C.2B.2B_Example
    if(n < 2) return n;
    var phi = n;
    if (n % 2 == 0) {
        phi /= 2;
        n /= 2;
        while(n % 2 == 0) n /= 2;
    }
    if (n % 3 == 0) {
        phi -= phi/3;
        n /= 3;
        while(n % 3 == 0) n /= 3;
    }
    for(p = 5; p * p <= n;) {
        if(n % p == 0) {
            phi -= phi/p;
            n /= p;
            while(n % p == 0) n /= p;
        }
        p += 2;
        if(p * p > n) break;
        if(n % p == 0) {
            phi -= phi/p;
            n /= p;
            while(n % p == 0) n /= p;
        }
    }
    if(n > 1) phi -= phi/n;
    return phi;
}

function seed() {
    var s = 2*Math.floor(Math.random() * Math.pow(2,31))-1; //odd
    if(s < 2) {
        return seed();
    } else {
        return s;
    }
}

function bbs(n) {
    // Blum Blum Shub cryptographically secure PRNG
    // See https://en.wikipedia.org/wiki/Blum_Blum_Shub
    var a = new Uint32Array(n);
    // Max int = 2^53 == (2^26)*(2^27) -> (2^p1)*(2^p2)
    var p1 = Math.floor(Math.random()*2)+25; // first power, 26 or 27
    var p2 = 51-p1; // second power
    var p = random_prime(2*Math.floor(Math.random() * Math.pow(2,p1))-1);
    var q = random_prime(2*Math.floor(Math.random() * Math.pow(2,p2))-1);
    var s = seed();

    // Ensure each quadratic residue has one square root which is also quadratic
    // residue. Also, gcd(totient(p-1),totient(q-1)) should be small to ensure a
    // large cycle length.
    while(p%4 != 3 || q%4 != 3 || gcd(totient(p-1),totient(q-1)) >= 5) {
        p = random_prime(2*Math.floor(Math.random() * Math.pow(2,p1))-1);
        q = random_prime(2*Math.floor(Math.random() * Math.pow(2,p2))-1);
    }

    // s should be coprime to p*q
    while(gcd(p*q, s) != 1) {
        s = seed();
    }

    for(i=n; i--;) {
        s = Math.pow(s,2)%(p*q);
        a[i] = s;
    }

    return a;
}

function make_key() {
    var text = "";
    var possible =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    var random_array = new Uint32Array(22);

    // Always prefer a cryptographically strong PRNG
    if(window.crypto && window.crypto.getRandomValues) {
        // Desktop Chrome 11.0, Firefox 21.0, Opera 15.0, Safari 3.1
        // Mobile Chrome 23, Firefox 21.0, iOS 6
        window.crypto.getRandomValues(random_array);
    }
    else if(window.msCrypto && window.msCrypto.getRandomValues) {
        // IE 11
        window.msCrypto.getRandomValues(random_array);
    }
    else {
        // Android browser, IE Mobile, Opera Mobile, other browsers
        random_array = bbs(22);
    }

    for(i=22; i--;) {
        text += possible.charAt(Math.floor(random_array[i] % possible.length));
    }

    return text;
}

function please_wait() {
    span = document.getElementById('progress');
    span.style.visibility = 'visible';
}

function validate_form() {
    if(document.getElementById('paste').value == "") {
        alert("You need to enter a message.");
        return false;
    }
    else {
        please_wait();
        setTimeout(function(){},0);
        validate_token(fingerprint);
        return true;
    }
}
<commit_msg>remove unnecessary call to Math.floor() from previous code<commit_after>function modProd(a,b,n){
    if(b==0) return 0;
    if(b==1) return a%n;
    return (modProd(a,(b-b%10)/10,n)*10+(b%10)*a)%n;
}

function modPow(a,b,n){
    if(b==0) return 1;
    if(b==1) return a%n;
    if(b%2==0){
        var c=modPow(a,b/2,n);
        return modProd(c,c,n);
    }
    return modProd(a,modPow(a,b-1,n),n);
}

function isPrime(n){
    // Miller-Rabin primality test taken from
    // O(k*log(n)^3) worst case, given k-accuracy
    // http://rosettacode.org/wiki/Miller-Rabin_primality_test#JavaScript
    if(n==2||n==3||n==5) return true;
    if(n%2==0||n%3==0||n%5==0) return false;
    if(n<25) return true;
    for(var a=[2,3,5,7,11,13,17,19],b=n-1,d,t,i,x;b%2==0;b/=2);
    for(i=0;i<a.length;i++) {
        x=modPow(a[i],b,n);
        if(x==1||x==n-1) continue;
        for(t=true,d=b;t&&d<n-1;d*=2){
              x=modProd(x,x,n); if(x==n-1) t=false;
        }
        if(t) return false;
    }
    return true;
}

function random_prime(n) {
    while(!isPrime(n)) n -= 2;
    return n;
}

function gcd(x, y) {
    if(!y) return x;
    return gcd(y, x%y);
}

function totient(n) {
    // compute Euler's totient function
    // O(sqrt(n)/3) worst case
    // Taken from:
    // https://en.wikipedia.org/wiki/Talk:Euler%27s_totient_function#C.2B.2B_Example
    if(n < 2) return n;
    var phi = n;
    if (n % 2 == 0) {
        phi /= 2;
        n /= 2;
        while(n % 2 == 0) n /= 2;
    }
    if (n % 3 == 0) {
        phi -= phi/3;
        n /= 3;
        while(n % 3 == 0) n /= 3;
    }
    for(p = 5; p * p <= n;) {
        if(n % p == 0) {
            phi -= phi/p;
            n /= p;
            while(n % p == 0) n /= p;
        }
        p += 2;
        if(p * p > n) break;
        if(n % p == 0) {
            phi -= phi/p;
            n /= p;
            while(n % p == 0) n /= p;
        }
    }
    if(n > 1) phi -= phi/n;
    return phi;
}

function seed() {
    var s = 2*Math.floor(Math.random() * Math.pow(2,31))-1; //odd
    if(s < 2) {
        return seed();
    } else {
        return s;
    }
}

function bbs(n) {
    // Blum Blum Shub cryptographically secure PRNG
    // See https://en.wikipedia.org/wiki/Blum_Blum_Shub
    var a = new Uint32Array(n);
    // Max int = 2^53 == (2^26)*(2^27) -> (2^p1)*(2^p2)
    var p1 = Math.floor(Math.random()*2)+25; // first power, 26 or 27
    var p2 = 51-p1; // second power
    var p = random_prime(2*Math.floor(Math.random() * Math.pow(2,p1))-1);
    var q = random_prime(2*Math.floor(Math.random() * Math.pow(2,p2))-1);
    var s = seed();

    // Ensure each quadratic residue has one square root which is also quadratic
    // residue. Also, gcd(totient(p-1),totient(q-1)) should be small to ensure a
    // large cycle length.
    while(p%4 != 3 || q%4 != 3 || gcd(totient(p-1),totient(q-1)) >= 5) {
        p = random_prime(2*Math.floor(Math.random() * Math.pow(2,p1))-1);
        q = random_prime(2*Math.floor(Math.random() * Math.pow(2,p2))-1);
    }

    // s should be coprime to p*q
    while(gcd(p*q, s) != 1) {
        s = seed();
    }

    for(i=n; i--;) {
        s = Math.pow(s,2)%(p*q);
        a[i] = s;
    }

    return a;
}

function make_key() {
    var text = "";
    var possible =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    var random_array = new Uint32Array(22);

    // Always prefer a cryptographically strong PRNG
    if(window.crypto && window.crypto.getRandomValues) {
        // Desktop Chrome 11.0, Firefox 21.0, Opera 15.0, Safari 3.1
        // Mobile Chrome 23, Firefox 21.0, iOS 6
        window.crypto.getRandomValues(random_array);
    }
    else if(window.msCrypto && window.msCrypto.getRandomValues) {
        // IE 11
        window.msCrypto.getRandomValues(random_array);
    }
    else {
        // Android browser, IE Mobile, Opera Mobile, other browsers
        random_array = bbs(22);
    }

    for(i=22; i--;) {
        text += possible.charAt(random_array[i] % possible.length);
    }

    return text;
}

function please_wait() {
    span = document.getElementById('progress');
    span.style.visibility = 'visible';
}

function validate_form() {
    if(document.getElementById('paste').value == "") {
        alert("You need to enter a message.");
        return false;
    }
    else {
        please_wait();
        setTimeout(function(){},0);
        validate_token(fingerprint);
        return true;
    }
}
<|endoftext|>


<commit_before>function my_script(orgs){
    console.log('script called.');
    var org = orgs;
    console.log('org assigned.');

    function make_drop_down(list_of_orgs, element_id){
        select_elem = document.getElementById(element_id)
        if(select_elem){
            for(var i = 0; i < list_of_orgs.length; i++) {
                var option = document.createElement('option');
                option.innerHTML = list_of_orgs[i];
                option.value = list_of_orgs[i];
                select_elem.appendChild(option);
            }
        }
    };

    console.log("Making Drop Downs!!");
    make_drop_down(org, 'drop_down_1');
    console.log("Made Drop Downs!!");

};
function my_script(vdc){
    console.log('script called.');
    var vdc = vdc;
    console.log('vdc assigned.');

    function make_drop_down(list_of_vdc, element_id){
        select_elem = document.getElementById(element_id)
        if(select_elem){
            for(var i = 0; i < list_of_vdc.length; i++) {
                var option = document.createElement('option');
                option.innerHTML = list_of_vdc[i];
                option.value = list_of_vdc[i];
                select_elem.appendChild(option);
            }
        }
    };

    console.log("Making Drop Downs!!");
    make_drop_down(vdc, 'drop_down_1');
    console.log("Made Drop Downs!!");

};
function my_script(vc){
    console.log('script called.');
    var vc = vc;
    console.log('vc assigned.');

    function make_drop_down(list_of_vc, element_id){
        select_elem = document.getElementById(element_id)
        if(select_elem){
            for(var i = 0; i < list_of_vc.length; i++) {
                var option = document.createElement('option');
                option.innerHTML = list_of_vc[i];
                option.value = list_of_vc[i];
                select_elem.appendChild(option);
            }
        }
    };

    console.log("Making Drop Downs!!");
    make_drop_down(vc, 'drop_down_1');
    console.log("Made Drop Downs!!");

};

function checkboxes(vmlist){
    console.log('script called.');
    var vmlist = vmlist;
    console.log('vmlist assigned.');

    function make_checkboxes(list_of_vms, element_id){
        select_elem = document.getElementById(make_checkboxes1)
        if(select_elem){
            for(var i = 0; i < list_of_vms.length; i++) {
                var checkBox = document.createElement('input');
                var label = document.createElement("label");
                checkBox.type = "checkbox";
                checkBox.value = list_of_vms[i];
                select_elem.appendChild(checkBox);
                select_elem.appendChild(label);
                label.appendChild(document.createTextNode(list_of_vms[i]));
            }
        }
    };

    console.log("Making Checkboxes!!");
    make_checkboxes(vmlist, 'make_checkboxes1');
    console.log("Made Checkboxes!!");

};

function myFunction1()
{
   document.forms[0].submit();
};
function myFunction2()
{
   document.forms[0].submit();
};
function myFunction3()
{
   document.forms[0].submit();
};
function myFunction4()
{
   document.forms[0].submit();
};
<commit_msg>Update main.js<commit_after>function my_script(orgs){
    console.log('script called.');
    var org = orgs;
    console.log('org assigned.');

    function make_drop_down(list_of_orgs, element_id){
        select_elem = document.getElementById(element_id)
        if(select_elem){
            for(var i = 0; i < list_of_orgs.length; i++) {
                var option = document.createElement('option');
                option.innerHTML = list_of_orgs[i];
                option.value = list_of_orgs[i];
                select_elem.appendChild(option);
            }
        }
    };

    console.log("Making Drop Downs!!");
    make_drop_down(org, 'drop_down_1');
    console.log("Made Drop Downs!!");

};
function my_script(vdc){
    console.log('script called.');
    var vdc = vdc;
    console.log('vdc assigned.');

    function make_drop_down(list_of_vdc, element_id){
        select_elem = document.getElementById(element_id)
        if(select_elem){
            for(var i = 0; i < list_of_vdc.length; i++) {
                var option = document.createElement('option');
                option.innerHTML = list_of_vdc[i];
                option.value = list_of_vdc[i];
                select_elem.appendChild(option);
            }
        }
    };

    console.log("Making Drop Downs!!");
    make_drop_down(vdc, 'drop_down_1');
    console.log("Made Drop Downs!!");

};
function my_script(vc){
    console.log('script called.');
    var vc = vc;
    console.log('vc assigned.');

    function make_drop_down(list_of_vc, element_id){
        select_elem = document.getElementById(element_id)
        if(select_elem){
            for(var i = 0; i < list_of_vc.length; i++) {
                var option = document.createElement('option');
                option.innerHTML = list_of_vc[i];
                option.value = list_of_vc[i];
                select_elem.appendChild(option);
            }
        }
    };

    console.log("Making Drop Downs!!");
    make_drop_down(vc, 'drop_down_1');
    console.log("Made Drop Downs!!");

};

function checkboxes(vmlist){
    console.log('script called.');
    var vmlist = vmlist;
    console.log('vmlist assigned.');

    function make_checkboxes(list_of_vms, element_id){
        select_elem = document.getElementById(element_id)
        if(select_elem){
            for(var i = 0; i < list_of_vms.length; i++) {
                var checkBox = document.createElement('input');
                var label = document.createElement("label");
                checkBox.type = "checkbox";
                checkBox.value = list_of_vms[i];
                select_elem.appendChild(checkBox);
                select_elem.appendChild(label);
                label.appendChild(document.createTextNode(list_of_vms[i]));
            }
        }
    };

    console.log("Making Checkboxes!!");
    make_checkboxes(vmlist, 'make_checkboxes1');
    console.log("Made Checkboxes!!");

};

function myFunction1()
{
   document.forms[0].submit();
};
function myFunction2()
{
   document.forms[0].submit();
};
function myFunction3()
{
   document.forms[0].submit();
};
function myFunction4()
{
   document.forms[0].submit();
};
<|endoftext|>


<commit_before>var socket_name = 'http://' + document.domain + ':' + location.port;
var socket = io.connect(socket_name);
var gamemode = null,
    input_type = null;
var username = null

function main() {
    // create, initiate and append game canvas
    username = window.prompt("Enter a username", "Username");
    init(); // initiate game objects
    //$(document).keydown(keyDown); //add keylisteners
    //$(document).keyup(keyUp);
    //draw();
}

function init() {
    socket.emit('add user', username);
}
function fillNES(){
    var a_button= $('<input class="A_button" type="button" value="new button"/>');
    var b_button= $('<input class="B_button" type="button" value="new button"/>');
    var d_pad= $('<input class="D_pad" type="button" value="new button"/>');
    $("#button_layout").append(a_button);
    $("#button_layout").append(b_button);
    $("#button_layout").append(d_pad);
}
function fillSNES(){
    fillNES();
    var x_button= $('<input class="X_button" type="button" value="new button"/>');
    var y_button= $('<input class="Y_button" type="button" value="new button"/>');
    $("#button_layout").append(x_button);
    $("#button_layout").append(y_button);

}
socket.on('initialize', function(data) {
    console.log(data);
    gamemode = data.mode ? 'chaos' : 'democracy';
    input_type = data.input_type;
    switch (input_type) {
        case ('NES'):
            {
                fillNES();
                break;
            }
        case ('SNES'):
            {
                fillSNES();
                break;
            }
        case ('Full Keyboard'):
            {
                break;
            }
            default: {
                break;
            }
    }
});
window.beforeunload = function() {
    if (username != null) socket.emit("disconnect", username);
}
main();<commit_msg>Latest Commit from sublime text<commit_after>var socket_name = 'http://' + document.domain + ':' + location.port;
var socket = io.connect(socket_name);
var gamemode = null,
    input_type = null;
var username = null

function main() {
    // create, initiate and append game canvas
    username = window.prompt("Enter a username", "Username");
    init(); // initiate game objects
    //$(document).keydown(keyDown); //add keylisteners
    //$(document).keyup(keyUp);
    //draw();
}

function init() {
    socket.emit('add user', username);
}
function fillNES(){
    var a_button= $('<input class="A_button" type="button" value="new button"/>');
    var b_button= $('<input class="B_button" type="button" value="new button"/>');
    var d_pad= $('<input class="D_pad" type="button" value="new button"/>');
    $("#button_layout").append(a_button);
    $("#button_layout").append(b_button);
    $("#button_layout").append(d_pad);
}
function fillSNES(){
    fillNES();
    var x_button= $('<input class="X_button" type="button" value="new button"/>');
    var y_button= $('<input class="Y_button" type="button" value="new button"/>');
    $("#button_layout").append(x_button);
    $("#button_layout").append(y_button);

}
socket.on('initialize', function(data) {
    console.log(data);
    gamemode = data.mode ? 'chaos' : 'democracy';
    input_type = data.input_type;
    switch (input_type) {
        case ('NES'):
            {
                fillNES();
                break;
            }
        case ('SNES'):
            {
                fillSNES();
                break;
            }
        case ('Full Keyboard'):
            {
                fillSNES();
                break;
            }
            default: {
                break;
            }
    }
});
window.beforeunload = function() {
    if (username != null) socket.emit("disconnect", username);
}
main();<|endoftext|>


<commit_before>/* = DEBUG ==================================================================== */
function showWarning( msg ){
    if( $('#msgerror').length ){
        $('#msgerror').append( '
' + msg + '
' );
    }
}

function showError( msg ){
    if( $('#msgerror').length ){
        $('#msgerror').append( '
' + msg + '
' );
    }
}

/* = USER NAME = ============================================================== */
!function ($) {
    "use strict"; // jshint ;_;

    if( $( '#username').length ){
        refreshUserName();
    }

}(window.jQuery);

function getUserName( f_ok ){
    $.ajax({
        dataType: "json",
        url: '/ajax/me',
        success: function( data ) { f_ok( data['username'] ) }
    });
}

function refreshUserName(){
    getUserName( function( username ){
        $('#username').replaceWith( '
' + username + '
' );
    });
}

/* = FILE UPLOAD ============================================================== */
!function ($) {
    "use strict"; // jshint ;_;

    var filesel = $('input[id=filesel]');
    filesel.change( function(){
        $('#filename').val( $(this).val() );
    });
    filesel.css( 'position', 'absolute' );
    filesel.css( 'visibility', 'hidden' );

    $('#filealert').css( 'visibility', 'hidden' );

    $('#filebrowse').click( function(){
        $('#filesel').click();
    });

    $('#filesend').click( function(){
        var input = document.getElementById('filesel')
        var size = getFileSize( input )
        if( size == 0 || size > 2*1024*1024*1024 ){
            showError( "Can't load Files > 2 GBs" )
            return
        }

        $('#filebar > .bar').replaceWith( '

' );
        $('#filebar').addClass( 'progress-striped' );
        $('#filebar').addClass( 'active' );
        $('#filealert').css( 'visibility', 'hidden' );
        var xhr = new XMLHttpRequest();
        if( xhr.upload ){
            xhr.upload.onprogress = function( e ){
                var done = e.position || e.loaded, total = e.totalSize || e.total;
                var perc = (Math.floor(done/total*1000)/10);
                $('#filebar > .bar').css( 'width', perc + '%' );
            };
        }
        xhr.onreadystatechange = function( e ){
            if( 4 == this.readyState ){
                $('#filebar > .bar').css( 'width', '100%' );
                $('#filebar').removeClass( 'progress-striped' );
                $('#filebar').removeClass( 'active' )
                $('#fileform').css( 'visibility', 'visible' );
                $('#filealert').css( 'visibility', 'visible' );
                refreshFileList();
            }
        };

        xhr.open( 'PUT', '/ajax/file', true );

        var form = $('#fileform')[0];
        var fd = new FormData( form );
        xhr.send( fd );

        $('#fileform').css( 'visibility', 'hidden' );
    });

}(window.jQuery);

function getFileSize( input ){
    if( ! window.FileReader) {
        showError( "The file API isn't supported on this browser yet." );
    }else if( ! input ){
        showError( "Couldn't find the file input element." );
    }else if( ! input.files ){
        showError( "This browser doesn't support the `files` property of file inputs.");
    }else if( ! input.files[0] ){
        showError( "Please select a file before clicking 'Load'" );
    }else{
        var file = input.files[0];
        return file.size;
    }

    return 0;
}

/* = FILE LIST ============================================================== */
!function ($) {
    "use strict"; // jshint ;_;

    refreshFileList();

}(window.jQuery);

function getFileList( f_ok ){
    $.ajax({
        dataType: "json",
        url: '/ajax/file',
        success: function( data ) { f_ok( data['files'] ) }
    });
}

function getFileListWithType( ftype, f_ok ){
    $.ajax({
        dataType: "json",
        data: { filetype: ftype },
        url: '/ajax/file',
        success: function( data ) { f_ok( data['files'] ) }
    });
}

function refreshFileList(){
    getFileList( function( files ){
        var items1 = [];
        var items2 = [];

        $.each(files, function( key, val ) {
            items1.push('
' + val['file'] + '
');
            items2.push('<option value="' + val['id'] + '">' + val['file'] + '</option>');
        });

        var newlist = $('
', {
            'id': 'filelist',
            'class': 'unstyled',
            html: items1.join('')
        });

        $('#filelist').replaceWith( newlist );

        var newformlist = $('<select/>', {
            'id': 'jobfile',
            'name': 'file',
            html: items2.join('')
        });

        $('#jobfile').replaceWith( newformlist );
// EK edit --------------------------------------------------
        // var newformlist = $('<select/>', {
        //     'id': 'jobfile2',
        //     'name': 'file2',
        //     html: items2.join('')
        // });

        // $('#jobfile2').replaceWith( newformlist );

        // var newformlist = $('<select/>', {
        //     'id': 'jobfile3',
        //     'name': 'file',
        //     html: items2.join('')
        // });

        // $('#jobfile3').replaceWith( newformlist );

// EK edit --------------------------------------------------
    });
}

/* = JOB STUFF ============================================================== */
!function ($) {
    "use strict"; // jshint ;_;

    $('#jobstart').click( function(){
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function( e ){
            if( 4 == this.readyState ){
                alert( "job sended" );
                refreshJobList();
            }
        };

        xhr.open( 'POST', '/ajax/job', true );

        var form = $('#jobform')[0];
        var fd = new FormData( form );
        xhr.send( fd );
    });

    refreshJobList();

}(window.jQuery);

function refreshJobList(){
    $.ajax({
        dataType: "json",
        url: '/ajax/job',
        success: function( data ) {
            var items = [];
            var jobs = data['jobs']

            $.each( jobs, function( key, val ) {
                items.push('
Job ' + val['id'] + '
');
            });

            var newlist = $('
', {
                'id': 'joblist',
                'class': 'unstyled',
                html: items.join('')
            });

            $('#joblist').replaceWith( newlist );
        }
    });
}

/*EK EDITS =================================================================== */

    $('.nav-tabs').click(function (e) {
        e.preventDefault();
    });

    $('.accordion-toggle').click(function (e) {
        e.preventDefault();
        var n = $(document).height();
        $('html, body').animate({ scrollTop: n/2 },'500');
    });

    //
    // $('#myTab a').click(function (e) {
    //  e.preventDefault();
    //  $(this).tab('show');
    // })

// Select the number and type of input:

$(document).ready(function(){
    var reads_1 = $("div[id=reads_1]")
    var reads_2 = $("div[id=reads_2]")
    var in_type = $("input[name=input_type]")

// Setting single or paired reads
    in_type.change(function (){
        var in_type = $("input[name=input_type]:checked").val()

        if (in_type == "single")
        {
            reads_1.children("label").text("Single reads file:")
            reads_1.show()
            reads_2.hide()
//          $("p[id=demo]").text(in_type)
        }
        else if (in_type == "paired")
        {
            reads_1.children("label").text("Left reads file:")
            reads_1.show()
            reads_2.show()
//          $("p[id=demo]").text(in_type)
        }

    })
});
// Displaying warning message if action are not available with the current input
(function($) {
    var trin_check = $("input[id=trinity]")
    var warn = $('div[id=no_assembly_alert]')

    trin_check.change( function(){
        if (trin_check.is(':checked'))
        {
            warn.hide()
        }
        else
        {
            warn.show()
        }
    })

})(jQuery);

// Function to have activation/deactivation of checkboxes
$(function() {

    var in_type = $("input[name=input_type]")
    var warn_read = $('div[id=no_reads_alert]')

    in_type.change(function (){
        $("p[id=demo]").text($(this).val())

        cleaning_arr = ["single","paired","contigs_with_single","contigs_with_paired"]

        if (jQuery.inArray($(this).val(), cleaning_arr) === -1)
        {
            $('.cleaning_steps').attr('disabled', true);
            warn_read.show()
        }
        else
        {
            $('.cleaning_steps').attr('disabled', false);
            warn_read.hide()
        }
    });
});

$('#example').popover({html:true})
<commit_msg>separate file upload in >2GB and <2GB<commit_after>/* = DEBUG ==================================================================== */
function showWarning( msg ){
    if( $('#msgerror').length ){
        $('#msgerror').append( '
' + msg + '
' );
    }
}

function showError( msg ){
    if( $('#msgerror').length ){
        $('#msgerror').append( '
' + msg + '
' );
    }
}

/* = USER NAME = ============================================================== */
!function ($) {
    "use strict"; // jshint ;_;

    if( $( '#username').length ){
        refreshUserName();
    }

}(window.jQuery);

function getUserName( f_ok ){
    $.ajax({
        dataType: "json",
        url: '/ajax/me',
        success: function( data ) { f_ok( data['username'] ) }
    });
}

function refreshUserName(){
    getUserName( function( username ){
        $('#username').replaceWith( '
' + username + '
' );
    });
}

/* = FILE UPLOAD ============================================================== */
!function ($) {
    "use strict"; // jshint ;_;

    var filesel = $('input[id=filesel]');
    filesel.change( function(){
        $('#filename').val( $(this).val() );
    });
    filesel.css( 'position', 'absolute' );
    filesel.css( 'visibility', 'hidden' );

    $('#filealert').css( 'visibility', 'hidden' );

    $('#filebrowse').click( function(){
        $('#filesel').click();
    });

    $('#filesend').click( function(){
        var input = document.getElementById('filesel')
        var size = getFileSize( input )
        if( size > 0 && size < 2*1024*1024*1024 ){
            sendLittleFile()
        }else{
            sendBigFile()
        }
    });

}(window.jQuery);

function getFileSize( input ){
    if( ! window.FileReader) {
        showError( "The file API isn't supported on this browser yet." );
    }else if( ! input ){
        showError( "Couldn't find the file input element." );
    }else if( ! input.files ){
        showError( "This browser doesn't support the `files` property of file inputs.");
    }else if( ! input.files[0] ){
        showError( "Please select a file before clicking 'Load'" );
    }else{
        var file = input.files[0];
        return file.size;
    }

    return 0;
}

function sendLittleFile(){
    $('#filebar > .bar').replaceWith( '

' );
    $('#filebar').addClass( 'progress-striped' );
    $('#filebar').addClass( 'active' );
    $('#filealert').css( 'visibility', 'hidden' );
    var xhr = new XMLHttpRequest();
    if( xhr.upload ){
        xhr.upload.onprogress = function( e ){
            var done = e.position || e.loaded, total = e.totalSize || e.total;
            var perc = (Math.floor(done/total*1000)/10);
            $('#filebar > .bar').css( 'width', perc + '%' );
        };
    }
    xhr.onreadystatechange = function( e ){
        if( 4 == this.readyState ){
            $('#filebar > .bar').css( 'width', '100%' );
            $('#filebar').removeClass( 'progress-striped' );
            $('#filebar').removeClass( 'active' )
            $('#fileform').css( 'visibility', 'visible' );
            $('#filealert').css( 'visibility', 'visible' );
            refreshFileList();
        }
    };

    xhr.open( 'PUT', '/ajax/file', true );

    var form = $('#fileform')[0];
    var fd = new FormData( form );
    xhr.send( fd );

    $('#fileform').css( 'visibility', 'hidden' );
}

function sendBigFile(){
    showError( "Can't load Files > 2 GBs" )
    // var input = $('#filesel')[0]
    // var file = input.files[0]
    // showWarning( file )
    // var blob = file.slice( 0, 1024 )
    // showWarning( file + " size" + blob.size )
}

/* = FILE LIST ============================================================== */
!function ($) {
    "use strict"; // jshint ;_;

    refreshFileList();

}(window.jQuery);

function getFileList( f_ok ){
    $.ajax({
        dataType: "json",
        url: '/ajax/file',
        success: function( data ) { f_ok( data['files'] ) }
    });
}

function getFileListWithType( ftype, f_ok ){
    $.ajax({
        dataType: "json",
        data: { filetype: ftype },
        url: '/ajax/file',
        success: function( data ) { f_ok( data['files'] ) }
    });
}

function refreshFileList(){
    getFileList( function( files ){
        var items1 = [];
        var items2 = [];

        $.each(files, function( key, val ) {
            items1.push('
' + val['file'] + '
');
            items2.push('<option value="' + val['id'] + '">' + val['file'] + '</option>');
        });

        var newlist = $('
', {
            'id': 'filelist',
            'class': 'unstyled',
            html: items1.join('')
        });

        $('#filelist').replaceWith( newlist );

        var newformlist = $('<select/>', {
            'id': 'jobfile',
            'name': 'file',
            html: items2.join('')
        });

        $('#jobfile').replaceWith( newformlist );
// EK edit --------------------------------------------------
        // var newformlist = $('<select/>', {
        //     'id': 'jobfile2',
        //     'name': 'file2',
        //     html: items2.join('')
        // });

        // $('#jobfile2').replaceWith( newformlist );

        // var newformlist = $('<select/>', {
        //     'id': 'jobfile3',
        //     'name': 'file',
        //     html: items2.join('')
        // });

        // $('#jobfile3').replaceWith( newformlist );

// EK edit --------------------------------------------------
    });
}

/* = JOB STUFF ============================================================== */
!function ($) {
    "use strict"; // jshint ;_;

    $('#jobstart').click( function(){
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function( e ){
            if( 4 == this.readyState ){
                alert( "job sended" );
                refreshJobList();
            }
        };

        xhr.open( 'POST', '/ajax/job', true );

        var form = $('#jobform')[0];
        var fd = new FormData( form );
        xhr.send( fd );
    });

    refreshJobList();

}(window.jQuery);

function refreshJobList(){
    $.ajax({
        dataType: "json",
        url: '/ajax/job',
        success: function( data ) {
            var items = [];
            var jobs = data['jobs']

            $.each( jobs, function( key, val ) {
                items.push('
Job ' + val['id'] + '
');
            });

            var newlist = $('
', {
                'id': 'joblist',
                'class': 'unstyled',
                html: items.join('')
            });

            $('#joblist').replaceWith( newlist );
        }
    });
}

/*EK EDITS =================================================================== */

    $('.nav-tabs').click(function (e) {
        e.preventDefault();
    });

    $('.accordion-toggle').click(function (e) {
        e.preventDefault();
        var n = $(document).height();
        $('html, body').animate({ scrollTop: n/2 },'500');
    });

    //
    // $('#myTab a').click(function (e) {
    //  e.preventDefault();
    //  $(this).tab('show');
    // })

// Select the number and type of input:

$(document).ready(function(){
    var reads_1 = $("div[id=reads_1]")
    var reads_2 = $("div[id=reads_2]")
    var in_type = $("input[name=input_type]")

// Setting single or paired reads
    in_type.change(function (){
        var in_type = $("input[name=input_type]:checked").val()

        if (in_type == "single")
        {
            reads_1.children("label").text("Single reads file:")
            reads_1.show()
            reads_2.hide()
//          $("p[id=demo]").text(in_type)
        }
        else if (in_type == "paired")
        {
            reads_1.children("label").text("Left reads file:")
            reads_1.show()
            reads_2.show()
//          $("p[id=demo]").text(in_type)
        }

    })
});
// Displaying warning message if action are not available with the current input
(function($) {
    var trin_check = $("input[id=trinity]")
    var warn = $('div[id=no_assembly_alert]')

    trin_check.change( function(){
        if (trin_check.is(':checked'))
        {
            warn.hide()
        }
        else
        {
            warn.show()
        }
    })

})(jQuery);

// Function to have activation/deactivation of checkboxes
$(function() {

    var in_type = $("input[name=input_type]")
    var warn_read = $('div[id=no_reads_alert]')

    in_type.change(function (){
        $("p[id=demo]").text($(this).val())

        cleaning_arr = ["single","paired","contigs_with_single","contigs_with_paired"]

        if (jQuery.inArray($(this).val(), cleaning_arr) === -1)
        {
            $('.cleaning_steps').attr('disabled', true);
            warn_read.show()
        }
        else
        {
            $('.cleaning_steps').attr('disabled', false);
            warn_read.hide()
        }
    });
});

$('#example').popover({html:true})
<|endoftext|>


<commit_before>var OSRM = require('../');
var test = require('tape');
var berlin_path = "test/data/berlin-latest.osrm";

test('tile', function(assert) {
    assert.plan(2);
    var osrm = new OSRM(berlin_path);
    osrm.tile([17603, 10747, 15], function(err, result) {
        assert.ifError(err);
        assert.equal(result.length, 18160);
    });
});
<commit_msg>Update tile size<commit_after>var OSRM = require('../');
var test = require('tape');
var berlin_path = "test/data/berlin-latest.osrm";

test('tile', function(assert) {
    assert.plan(2);
    var osrm = new OSRM(berlin_path);
    osrm.tile([17603, 10747, 15], function(err, result) {
        assert.ifError(err);
        assert.equal(result.length, 18222);
    });
});
<|endoftext|>


<commit_before>'use strict';

var chai = require('chai'),
    vain = require('./../lib/vain');

chai.should();

describe('Vain', function() {
  describe('.render', function() {
    it('should return the same markup if no snippets were invoked', function() {
      var startMarkup = 'Google A search engine.',
          renderResult = vain.render(startMarkup);

      renderResult.should.equal(startMarkup);
    });

    it('should pass in the entire matching node to a snippet', function(callback) {
      var startMarkup = 'Google A search engine.',
          snippetHandler = function($, element) {
            var passedInMarkup = $("
").append(element).html();

            passedInMarkup.should.equal(startMarkup);
            callback();
          },
          renderResult = vain.render(startMarkup, {snippets: {'test': snippetHandler}});
    });
  });
});
<commit_msg>Add a test for basic transformation testing.<commit_after>'use strict';

var chai = require('chai'),
    vain = require('./../lib/vain');

chai.should();

describe('Vain', function() {
  describe('.render', function() {
    it('should return the same markup if no snippets were invoked', function() {
      var startMarkup = 'Google A search engine.',
          renderResult = vain.render(startMarkup);

      renderResult.should.equal(startMarkup);
    });

    it('should pass in the entire matching node to a snippet', function(callback) {
      var startMarkup = 'Google A search engine.',
          snippetHandler = function($, element) {
            var passedInMarkup = $("
").append(element).html();

            passedInMarkup.should.equal(startMarkup);
            callback();
          },
          renderResult = vain.render(startMarkup, {snippets: {'test': snippetHandler}});
    });

    it('should return transformed node markup', function() {
      var startMarkup = 'Google',
          expectedMarkup = 'Google',
          snippetHandler = function($, element) {
            $(element).addClass("fancy");
          },
          renderResult = vain.render(startMarkup, {snippets: {'test': snippetHandler}});

      renderResult.should.equal(expectedMarkup);
    });
  });
});
<|endoftext|>


<commit_before>var assert = require('better-assert'),
  path = require('path'),
  fs = require('fs'),
  Stream = require('stream'),
  streamAssert = require('stream-equal'),
  VeohExtractor = require('../lib/extractors/veoh'),
  config = require('../lib/config/config'),
  url = 'http://www.veoh.com/watch/v31498313WdzjfXJ3';

describe('VeohExtractor', function() {
  describe('getId', function() {
    it('Should return id of a veoh clip', function() {
      var ve = new VeohExtractor(config);
      var id = ve.getId(url);
      assert(id === 'v31498313WdzjfXJ3');
    });
  });
  describe('info', function() {
    it('Should get meta-data information about a certain clip', function(done){
      var ve = new VeohExtractor(config);
      ve.info(url).done(function(info){
        assert(info.rsp.videoList instanceof Array);
        done();
      });
    });
  });
  describe('download', function() {
    it('Should download a file from veoh', function(done){
      var video = path.resolve(__dirname, 'files/veoh'),
        ve = new VeohExtractor(config),
        vidStream = fs.createReadStream(video);

      ve.download(url).done(function(file){
        streamAssert(vidStream, file, function(err, equals) {
          assert(equals);
          assert(file instanceof Stream);
          done();
        });
      });
    });
  });
});<commit_msg>formatting<commit_after>var assert = require('better-assert'),
  path = require('path'),
  fs = require('fs'),
  Stream = require('stream'),
  streamAssert = require('stream-equal'),
  VeohExtractor = require('../lib/extractors/veoh'),
  config = require('../lib/config/config'),
  url = 'http://www.veoh.com/watch/v31498313WdzjfXJ3';

describe('VeohExtractor', function() {
  describe('getId', function() {
    it('Should return id of a veoh clip', function() {
      var ve = new VeohExtractor(config);
      var id = ve.getId(url);
      assert(id === 'v31498313WdzjfXJ3');
    });
  });
  describe('info', function() {
    it('Should get meta-data information about a certain clip', function(done) {
      var ve = new VeohExtractor(config);
      ve.info(url).done(function(info) {
        assert(info.rsp.videoList instanceof Array);
        done();
      });
    });
  });
  describe('download', function() {
    it('Should download a file from veoh', function(done) {
      var video = path.resolve(__dirname, 'files/veoh'),
        ve = new VeohExtractor(config),
        vidStream = fs.createReadStream(video);

      ve.download(url).done(function(file) {
        streamAssert(vidStream, file, function(err, equals) {
          assert(equals);
          assert(file instanceof Stream);
          done();
        });
      });
    });
  });
});<|endoftext|>


<commit_before>View = Backbone.View.extend({
    events : {
        "click :checkbox" : function(e) {
            var target = $(e.currentTarget);
            var key = target.attr('target');
            console.log(target.is(':checked'));
            if (target.is(':checked'))
                this.keyOff(key);
            else
                this.keyOn(key, this.keys[key]);
            return this;
        }
    },
    keys : {
        'x' : function(e) {
            return this.log('You typed x');
        },
        'esc' : 'clear',
        'return' : 'submit'
    },

    render : function() {
        //this.keyOff('esc', 'clear');
    },

    submit : function(e) {
        this.log(
            'Submitted: ' + this.$('#text').val()
        );
        return this;
    },

    clear : function(e) {
        this.$('#text').val('');
        return this;
    },

    log : function(msg) {
        this.$('#log').append(
            this.make('p', {}, msg)
        );
        return this;
    }
});
<commit_msg>Fix error in test view<commit_after>View = Backbone.View.extend({
    events : {
        "click :checkbox" : function(e) {
            var target = $(e.currentTarget);
            var key = target.attr('target');
            if (target.is(':checked'))
                this.keyOn(key, this.keys[key]);
            else
                this.keyOff(key);
            return this;
        }
    },
    keys : {
        'x' : function(e) {
            return this.log('You typed x');
        },
        'esc' : 'clear',
        'return' : 'submit'
    },

    render : function() {
        //this.keyOff('esc', 'clear');
    },

    submit : function(e) {
        this.log(
            'Submitted: ' + this.$('#text').val()
        );
        return this;
    },

    clear : function(e) {
        this.$('#text').val('');
        return this;
    },

    log : function(msg) {
        this.$('#log').append(
            this.make('p', {}, msg)
        );
        return this;
    }
});
<|endoftext|>


<commit_before>define(['d3'], function (d3) {

  function median(data, n) {
    if (n == 0)
      return NaN;

    var middle = Math.floor(n / 2);

    if (n % 2 == 1) {
      return data[middle];
    } else {
      return (data[middle - 1] + data[middle]) * 0.5;
    }
  }

  function percentile(data, n, percentile) {
    if (n == 0)
      return NaN;

    var k = (n - 1) * percentile;
    var f = Math.floor(k);
    var c = Math.ceil(k);
    if (f == c) {
      return data[f];
    } else {
      var d0 = data[f] * (c - k);
      var d1 = data[c] * (k - f);
      return d0 + d1;
    }
  }

  return {

    statisticsOf: function (data) {

      var stats = {
        min: NaN,
        max: NaN,
        nans: 0,
        median: NaN,
        quartile25: NaN,
        quartile75: NaN,
        iqrMin: NaN,
        iqrMax: NaN,
        numElements: data.length
      };

      var sortedData = Object.create(data);
      sortedData.sort(function (a, b) {
        return isNaN(a) && isNaN(b) ? 0 : isNaN(a) ? 1 : isNaN(b) ? -1 : d3.ascending(a, b);
      });

      sortedData.forEach(function (d) {
        if (isNaN(d)) {
          stats.nans++;
        } else {
          if (isNaN(stats.min) || d < stats.min) {
            stats.min = d;
          }
          if (isNaN(stats.max) || d > stats.max) {
            stats.max = d;
          }
        }
      });

      var lengthWithoutNaNs = sortedData.length - stats.nans;

      stats.median = median(sortedData, lengthWithoutNaNs);
      stats.quartile25 = percentile(sortedData, lengthWithoutNaNs, 0.25);
      stats.quartile75 = percentile(sortedData, lengthWithoutNaNs, 0.75);

      var lowerIQRBounds = stats.quartile25 - (stats.quartile75 - stats.quartile25) * 1.5;
      var upperIQRBounds = stats.quartile75 + (stats.quartile75 - stats.quartile25) * 1.5;

      for (var i = 0; i < lengthWithoutNaNs; i++) {
        if (sortedData[i] >= lowerIQRBounds && sortedData[i] <= stats.quartile25) {
          stats.iqrMin = sortedData[i];
          break;
        }
      }

      for (var i = lengthWithoutNaNs - 1; i >= 0; i--) {
        if (sortedData[i] <= upperIQRBounds && sortedData[i] >= stats.quartile75) {
          stats.iqrMax = sortedData[i];
          break;
        }
      }

      return stats;
    }

  };
});
<commit_msg>added client-side computation of mean and std<commit_after>define(['d3'], function (d3) {

  function median(data, n) {
    if (n == 0)
      return NaN;

    var middle = Math.floor(n / 2);

    if (n % 2 == 1) {
      return data[middle];
    } else {
      return (data[middle - 1] + data[middle]) * 0.5;
    }
  }

  function percentile(data, n, percentile) {
    if (n == 0)
      return NaN;

    var k = (n - 1) * percentile;
    var f = Math.floor(k);
    var c = Math.ceil(k);
    if (f == c) {
      return data[f];
    } else {
      var d0 = data[f] * (c - k);
      var d1 = data[c] * (k - f);
      return d0 + d1;
    }
  }

  return {

    statisticsOf: function (data) {

      var stats = {
        min: NaN,
        max: NaN,
        nans: 0,
        median: NaN,
        mean: NaN,
        sd: NaN,
        quartile25: NaN,
        quartile75: NaN,
        iqrMin: NaN,
        iqrMax: NaN,
        numElements: data.length
      };

      var sortedData = Object.create(data);
      sortedData.sort(function (a, b) {
        return isNaN(a) && isNaN(b) ? 0 : isNaN(a) ? 1 : isNaN(b) ? -1 : d3.ascending(a, b);
      });

      var n = 0;
      var variance = 0;
      sortedData.forEach(function (d) {
        if (isNaN(d)) {
          stats.nans++;
        } else {

          n++;
          if (isNaN(stats.min) || d < stats.min) {
            stats.min = d;
          }
          if (isNaN(stats.max) || d > stats.max) {
            stats.max = d;
          }
          if (n == 1) {
            stats.mean = d;
          } else {
            var prevMean = stats.mean;
            stats.mean = stats.mean + (d - stats.mean) / n;
            variance = variance + (d - prevMean) * (d - stats.mean);
          }
        }
      });
      variance = variance/(n-1);

      var lengthWithoutNaNs = sortedData.length - stats.nans;

      stats.std = Math.sqrt(variance);

      stats.median = median(sortedData, lengthWithoutNaNs);
      stats.quartile25 = percentile(sortedData, lengthWithoutNaNs, 0.25);
      stats.quartile75 = percentile(sortedData, lengthWithoutNaNs, 0.75);

      var lowerIQRBounds = stats.quartile25 - (stats.quartile75 - stats.quartile25) * 1.5;
      var upperIQRBounds = stats.quartile75 + (stats.quartile75 - stats.quartile25) * 1.5;

      for (var i = 0; i < lengthWithoutNaNs; i++) {
        if (sortedData[i] >= lowerIQRBounds && sortedData[i] <= stats.quartile25) {
          stats.iqrMin = sortedData[i];
          break;
        }
      }

      for (var i = lengthWithoutNaNs - 1; i >= 0; i--) {
        if (sortedData[i] <= upperIQRBounds && sortedData[i] >= stats.quartile75) {
          stats.iqrMax = sortedData[i];
          break;
        }
      }

      return stats;
    }

  };
});
<|endoftext|>


<commit_before>// take a bullet for this city

var RLDB = true; // print lots of shit
var usecached = true; // use local file... don't re-download

var testfire = true; // insert testfire in 1 minute

debugprint("hi there"); // friendly

// node shit
var http = require('http');
var fs = require('fs');

// URL shit
var APIep = "http://data.nola.gov/resource/jsyu-nz5r.json"; // endpoint for NOLA open data
var APIquery = "?typetext=DISCHARGING%20FIREARM&$order=timecreate%20DESC"; // query we want
var queryURL = APIep + APIquery; // the whole enchilada

// local file shit
var destFile = "foo.json"; // where are we stashing this locally?

// data shit
var thestuff; // holder for JSON
var gunQueue = new Array(); // gun queue
var backdate = 7; // use week old data
var loaded = false;

// timer shit
var timer = setInterval(pollQueue, 1000, backdate);

//
// FUNCTION BLOCK:
//

// download the SODA stuff asynchronously and fire off a callback
var downloadJSON = function(url, dest, cb) {
  	var file = fs.createWriteStream(dest);
  	debugprint("about to download...");
  	var request = http.get(url, function(response) {
    response.pipe(file);
    file.on('finish', function() {
      file.close(cb(dest));  // close() is async, call cb after close completes.
    });
  });
}

// callback out of downloadJSON... loads and parses the file and continues
function gotFile(destFile)
{
	debugprint("parsing file...");
	thestuff = (JSON.parse(fs.readFileSync(destFile, "utf8")));
	//debugprint(thestuff);

	// parse JSON into queue
	debugprint("generating queue...");
	gunQueue = JSONtoQueue(thestuff, backdate);
	// dump Queue to screen
	debugprint("dumping queue...");
	dumpQueue(gunQueue);
}

// parses JSON and returns Array object of Date elements
// Date elements are to be queued based on old data set by 'backdate'
function JSONtoQueue(stuff, bd)
{
	// new array
	q = new Array();

	// date shit
	var lastday = bd*24*60*60*1000; // milliseconds
	var today = new Date();
	var tda = new Date(today.getTime() - lastday); // bd days ago
	debugprint("Today is: " + tda);

	for(var i=0;i<stuff.length;i++){
        var d = new Date(Date.parse(stuff[i].timecreate));

        // date matches three days ago... add to queue
        if(d.getDate()==tda.getDate()
         && d.getFullYear()==tda.getFullYear()
          && d.getMonth()==tda.getMonth()) {
          	// strip duplicates
          	if(stuff[i].disposition!="DUP")
          	{
	          	q.push(d);
          	}
        }
     }

     if(testfire)
     {
     	var t = new Date(tda.getTime() + 60*1000);
     	q.push(t);
     }

     q.reverse();
     loaded = true;
     return(q);
}

// print out queue
function dumpQueue(q)
{
	for(var i = 0;i<q.length;i++)
	{
		debugprint("schedule gun at: " +q[i]);
	}
}

// main event callback
function pollQueue(bd)
{
	if(loaded) {
		// date shit
		var lastday = bd*24*60*60*1000; // milliseconds
		var today = new Date();
		var tda = new Date(today.getTime() - lastday); // bd days ago
		debugprint("queue serviced: " + tda);
		for(var i = 0;i<q.length;i++)
		{
			if(gunQueue[i].getMinutes()==tda.getMinutes()
				&& gunQueue[i].getHours()==tda.getHours())
			{
				// FIRE!
				console.log("FIRE!!!!! : tda");
				//
				// insert pi shit
				//
				gunQueue.splice(i, 1); // remove from queue
				dumpQueue(gunQueue); // list next fires
			}
		}
	}
}

function debugprint(stuff)
{
	if(RLDB) console.log(stuff);
}

// MASTER BLOCK
if(usecached)
{
	gotFile(destFile);
}
else {
	downloadJSON(queryURL, destFile, gotFile);
}

<commit_msg>turn off testfire<commit_after>// take a bullet for this city

var RLDB = true; // print lots of shit
var usecached = true; // use local file... don't re-download

var testfire = false; // insert testfire in 1 minute

debugprint("hi there"); // friendly

// node shit
var http = require('http');
var fs = require('fs');

// URL shit
var APIep = "http://data.nola.gov/resource/jsyu-nz5r.json"; // endpoint for NOLA open data
var APIquery = "?typetext=DISCHARGING%20FIREARM&$order=timecreate%20DESC"; // query we want
var queryURL = APIep + APIquery; // the whole enchilada

// local file shit
var destFile = "foo.json"; // where are we stashing this locally?

// data shit
var thestuff; // holder for JSON
var gunQueue = new Array(); // gun queue
var backdate = 7; // use week old data
var loaded = false;

// timer shit
var timer = setInterval(pollQueue, 1000, backdate);

//
// FUNCTION BLOCK:
//

// download the SODA stuff asynchronously and fire off a callback
var downloadJSON = function(url, dest, cb) {
  	var file = fs.createWriteStream(dest);
  	debugprint("about to download...");
  	var request = http.get(url, function(response) {
    response.pipe(file);
    file.on('finish', function() {
      file.close(cb(dest));  // close() is async, call cb after close completes.
    });
  });
}

// callback out of downloadJSON... loads and parses the file and continues
function gotFile(destFile)
{
	debugprint("parsing file...");
	thestuff = (JSON.parse(fs.readFileSync(destFile, "utf8")));
	//debugprint(thestuff);

	// parse JSON into queue
	debugprint("generating queue...");
	gunQueue = JSONtoQueue(thestuff, backdate);
	// dump Queue to screen
	debugprint("dumping queue...");
	dumpQueue(gunQueue);
}

// parses JSON and returns Array object of Date elements
// Date elements are to be queued based on old data set by 'backdate'
function JSONtoQueue(stuff, bd)
{
	// new array
	q = new Array();

	// date shit
	var lastday = bd*24*60*60*1000; // milliseconds
	var today = new Date();
	var tda = new Date(today.getTime() - lastday); // bd days ago
	debugprint("Today is: " + tda);

	for(var i=0;i<stuff.length;i++){
        var d = new Date(Date.parse(stuff[i].timecreate));

        // date matches three days ago... add to queue
        if(d.getDate()==tda.getDate()
         && d.getFullYear()==tda.getFullYear()
          && d.getMonth()==tda.getMonth()) {
          	// strip duplicates
          	if(stuff[i].disposition!="DUP")
          	{
	          	q.push(d);
          	}
        }
     }

     if(testfire)
     {
     	var t = new Date(tda.getTime() + 60*1000);
     	q.push(t);
     }

     q.reverse();
     loaded = true;
     return(q);
}

// print out queue
function dumpQueue(q)
{
	for(var i = 0;i<q.length;i++)
	{
		debugprint("schedule gun at: " +q[i]);
	}
}

// main event callback
function pollQueue(bd)
{
	if(loaded) {
		// date shit
		var lastday = bd*24*60*60*1000; // milliseconds
		var today = new Date();
		var tda = new Date(today.getTime() - lastday); // bd days ago
		debugprint("queue serviced: " + tda);
		for(var i = 0;i<q.length;i++)
		{
			if(gunQueue[i].getMinutes()==tda.getMinutes()
				&& gunQueue[i].getHours()==tda.getHours())
			{
				// FIRE!
				console.log("FIRE!!!!! :" + tda);
				//
				// insert pi shit
				//
				gunQueue.splice(i, 1); // remove from queue
				dumpQueue(gunQueue); // list next fires
			}
		}
	}
}

function debugprint(stuff)
{
	if(RLDB) console.log(stuff);
}

// MASTER BLOCK
if(usecached)
{
	gotFile(destFile);
}
else {
	downloadJSON(queryURL, destFile, gotFile);
}

<|endoftext|>


<commit_before>#!/usr/bin/env node
// The changes_couchdb command-line interface.
//

var COUCH = 'http://localhost:5984';
var DB    = 'cqs_test';

var cqs = require('../api').defaults({'couch':COUCH, 'db':DB})
  , util = require('util')
  , assert = require('assert')
  , request = require('request')
  ;

var state = {};
var TESTS = [

function setup(done) {
  var url = COUCH + '/' + DB;
  request({method:'DELETE', uri:url}, function(er, resp, body) {
    if(er) throw er;
    var json = JSON.parse(body);

    var already_gone = (resp.statusCode === 404 && json.error === 'not_found');
    var deleted      = (resp.statusCode === 200 && json.ok    === true);

    if(! (already_gone || deleted))
      throw new Error('Unknown DELETE response: ' + resp.statusCode + ' ' + body);

    request({method:'PUT', uri:url}, function(er, resp, body) {
      if(er) throw er;
      var json = JSON.parse(body);

      if(resp.statusCode !== 201 || json.ok !== true)
        throw new Error('Unknown PUT response: ' + resp.statusCode + ' ' + body);

      done();
    })
  })
},

//
// TESTS
//

function create_queue(done) {
  cqs.CreateQueue('foo', function(er, queue) {
    if(er) return done(er);
    assert.equal(queue.name, 'foo', "CreateQueue returns the queue name");
    state.foo = queue;
    done();
  })
},

function create_queue_with_obj(done) {
  cqs.CreateQueue({name:'bar'}, function(er, queue) {
    if(er) return done(er);
    assert.equal(queue.name, 'bar', "CreateQueue returns the queue name");
    state.bar = queue;
    done();
  })
},

function list_queues(done) {
  cqs.ListQueues(function(er, res) {
    if(er) throw er;
    assert.equal(2, res.length);
    assert.ok(res.indexOf('foo') !== -1);
    assert.ok(res.indexOf('bar') !== -1);
    done();
  })
},

function list_queues_with_prefix(done) {
  cqs.ListQueues('f', function(er, res) {
    if(er) throw er;
    assert.equal(1, res.length);
    assert.ok(res.indexOf('foo') !== -1);
    assert.ok(res.indexOf('bar') === -1);

    cqs.ListQueues('b', function(er, res) {
      if(er) throw er;
      assert.equal(1, res.length);
      assert.ok(res.indexOf('foo') === -1);
      assert.ok(res.indexOf('bar') !== -1);
      done();
    })
  })
},

function xxsend_message(done) {
  //cqs.
},

]; // TESTS

//
// Runner
//

var errors = [];
var count = { pass: 0
            , timeout: 0
            , fail: 0
            , skip: 0
            , inc: function(type) {
                     this[type] += 1
                     var symbol = type[0].toUpperCase().replace(/P/, '.');
                     process.stdout.write(symbol);
                     return run();
                   }
            }

function run() {
  var test = TESTS.shift();
  if(!test)
    return complete();

  if(/^xx/.test(test.name))
    return count.inc('skip');

  function done(er) {
    if(er === 'timeout') {
      errors.push(new Error('Timeout: ' + test.name));
      return count.inc('timeout');
    }

    clearTimeout(test.timer);
    if(er) {
      errors.push(er);
      return count.inc('fail');
    }

    return count.inc('pass');
  }

  var timeout = 250;
  test.timer = setTimeout(function() { done('timeout') }, timeout);

  // This is pretty convenient. Simply throw an error and we'll assume it pertains to this unit test.
  process.removeAllListeners('uncaughtException');
  process.on('uncaughtException', function(er) { return done(er); })

  test(done);
}

function complete() {
  process.stdout.write('\n\n');
  errors.forEach(function(er) {
    var stack = er.stack;
    if(er.expected || er.actual)
      stack = "expected=" + util.inspect(er.expected) + ' actual=' + util.inspect(er.actual) + '\n' + stack;

    console.error(stack);
  })

  console.log('Done: pass:' + count.pass + ' fail:' + count.fail + ' timeout:' + count.timeout + ' skip:' + count.skip);
}

run();

//
// Utilities
//
<commit_msg>Test helpers<commit_after>#!/usr/bin/env node
// The changes_couchdb command-line interface.
//

var COUCH = 'http://localhost:5984';
var DB    = 'cqs_test';

var cqs = require('../api').defaults({'couch':COUCH, 'db':DB})
  , util = require('util'), I = util.inspect
  , assert = require('assert')
  , request = require('request')
  ;

var XX_MEANS_EXCLUDE = process.env.xx ? false : true; // Set to false to run *only* the xx tests.

var state = {};
var TESTS = [

function setup(done) {
  var url = COUCH + '/' + DB;
  request({method:'DELETE', uri:url}, function(er, resp, body) {
    if(er) throw er;
    var json = JSON.parse(body);

    var already_gone = (resp.statusCode === 404 && json.error === 'not_found');
    var deleted      = (resp.statusCode === 200 && json.ok    === true);

    if(! (already_gone || deleted))
      throw new Error('Unknown DELETE response: ' + resp.statusCode + ' ' + body);

    request({method:'PUT', uri:url}, function(er, resp, body) {
      if(er) throw er;
      var json = JSON.parse(body);

      if(resp.statusCode !== 201 || json.ok !== true)
        throw new Error('Unknown PUT response: ' + resp.statusCode + ' ' + body);

      done();
    })
  })
},

//
// TESTS
//

function create_queue(done) {
  cqs.CreateQueue('foo', function(er, queue) {
    if(er) return done(er);
    assert.equal(queue.name, 'foo', "CreateQueue returns the queue name");
    state.foo = queue;
    done();
  })
},

function create_queue_with_obj(done) {
  cqs.CreateQueue({name:'bar'}, function(er, queue) {
    if(er) return done(er);
    assert.equal(queue.name, 'bar', "CreateQueue returns the queue name");
    state.bar = queue;
    done();
  })
},

function list_queues(done) {
  cqs.ListQueues(function(er, res) {
    if(er) throw er;
    assert.equal(2, res.length);
    assert.ok(res.indexOf('foo') !== -1);
    assert.ok(res.indexOf('bar') !== -1);
    done();
  })
},

function list_queues_with_prefix(done) {
  cqs.ListQueues('f', function(er, res) {
    if(er) throw er;
    assert.equal(1, res.length);
    assert.ok(res.indexOf('foo') !== -1);
    assert.ok(res.indexOf('bar') === -1);

    cqs.ListQueues('b', function(er, res) {
      if(er) throw er;
      assert.equal(1, res.length);
      assert.ok(res.indexOf('foo') === -1);
      assert.ok(res.indexOf('bar') !== -1);
      done();
    })
  })
},

function xxsend_message(done) {
  //cqs.
},

]; // TESTS

//
// Runner
//

var errors = [];
var count = { pass: 0
            , timeout: 0
            , fail: 0
            , skip: 0
            , inc: function(type) {
                     this[type] += 1
                     var symbol = type[0].toUpperCase().replace(/P/, '.');
                     process.stdout.write(symbol);
                     return run();
                   }
            }

function run() {
  var test = TESTS.shift();
  if(!test)
    return complete();

  var starts_with_xx = /^xx/.test(test.name);
  if( XX_MEANS_EXCLUDE ? starts_with_xx : !starts_with_xx )
    return count.inc('skip');

  function done(er) {
    if(er === 'timeout') {
      errors.push(new Error('Timeout: ' + test.name));
      return count.inc('timeout');
    }

    clearTimeout(test.timer);
    if(er) {
      errors.push(er);
      return count.inc('fail');
    }

    return count.inc('pass');
  }

  var timeout = 250;
  test.timer = setTimeout(function() { done('timeout') }, timeout);

  // This is pretty convenient. Simply throw an error and we'll assume it pertains to this unit test.
  process.removeAllListeners('uncaughtException');
  process.on('uncaughtException', function(er) { return done(er); })

  test(done);
}

function complete() {
  process.stdout.write('\n\n');
  errors.forEach(function(er) {
    var stack = er.stack;
    if(er.expected || er.actual)
      stack = "expected=" + util.inspect(er.expected) + ' actual=' + util.inspect(er.actual) + '\n' + stack;

    console.error(stack);
  })

  console.log('Done: pass:' + count.pass + ' fail:' + count.fail + ' timeout:' + count.timeout + ' skip:' + count.skip);
}

run();

//
// Utilities
//

if(! assert.member)
  assert.member = function(elem, list, message) {
    var is_member = false;
    list.forEach(function(list_elem) {
      if(list_elem === elem)
        is_member = true;
    })

    if(!is_member)
      throw new Error(message || "");
  }

if(! assert.any)
  assert.any = function(list, message, pred) {
    for(var a = 0; a < list.length; a++)
      if(pred.call(null, list[a]))
        return true;
    throw new Error(message || "assert.any");
  }

if(! assert.none)
  assert.none = function(list, message, pred) {
    for(var a = 0; a < list.length; a++)
      if(pred.call(null, list[a]))
        throw new Error(message || "assert.none");
    return true;
  }
<|endoftext|>