<commit_before>/*global HTMLDocument, Window, console */
// Helper method used to avoid exposing costanza internals to the funky string methods
var _costanzaEvil = function(__costanza_str) {
  return function() {
    return eval(__costanza_str);
  };
};

this.Costanza = (function() {
  // Save off a reference to the eval rescoper and remove it from the global scope
  // to keep things somewhat modular
  var costanzaEvil = _costanzaEvil;
  _costanzaEvil = undefined;

  function defaultReporter(info, err) {
    /*jshint eqnull:true */
    console.error('Costanza error:'
          + '\n  type: ' + info.type
          + '\n  section: ' + info.section
          + (info.url ? '\n  url: ' + info.url : '')
          + (info.line != null ? '\n  line: ' + info.line : '')
          + ((info.stack && info.stack.indexOf(info.msg) < 0) ? '\n\n' + info.msg : ''),
          + '\n\n' + (info.stack || info.msg));
  }

  var reportCallback = defaultReporter,
      currentSection = 'global',
      _onError,
      _setTimeout,
      _setInterval;

  function init(_reportCallback, options) {
    options = options || {};
    reportCallback = _reportCallback || defaultReporter;

    if (!options.noGlobal && window.addEventListener && (!window.onerror || !window.onerror._costanza)) {
      _onError = _onError || window.onerror;
      window.onerror = onErrorRoot;

      window.addEventListener('error', onError, true);

      if ('onpagehide' in window) {
        window.addEventListener('pageshow', onPageShow, false);
        window.addEventListener('pagehide', onPageHide, false);
      } else {
        window.addEventListener('beforeunload', onPageHide, false);
      }
    }

    // Allow users to opt out of the native prototype augmentation.
    if (options.safeMode) {
      return;
    }

    if (window.setTimeout && !setTimeout._costanza) {
      _setTimeout = setTimeout;
      window.setTimeout = wrapSet(_setTimeout);
    }

    if (window.setInterval && !setInterval._costanza) {
      _setInterval = setInterval;
      window.setInterval = wrapSet(_setInterval);
    }

    function wrapSet($super) {
      function ret(callback, duration) {
        if (typeof callback === 'string') {
          callback = costanzaEvil(callback);
        }

        var args = Array.prototype.slice.call(arguments);
        args[0] = bind({
          captureErrors: true,     // No need to propagate to global error handler
          callback: callback
        });

        return $super.apply(this, args);
      }
      ret._costanza = true;
      return ret;
    }

    if (window.Element && Element.prototype.addEventListener && !Element.prototype.addEventListener._costanza) {

      wrapListener(Element.prototype);
      if (window.HTMLDocument || window.Document) {
        // IE10: Document, others are HTMLDocument
        wrapListener((window.HTMLDocument || window.Document).prototype);
      }
      if (window.Window) {
        wrapListener(Window.prototype);
      }
    }

    function wrapListener(proto) {
      // We must pair the native implementation with the proper proto object as ios7 will throw
      // if they are not.
      proto._addEventListener = proto.addEventListener;
      proto.addEventListener = function(type, callback, useCapture) {
        if (!callback._section) {
          var className = '';
          if (this.className) {
            // baseValue for SVGAnimatedString on svg elements
            className = this.className.baseVal || this.className;
            className = '.' + className.replace(' ', '.');
          }

          var elementId = (this.nodeName || 'window').toLowerCase()
              + (this.id ? '#' + this.id : className),
            sectionName = 'event-' + elementId + ':' + type;

          if (callback.handleEvent) {
            callback._section = {
              handleEvent: bind(sectionName, function(event) {
                return callback.handleEvent(event);
              })
            };
          } else {
            callback._section = bind({
              name: sectionName,
              captureErrors: true,   // No need to propagate to global error handler
              callback: callback
            });
          }
        }

        this._addEventListener(type, callback._section, useCapture);
      };
      proto.addEventListener._costanza = true;

      proto._removeEventListener = proto.removeEventListener;
      proto.removeEventListener = function(type, callback, useCapture) {
        this._removeEventListener(type, callback._section || callback, useCapture);
      };
      proto.removeEventListener._costanza = true;
    }
  }
  function cleanup() {
    function cleanupListener(proto) {
      proto.addEventListener = proto._addEventListener;
      proto.removeEventListener = proto._removeEventListener;
    }

    reportCallback = defaultReporter;
    if (_setTimeout && setTimeout._costanza) {
      window.setTimeout = _setTimeout;
    }
    if (_setInterval && setInterval._costanza) {
      window.setInterval = _setInterval;
    }
    if (window.Element && Element.prototype.addEventListener && Element.prototype.addEventListener._costanza) {
      cleanupListener(Element.prototype);
      if (window.HTMLDocument) {
        cleanupListener(HTMLDocument.prototype);
      }
      if (window.Window) {
        cleanupListener(Window.prototype);
      }
    }

    if (window.onerror && window.onerror._costanza) {
      window.onerror = _onError;

      window.removeEventListener('error', onError, true);
    }
  }

  function bind(/* [name, ][info, ] callback */) {
    var callback = arguments[2] || arguments[1] || arguments[0],
        captureErrors,
        info,
        name = currentSection;

    if (!callback.apply) {
      // Options object was passed
      name = callback.name || name;
      info = callback.info;
      captureErrors = callback.captureErrors;

      callback = callback.callback;
    } else {
      // Array-based arguments
      if (arguments.length > 2) {
        info = arguments[1];
        name = arguments[0];
      }
      if (arguments.length > 1) {
        name = arguments[0];
        if (typeof name !== 'string') {
          info = name;
          name = currentSection;
        }
      }
    }

    if (!callback || !callback.apply) {
      // If we don't have a valid function, log it and pass whatever it is on
      reportError(new Error('Costanza:Unexpected bind: ' + callback));

      return callback;
    } else if (callback._costanza) {
      return callback;
    }

    var ret = function() {
      var priorSite = currentSection;

      try {
        currentSection = name;

        return callback.apply(this, arguments);
      } catch (err) {
        reportError(err);

        // Continute propagation of the error so we aren't left in an intedeterminate
        // state
        if (!captureErrors) {
          // Rewrite the error so we know that its already gone through the error handling
          // stack
          var toThrow = new Error('Costanza: ' + err.stack);
          toThrow.stack = err.stack || toThrow.stack;
          toThrow._costanza = true;
          throw toThrow;
        }
      } finally {
        currentSection = priorSite;
      }
    };
    ret._costanza = true;
    return ret;

    function reportError(err) {
      // Do not over report
      if (err._costanza) {
        return;
      }
      err._costanza = true;

      var reportInfo = {
        type: 'javascript',
        section: currentSection,
        msg: err.message,
        stack: err.stack
      };

      // Inline debug data
      function extend(info) {
        if (info) {
          for (var keyName in info) {
            if (info.hasOwnProperty(keyName)) {
              reportInfo[keyName] = info[keyName];
            }
          }
        }
      }
      extend(info);
      extend(err.info);

      reportCallback(reportInfo, err);
    }
  }

  function onError(errorMsg, url, lineNumber, error) {
    var type = 'javascript';

    // Handle ErrorEvent if we receieve it
    if (errorMsg && errorMsg.message) {
      url = errorMsg.filename;
      lineNumber = errorMsg.lineno;
      error = errorMsg.error;
      errorMsg = errorMsg.message;
    }

    if (errorMsg === 'Script error.' && !url) {
      // Ignore untrackable external errors locally
      return;
    }
    if (!url && lineNumber === 0) {
      // If the external script error message MIGHT have some more meaning then provide a more
      // meaningful url than undefined.
      url = 'Unknown External Script';
    }

    // This is a real event handler vs. the onerror special case.
    // Since some browsers decide to treat window.onerror as the error event handler,
    // we have to be prepared for either case
    var el = errorMsg.target || errorMsg.srcElement;
    if (errorMsg && el) {
      // Don't submit duplciate events (and if we weren't already tracking
      // it, it probably wasn't that important)
      // Additionally ignore load errors that might happen after page unload has started.
      if (errorMsg.defaultPrevented || errorMsg._costanzaHandled
          || Costanza.pageUnloading) {
        return;
      }

      errorMsg._costanzaHandled = true;
      url = url || el.src || el.href;
      type = el.nodeName.toLowerCase();
      errorMsg = 'load-failed';
    }

    // Error argument added to the spec. Adding support so we can catch this as it rolls out
    // http://html5.org/tools/web-apps-tracker?from=8085&to=8086
    reportCallback({
      section: currentSection,
      url: url,
      line: lineNumber,
      type: type,

      // Cast error message to string as it sometimes can come through with objects, particularly DOM objects
      // containing circular references.
      msg: errorMsg+'',
      stack: error && error.stack
    }, error);
  }

  function onErrorRoot(errorMsg, url, lineNumber, error) {
    _onError && _onError(errorMsg, url, lineNumber, error);
    onError(errorMsg, url, lineNumber, error);
  }
  onErrorRoot._costanza = true;

  function onPageShow(event) {
    Costanza.pageUnloading = false;
  }
  function onPageHide(event) {
    Costanza.pageUnloading = true;
  }

  var Costanza = {
    init: init,
    cleanup: cleanup,
    current: function() {
      return currentSection;
    },
    emit: function(info, error) {
      reportCallback(info, error);
    },
    bind: bind,
    run: function(name, info, callback) {
      return bind(name, info, callback)();
    },
    onError: onError
  };
  return Costanza;
})();
<commit_msg>Do not report previously handled global errors<commit_after>/*global HTMLDocument, Window, console */
// Helper method used to avoid exposing costanza internals to the funky string methods
var _costanzaEvil = function(__costanza_str) {
  return function() {
    return eval(__costanza_str);
  };
};

this.Costanza = (function() {
  // Save off a reference to the eval rescoper and remove it from the global scope
  // to keep things somewhat modular
  var costanzaEvil = _costanzaEvil;
  _costanzaEvil = undefined;

  function defaultReporter(info, err) {
    /*jshint eqnull:true */
    console.error('Costanza error:'
          + '\n  type: ' + info.type
          + '\n  section: ' + info.section
          + (info.url ? '\n  url: ' + info.url : '')
          + (info.line != null ? '\n  line: ' + info.line : '')
          + ((info.stack && info.stack.indexOf(info.msg) < 0) ? '\n\n' + info.msg : ''),
          + '\n\n' + (info.stack || info.msg));
  }

  var reportCallback = defaultReporter,
      currentSection = 'global',
      _onError,
      _setTimeout,
      _setInterval;

  function init(_reportCallback, options) {
    options = options || {};
    reportCallback = _reportCallback || defaultReporter;

    if (!options.noGlobal && window.addEventListener && (!window.onerror || !window.onerror._costanza)) {
      _onError = _onError || window.onerror;
      window.onerror = onErrorRoot;

      window.addEventListener('error', onError, true);

      if ('onpagehide' in window) {
        window.addEventListener('pageshow', onPageShow, false);
        window.addEventListener('pagehide', onPageHide, false);
      } else {
        window.addEventListener('beforeunload', onPageHide, false);
      }
    }

    // Allow users to opt out of the native prototype augmentation.
    if (options.safeMode) {
      return;
    }

    if (window.setTimeout && !setTimeout._costanza) {
      _setTimeout = setTimeout;
      window.setTimeout = wrapSet(_setTimeout);
    }

    if (window.setInterval && !setInterval._costanza) {
      _setInterval = setInterval;
      window.setInterval = wrapSet(_setInterval);
    }

    function wrapSet($super) {
      function ret(callback, duration) {
        if (typeof callback === 'string') {
          callback = costanzaEvil(callback);
        }

        var args = Array.prototype.slice.call(arguments);
        args[0] = bind({
          captureErrors: true,     // No need to propagate to global error handler
          callback: callback
        });

        return $super.apply(this, args);
      }
      ret._costanza = true;
      return ret;
    }

    if (window.Element && Element.prototype.addEventListener && !Element.prototype.addEventListener._costanza) {

      wrapListener(Element.prototype);
      if (window.HTMLDocument || window.Document) {
        // IE10: Document, others are HTMLDocument
        wrapListener((window.HTMLDocument || window.Document).prototype);
      }
      if (window.Window) {
        wrapListener(Window.prototype);
      }
    }

    function wrapListener(proto) {
      // We must pair the native implementation with the proper proto object as ios7 will throw
      // if they are not.
      proto._addEventListener = proto.addEventListener;
      proto.addEventListener = function(type, callback, useCapture) {
        if (!callback._section) {
          var className = '';
          if (this.className) {
            // baseValue for SVGAnimatedString on svg elements
            className = this.className.baseVal || this.className;
            className = '.' + className.replace(' ', '.');
          }

          var elementId = (this.nodeName || 'window').toLowerCase()
              + (this.id ? '#' + this.id : className),
            sectionName = 'event-' + elementId + ':' + type;

          if (callback.handleEvent) {
            callback._section = {
              handleEvent: bind(sectionName, function(event) {
                return callback.handleEvent(event);
              })
            };
          } else {
            callback._section = bind({
              name: sectionName,
              captureErrors: true,   // No need to propagate to global error handler
              callback: callback
            });
          }
        }

        this._addEventListener(type, callback._section, useCapture);
      };
      proto.addEventListener._costanza = true;

      proto._removeEventListener = proto.removeEventListener;
      proto.removeEventListener = function(type, callback, useCapture) {
        this._removeEventListener(type, callback._section || callback, useCapture);
      };
      proto.removeEventListener._costanza = true;
    }
  }
  function cleanup() {
    function cleanupListener(proto) {
      proto.addEventListener = proto._addEventListener;
      proto.removeEventListener = proto._removeEventListener;
    }

    reportCallback = defaultReporter;
    if (_setTimeout && setTimeout._costanza) {
      window.setTimeout = _setTimeout;
    }
    if (_setInterval && setInterval._costanza) {
      window.setInterval = _setInterval;
    }
    if (window.Element && Element.prototype.addEventListener && Element.prototype.addEventListener._costanza) {
      cleanupListener(Element.prototype);
      if (window.HTMLDocument) {
        cleanupListener(HTMLDocument.prototype);
      }
      if (window.Window) {
        cleanupListener(Window.prototype);
      }
    }

    if (window.onerror && window.onerror._costanza) {
      window.onerror = _onError;

      window.removeEventListener('error', onError, true);
    }
  }

  function bind(/* [name, ][info, ] callback */) {
    var callback = arguments[2] || arguments[1] || arguments[0],
        captureErrors,
        info,
        name = currentSection;

    if (!callback.apply) {
      // Options object was passed
      name = callback.name || name;
      info = callback.info;
      captureErrors = callback.captureErrors;

      callback = callback.callback;
    } else {
      // Array-based arguments
      if (arguments.length > 2) {
        info = arguments[1];
        name = arguments[0];
      }
      if (arguments.length > 1) {
        name = arguments[0];
        if (typeof name !== 'string') {
          info = name;
          name = currentSection;
        }
      }
    }

    if (!callback || !callback.apply) {
      // If we don't have a valid function, log it and pass whatever it is on
      reportError(new Error('Costanza:Unexpected bind: ' + callback));

      return callback;
    } else if (callback._costanza) {
      return callback;
    }

    var ret = function() {
      var priorSite = currentSection;

      try {
        currentSection = name;

        return callback.apply(this, arguments);
      } catch (err) {
        reportError(err);

        // Continute propagation of the error so we aren't left in an intedeterminate
        // state
        if (!captureErrors) {
          // Rewrite the error so we know that its already gone through the error handling
          // stack
          var toThrow = new Error('Costanza: ' + err.stack);
          toThrow.stack = err.stack || toThrow.stack;
          toThrow._costanza = true;
          throw toThrow;
        }
      } finally {
        currentSection = priorSite;
      }
    };
    ret._costanza = true;
    return ret;

    function reportError(err) {
      // Do not over report
      if (err._costanza) {
        return;
      }
      err._costanza = true;

      var reportInfo = {
        type: 'javascript',
        section: currentSection,
        msg: err.message,
        stack: err.stack
      };

      // Inline debug data
      function extend(info) {
        if (info) {
          for (var keyName in info) {
            if (info.hasOwnProperty(keyName)) {
              reportInfo[keyName] = info[keyName];
            }
          }
        }
      }
      extend(info);
      extend(err.info);

      reportCallback(reportInfo, err);
    }
  }

  function onError(errorMsg, url, lineNumber, error) {
    var type = 'javascript';

    // Handle ErrorEvent if we receieve it
    if (errorMsg && errorMsg.message) {
      url = errorMsg.filename;
      lineNumber = errorMsg.lineno;
      error = errorMsg.error;
      errorMsg = errorMsg.message;
    }

    var isCostanzaError = /\bCostanza: /.test(errorMsg);
    if ((errorMsg === 'Script error.' && !url)
        || isCostanzaError) {
      // Ignore untrackable external errors locally
      // Also ignore errors that have already been reported (The _costanza flag does not
      // propagate to window.onerror
      return isCostanzaError;
    }
    if (!url && lineNumber === 0) {
      // If the external script error message MIGHT have some more meaning then provide a more
      // meaningful url than undefined.
      url = 'Unknown External Script';
    }

    // This is a real event handler vs. the onerror special case.
    // Since some browsers decide to treat window.onerror as the error event handler,
    // we have to be prepared for either case
    var el = errorMsg.target || errorMsg.srcElement;
    if (errorMsg && el) {
      // Don't submit duplciate events (and if we weren't already tracking
      // it, it probably wasn't that important)
      // Additionally ignore load errors that might happen after page unload has started.
      if (errorMsg.defaultPrevented || errorMsg._costanzaHandled
          || Costanza.pageUnloading) {
        return;
      }

      errorMsg._costanzaHandled = true;
      url = url || el.src || el.href;
      type = el.nodeName.toLowerCase();
      errorMsg = 'load-failed';
    }

    // Error argument added to the spec. Adding support so we can catch this as it rolls out
    // http://html5.org/tools/web-apps-tracker?from=8085&to=8086
    reportCallback({
      section: currentSection,
      url: url,
      line: lineNumber,
      type: type,

      // Cast error message to string as it sometimes can come through with objects, particularly DOM objects
      // containing circular references.
      msg: errorMsg+'',
      stack: error && error.stack
    }, error);
  }

  function onErrorRoot(errorMsg, url, lineNumber, error) {
    _onError && _onError(errorMsg, url, lineNumber, error);
    return onError(errorMsg, url, lineNumber, error);
  }
  onErrorRoot._costanza = true;

  function onPageShow(event) {
    Costanza.pageUnloading = false;
  }
  function onPageHide(event) {
    Costanza.pageUnloading = true;
  }

  var Costanza = {
    init: init,
    cleanup: cleanup,
    current: function() {
      return currentSection;
    },
    emit: function(info, error) {
      reportCallback(info, error);
    },
    bind: bind,
    run: function(name, info, callback) {
      return bind(name, info, callback)();
    },
    onError: onError
  };
  return Costanza;
})();
<|endoftext|>


<commit_before>'use strict';

function check(){
    var integer = random_integer(
      100000,
      'ceil'
    );
    var result = ' was generated. You ';

    result += parseInt(document.getElementById('answer').value, 10) === integer
      ? 'might have ESP!'
      : 'probably don\'t have ESP.';

    document.getElementById('integer').innerHTML = integer;
    document.getElementById('result').innerHTML = result;
}

window.onload = function(e){
    input_init(
      {
        13: {
          'todo': check,
        },
      }
    );

    document.getElementById('answer').focus();
    document.getElementById('check').onclick = check;
};
<commit_msg>switched random.js to args<commit_after>'use strict';

function check(){
    var integer = random_integer({
      'max': 100000,
      'todo': 'ceil',
    });
    var result = ' was generated. You ';

    result += parseInt(document.getElementById('answer').value, 10) === integer
      ? 'might have ESP!'
      : 'probably don\'t have ESP.';

    document.getElementById('integer').innerHTML = integer;
    document.getElementById('result').innerHTML = result;
}

window.onload = function(e){
    input_init(
      {
        13: {
          'todo': check,
        },
      }
    );

    document.getElementById('answer').focus();
    document.getElementById('check').onclick = check;
};
<|endoftext|>


<commit_before>(function( $ ){

  $.fn.pad = function( options ) {
    var settings = {
      'host'              : 'http://beta.etherpad.org',
      'baseUrl'           : '/p/test1',
      'showControls'      : false,
      'showChat'          : false,
      'showLineNumbers'   : false,
      'userName'          : 'unnamed',
      'lang'              : '',
      'useMonospaceFont'  : false,
      'noColors'          : false,
      'userColor'         : false,
      'hideQRCode'        : false,
      'alwaysShowChat'    : false,
      'width'             : 100,
      'height'            : 100,
      'border'            : 0,
      'borderStyle'       : 'solid',
      'toggleTextOn'      : 'Disable Rich-text',
      'toggleTextOff'     : 'Enable Rich-text',
      'plugins'           : {},
      'rtl'               : false
    };

    var $self = this;
    if (!$self.length) return;
    if (!$self.attr('id')) throw new Error('No "id" attribute');

    var useValue = $self[0].tagName.toLowerCase() == 'textarea';
    var selfId = $self.attr('id');
    var epframeId = 'epframe'+ selfId;
    // This writes a new frame if required
    if ( !options.getContents ) {
      if ( options ) {
        $.extend( settings, options );
      }

      var pluginParams = '';
      for(var option in settings.plugins) {
        pluginParams += '&' + option + '=' + settings.plugins[option]
      }

      var iFrameLink = '<iframe id="'+epframeId;
          iFrameLink = iFrameLink +'" name="' + epframeId;
          iFrameLink = iFrameLink +'" src="' + settings.host+settings.baseUrl+settings.padId;
          iFrameLink = iFrameLink + '?showControls=' + settings.showControls;
          iFrameLink = iFrameLink + '&showChat=' + settings.showChat;
          iFrameLink = iFrameLink + '&showLineNumbers=' + settings.showLineNumbers;
          iFrameLink = iFrameLink + '&useMonospaceFont=' + settings.useMonospaceFont;
          iFrameLink = iFrameLink + '&userName=' + settings.userName;
          if (settings.lang) {
            iFrameLink = iFrameLink + '&lang=' + settings.lang;
          }
          iFrameLink = iFrameLink + '&noColors=' + settings.noColors;
          iFrameLink = iFrameLink + '&userColor=' + settings.userColor;
          iFrameLink = iFrameLink + '&hideQRCode=' + settings.hideQRCode;
          iFrameLink = iFrameLink + '&alwaysShowChat=' + settings.alwaysShowChat;
          iFrameLink = iFrameLink + '&rtl=' + settings.rtl;
          iFrameLink = iFrameLink + pluginParams;
          iFrameLink = iFrameLink +'" style="border:' + settings.border;
          iFrameLink = iFrameLink +'; border-style:' + settings.borderStyle;
          iFrameLink = iFrameLink +';" width="' + '100%';//settings.width;
          iFrameLink = iFrameLink +'" height="' + settings.height;
          iFrameLink = iFrameLink +'">';

      var $iFrameLink = $(iFrameLink);

      if (useValue) {
        var $toggleLink = $(''+ settings.toggleTextOn +'').click(function(){
          var $this = $(this);
          $this.toggleClass('active');
          if ($this.hasClass('active')) $this.text(settings.toggleTextOff);
          $self.pad({getContents: true});
          return false;
        });
        $self
          .hide()
          .after($toggleLink)
          .after($iFrameLink)
        ;
      }
      else {
        $self.html(iFrameLink);
      }
    }

    // This reads the etherpad contents if required
    else {
      var frameUrl = $('#'+ epframeId).attr('src').split('?')[0];
      var contentsUrl = frameUrl + "/export/html";
      var target = $('#'+ options.getContents);

      // perform an ajax call on contentsUrl and write it to the parent
      $.get(contentsUrl, function(data) {

        if (target.is(':input')) {
          target.val(data).show();
        }
        else {
          target.html(data);
        }

        $('#'+ epframeId).remove();
      });
    }

    return $self;
  };
})( jQuery );
<commit_msg>Update etherpad.js<commit_after>(function( $ ){

  $.fn.pad = function( options ) {
    var settings = {
      'host'              : 'http://beta.etherpad.org',
      'baseUrl'           : '/p/',
      'showControls'      : false,
      'showChat'          : false,
      'showLineNumbers'   : false,
      'userName'          : 'test1',
      'lang'              : '',
      'useMonospaceFont'  : false,
      'noColors'          : false,
      'userColor'         : false,
      'hideQRCode'        : false,
      'alwaysShowChat'    : false,
      'width'             : 100,
      'height'            : 100,
      'border'            : 0,
      'borderStyle'       : 'solid',
      'toggleTextOn'      : 'Disable Rich-text',
      'toggleTextOff'     : 'Enable Rich-text',
      'plugins'           : {},
      'rtl'               : false
    };

    var $self = this;
    if (!$self.length) return;
    if (!$self.attr('id')) throw new Error('No "id" attribute');

    var useValue = $self[0].tagName.toLowerCase() == 'textarea';
    var selfId = $self.attr('id');
    var epframeId = 'epframe'+ selfId;
    // This writes a new frame if required
    if ( !options.getContents ) {
      if ( options ) {
        $.extend( settings, options );
      }

      var pluginParams = '';
      for(var option in settings.plugins) {
        pluginParams += '&' + option + '=' + settings.plugins[option]
      }

      var iFrameLink = '<iframe id="'+epframeId;
          iFrameLink = iFrameLink +'" name="' + epframeId;
          iFrameLink = iFrameLink +'" src="' + settings.host+settings.baseUrl+settings.padId;
          iFrameLink = iFrameLink + '?showControls=' + settings.showControls;
          iFrameLink = iFrameLink + '&showChat=' + settings.showChat;
          iFrameLink = iFrameLink + '&showLineNumbers=' + settings.showLineNumbers;
          iFrameLink = iFrameLink + '&useMonospaceFont=' + settings.useMonospaceFont;
          iFrameLink = iFrameLink + '&userName=' + settings.userName;
          if (settings.lang) {
            iFrameLink = iFrameLink + '&lang=' + settings.lang;
          }
          iFrameLink = iFrameLink + '&noColors=' + settings.noColors;
          iFrameLink = iFrameLink + '&userColor=' + settings.userColor;
          iFrameLink = iFrameLink + '&hideQRCode=' + settings.hideQRCode;
          iFrameLink = iFrameLink + '&alwaysShowChat=' + settings.alwaysShowChat;
          iFrameLink = iFrameLink + '&rtl=' + settings.rtl;
          iFrameLink = iFrameLink + pluginParams;
          iFrameLink = iFrameLink +'" style="border:' + settings.border;
          iFrameLink = iFrameLink +'; border-style:' + settings.borderStyle;
          iFrameLink = iFrameLink +';" width="' + '100%';//settings.width;
          iFrameLink = iFrameLink +'" height="' + settings.height;
          iFrameLink = iFrameLink +'">';

      var $iFrameLink = $(iFrameLink);

      if (useValue) {
        var $toggleLink = $(''+ settings.toggleTextOn +'').click(function(){
          var $this = $(this);
          $this.toggleClass('active');
          if ($this.hasClass('active')) $this.text(settings.toggleTextOff);
          $self.pad({getContents: true});
          return false;
        });
        $self
          .hide()
          .after($toggleLink)
          .after($iFrameLink)
        ;
      }
      else {
        $self.html(iFrameLink);
      }
    }

    // This reads the etherpad contents if required
    else {
      var frameUrl = $('#'+ epframeId).attr('src').split('?')[0];
      var contentsUrl = frameUrl + "/export/html";
      var target = $('#'+ options.getContents);

      // perform an ajax call on contentsUrl and write it to the parent
      $.get(contentsUrl, function(data) {

        if (target.is(':input')) {
          target.val(data).show();
        }
        else {
          target.html(data);
        }

        $('#'+ epframeId).remove();
      });
    }

    return $self;
  };
})( jQuery );
<|endoftext|>


<commit_before>//Add the features list
jviz.modules.karyoviewer.prototype.features = function(list)
{
  //Check the features list
  if(typeof list === 'undefined'){ return this; }

  //Check for array
  if(jviz.is.array(list) === false){ list = [ list ]; }

  //Reset the features list
  this._features.list = {};

  //Reset the features counter list
  this._features.counter.list = {};

  //Initialize the features names max length
  this._features.name.length = 0;

  //Read all the features
  for(var i = 0; i < list.length; i++)
  {
    //Get the feature
    var feature = list[i];

    //Initialize the new feature object
    var obj_feature = { posx: 0, posy: 0, width: 0, height: 0 };

    //Save the feature name
    obj_feature.name = feature.name;

    //Save the feature chromosome
    obj_feature.chromosome = feature.chromosome;

    //Save the feature start point
    obj_feature.start = parseInt(feature.start);

    //Save the feature end point
    obj_feature.end = (typeof feature.end === 'undefined') ? obj_feature.start : parseInt(feature.end);

    //Save the feature length
    obj_feature.length = Math.abs(obj_feature.end - obj_feature.start) + 1;

    //Save the feature index
    obj_feature.index = i;

    //Save the feature start position
    //obj.start = draw.height * (feature.start / this._chromosomes.max);

    //Save the feature end position
    //obj.end = draw.height * (feature.end / this._chromosomes.max);

    //feature width
    //obj.width = this._chromosomes.width;

    //feature height
    //obj.height = Math.max(Math.abs(obj.end - obj.start), 1);

    //Add the feature color
    obj_feature.color = (typeof feature.color === 'string') ? feature.color : this._features.color;

    //Check the feature name size
    if(feature.name.length > this._features.name.length){ this._features.name.length = feature.name.length; }

    //Check if chromosome exists
    if(typeof this._features.list[feature.chromosome] === 'undefined')
    {
      //Initialize this chromosome
      this._features.list[feature.chromosome] = [];

      //Add the features counter
      this._features.counter.list[feature.chromosome] = new jviz.canvas.tooltip({ color: this._features.color });
    }

    //Add the index to the chromosome list
    this._features.list[feature.chromosome].push(obj_feature);
  }

  //Initialize the features name tooltip
  this._features.name.tooltip = new jviz.canvas.tooltip({ text: jviz.string.spaces(this._features.name.length) });

  //Set to resize the features
  this._features.resized = false;

  //Continue
  return this;
};

//Resize the features data
jviz.modules.karyoviewer.prototype.featuresResize = function()
{
  //Get the draw info
  var draw = this._block.draw;

  //Get margins
  var margin = this._block.margin;

  //Read all the chromosomes
  for(var i = 0; i < this._chromosomes.list.length; i++)
  {
    //Get the chromosome
    var chr = this._chromosomes.list[i];

    //Check features on this chromosome
    if(typeof this._features.list[chr.name] === 'undefined'){ continue; }

    //Red all features
    for(var j = 0; j < this._features.list[chr.name].length; j++)
    {
      //Get the feature object
      var feature = this._features.list[chr.name][j];

      //Check for landscape
      if(this.isLandscape() === true)
      {
        //Save the feature width
        feature.width = Math.max(draw.width * feature.length / this._chromosomes.max, 1);

        //Save the feature height
        feature.height = this._chromosomes.height;

        //Save the feature position x
        feature.posx = chr.posx + draw.width * Math.min(feature.start, feature.end) / this._chromosomes.max;

        //Save the feature position y
        feature.posy = chr.posy;
      }

      //Check for portrait
      else
      {
        //Save the feature width for portrait
        feature.width = this._chromosomes.width;

        //Save the feature height for portrait
        feature.height = Math.max(draw.height * feature.length / this._chromosomes.max, 1);

        //Save the feature position x for portrait
        feature.posx = chr.posx;

        //Save the feature position y for portrait
        feature.posy = chr.posy + draw.height * Math.min(feature.start, feature.end) / this._chromosomes.max;
      }

      //Save the feature object
      this._features.list[chr.name][j] = feature;
    }

    //Initialize the counter positions object
    var counter = { posx: 0, posy: 0, position: 'top' };

    //Check for landscape
    if(this.isLandscape() === true)
    {
      //Calculate the position x
      counter.posx = chr.posx + chr.width + this._features.counter.margin;

      //Calculate the position y
      counter.posy = chr.posy + chr.height / 2;

      //Set the tooltip position
      counter.position = 'right';
    }

    //Check for portrait
    else
    {
      //Calculate the tooltip position x
      counter.posx = chr.posx + chr.width / 2;

      //Calculate the tooltip position y
      counter.posy = chr.posy - this._features.counter.margin;

      //Set the tooltip position
      counter.position = 'top';
    }

    //Move the counter object
    this._features.counter.list[chr.name].move(counter);

    //Set the tooltip position
    this._features.counter.list[chr.name].position(counter.position);

    //Set the number of features
    this._features.counter.list[chr.name].text(this._features.list[chr.name].length + '');
  }

  //Set features resized
  this._features.resized = true;

  //Continue
  return this;
};

//Draw the features
jviz.modules.karyoviewer.prototype.featuresDraw = function()
{
  //Get the canvas
  var canvas = this._canvas.el.layer(this._features.layer);

  //Read all the chromosomes
  for(var i = 0; i < this._chromosomes.list.length; i++)
  {
    //Get the chromosome
    var chr = this._chromosomes.list[i];

    //Get the features list
    var features = this.featuresByChromosome(chr.name);

    //Red all features
    for(var j = 0; j < features.length; j++)
    {
      //Get this feature
      var feature = features[j];

      //Draw the feature
      canvas.Rect({ x: feature.posx, y: feature.posy, width: feature.width, height: feature.height });

      //feature fill
      canvas.Fill({ color: feature.color, opacity: this._features.opacity });
    }

    //Check for drawing the features counter
    if(this._features.counter.visible === false){ continue; }

    //Check for no features
    if(features.length === 0){ continue; }

    //Draw the counter tooltip
    this._features.counter.list[chr.name].draw(canvas);
  }

  //Exit
  return this;
};

//Get features by chromosome name
jviz.modules.karyoviewer.prototype.featuresByChromosome = function(name)
{
  //Check for no features on this chromosome
  if(typeof this._features.list[name] === 'undefined'){ return []; }

  //Return the features  for this chromosome
  return this._features.list[name];
};
<commit_msg>js/features.js: updated features name tooltip text initialization<commit_after>//Add the features list
jviz.modules.karyoviewer.prototype.features = function(list)
{
  //Check the features list
  if(typeof list === 'undefined'){ return this; }

  //Check for array
  if(jviz.is.array(list) === false){ list = [ list ]; }

  //Reset the features list
  this._features.list = {};

  //Reset the features counter list
  this._features.counter.list = {};

  //Initialize the features names max length
  this._features.name.length = 0;

  //Read all the features
  for(var i = 0; i < list.length; i++)
  {
    //Get the feature
    var feature = list[i];

    //Initialize the new feature object
    var obj_feature = { posx: 0, posy: 0, width: 0, height: 0 };

    //Save the feature name
    obj_feature.name = feature.name;

    //Save the feature chromosome
    obj_feature.chromosome = feature.chromosome;

    //Save the feature start point
    obj_feature.start = parseInt(feature.start);

    //Save the feature end point
    obj_feature.end = (typeof feature.end === 'undefined') ? obj_feature.start : parseInt(feature.end);

    //Save the feature length
    obj_feature.length = Math.abs(obj_feature.end - obj_feature.start) + 1;

    //Save the feature index
    obj_feature.index = i;

    //Save the feature start position
    //obj.start = draw.height * (feature.start / this._chromosomes.max);

    //Save the feature end position
    //obj.end = draw.height * (feature.end / this._chromosomes.max);

    //feature width
    //obj.width = this._chromosomes.width;

    //feature height
    //obj.height = Math.max(Math.abs(obj.end - obj.start), 1);

    //Add the feature color
    obj_feature.color = (typeof feature.color === 'string') ? feature.color : this._features.color;

    //Check the feature name size
    if(feature.name.length > this._features.name.length){ this._features.name.length = feature.name.length; }

    //Check if chromosome exists
    if(typeof this._features.list[feature.chromosome] === 'undefined')
    {
      //Initialize this chromosome
      this._features.list[feature.chromosome] = [];

      //Add the features counter
      this._features.counter.list[feature.chromosome] = new jviz.canvas.tooltip({ color: this._features.color });
    }

    //Add the index to the chromosome list
    this._features.list[feature.chromosome].push(obj_feature);
  }

  //Update the tooltip text
  this._features.name.tooltip.text(jviz.string.spaces(this._features.name.length);

  //Set to resize the features
  this._features.resized = false;

  //Continue
  return this;
};

//Resize the features data
jviz.modules.karyoviewer.prototype.featuresResize = function()
{
  //Get the draw info
  var draw = this._block.draw;

  //Get margins
  var margin = this._block.margin;

  //Read all the chromosomes
  for(var i = 0; i < this._chromosomes.list.length; i++)
  {
    //Get the chromosome
    var chr = this._chromosomes.list[i];

    //Check features on this chromosome
    if(typeof this._features.list[chr.name] === 'undefined'){ continue; }

    //Red all features
    for(var j = 0; j < this._features.list[chr.name].length; j++)
    {
      //Get the feature object
      var feature = this._features.list[chr.name][j];

      //Check for landscape
      if(this.isLandscape() === true)
      {
        //Save the feature width
        feature.width = Math.max(draw.width * feature.length / this._chromosomes.max, 1);

        //Save the feature height
        feature.height = this._chromosomes.height;

        //Save the feature position x
        feature.posx = chr.posx + draw.width * Math.min(feature.start, feature.end) / this._chromosomes.max;

        //Save the feature position y
        feature.posy = chr.posy;
      }

      //Check for portrait
      else
      {
        //Save the feature width for portrait
        feature.width = this._chromosomes.width;

        //Save the feature height for portrait
        feature.height = Math.max(draw.height * feature.length / this._chromosomes.max, 1);

        //Save the feature position x for portrait
        feature.posx = chr.posx;

        //Save the feature position y for portrait
        feature.posy = chr.posy + draw.height * Math.min(feature.start, feature.end) / this._chromosomes.max;
      }

      //Save the feature object
      this._features.list[chr.name][j] = feature;
    }

    //Initialize the counter positions object
    var counter = { posx: 0, posy: 0, position: 'top' };

    //Check for landscape
    if(this.isLandscape() === true)
    {
      //Calculate the position x
      counter.posx = chr.posx + chr.width + this._features.counter.margin;

      //Calculate the position y
      counter.posy = chr.posy + chr.height / 2;

      //Set the tooltip position
      counter.position = 'right';
    }

    //Check for portrait
    else
    {
      //Calculate the tooltip position x
      counter.posx = chr.posx + chr.width / 2;

      //Calculate the tooltip position y
      counter.posy = chr.posy - this._features.counter.margin;

      //Set the tooltip position
      counter.position = 'top';
    }

    //Move the counter object
    this._features.counter.list[chr.name].move(counter);

    //Set the tooltip position
    this._features.counter.list[chr.name].position(counter.position);

    //Set the number of features
    this._features.counter.list[chr.name].text(this._features.list[chr.name].length + '');
  }

  //Set features resized
  this._features.resized = true;

  //Continue
  return this;
};

//Draw the features
jviz.modules.karyoviewer.prototype.featuresDraw = function()
{
  //Get the canvas
  var canvas = this._canvas.el.layer(this._features.layer);

  //Read all the chromosomes
  for(var i = 0; i < this._chromosomes.list.length; i++)
  {
    //Get the chromosome
    var chr = this._chromosomes.list[i];

    //Get the features list
    var features = this.featuresByChromosome(chr.name);

    //Red all features
    for(var j = 0; j < features.length; j++)
    {
      //Get this feature
      var feature = features[j];

      //Draw the feature
      canvas.Rect({ x: feature.posx, y: feature.posy, width: feature.width, height: feature.height });

      //feature fill
      canvas.Fill({ color: feature.color, opacity: this._features.opacity });
    }

    //Check for drawing the features counter
    if(this._features.counter.visible === false){ continue; }

    //Check for no features
    if(features.length === 0){ continue; }

    //Draw the counter tooltip
    this._features.counter.list[chr.name].draw(canvas);
  }

  //Exit
  return this;
};

//Get features by chromosome name
jviz.modules.karyoviewer.prototype.featuresByChromosome = function(name)
{
  //Check for no features on this chromosome
  if(typeof this._features.list[name] === 'undefined'){ return []; }

  //Return the features  for this chromosome
  return this._features.list[name];
};

//Get features by position
jviz.modules.karyoviewer.prototype.featuresByPosition = function(x, y)
{
  //Get the chromosome
  var chr = this.chromosomeByPosition(x, y);

  //Check for no chromosome
  if(chr === false){ return []; }

  //Get the features on this chromosome
  var features = this.featuresByChromosome(chr.name);

  //Check the features length
  if(features.length === 0){ return []; }

  //Output features
  var out = [];

  //Read all the features
  for(var i = 0; i < features.length; i++)
  {
    //Check the feature x coordinate
    if(x < features[i].posx){ break; }

    //Check the feature y coordinate
    if(y < features[i].posy){ break; }

    //Check the feature x coordinate
    if(feautres[i].posx + features[i].width < x){ continue; }

    //Check the feature y coordinate
    if(feautres[i].posy + features[i].height < y){ continue; }

    //Save the feature
    out.push(features[i]);
  }

  //Return the features list
  return out;
};
<|endoftext|>


<commit_before>/*jslint browser: true, devel: true, sloppy: true, plusplus: true, nomen: true, forin: true, continue: true */
/*globals kiwi, $, _, Tabview, Userlist, User, Box */
kiwi.front.ui = {

    doLayoutSize: function () {
        var kiwi, toolbars, ul, n_top, n_bottom, nl;
        kiwi = $('#kiwi');

        if (kiwi.width() < 330 && !kiwi.hasClass('small_kiwi')) {
            console.log("switching to small kiwi");
            kiwi.removeClass('large_kiwi');
            kiwi.addClass('small_kiwi');
        } else if (kiwi.width() >= 330 && !kiwi.hasClass('large_kiwi')) {
            kiwi.removeClass('small_kiwi');
            kiwi.addClass('large_kiwi');
        }

        toolbars = $('#kiwi .toolbars');
        ul = $('#kiwi .userlist');

        n_top = parseInt(toolbars.offset().top, 10) + parseInt(toolbars.outerHeight(true), 10);
        n_bottom = $(document).height() - parseInt($('#kiwi .control').offset().top, 10);

        $('#kiwi .windows').css({top: n_top + 'px', bottom: n_bottom + 'px'});
        ul.css({top: n_top + 'px', bottom: n_bottom + 'px'});

        nl = $('#nicklist_resize');
        nl.css({top: n_top + 'px', bottom: n_bottom + 'px', left: $(document).width() - ul.outerWidth(true)});
    },

    doLayout: function () {
        $('#kiwi .msginput .nick a').text(kiwi.gateway.nick);
        $('#kiwi_msginput').val(' ');
        $('#kiwi_msginput').focus();
    },

    registerKeys: function () {
        var tabcomplete = {active: false, data: [], prefix: ''};
        $('#kiwi_msginput').bind('keydown', function (e) {
            var windows, meta, num, msg, data, self;
            windows = $('#windows');
            //var meta = e.altKey;
            meta = e.ctrlKey;

            if (e.which !== 9) {
                tabcomplete.active = false;
                tabcomplete.data = [];
                tabcomplete.prefix = '';
            }

            switch (true) {
            case (e.which >= 48) && (e.which <= 57):
                if (meta) {
                    num = e.which - 48;
                    if (num === 0) {
                        num = 10;
                    }
                    num = num - 1;
                    kiwi.front.ui.windowsShow(num);
                    return false;
                }
                break;
            case e.which === 27:            // escape
                return false;
            case e.which === 13:            // return
                msg = $('#kiwi_msginput').val();
                msg = msg.trim();

                kiwi.front.buffer.push(msg);
                kiwi.front.buffer_pos = kiwi.front.buffer.length;

                kiwi.front.run(msg);
                $('#kiwi_msginput').val('');

                break;
            case e.which === 33:             // page up
                console.log("page up");
                windows[0].scrollTop = windows[0].scrollTop - windows.height();
                return false;
            case e.which === 34:             // page down
                windows[0].scrollTop = windows[0].scrollTop + windows.height();
                return false;
            case e.which === 37:            // left
                if (meta) {
                    kiwi.front.ui.windowsPrevious();
                    return false;
                }
                break;
            case e.which === 38:            // up
                if (kiwi.front.buffer_pos > 0) {
                    kiwi.front.buffer_pos--;
                    $('#kiwi_msginput').val(kiwi.front.buffer[kiwi.front.buffer_pos]);
                }
                break;
            case e.which === 39:            // right
                if (meta) {
                    kiwi.front.ui.windowsNext();
                    return false;
                }
                break;
            case e.which === 40:            // down
                if (kiwi.front.buffer_pos < kiwi.front.buffer.length) {
                    kiwi.front.buffer_pos++;
                    $('#kiwi_msginput').val(kiwi.front.buffer[kiwi.front.buffer_pos]);
                }
                break;

            case e.which === 9:                // tab
                tabcomplete.active = true;
                if (_.isEqual(tabcomplete.data, [])) {
                    // Get possible autocompletions
                    data = [];
                    Tabview.getCurrentTab().userlist.listUsers(false).each(function () {
                        var nick;
                        nick = User.stripPrefix($('a.nick', this).text());
                        data.push(nick);
                    });
                    data = _.sortBy(data, function (nick) {
                        return nick;
                    });
                    tabcomplete.data = data;
                }

                if (this.value[this.selectionStart - 1] === ' ') {
                    return false;
                }
                self = this;
                (function () {
                    var tokens = self.value.substring(0, self.selectionStart).split(" "),
                        val,
                        p1,
                        newnick,
                        range,
                        nick = tokens[tokens.length - 1];
                    if (tabcomplete.prefix === '') {
                        tabcomplete.prefix = nick;
                    }

                    tabcomplete.data = _.select(tabcomplete.data, function (n) {
                        return (n.toLowerCase().indexOf(tabcomplete.prefix.toLowerCase()) === 0);
                    });

                    if (tabcomplete.data.length > 0) {
                        p1 = self.selectionStart - (nick.length);
                        val = self.value.substr(0, p1);
                        newnick = tabcomplete.data.shift();
                        tabcomplete.data.push(newnick);
                        val += newnick;
                        val += self.value.substr(self.selectionStart);
                        self.value = val;
                        if (self.setSelectionRange) {
                            self.setSelectionRange(p1 + newnick.length, p1 + newnick.length);
                        } else if (self.createTextRange) { // not sure if this bit is actually needed....
                            range = self.createTextRange();
                            range.collapse(true);
                            range.moveEnd('character', p1 + newnick.length);
                            range.moveStart('character', p1 + newnick.length);
                            range.select();
                        }
                    }
                }());
                return false;
            }
        });

        $('#kiwi .control .msginput .nick').click(function () {
            kiwi.front.ui.showChangeNick();
        });

        $('#kiwi .plugins .load_plugin_file').click(function () {
            if (typeof kiwi.front.boxes.plugins !== "undefined") {
                return;
            }

            kiwi.front.boxes.plugins = new Box("plugin_file");
            $('#tmpl_plugins').tmpl({}).appendTo(kiwi.front.boxes.plugins.content);
            kiwi.front.boxes.plugins.box.css('top', -(kiwi.front.boxes.plugins.height + 40));

            // Populate the plugin list..
            function enumPlugins() {
                var lst, j, txt;
                lst = $('#plugin_list');
                lst.find('option').remove();
                for (j in kiwi.plugs.loaded) {
                    txt = kiwi.plugs.loaded[j].name;
                    lst.append('<option value="' + txt + '">' + txt + '</option>');
                }
            }
            enumPlugins();

            // Event bindings
            $('#kiwi .plugin_file').submit(function () {
                $('

').load($('.txtpluginfile').val(), function (e) {
                    enumPlugins();
                });
                return false;
            });
            $('#kiwi .cancelpluginfile').click(function () {
                kiwi.front.boxes.plugins.destroy();
            });

            $('#kiwi #plugins_list_unload').click(function () {
                var selected_plugin;
                selected_plugin = $('#plugin_list').val();
                kiwi.plugs.unloadPlugin(selected_plugin);
                enumPlugins();
            });

            $('#kiwi .txtpluginfile').focus();

        });

        $('#kiwi .plugins .reload_css').click(function () {
            var links = document.getElementsByTagName("link"),
                i;
            for (i = 0; i < links.length; i++) {
                if (links[i].rel === "stylesheet") {
                    if (links[i].href.indexOf("?") === -1) {
                        links[i].href += "?";
                    }
                    links[i].href += "x";
                }
            }
        });

        $('#kiwi .about .about_close').click(function () {
            $('#kiwi .about').css('display', 'none');
        });

        $('#kiwi .poweredby').click(function () {
            $('#kiwi .about').css('display', 'block');
        });

    },

    showChangeNick: function (caption) {
        caption = (typeof caption !== 'undefined') ? caption : '';

        $('#kiwi').append($('#tmpl_change_nick').tmpl({}));

        $('#kiwi .newnick .caption').text(caption);

        $('#kiwi .form_newnick').submit(function () {
            kiwi.front.run('/NICK ' + $('#kiwi .txtnewnick').val());
            $('#kiwi .newnick').remove();
            return false;
        });

        $('#kiwi .txtnewnick').keypress(function (ev) {
            if (!this.first_press) {
                this.first_press = true;
                return false;
            }
        });

        $('#kiwi .txtnewnick').keydown(function (ev) {
            if (ev.which === 27) {  // ESC
                $('#kiwi_msginput').focus();
                $('#kiwi .newnick').remove();
            }
        });

        $('#kiwi .cancelnewnick').click(function () {
            $('#kiwi .newnick').remove();
        });

        $('#kiwi .txtnewnick').focus();
    },

    setTopicText: function (new_topic) {
        kiwi.front.cache.original_topic = new_topic;
        $('#kiwi .cur_topic .topic').text(new_topic);
        kiwi.front.ui.doLayoutSize();
    },

    tabviewsNext: function () {
        var wl = $('#kiwi .windowlist ul'),
            next_left = parseInt(wl.css('text-indent').replace('px', ''), 10) + 170;
        wl.css('text-indent', next_left);
    },

    tabviewsPrevious: function () {
        var wl = $('#kiwi .windowlist ul'),
            next_left = parseInt(wl.css('text-indent').replace('px', ''), 10) - 170;
        wl.css('text-indent', next_left);
    },

    windowsNext: function () {
        var tab, tabs, curTab, next;
        next = false;
        tabs = Tabview.getAllTabs();
        curTab = Tabview.getCurrentTab();
        for (tab in tabs) {
            if (!next) {
                if (tabs[tab] === curTab) {
                    next = true;
                    continue;
                }
            } else {
                tabs[tab].show();
                return;
            }
        }
    },

    windowsPrevious: function () {
        var tab, tabs, curTab, prev_tab, next;
        next = false;
        tabs = Tabview.getAllTabs();
        curTab = Tabview.getCurrentTab();
        for (tab in tabs) {
            if (tabs[tab] === curTab) {
                if (prev_tab) {
                    prev_tab.show();
                }
                return;
            }
            prev_tab = tabs[tab];
        }
    },

    windowsShow: function (num) {
        num = parseInt(num, 10);
        console.log('Showing window ' + num.toString());
        var i = 0, tab, tabs;
        tabs = Tabview.getAllTabs();
        for (tab in tabs) {
            if (i === num) {
                tabs[tab].show();
                return;
            }
            i++;
        }
    },

    barsShow: function () {
        $('#kiwi .toolbars').slideDown();
        $('#kiwi .control').slideDown();
    },

    barsHide: function () {
        $('#kiwi .toolbars').slideUp();
        $('#kiwi .control').slideUp();
    },

    tutorial: function () {
        var b = $('

'),
            bounds,
            s,
            current_s,
            next_s;
        b.css({display: 'block', position: 'absolute', height:'100%', width:'100%'});
        $('#kiwi').append(b);

        bounds = function (el) {
            var b = 3, ret = {};
            ret.top = el.offset().top;
            ret.left = el.offset().left;
            ret.width = parseInt(el.outerWidth(true), 10) - (b*2);
            ret.height = parseInt(el.outerHeight(true), 10) - (b*2);
            return ret;
        };

        s = [
            function(){
                b.animate(bounds($('#kiwi .msginput')), 2000, '', next_s);
            },

            function(){
                b.animate(bounds($('#kiwi .userlist')), 2000, '', next_s);
            },

            function(){
                b.animate(bounds($('#panel1')), 2000, '', next_s);
            },

            function(){
                b.animate(bounds($('#kiwi .cur_topic')), 2000, '', next_s);
            },

            function(){
                b.animate(bounds($('#kiwi .windowlist')), 2000, '', next_s);
            }
        ];

        current_s = -1;
        next_s = function () {
            current_s++;
            if (typeof s[current_s] === 'function') {
                console.log('Animating ' + current_s.toString());
                s[current_s]();
            }
        };
        next_s();
    }

};<commit_msg>Nick autocomplete fix<commit_after>/*jslint browser: true, devel: true, sloppy: true, plusplus: true, nomen: true, forin: true, continue: true */
/*globals kiwi, $, _, Tabview, Userlist, User, Box */
kiwi.front.ui = {

    doLayoutSize: function () {
        var kiwi, toolbars, ul, n_top, n_bottom, nl;
        kiwi = $('#kiwi');

        if (kiwi.width() < 330 && !kiwi.hasClass('small_kiwi')) {
            console.log("switching to small kiwi");
            kiwi.removeClass('large_kiwi');
            kiwi.addClass('small_kiwi');
        } else if (kiwi.width() >= 330 && !kiwi.hasClass('large_kiwi')) {
            kiwi.removeClass('small_kiwi');
            kiwi.addClass('large_kiwi');
        }

        toolbars = $('#kiwi .toolbars');
        ul = $('#kiwi .userlist');

        n_top = parseInt(toolbars.offset().top, 10) + parseInt(toolbars.outerHeight(true), 10);
        n_bottom = $(document).height() - parseInt($('#kiwi .control').offset().top, 10);

        $('#kiwi .windows').css({top: n_top + 'px', bottom: n_bottom + 'px'});
        ul.css({top: n_top + 'px', bottom: n_bottom + 'px'});

        nl = $('#nicklist_resize');
        nl.css({top: n_top + 'px', bottom: n_bottom + 'px', left: $(document).width() - ul.outerWidth(true)});
    },

    doLayout: function () {
        $('#kiwi .msginput .nick a').text(kiwi.gateway.nick);
        $('#kiwi_msginput').val(' ');
        $('#kiwi_msginput').focus();
    },

    registerKeys: function () {
        var tabcomplete = {active: false, data: [], prefix: ''};
        $('#kiwi_msginput').bind('keydown', function (e) {
            var windows, meta, num, msg, data, self;
            windows = $('#windows');
            //var meta = e.altKey;
            meta = e.ctrlKey;

            if (e.which !== 9) {
                tabcomplete.active = false;
                tabcomplete.data = [];
                tabcomplete.prefix = '';
            }

            switch (true) {
            case (e.which >= 48) && (e.which <= 57):
                if (meta) {
                    num = e.which - 48;
                    if (num === 0) {
                        num = 10;
                    }
                    num = num - 1;
                    kiwi.front.ui.windowsShow(num);
                    return false;
                }
                break;
            case e.which === 27:            // escape
                return false;
            case e.which === 13:            // return
                msg = $('#kiwi_msginput').val();
                msg = msg.trim();

                kiwi.front.buffer.push(msg);
                kiwi.front.buffer_pos = kiwi.front.buffer.length;

                kiwi.front.run(msg);
                $('#kiwi_msginput').val('');

                break;
            case e.which === 33:             // page up
                console.log("page up");
                windows[0].scrollTop = windows[0].scrollTop - windows.height();
                return false;
            case e.which === 34:             // page down
                windows[0].scrollTop = windows[0].scrollTop + windows.height();
                return false;
            case e.which === 37:            // left
                if (meta) {
                    kiwi.front.ui.windowsPrevious();
                    return false;
                }
                break;
            case e.which === 38:            // up
                if (kiwi.front.buffer_pos > 0) {
                    kiwi.front.buffer_pos--;
                    $('#kiwi_msginput').val(kiwi.front.buffer[kiwi.front.buffer_pos]);
                }
                break;
            case e.which === 39:            // right
                if (meta) {
                    kiwi.front.ui.windowsNext();
                    return false;
                }
                break;
            case e.which === 40:            // down
                if (kiwi.front.buffer_pos < kiwi.front.buffer.length) {
                    kiwi.front.buffer_pos++;
                    $('#kiwi_msginput').val(kiwi.front.buffer[kiwi.front.buffer_pos]);
                }
                break;

            case e.which === 9:                // tab
                tabcomplete.active = true;
                if (_.isEqual(tabcomplete.data, [])) {
                    // Get possible autocompletions
                    data = [];
                    $.each(Tabview.getCurrentTab().userlist.listUsers(false), function () {
                        var nick;
                        nick = User.stripPrefix(this.nick);
                        data.push(nick);
                    });
                    data = _.sortBy(data, function (nick) {
                        return nick;
                    });
                    tabcomplete.data = data;
                }

                if (this.value[this.selectionStart - 1] === ' ') {
                    return false;
                }
                self = this;
                (function () {
                    var tokens = self.value.substring(0, self.selectionStart).split(" "),
                        val,
                        p1,
                        newnick,
                        range,
                        nick = tokens[tokens.length - 1];
                    if (tabcomplete.prefix === '') {
                        tabcomplete.prefix = nick;
                    }

                    tabcomplete.data = _.select(tabcomplete.data, function (n) {
                        return (n.toLowerCase().indexOf(tabcomplete.prefix.toLowerCase()) === 0);
                    });

                    if (tabcomplete.data.length > 0) {
                        p1 = self.selectionStart - (nick.length);
                        val = self.value.substr(0, p1);
                        newnick = tabcomplete.data.shift();
                        tabcomplete.data.push(newnick);
                        val += newnick;
                        val += self.value.substr(self.selectionStart);
                        self.value = val;
                        if (self.setSelectionRange) {
                            self.setSelectionRange(p1 + newnick.length, p1 + newnick.length);
                        } else if (self.createTextRange) { // not sure if this bit is actually needed....
                            range = self.createTextRange();
                            range.collapse(true);
                            range.moveEnd('character', p1 + newnick.length);
                            range.moveStart('character', p1 + newnick.length);
                            range.select();
                        }
                    }
                }());
                return false;
            }
        });

        $('#kiwi .control .msginput .nick').click(function () {
            kiwi.front.ui.showChangeNick();
        });

        $('#kiwi .plugins .load_plugin_file').click(function () {
            if (typeof kiwi.front.boxes.plugins !== "undefined") {
                return;
            }

            kiwi.front.boxes.plugins = new Box("plugin_file");
            $('#tmpl_plugins').tmpl({}).appendTo(kiwi.front.boxes.plugins.content);
            kiwi.front.boxes.plugins.box.css('top', -(kiwi.front.boxes.plugins.height + 40));

            // Populate the plugin list..
            function enumPlugins() {
                var lst, j, txt;
                lst = $('#plugin_list');
                lst.find('option').remove();
                for (j in kiwi.plugs.loaded) {
                    txt = kiwi.plugs.loaded[j].name;
                    lst.append('<option value="' + txt + '">' + txt + '</option>');
                }
            }
            enumPlugins();

            // Event bindings
            $('#kiwi .plugin_file').submit(function () {
                $('

').load($('.txtpluginfile').val(), function (e) {
                    enumPlugins();
                });
                return false;
            });
            $('#kiwi .cancelpluginfile').click(function () {
                kiwi.front.boxes.plugins.destroy();
            });

            $('#kiwi #plugins_list_unload').click(function () {
                var selected_plugin;
                selected_plugin = $('#plugin_list').val();
                kiwi.plugs.unloadPlugin(selected_plugin);
                enumPlugins();
            });

            $('#kiwi .txtpluginfile').focus();

        });

        $('#kiwi .plugins .reload_css').click(function () {
            var links = document.getElementsByTagName("link"),
                i;
            for (i = 0; i < links.length; i++) {
                if (links[i].rel === "stylesheet") {
                    if (links[i].href.indexOf("?") === -1) {
                        links[i].href += "?";
                    }
                    links[i].href += "x";
                }
            }
        });

        $('#kiwi .about .about_close').click(function () {
            $('#kiwi .about').css('display', 'none');
        });

        $('#kiwi .poweredby').click(function () {
            $('#kiwi .about').css('display', 'block');
        });

    },

    showChangeNick: function (caption) {
        caption = (typeof caption !== 'undefined') ? caption : '';

        $('#kiwi').append($('#tmpl_change_nick').tmpl({}));

        $('#kiwi .newnick .caption').text(caption);

        $('#kiwi .form_newnick').submit(function () {
            kiwi.front.run('/NICK ' + $('#kiwi .txtnewnick').val());
            $('#kiwi .newnick').remove();
            return false;
        });

        $('#kiwi .txtnewnick').keypress(function (ev) {
            if (!this.first_press) {
                this.first_press = true;
                return false;
            }
        });

        $('#kiwi .txtnewnick').keydown(function (ev) {
            if (ev.which === 27) {  // ESC
                $('#kiwi_msginput').focus();
                $('#kiwi .newnick').remove();
            }
        });

        $('#kiwi .cancelnewnick').click(function () {
            $('#kiwi .newnick').remove();
        });

        $('#kiwi .txtnewnick').focus();
    },

    setTopicText: function (new_topic) {
        kiwi.front.cache.original_topic = new_topic;
        $('#kiwi .cur_topic .topic').text(new_topic);
        kiwi.front.ui.doLayoutSize();
    },

    tabviewsNext: function () {
        var wl = $('#kiwi .windowlist ul'),
            next_left = parseInt(wl.css('text-indent').replace('px', ''), 10) + 170;
        wl.css('text-indent', next_left);
    },

    tabviewsPrevious: function () {
        var wl = $('#kiwi .windowlist ul'),
            next_left = parseInt(wl.css('text-indent').replace('px', ''), 10) - 170;
        wl.css('text-indent', next_left);
    },

    windowsNext: function () {
        var tab, tabs, curTab, next;
        next = false;
        tabs = Tabview.getAllTabs();
        curTab = Tabview.getCurrentTab();
        for (tab in tabs) {
            if (!next) {
                if (tabs[tab] === curTab) {
                    next = true;
                    continue;
                }
            } else {
                tabs[tab].show();
                return;
            }
        }
    },

    windowsPrevious: function () {
        var tab, tabs, curTab, prev_tab, next;
        next = false;
        tabs = Tabview.getAllTabs();
        curTab = Tabview.getCurrentTab();
        for (tab in tabs) {
            if (tabs[tab] === curTab) {
                if (prev_tab) {
                    prev_tab.show();
                }
                return;
            }
            prev_tab = tabs[tab];
        }
    },

    windowsShow: function (num) {
        num = parseInt(num, 10);
        console.log('Showing window ' + num.toString());
        var i = 0, tab, tabs;
        tabs = Tabview.getAllTabs();
        for (tab in tabs) {
            if (i === num) {
                tabs[tab].show();
                return;
            }
            i++;
        }
    },

    barsShow: function () {
        $('#kiwi .toolbars').slideDown();
        $('#kiwi .control').slideDown();
    },

    barsHide: function () {
        $('#kiwi .toolbars').slideUp();
        $('#kiwi .control').slideUp();
    },

    tutorial: function () {
        var b = $('

'),
            bounds,
            s,
            current_s,
            next_s;
        b.css({display: 'block', position: 'absolute', height:'100%', width:'100%'});
        $('#kiwi').append(b);

        bounds = function (el) {
            var b = 3, ret = {};
            ret.top = el.offset().top;
            ret.left = el.offset().left;
            ret.width = parseInt(el.outerWidth(true), 10) - (b*2);
            ret.height = parseInt(el.outerHeight(true), 10) - (b*2);
            return ret;
        };

        s = [
            function(){
                b.animate(bounds($('#kiwi .msginput')), 2000, '', next_s);
            },

            function(){
                b.animate(bounds($('#kiwi .userlist')), 2000, '', next_s);
            },

            function(){
                b.animate(bounds($('#panel1')), 2000, '', next_s);
            },

            function(){
                b.animate(bounds($('#kiwi .cur_topic')), 2000, '', next_s);
            },

            function(){
                b.animate(bounds($('#kiwi .windowlist')), 2000, '', next_s);
            }
        ];

        current_s = -1;
        next_s = function () {
            current_s++;
            if (typeof s[current_s] === 'function') {
                console.log('Animating ' + current_s.toString());
                s[current_s]();
            }
        };
        next_s();
    }

};<|endoftext|>


<commit_before>var Q = require('q');
var async = require('async');
var fs = require('fs');
var cssom = require('cssom');
var request = require('request');
var crypto = require('crypto');

module.exports = {
    newRule: function() {
        return {
            ignored: false,
            matches_html: 0,
            occurences_css: 0,
            pos_css: {}
        };
    },

    // TODO: Document result object properly
    /**
     * Get CSS selectors from CSS
     * @param {Array}  css CSS to search through. This can be either an array
     *         of Strings (containing CSS), an array of URIs to CSS files, or
     *         an array of paths to CSS files.
     * @param {Object} result Result object
     * @param {Int}    timeout Request timeout
     * @returns {Promise} Result object
     */
    getSelectors: function(css, result, timeout) {
        var self = this;
        var deferred = Q.defer();

        // Find all selectors
        async.forEach(css, function(item, forEachCallback) {
            var itemId = "";
            if (0 === item.indexOf("http")) { // From URI
                itemId = item;

                var options = { uri: item,
                                timeout: timeout || 4000,
                                pool: false };

                request.get(options, function(error, res, data) {
                        self._extractSelectorsFromString(
                                itemId, data, result);
                        forEachCallback();
                });

                return;
            } else if (-1 === item.indexOf("{")) { // From file
                itemId = item;

                try {
                    item = fs.readFileSync(item).toString();
                } catch (e) {
                    console.warn("getSelectors(): unable to read file %s: %s,", item, e.message);
                }
                self._extractSelectorsFromString(itemId, item, result);
            } else { // From string
                itemId = crypto.createHash('md5').update(item).digest('hex');

                self._extractSelectorsFromString(itemId, item, result);
            }

            forEachCallback();
        }, function(err) {
            if (err) {
                // TODO: Error handling
                deferred.reject(new Error(err));
            } else {
                deferred.resolve(result);
            }
        });

        return deferred.promise;
    },

    // TODO: Document result object properly
    /**
     * Find selectors in CSS string
     *
     * @private
     * @param {String} css CSS code
     * @param {Object} selectors (optional) object to append found selectors
     *        to. Also keeps count (e.g. {'.foo': 2})
     * @param {Object} result Result object
     * @returns {Object} Result object
     */
    _extractSelectorsFromString: function(itemId, css, result) {
        if (!css) {
            return result;
        }

        // Delete unsupported rules before CSSOM parsing, to avoid crash
        // TODO: Remove these, when/if they get supported by CSSOM
        var unsupported = [
            // "@supports { .foo { ... }}" or
            // "@-prefix-supports { .foo { ... }}"
            /@-*\w*-*supports\s.*?\}\s*?\}/g,

            // "@document url(http://example.com) { .foo { ... }}" or
            // "@-prefix-document url(http://example.com) { .foo { ... }}"
            /@-*\w*-*document\s.*?\}\s*?\}/g];
        for (var i=0, l=unsupported.length; i<l; i++) {
            css = css.replace(unsupported[i], "");
        }

        var styles = cssom.parse(css);
        var rules = styles.cssRules;
        if (!rules) {
            return result;
        }

        this._getSelectorsFromRules(itemId, rules, result);

        return result;
    },

    // TODO: Document result object properly
    /**
     * @private
     * @param {Object} rules Object as given by cssom.parse().cssRules.
     * @param {Object} selectors Already found selectors, with count.
     * @param {Object} result Result object
     * @returns {Object} Result object
     */
    _getSelectorsFromRules: function(itemId, rules, result) {
        for (var i=0, l=rules.length; i<l; i++) {
            var rule = rules[i];
            var pos = rule.__starts;

            // @-rules are ignored, except media queries. For media queries,
            // child rules are handled. Other rules are handled as if they
            // have a selector text.
            //
            // @media:
            if (rule.media && rule.cssRules) {
                this._getSelectorsFromRules(itemId, rule.cssRules, result);

            // Rules without selectorText are not processed (@-rules,
            // except @media)
            } else if (!rule.selectorText) {
                // Cleaning: Only want the first part (e.g. @font-face),
                // not full rule
                var sel = rule.cssText.split("{")[0].trim();
                result.selectors[sel] = this.newRule();
                result.selectors[sel].occurences_css++;
                result.total++;

            // Other rules, containing selector(s)
            } else {
                var selectorGroup = rule.selectorText;

                // Several selectors can be grouped together, separated by
                // comma, e.g. ".foo, .bar":
                var selectorList = selectorGroup.split(",");
                var selectors = result.selectors;

                for (var j=0, sl=selectorList.length; j<sl; j++) {
                    var s = selectorList[j].trim();

                    if (undefined === selectors[s]) {
                        selectors[s] = this.newRule();
                        selectors[s].occurences_css = 1;
                        result.total++;
                    } else {
                        selectors[s].occurences_css++;
                    }

                    if (undefined === selectors[s].pos_css[itemId]) {
                        selectors[s].pos_css[itemId] = [pos];
                    } else {
                        selectors[s].pos_css[itemId].push(pos);
                    }
                }
            }
        }

        return result;
    }
};<commit_msg>Update css.js<commit_after>var Q = require('q');
var async = require('async');
var fs = require('fs');
var cssom = require('cssom');
var request = require('request');
var crypto = require('crypto');

module.exports = {
    // TODO: Make private, add documentation. Rename to newSelector?
    newRule: function() {
        return {
            ignored: false,
            matches_html: 0,
            occurences_css: 0,
            pos_css: {}
        };
    },

    // TODO: Document result object properly
    /**
     * Get CSS selectors from CSS
     * @param {Array}  css CSS to search through. This can be either an array
     *         of Strings (containing CSS), an array of URIs to CSS files, or
     *         an array of paths to CSS files.
     * @param {Object} result Result object
     * @param {Int}    timeout Request timeout
     * @returns {Promise} Result object
     */
    getSelectors: function(css, result, timeout) {
        var self = this;
        var deferred = Q.defer();

        // Find all selectors
        async.forEach(css, function(item, forEachCallback) {
            var itemId = "";
            if (0 === item.indexOf("http")) { // From URI
                itemId = item;

                var options = { uri: item,
                                timeout: timeout || 4000,
                                pool: false };

                request.get(options, function(error, res, data) {
                        self._extractSelectorsFromString(
                                itemId, data, result);
                        forEachCallback();
                });

                return;
            } else if (-1 === item.indexOf("{")) { // From file
                itemId = item;

                try {
                    item = fs.readFileSync(item).toString();
                } catch (e) {
                    console.warn("getSelectors(): unable to read file %s: %s,", item, e.message);
                }
                self._extractSelectorsFromString(itemId, item, result);
            } else { // From string
                itemId = crypto.createHash('md5').update(item).digest('hex');

                self._extractSelectorsFromString(itemId, item, result);
            }

            forEachCallback();
        }, function(err) {
            if (err) {
                // TODO: Error handling
                deferred.reject(new Error(err));
            } else {
                deferred.resolve(result);
            }
        });

        return deferred.promise;
    },

    // TODO: Document result object properly
    /**
     * Find selectors in CSS string
     *
     * @private
     * @param {String} css CSS code
     * @param {Object} selectors (optional) object to append found selectors
     *        to. Also keeps count (e.g. {'.foo': 2})
     * @param {Object} result Result object
     * @returns {Object} Result object
     */
    _extractSelectorsFromString: function(itemId, css, result) {
        if (!css) {
            return result;
        }

        // Delete unsupported rules before CSSOM parsing, to avoid crash
        // TODO: Remove these, when/if they get supported by CSSOM
        var unsupported = [
            // "@supports { .foo { ... }}" or
            // "@-prefix-supports { .foo { ... }}"
            /@-*\w*-*supports\s.*?\}\s*?\}/g,

            // "@document url(http://example.com) { .foo { ... }}" or
            // "@-prefix-document url(http://example.com) { .foo { ... }}"
            /@-*\w*-*document\s.*?\}\s*?\}/g];
        for (var i=0, l=unsupported.length; i<l; i++) {
            css = css.replace(unsupported[i], "");
        }

        var styles = cssom.parse(css);
        var rules = styles.cssRules;
        if (!rules) {
            return result;
        }

        this._getSelectorsFromRules(itemId, rules, result);

        return result;
    },

    // TODO: Document result object properly
    /**
     * @private
     * @param {Object} rules Object as given by cssom.parse().cssRules.
     * @param {Object} selectors Already found selectors, with count.
     * @param {Object} result Result object
     * @returns {Object} Result object
     */
    _getSelectorsFromRules: function(itemId, rules, result) {
        for (var i=0, l=rules.length; i<l; i++) {
            var rule = rules[i];
            var pos = rule.__starts;

            // @-rules are ignored, except media queries. For media queries,
            // child rules are handled. Other rules are handled as if they
            // have a selector text.
            //
            // @media:
            if (rule.media && rule.cssRules) {
                this._getSelectorsFromRules(itemId, rule.cssRules, result);

            // Rules without selectorText are not processed (@-rules,
            // except @media)
            } else if (!rule.selectorText) {
                // Cleaning: Only want the first part (e.g. @font-face),
                // not full rule
                var sel = rule.cssText.split("{")[0].trim();
                result.selectors[sel] = this.newRule();
                result.selectors[sel].occurences_css++;
                result.total++;

            // Other rules, containing selector(s)
            } else {
                var selectorGroup = rule.selectorText;

                // Several selectors can be grouped together, separated by
                // comma, e.g. ".foo, .bar":
                var selectorList = selectorGroup.split(",");
                var selectors = result.selectors;

                for (var j=0, sl=selectorList.length; j<sl; j++) {
                    var s = selectorList[j].trim();

                    if (undefined === selectors[s]) {
                        selectors[s] = this.newRule();
                        selectors[s].occurences_css = 1;
                        result.total++;
                    } else {
                        selectors[s].occurences_css++;
                    }

                    if (undefined === selectors[s].pos_css[itemId]) {
                        selectors[s].pos_css[itemId] = [pos];
                    } else {
                        selectors[s].pos_css[itemId].push(pos);
                    }
                }
            }
        }

        return result;
    }
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import {Input, Button} from 'react-bootstrap';

export default class Commit extends Component {
  static propTypes = {
    commit: PropTypes.func.isRequired
  }
  constructor(props) {
    super(props);
    this.state = {message: ''};
  }

  onChange(e) {
    this.setState({message: e.target.value});
  }

  commit() {
    this.props.commit(this.refs.message.value);
  }

  render() {
    return (

          <Input type="textarea" value={this.state.message} onChange={this.onChange.bind(this)} ref="message" placeholder="Enter a commit message..."/>
          <Button disabled={this.state.message.length < 1} onClick={() => this.commit()}>Commit</Button>

      );
  }
}
<commit_msg>Fix commit text bug.<commit_after>import React, { Component, PropTypes } from 'react';
import {Input, Button} from 'react-bootstrap';

export default class Commit extends Component {
  static propTypes = {
    commit: PropTypes.func.isRequired
  }
  constructor(props) {
    super(props);
    this.state = {message: ''};
  }

  onChange(e) {
    this.setState({message: e.target.value});
  }

  commit() {
    this.props.commit(this.state.message);
    this.setState({message: ''});
  }

  render() {
    return (

          <Input type="textarea" value={this.state.message} onChange={this.onChange.bind(this)} ref="message" placeholder="Enter a commit message..."/>
          <Button disabled={this.state.message.length < 1} onClick={() => this.commit()}>Commit</Button>

      );
  }
}
<|endoftext|>


<commit_before>(function(window){

	if('function' === typeof window.highlight)
	{
		window.highlight.sql=[
			{
				'class':'string',
				'match':/("(?:[^"]|\\")*"|'(?:[^']|\\')*')(?=[\b\s\(\),])/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'number',
				'match':/(?![a-z_\-])(\d+(?:\.\d+))(?=[\b\s\(\),])/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'comment',
				'match':/((?:\/\/|\-\-\s|#\s)[^\r\n]*|\/\*(?:[^*]|\*[^\/])*\*\/)/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'name',
				'match':/(`[^`]+`)/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'keyword',
				//the keyword replace must have an aditional check (`(?!\()` after the name), due to the function replace()
				'match':/\b(accessible|add|all|alter|analyze|and|as|asc|asensitive|before|between|bigint|binary|blob|both|by|call|cascade|case|change|char|character|check|collate|column|condition|constraint|continue|convert|create|cross|current_date|current_time|current_timestamp|current_user|cursor|database|databases|day_hour|day_microsecond|day_minute|day_second|dec|decimal|declare|default|delayed|delete|desc|describe|deterministic|distinct|distinctrow|div|double|drop|dual|each|else|elseif|enclosed|escaped|exists|exit|explain|false|fetch|float|float4|float8|for|force|foreign|from|fulltext|generated|get|grant|group|having|high_priority|hour_microsecond|hour_minute|hour_second|if|ignore|in|index|infile|inner|inout|insensitive|insert|int|int1|int2|int3|int4|int8|integer|interval|into|io_after_gtids|io_before_gtids|is|iterate|join|key|keys|kill|leading|leave|left|like|limit|linear|lines|load|localtime|localtimestamp|lock|long|longblob|longtext|loop|low_priority|master_bind|master_ssl_verify_server_cert|match|maxvalue|mediumblob|mediumint|mediumtext|middleint|minute_microsecond|minute_second|mod|modifies|natural|nonblocking|not|no_write_to_binlog|null|numeric|on|optimize|optimizer_costs|option|optionally|or|order|out|outer|outfile|parse_gcol_expr|partition|precision|primary|procedure|purge|range|read|reads|read_write|real|references|regexp|release|rename|repeat|replace(?!\()|require|resignal|restrict|return|revoke|right|rlike|schema|schemas|second_microsecond|select|sensitive|separator|set|show|signal|smallint|spatial|specific|sql|sqlexception|sqlstate|sqlwarning|sql_big_result|sql_calc_found_rows|sql_small_result|ssl|starting|stored|straight_join|table|terminated|then|tinyblob|tinyint|tinytext|to|trailing|trigger|true|undo|union|unique|unlock|unsigned|update|usage|use|using|utc_date|utc_time|utc_timestamp|values|varbinary|varchar|varcharacter|varying|virtual|when|where|while|with|write|xor|year_month|zerofill)\b/gi,
				'replace':window.highlight.default_replace
			},
			{
				'class':'func',
				'match':/\b([a-z_][a-z_\d]*)\b(?=\()/gi,
				'replace':window.highlight.default_replace
			}
		];
	}

})(Function('return this')());
<commit_msg>Fixed negative and positive matching<commit_after>(function(window){

	if('function' === typeof window.highlight)
	{
		window.highlight.sql=[
			{
				'class':'string',
				'match':/("(?:[^"]|\\")*"|'(?:[^']|\\')*')(?=[\b\s\(\),])/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'number',
				'match':/(?![a-z_])([+\-]?\d+(?:\.\d+))(?=[\b\s\(\),])/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'comment',
				'match':/((?:\/\/|\-\-\s|#\s)[^\r\n]*|\/\*(?:[^*]|\*[^\/])*\*\/)/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'name',
				'match':/(`[^`]+`)/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'keyword',
				//the keyword replace must have an aditional check (`(?!\()` after the name), due to the function replace()
				'match':/\b(accessible|add|all|alter|analyze|and|as|asc|asensitive|before|between|bigint|binary|blob|both|by|call|cascade|case|change|char|character|check|collate|column|condition|constraint|continue|convert|create|cross|current_date|current_time|current_timestamp|current_user|cursor|database|databases|day_hour|day_microsecond|day_minute|day_second|dec|decimal|declare|default|delayed|delete|desc|describe|deterministic|distinct|distinctrow|div|double|drop|dual|each|else|elseif|enclosed|escaped|exists|exit|explain|false|fetch|float|float4|float8|for|force|foreign|from|fulltext|generated|get|grant|group|having|high_priority|hour_microsecond|hour_minute|hour_second|if|ignore|in|index|infile|inner|inout|insensitive|insert|int|int1|int2|int3|int4|int8|integer|interval|into|io_after_gtids|io_before_gtids|is|iterate|join|key|keys|kill|leading|leave|left|like|limit|linear|lines|load|localtime|localtimestamp|lock|long|longblob|longtext|loop|low_priority|master_bind|master_ssl_verify_server_cert|match|maxvalue|mediumblob|mediumint|mediumtext|middleint|minute_microsecond|minute_second|mod|modifies|natural|nonblocking|not|no_write_to_binlog|null|numeric|on|optimize|optimizer_costs|option|optionally|or|order|out|outer|outfile|parse_gcol_expr|partition|precision|primary|procedure|purge|range|read|reads|read_write|real|references|regexp|release|rename|repeat|replace(?!\()|require|resignal|restrict|return|revoke|right|rlike|schema|schemas|second_microsecond|select|sensitive|separator|set|show|signal|smallint|spatial|specific|sql|sqlexception|sqlstate|sqlwarning|sql_big_result|sql_calc_found_rows|sql_small_result|ssl|starting|stored|straight_join|table|terminated|then|tinyblob|tinyint|tinytext|to|trailing|trigger|true|undo|union|unique|unlock|unsigned|update|usage|use|using|utc_date|utc_time|utc_timestamp|values|varbinary|varchar|varcharacter|varying|virtual|when|where|while|with|write|xor|year_month|zerofill)\b/gi,
				'replace':window.highlight.default_replace
			},
			{
				'class':'func',
				'match':/\b([a-z_][a-z_\d]*)\b(?=\()/gi,
				'replace':window.highlight.default_replace
			}
		];
	}

})(Function('return this')());
<|endoftext|>


<commit_before>import {h, Component} from 'preact'
import {connect} from 'preact-redux'
import {createBox} from '../actions/box'
import {Recaptcha} from './Recaptcha'

export class Launch extends Component {

  constructor(props) {
    super(props)

    this.state = {
        image: CONFIG.images[0]
    }
  }

  launchClick() {
    this.props.dispatch(createBox({
      image: this.state.image.image,
      version: this.state.image.versions[0],
      captcha: this.state.captcha
    }))

    this.setState({
      loading: true
    })
  }

  render({box}, {image}) {
    return

              Launch a Linux box with two clicks.

            {CONFIG.images.map((i) =>

                 this.setState({image: i})}>

{i.displayName}

{i.versions[0]}

            )}

              <Recaptcha
                sitekey={CONFIG.rcsitekey}
                onChange={c => this.setState({captcha: c})}
              />

                Launch

            {box.error ?

                {box.error.message}

            : null}

                      Free

                      Termbox is completely free, no sign up required.

                      Secure

                      Boxes are securely isolated in their own virtual
                      machine.

                      Ephemeral

                      Boxes and all their data are automatically deleted after
                      3 hours.

For more information, visit our FAQ.

  }

}

export const LaunchContainer = connect(
  state => ({box: state.box}),
  dispatch => ({dispatch})
)(Launch);
<commit_msg>fix error alignment<commit_after>import {h, Component} from 'preact'
import {connect} from 'preact-redux'
import {createBox} from '../actions/box'
import {Recaptcha} from './Recaptcha'

export class Launch extends Component {

  constructor(props) {
    super(props)

    this.state = {
        image: CONFIG.images[0]
    }
  }

  launchClick() {
    this.props.dispatch(createBox({
      image: this.state.image.image,
      version: this.state.image.versions[0],
      captcha: this.state.captcha
    }))

    this.setState({
      loading: true
    })
  }

  render({box}, {image}) {
    return

              Launch a Linux box with two clicks.

            {CONFIG.images.map((i) =>

                 this.setState({image: i})}>

{i.displayName}

{i.versions[0]}

            )}

              <Recaptcha
                sitekey={CONFIG.rcsitekey}
                onChange={c => this.setState({captcha: c})}
              />

                Launch

            {box.error ?

                {box.error.message}

            : null}

                      Free

                      Termbox is completely free, no sign up required.

                      Secure

                      Boxes are securely isolated in their own virtual
                      machine.

                      Ephemeral

                      Boxes and all their data are automatically deleted after
                      3 hours.

For more information, visit our FAQ.

  }

}

export const LaunchContainer = connect(
  state => ({box: state.box}),
  dispatch => ({dispatch})
)(Launch);
<|endoftext|>